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
4 changes: 3 additions & 1 deletion PLUGIN.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ Fetch once at plugin startup.
"headers": {
"agent": "x-bili-plugin",
"conversation": "x-bili-plugin-conversation",
"contextWindow": "x-bili-plugin-context-window"
"contextWindow": "x-bili-plugin-context-window",
"instructionsMutable": "x-bili-plugin-instructions-mutable"
},
"toolEndpoint": "/__bili/plugin/tool",
"statusEndpoint": "/__bili/plugin/status"
Expand All @@ -58,6 +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.

Effects on the proxy for that session:

Expand Down
4 changes: 4 additions & 0 deletions src/agent/opencode-native.ts
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,10 @@ export function createV1ServerHooks(origin: string, ctx: V1PluginContext, deps:
}
output.headers["x-bili-plugin"] = "opencode";
output.headers["x-bili-plugin-conversation"] = input.sessionID;
// #1102: opencode mints one session id per persona (task-tool
// subagents get fresh child ids), so instruction drift (AGENTS.md
// reconcile) must not fork the compression session.
output.headers["x-bili-plugin-instructions-mutable"] = "1";
const model = input.model;
if (model && typeof model.providerID === "string" && typeof model.id === "string") {
const key = `${model.providerID}/${model.id}`;
Expand Down
4 changes: 4 additions & 0 deletions src/agent/opencode-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,10 @@ export function createOpencodeV2Setup(options: OpencodeV2SetupOptions = {}): (ct
if (!headers || typeof headers.set !== "function" || !sid || !state.proxyBase) return;
headers.set("x-bili-plugin-conversation", sid);
headers.set("x-bili-plugin", "opencode");
// #1102: one session id per persona (subagents get child ids) —
// instruction drift (AGENTS.md reconcile) must not fork the
// compression session.
headers.set("x-bili-plugin-instructions-mutable", "1");
const model = e.model;
if (model && typeof model.providerID === "string" && typeof model.id === "string") {
const key = `${model.providerID}/${model.id}`;
Expand Down
10 changes: 9 additions & 1 deletion src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,14 @@ 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. */
export const PLUGIN_INSTRUCTIONS_MUTABLE_HEADER = "x-bili-plugin-instructions-mutable";

export const PLUGIN_PROTOCOL_VERSION = 1;

Expand Down Expand Up @@ -532,7 +540,7 @@ export function handlePluginManifest(res: import("node:http").ServerResponse): v
openai: withSearchContextConversationDescription([...BILI_ACP_TOOLS_OPENAI, ABSORB_TOOL_OPENAI, RULE_TOOL_OPENAI].map(withConversationIdParam)),
responses: withSearchContextConversationDescription([...BILI_ACP_TOOLS_RESPONSES, ABSORB_TOOL_RESPONSES, RULE_TOOL_RESPONSES].map(withConversationIdParam)),
},
headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER, maxOutput: PLUGIN_MAX_OUTPUT_HEADER, model: PLUGIN_MODEL_HEADER },
headers: { agent: PLUGIN_AGENT_HEADER, conversation: PLUGIN_CONVERSATION_HEADER, contextWindow: PLUGIN_CONTEXT_WINDOW_HEADER, maxOutput: PLUGIN_MAX_OUTPUT_HEADER, model: PLUGIN_MODEL_HEADER, instructionsMutable: PLUGIN_INSTRUCTIONS_MUTABLE_HEADER },
toolEndpoint: "/__bili/plugin/tool",
statusEndpoint: "/__bili/plugin/status",
runtimeInfoEndpoint: "/__bili/plugin/runtime-info",
Expand Down
20 changes: 15 additions & 5 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, preferPromptCacheKeyIdentity, type ConversationIdentity } from "./session-id.js";
import { affinityToken, claudeSubagentAgentId, claudeSubagentSplit, clientConversationHeader, codexTurnIdentity, instructionsFingerprintExempt, 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,10 +1345,20 @@ async function handle(
// kernel's empty-instructions non-anchoring path is left
// untouched for metadata-less clients).
? codexTurn.value
: subagentNamespace(
responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader),
(parsed as ResponsesRequestBody).instructions,
);
: 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(
responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader),
(parsed as ResponsesRequestBody).instructions,
);
// 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
47 changes: 46 additions & 1 deletion src/session-id.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,13 @@ export type ConversationIdentity = {

/** Pull a client-provided conversation signal from headers, if any. */
export function clientConversationHeader(headers: Record<string, string | string[] | undefined>): string | undefined {
return conversationHeaderSource(headers)?.value;
}

/** Same header walk as clientConversationHeader, but also reports WHICH header
* won — needed by callers whose trust decision depends on the signal's origin
* (#1102), not just its value. */
export function conversationHeaderSource(headers: Record<string, string | string[] | undefined>): { name: string; value: string } | undefined {
// x-bili-plugin-conversation first: a cooperative plugin's explicit
// statement of which conversation it is driving (see src/plugin.ts).
// It outranks every other signal — the plugin owns the session identity
Expand Down Expand Up @@ -61,11 +68,49 @@ export function clientConversationHeader(headers: Record<string, string | string
for (const name of names) {
if (name === "x-bili-plugin-conversation" && !pluginMarker) continue;
const v = headers[name];
if (typeof v === "string" && v.trim().length > 0) return v.trim();
if (typeof v === "string" && v.trim().length > 0) return { name, value: v.trim() };
}
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.
*
* 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.
*
* 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.
*
* 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.
*/
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;
}

/**
* Return only an identity the client already supplied. Generated identities
* remain proxy-internal so billion-context does not invent upstream headers.
Expand Down
Loading
Loading