Skip to content
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,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 `<session>\|sub:<agent-id>` 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 subagent session splitting (#970/#4352), two mechanisms both gated by this switch. (1) anthropic-wire requests carrying the `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` pair get their own `<session>\|sub:<agent-id>` session — own lock chain and compression state — instead of queueing behind the main session's lock. (2) Header-less claude code traffic (the VS Code extension build, whose subagents carry no agent-id headers and share the parent's first system block, so the pair gate misses — #4352) is routed through the continuity-aware order resolver: a continuing main conversation keeps the raw key on order+content evidence, while a history-disjoint subagent ride forks onto its own `<session>\|sub:<fp>` lane so it stops destroying the parent's fold substrate. Set `BILI_SUBAGENT_SPLIT=0` to disable BOTH mechanisms.

### `forkAdoption`

Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -767,7 +767,7 @@
- **类型:** `boolean`
- **默认值:** `true`
- **状态:** ACTIVE
- **说明:** Claude Code 后台子代理会话拆分(#970):携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 对的 anthropic-wire 请求获得自己的 `<session>\|sub:<agent-id>` 会话 —— 独立的锁链与压缩状态 —— 而不是排在主会话锁后面。`BILI_SUBAGENT_SPLIT=0` 关闭。
- **说明:** Claude Code subagent 会话拆分(#970/#4352),两套机制都由本开关控制。(1) 携带 `x-claude-code-agent-id` + `x-claude-code-parent-agent-id` 对的 anthropic-wire 请求获得自己的 `<session>\|sub:<agent-id>` 会话 —— 独立的锁链与压缩状态 —— 而不是排在主会话锁后面。(2) 无头 claude code 流量(VS Code 扩展构建:其 subagent 不带 agent-id 头、且与父会话逐字共享第一个 system block,因此双信号门必然不命中,#4352)改走顺序优先会话解析器 —— 历史连续的主会话按顺序+内容证据留在原 key,历史不相交的 subagent 借道则分叉到自己的 `<session>\|sub:<fp>` 车道,不再摧毁父会话的折叠基底。设 `BILI_SUBAGENT_SPLIT=0` 同时关闭两套机制。

### `forkAdoption`

Expand Down
12 changes: 8 additions & 4 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -878,10 +878,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
Expand Down
22 changes: 16 additions & 6 deletions src/host-profiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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:<fp> 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
Expand All @@ -68,7 +78,7 @@ export interface HostProfile {
}

const PROFILES: Record<string, HostProfile> = {
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
Expand All @@ -79,16 +89,16 @@ const PROFILES: Record<string, HostProfile> = {
// 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.
Expand Down
34 changes: 24 additions & 10 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,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, describeResumeMiss, type AnonymousAffinity } from "../prefix-affinity.js";
import { buildAnonymousProvenance, type AnonymousProvenance } from "../anon-provenance.js";
Expand Down Expand Up @@ -1087,15 +1087,29 @@ async function handleRequest(
// semantics): ride the verbatim id — never route
// 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)
: protocol === "openai"
? (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:<fp> 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(
openaiIdentity?.value ?? openaiSignal,
Expand Down
10 changes: 6 additions & 4 deletions src/server/lane-decisions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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",
},
];
Expand Down
54 changes: 44 additions & 10 deletions src/session-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,11 @@ export function conversationHeaderSource(headers: Record<string, string | string
* predicate); the fingerprint still matters for root threads and older
* codex builds, detected by the turn-metadata header or the user agent
* (same convention as isCodexClient, #645).
* - 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).
* - claude code (#970/#4352): subagents SHARE the main agent's session id
* on every wire (the anthropic path also separates them via the order
* resolver when its two-signal header gate misses — see
* claudeAnthropicPersonaOrderApplies below; the responses wire relies on
* this fingerprint alone).
*
* Everyone else keys VERBATIM: instructions drift mid-id means "same
* conversation, evolved system context" (software upgrade, plugin install,
Expand All @@ -120,21 +122,53 @@ export function conversationHeaderSource(headers: Record<string, string | string
* by instructions must be added here (same evidence-per-client discipline as
* #1104, inverted).
*/
export function instructionsFingerprintApplies(headers: Record<string, string | string[] | undefined>): 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<string, string | string[] | undefined>): { headerNames: Set<string>; conversationSourceName: string | undefined; codexUserAgent: boolean } {
const headerNames = new Set<string>();
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<string, string | string[] | undefined>): 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:<fp> 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<string, string | string[] | undefined>): boolean {
return resolveWireClientProfile(wireClientSignals(headers)).personaOrderKeyed;
}

/** #1916/#1307/#1314: whether the persona fingerprint (session id + system
Expand Down
Loading
Loading