Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/mcp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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_<uuid>), 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
Expand Down
38 changes: 29 additions & 9 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, releaseNudgeHold, 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, blockOpsTools, retrieveToolsFor, withAcpNotes, withAcpNotesOpenAI } from "./compress-tool.js";
import { blockOpsEnabled, effectiveBlockOpsConfig } from "./acp-block-ops.js";
Expand Down Expand Up @@ -2241,7 +2241,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_<uuid> → <uuid>) 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" });
Expand Down Expand Up @@ -2785,6 +2788,11 @@ export async function pipePluginChatWithStrip(
// #5951: the requesting host already classifies this cut and retries on its
// own budget — the proxy must not spend a second one.
hostOwnsTruncationRecovery = false,
// #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<void> {
let reader = stream.getReader();
let decoder = new TextDecoder("utf-8");
Expand Down Expand Up @@ -2931,14 +2939,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
Expand Down Expand Up @@ -4359,6 +4368,8 @@ export async function pipePluginResponsesWithStrip(
upstreamMeta?: UpstreamMeta,
reply?: HandoffReply,
hostOwnsTruncationRecovery = false,
// #6433: session id for witness recording only — see pipePluginChatWithStrip.
witnessSessionId?: string,
): Promise<void> {
let reader = stream.getReader();
let decoder = new TextDecoder("utf-8");
Expand Down Expand Up @@ -4422,15 +4433,16 @@ export async function pipePluginResponsesWithStrip(
// function_call_arguments.done; both are accumulate-then-record at settle.
const witnessedCalls = new Map<string, { name: string; args: string; named: boolean }>();
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:<index>") 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;
Expand Down Expand Up @@ -5215,6 +5227,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<void> {
// Also serves proxy-mode JSON responses that skipped compress injection
// (#460 residual) — pass no session there so usage accounting stays off.
Expand Down Expand Up @@ -5283,7 +5299,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
Expand Down
13 changes: 12 additions & 1 deletion src/server/relay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2555,6 +2555,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
upstreamMeta,
reply,
hostOwnsTruncationRecovery,
prepared.session?.id,
);
} else {
await pipeThrough(toClient, res);
Expand Down Expand Up @@ -2584,6 +2585,11 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
// 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,
Expand All @@ -2608,6 +2614,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
upstreamMeta,
reply,
hostOwnsTruncationRecovery,
witnessSid,
);
} else {
await pipePluginChatWithStrip(
Expand Down Expand Up @@ -2636,6 +2643,7 @@ const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepare
reply,
opts.streamErrorShape,
hostOwnsTruncationRecovery,
witnessSid,
);
}
} else if (
Expand All @@ -2647,7 +2655,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);
}
Expand Down
19 changes: 18 additions & 1 deletion src/session-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ export type ConversationIdentity = {
clientProvided: boolean;
};

/** #6433: zcode's bootstrap-hook injects CLAUDE_CODE_SESSION_ID with a `sess_`
* prefix (sess_<uuid>), 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.
*
Expand Down Expand Up @@ -97,7 +109,12 @@ export function conversationHeaderSource(headers: Record<string, string | string
for (const name of names) {
if (name === "x-bili-plugin-conversation" && !pluginMarker) continue;
const v = headers[name];
if (typeof v === "string" && v.trim().length > 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;
}
Expand Down
32 changes: 31 additions & 1 deletion tests/proxy-session-id.test.ts
Original file line number Diff line number Diff line change
@@ -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)", () => {
Expand Down Expand Up @@ -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_<uuid>), 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
Expand Down
26 changes: 26 additions & 0 deletions tests/tool-witness-pipes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
Loading