Skip to content
Merged
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
2 changes: 1 addition & 1 deletion PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ On **every model request** the plugin sends:
- `x-bili-plugin: <agent-name>` — announces plugin mode for this session.
- `x-bili-plugin-conversation: <conversation-id>` — the agent's real conversation/session id, stable for the whole conversation.
- `x-bili-plugin-context-window: <tokens>` (optional but recommended) — the model's context window as configured inside the agent (e.g. a pinned/overridden `contextWindow`). This becomes the authoritative "native" window for nudge decisions — it outranks the proxy's built-in table and the models.dev registry (most valuable for private relays and MITM mode), while operator tuning (`compress.modelContextLimit`) still outranks it.
- `x-bili-plugin-instructions-mutable: 1` (optional; send only if true) — declares that your conversation ids are **persona-scoped**: one id per persona, and the request's system/instructions text may change mid-conversation without changing the persona (e.g. opencode re-renders AGENTS.md into `instructions` on every edit). With this flag the proxy stops mixing the instructions text into the compression-namespace fingerprint, so instruction drift no longer forks the session into an orphan `|sub:<fp>` namespace that resets all compression state. Without it, drifted instructions still fork — that is the safe default for agents whose ids are not persona-scoped.
- `x-bili-plugin-instructions-mutable: 1` (optional; send only if true) — declares that your conversation ids are **persona-scoped**: one id per persona, and the request's system/instructions text may change mid-conversation without changing the persona (e.g. opencode re-renders AGENTS.md into `instructions` on every edit). The proxy now keys plugin conversation ids verbatim by default (#1106), so this flag is vestigial for current proxies — keep stamping it for compatibility with older proxy versions, which use it to stop mixing the instructions text into the compression-namespace fingerprint.

Effects on the proxy for that session:

Expand Down
13 changes: 6 additions & 7 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,13 +59,12 @@ export const PLUGIN_BYPASS_HEADER = "x-bili-plugin-bypass";
export const PLUGIN_CONTEXT_WINDOW_HEADER = "x-bili-plugin-context-window";
export const PLUGIN_MAX_OUTPUT_HEADER = "x-bili-plugin-max-output";
export const PLUGIN_MODEL_HEADER = "x-bili-plugin-model";
/** #1102: stamped "1" by plugins whose host mints one conversation id per
* persona (opencode: subagents get their own child session ids), so
* mid-conversation instruction drift (AGENTS.md reconcile) must NOT fork the
* compression session via the instructions fingerprint. Honored only together
* with x-bili-plugin + x-bili-plugin-conversation (see
* instructionsFingerprintExempt in src/session-id.ts); hosts whose id
* semantics are unverified never stamp it. */
/** #1102/#1106: stamped "1" by plugins whose host mints one conversation id per
* persona (opencode: subagents get their own child session ids). Since the
* instructions fingerprint became an allowlist (#1106 — exempt is the
* default for every non-codex/non-claude signal), this declaration is
* vestigial: hosts keep stamping it for protocol compatibility with older
* proxies, but current proxies key verbatim regardless. */
export const PLUGIN_INSTRUCTIONS_MUTABLE_HEADER = "x-bili-plugin-instructions-mutable";

export const PLUGIN_PROTOCOL_VERSION = 1;
Expand Down
28 changes: 15 additions & 13 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ import { rewriteGoogleJsonResponse } from "./stream-google.js";
import { rewriteResponsesJsonResponse } from "./stream-responses.js";
import { observeResponsesTerminalState } from "./stream-terminal.js";
import { emitPreflightError, emitStreamError } from "./stream-error.js";
import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, instructionsFingerprintExempt, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js";
import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, instructionsFingerprintApplies, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js";
import { prefixAffinity, type AnonymousAffinity } from "./prefix-affinity.js";
import { maybeAdoptForkBlocks } from "./fork-adoption.js";
import { flushPrefixAffinity, hydratePrefixAffinity, scheduleAffinityPersist } from "./affinity-persist.js";
Expand Down Expand Up @@ -1345,20 +1345,22 @@ async function handle(
// kernel's empty-instructions non-anchoring path is left
// untouched for metadata-less clients).
? codexTurn.value
: instructionsFingerprintExempt(req.headers)
// #1102: verified persona-scoped native conversation ids
// (opencode ses_ headers / plugin declaration) may see
// instruction drift mid-conversation (AGENTS.md reconcile)
// without a persona change — key them verbatim like the
// trusted codexTurn branch above instead of forking an
// orphan |sub:<fp> session. Trust set + why every other
// signal keeps the fingerprint: see
// instructionsFingerprintExempt in src/session-id.ts.
? (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader))
: subagentNamespace(
: instructionsFingerprintApplies(req.headers)
// #1106: the instructions fingerprint is an inverted
// allowlist — it applies ONLY to codex traffic (root
// threads / older builds; subagent threads key by thread-id
// above) and claude-over-Responses (#150/#970 id-sharing
// personas). Everyone else (opencode #1102, grok/mcode,
// plugin lanes, generic x-session-id / body session_id)
// keys verbatim: instructions drift there means the same
// conversation evolved (upgrade / plugin / AGENTS.md),
// not a new persona. See instructionsFingerprintApplies
// in src/session-id.ts.
? subagentNamespace(
responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader),
(parsed as ResponsesRequestBody).instructions,
);
)
: (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader));
// The session ID is the client-provided conversation value VERBATIM —
// no hash, no protocol/credential/upstream dimensions (#286): those
// are all mutable mid-conversation (bearer rotation, relay switching,
Expand Down
69 changes: 38 additions & 31 deletions src/session-id.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { isCodexClient } from "./codex-compact.js";

