From 8c989a43a876a0af18a746592a54273a65d82b35 Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 13 Nov 2026 02:43:57 +0800 Subject: [PATCH 1/4] fix(zcode): normalize sess_ prefix so shim env binding resolves the proxy session (#6433) zcode's bootstrap-hook injects CLAUDE_CODE_SESSION_ID with a sess_ prefix (sess_), but the proxy's plugin routing keys sessions by the bare uuid (the model request header carries the bare form). Neither side stripped the prefix, so the shim's default binding always 404'd with 'unknown plugin conversation'. Fix: strip the sess_ prefix at all three id-extraction points: - src/mcp.ts: CONVERSATION_FROM_ENV (shim env binding) - src/plugin.ts: handlePluginTool body conversationId (defensive, for older shims) - src/session-id.ts: conversationHeaderSource (model request header, for robustness) The shared stripSessPrefix helper lives in src/session-id.ts. No other client uses this prefix (grep-verified), so a global strip is safe. --- src/mcp.ts | 7 ++++++- src/plugin.ts | 7 +++++-- src/session-id.ts | 19 ++++++++++++++++++- tests/proxy-session-id.test.ts | 32 +++++++++++++++++++++++++++++++- 4 files changed, 60 insertions(+), 5 deletions(-) diff --git a/src/mcp.ts b/src/mcp.ts index 88f1e6c015..a8ab6f34fa 100644 --- a/src/mcp.ts +++ b/src/mcp.ts @@ -37,6 +37,7 @@ import { fileURLToPath } from "node:url"; import { isPidAlive, isProxyInstanceFile, readProxyInstanceFile } from "./instance.js"; import { parseBlocksCreated, parseToolOutcome, partialOutcomeNote } from "./proxy-tool-result.js"; import type { ToolOutcomeKind } from "./proxy-tool-result.js"; +import { stripSessPrefix } from "./session-id.js"; const VERSION = (() => { try { @@ -89,7 +90,11 @@ const TOOL_TIMEOUT_MS = 60_000; // compress-call HTTP wait — covers the non-budgeted work around the batch outside the // totalTimeoutMs clock (same rationale as src/agent/shared.ts). const TOOL_TIMEOUT_OVERHEAD_MARGIN_MS = 30_000; -const CONVERSATION_FROM_ENV = process.env.CLAUDE_CODE_SESSION_ID?.trim() || process.env.BILI_CONVERSATION_ID?.trim() || undefined; +// #6433: zcode's bootstrap-hook injects CLAUDE_CODE_SESSION_ID with a `sess_` +// prefix (sess_), but the proxy's plugin routing keys sessions by the +// bare uuid (the model request header carries the bare form). Strip the prefix +// so the shim's default binding matches the session the proxy created. +const CONVERSATION_FROM_ENV = stripSessPrefix(process.env.CLAUDE_CODE_SESSION_ID) || stripSessPrefix(process.env.BILI_CONVERSATION_ID) || undefined; const IDENTITY_BINDING = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim()); // #656: hosts that resume a session (claude --resume forks a NEW session id) // do so after MCP children were spawned — the env-captured id goes stale and diff --git a/src/plugin.ts b/src/plugin.ts index ab0b10c90e..73ca82a741 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -9,7 +9,7 @@ import { createHash } from "node:crypto"; import { CORRUPT_SIBLING_CAP, getStore, pruneCorruptSiblings, storageStatusLabel, kvStore } from "./persist.js"; import { cloneStoreForRefs } from "./store.js"; import { acquireInFlight, createSession, getSessionAsync, publishForkSession, diagnoseSuccessWithoutUsage, effectiveConfig, findSessionByCanonicalId, listSessions, markCompactionBoundary, markDirty, noteAbortedTurn, noteTruncatedUpstream, peekSession, releaseInFlight, statusInputBaseline, withSessionLock, type Session } from "./session.js"; -import { clientConversationHeader } from "./session-id.js"; +import { clientConversationHeader, stripSessPrefix } from "./session-id.js"; import { buildContextView } from "./context-view.js"; import { ABSORB_TOOL_NAME, BILI_ACP_TOOLS_ANTHROPIC, BILI_ACP_TOOLS_ANTHROPIC_NO_RANGE, BILI_ACP_TOOLS_OPENAI, BILI_ACP_TOOLS_OPENAI_NO_RANGE, BILI_ACP_TOOLS_RESPONSES_NO_RANGE, PROXY_TOOL_NAMES, READ_ORIGINAL_IMAGE_TOOL, READ_ORIGINAL_IMAGE_TOOL_NAME, READ_ORIGINAL_IMAGE_TOOL_OPENAI, READ_ORIGINAL_IMAGE_TOOL_RESPONSES, RETRIEVE_TOOL_NAME, RULE_TOOL, RULE_TOOL_NAME, RULE_TOOL_OPENAI, RULE_TOOL_RESPONSES, SEARCH_CONTEXT_TOOL_NAME, absorbToolsFor, retrieveToolsFor, withAcpNotes, withAcpNotesOpenAI } from "./compress-tool.js"; import { externalSummaryEnabled, externalSummaryMaxToolDurationMs, withExternalSummaryTools } from "./external-summary-surface.js"; @@ -2179,7 +2179,10 @@ export async function handlePluginTool( res.end(JSON.stringify({ ok: false, error: "invalid JSON body" })); return; } - const conversationId = typeof parsed.conversationId === "string" ? parsed.conversationId.trim() : ""; + // #6433: normalize the zcode `sess_` prefix (sess_ → ) so an + // older shim or another client sending the prefixed form still resolves the + // bare-uuid session the proxy created from the model request header. + const conversationId = stripSessPrefix(typeof parsed.conversationId === "string" ? parsed.conversationId : undefined) ?? ""; const tool = typeof parsed.tool === "string" ? parsed.tool : ""; if (parsed.toolCallId !== undefined && (typeof parsed.toolCallId !== "string" || !parsed.toolCallId.trim() || parsed.toolCallId.length > 512)) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "toolCallId must be a non-empty string of at most 512 characters" }); if (parsed.expectedRevision !== undefined && (typeof parsed.expectedRevision !== "string" || !/^[a-f0-9]{64}$/.test(parsed.expectedRevision))) return forkReply(res, 400, { ok: false, code: "INVALID_REQUEST", error: "expectedRevision must be a snapshot revision" }); diff --git a/src/session-id.ts b/src/session-id.ts index e12327a225..6fb6dd1b60 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -10,6 +10,18 @@ export type ConversationIdentity = { clientProvided: boolean; }; +/** #6433: zcode's bootstrap-hook injects CLAUDE_CODE_SESSION_ID with a `sess_` + * prefix (sess_), but the proxy's plugin routing keys sessions by the + * bare uuid (the model request header carries the bare form). Strip the prefix + * so the shim's env binding and the proxy's session store agree on the id. + * No other client uses this prefix (grep-verified), so a global strip is safe. */ +export function stripSessPrefix(v: string | undefined): string | undefined { + const t = v?.trim(); + if (!t) return undefined; + const stripped = t.startsWith("sess_") ? t.slice("sess_".length) : t; + return stripped.length > 0 ? stripped : undefined; +} + /** * Session identity for the proxy's OWN compression state. * @@ -97,7 +109,12 @@ export function conversationHeaderSource(headers: Record 0) return { name, value: v.trim() }; + // #6433: normalize the zcode `sess_` prefix so a header carrying the + // prefixed form still keys the same bare-uuid session the shim binds to. + if (typeof v === "string") { + const normalized = stripSessPrefix(v); + if (normalized) return { name, value: normalized }; + } } return undefined; } diff --git a/tests/proxy-session-id.test.ts b/tests/proxy-session-id.test.ts index 68689cb7c6..5893d45fb1 100644 --- a/tests/proxy-session-id.test.ts +++ b/tests/proxy-session-id.test.ts @@ -1,6 +1,6 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { affinityToken, clientConversationHeader, codexTurnIdentity, preferPromptCacheKeyIdentity } from "../src/session-id.ts"; +import { affinityToken, clientConversationHeader, codexTurnIdentity, preferPromptCacheKeyIdentity, stripSessPrefix } from "../src/session-id.ts"; import { conversationIdentityResponses, conversationSignalResponses } from "acp-kernel/wire"; test("preferPromptCacheKeyIdentity: fingerprint + prompt_cache_key → stable client-provided identity (omp stateless replay)", () => { @@ -102,6 +102,36 @@ test("clientConversationHeader: reads known session header names in priority ord assert.equal(clientConversationHeader({ "x-bili-plugin": "opencode", "x-bili-plugin-conversation": "P", "x-opencode-session-id": "N" }), "P"); }); +test("stripSessPrefix: zcode sess_ prefix normalization (#6433)", () => { + // zcode's bootstrap-hook injects CLAUDE_CODE_SESSION_ID with a sess_ prefix + // (sess_), but the proxy's plugin routing keys sessions by the bare + // uuid. The prefix must be stripped so both forms agree on the id. + assert.equal(stripSessPrefix("sess_abc-123"), "abc-123"); + assert.equal(stripSessPrefix(" sess_abc-123 "), "abc-123"); + // Bare uuid (no prefix) is unchanged. + assert.equal(stripSessPrefix("abc-123"), "abc-123"); + // "sess" without the trailing underscore is NOT the prefix — kept verbatim. + assert.equal(stripSessPrefix("sess-abc"), "sess-abc"); + // "sess_" alone strips to empty → undefined (no usable id). + assert.equal(stripSessPrefix("sess_"), undefined); + // Empty / undefined inputs. + assert.equal(stripSessPrefix(""), undefined); + assert.equal(stripSessPrefix(" "), undefined); + assert.equal(stripSessPrefix(undefined), undefined); +}); + +test("clientConversationHeader: normalizes zcode sess_ prefix (#6433)", () => { + // A header carrying the sess_-prefixed form must resolve to the bare uuid + // so the session the proxy created (from the bare-uuid model request) is + // found by the shim's env binding. + assert.equal(clientConversationHeader({ "x-claude-code-session-id": "sess_abc-123" }), "abc-123"); + assert.equal(clientConversationHeader({ "x-session-id": "sess_abc-123" }), "abc-123"); + // A value that is ONLY the prefix strips to empty → falls through to the + // next header in the walk (or undefined when none remains). + assert.equal(clientConversationHeader({ "x-session-id": "sess_", "x-acp-session": "B" }), "B"); + assert.equal(clientConversationHeader({ "x-session-id": "sess_" }), undefined); +}); + test("affinityToken: client-provided identity passes through verbatim (credentials never in scope)", () => { // affinityToken receives only the resolved identity object // ({ value, source, clientProvided }) — never raw headers or the From 908c34ca7fc5694bb3009815736b143813bf037f Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 13 Nov 2026 04:18:38 +0800 Subject: [PATCH 2/4] fix(zcode): ring-record outbound tool calls on the non-plugin response lane (#6433) The unbound zcode subagent shim (no CLAUDE_CODE_SESSION_ID) routes via the witness ring, but the ring was only fed by the plugin-mode response pipe (settleWitnesses), which early-returns when no session object is passed. The non-plugin lane deliberately passes undefined to keep usage accounting off, so a subagent's own outbound tool calls were never ring-recorded and the witness route always missed. Add an optional witnessSessionId parameter to pipePluginChatWithStrip and pipePluginResponsesWithStrip; settleWitnesses now records under that id even when the full session is absent, so usage accounting stays off while the witness ring is still fed. The non-plugin SSE branch in relay.ts passes p.session?.id as the witness id. --- src/plugin.ts | 21 +++++++++++++++------ src/server/relay.ts | 8 ++++++++ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/src/plugin.ts b/src/plugin.ts index 73ca82a741..b2006cf5d1 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -2722,6 +2722,11 @@ export async function pipePluginChatWithStrip( // default); hosts that need the legacy completed-turn shape opt back in with // streamErrorShape:"completion". streamErrorShape?: "protocol" | "completion", + // #6433: session id for witness recording only — lets the non-plugin lane + // ring-record outbound tool calls (so the unbound shim's witness route can + // match) without passing the full session (which would turn on usage + // accounting and clobber lastInputTokens for title-gen / side calls). + witnessSessionId?: string, ): Promise { let reader = stream.getReader(); let decoder = new TextDecoder("utf-8"); @@ -2867,14 +2872,15 @@ export async function pipePluginChatWithStrip( const compressDeltaFrame = (index: number, partialJson: string): string => `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", index, delta: { type: "input_json_delta", partial_json: partialJson } })}\n\n`; const settleWitnesses = () => { - if (!session) return; + const sid = witnessSessionId ?? session?.id; + if (!sid) return; for (const tc of seenToolCalls.values()) { if (tc.name.length === 0) continue; - recordToolWitness(session.id, tc.name, tc.args); + recordToolWitness(sid, tc.name, tc.args); // #4580: the same observation carries the host's tool_use id — // ring it so a later tools/call stamped with that id routes to // THIS lane even when the shared MCP shim is bound elsewhere. - if (tc.id.length > 0) recordToolUseId(tc.id, session.id); + if (tc.id.length > 0) recordToolUseId(tc.id, sid); } }; // Degenerate-turn retry (#732/#821 for this pipe). The first attempt's @@ -4226,6 +4232,8 @@ export async function pipePluginResponsesWithStrip( // #2328 Q2 — see pipePluginChatWithStrip. upstreamMeta?: UpstreamMeta, reply?: HandoffReply, + // #6433: session id for witness recording only — see pipePluginChatWithStrip. + witnessSessionId?: string, ): Promise { let reader = stream.getReader(); let decoder = new TextDecoder("utf-8"); @@ -4288,15 +4296,16 @@ export async function pipePluginResponsesWithStrip( // function_call_arguments.done; both are accumulate-then-record at settle. const witnessedCalls = new Map(); const settleWitnesses = () => { - if (!session) return; + const sid = witnessSessionId ?? session?.id; + if (!sid) return; for (const [itemId, wc] of witnessedCalls) { if (!wc.named || wc.name.length === 0) continue; - recordToolWitness(session.id, wc.name, wc.args); + recordToolWitness(sid, wc.name, wc.args); // #4580: the map key is the output item's id (fc_…), i.e. the // host's per-call id — ring it for id-stamped tools/call routing. // Synthetic fallback keys ("oi:") are never host-stamped; // skip them so cross-session index keys can't shadow real ids. - if (itemId.length > 0 && !itemId.startsWith("oi:")) recordToolUseId(itemId, session.id); + if (itemId.length > 0 && !itemId.startsWith("oi:")) recordToolUseId(itemId, sid); } }; let sawReasoning = false; diff --git a/src/server/relay.ts b/src/server/relay.ts index 99c6cb5667..ccaf1a9c04 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -2478,6 +2478,7 @@ async function forwardCaptured( undefined, upstreamMeta, reply, + prepared.session?.id, ); } else { await pipeThrough(toClient, res); @@ -2507,6 +2508,11 @@ async function forwardCaptured( // the main conversation (see pipePluginChatWithStrip docs). const p = prepared; const tagLog = (msg: string) => log("info", `[${p.session.id}] ${msg}`); + // #6433: pass the session id (not the full session) so the pipe can + // ring-record outbound tool calls for the unbound shim's witness + // route, while keeping usage accounting off (the full session would + // turn it on and clobber lastInputTokens for title-gen / side calls). + const witnessSid = p.session?.id; if (p.protocol === "responses") { await pipePluginResponsesWithStrip( responseBody, @@ -2530,6 +2536,7 @@ async function forwardCaptured( undefined, upstreamMeta, reply, + witnessSid, ); } else { await pipePluginChatWithStrip( @@ -2557,6 +2564,7 @@ async function forwardCaptured( upstreamMeta, reply, opts.streamErrorShape, + witnessSid, ); } } else if ( From 3ee5770cbcce79e70223eea264c148afabcee3cd Mon Sep 17 00:00:00 2001 From: ci-check Date: Sat, 14 Nov 2026 15:18:03 +0800 Subject: [PATCH 3/4] fix(zcode): ring-record non-plugin tool calls on the non-streaming JSON lane (#6433) The witnessSessionId seam added by this PR covered only the two SSE pipes (pipePluginChatWithStrip / pipePluginResponsesWithStrip). The non-streaming non-plugin lane (relay.ts pipePluginJson) still passed no session, so a non-streaming subagent's outbound tool calls were never ring-recorded and the unbound shim's witness route kept missing them. Mirror the SSE pattern: pipePluginJson takes an optional trailing witnessSessionId and records under witnessSessionId ?? session?.id; the relay JSON branch passes prepared.session?.id. Plugin-lane callers are unaffected (session already passed, witnessSessionId omitted). Adds the missing non-plugin witnessSessionId regression tests (SSE + JSON). --- src/plugin.ts | 10 +++++++++- src/server/relay.ts | 5 ++++- tests/tool-witness-pipes.test.ts | 26 ++++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/src/plugin.ts b/src/plugin.ts index 2993e632b6..207b7a2afe 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -5214,6 +5214,10 @@ export async function pipePluginJson( // m00885: echoed (user-requested verbatim) emission spans survive. requestText?: string, reply?: HandoffReply, + // #6433: session id for witness recording only — lets the non-plugin JSON + // lane ring-record outbound tool calls (mirroring the SSE pipes) without + // passing the full session (which would turn on usage accounting). + witnessSessionId?: string, ): Promise { // Also serves proxy-mode JSON responses that skipped compress injection // (#460 residual) — pass no session there so usage accounting stays off. @@ -5279,7 +5283,11 @@ export async function pipePluginJson( // #1685: a non-streaming plugin response still carries the model's // complete tool calls — same witness feed as the SSE pipes, from the // one full-body parse this path already does. Observe-only (#1039). - if (session) recordJsonToolWitnesses(session.id, json, protocol); + // #6433: the non-plugin JSON lane passes no session (usage accounting + // stays off) but still ring-records via witnessSessionId, mirroring + // the SSE pipes, so the unbound shim's witness route can match. + const witnessSid = witnessSessionId ?? session?.id; + if (witnessSid) recordJsonToolWitnesses(witnessSid, json, protocol); } catch { /* non-JSON body — forward verbatim */ } // #2190: degenerate-close residue never trips RENDER_TAG_DETECT — check its shape too. // m00885: an absorb-instructed turn may answer with a whole-field diff --git a/src/server/relay.ts b/src/server/relay.ts index b540eae8cf..c2f2e9c4cb 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -2617,7 +2617,10 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare // so a non-injected JSON response must not hand the model's echoes // back untouched. Same pipe as plugin mode; no session, so usage // accounting stays off for the same reason as above. - await pipePluginJson(responseBody, res, undefined, prepared.protocol, undefined, undefined, undefined, reply); + // #6433: pass the session id (not the full session) so the pipe can + // ring-record outbound tool calls for the unbound shim's witness + // route, mirroring the SSE branch above. + await pipePluginJson(responseBody, res, undefined, prepared.protocol, undefined, undefined, undefined, reply, prepared.session?.id); } else { await pipeThrough(responseBody, res); } diff --git a/tests/tool-witness-pipes.test.ts b/tests/tool-witness-pipes.test.ts index ecb0c30b12..ade6308340 100644 --- a/tests/tool-witness-pipes.test.ts +++ b/tests/tool-witness-pipes.test.ts @@ -130,6 +130,32 @@ test("json pipe: non-stream tool_calls land in the witness ring", async () => { assert.deepEqual([...lookupToolWitness("compress", COMPRESS_ARGS)], ["w-json"]); }); +test("chat pipe: non-plugin lane (session=undefined) ring-records via witnessSessionId (#6433)", async () => { + resetToolRingForTest(); + const events = [ + chatChunk({ role: "assistant" }), + chatChunk({ tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "compress", arguments: '{"startId":"m00001",' } }] }), + chatChunk({ tool_calls: [{ index: 0, function: { arguments: '"endId":"m00009","summary":"witness lane test"}' } }] }), + chatChunk({}, { choices: [{ index: 0, delta: {}, finish_reason: "tool_calls" }] }), + DONE, + ]; + // session omitted (non-plugin lane, usage accounting stays off); the + // witnessSessionId is the trailing param — the ring must record under it. + await pipePluginChatWithStrip(streamOf(events), makeRes([]), "openai", undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "w-np"); + assert.deepEqual([...lookupToolWitness("compress", COMPRESS_ARGS)], ["w-np"]); +}); + +test("json pipe: non-plugin lane (session=undefined) ring-records via witnessSessionId (#6433)", async () => { + resetToolRingForTest(); + const body = JSON.stringify({ + id: "chatcmpl-x", object: "chat.completion", created: 1, model: "qwen", + choices: [{ index: 0, message: { role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "compress", arguments: COMPRESS_ARGS } }] }, finish_reason: "tool_calls" }], + }); + // session omitted; witnessSessionId is the trailing param on pipePluginJson. + await pipePluginJson(streamOf([body]), makeRes([]), undefined, "openai", undefined, undefined, undefined, undefined, "w-np-json"); + assert.deepEqual([...lookupToolWitness("compress", COMPRESS_ARGS)], ["w-np-json"]); +}); + test("nameless tool call never becomes a witness (#1484 class)", async () => { resetToolRingForTest(); const events = [ From a64266ea4e39c967aa7944b6fba64b51f8d9ec83 Mon Sep 17 00:00:00 2001 From: ework-agent Date: Sun, 15 Nov 2026 10:55:39 +0800 Subject: [PATCH 4/4] fix(ci): resolve REPO_ROOT via import.meta.dirname in e2e-selfupdate-cli On Windows, new URL(import.meta.url).pathname yields /D:/a/... (leading slash before the drive), so path.resolve prepends the current drive and the module-level readFileSync opens D:\D:\a\...\package.json and crashes the whole test file at import time. import.meta.dirname is the cross-platform form already used by every sibling e2e test. --- tests/e2e/e2e-selfupdate-cli.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/e2e/e2e-selfupdate-cli.test.ts b/tests/e2e/e2e-selfupdate-cli.test.ts index ed666e81cf..59c3402316 100644 --- a/tests/e2e/e2e-selfupdate-cli.test.ts +++ b/tests/e2e/e2e-selfupdate-cli.test.ts @@ -27,7 +27,7 @@ import { test } from "node:test"; import { startRegistry } from "./registry-fixture.js"; import { biliSpawnEnv, isolatedEnv, npmHomeEnv, npmRunSync, windowsSystemEnv } from "./crossplat.ts"; -const REPO_ROOT = path.resolve(path.dirname(new URL(import.meta.url).pathname), "..", ".."); +const REPO_ROOT = path.resolve(import.meta.dirname, "..", ".."); const PKG = JSON.parse(fs.readFileSync(path.join(REPO_ROOT, "package.json"), "utf8")) as { name: string; files: string[];