diff --git a/CONFIGURATION.md b/CONFIGURATION.md index a9de25ce50..a2b12795ad 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -102,7 +102,7 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `rollout.features.base` | string | unset (roll out over everyone) | — | Nested rollout: evaluate this feature only inside the named feature's enabled cohort, so the percent is relative to that population (roll B out to A's users; chains allowed, cycles fail closed). | | `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | Mask non-public target hosts in logs as ; credential headers are always masked regardless. | | `security.adminRelay` | boolean | false | — | Let an embedding host (dsh web today) relay the ENTIRE /__bili/ admin surface through its own entry origin so a remote browser can open the panel (#3373). Fail-closed, file-only. The relayed hop reaches the proxy as a local non-browser client (loopback source + loopback Host, no Origin), so the admin gate stays unchanged; enabling it exposes config editing and credential writes to whoever can reach the host web entry — protect that entry (auth / reverse proxy) first. | -| `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude Code subagents get their own session namespace (\|sub:) instead of queueing behind the main session. | +| `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude Code subagents get their own session namespace instead of queueing behind the main session: header-carrying ones key by agent id (\|sub:); header-less ones (VS Code build) route through the continuity-aware order resolver (#970/#4352). | | `forkAdoption` | boolean | false | BILI_FORK_ADOPTION | Anonymous forks inherit the parent's compression blocks whose source content is fully present in the forked request. | | `autoModeForge.enabled` | boolean | true | BILI_AUTO_MODE_FORGE | Answer Claude Code auto-mode safety-classifier calls locally with a forged allow verdict instead of forwarding them upstream (#2740): zero egress, zero billing for that lane; every forged verdict is audit-logged and the session carries a notice badge. false / env 0 restores pure passthrough for users who pay for real verdicts. | | `affinitySimhash` | boolean | true | BILI_AFFINITY_SIMHASH | Simhash chain-alignment adoption for anonymous clients (#2265): a client-side pervasive decorative rewrite (e.g. Trae re-stamping model tags on every assistant message) re-attaches the existing session with its compression state instead of minting fresh and re-folding from zero. | @@ -729,7 +729,7 @@ Top-level keys that control how the proxy listens and behaves globally. - **Type:** `boolean` - **Default:** `true` - **Status:** ACTIVE -- **Description:** Claude Code background-subagent session splitting (#970): anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair get their own `\|sub:` session — own lock chain and compression state — instead of queueing behind the main session's lock. Disabled by `BILI_SUBAGENT_SPLIT=0`. +- **Description:** Claude Code background-subagent session splitting (#970): anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair get their own `\|sub:` session — own lock chain and compression state — instead of queueing behind the main session's lock. A second, header-less path (#4352) covers claude code builds that stamp no agent-id headers (VS Code extension subagents): their traffic routes through the continuity-aware order resolver (#2944), so a history-disjoint ride on the parent id forks onto its own `\|sub:` lane while a continuing main conversation keeps the raw key on order+content evidence. Disabled by `BILI_SUBAGENT_SPLIT=0`. ### `forkAdoption` @@ -1905,7 +1905,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes | `ACP_DUMP_SSE` | Directory to dump raw SSE frames for debugging — including loop-originated upstream responses (compress re-requests and truncation retries, named `--loop-raw.sse`), which the outer forward tee cannot see (#1455). | | `BILI_STREAM_ERROR_SHAPE` | Set `"completion"` to restore the legacy failure shape on the anthropic/openai wire (failure text inside a synthesized successful completion); default `"protocol"` = protocol-native error frames (#1455). Same knob as `compat.streamErrorShape`; this env var wins. | | `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_SUBAGENT_SPLIT` | Set `0` to turn OFF Claude Code subagent session splitting (#970/#4352): 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; header-less claude code traffic (VS Code build subagents) routes through the continuity-aware order resolver, forking a history-disjoint ride onto its own `\|sub:` lane while continuing main conversations keep the raw key. Default is ON. `"subagentSplit": false` in the config file does the same; the env var wins. | | `BILI_FORK_ADOPTION` | Set `1` to turn ON fork block-adoption (#629): when an anonymous (prefix-affinity) client forks its history mid-conversation (edit-and-resend / regenerate an earlier turn), the new session inherits the parent's compression blocks whose source content is fully present in the forked request — instead of restarting with zero compression state and re-folding the shared prefix from scratch. Default is OFF. Identified resume-forks are NOT governed by this switch — they adopt blocks together with `BILI_RESUME_INHERITANCE` (#1834). `"forkAdoption": true` in the config file does the same; the env var wins. The adoptable inventory is logged on every anonymous fork even while disabled, so you can size the win before flipping it on. | | `BILI_AFFINITY_SIMHASH` | Set `0` to turn OFF simhash chain-alignment adoption (#2265): anonymous requests whose exact hash chain was broken by a client-side pervasive decorative rewrite (e.g. Trae re-stamping model tags on every assistant message) re-attach the existing session with its compression state instead of minting fresh and re-folding from zero. Guards: ≥90% coverage within Hamming 10, ≥20% mutated-but-similar positions (point edits still fork, #629), ≥1 byte-identical user message, unique candidate only. Default ON. `"affinitySimhash": false` in the config file does the same; the env var wins. | | `BILI_RESUME_INHERITANCE` | Set `0` to turn OFF resume inheritance (ON by default) (#1486): when an identified client (sends its own session id, e.g. Claude Code's `x-claude-code-session-id`) resumes a conversation under a NEW session id while replaying the full transcript (`cc --resume` forks a fresh UUID), bili matches the incoming history byte-exactly against that client's tracked chains (≥8 messages, append-only tracking) and, on the resumed session's first request, inherits the parent's ref assignments — stale model citations then resolve to their ORIGINAL messages instead of mis-hitting renumbered ones — adopts the fully-present compression blocks (together with this inheritance, #1834: losing them on resume meant the folded originals came back on the wire and the upstream request ballooned; the old `forkAdoption` co-gate now applies only to anonymous forks, #629), and records the `derivedFrom` lineage. The parent is never modified and fresh messages number above the parent's ref space. A resume must strictly EXTEND the parent's history — an equal-depth byte-exact replay under another id is a duplicate, not a resume. Anonymous sessions are unaffected (they keep their own pfa-* world, #309). `"resumeInheritance": false` in the config file does the same; the env var wins. | diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 9f295fed8f..b169b97b85 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -102,7 +102,7 @@ | `rollout.features.base` | string | unset (roll out over everyone) | — | 嵌套灰度:仅在所指特性的已入组人群内评估本特性,percent 相对该人群(B 只放量给 A 的用户;允许链式,环路判为关)。 | | `maskHosts` | boolean | true | BILI_LOG_MASK_HOSTS | 日志中把非公开目标主机遮成 ;凭据头无论此开关如何总是遮盖。 | | `security.adminRelay` | boolean | false | — | 允许宿主(当前为 dsh web)把它自己入口域名下的整个 /__bili/ 管理面中继到本机代理,使远程浏览器能打开面板(#3373)。默认关闭、仅配置文件。中继跳到达代理时是本机非浏览器客户端(回环源地址 + 回环 Host、无 Origin 头),管理端门槛不变;开启后,凡能访问宿主 web 入口的人都能改配置、写凭据——请先给入口加鉴权/反代。 | -| `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude 子代理拥有独立会话命名空间(\|sub:),不再排队在主会话锁后。 | +| `subagentSplit` | boolean | true | BILI_SUBAGENT_SPLIT | Claude 子代理拥有独立会话命名空间,不再排队在主会话锁后:带 agent-id 头的按 \|sub: 键控;无头的(VS Code 构建)走连续性感知顺序解析器分流(#970/#4352)。 | | `forkAdoption` | boolean | false | BILI_FORK_ADOPTION | 匿名 fork 会话继承父会话中源内容完整存在于本次请求里的压缩块。 | | `autoModeForge.enabled` | boolean | true | BILI_AUTO_MODE_FORGE | Claude Code auto mode 安全分类器请求由 bili 在本地代答放行判定,不再转发上游(#2740):该旁路零流出、零计费;每条代答写审计日志,会话带提示徽标。false / env 0 恢复纯透传(愿意付费要真判定的用户)。 | | `affinitySimhash` | boolean | true | BILI_AFFINITY_SIMHASH | 匿名客户端的 simhash 链对齐收养(#2265):客户端侧大面积装饰性改写(如 Trae 切模型后给每条 assistant 消息重打模型标签)时,重新挂回既有会话并保留压缩状态,而不是每次新铸会话、从零重折。 | @@ -729,7 +729,7 @@ - **类型:** `boolean` - **默认值:** `true` - **状态:** ACTIVE -- **说明:** Claude Code 后台子代理会话拆分(#970):携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 对的 anthropic-wire 请求获得自己的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 而不是排在主会话锁后面。`BILI_SUBAGENT_SPLIT=0` 关闭。 +- **说明:** Claude Code 后台子代理会话拆分(#970):携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 对的 anthropic-wire 请求获得自己的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 而不是排在主会话锁后面。第二条无头路径(#4352)覆盖不打 agent-id 头的 claude code 构建(VS Code 扩展子代理):其流量经连续性感知顺序解析器(#2944)路由,历史不连续的骑乘会分叉到自己的 `\|sub:` 车道,而延续中的主会话凭顺序+内容证据保留原始键。`BILI_SUBAGENT_SPLIT=0` 关闭。 ### `forkAdoption` @@ -1900,7 +1900,7 @@ ACP 原生 agent(当前为 `pi` 扩展)会在每个进程内向代理上报 | `ACP_DUMP_SSE` | 调试用:转储原始 SSE 帧的目录——含压缩重发/截断重试的循环内上游响应(命名 `--loop-raw.sse`),外层 tee 看不到(#1455)。 | | `BILI_STREAM_ERROR_SHAPE` | 设为 `"completion"` 恢复 anthropic/openai 线上旧的失败形状(失败文本包在合成的成功完成里);默认 `"protocol"` = 协议原生错误帧(#1455)。与 `compat.streamErrorShape` 同一开关,此环境变量优先。 | | `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_SUBAGENT_SPLIT` | 设为 `0` 关闭 Claude Code subagent 会话分流(#970/#4352):默认情况下,anthropic 线路上同时携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 头的请求(后台 subagent)会获得独立的 `\|sub:` 会话 —— 独立的锁链与压缩状态 —— 不再排在主会话的锁后面;无 agent-id 头的 claude code 流量(VS Code 构建子代理)经连续性感知顺序解析器分流,历史不连续的骑乘分叉到独立的 `\|sub:` 车道,延续中的主会话保留原始键。默认开启。配置文件中设 `"subagentSplit": false` 效果相同;环境变量优先。 | | `BILI_FORK_ADOPTION` | 设为 `1` 开启 fork 块继承(#629):匿名(prefix-affinity)客户端在会话中途分叉历史(编辑重发 / 从更早轮次重新生成)时,新会话直接继承父会话中"源内容在分叉请求里完整存在"的压缩块 —— 而不是从零开始、把共享前缀重新折叠一遍。默认关闭。带自有 id 的 resume-fork 不受此开关管 —— 它们随 `BILI_RESUME_INHERITANCE` 一并继承压缩块(#1834)。配置文件中设 `"forkAdoption": true` 效果相同;环境变量优先。无论开关如何,匿名 fork 发生时日志都会记录可继承的块清单,便于先评估收益再开启。 | | `BILI_AFFINITY_SIMHASH` | 设为 `0` 关闭 simhash 链对齐收养(#2265):匿名请求的精确哈希链被客户端侧大面积装饰性改写(如 Trae 切模型后给每条 assistant 消息重打模型标签)打断时,重新挂回既有会话并保留压缩状态,而不是每次新铸会话、从零重折。护栏:覆盖率 ≥90%(Hamming ≤10)、变异位置 ≥20%(单点编辑仍走 fork,#629)、至少一条字节相同的用户消息、双候选歧义拒猜。默认开启。配置文件中设 `"affinitySimhash": false` 效果相同;环境变量优先。 | | `BILI_RESUME_INHERITANCE` | 设为 `0` 关闭 resume 继承(默认开启)(#1486):当带自有会话 id 的客户端(如 Claude Code 的 `x-claude-code-session-id`)以**新**会话 id 重放完整历史来续接会话时(`cc --resume` 会 fork 出新 UUID),bili 通过字节级前缀匹配(≥8 条消息、append-only 跟踪)识别出它与该客户端已跟踪历史的父子关系,并在续接会话的首个请求上继承父会话的 ref 分配 —— 模型引用的旧代际 refs 因此命中**原始**消息、而不是错配到重新编号的新消息 —— 同时继承源内容完整存在的压缩块(随本继承一并生效,#1834:resume 丢块会导致被折叠原文重新回到线上、上游请求膨胀;旧的 `forkAdoption` 联动门现仅作用于匿名 fork,#629),并记录 `derivedFrom` 血缘。父会话不受影响;新消息在父会话 ref 空间之上继续编号。resume 必须**严格扩展**父历史 —— 同深度的字节级重放(不同 id)视为重复会话而非 resume。匿名会话不受影响(保留自己的 pfa-* 世界,#309)。配置文件中设 `"resumeInheritance": false` 效果相同;环境变量优先。 | diff --git a/src/config.ts b/src/config.ts index b338b0955c..22368022b2 100644 --- a/src/config.ts +++ b/src/config.ts @@ -863,10 +863,14 @@ 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). */ + /** Split Claude Code subagent requests into their own session id so they + * don't queue on the main session's lock (#970, default on). Two + * mechanisms, both gated by this switch: the agent-id header pair split, + * and header-less claude code traffic (VS Code build subagents, #4352) + * routed through the continuity-aware order resolver so a history- + * disjoint ride forks onto its own |sub lane while continuing main + * conversations keep the raw key. Opt out with env BILI_SUBAGENT_SPLIT=0 + * or `subagentSplit: false` in the config file (env wins). */ subagentSplit?: boolean; /** Opt-in fork block-adoption (#629, default off). ANONYMOUS clients * (prefix-affinity) that fork their history inherit the parent's diff --git a/src/host-profiles.ts b/src/host-profiles.ts index 9312b83593..c5e2d9ee99 100644 --- a/src/host-profiles.ts +++ b/src/host-profiles.ts @@ -58,6 +58,16 @@ export interface HostProfile { * share the main session id there). #3482 site 4. */ readonly instructionsFingerprintKeyed: boolean; + /** + * Declared: this client shares one conversation id across personas + * (main agent + subagents), so its ANTHROPIC-wire traffic rides the + * continuity-aware order resolver (personaConversationOrder) for persona + * separation (#4352): a continuing main conversation keeps the raw key on + * order+content evidence, a history-disjoint subagent ride forks onto its + * own |sub: lane. Anthropic wire only — the responses wire expresses + * the same intent via instructionsFingerprintKeyed (#970/#2250). + */ + readonly personaOrderKeyed: boolean; /** * Declared: this host compacts histories CLIENT-SIDE and resends the * compacted form (dsh native compaction, #2432) — the four prepares run @@ -68,7 +78,7 @@ export interface HostProfile { } const PROFILES: Record = { - dsh: { identity: "dsh", toolsHostScopedByDefault: true, wantsBillingBlock: true, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: true }, + dsh: { identity: "dsh", toolsHostScopedByDefault: true, wantsBillingBlock: true, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: true }, // #4344: zcode reaches the ACP tools ONLY through its MCP bridge // (mcp__bili__* names), and bridge delivery is environmental — zcode's // agent modes gate MCP tools, and the degraded shim path serves an EMPTY @@ -79,16 +89,16 @@ const PROFILES: Record = { // and the surface goes silent instead of advertising a tool the model // cannot call (the #4344 shape: nudges armed at 21-29% usage, 0 // compressions — #3177's "unknown tool" discipline, applied to zcode). - zcode: { identity: "zcode", toolsHostScopedByDefault: true, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }, - pi: { identity: "pi", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }, - omp: { identity: "omp", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: true, coworkTransportPossible: true, instructionsFingerprintKeyed: false, compactsClientSide: false }, - opencode: { identity: "opencode", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }, + zcode: { identity: "zcode", toolsHostScopedByDefault: true, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, + pi: { identity: "pi", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, + omp: { identity: "omp", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: true, coworkTransportPossible: true, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, + opencode: { identity: "opencode", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }, }; /** No declared defaults at all — unknown agents and header-less proxy-lane * clients resolve here (lane-decisions re-identifies them by name or wire * signals). Exported because the wire-client table spreads it. */ -export const ANONYMOUS: HostProfile = { identity: "", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, compactsClientSide: false }; +export const ANONYMOUS: HostProfile = { identity: "", toolsHostScopedByDefault: false, wantsBillingBlock: false, stampsBodyPromptCacheKey: false, coworkTransportPossible: false, instructionsFingerprintKeyed: false, personaOrderKeyed: false, compactsClientSide: false }; /** Resolve the declared profile for a plugin agent header value. Trimmed * exact match — the historical shape of every pluginAgent comparison. diff --git a/src/server/handle.ts b/src/server/handle.ts index a1d5f4bcb6..900415557b 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -32,7 +32,7 @@ import { enterSessionContext, log as loggerLog } from "../logger.js"; import { codexCompactGatePre, codexCompactMode, hasCompactionTrigger, isCodexHost, replaceBiliCompactionItems } from "../codex-compact.js"; import { emitPreflightError } from "../stream-error.js"; import { agentProviderRecipes } from "../agent-providers.js"; -import { affinityToken, conversationHeaderSource, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity } from "../session-id.js"; +import { affinityToken, claudeAnthropicPersonaOrderApplies, conversationHeaderSource, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, dshPersonaFingerprintApplies, instructionsFingerprintApplies, openaiSystemTextForPersona, preferPromptCacheKeyIdentity } from "../session-id.js"; import { personaConversationOrder } from "../session-resolve.js"; import { prefixAffinity, type AnonymousAffinity } from "../prefix-affinity.js"; import { buildAnonymousProvenance, type AnonymousProvenance } from "../anon-provenance.js"; @@ -1033,13 +1033,27 @@ async function handleRequest( // empty-tag traffic through the order resolver // (codex turn-1 shape keys by its session header). ? (anthropicIdentity?.value ?? anthropicSignal) - : personaConversationOrder( - anthropicIdentity?.value ?? anthropicSignal, - (parsed as AnthropicRequestBody).messages, - personaSystemText, - pluginReportedModel(req.headers), - )) - : anthropicIdentity?.value ?? anthropicSignal) + : personaConversationOrder( + anthropicIdentity?.value ?? anthropicSignal, + (parsed as AnthropicRequestBody).messages, + personaSystemText, + pluginReportedModel(req.headers), + )) + : claudeAnthropicPersonaOrderApplies(req.headers) && opts.subagentSplit !== false + && !sideRequestLike && personaSystemText !== "" + // #4352: header-less claude code subagents (VS Code + // build) ride the raw parent id; route them through the + // continuity-aware order resolver so a history-disjoint + // ride forks onto its own |sub: lane while a + // continuing main conversation keeps the raw key on + // order+content evidence (#2944). + ? personaConversationOrder( + anthropicIdentity?.value ?? anthropicSignal, + (parsed as AnthropicRequestBody).messages, + personaSystemText, + pluginReportedModel(req.headers), + ) + : anthropicIdentity?.value ?? anthropicSignal) : protocol === "openai" ? (dshPersona && !sideRequestLike && personaSystemText !== "" ? personaConversationOrder( diff --git a/src/server/lane-decisions.ts b/src/server/lane-decisions.ts index 1c480ad193..9964645955 100644 --- a/src/server/lane-decisions.ts +++ b/src/server/lane-decisions.ts @@ -114,10 +114,12 @@ const WIRE_CLIENTS: readonly WireClientEntry[] = [ matches: (s) => !s.headerNames.has("x-bili-plugin") && (s.headerNames.has("x-codex-turn-metadata") || s.codexUserAgent), }, { - // claude over Responses (#970): subagents SHARE the main agent's - // session id (the anthropic path splits them via claudeSubagentSplit; - // a claude client on the Responses wire only has this fingerprint). - profile: { ...ANONYMOUS, identity: "claude-responses", instructionsFingerprintKeyed: true }, + // claude code (#970/#4352): subagents SHARE the main agent's session + // id on every wire. The responses wire separates them via the + // instructions fingerprint (instructionsFingerprintKeyed); the + // anthropic wire via the order resolver (personaOrderKeyed) when the + // two-signal header gate (claudeSubagentAgentId) misses. + profile: { ...ANONYMOUS, identity: "claude-responses", instructionsFingerprintKeyed: true, personaOrderKeyed: true }, matches: (s) => s.conversationSourceName === "x-claude-code-session-id", }, ]; diff --git a/src/session-id.ts b/src/session-id.ts index 66e214e955..f691eafabf 100644 --- a/src/session-id.ts +++ b/src/session-id.ts @@ -102,9 +102,11 @@ export function conversationHeaderSource(headers: Record): boolean { - // Detection only — the client-identity DECISION (who keys by - // instructions) lives in the lane-decisions wire-client registry - // (#3482 site 4): the header-name literals are registry data, not - // scattered comparisons. Signals are name-free observations here. +/** Name-free wire observations for the lane-decisions client registry + * (#3482): present header names, the resolved conversation-source header, + * and the codex user-agent fact. Shared by every predicate below so the + * signal extraction stays single-sourced. */ +function wireClientSignals(headers: Record): { headerNames: Set; conversationSourceName: string | undefined; codexUserAgent: boolean } { const headerNames = new Set(); for (const [name, value] of Object.entries(headers ?? {})) { const first = Array.isArray(value) ? value[0] : value; if (typeof first === "string" && first.trim().length > 0) headerNames.add(name); } - return resolveWireClientProfile({ + return { headerNames, conversationSourceName: conversationHeaderSource(headers)?.name, codexUserAgent: isCodexClient(headers), - }).instructionsFingerprintKeyed; + }; +} + +export function instructionsFingerprintApplies(headers: Record): boolean { + // Detection only — the client-identity DECISION (who keys by + // instructions) lives in the lane-decisions wire-client registry + // (#3482 site 4): the header-name literals are registry data, not + // scattered comparisons. Signals are name-free observations here. + return resolveWireClientProfile(wireClientSignals(headers)).instructionsFingerprintKeyed; +} + +/** #4352: whether THIS request's claude-code-over-Anthropic traffic should + * ride the continuity-aware order resolver (personaConversationOrder) for + * persona separation when the #970 two-signal header gate + * (claudeSubagentAgentId) misses. + * + * Evidence (v0.1.204 field report, #4352): Claude Code stamps ONE session id + * on every model request of a session INCLUDING Task-tool subagents, and the + * VS Code extension build's subagent requests carry no agent-id headers at + * all — so claudeSubagentAgentId misses and those subagents ride the raw + * parent id, where their disjoint short histories accumulate fold-reconcile + * drop events until epoch confirmation fires substrate-destruction and the + * parent's refs go permanently DEAD (compress rejected for the rest of the + * session). Routing such traffic through the order resolver separates exactly + * those disjoint rides onto |sub: lanes while a continuing main + * conversation keeps the raw key on order+content evidence (#2944) — the same + * mechanism the dsh lane uses (#1916). + * + * Detection only — the client-identity DECISION lives in the lane-decisions + * wire-client registry (#3482 site 4), same shape as + * instructionsFingerprintApplies above. */ +export function claudeAnthropicPersonaOrderApplies(headers: Record): boolean { + return resolveWireClientProfile(wireClientSignals(headers)).personaOrderKeyed; } /** #1916/#1307/#1314: whether the persona fingerprint (session id + system diff --git a/tests/issue4352-claude-anthropic-subagent-split.test.ts b/tests/issue4352-claude-anthropic-subagent-split.test.ts new file mode 100644 index 0000000000..4e28808a1a --- /dev/null +++ b/tests/issue4352-claude-anthropic-subagent-split.test.ts @@ -0,0 +1,339 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { createHash, randomUUID } from "node:crypto"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _resetSessionsForTest, _sessionsSizeForTest, peekSession } from "../src/session.ts"; +import { claudeAnthropicPersonaOrderApplies } from "../src/session-id.ts"; +import { resetSessionOrderForTest, resolveSessionOrder } from "../src/session-resolve.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { _setForTest as setRegistryForTest } from "../src/registry.ts"; + +// #4352: claude code builds that stamp NO agent-id headers (VS Code extension +// subagents) ride the parent session id. Their traffic must fork onto its own +// |sub lane instead of destroying the parent's fold substrate. + +// Every test mints its OWN session id: the order-resolver skeleton state is +// persisted per raw id (#3397) and re-hydrated on each server boot, so a fixed +// id shared across tests would let one test's system-drift anchor migration +// (#2241) leak into the next test's resolution. + +// System-block shapes captured from live Claude Code traffic (same corpus as +// tests/claude-subagent-split.test.ts). +const MAIN_SYSTEM = ["You are Claude Code, Anthropic's official CLI for Claude. You are an interactive agent..."]; +const SUB_AGENT_SYSTEM = ["x-anthropic-billing-header: cc_version=...", "You are a Claude agent, built on Anthropic's...", "You are a file search specialist for..."]; +const OTHER_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 tag = (blocks: string[]): string => blocks.join("\n\n"); +const forkKey = (conv: string, systemText: string): string => + `${conv}|sub:${createHash("sha256").update(systemText, "utf8").digest("hex").slice(0, 16)}`; + +type Msg = { role: string; content: string }; +/** n alternating user/assistant turns with distinct per-prefix content. */ +function history(prefix: string, turns: number): Msg[] { + const out: Msg[] = []; + for (let i = 1; i <= turns; i++) { + out.push({ role: "user", content: `${prefix}-user-${i}` }); + out.push({ role: "assistant", content: `${prefix}-assistant-${i}` }); + } + return out; +} + +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", {}) + ); +} + +function startMockUpstream(): http.Server { + const server = http.createServer((_req, res) => { + res.writeHead(200, { "content-type": "text/event-stream", "cache-control": "no-cache" }); + res.write(anthropicStream()); + res.end(); + }); + server.listen(0, "127.0.0.1"); + return server; +} + +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()))); +} + +async function startHarness(upstream: http.Server, over: Partial = {}): Promise<{ proxy: http.Server; post: (headers: Record, body?: Record) => Promise<{ status: number; text: string }> }> { + 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, + compat: { roles: {} }, + streamErrorShape: "protocol", + passthroughSource: null, + autoRestartOnUpdate: false, + updateTag: "latest", + advisoryCheck: false, + releaseNotesCheck: 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 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); + const text = await res.text(); + return { status: res.status, text }; + }; + return { proxy, post }; +} + +function freshState(): void { + _setStoreForTest(new SessionStore({ enabled: false })); + setRegistryForTest({}); + _resetSessionsForTest(); + resetSessionOrderForTest(); +} + +const ccHeadersFor = (id: string) => ({ "x-claude-code-session-id": id }); +const sysBlocks = (system: string[]) => system.map((t) => ({ type: "text", text: t })); +const mainBody = (hist: Msg[], system: string[] = MAIN_SYSTEM): Record => + ({ model: "claude-test", stream: true, max_tokens: 1024, system: sysBlocks(system), messages: hist }); + +test("claudeAnthropicPersonaOrderApplies: allowlist is the claude-code conversation source only", () => { + const id = randomUUID(); + assert.equal(claudeAnthropicPersonaOrderApplies({ "x-claude-code-session-id": id }), true); + assert.equal(claudeAnthropicPersonaOrderApplies({ "x-acp-session": id }), false, "plain anthropic clients keep verbatim identity (#1106)"); + assert.equal(claudeAnthropicPersonaOrderApplies({ "x-bili-plugin": "dsh", "x-bili-plugin-conversation": id }), false, "dsh keeps its own persona mechanism (#1916)"); + assert.equal(claudeAnthropicPersonaOrderApplies({}), false); +}); + +test("#4352 resolver rows: disjoint ride forks; continuing main and compaction keep the raw key", () => { + const SESSION = randomUUID(); + const MAIN_TAG = tag(MAIN_SYSTEM); + const SUB_TAG = tag(SUB_AGENT_SYSTEM); + const OTHER_TAG = tag(OTHER_SUB_SYSTEM); + + resetSessionOrderForTest(); + const claim = resolveSessionOrder(SESSION, history("main", 4), MAIN_TAG); + assert.equal(claim.key, SESSION, "first sight claims the raw id"); + assert.equal(claim.action, "claim"); + + const ride = resolveSessionOrder(SESSION, history("sub", 2), SUB_TAG); + assert.equal(ride.key, forkKey(SESSION, SUB_TAG), "history-disjoint ride under a different system forks onto its own lane"); + assert.equal(ride.action, "derived-persona"); + + const ride2 = resolveSessionOrder(SESSION, history("sub", 3), SUB_TAG); + assert.equal(ride2.key, forkKey(SESSION, SUB_TAG), "successive passes of the same persona stay on ONE lane (ref continuity)"); + + const other = resolveSessionOrder(SESSION, history("other", 2), OTHER_TAG); + assert.notEqual(other.key, ride.key, "a different subagent system gets its own lane"); + + const drifted = resolveSessionOrder(SESSION, history("main", 5), MAIN_TAG + "\n[additional context loaded]"); + assert.equal(drifted.key, SESSION, "byte-drifted system on a verbatim-continuing history keeps the raw key (#1106)"); + assert.equal(drifted.action, "reanchor"); + + resetSessionOrderForTest(); + resolveSessionOrder(SESSION, history("main", 4), MAIN_TAG); + // Native /compact shape: the head collapses into a summary, the living tail + // stays verbatim, same system — must stay on the raw key. + const compacted = [ + { role: "user", content: "" }, + ...history("main", 4).slice(-4), + ]; + const compactRes = resolveSessionOrder(SESSION, compacted, MAIN_TAG); + assert.equal(compactRes.key, SESSION, "head-rewritten /compact replay keeps the raw key"); +}); + +test("#4352 field shape: VS Code build shares the parent's first system block; the fork still fires", () => { + // Live transcripts from Claude Code VS Code extension 2.1.307 (issue + // comment): the parent and ALL subagents send the SAME first system block + // verbatim — only the second block differs. The #975 main-prefix heuristic + // therefore cannot separate these subagents (their first block starts with + // "You are Claude Code"); separation must come from order+tag alone. + const SESSION = randomUUID(); + const SHARED = "You are Claude Code, Anthropic's official CLI for Claude, running within the Claude Agent SDK."; + const PARENT_TAG = [SHARED, "You are an interactive agent... (parent-specific second block)"].join("\n\n"); + const SUB_TAG = [SHARED, "You are an agent for Claude Code, ... (subagent second block)"].join("\n\n"); + + resetSessionOrderForTest(); + resolveSessionOrder(SESSION, history("main", 4), PARENT_TAG); + const ride = resolveSessionOrder(SESSION, history("sub", 2), SUB_TAG); + assert.equal(ride.key, forkKey(SESSION, SUB_TAG), "a shared first system block does not block the fork (order+tag decide)"); + assert.equal(ride.action, "derived-persona"); + const back = resolveSessionOrder(SESSION, history("main", 5), PARENT_TAG); + assert.equal(back.key, SESSION, "the parent returns to the raw key after the subagent burst"); +}); + +test("#4352 split: header-less subagent rides its own lane; the parent session is untouched", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + for (let t = 1; t <= 3; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + const parentBefore = peekSession(SESSION); + assert.ok(parentBefore, "parent session exists"); + assert.equal(parentBefore.stats.requests, 3); + + const sub1 = await post(ccHeaders, mainBody(history("sub", 2), SUB_AGENT_SYSTEM)); + assert.equal(sub1.status, 200, `subagent pass 1: ${sub1.text}`); + const subKey = forkKey(SESSION, tag(SUB_AGENT_SYSTEM)); + const subSession = peekSession(subKey); + assert.ok(subSession, "header-less subagent must fork onto its own |sub: lane"); + assert.notEqual(subSession, parentBefore, "forked lane is a separate session object (own lock chain / compression state)"); + assert.equal(peekSession(SESSION), parentBefore, "parent session object is the same instance"); + assert.equal(parentBefore.stats.requests, 3, "subagent turns must not accumulate on the parent"); + + const sub2 = await post(ccHeaders, mainBody(history("sub", 3), SUB_AGENT_SYSTEM)); + assert.equal(sub2.status, 200, `subagent pass 2: ${sub2.text}`); + assert.equal(peekSession(subKey)!.stats.requests, 2, "successive passes share ONE forked session"); + assert.equal(parentBefore.stats.requests, 3, "parent still untouched after pass 2"); + + const main4 = await post(ccHeaders, mainBody(history("main", 4))); + assert.equal(main4.status, 200, `parent turn 4: ${main4.text}`); + assert.equal(parentBefore.stats.requests, 4, "the parent continues accumulating on the raw key after the burst"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 negative: a main turn with a byte-drifted system keeps the raw key (#1106)", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + for (let t = 1; t <= 3; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + const drifted = [...MAIN_SYSTEM, "[additional context loaded]"]; + const r = await post(ccHeaders, mainBody(history("main", 4), drifted)); + assert.equal(r.status, 200, `drifted-system continuation: ${r.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 4, "continuation must stay on the raw key"); + assert.equal(peekSession(forkKey(SESSION, tag(drifted))), undefined, "no |sub lane is minted for a continuing conversation"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 negative: non-claude anthropic clients stay verbatim (#1106)", async () => { + freshState(); + const OTHER_SESSION = randomUUID(); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + const headers = { "x-acp-session": OTHER_SESSION }; + // Two disjoint main-shaped conversations under the same id must behave + // EXACTLY as before the fix: verbatim identity, one session. + for (let t = 1; t <= 2; t++) { + const r = await post(headers, mainBody(history("alpha", t))); + assert.equal(r.status, 200, `alpha turn ${t}: ${r.text}`); + } + for (let t = 1; t <= 2; t++) { + const r = await post(headers, mainBody(history("beta", t), OTHER_SUB_SYSTEM)); + assert.equal(r.status, 200, `beta turn ${t}: ${r.text}`); + } + assert.equal(peekSession(OTHER_SESSION)!.stats.requests, 4, "all four requests accumulate on the one verbatim session"); + assert.equal(peekSession(forkKey(OTHER_SESSION, tag(OTHER_SUB_SYSTEM))), undefined, "no fork lane is minted for non-claude clients"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 opt-out: subagentSplit:false disables the header-less fallback too", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream, { subagentSplit: false }); + try { + for (let t = 1; t <= 3; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + const sub = await post(ccHeaders, mainBody(history("sub", 2), SUB_AGENT_SYSTEM)); + assert.equal(sub.status, 200, `subagent with split off: ${sub.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 4, "with the split off, the subagent rides the raw key (pre-fix behavior)"); + assert.equal(peekSession(forkKey(SESSION, tag(SUB_AGENT_SYSTEM))), undefined, "with the split off, no fork lane is minted"); + } finally { + await close(proxy); + await close(upstream); + } +}); + +test("#4352 exemptions: side calls and empty-system requests stay verbatim", async () => { + freshState(); + const SESSION = randomUUID(); + const ccHeaders = ccHeadersFor(SESSION); + const upstream = startMockUpstream(); + await listen(upstream); + const { proxy, post } = await startHarness(upstream); + try { + for (let t = 1; t <= 2; t++) { + const r = await post(ccHeaders, mainBody(history("main", t))); + assert.equal(r.status, 200, `parent turn ${t}: ${r.text}`); + } + // Tool-less request with a small output budget = the #388 side-request + // shape: it rides the main session key verbatim by contract. Side calls + // never increment stats.requests (the passthrough lane skips the + // counter), so only the two parent turns + the empty-system request + // count here. + const side = await post(ccHeaders, { model: "claude-test", stream: true, max_tokens: 100, system: sysBlocks(MAIN_SYSTEM), messages: [{ role: "user", content: "summarize in one word" }] }); + assert.equal(side.status, 200, `side call: ${side.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 2, "side call rides the raw key but does not bump the request counter"); + // Empty system is non-anchoring (kernel anchor semantics): verbatim. + const bare = await post(ccHeaders, { model: "claude-test", stream: true, max_tokens: 1024, messages: history("sub", 2) }); + assert.equal(bare.status, 200, `empty-system request: ${bare.text}`); + assert.equal(peekSession(SESSION)!.stats.requests, 3, "both exempt shapes land on the raw key; side calls are uncounted"); + assert.equal(_sessionsSizeForTest(), 1, "no fork lane is minted for exempt shapes"); + } finally { + await close(proxy); + await close(upstream); + } +});