export type ConversationIdentity = {
value: string;
source: "header" | "body-session" | "metadata-session" | "previous-response" | "prompt-cache-key" | "content-fingerprint" | "generated";
Expand Down Expand Up @@ -73,42 +75,47 @@ export function conversationHeaderSource(headers: Record<string, string | string
return undefined;
}

/** #1102: whether the winning conversation signal is a VERIFIED persona-scoped
* native identifier, in which case the Responses-wire instructions fingerprint
* must be skipped when keying the compression session.
/** #1106/#1102: whether the Responses-wire instructions fingerprint should
* participate in the compression-session key at all. Inverted allowlist: the
* fingerprint is OFF by default and applies ONLY to signals with a verified
* id-sharing persona problem.
*
* subagentNamespace's instructions fingerprint exists to separate PERSONAS that
* share one conversation id (Codex threads reuse the task-level session id,
* #150). For clients whose native conversation id is persona-scoped — one id is
* minted per persona, so an id can never be reused across personas — the same
* id carrying different instructions mid-conversation means "same persona,
* updated system context" (opencode's system-context reconcile after an
* AGENTS.md edit), not a new persona. Fingerprinting there forks an orphan
* |sub:<fp> session and resets all compression state.
* share one conversation id. Exactly two defendants ever needed it:
* - codex (#150): task-level session ids are REUSED across tasks, so
* different task instructions under one id must not merge. Modern codex
* (>=0.147) already isolates subagent threads via x-codex-turn-metadata ->
* thread-id verbatim (server.ts keys those directly, bypassing this
* 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).
*
* Trust set (each verified against the client's own source):
* - x-session-affinity with a ses_… value / x-opencode-session: opencode stamps
* its session id on every model request and mints a fresh child session id
* for every task-tool subagent (sessions.create({ parentID })).
* - x-bili-plugin-conversation + x-bili-plugin-instructions-mutable: 1 — the
* plugin declares its host's conversation ids are persona-scoped. Only the
* opencode plugin stamps the declaration today; unverified hosts (dsh,
* hermes, …) stay on the fingerprinted path.
* Everyone else keys VERBATIM: instructions drift mid-id means "same
* conversation, evolved system context" (software upgrade, plugin install,
* AGENTS.md edit - the relay-station majority case, #1106), and forking there
* resets all compression state for no defending bug. opencode (persona-scoped
* ses_ ids, #1102/#1104), grok/mcode (per-session ids by their own source),
* plugin conversation ids, and generic x-session-id / body session_id all
* stay on the verbatim path now. The x-bili-plugin-instructions-mutable
* declaration (#1104) is vestigial: exempt is the default; hosts keep
* stamping it for protocol compatibility with older proxies.
*
* Everything else deliberately keeps the fingerprint: Codex body/header/metadata
* session ids (#150), x-claude-code-session-id (Claude subagents SHARE the main
* agent's session id, #970), grok/mcode/generic x-session-id, prompt-cache-key.
* A future client that shares one id across personas and separates them ONLY
* by instructions must be added here (same evidence-per-client discipline as
* #1104, inverted).
*/
export function instructionsFingerprintExempt(headers: Record<string, string | string[] | undefined>): boolean {
const src = conversationHeaderSource(headers);
if (!src) return false;
if (src.name === "x-opencode-session") return true;
if (src.name === "x-session-affinity" && src.value.startsWith("ses_")) return true;
if (src.name === "x-bili-plugin-conversation") {
const flag = headers["x-bili-plugin-instructions-mutable"];
return typeof flag === "string" && flag.trim() === "1";
}
return false;
export function instructionsFingerprintApplies(headers: Record<string, string | string[] | undefined>): boolean {
const turnMeta = headers["x-codex-turn-metadata"];
if (typeof turnMeta === "string" && turnMeta.trim().length > 0) return true;
// One definition of "codex traffic" process-wide (every other codex path in
// server.ts uses isCodexClient, #645): case-sensitive by convention. A
// case-insensitive match would pull non-codex relays with "Codex"-shaped
// UAs back into the fingerprint and re-fork them mid-conversation (#1106).
if (isCodexClient(headers)) return true;
return conversationHeaderSource(headers)?.name === "x-claude-code-session-id";
}

/**
Expand Down
Loading
Loading