From c4e6a0afed0d2eeae565bba94a26bc14a0c96bbc Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 14 Sep 2026 13:52:24 +0800 Subject: [PATCH 1/4] feat: per-call conversation_id for MCP tools (#760) --- src/compress-tool.ts | 10 + src/mcp.ts | 63 ++- src/plugin.ts | 83 +++- src/server.ts | 11 +- tests/issue760-percall-conversation.test.ts | 411 ++++++++++++++++++++ 5 files changed, 550 insertions(+), 28 deletions(-) create mode 100644 tests/issue760-percall-conversation.test.ts diff --git a/src/compress-tool.ts b/src/compress-tool.ts index 9e67869bef..42f763b88d 100644 --- a/src/compress-tool.ts +++ b/src/compress-tool.ts @@ -108,3 +108,13 @@ const MARKER_INTEGRITY_NOTE = export function withMarkerIntegrityNote(text: string): string { return text + MARKER_INTEGRITY_NOTE; } + +// #760: per-call conversation_id for MCP tools. Hosts that share ONE MCP shim +// process across several concurrent conversations (kimi web et al.) have no +// env/meta session channel, so the proxy prints its own resolved session id +// and the model echoes it back as the conversation_id argument of every +// mcp__bili__ call. Session-stable, so it rides the static system-prompt part +// (prefix-cache safe) next to MARKER_INTEGRITY_NOTE, in BOTH modes. +export function withConversationIdNote(text: string, conversationId: string): string { + return text + `\n\n[Your bili conversation id: ${conversationId}. When calling the bili compression tools, pass this value as the conversation_id argument so a shared MCP process can route the call to THIS session.]`; +} diff --git a/src/mcp.ts b/src/mcp.ts index 8f91941deb..5a255f9e24 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -5,6 +5,11 @@ // POST /__bili/plugin/tool. Claude Code passes its session id via the MCP // initialize request's _meta.ui.sessionId (documented SessionStart context); // we also accept BILI_CONVERSATION_ID env (codex spawn-time registration). +// #760: a fourth channel for hosts that share ONE shim across several +// concurrent conversations (no env/meta session at all): every tool accepts an +// optional conversation_id argument the model copies from the proxy's notes, +// which overrides the default binding and lazily registers the named +// conversation on first use. import fs from "node:fs"; import path from "node:path"; @@ -70,7 +75,9 @@ const IDENTITY_BINDING = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim()); const ORPHAN_ADOPT = IDENTITY_BINDING && process.env.BILI_MCP_NO_ORPHAN_ADOPT !== "1"; let manifestTools: McpToolDef[] = []; let conversationId = CONVERSATION_FROM_ENV; -let registered = false; +// #760: every conversation this shim has ever registered — the default +// binding plus any per-call ids seen so far (issue-once each). +const registeredConversations = new Set(); let initialized = false; function send(msg: unknown): void { process.stdout.write(JSON.stringify(msg) + "\n"); @@ -105,14 +112,15 @@ function ensureManifest(): Promise { return manifestPromise; } -export async function forwardTool(tool: string, args: unknown, timeoutMs: number = TOOL_TIMEOUT_MS): Promise { +export async function forwardTool(tool: string, args: unknown, timeoutMs: number = TOOL_TIMEOUT_MS, conversationIdOverride: string | undefined = undefined): Promise { + const effectiveConversationId = conversationIdOverride ?? conversationId; for (let attempt = 0; ; attempt++) { let res: Response; try { res = await fetch(`${resolveProxyOrigin()}/__bili/plugin/tool`, { method: "POST", headers: { "content-type": "application/json" }, - body: JSON.stringify({ conversationId, tool, args }), + body: JSON.stringify({ conversationId: effectiveConversationId, tool, args }), signal: AbortSignal.timeout(timeoutMs), }); } catch (err) { @@ -123,9 +131,11 @@ export async function forwardTool(tool: string, args: unknown, timeoutMs: number if (res.ok && data.ok) return data.result ?? ""; // #656: the shim's captured id was never registered — the host likely // resumed its session and forked a new id after this shim spawned. - // Adopt the proxy's latest active conversation and retry once. + // Adopt the proxy's latest active conversation and retry once. Armed + // for DEFAULT-bound calls only: a per-call (#760) id naming an unknown + // session must fail loudly, never adopt a sibling conversation. if ( - res.status === 404 && attempt === 0 && ORPHAN_ADOPT && conversationId && + res.status === 404 && attempt === 0 && ORPHAN_ADOPT && conversationIdOverride === undefined && conversationId && typeof data.error === "string" && data.error.includes("no model request has arrived") ) { if (await adoptLatestActiveConversation()) continue; @@ -134,6 +144,26 @@ export async function forwardTool(tool: string, args: unknown, timeoutMs: number } } +/** #760: lazy registration for a per-call conversation id. Always identity- + * mode: the id names an EXISTING conversation whose model requests carry the + * same value, so binding fires on that conversation's next request only — + * never headless (which would bind the NEXT new session, i.e. some other + * client's conversation, on a shared multi-session proxy). */ +async function ensureRegistered(conversationIdArg: string): Promise { + if (registeredConversations.has(conversationIdArg)) return; + registeredConversations.add(conversationIdArg); // issue-once even if the fetch fails + try { + await fetch(`${resolveProxyOrigin()}/__bili/plugin/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: conversationIdArg, agent: "mcp", identity: true }), + signal: AbortSignal.timeout(5000), + }); + } catch (err) { + process.stderr.write(`[bili-mcp] per-call registration of "${conversationIdArg}" failed: ${err instanceof Error ? err.message : String(err)}\n`); + } +} + /** One-shot recovery for a stale shim id (#656): resolve the proxy's * most-recent ACTIVE conversation via the status endpoint's fallback=latest * and adopt it for all subsequent tool calls. Returns true when an adoption @@ -181,14 +211,14 @@ async function handleMessage(msg: { const fromMeta = params._meta?.ui?.sessionId?.trim(); if (fromMeta) conversationId ??= fromMeta; initialized = true; - if (conversationId && !registered) { + if (conversationId && !registeredConversations.has(conversationId)) { const registerFetch = fetch(`${resolveProxyOrigin()}/__bili/plugin/register`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ conversationId, agent: "mcp", identity: IDENTITY_BINDING }), signal: AbortSignal.timeout(5000), }); - registered = true; // issue-once: a repeated initialize must not re-register + registeredConversations.add(conversationId); // issue-once: a repeated initialize must not re-register if (IDENTITY_BINDING) { // Identity-mode binding survives any arrival order — // respond immediately so pipelined hosts are not stuck @@ -225,20 +255,29 @@ async function handleMessage(msg: { } case "tools/call": { const tool = typeof params.name === "string" ? params.name : ""; - const args = params.arguments && typeof params.arguments === "object" ? params.arguments : {}; + const rawArgs: Record = params.arguments && typeof params.arguments === "object" ? (params.arguments as Record) : {}; if (!tool) { sendError(id, ERR_TOOL, "params.name is required"); return; } - if (!conversationId) { - sendError(id, ERR_TOOL, "no conversation id (set BILI_CONVERSATION_ID or connect via Claude Code MCP session meta)"); + // #760: per-call conversation_id — the model copies the id the + // proxy printed in its notes ("your bili conversation id: …"). + // Overrides the default binding (env/meta); stripped before + // forwarding since the proxy routes on the body-level field. + const perCallRaw = rawArgs.conversation_id; + const perCall = typeof perCallRaw === "string" ? perCallRaw.trim() : ""; + const args = { ...rawArgs }; + delete args.conversation_id; + if (!perCall && !conversationId) { + sendError(id, ERR_TOOL, "no conversation id (pass the conversation_id argument — see the 'your bili conversation id' line in the proxy notes — or set BILI_CONVERSATION_ID or connect via Claude Code MCP session meta)"); return; } try { - const text = await forwardTool(tool, args); + if (perCall) await ensureRegistered(perCall); + const text = await forwardTool(tool, args, TOOL_TIMEOUT_MS, perCall || undefined); sendResult(id, { content: [{ type: "text", text }], isError: false }); } catch (err) { - // Tool-level failures are results (isError), not JSON-RPC + // Protocol failures are results (isError), not JSON-RPC // errors, so the host surfaces them to the model. sendResult(id, { content: [{ type: "text", text: `bili tool error: ${err instanceof Error ? err.message : String(err)}` }], isError: true }); } diff --git a/src/plugin.ts b/src/plugin.ts index c4c7c1b8da..182007c873 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -320,17 +320,65 @@ export function handlePluginCompact(payload: string, res: import("node:http").Se return; } const entry = conversations.get(conversationId); - const session = entry ? peekSession(entry.sessionId) : undefined; - if (!entry || !session) { + let session = entry ? peekSession(entry.sessionId) : undefined; + // #760: the session id IS the client-provided conversation value verbatim + // (#286), so resolve directly when the map has no entry yet — a FIRST tool + // call must route before any plugin binding recorded the mapping (header- + // based clients have no prompt_cache_key record to lean on). Read-only: an + // unknown id finds nothing and creates nothing. + if (!session) { + session = peekSession(conversationId); + if (session) recordPluginSession(conversationId, session.id); + } + // #760: the verbatim-id fallback above can resolve a session with NO map + // entry (first call), so only the session itself gates execution. + if (!session) { res.writeHead(404, { "content-type": "application/json" }); - res.end(JSON.stringify({ ok: false, error: "unknown plugin conversation (no model request has arrived with this conversation id yet)" })); + res.end(JSON.stringify({ + ok: false, + error: entry + ? `unknown plugin conversation id "${conversationId}" (id registered but session not resident)` + : `unknown plugin conversation id "${conversationId}" (no model request has arrived with this conversation id yet)`, + })); return; } markCompactionBoundary(session); - entry.lastSeen = Date.now(); + if (entry) entry.lastSeen = Date.now(); res.end(JSON.stringify({ ok: true, conversationId })); } +// #760: per-call conversation_id for MCP tools. Hosts that share ONE shim +// process across several concurrent conversations have no env/meta session +// channel, so the model supplies the target conversation per call (the proxy +// prints its own session id in the wire notes). The param is added to CLONED +// schemas only — wire-mode injection serves the kernel constants directly and +// those models are routed by request identity, not arguments. +const CONVERSATION_ID_PARAM = { + type: "string" as const, + description: + "Your bili conversation id (the value from the 'your bili conversation id' line in the proxy notes). " + + "Pass it on every call when your host shares one MCP process across several concurrent conversations; " + + "omit it when the host bound the session itself.", +}; + +function withConversationIdParam(tool: unknown): unknown { + const copy = structuredClone(tool); + if (!copy || typeof copy !== "object") return copy; + const t = copy as Record; + const add = (schema: unknown): void => { + if (!schema || typeof schema !== "object") return; + const s = schema as { properties?: Record }; + s.properties = { ...(s.properties ?? {}), conversation_id: CONVERSATION_ID_PARAM }; + }; + if (t.input_schema !== undefined) add(t.input_schema); + else { + const fn = t.function; + if (fn && typeof fn === "object") add((fn as { parameters?: unknown }).parameters); + else add(t.parameters); + } + return copy; +} + export function handlePluginManifest(res: import("node:http").ServerResponse): void { res.writeHead(200, { "content-type": "application/json" }); res.end(JSON.stringify({ @@ -345,9 +393,9 @@ export function handlePluginManifest(res: import("node:http").ServerResponse): v // manifest has no request context to know which route will win. toolNames: [...PROXY_TOOL_NAMES, ABSORB_TOOL_NAME], tools: { - anthropic: [...ACP_TOOLS_ANTHROPIC, ABSORB_TOOL], - openai: [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI], - responses: [...ACP_TOOLS_RESPONSES, ABSORB_TOOL_RESPONSES], + anthropic: [...ACP_TOOLS_ANTHROPIC, ABSORB_TOOL].map(withConversationIdParam), + openai: [...ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI].map(withConversationIdParam), + responses: [...ACP_TOOLS_RESPONSES, ABSORB_TOOL_RESPONSES].map(withConversationIdParam), }, headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER }, toolEndpoint: "/__bili/plugin/tool", @@ -502,8 +550,17 @@ export async function handlePluginTool( return; } const entry = conversations.get(conversationId); - const session = entry ? peekSession(entry.sessionId) : undefined; - if (!entry || !session) { + let session = entry ? peekSession(entry.sessionId) : undefined; + // #760: same first-call routing as handlePluginCompact — resolve the + // verbatim session id directly when the map has no entry yet. Read-only: + // an unknown id finds nothing and creates nothing. + if (!session) { + session = peekSession(conversationId); + if (session) recordPluginSession(conversationId, session.id); + } + // #760: the verbatim-id fallback above can resolve a session with NO map + // entry (first call), so only the session itself gates execution. + if (!session) { // #656: two distinct failures shared one message before. An id that was // NEVER registered is the classic stale-shim-id case (host resumed its // session after the MCP shim captured CLAUDE_CODE_SESSION_ID) — say so, @@ -528,8 +585,12 @@ export async function handlePluginTool( res.end(JSON.stringify({ ok: false, error: `unknown tool "${tool}" (expected one of: ${allowed.join(", ")})` })); return; } - entry.lastSeen = Date.now(); - const args = parsed.args && typeof parsed.args === "object" ? (parsed.args as Record) : {}; + if (entry) entry.lastSeen = Date.now(); + const args = parsed.args && typeof parsed.args === "object" ? { ...(parsed.args as Record) } : {}; + // #760: the MCP manifest advertises an optional conversation_id argument + // for per-call routing; routing itself uses the body-level conversationId + // field, so strip it before kernel arg parsing sees it. + delete args.conversation_id; const callId = `plugin_${Date.now().toString(36)}`; acquireInFlight(session); let result: string; diff --git a/src/server.ts b/src/server.ts index 9f723ddc80..1bbc706b85 100644 --- a/src/server.ts +++ b/src/server.ts @@ -44,7 +44,7 @@ import { subagentNamespace, } from "acp-kernel/wire"; import { getSession, listSessions, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, withSessionLock, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, snapshotMessages, applyCompactionArchive } from "./session.js"; -import { ABSORB_TOOL, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, COMPRESS_TOOL, ACP_TOOLS_ANTHROPIC, ACP_TOOLS_OPENAI, ACP_TOOLS_RESPONSES, ACP_READONLY_TOOLS_RESPONSES, COMPRESS_TOOL_NAME, buildAbsorbSystemPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withMarkerIntegrityNote, withStagedCompressGuidance } from "./compress-tool.js"; +import { ABSORB_TOOL, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, COMPRESS_TOOL, ACP_TOOLS_ANTHROPIC, ACP_TOOLS_OPENAI, ACP_TOOLS_RESPONSES, ACP_READONLY_TOOLS_RESPONSES, COMPRESS_TOOL_NAME, buildAbsorbSystemPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withConversationIdNote, withMarkerIntegrityNote, withStagedCompressGuidance } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; import { rewriteJsonResponse, type RewriteCtx } from "./stream.js"; import { applyRanges } from "./stream.js"; @@ -2041,7 +2041,7 @@ function prepareAnthropic( reapOrphanBlocks(session, msgs, deactivateBlock); rebuiltMessages = coreToAnthropic(processedMessages as BiliMessage[], cacheControls); - systemOut = injectSystem(parsed, opts, prompts, loopConfig); + systemOut = injectSystem(parsed, opts, prompts, loopConfig, session.id, surface); if (injectTools) { toolsOut = injectTool(parsed.tools, absorbActive ? ABSORB_TOOL : undefined); } @@ -2283,7 +2283,7 @@ function prepareOpenai( // would invalidate the cache every turn. const sysParts: string[] = []; if (systemText) sysParts.push(systemText); - if (shouldInject) sysParts.push(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections))); + if (shouldInject) sysParts.push(withConversationIdNote(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), sessionId)); if (absorbActive) sysParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); rebuiltMessages = injectOpenaiSystem(rebuiltMessages, sysParts); // #532: capture what bili injects outside the fold space (client system @@ -2474,7 +2474,7 @@ function prepareResponses( ? [] : (session.metadata.codexForgedSummaries as string[] | undefined) ?? []; if (shouldInject && !isCompactionTrigger && !process.env.ACP_NO_COMPRESS_PROMPT) { - const prompt = withMarkerIntegrityNote(responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts, surface?.promptSections) : buildCompressSystemPrompt(prompts, surface?.promptSections)); + const prompt = withConversationIdNote(withMarkerIntegrityNote(responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts, surface?.promptSections) : buildCompressSystemPrompt(prompts, surface?.promptSections)), sessionId); const devParts = [...projection.systemParts, ...forgedSummaries, prompt]; if (absorbActive) devParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); const devContent = devParts.join("\n\n---\n\n"); @@ -2802,6 +2802,7 @@ function injectSystem( opts: ProxyOptions, prompts: Prompts = defaultPrompts, config: Config, + sessionId: string, surface?: PackSurface, ): string | AnthropicRequestBody["system"] { // ONLY the static compress prompt goes into the system block — it is the @@ -2810,7 +2811,7 @@ function injectSystem( // the caller (prepareAnthropic), never merged into system. const baseText = extractSystem(parsed.system); const parts: string[] = []; - if (opts.compress.injectTool) parts.push(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections))); + if (opts.compress.injectTool) parts.push(withConversationIdNote(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), sessionId)); if (opts.compress.injectTool && absorbEnabled(config)) parts.push(buildAbsorbSystemPrompt(absorbToolName(config))); if (parts.length === 0) return parsed.system; const full = baseText ? `${baseText}\n\n---\n\n${parts.join("\n\n")}` : parts.join("\n\n"); diff --git a/tests/issue760-percall-conversation.test.ts b/tests/issue760-percall-conversation.test.ts new file mode 100644 index 0000000000..55d5a7c51b --- /dev/null +++ b/tests/issue760-percall-conversation.test.ts @@ -0,0 +1,411 @@ +import assert from "node:assert"; +import http from "node:http"; +import { once } from "node:events"; +import test from "node:test"; +import { spawn } from "node:child_process"; + +process.env.NODE_ENV = "test"; + +import { defaultConfig } from "acp-kernel"; +import { startServer, type ProxyOptions } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { ACP_TOOLS_ANTHROPIC } from "../src/compress-tool.ts"; + +// #760: per-call conversation_id for MCP tools. Hosts that share ONE shim +// process across several concurrent conversations (kimi web et al.) have no +// env/meta session channel, so the model supplies the target conversation per +// tool call. Covered here: manifest schema, the proxy's injected id note, +// first-call routing (peekSession fallback), unknown-id rejection, sticky +// plugin-mode flip via identity-mode lazy registration, and the shim's +// per-call routing / arg stripping / adoption guard. + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function close(server: http.Server): Promise { + const { promise, resolve, reject } = Promise.withResolvers(); + server.close((error) => (error ? reject(error) : resolve())); + return promise; +} + +function anthropicSse(event: string, data: unknown): string { + return `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`; +} + +function textScript(): string { + return anthropicSse("message_start", { type: "message_start", message: { id: "m1", role: "assistant", usage: { input_tokens: 42 } } }) + + anthropicSse("content_block_start", { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }) + + anthropicSse("content_block_delta", { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: "ok" } }) + + anthropicSse("content_block_stop", { type: "content_block_stop", index: 0 }) + + anthropicSse("message_delta", { type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } }) + + anthropicSse("message_stop", { type: "message_stop" }); +} + +interface Rig { + proxyUrl: (path: string) => string; + modelUrl: () => string; + upstreamBodies: string[]; + closeAll(): Promise; +} + +async function startRig(): Promise { + const upstreamBodies: string[] = []; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + upstreamBodies.push(Buffer.concat(chunks).toString("utf8")); + res.writeHead(200, { "content-type": "text/event-stream" }); + res.end(textScript()); + }); + }); + upstream.listen(0, "127.0.0.1"); + await listen(upstream); + const upstreamPort = (upstream.address() as { port: number }).port; + + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetPluginStateForTest(); + + const opts: ProxyOptions = { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "l162-model": { context: 100_000 } } } }, + modelContextLimit: 100_000, + kernelConfig: defaultConfig(100_000), + compress: { injectTool: true, injectNudge: true }, + promptCache: { routing: "auto" }, + log: false, + sessionHeader: "x-acp-session", + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + }; + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + return { + proxyUrl: (path) => `http://127.0.0.1:${proxyPort}${path}`, + modelUrl: () => `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`, + upstreamBodies, + closeAll: async () => { + await close(proxy); + await close(upstream); + }, + }; +} + +function postModel(rig: Rig, conversationId: string, headerName = "x-session-affinity"): Promise { + return fetch(rig.modelUrl(), { + method: "POST", + headers: { "content-type": "application/json", [headerName]: conversationId }, + body: JSON.stringify({ model: "l162-model", max_tokens: 8192, stream: true, messages: [{ role: "user", content: "hello" }] }), + }); +} + +async function toolCall(rig: Rig, conversationId: string, tool = "acp_status", args: Record = {}): Promise<{ status: number; data: { ok?: boolean; result?: string; error?: string } }> { + const res = await fetch(rig.proxyUrl("/__bili/plugin/tool"), { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId, tool, args }), + }); + return { status: res.status, data: (await res.json()) as { ok?: boolean; result?: string; error?: string } }; +} + +async function statusOf(rig: Rig, conversationId: string): Promise<{ ok?: boolean; pluginAgent?: string }> { + const res = await fetch(rig.proxyUrl(`/__bili/plugin/status?conversationId=${encodeURIComponent(conversationId)}`)); + return (await res.json()) as { ok?: boolean; pluginAgent?: string }; +} + +async function waitFor(cond: () => boolean, what: string): Promise { + const t0 = Date.now(); + while (!cond()) { + if (Date.now() - t0 > 5000) throw new Error(`timeout waiting for ${what}`); + await new Promise((r) => setTimeout(r, 25)); + } +} + +function sysText(body: string): string { + const parsed = JSON.parse(body) as { system?: string | { text?: string }[] }; + if (typeof parsed.system === "string") return parsed.system; + if (Array.isArray(parsed.system)) return parsed.system.map((s) => s.text ?? "").join("\n"); + return ""; +} + +function toolNames(body: string): string[] { + const parsed = JSON.parse(body) as { tools?: { name?: string }[] }; + return (parsed.tools ?? []).map((t) => t.name ?? ""); +} + +type SchemaObj = { properties?: Record; required?: string[] }; + +function schemaOf(tool: unknown): SchemaObj | undefined { + if (!tool || typeof tool !== "object") return undefined; + const t = tool as Record; + if (t.input_schema && typeof t.input_schema === "object") return t.input_schema as SchemaObj; + const fn = t.function; + if (fn && typeof fn === "object") { + const params = (fn as { parameters?: unknown }).parameters; + if (params && typeof params === "object") return params as SchemaObj; + } + if (t.parameters && typeof t.parameters === "object") return t.parameters as SchemaObj; + return undefined; +} + +test("plugin manifest advertises an optional conversation_id in all three tool formats", async () => { + const rig = await startRig(); + try { + const res = await fetch(rig.proxyUrl("/__bili/plugin/manifest")); + assert.equal(res.status, 200); + const m = (await res.json()) as { ok: boolean; tools: Record }; + assert.equal(m.ok, true); + for (const format of ["anthropic", "openai", "responses"] as const) { + const tools = m.tools[format]; + assert.ok(Array.isArray(tools) && tools.length >= 4, `${format}: tools listed`); + for (const t of tools) { + const schema = schemaOf(t); + assert.ok(schema?.properties, `${format}/${(t as { name?: string }).name}: has properties`); + assert.equal((schema!.properties!.conversation_id as { type?: string } | undefined)?.type, "string", `${format}: conversation_id advertised as optional string`); + assert.ok(!(schema!.required ?? []).includes("conversation_id"), `${format}: conversation_id not required`); + } + } + // Wire-mode injection serves the kernel constants directly — the + // manifest extension must not leak into them. + assert.doesNotMatch(JSON.stringify(ACP_TOOLS_ANTHROPIC), /conversation_id/, "kernel constants unmutated"); + } finally { + await rig.closeAll(); + } +}); + +test("wire mode: proxy prints its own conversation id in the static system part, byte-stable across turns", async () => { + const rig = await startRig(); + try { + await postModel(rig, "conv-760-a"); + await postModel(rig, "conv-760-a"); + await waitFor(() => rig.upstreamBodies.length >= 2, "two upstream bodies"); + const sys0 = sysText(rig.upstreamBodies[0]); + assert.match(sys0, /\[Your bili conversation id: conv-760-a\./, "id note present in wire mode"); + assert.equal(sysText(rig.upstreamBodies[1]), sys0, "system bytes stable across turns (prefix-cache anchor)"); + } finally { + await rig.closeAll(); + } +}); + +test("first tool call routes before any plugin binding recorded the mapping (peekSession fallback)", async () => { + const rig = await startRig(); + try { + // No register, no prompt_cache_key: header-based clients leave NO + // conversations-map entry, so routing must fall back to the verbatim + // session-id lookup. + await postModel(rig, "conv-fb"); + const r = await toolCall(rig, "conv-fb"); + assert.equal(r.status, 200, `first-call routing succeeded: ${JSON.stringify(r.data)}`); + assert.equal(r.data.ok, true); + assert.match(r.data.result ?? "", /CONTEXT BREAKDOWN/); + } finally { + await rig.closeAll(); + } +}); + +test("unknown conversation id is rejected without creating a session", async () => { + const rig = await startRig(); + try { + const r = await toolCall(rig, "conv-ghost"); + assert.equal(r.status, 404); + assert.equal(r.data.ok, false); + assert.match(r.data.error ?? "", /no model request has arrived/, "orphan-adoption trigger substring preserved"); + const st = await statusOf(rig, "conv-ghost"); + assert.notEqual(st.ok, true, "no session materialized for the fabricated id"); + } finally { + await rig.closeAll(); + } +}); + +interface ShellHarness { + send(msg: unknown): void; + settled: Promise; + lines: string[]; + kill(): void; +} + +function spawnShell(env: Record): ShellHarness { + const shell = spawn(process.execPath, ["--import", "tsx", "src/mcp.ts"], { + env: { ...process.env, ...env }, + stdio: ["pipe", "pipe", "pipe"], + }); + const lines: string[] = []; + const settled = new Promise((resolve, reject) => { + shell.on("error", reject); + shell.stdout.on("data", (d: Buffer) => { + for (const l of d.toString().split("\n")) { + if (l.trim()) lines.push(l.trim()); + } + }); + }); + shell.stderr.on("data", () => {}); + return { + send: (msg) => shell.stdin.write(JSON.stringify(msg) + "\n"), + settled, + lines, + kill: () => shell.kill(), + }; +} + +function byId(lines: string[], n: number): Record { + return JSON.parse(lines.find((l) => (JSON.parse(l) as { id?: number }).id === n) ?? "{}"); +} + +test("shared shim, no env/meta id: per-call ids route two sessions independently and flip them to plugin mode", async () => { + const rig = await startRig(); + const h = spawnShell({ + BILI_MCP_PROXY: rig.proxyUrl(""), + BILI_CONVERSATION_ID: "", + CLAUDE_CODE_SESSION_ID: "", + }); + try { + h.send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "0" } } }); + h.send({ jsonrpc: "2.0", method: "notifications/initialized" }); + h.send({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }); + await waitFor(() => h.lines.length >= 2, "initialize + tools/list responses"); + const tools = byId(h.lines, 2) as { result?: { tools?: { inputSchema?: { properties?: Record } }[] } }; + for (const t of tools.result?.tools ?? []) { + assert.equal((t.inputSchema?.properties?.conversation_id as { type?: string } | undefined)?.type, "string", `shim exposes conversation_id on ${t.inputSchema ? "tool" : "unknown"}`); + } + + // Session A exists; first per-call tool call must route immediately + // (lazy identity registration rides along). + await postModel(rig, "conv-mcp-a"); + h.send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "conv-mcp-a" } } }); + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 3), "per-call acp_status(A)"); + const callA = byId(h.lines, 3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; + assert.equal(callA.result?.isError, false, `per-call call routed to A${callA.result?.isError ? ": " + (callA.result?.content?.[0]?.text ?? "") : ""}`); + assert.match(callA.result?.content?.[0]?.text ?? "", /CONTEXT BREAKDOWN/); + + // A brand-new unrelated session lands BEFORE A's next request: a + // headless registration would have bound IT instead of A. + await postModel(rig, "conv-other"); + await postModel(rig, "conv-mcp-a"); + await postModel(rig, "conv-mcp-b"); + h.send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "conv-mcp-b" } } }); + // Await the tool result BEFORE B's next request: real agents only + // resume the model loop after the tool call returns, so the lazy + // registration always lands first — the test must mirror that order. + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 4), "per-call acp_status(B)"); + await postModel(rig, "conv-mcp-b"); + const callB = byId(h.lines, 4) as { result?: { content?: { text?: string }[]; isError?: boolean } }; + assert.equal(callB.result?.isError, false, `per-call call routed to B${callB.result?.isError ? ": " + (callB.result?.content?.[0]?.text ?? "") : ""}`); + + await waitFor(() => rig.upstreamBodies.length >= 5, "five upstream bodies"); + // A's first request: wire mode — ephemeral compress tool injected, id note present. + assert.ok(toolNames(rig.upstreamBodies[0]).includes("compress"), "wire request carries the ephemeral compress tool"); + assert.match(sysText(rig.upstreamBodies[0]), /\[Your bili conversation id: conv-mcp-a\./); + // A's second request arrives AFTER the identity registration landed: + // pure plugin mode — no ephemeral tools, id note still flows. + assert.ok(!toolNames(rig.upstreamBodies[2]).includes("compress"), "post-registration request drops the ephemeral compress tool"); + assert.match(sysText(rig.upstreamBodies[2]), /\[Your bili conversation id: conv-mcp-a\./, "id note flows in plugin mode too"); + // B's requests carry B's id, not A's — no cross-talk. + assert.match(sysText(rig.upstreamBodies[3]), /\[Your bili conversation id: conv-mcp-b\./); + + // Sticky plugin-mode flip, and the untouched sibling stays wire mode. + const stA = await statusOf(rig, "conv-mcp-a"); + assert.equal(stA.ok, true); + assert.equal(stA.pluginAgent, "mcp", "A flipped to plugin mode via identity-mode lazy registration"); + const stB = await statusOf(rig, "conv-mcp-b"); + assert.equal(stB.pluginAgent, "mcp", "B flipped independently"); + const stOther = await statusOf(rig, "conv-other"); + assert.notEqual(stOther.pluginAgent, "mcp", "unrelated session NOT stolen by a headless registration"); + + // A repeat per-call call still routes to A. + h.send({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "conv-mcp-a" } } }); + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 5), "repeat per-call acp_status(A)"); + const callA2 = byId(h.lines, 5) as { result?: { isError?: boolean } }; + assert.equal(callA2.result?.isError, false, "repeat call still routes to A"); + } finally { + h.kill(); + await rig.closeAll(); + } +}); + +test("shim: per-call id strips the forwarded arg, registers identity-once, never adopts for per-call 404s", async () => { + const posts: { url: string; body: Record }[] = []; + const mock = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (c: Buffer) => chunks.push(c)); + req.on("end", () => { + const raw = Buffer.concat(chunks).toString("utf8"); + const body = raw ? (JSON.parse(raw) as Record) : {}; + if (req.method === "POST") posts.push({ url: req.url ?? "", body }); + res.writeHead(200, { "content-type": "application/json" }); + if ((req.url ?? "").startsWith("/__bili/plugin/manifest")) { + res.end(JSON.stringify({ + ok: true, version: "t", protocolVersion: 1, toolNames: [], + tools: { + anthropic: [{ name: "acp_status", description: "", input_schema: { type: "object", properties: {}, required: [] } }], + openai: [], responses: [], + }, + headers: {}, toolEndpoint: "/__bili/plugin/tool", statusEndpoint: "/__bili/plugin/status", + })); + } else if ((req.url ?? "").startsWith("/__bili/plugin/register")) { + res.end(JSON.stringify({ ok: true })); + } else if (body.conversationId === "GHOST") { + res.statusCode = 404; + res.end(JSON.stringify({ ok: false, error: 'unknown plugin conversation id "GHOST" (no model request has arrived with this conversation id yet)' })); + } else { + res.end(JSON.stringify({ ok: true, result: "fine" })); + } + }); + }); + mock.listen(0, "127.0.0.1"); + await listen(mock); + const mockPort = (mock.address() as { port: number }).port; + const h = spawnShell({ + BILI_MCP_PROXY: `http://127.0.0.1:${mockPort}`, + BILI_CONVERSATION_ID: "", + CLAUDE_CODE_SESSION_ID: "", + }); + try { + h.send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "t", version: "0" } } }); + h.send({ jsonrpc: "2.0", method: "notifications/initialized" }); + // No default binding → no register on initialize. + h.send({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "acp_status", arguments: {} } }); + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 2), "no-id error"); + const noId = byId(h.lines, 2) as { error?: { message?: string } }; + assert.match(noId.error?.message ?? "", /conversation_id argument/, "no-id error hints at the per-call parameter"); + + h.send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "X", extra: 1 } } }); + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 3), "per-call X"); + const callX = byId(h.lines, 3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; + assert.equal(callX.result?.isError, false); + assert.equal(callX.result?.content?.[0]?.text, "fine"); + + const regs = posts.filter((p) => p.url.startsWith("/__bili/plugin/register")); + assert.equal(regs.length, 1, "exactly one lazy registration"); + assert.deepEqual(regs[0].body, { conversationId: "X", agent: "mcp", identity: true }, "identity-mode registration, never headless"); + const toolPost = posts.find((p) => p.url.startsWith("/__bili/plugin/tool")); + assert.equal(toolPost?.body.conversationId, "X", "routes on the body-level field"); + assert.deepEqual(toolPost?.body.args, { extra: 1 }, "conversation_id stripped from the forwarded args"); + + // Issue-once: a repeat call issues no second registration. + h.send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "X" } } }); + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 4), "repeat per-call X"); + assert.equal(posts.filter((p) => p.url.startsWith("/__bili/plugin/register")).length, 1, "registration issue-once"); + + // Unknown per-call id fails loudly — no orphan adoption (which would + // mutate the shared default binding for everyone else's calls). + h.send({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "GHOST" } } }); + await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 5), "ghost per-call"); + const ghost = byId(h.lines, 5) as { result?: { content?: { text?: string }[]; isError?: boolean } }; + assert.equal(ghost.result?.isError, true, "unknown per-call id surfaces as a tool error"); + assert.match(ghost.result?.content?.[0]?.text ?? "", /no model request has arrived/); + assert.ok(!posts.some((p) => p.url.startsWith("/__bili/plugin/status")), "no adoption lookup for per-call failures"); + } finally { + h.kill(); + await close(mock); + } +}); From 4b5610167855dcc7e22221eb2dc97ea934d7236b Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 14 Sep 2026 19:16:55 +0800 Subject: [PATCH 2/4] feat: unified canonical session id for MCP tool routing Every session now exposes a stable pfa-* canonical id that MCP tools route by, independent of what the client calls itself. Anonymous sessions already ARE pfa-* (canonical == session.id); legacy client-named sessions derive a deterministic pfa-* from their session id, materialized onto persisted metadata.canonicalId. - wire notes inject the canonical id (all three prepare paths), so the model echoes back one uniform id space - tool/compact/status endpoints gain a canonical reverse-lookup path (map -> verbatim -> canonical); old ids keep working, unknown ids still 404 and create nothing - evidence-based plugin-mode flip: a successful MCP tool execution binds that session to plugin mode (guarded: never overrides an existing agent binding) Extends PR #761 (per-call conversation_id). Fixes #760. --- src/plugin.ts | 56 +++++++++------- src/server.ts | 12 ++-- src/session.ts | 43 ++++++++++++ tests/issue760-percall-conversation.test.ts | 72 +++++++++++++++++++-- 4 files changed, 147 insertions(+), 36 deletions(-) diff --git a/src/plugin.ts b/src/plugin.ts index 182007c873..8e6d655071 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -3,7 +3,7 @@ import { buildStatusPanel } from "acp-kernel/panel"; import { fileURLToPath } from "node:url"; import fs from "node:fs"; import path from "node:path"; -import { acquireInFlight, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, withSessionLock, type Session } from "./session.js"; +import { acquireInFlight, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, peekSession, releaseInFlight, withSessionLock, type Session } from "./session.js"; import { ABSORB_TOOL, ABSORB_TOOL_NAME, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, ACP_TOOLS_ANTHROPIC, ACP_TOOLS_OPENAI, ACP_TOOLS_RESPONSES, PROXY_TOOL_NAMES } from "./compress-tool.js"; import { effectiveAbsorbConfig, isProxyToolFor } from "./absorb.js"; import { executeProxyTool } from "./loop/core.js"; @@ -319,17 +319,7 @@ export function handlePluginCompact(payload: string, res: import("node:http").Se res.end(JSON.stringify({ ok: false, error: "conversationId is required" })); return; } - const entry = conversations.get(conversationId); - let session = entry ? peekSession(entry.sessionId) : undefined; - // #760: the session id IS the client-provided conversation value verbatim - // (#286), so resolve directly when the map has no entry yet — a FIRST tool - // call must route before any plugin binding recorded the mapping (header- - // based clients have no prompt_cache_key record to lean on). Read-only: an - // unknown id finds nothing and creates nothing. - if (!session) { - session = peekSession(conversationId); - if (session) recordPluginSession(conversationId, session.id); - } + const { session, entry } = resolveConversation(conversationId); // #760: the verbatim-id fallback above can resolve a session with NO map // entry (first call), so only the session itself gates execution. if (!session) { @@ -427,14 +417,32 @@ function conversationIdForSession(sessionId: string): string | undefined { return bestId; } +/** Resolve a caller-supplied conversation id to a resident session through every + * known channel, in precedence order: (1) the persisted conversation→session map + * (plugin binding / prior calls), (2) the verbatim session id (#760 — the id IS + * the client-provided conversation value), (3) the proxy-derived canonical pfa-* + * alias (#760b — every session exposes a stable canonical id the model echoes + * back from the wire notes). Paths 2/3 record the resolved mapping so later + * calls hit path 1 directly. Read-only w.r.t. creation: an unknown id finds + * nothing and creates nothing. */ +function resolveConversation(conversationId: string): { session: Session | undefined; entry?: ConversationEntry } { + const entry = conversations.get(conversationId); + let session = entry ? peekSession(entry.sessionId) : undefined; + if (!session) { + session = peekSession(conversationId) ?? findSessionByCanonicalId(conversationId); + if (session) recordPluginSession(conversationId, session.id); + } + return { session, entry }; +} + /** Context-level visibility for plugin UIs (status bars / slash commands): * the same usage the nudge decision sees, keyed by conversation id. */ export function handlePluginStatus(conversationId: string, res: import("node:http").ServerResponse, deps: PluginToolDeps, fallbackLatest = false): void { - let entry = conversations.get(conversationId); - let session = entry ? peekSession(entry.sessionId) : undefined; + const { session: resolvedSession, entry } = resolveConversation(conversationId); + let session = resolvedSession; let viaFallback = false; let resolvedConversationId = conversationId; - if ((!entry || !session) && fallbackLatest) { + if (!session && fallbackLatest) { // #404: only sessions with real activity in THIS process qualify. // Before the fix every boot-restored session carried lastSeen = // restore time, so a 245-way tie resolved by insertion (readdir) @@ -549,15 +557,7 @@ export async function handlePluginTool( res.end(JSON.stringify({ ok: false, error: `conversationId is required (send the same value as the ${PLUGIN_CONVERSATION_HEADER} header)` })); return; } - const entry = conversations.get(conversationId); - let session = entry ? peekSession(entry.sessionId) : undefined; - // #760: same first-call routing as handlePluginCompact — resolve the - // verbatim session id directly when the map has no entry yet. Read-only: - // an unknown id finds nothing and creates nothing. - if (!session) { - session = peekSession(conversationId); - if (session) recordPluginSession(conversationId, session.id); - } + const { session, entry } = resolveConversation(conversationId); // #760: the verbatim-id fallback above can resolve a session with NO map // entry (first call), so only the session itself gates execution. if (!session) { @@ -618,6 +618,14 @@ export async function handlePluginTool( return; } releaseInFlight(session); + // #760b: evidence-based plugin-mode flip. A successful MCP tool execution proves + // this session's host owns the bili compression tools, so bind it to plugin mode + // (sticky) — the next model request stops injecting the duplicate ephemeral wire + // tools. Guarded: only flips a session with NO existing agent binding, never + // overriding a pi/omp/opencode plugin or a launcher-registered agent. + if (typeof session.metadata.pluginAgent !== "string") { + session.metadata.pluginAgent = "mcp"; + } markDirty(session); deps.log("info", `[${session.id}] [plugin] tool ${tool} executed via plugin (${result.length} chars)`); res.writeHead(200, { "content-type": "application/json" }); diff --git a/src/server.ts b/src/server.ts index 1bbc706b85..f3724d0aa6 100644 --- a/src/server.ts +++ b/src/server.ts @@ -43,7 +43,7 @@ import { conversationSignalResponses, subagentNamespace, } from "acp-kernel/wire"; -import { getSession, listSessions, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, withSessionLock, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, snapshotMessages, applyCompactionArchive } from "./session.js"; +import { getSession, listSessions, type Session, initSessions, markDirty, flushAllSessions, acquireInFlight, releaseInFlight, withSessionLock, markNativeCompactionBoundary, reconcileNativeCompactionBoundary, snapshotMessages, applyCompactionArchive, ensureCanonicalId } from "./session.js"; import { ABSORB_TOOL, ABSORB_TOOL_OPENAI, ABSORB_TOOL_RESPONSES, COMPRESS_TOOL, ACP_TOOLS_ANTHROPIC, ACP_TOOLS_OPENAI, ACP_TOOLS_RESPONSES, ACP_READONLY_TOOLS_RESPONSES, COMPRESS_TOOL_NAME, buildAbsorbSystemPrompt, buildCompressSystemPrompt, buildCompressHybridSystemPrompt, withConversationIdNote, withMarkerIntegrityNote, withStagedCompressGuidance } from "./compress-tool.js"; import { applyAbsorbView, absorbEnabled, absorbToolName, storeEffectiveAbsorb } from "./absorb.js"; import { rewriteJsonResponse, type RewriteCtx } from "./stream.js"; @@ -2041,7 +2041,7 @@ function prepareAnthropic( reapOrphanBlocks(session, msgs, deactivateBlock); rebuiltMessages = coreToAnthropic(processedMessages as BiliMessage[], cacheControls); - systemOut = injectSystem(parsed, opts, prompts, loopConfig, session.id, surface); + systemOut = injectSystem(parsed, opts, prompts, loopConfig, ensureCanonicalId(session), surface); if (injectTools) { toolsOut = injectTool(parsed.tools, absorbActive ? ABSORB_TOOL : undefined); } @@ -2283,7 +2283,7 @@ function prepareOpenai( // would invalidate the cache every turn. const sysParts: string[] = []; if (systemText) sysParts.push(systemText); - if (shouldInject) sysParts.push(withConversationIdNote(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), sessionId)); + if (shouldInject) sysParts.push(withConversationIdNote(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), ensureCanonicalId(session))); if (absorbActive) sysParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); rebuiltMessages = injectOpenaiSystem(rebuiltMessages, sysParts); // #532: capture what bili injects outside the fold space (client system @@ -2474,7 +2474,7 @@ function prepareResponses( ? [] : (session.metadata.codexForgedSummaries as string[] | undefined) ?? []; if (shouldInject && !isCompactionTrigger && !process.env.ACP_NO_COMPRESS_PROMPT) { - const prompt = withConversationIdNote(withMarkerIntegrityNote(responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts, surface?.promptSections) : buildCompressSystemPrompt(prompts, surface?.promptSections)), sessionId); + const prompt = withConversationIdNote(withMarkerIntegrityNote(responsesTextProtocol ? buildCompressHybridSystemPrompt(prompts, surface?.promptSections) : buildCompressSystemPrompt(prompts, surface?.promptSections)), ensureCanonicalId(session)); const devParts = [...projection.systemParts, ...forgedSummaries, prompt]; if (absorbActive) devParts.push(buildAbsorbSystemPrompt(absorbToolName(config))); const devContent = devParts.join("\n\n---\n\n"); @@ -2802,7 +2802,7 @@ function injectSystem( opts: ProxyOptions, prompts: Prompts = defaultPrompts, config: Config, - sessionId: string, + noteId: string, surface?: PackSurface, ): string | AnthropicRequestBody["system"] { // ONLY the static compress prompt goes into the system block — it is the @@ -2811,7 +2811,7 @@ function injectSystem( // the caller (prepareAnthropic), never merged into system. const baseText = extractSystem(parsed.system); const parts: string[] = []; - if (opts.compress.injectTool) parts.push(withConversationIdNote(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), sessionId)); + if (opts.compress.injectTool) parts.push(withConversationIdNote(withMarkerIntegrityNote(buildCompressSystemPrompt(prompts, surface?.promptSections)), noteId)); if (opts.compress.injectTool && absorbEnabled(config)) parts.push(buildAbsorbSystemPrompt(absorbToolName(config))); if (parts.length === 0) return parsed.system; const full = baseText ? `${baseText}\n\n---\n\n${parts.join("\n\n")}` : parts.join("\n\n"); diff --git a/src/session.ts b/src/session.ts index d09d4f4f02..bd43781837 100644 --- a/src/session.ts +++ b/src/session.ts @@ -1,4 +1,5 @@ import { createInitialState, type CompressionState, type CoreMessage } from "acp-kernel"; +import { createHash } from "node:crypto"; import { getStore } from "./persist.js"; export type BlockView = { text: string; count: number }; @@ -280,6 +281,48 @@ export function peekSession(id: string): Session | undefined { return sessions.get(id); } +// #760b: unified canonical session id. Every session exposes a stable pfa-* id +// that MCP tools route by, independent of what the client calls itself. +// Anonymous sessions already ARE pfa-* (PFA-minted session.id), so their +// canonical id is session.id itself. Legacy (client-id) sessions derive a +// stable pfa-* from their session id — deterministic, so the value survives even +// if the persisted copy is lost. It is materialized onto metadata.canonicalId +// (persisted) on first use so lookups are cheap and the value is inspectable. +function derivedLegacyCanonicalId(sessionId: string): string { + return `pfa-${createHash("sha256").update(`legacy:${sessionId}`).digest("hex").slice(0, 16)}`; +} + +/** Pure: the session's canonical id (always pfa-*). Never mutates. */ +function canonicalIdOf(session: Session): string { + if (session.id.startsWith("pfa-")) return session.id; + const c = session.metadata.canonicalId; + if (typeof c === "string" && c.length > 0) return c; + return derivedLegacyCanonicalId(session.id); +} + +/** Materialize + persist the session's canonical id (idempotent) and return it. + * Called where the id is surfaced to the model (wire notes) so the exact value + * shown is the one persisted and routable. Anonymous sessions are a no-op + * (canonical id already equals session.id). */ +export function ensureCanonicalId(session: Session): string { + const id = canonicalIdOf(session); + if (!session.id.startsWith("pfa-") && session.metadata.canonicalId !== id) { + session.metadata.canonicalId = id; + markDirty(session); + } + return id; +} + +/** Read-only reverse lookup: the resident session whose canonical id matches. + * Scans the in-memory pool (≤ MAX_SESSIONS); always consistent with the live + * session set — no separate index to desync on evict/load. */ +export function findSessionByCanonicalId(canonicalId: string): Session | undefined { + for (const s of sessions.values()) { + if (canonicalIdOf(s) === canonicalId) return s; + } + return undefined; +} + /** Overwrite the session's full-conversation snapshot with the latest client * raw request messages (originalMessages from prepare*). One array per * session, replaced every request — bounded, always the newest state. Empty diff --git a/tests/issue760-percall-conversation.test.ts b/tests/issue760-percall-conversation.test.ts index 55d5a7c51b..af5a08c640 100644 --- a/tests/issue760-percall-conversation.test.ts +++ b/tests/issue760-percall-conversation.test.ts @@ -3,6 +3,7 @@ import http from "node:http"; import { once } from "node:events"; import test from "node:test"; import { spawn } from "node:child_process"; +import { createHash } from "node:crypto"; process.env.NODE_ENV = "test"; @@ -158,6 +159,12 @@ function schemaOf(tool: unknown): SchemaObj | undefined { return undefined; } +// Mirrors src/session.ts derivedLegacyCanonicalId: the stable pfa-* id a +// non-pfa (client-named) session exposes for MCP routing. +function canonicalOf(sessionId: string): string { + return `pfa-${createHash("sha256").update(`legacy:${sessionId}`).digest("hex").slice(0, 16)}`; +} + test("plugin manifest advertises an optional conversation_id in all three tool formats", async () => { const rig = await startRig(); try { @@ -190,7 +197,9 @@ test("wire mode: proxy prints its own conversation id in the static system part, await postModel(rig, "conv-760-a"); await waitFor(() => rig.upstreamBodies.length >= 2, "two upstream bodies"); const sys0 = sysText(rig.upstreamBodies[0]); - assert.match(sys0, /\[Your bili conversation id: conv-760-a\./, "id note present in wire mode"); + const canon = canonicalOf("conv-760-a"); + assert.match(sys0, new RegExp(`\\[Your bili conversation id: ${canon}\\.`), "id note carries the derived canonical pfa-* id"); + assert.doesNotMatch(sys0, /\[Your bili conversation id: conv-760-a\./, "note no longer leaks the raw client session id"); assert.equal(sysText(rig.upstreamBodies[1]), sys0, "system bytes stable across turns (prefix-cache anchor)"); } finally { await rig.closeAll(); @@ -227,6 +236,55 @@ test("unknown conversation id is rejected without creating a session", async () } }); +test("canonical pfa-* id (derived, not the client's own) routes to the right session; raw id still works", async () => { + const rig = await startRig(); + try { + await postModel(rig, "conv-canonical"); + await waitFor(() => rig.upstreamBodies.length >= 1, "one upstream body"); + const sys0 = sysText(rig.upstreamBodies[0]); + const canon = canonicalOf("conv-canonical"); + assert.match(sys0, new RegExp(`\\[Your bili conversation id: ${canon}\\.`), "note carries the derived canonical id"); + + // Route by the CANONICAL id — the value the model actually echoes back. + const rCanon = await toolCall(rig, canon); + assert.equal(rCanon.status, 200, `canonical-id routing succeeded: ${JSON.stringify(rCanon.data)}`); + assert.equal(rCanon.data.ok, true); + assert.match(rCanon.data.result ?? "", /CONTEXT BREAKDOWN/); + + // Backward compat: the raw client session id STILL routes. + const rRaw = await toolCall(rig, "conv-canonical"); + assert.equal(rRaw.status, 200, `raw-id routing still succeeds: ${JSON.stringify(rRaw.data)}`); + assert.equal(rRaw.data.ok, true); + + // A fabricated canonical-looking id is rejected and creates nothing. + const rGhost = await toolCall(rig, "pfa-deadbeefdeadbeef"); + assert.equal(rGhost.status, 404); + assert.match(rGhost.data.error ?? "", /no model request has arrived/); + } finally { + await rig.closeAll(); + } +}); + +test("successful MCP tool execution flips a wire-mode session to plugin mode (evidence-based)", async () => { + const rig = await startRig(); + try { + await postModel(rig, "conv-ev-a"); + await postModel(rig, "conv-ev-b"); + await waitFor(() => rig.upstreamBodies.length >= 2, "two upstream bodies"); + // Neither is bound yet — both wire mode. + assert.notEqual((await statusOf(rig, "conv-ev-a")).pluginAgent, "mcp", "A starts in wire mode"); + // A successful tool call against A flips ONLY A. + const r = await toolCall(rig, "conv-ev-a"); + assert.equal(r.status, 200, `tool call succeeded: ${JSON.stringify(r.data)}`); + const stA = await statusOf(rig, "conv-ev-a"); + assert.equal(stA.pluginAgent, "mcp", "session flipped to plugin mode after its own MCP tool execution"); + const stB = await statusOf(rig, "conv-ev-b"); + assert.notEqual(stB.pluginAgent, "mcp", "sibling without a tool call stays wire mode"); + } finally { + await rig.closeAll(); + } +}); + interface ShellHarness { send(msg: unknown): void; settled: Promise; @@ -302,15 +360,17 @@ test("shared shim, no env/meta id: per-call ids route two sessions independently assert.equal(callB.result?.isError, false, `per-call call routed to B${callB.result?.isError ? ": " + (callB.result?.content?.[0]?.text ?? "") : ""}`); await waitFor(() => rig.upstreamBodies.length >= 5, "five upstream bodies"); + const canonA = canonicalOf("conv-mcp-a"); + const canonB = canonicalOf("conv-mcp-b"); // A's first request: wire mode — ephemeral compress tool injected, id note present. assert.ok(toolNames(rig.upstreamBodies[0]).includes("compress"), "wire request carries the ephemeral compress tool"); - assert.match(sysText(rig.upstreamBodies[0]), /\[Your bili conversation id: conv-mcp-a\./); - // A's second request arrives AFTER the identity registration landed: + assert.match(sysText(rig.upstreamBodies[0]), new RegExp(`\\[Your bili conversation id: ${canonA}\\.`)); + // A's second request arrives AFTER the tool call landed: // pure plugin mode — no ephemeral tools, id note still flows. - assert.ok(!toolNames(rig.upstreamBodies[2]).includes("compress"), "post-registration request drops the ephemeral compress tool"); - assert.match(sysText(rig.upstreamBodies[2]), /\[Your bili conversation id: conv-mcp-a\./, "id note flows in plugin mode too"); + assert.ok(!toolNames(rig.upstreamBodies[2]).includes("compress"), "post-tool-call request drops the ephemeral compress tool"); + assert.match(sysText(rig.upstreamBodies[2]), new RegExp(`\\[Your bili conversation id: ${canonA}\\.`), "id note flows in plugin mode too"); // B's requests carry B's id, not A's — no cross-talk. - assert.match(sysText(rig.upstreamBodies[3]), /\[Your bili conversation id: conv-mcp-b\./); + assert.match(sysText(rig.upstreamBodies[3]), new RegExp(`\\[Your bili conversation id: ${canonB}\\.`)); // Sticky plugin-mode flip, and the untouched sibling stays wire mode. const stA = await statusOf(rig, "conv-mcp-a"); From 5f1e0df07c41ae8e7de59ba8425c2f8ff40917b1 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 14 Sep 2026 19:38:09 +0800 Subject: [PATCH 3/4] refactor: drop redundant per-call lazy registration; test canonical routing Per review of #760: per-call ensureRegistered() was dead weight. The sticky plugin-mode flip already comes from successful-tool evidence inside handlePluginTool, and a registration keyed by the canonical pfa-* id would never be consumed by a raw-client-id request anyway (consumePluginRegisterFor(raw-id) misses it) while still evicting identity-register LRU slots (cap 64). - src/mcp.ts: remove the per-call register call and the now-unused ensureRegistered(); keep initialize/register (single-session hosts enter plugin mode before their first model request) and rely on evidence for shared-host flips. - tests: the shared-shim e2e now passes the canonical pfa-* id (what the model copies from the injected note) instead of the raw client id, so it exercises the canonical reverse-lookup path end-to-end; the mock-proxy unit asserts NO registration is issued for per-call ids; comments/assertion messages updated from 'identity-mode lazy registration' to 'successful-tool evidence'. Extends PR #761. Fixes #760. --- src/mcp.ts | 21 ----------- tests/issue760-percall-conversation.test.ts | 40 +++++++++++---------- 2 files changed, 22 insertions(+), 39 deletions(-) diff --git a/src/mcp.ts b/src/mcp.ts index 5a255f9e24..5de66bd5b7 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -144,26 +144,6 @@ export async function forwardTool(tool: string, args: unknown, timeoutMs: number } } -/** #760: lazy registration for a per-call conversation id. Always identity- - * mode: the id names an EXISTING conversation whose model requests carry the - * same value, so binding fires on that conversation's next request only — - * never headless (which would bind the NEXT new session, i.e. some other - * client's conversation, on a shared multi-session proxy). */ -async function ensureRegistered(conversationIdArg: string): Promise { - if (registeredConversations.has(conversationIdArg)) return; - registeredConversations.add(conversationIdArg); // issue-once even if the fetch fails - try { - await fetch(`${resolveProxyOrigin()}/__bili/plugin/register`, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ conversationId: conversationIdArg, agent: "mcp", identity: true }), - signal: AbortSignal.timeout(5000), - }); - } catch (err) { - process.stderr.write(`[bili-mcp] per-call registration of "${conversationIdArg}" failed: ${err instanceof Error ? err.message : String(err)}\n`); - } -} - /** One-shot recovery for a stale shim id (#656): resolve the proxy's * most-recent ACTIVE conversation via the status endpoint's fallback=latest * and adopt it for all subsequent tool calls. Returns true when an adoption @@ -273,7 +253,6 @@ async function handleMessage(msg: { return; } try { - if (perCall) await ensureRegistered(perCall); const text = await forwardTool(tool, args, TOOL_TIMEOUT_MS, perCall || undefined); sendResult(id, { content: [{ type: "text", text }], isError: false }); } catch (err) { diff --git a/tests/issue760-percall-conversation.test.ts b/tests/issue760-percall-conversation.test.ts index af5a08c640..220bce85a9 100644 --- a/tests/issue760-percall-conversation.test.ts +++ b/tests/issue760-percall-conversation.test.ts @@ -19,7 +19,7 @@ import { ACP_TOOLS_ANTHROPIC } from "../src/compress-tool.ts"; // env/meta session channel, so the model supplies the target conversation per // tool call. Covered here: manifest schema, the proxy's injected id note, // first-call routing (peekSession fallback), unknown-id rejection, sticky -// plugin-mode flip via identity-mode lazy registration, and the shim's +// plugin-mode flip via successful-tool evidence, and the shim's // per-call routing / arg stripping / adoption guard. function listen(server: http.Server): Promise { @@ -336,24 +336,27 @@ test("shared shim, no env/meta id: per-call ids route two sessions independently assert.equal((t.inputSchema?.properties?.conversation_id as { type?: string } | undefined)?.type, "string", `shim exposes conversation_id on ${t.inputSchema ? "tool" : "unknown"}`); } - // Session A exists; first per-call tool call must route immediately - // (lazy identity registration rides along). + // Session A exists; first per-call tool call routes immediately via + // the canonical reverse lookup — the model copies the pfa-* id the + // proxy printed in A's note, not the raw client id. await postModel(rig, "conv-mcp-a"); - h.send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "conv-mcp-a" } } }); + h.send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: canonicalOf("conv-mcp-a") } } }); await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 3), "per-call acp_status(A)"); const callA = byId(h.lines, 3) as { result?: { content?: { text?: string }[]; isError?: boolean } }; assert.equal(callA.result?.isError, false, `per-call call routed to A${callA.result?.isError ? ": " + (callA.result?.content?.[0]?.text ?? "") : ""}`); assert.match(callA.result?.content?.[0]?.text ?? "", /CONTEXT BREAKDOWN/); - // A brand-new unrelated session lands BEFORE A's next request: a - // headless registration would have bound IT instead of A. + // An unrelated session lands between A's requests: the evidence-based + // flip touches ONLY the session whose own tool executed, so this one + // must NOT be flipped or routed to. await postModel(rig, "conv-other"); await postModel(rig, "conv-mcp-a"); await postModel(rig, "conv-mcp-b"); - h.send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "conv-mcp-b" } } }); + h.send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: canonicalOf("conv-mcp-b") } } }); // Await the tool result BEFORE B's next request: real agents only - // resume the model loop after the tool call returns, so the lazy - // registration always lands first — the test must mirror that order. + // resume the model loop after the tool call returns, and the + // evidence-based flip lands synchronously inside that call — the test + // must mirror that order. await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 4), "per-call acp_status(B)"); await postModel(rig, "conv-mcp-b"); const callB = byId(h.lines, 4) as { result?: { content?: { text?: string }[]; isError?: boolean } }; @@ -375,14 +378,14 @@ test("shared shim, no env/meta id: per-call ids route two sessions independently // Sticky plugin-mode flip, and the untouched sibling stays wire mode. const stA = await statusOf(rig, "conv-mcp-a"); assert.equal(stA.ok, true); - assert.equal(stA.pluginAgent, "mcp", "A flipped to plugin mode via identity-mode lazy registration"); + assert.equal(stA.pluginAgent, "mcp", "A flipped to plugin mode via successful-tool evidence"); const stB = await statusOf(rig, "conv-mcp-b"); assert.equal(stB.pluginAgent, "mcp", "B flipped independently"); const stOther = await statusOf(rig, "conv-other"); - assert.notEqual(stOther.pluginAgent, "mcp", "unrelated session NOT stolen by a headless registration"); + assert.notEqual(stOther.pluginAgent, "mcp", "unrelated session NOT flipped (evidence flip touches only the session whose own tool ran)"); // A repeat per-call call still routes to A. - h.send({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "conv-mcp-a" } } }); + h.send({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: canonicalOf("conv-mcp-a") } } }); await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 5), "repeat per-call acp_status(A)"); const callA2 = byId(h.lines, 5) as { result?: { isError?: boolean } }; assert.equal(callA2.result?.isError, false, "repeat call still routes to A"); @@ -392,7 +395,7 @@ test("shared shim, no env/meta id: per-call ids route two sessions independently } }); -test("shim: per-call id strips the forwarded arg, registers identity-once, never adopts for per-call 404s", async () => { +test("shim: per-call id strips the forwarded arg, routes on the body field, never registers or adopts for per-call ids", async () => { const posts: { url: string; body: Record }[] = []; const mock = http.createServer((req, res) => { const chunks: Buffer[] = []; @@ -444,17 +447,18 @@ test("shim: per-call id strips the forwarded arg, registers identity-once, never assert.equal(callX.result?.isError, false); assert.equal(callX.result?.content?.[0]?.text, "fine"); - const regs = posts.filter((p) => p.url.startsWith("/__bili/plugin/register")); - assert.equal(regs.length, 1, "exactly one lazy registration"); - assert.deepEqual(regs[0].body, { conversationId: "X", agent: "mcp", identity: true }, "identity-mode registration, never headless"); + // No lazy registration for per-call ids anymore — the sticky flip comes + // from successful-tool evidence inside the call, not from a registration + // a raw-client-id request would never consume. + assert.equal(posts.filter((p) => p.url.startsWith("/__bili/plugin/register")).length, 0, "no lazy registration issued for a per-call id"); const toolPost = posts.find((p) => p.url.startsWith("/__bili/plugin/tool")); assert.equal(toolPost?.body.conversationId, "X", "routes on the body-level field"); assert.deepEqual(toolPost?.body.args, { extra: 1 }, "conversation_id stripped from the forwarded args"); - // Issue-once: a repeat call issues no second registration. + // A repeat call still issues no registration. h.send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "acp_status", arguments: { conversation_id: "X" } } }); await waitFor(() => h.lines.some((l) => (JSON.parse(l) as { id?: number }).id === 4), "repeat per-call X"); - assert.equal(posts.filter((p) => p.url.startsWith("/__bili/plugin/register")).length, 1, "registration issue-once"); + assert.equal(posts.filter((p) => p.url.startsWith("/__bili/plugin/register")).length, 0, "still no registration after a repeat call"); // Unknown per-call id fails loudly — no orphan adoption (which would // mutate the shared default binding for everyone else's calls). From 9009973409375adb9d9908f84bf1e9cb76e8e118 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Mon, 14 Sep 2026 23:04:17 +0800 Subject: [PATCH 4/4] =?UTF-8?q?docs:=20mcp.ts=20header=20=E2=80=94=20per-c?= =?UTF-8?q?all=20ids=20route=20without=20registration=20(#760b)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/mcp.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/mcp.ts b/src/mcp.ts index 5de66bd5b7..c71717483a 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -8,8 +8,9 @@ // #760: a fourth channel for hosts that share ONE shim across several // concurrent conversations (no env/meta session at all): every tool accepts an // optional conversation_id argument the model copies from the proxy's notes, -// which overrides the default binding and lazily registers the named -// conversation on first use. +// which overrides the default binding for that one call only. No registration +// is issued for per-call ids — the proxy resolves them directly and flips the +// target session to plugin mode on successful execution. import fs from "node:fs"; import path from "node:path";