Skip to content
Closed
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
3 changes: 3 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ The full file-by-file map lives in [reference/architecture.md](reference/archite
9. **Hosts that reuse ONE session id across personas get id + system-hash session keys ("hash 不一样自动分裂")** — when a plugin host stamps the SAME conversation id on every model request of a session INCLUDING auxiliary personas (dsh auto-review `classifyRisk()`: fixed REVIEW_POLICY system + a fresh flattened blob before every tool call — #1916/#1307/#1314), those auxiliary requests must be keyed by `subagentNamespace(id, systemText)` so the persona forks onto its own `<id>|sub:<fp>` session instead of overwriting the main session's baseline/snapshots. The FIRST system seen under the id keeps the raw key (kernel anchor), so main turns never fork; an empty system is non-anchoring (verbatim); SIDE REQUESTS never claim the anchor either — dsh's title-gen sidecar fires at session start before/concurrent with the first main turn, and claiming it would fork the whole main conversation onto `|sub:<fp>` while every host-stamped ACP management call (compress/decompress/acp_status) routes into the ghost's empty session and fails forever (#2156/#2160; the `sideRequestLike` gate in `src/server.ts` mirrors the #388 passthrough predicate). This is an EVIDENCE-PERMITLIST (`dshPersonaFingerprintApplies` in `src/session-id.ts`), the same discipline as the instructions fingerprint (#1104/#1107): do NOT enable it wholesale — for everyone else system drift mid-id means "same conversation, evolved", and forking resets compression for no defending bug (#1106). A future host found reusing session ids across personas gets added to that predicate WITH traffic evidence (shape + stability proof: the host's main system must be session-stable, e.g. dsh composes it once per session and puts volatile time-context in a USER message). The fork must record itself under its suffixed id (`personaForked` → `recordPluginSession`) so the single-valued conversations map keeps the raw key owned by the main session (#970 discipline). Tests: `tests/dsh-persona-fingerprint.test.ts`.

10. **Thinking-family blocks are signature-verified — NEVER rewrite them (#1960)** — Anthropic `thinking`/`redacted_thinking` blocks and Gemini `thoughtSignature` parts are verified byte-for-byte when the latest assistant message is replayed ("thinking blocks ... cannot be modified"). The bytes the proxy forwards become the client's persisted history, and the bytes the loop accumulates become the re-request rebuild — BOTH must stay verbatim. Any transformation (tag/marker stripping, dedup, trimming, re-laying-out block order, dropping empty segments) desynchronizes text from signature and bricks the session: first on the in-turn re-request, then on every subsequent request via the client's echo. #1882 put a prose filter on the thinking channel and it was exactly this bug. Treat ANY future change touching thinking-family payloads as high-risk: it needs loop-level byte-equality tests (re-request body AND client-visible stream) on both signed wires, not just adapter-level ones. The prose filters (#206/#1881) are for the TEXT channel only.
11. **工具提示词是环境配置,不参与会话身份 (tool prompts are ambient config, ignored by session identity — owner rule, 2026-10-12, #2917)** — the dsh host renders the plugin manifest's tool descriptions INTO the main system message, so the persona fingerprint would otherwise key on strings bili itself controls: an upgrade that rewords a tool description (kernel 540f44028, compress 55473→55496 chars — #2917: restart race claimed the raw key with the OLD prompt, the NEW prompt forked `|sub:<fp>` with zero folds and a 14MB unfold died in preflight) or a user installing a plugin mid-session (new tool lines) would BOTH fork the main lane off its compression state. Rule: `neutralizeToolPrompts` (src/persona-anchor.ts) drops every system line containing a request-declared tool description BEFORE fingerprinting, anchor storage, and #2601 model-drift line-diff — tool-prompt churn is invisible to session identity by construction. Line granularity (not substring) so the tool-name remnant disappears too; wrapped/reformatted renders fail the containment and stay conservative; a system that empties out entirely passes through un-anchored. A REAL persona edit (AGENTS.md) still forks — tool prompts must be ignored, not the whole system. Tests: `tests/issue2917-tool-prompt-neutralization.test.ts`.

12. **顺序+自铸 id 即可认领会话,hash 只是护栏 (order+id claim, hash as guard — owner rule, 2026-10-12, #2944)** — the session-identity layer must not key on representation: #2847/#2821/#2917 were all "content representation churn → ghost fork (`|sub:<fp>` with zero folds) → giant unfold → doomed 502". Rule ①: a client-minted, UNAMBIGUOUS conversation id plus an intact ORDER SKELETON (per-position message-kind sequence: role + tool shape, content-blind) claims the same session — 绝对没有错误, even if 50% of mid-conversation content changed. Rule ②: shallow traffic (no assistant turns — dsh auto-review blob) NEVER claims the raw key; it is always derived (`|sub:aux`), which kills the #1916 restart race without reading a byte of system text. Rule ③: head truncation (native compaction) keeps the raw key and re-anchors (tail window aligns or the id is simply trusted); a deep main-shaped history sharing nothing with the recorded skeleton parks at `|sub:task` — the only hash-shaped guard rails, and they are SHAPE rails, not content rails. System text is not read anywhere in the claim decision. Implementation lives in `src/session-resolve.ts` ALONGSIDE `src/persona-anchor.ts` (the old fp ladder) — the old file is NOT deleted and the server switch-over happens only after the differential corpus in `tests/issue2944-session-resolve.test.ts` (same inputs through both implementations; behavior-compatible rows share one expectation, designed divergences old→new documented per row) stays green. 压缩锚点默认顺序位置,hash 只是参考 — the lower layer rides #2939 (order-centric reconcile) — verify its merge state before the switch-over.

### Install-Lane & Update-Ownership Contract (#1196)

Expand Down
4 changes: 3 additions & 1 deletion reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,8 @@ billion-context/
│ ├── registry-snapshot.json # Bundled full models.dev snapshot (offline floor)
│ ├── session.ts # Session model + in-memory store (bounded, MAX_SESSIONS)
│ ├── session-id.ts # Session identity: client value verbatim + persona fork fingerprint
│ ├── persona-anchor.ts # Persona fp ladder (old identity layer, retiring per #2944) + tool-prompt neutralization (#2917)
│ ├── session-resolve.ts # Order+id session resolution (new identity layer, #2944; alongside until switch-over)
│ ├── session-gc.ts # Session-file GC, opt-in (sessions.gc.* / BILI_SESSION_GC*) (#1082)
│ ├── persist.ts # On-disk session persistence (kernel StateStore)
│ ├── persist-eperm.ts # EPERM/EACCES write-failure alert layer (#362)
Expand Down Expand Up @@ -204,7 +206,7 @@ When navigating this codebase, these are the load-bearing entry points:
- **Knobs** — every behavior knob resolves through `src/knobs.ts` (env > config file > default, #2030). Never add a new `process.env` read in a leaf module — see AGENTS.md "Environment Variable Discipline".
- **Update path** — `src/update.ts` is deliberately self-contained and conservative; it installs via tarball extraction (not `npm install`) to avoid lifecycle-script surprises on user machines. It is load-bearing infrastructure: changes require a no-op validation release first (§5).
- **Agent plugins** — `src/agent/*.ts` are thin host-specific adapters; shared logic lives in `src/agent/shared.ts`. Each host has a `-native.ts` bootstrap gate variant.
- **Persistence** — `src/persist.ts` wraps the acp-kernel `StateStore`; `src/session.ts` holds the in-memory session pool. Session identity rules: `src/session-id.ts`.
- **Persistence** — `src/persist.ts` wraps the acp-kernel `StateStore`; `src/session.ts` holds the in-memory session pool. Session identity rules: `src/session-id.ts`; persona-fp ladder `src/persona-anchor.ts` and its order+id successor `src/session-resolve.ts` (#2944, switch-over pending).
- **会话派生缓存** — `Session.transient` 持有插件工具视图与诊断请求副本;随会话淘汰释放,也纳入会话对象图的字节计量。它不写入持久化记录或上游协议;诊断截段独立复制 UTF-16 内容,避免保留完整请求底层字符串(#2920)。
- **Wire fidelity** — `src/stream-*.ts` files handle per-protocol streaming transformation. The invariant: never alter upstream protocol shape beyond intended injection (§7.3).
- **E2E regression** — `tests/e2e/` contains real-client suites (codex, opencode, pi, dsh) plus hermetic lanes (registry, advisory-rollback, release-canary, opencode WS, image billing); each carries its own skip gate — read the test header for the exact env var.
Expand Down
58 changes: 52 additions & 6 deletions src/persona-anchor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,44 @@ import { prefixAffinity } from "./prefix-affinity.js";

const anchors = new Map<string, { fp: string; system: string; model?: string }>();

/** #2917: request-declared tool descriptions — anthropic
* {name,description}, openai chat {type:"function",function:{description}},
* Responses {type:"function",name,description}. Short strings (<16
* chars) are skipped: removing a tiny fragment is noise, not signal. */
function toolDescriptions(tools: unknown): string[] {
if (!Array.isArray(tools)) return [];
const out: string[] = [];
for (const t of tools) {
if (t === null || typeof t !== "object") continue;
const o = t as Record<string, unknown>;
const fn = o.function as Record<string, unknown> | undefined;
const desc =
typeof o.description === "string" ? o.description : typeof fn?.description === "string" ? fn.description : undefined;
if (desc !== undefined && desc.trim().length >= 16) out.push(desc);
}
return out;
}

/** #2917: tool prompts are ambient configuration, not conversation
* identity. bili's own upgrades rewrite tool descriptions (kernel 540f44028
* reworded the compress tool mid-#2917-session, 55473→55496 chars) and
* plugin installs add tools mid-session; neither event may fork the main
* lane off the raw key. Every line of the system text that contains a
* request-declared tool description is DROPPED before fingerprinting and
* anchor storage — the dsh host renders the manifest's description strings
* into whole system lines ("- compress: <description>"), so line-granular
* removal also erases the tool-name remnant a pure substring cut would
* leave behind (a plugin install would otherwise show up as an extra
* remnant line and drift the fingerprint). A wrapped or reformatted render
* spans lines and simply fails to match — conservative, the fragment stays
* in the hash. */
export function neutralizeToolPrompts(systemText: string, tools: unknown): string {
const descs = toolDescriptions(tools);
if (descs.length === 0) return systemText;
const kept = systemText.split("\n").filter((line) => !descs.some((d) => line.includes(d)));
return kept.join("\n");
}

function personaFingerprint(systemText: string): string {
return createHash("sha256").update(systemText, "utf8").digest("hex").slice(0, 16);
}
Expand Down Expand Up @@ -110,12 +148,19 @@ export function resolvePersonaKey(
systemText: string,
messages: unknown[],
model?: string,
tools?: unknown,
): PersonaKeyResolution {
if (!systemText) return { key: rawId, action: "passthrough" };
const fp = personaFingerprint(systemText);
// #2917: strip the request's own tool descriptions before any identity
// comparison — anchor, fp, and modelDriftAbsorbed all see the neutralized
// text, so a tool-description rewrite (upgrade) or a new tool (plugin
// install) cannot change the fingerprint.
const text = neutralizeToolPrompts(systemText, tools);
if (!text.trim()) return { key: rawId, action: "passthrough" };
const fp = personaFingerprint(text);
const anchored = anchors.get(rawId);
if (anchored === undefined) {
anchors.set(rawId, { fp, system: systemText, model });
anchors.set(rawId, { fp, system: text, model });
return { key: rawId, action: "claim" };
}
if (anchored.fp === fp) {
Expand All @@ -131,11 +176,11 @@ export function resolvePersonaKey(
return { key: rawId, action: "match" };
}
if (prefixAffinity.chainContinues(messages, rawId)) {
anchors.set(rawId, { fp, system: systemText, model });
anchors.set(rawId, { fp, system: text, model });
return { key: rawId, action: "migrate" };
}
if (modelDriftAbsorbed(anchored, systemText, model)) {
anchors.set(rawId, { fp, system: systemText, model });
if (modelDriftAbsorbed(anchored, text, model)) {
anchors.set(rawId, { fp, system: text, model });
return { key: rawId, action: "migrate-model" };
}
return { key: `${rawId}|sub:${fp}`, action: "fork" };
Expand All @@ -157,10 +202,11 @@ export function personaNamespace(
messages: unknown,
log: (level: "info" | "warn" | "error", message: string) => void,
model?: string,
tools?: unknown,
): string {
const list = Array.isArray(messages) ? messages : [];
const text = typeof systemText === "string" && systemText.trim().length > 0 ? systemText : "";
const res = resolvePersonaKey(rawId, text, list, model);
const res = resolvePersonaKey(rawId, text, list, model, tools);
if (res.action === "migrate") {
log("info", `[persona] persona text changed mid-conversation but the history continues ${rawId}'s chain — anchor migrated, compression state stays on the raw key (#2241/#2250)`);
} else if (res.action === "migrate-model") {
Expand Down
4 changes: 4 additions & 0 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,7 @@ async function handleRequest(
(parsed as AnthropicRequestBody).messages,
log,
pluginReportedModel(req.headers),
(parsed as AnthropicRequestBody).tools,
)
: anthropicIdentity?.value ?? anthropicSignal)
: protocol === "openai"
Expand All @@ -832,6 +833,7 @@ async function handleRequest(
(parsed as OpenAIRequestBody).messages,
log,
pluginReportedModel(req.headers),
(parsed as OpenAIRequestBody).tools,
)
: openaiIdentity?.value ?? openaiSignal)
: codexTurn
Expand All @@ -854,6 +856,7 @@ async function handleRequest(
(parsed as ResponsesRequestBody).input,
log,
pluginReportedModel(req.headers),
(parsed as ResponsesRequestBody).tools,
)
: opts.stableSystemAnchor && pluginAgentHeader(req.headers) === undefined
// #1085: with anchoring on (plain-proxy mode only — see the
Expand Down Expand Up @@ -891,6 +894,7 @@ async function handleRequest(
(parsed as ResponsesRequestBody).input,
log,
pluginReportedModel(req.headers),
(parsed as ResponsesRequestBody).tools,
)
: (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader)))
: (responsesIdentity?.value ?? conversationSignalResponses(parsed as ResponsesRequestBody, convHeader));
Expand Down
Loading
Loading