diff --git a/CHANGELOG.md b/CHANGELOG.md index 08a722ced2..5aaa897124 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,10 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ## [Unreleased] +### Fixes + +- **Claude Code subagent requests no longer queue behind the main turn's lock (#970)**: Claude Code stamps the SAME `x-claude-code-session-id` on every model request of a session — background subagents (Task tool) included — so main turn and all subagents landed on ONE session and serialized on `withSessionLock` (which covers prepare + forward + the whole streamed response). A slow subagent first token head-of-line-blocked the main turn (and vice versa) for the full upstream latency; observed live as 116-142s first-byte stalls when two subagents launched concurrently. Discrimination is two-signal, both verified against live Claude Code 2.1.274 traffic (`-p` mode, general-purpose AND custom agent types like Explore): (1) the request carries `x-claude-code-agent-id` and/or `x-claude-code-parent-agent-id` — the parent header alone is NOT reliable (`-p` general-purpose subagents send it, custom agent types do not; main turns carry agent-id only from their second request on); (2) the MAIN agent's system always contains a block starting with "You are Claude Code…" (interactive) or "You are an interactive agent…" (`-p`/SDK), while a subagent's system blocks are its agent definition ("This session is a background job…", "You are a file search specialist for…", …) — no stable positive marker exists across agent types, so the check is negative (none of the main prefixes may match). The anthropic identity branch derives `|sub:` only when BOTH signals say subagent (`claudeSubagentAgentId`/`claudeSubagentSplit` in `src/session-id.ts`, mirroring the codex #316 / Responses `subagentNamespace` precedents): each subagent gets its own lock chain and its own compression state (a subagent is its own conversation — same isolation semantics as #150). Failure degrades in the safe direction: a future rewording of the main prompts only stops the split (back to serial), never mis-splits the main session. `anthropicIdentity` itself is NOT rewritten — `affinityToken`/`clientLabel` keep the raw value, so upstream prefix caches and the UI label stay continuous across main and subagent sessions. Two guards keep the plugin layer honest: a split session's first request cannot claim the ROOT's pending register (#317 mirror), and `recordPluginSession` keys a subagent session under its split id instead of the raw conversation value — the single-valued conversations map used to flip between main and subagent sessions on every interleaved request, breaking `/acp` lookups and MCP tool routing. Older Claude Code (no headers), other agents, and curl are untouched (no split, previous behavior). Opt out with `BILI_SUBAGENT_SPLIT=0` or `"subagentSplit": false` in the config file. Tests pin: two-signal discrimination across the captured system shapes, stable namespaces, session isolation with main-identity stability, a deterministic no-stall case (upstream gates the main stream 1200ms; the subagent's first byte must beat it by a wide margin — pre-fix it arrives after, reproduced at 1238ms), and the off-switch restoring single-session behavior. End-to-end verified against live traffic: two concurrent Task subagents through the proxy land on `…|sub:` sessions in the log and complete in parallel. + ### Features - **Coexistence marker for standalone extensions (#820)**: the pi-native and opencode-native entries now set `BILLION_CONTEXT_NATIVE=` synchronously at module evaluation (gated on their own bootstrap gate, first writer wins — `markNativeHost()` in `src/agent/native-bootstrap.ts`), so the standalone `billion-context-pi` / `opencode-acp` extensions can stand down at action time when running alongside a native entry. Verified against both sibling repos that the pre-existing auto-disable does NOT cover native mode: they check `BILLION_CONTEXT_PROXY` only at extension-load time (native bootstrap writes it asynchronously, after the proxy is up) and detect `/bili/` in the configured baseUrl (native rewrites at the fetch layer, invisible to config); launcher mode and manual wiring keep working as before. Standalone-side adoption of the marker is tracked in each repo's issue tracker. diff --git a/CONFIGURATION.md b/CONFIGURATION.md index bc50f38bd9..263c3b3851 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -497,6 +497,7 @@ Environment variables take precedence over the config file. They are useful for | `ACP_LOG_FILE` | Log file path (default XDG state path; `off` disables the file, keeps stderr). Auto-rotates at 10 MB. | | `ACP_DUMP_SSE` | Directory to dump raw SSE frames for debugging. | | `BILI_LOG_MASK_HOSTS` | Set `0` to turn OFF host masking in proxy logs (#897): non-public target hosts (private relays, internal domains) are logged verbatim instead of ``. Default is ON (#255 — logs get pasted into public issues); credential-header masking is independent and always on. Real target hosts are always available without touching this flag: `GET /__bili/stats` → `blindTunnels`, `GET /__bili/health` (both loopback-only), and the `acp_status` output. | +| `BILI_SUBAGENT_SPLIT` | Set `0` to turn OFF Claude Code subagent session splitting (#970): by default, anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair (background subagents) get their own `\|sub:` session — own lock chain and compression state — instead of queueing behind the main session's lock. Default is ON. `"subagentSplit": false` in the config file does the same; the env var wins. | | `BILI_UPSTREAM_PROXY` | Upstream proxy for the proxy's own outbound connections — highest priority, above per-URL/per-provider config. See the README *Upstream proxy* section. | | `BILI_PERSIST` | Set `0` to disable session persistence (in-memory only, lost on restart). | | `BILI_PERSIST_DEBOUNCE_MS` | Debounce window for persistence writes to disk, in ms (default `500`). | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index d727cab06b..57793e4a23 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -493,6 +493,7 @@ | `ACP_LOG_FILE` | 日志文件路径(默认 XDG state 路径;`off` 关闭文件只保留 stderr)。10 MB 自动轮转。 | | `ACP_DUMP_SSE` | 调试用:转储原始 SSE 帧的目录。 | | `BILI_LOG_MASK_HOSTS` | 设为 `0` 关闭代理日志的 host 脱敏(#897):非公开目标主机(私有 relay、内网域名)原样记录,而不是 ``。默认开启(#255 —— 日志常被整段贴进公开 issue);凭据头脱敏与之独立、始终开启。真实目标域名不依赖此开关也可查:`GET /__bili/stats` → `blindTunnels`、`GET /__bili/health`(均仅 loopback),以及 `acp_status` 输出。 | +| `BILI_SUBAGENT_SPLIT` | 设为 `0` 关闭 Claude Code subagent 会话分流(#970):默认情况下,anthropic 线路上同时携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 头的请求(后台 subagent)会获得独立的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 不再排在主会话的锁后面。默认开启。配置文件中设 `"subagentSplit": false` 效果相同;环境变量优先。 | | `BILI_UPSTREAM_PROXY` | 代理自身出站连接的上游代理 —— 优先级最高,高于 per-URL/per-provider 配置。见 README「上游代理」一节。 | | `BILI_UPSTREAM_TIMEOUT_MS` | 上游请求的空闲预算(毫秒):首字节时间(TTFB)与响应体块之间的间隔(默认 `720000` = 12 分钟)。持续产出数据块的健康流永远不会被中途切断;静默的流才会。同一个值同时驱动底层 HTTP 客户端的传输层超时,因此这一个旋钮即可端到端约束本地大模型的超长 prefill(#551)。 | | `BILI_PERSIST` | 设 `0` 关闭会话持久化(仅内存,重启即丢)。 | diff --git a/src/config.ts b/src/config.ts index 4a840cbd92..2c3359c4a2 100644 --- a/src/config.ts +++ b/src/config.ts @@ -404,6 +404,11 @@ export type ProxyOptions = { * omitted). Opt out for local debugging with env BILI_LOG_MASK_HOSTS=0 * or `maskHosts: false` (#897); credential masking stays on either way. */ maskHosts?: boolean; + /** Split Claude Code subagent requests (parent+agent header pair) into + * their own session id so they don't queue on the main session's lock + * (#970, default on). Opt out with env BILI_SUBAGENT_SPLIT=0 or + * `subagentSplit: false` in the config file (env wins). */ + subagentSplit?: boolean; }; /** Re-read ONLY the routes from the current config sources, returning a fresh @@ -545,6 +550,7 @@ export function loadOptions(env: NodeJS.ProcessEnv = process.env): ProxyOptions ]), }, maskHosts: (env.BILI_LOG_MASK_HOSTS ?? (fileConfig.maskHosts === false ? "0" : "1")) !== "0", + subagentSplit: (env.BILI_SUBAGENT_SPLIT ?? (fileConfig.subagentSplit === false ? "0" : "1")) !== "0", }; } @@ -583,6 +589,9 @@ type FileConfig = { /** Set `false` to log real (non-public) target hosts instead of the * `` placeholder (#897; env BILI_LOG_MASK_HOSTS=0 wins). */ maskHosts?: boolean; + /** Set `false` to keep Claude Code subagents on the main session (#970; + * env BILI_SUBAGENT_SPLIT=0 wins). */ + subagentSplit?: boolean; /** Global wire-compat block. `roles` maps message roles to the role name * upstreams accept (e.g. `{"developer":"system"}`) — applied to the * final forwarded body for openai/responses requests (#552). */ diff --git a/src/server.ts b/src/server.ts index 380ecbd797..f5c4b6c2c0 100644 --- a/src/server.ts +++ b/src/server.ts @@ -74,7 +74,7 @@ import { rewriteOpenaiJsonResponse } from "./stream-openai.js"; import { rewriteResponsesJsonResponse } from "./stream-responses.js"; import { observeResponsesTerminalState } from "./stream-terminal.js"; import { emitPreflightError, emitStreamError } from "./stream-error.js"; -import { affinityToken, clientConversationHeader, codexTurnIdentity, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js"; +import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js"; import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js"; import { flushPrefixAffinity, hydratePrefixAffinity, scheduleAffinityPersist } from "./affinity-persist.js"; import { consumePluginRegisterFor, flushConversations, handlePluginCompact, handlePluginManifest, handlePluginRegister, handlePluginRuntimeInfo, handlePluginStatus, handlePluginTool, loadConversations, pipePluginChatWithStrip, pipePluginJson, pipePluginResponsesWithStrip, pluginAgentHeader, pluginConversationHeader, pluginHeadersMatchModel, pluginReportedContextWindow, pluginReportedMaxOutput, pluginRuntimeInfoFor, recordPluginSession, rememberPluginMessages, takePendingPluginRegister } from "./plugin.js"; @@ -1124,6 +1124,20 @@ async function handle( // unparseable / mismatched / unknown thread_source) → undefined, and // the legacy chain below is unchanged. const codexTurn = protocol === "responses" ? codexTurnIdentity(req.headers) : undefined; + // Claude Code subagent discriminator (#970): subagent requests carry + // the agent headers AND lack the main agent's system-prefix block + // (see claudeSubagentAgentId for the two-signal contract). Hoisted so + // the conversation split, the pending-register guard, and the plugin + // conversation binding below all test the same signal. + const systemTextsForSplit: string[] = + typeof (parsed as { system?: unknown }).system === "string" + ? [(parsed as { system: string }).system] + : Array.isArray((parsed as { system?: unknown }).system) + ? (parsed as { system: { text?: unknown }[] }).system + .map((b) => (typeof b?.text === "string" ? b.text : "")) + .filter((t) => t.length > 0) + : []; + const claudeSub = protocol === "anthropic" ? claudeSubagentAgentId(req.headers, systemTextsForSplit) : undefined; const responsesIdentity = protocol === "responses" ? (codexTurn ? { value: codexTurn.value, source: "header" as const, clientProvided: true } @@ -1168,7 +1182,16 @@ async function handle( ) : undefined; const conversation = protocol === "anthropic" - ? anthropicIdentity?.value ?? anthropicSignal + ? // #970: a subagent's conversation value gets its own + // `|sub:` namespace so it lands on its own session + // (own lock chain, own compression state) instead of queueing + // behind the main turn. The identity itself is NOT rewritten: + // affinityToken/clientLabel below keep consuming the raw value + // so upstream prefix caches and the UI label stay continuous + // across main and subagent sessions. + (claudeSub !== undefined && opts.subagentSplit !== false + ? claudeSubagentSplit(anthropicIdentity?.value ?? anthropicSignal, req.headers, systemTextsForSplit) + : anthropicIdentity?.value ?? anthropicSignal) : protocol === "openai" ? openaiIdentity?.value ?? openaiSignal : codexTurn @@ -1274,10 +1297,12 @@ async function handle( pluginConversation = clientConv ?? conversation; } } - if (!pluginAgent && session.stats.requests === 0 && codexTurnIdentity(req.headers) === undefined) { + if (!pluginAgent && session.stats.requests === 0 && codexTurnIdentity(req.headers) === undefined && claudeSub === undefined) { // A codex subagent thread mints a fresh session too, but it must // not claim the ROOT conversation's pending register (the plugin - // binding belongs to the root session, #317). + // binding belongs to the root session, #317). Same for a split + // Claude Code subagent session (#970): its first request looks + // brand-new, but the root's register is not its to claim. const pending = takePendingPluginRegister(); if (pending) { pluginAgent = pending.agent; @@ -1288,7 +1313,15 @@ async function handle( if (pluginAgent && !pluginConversation) pluginConversation = conversation; if (pluginAgent) { if (session.metadata.pluginAgent !== pluginAgent) session.metadata.pluginAgent = pluginAgent; - recordPluginSession(pluginConversation ?? conversation, session.id); + // #970: for a split subagent session, record it under its split + // conversation id — recording under the raw conversation value + // would flip the single-valued conversations map between the main + // and subagent sessions on every interleaved request, breaking + // /acp lookups and MCP tool routing (last writer wins). The raw + // key keeps pointing at the MAIN session; the subagent session + // stays reachable via its verbatim split id and its canonical + // pfa-* (printed in wire notes). + recordPluginSession(claudeSub !== undefined ? conversation : (pluginConversation ?? conversation), session.id); } // Responses, OpenAI-chat AND Anthropic-wire clients that send their // own session id as `prompt_cache_key` (omp) get that conversation diff --git a/src/session-id.ts b/src/session-id.ts index be0bd78f74..f2414ee831 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -158,3 +158,76 @@ export function codexTurnIdentity(headers: Record|sub:` on the + * Responses branch. Clients without these headers (older Claude Code, other + * agents, curl) are untouched. + */ +const MAIN_SYSTEM_PREFIXES = ["You are Claude Code", "You are an interactive agent"] as const; + +export function claudeSubagentAgentId( + headers: Record, + systemBlocks: string[], +): string | undefined { + // Node lowercases inbound header names; an array value (repeated header) + // is ambiguous and treated as absent, same posture as + // clientConversationHeader. + const agent = headers["x-claude-code-agent-id"]; + const parent = headers["x-claude-code-parent-agent-id"]; + const agentId = typeof agent === "string" && agent.trim().length > 0 ? agent.trim() : undefined; + const parentId = typeof parent === "string" && parent.trim().length > 0 ? parent.trim() : undefined; + if (agentId === undefined && parentId === undefined) return undefined; + const isMain = systemBlocks.some((block) => { + const t = block.trimStart(); + return MAIN_SYSTEM_PREFIXES.some((p) => t.startsWith(p)); + }); + if (isMain) return undefined; + return agentId ?? parentId; +} + +/** Derive the subagent session id `|sub:`; unchanged when the + * request is not a Claude Code subagent (no agent header, or main-turn + * system prefixes present). */ +export function claudeSubagentSplit(id: string, headers: Record, systemBlocks: string[]): string { + const agent = claudeSubagentAgentId(headers, systemBlocks); + return agent ? `${id}|sub:${agent}` : id; +} diff --git a/tests/claude-subagent-split.test.ts b/tests/claude-subagent-split.test.ts new file mode 100644 index 0000000000..af9e35cfe6 --- /dev/null +++ b/tests/claude-subagent-split.test.ts @@ -0,0 +1,218 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _resetSessionsForTest, peekSession } from "../src/session.ts"; +import { claudeSubagentAgentId, claudeSubagentSplit } from "../src/session-id.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +const SESSION = "bb54027d-f1bf-4043-8ec3-a1b2c3d4e5f6"; +const SUB_AGENT = "a51e8a9a05a035095"; +const SUB_SESSION = `${SESSION}|sub:${SUB_AGENT}`; + +function listen(server: http.Server): Promise { + if (server.listening) return Promise.resolve(); + return once(server, "listening").then(() => undefined); +} + +function close(server: http.Server): Promise { + return new Promise((resolve, reject) => server.close((error) => (error ? reject(error) : resolve()))); +} + +function sse(type: string, data: Record): string { + return `event: ${type}\ndata: ${JSON.stringify(data)}\n\n`; +} + +/** Minimal valid Anthropic /v1/messages SSE stream: one text block "ok". */ +function anthropicStream(): string { + return ( + sse("message_start", { message: { id: "msg_1", type: "message", role: "assistant", model: "claude-test", content: [], stop_reason: null, usage: { input_tokens: 10, output_tokens: 1 } } }) + + sse("content_block_start", { index: 0, content_block: { type: "text", text: "" } }) + + sse("content_block_delta", { index: 0, delta: { type: "text_delta", text: "ok" } }) + + sse("content_block_stop", { index: 0 }) + + sse("message_delta", { delta: { stop_reason: "end_turn" }, usage: { output_tokens: 2 } }) + + sse("message_stop", {}) + ); +} + +/** Mock anthropic upstream. The FIRST connection to arrive is gated behind + * `firstDelayMs` before its first byte; every later connection answers + * immediately. Used to prove the subagent request is not queued behind the + * main session's in-flight stream (the #970 stall). */ +function startMockAnthropicUpstream(firstDelayMs: number): { server: http.Server; connections: number } { + const state = { connections: 0 }; + const server = http.createServer((_req, res) => { + const isFirst = state.connections++ === 0; + const body = anthropicStream(); + if (isFirst) { + setTimeout(() => { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.write(body); + res.end(); + }, firstDelayMs); + } else { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.write(body); + res.end(); + } + }); + server.listen(0, "127.0.0.1"); + return { server, connections: 0 }; +} + +type Harness = { + proxy: http.Server; + url: string; + post: (headers: Record, body?: Record) => Promise<{ status: number; text: string; tFirstChunk: number }>; +}; + +async function startHarness(upstream: http.Server, over: Partial = {}): Promise { + const upstreamPort = (upstream.address() as { port: number }).port; + const opts: ProxyOptions = { + port: 0, + host: "127.0.0.1", + upstream: "http://127.0.0.1", + routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "claude-test": { context: 1_000_000 } } } } as ProxyOptions["routes"], + modelContextLimit: 1_000_000, + kernelConfig: defaultConfig(1_000_000), + compress: { injectTool: false, injectNudge: false }, + promptCache: { routing: "auto" }, + sessionHeader: "x-acp-session", + log: false, + debug: false, + passthrough: false, + autoUpdate: false, + mitm: { enabled: false, domains: [] }, + ...over, + }; + const proxy = await startServer(opts); + await listen(proxy); + const proxyPort = (proxy.address() as { port: number }).port; + const url = `http://127.0.0.1:${proxyPort}/bili/http://127.0.0.1:${upstreamPort}/v1/messages`; + const t0 = performance.now(); + const post = async (headers: Record, body?: Record) => { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json", ...headers }, + body: JSON.stringify(body ?? { model: "claude-test", stream: true, max_tokens: 1024, messages: [{ role: "user", content: "hi" }] }), + duplex: "half", + } as RequestInit); + let tFirstChunk = 0; + const text = await res.text(); + tFirstChunk = performance.now() - t0; + return { status: res.status, text, tFirstChunk }; + }; + return { proxy, url, post }; +} + +const sessionHeaders = { "x-claude-code-session-id": SESSION }; +const subagentHeaders = { "x-claude-code-session-id": SESSION, "x-claude-code-agent-id": SUB_AGENT, "x-claude-code-parent-agent-id": "a47c8f3e8bac7386b" }; + +// System-block shapes captured from live Claude Code 2.1.274 traffic. +const MAIN_INTERACTIVE_SYSTEM = ["You are Claude Code, Anthropic's official CLI for Claude. You are an interactive agent..."]; +const MAIN_PRINT_SYSTEM = ["x-anthropic-billing-header: cc_version=...", "You are a Claude agent, built on Anthropic's...", "You are an interactive agent that helps..."]; +const GENERAL_PURPOSE_SUB_SYSTEM = ["x-anthropic-billing-header: cc_version=...", "You are a Claude agent, built on Anthropic's...", "This session is a background job. The..."]; +const EXPLORE_SUB_SYSTEM = ["x-anthropic-billing-header: cc_version=...", "You are a Claude agent, built on Anthropic's...", "You are a file search specialist for..."]; + +test("claudeSubagentAgentId: two-signal discrimination (headers + main system prefixes)", () => { + assert.equal(claudeSubagentAgentId(subagentHeaders, GENERAL_PURPOSE_SUB_SYSTEM), SUB_AGENT, "general-purpose subagent splits"); + assert.equal(claudeSubagentAgentId(subagentHeaders, EXPLORE_SUB_SYSTEM), SUB_AGENT, "custom agent type (Explore) splits"); + assert.equal(claudeSubagentAgentId({ "x-claude-code-session-id": SESSION, "x-claude-code-agent-id": SUB_AGENT }, EXPLORE_SUB_SYSTEM), SUB_AGENT, "agent-id without parent still splits (custom agent types send no parent header)"); + assert.equal(claudeSubagentAgentId({ "x-claude-code-agent-id": "a47c8f3e8bac7386b" }, MAIN_PRINT_SYSTEM), undefined, "-p main turn (agent-id present, interactive system block) must not split"); + assert.equal(claudeSubagentAgentId({ "x-claude-code-agent-id": "a47c8f3e8bac7386b" }, MAIN_INTERACTIVE_SYSTEM), undefined, "interactive main turn must not split even with agent-id"); + assert.equal(claudeSubagentAgentId(sessionHeaders, MAIN_INTERACTIVE_SYSTEM), undefined, "no agent headers must not split"); + assert.equal(claudeSubagentAgentId(subagentHeaders, []), SUB_AGENT, "no system at all but agent headers present splits (header-only fallback)"); + assert.equal(claudeSubagentAgentId({ "x-claude-code-agent-id": " ", "x-claude-code-parent-agent-id": "p" }, EXPLORE_SUB_SYSTEM), "p", "blank agent id falls back to the parent id"); + assert.equal(claudeSubagentAgentId({ "x-claude-code-agent-id": ["a"], "x-claude-code-parent-agent-id": "p" }, EXPLORE_SUB_SYSTEM), "p", "array-valued (repeated) agent header falls back to parent"); + assert.equal(claudeSubagentAgentId(subagentHeaders, [" You are Claude Code..."]), undefined, "main prefix matched after leading whitespace"); +}); + +test("claudeSubagentSplit: stable namespace, main untouched", () => { + assert.equal(claudeSubagentSplit(SESSION, subagentHeaders, GENERAL_PURPOSE_SUB_SYSTEM), SUB_SESSION); + assert.equal(claudeSubagentSplit(SESSION, subagentHeaders, GENERAL_PURPOSE_SUB_SYSTEM), SUB_SESSION, "same agent id reuses the split id across turns"); + assert.equal(claudeSubagentSplit(SESSION, sessionHeaders, MAIN_INTERACTIVE_SYSTEM), SESSION); + const other = { ...subagentHeaders, "x-claude-code-agent-id": "a81aa02c77b7bece7" }; + assert.notEqual(claudeSubagentSplit(SESSION, other, EXPLORE_SUB_SYSTEM), SUB_SESSION, "a second subagent gets its own namespace"); + assert.equal(claudeSubagentSplit(SESSION, { "x-claude-code-agent-id": ` ${SUB_AGENT} `, "x-claude-code-parent-agent-id": " p " }, EXPLORE_SUB_SYSTEM), SUB_SESSION, "whitespace is trimmed"); +}); + +test("#970 split: subagent lands on its own session; main identity is stable", async () => { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + const upstream = startMockAnthropicUpstream(0).server; + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + const main1 = await post(sessionHeaders); + assert.equal(main1.status, 200, `main request: ${main1.text}`); + assert.ok(peekSession(SESSION), "main request must create the session keyed by the session header"); + + const sub = await post(subagentHeaders); + assert.equal(sub.status, 200, `subagent request: ${sub.text}`); + const subSession = peekSession(SUB_SESSION); + assert.ok(subSession, "subagent request must create a session keyed by the split id"); + assert.notEqual(subSession, peekSession(SESSION), "subagent and main must be separate session objects (isolated lock chains / compression state)"); + + const main2 = await post(sessionHeaders); + assert.equal(main2.status, 200, `main turn 2: ${main2.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 2, "later main turns accumulate on the MAIN session"); + assert.equal(peekSession(SUB_SESSION)!.stats.requests, 1, "subagent session must not absorb main turns"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#970 no-stall: a subagent is not head-of-line-blocked by the main turn's slow stream", async () => { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + // First upstream connection (= the main request, fired first) is gated + // 1200ms before its first byte. Pre-fix the subagent queued on the main + // session's lock chain and its first byte came AFTER the main's; post-fix + // it streams through its own session immediately. + const upstream = startMockAnthropicUpstream(1200).server; + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + const mainPromise = post(sessionHeaders); + await new Promise((r) => setTimeout(r, 80)); // let the main request take the lock first + const subPromise = post(subagentHeaders); + const [main, sub] = await Promise.all([mainPromise, subPromise]); + assert.equal(main.status, 200, `main: ${main.text}`); + assert.equal(sub.status, 200, `sub: ${sub.text}`); + assert.ok(peekSession(SUB_SESSION), "split session exists"); + assert.ok( + sub.tFirstChunk < main.tFirstChunk - 500, + `subagent first byte (${sub.tFirstChunk.toFixed(0)}ms) must beat the gated main stream (${main.tFirstChunk.toFixed(0)}ms) by a wide margin — it was queued on the main session's lock`, + ); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#970 gate: subagentSplit:false restores the single-session behavior", async () => { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + const upstream = startMockAnthropicUpstream(0).server; + await listen(upstream); + const { proxy, post } = await startHarness(upstream, { subagentSplit: false }); + try { + const main = await post(sessionHeaders); + const sub = await post(subagentHeaders); + assert.equal(main.status, 200, `main: ${main.text}`); + assert.equal(sub.status, 200, `sub: ${sub.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 2, "with the split off, both requests accumulate on one session"); + assert.equal(peekSession(SUB_SESSION), undefined, "with the split off, no split session is minted"); + } finally { + await close(proxy); + await close(upstream); + } +});