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
6 changes: 3 additions & 3 deletions docs/msgid-infrastructure.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Message-ID lane infrastructure: the sessionid+msgid production/consumption map

> Status: companion doc for the gap fix mandated by the #5826 release review (owner ruling 2026-11-07). Identity-ladder doctrine lives in message-identity.md (kernel) and session-identity.md (session side); this file does ONE job — explain where sessionid+msgid, the cross-lane public substrate, is produced, how it travels, who validates it (six copies), where it is pinned, its five consumers, and its declared trust boundaries. Read this before touching any of it.
> Status: companion doc for the gap fix mandated by the #5826 release review (owner ruling 2026-11-07). Identity-ladder doctrine lives in message-identity.md (kernel) and session-identity.md (session side); this file does ONE job — explain where sessionid+msgid, the cross-lane public substrate, is produced, how it travels, who validates it (six copies), where it is pinned, its six consumers, and its declared trust boundaries. Read this before touching any of it.

## 1. What it is

Expand All @@ -21,7 +21,7 @@ Discipline: collectors only "obtain and pre-screen"; they hold NO identity-adjud

Four carriers, **ALL stripped before forwarding to the model upstream** — the model wire still carries no message-level ids (#2821 doctrine):

1. **Envelope field** `biliMsgIds`: parallel array on full-resend model bodies, length-locked to messages, same lifecycle (stripped at ingress, src/server/prepare-anthropic.ts et al.).
1. **Envelope field** `biliMsgIds`: parallel array on full-resend model bodies, length-locked to the **post-hoist core count** (not the wire element count) — clients prove core-alignment via the kernel's own #3642 `wireIndex` back-pointer before stamping (src/agent/pi-msgids.ts `coreAlignEnvelopeIds`; every non-leading wire element must own exactly one core; any unprovable shape bails the whole request to content-derived ids — never guessed, never partial, request ships byte-identical). Wired: dsh full-resend (src/agent/dsh-native.ts `resolveEnvelopeMsgIds`, openai + anthropic wire, #6525) and pi + omp full-resend (src/agent/pi.ts `stampMsgIdEnvelope`, reuse the same already-validated walker output), the latter gated by `destinationRoutedThroughProxy` — a blind tunnel never gets stamped (#1403). Same lifecycle (stripped at ingress, src/server/prepare-anthropic.ts et al.).
2. **Incremental turn payload** `msgIds`: envelope on `POST /__bili/plugin/turn` (src/agent/incremental-client.ts); server re-stamps `biliMsgIds` (src/incremental-lane.ts).
3. **Watermark headers** `x-bili-pf-tail-ids` (v2-v4, #5403/#5418): window segment only = last anchor element + all elements added since K, percent-encoded per segment, comma-separated (commas inside ids travel as `%2C`, separators stay literal); sibling `x-bili-pf-count` count stamp. pf-* headers are **protocol headers, not hop headers**: stripped before upstream via `UPSTREAM_HOP_HEADERS`.
4. **Ledger-seq sibling** `biliLedgerSeqs` / `ledgerSeq` stamps (#4316 L3 PR2/3): 1-based positive-int parallel arrays, validated by `validateMsgSeqs`, same strict-validate-then-degrade lifecycle.
Expand All @@ -48,7 +48,7 @@ One-off closure from the review: `parseTailIds` alone lacked the reserved-prefix

The unified-store `messages.msg_id` column is the ONLY id truth: ingestion pins validated ids into rows (T5 ruling: no parallel ledger; skeleton rows carry no ids). Ledger primary key `(session_id, msg_id, content_hash)`; canonical rows key on **MSGID, not content hash** (#4491); fork clones preserve numbers (#4316 L3 PR3/3 `cloneSessionRows`).

## 6. Consumers (five; what question each one asks of the ids)
## 6. Consumers (six; what question each one asks of the ids)

| Consumer | Location | Question answered | Id-usage boundary |
|---|---|---|---|
Expand Down
10 changes: 7 additions & 3 deletions docs/plugin-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,15 +193,19 @@ Discover `capabilities.fork` from the manifest; do not infer support from the pa
"parentRevision": "<snapshot.parentRevision>",
"branchPoint": { "messageCount": 1, "orderHash": "<prefix order hash>" },
"orderedMessages": [{ "rawId": "h_example", "ref": "m00001", "identityHash": "<snapshot identity>" }],
"idempotencyKey": "stable-operation-id"
"idempotencyKey": "stable-operation-id",
"prefixMsgIds": ["host-uuid-1", "host-uuid-2"],
"driftFrom": 1
}
```

`prefixMsgIds` and `driftFrom` are optional (#6262). On a parent whose kernel ids are the host's own stable message ids (a pinned session, where snapshot `rawId` IS the host id), a client may additionally present the host id of every matched prefix message, plus the hash-run length as `driftFrom` (`0 ≤ driftFrom < prefixMsgIds.length`). The server accepts a byte-drifted prefix only when every presented id equals the parent's `rawId` — ids prove prefix identity where bytes no longer match — and marks the receipt `status: "drifted"` (or `"expanded+drifted"` when a block also crosses the branch) with the verified `driftFrom` echoed. A gate failure never fails the fork: the request falls back to the strict byte-verified fork (`"exact"`/`"expanded"`) and the extra fields are ignored. Malformed shapes (wrong length, bad identifier, `driftFrom` out of range or without `prefixMsgIds`) return `400 INVALID_REQUEST`. Parents without host-pinned ids make the track a no-op, byte path unchanged.

`protocolVersion` is `2` (current) or `1` (legacy) in both directions; the proxy accepts either (`acceptsProtocolVersions` in the manifest advertises this) and rejects anything newer with `400 INVALID_REQUEST`. Under protocol 2 the `parentRevision` token covers exactly the session id, the ordered-prefix length (`messageCount`), and the active block set — so routine stats churn (context estimates, usage bookkeeping) no longer changes the revision, while any structural change (messages appended or rewritten, a block folded or unfolded) still does. Protocol-1 clients that present the legacy whole-store revision token are still matched during the transition window; treat `parentRevision` as opaque in both cases: on `409 PARENT_REVISION_CONFLICT` take a fresh snapshot and re-match, regardless of which protocol version you speak.

The branch is an ordered prefix, including an empty prefix. Compute its existing order hash as lowercase SHA-256 of UTF-8 `JSON.stringify(orderedMessages)` with each identity object's keys in order `rawId`, `ref`, `identityHash`; for a full prefix reuse snapshot `orderHash`. Do not hash descriptors or folded text. Extra child messages, including a final model reply that has not left the proxy yet, may be appended on the child's first model request after copying the matched prefix.

New success is `201`; exact payload replay is `200` with `replayed: true`, even after restart or later parent changes. Both return `status`, `parentRevision`, `childRevision`, `sessionId`, `branchPoint`, `inheritedBlocks`, and `expandedBlocks`. Reusing the child id with another parent, key or payload returns `409 CHILD_CONFLICT`. Invalid shapes/version/identifiers return `400 INVALID_REQUEST`; absent parent returns `404 PARENT_NOT_FOUND`; stale parent returns `409 PARENT_REVISION_CONFLICT`; altered order/raw/ref/identity returns `409 BRANCH_POINT_CONFLICT`. Missing nested originals return `409 PARENT_STATE_INCOMPLETE` with `status: unavailable`. Publication/persistence failure returns `503 FORK_FAILED` with `status: unavailable` and exposes no child; the same request may be retried.
New success is `201`; exact payload replay is `200` with `replayed: true`, even after restart or later parent changes. Both return `status`, `parentRevision`, `childRevision`, `sessionId`, `branchPoint`, `inheritedBlocks`, and `expandedBlocks` (plus `driftFrom` when the msgid track accepted a drift, above). Reusing the child id with another parent, key or payload returns `409 CHILD_CONFLICT`. Invalid shapes/version/identifiers return `400 INVALID_REQUEST`; absent parent returns `404 PARENT_NOT_FOUND`; stale parent returns `409 PARENT_REVISION_CONFLICT`; altered order/raw/ref/identity returns `409 BRANCH_POINT_CONFLICT`. Missing nested originals return `409 PARENT_STATE_INCOMPLETE` with `status: unavailable`. Publication/persistence failure returns `503 FORK_FAILED` with `status: unavailable` and exposes no child; the same request may be retried.

Boundary handling is `exact` when complete blocks fit inside the prefix, `expanded` when a block crosses it (crossing summaries are omitted, affected nested descendants are expanded, matched originals are retained), and `unavailable` when safe reconstruction is impossible. Blocks, nested caches, raw messages, issued ref namespace, token snapshots, rules and prefix CCR payloads are independent copies. Note that the child inherits the parent's ENTIRE issued-ref namespace (dead refs included): refs are never reused, so forks keep allocating fresh refs without colliding with ids a sibling may still hold. The child never reads its parent's later state as a fallback. Registration and first-request resume heuristics do not replace its copied state. With existing persistence enabled, raw snapshots, receipts, nested originals and the child's CCR payloads survive restart; with persistence disabled, durability is not promised. Atomic child publication/idempotency covers concurrent requests to one proxy process; concurrent writers sharing one state directory across processes are not supported by this protocol.

Expand All @@ -213,7 +217,7 @@ Marker divert (#3248 phase 2 — native extensions): instead of switching the pr

中文增量要点(#3248):`POST /__bili/plugin/turn`,首次/恢复用 `sinceSeq:0` 全量(种子隐含 `resync:true`,永不 409);此后每轮只发新增(含上一轮 assistant 回复,客户端自持)。响应即上游原文,`x-bili-applied-seq` 为应用后的长度,下一轮作 `sinceSeq` 回传。409 必须按 serverSeq 对齐或全量重同步;503 表示未开 storage.unified。会话身份沿用客户端自己的 conversation id——增量与全量重发同一会话可任意切换,折叠/工具/状态栏不变。阶段 2(标记分流):普通模型请求上盖 `x-bili-plugin-turn: 1` 头 + 增量形状 body(顶层 conversationId/sinceSeq/messages、无顶层 model)即可,增量形状 turn 属 lane 流量,与直连 turn 端点同信任级(#3343):非回环/隧道/不可信源一律 403(其探针本就 403,正常宿主不会远程发增量);管理前缀(`/__bili/`、`/__acp/`)永不走分流。lane 按原始 URL 转发;探针 `GET /__bili/plugin/turn`;开关 rollout `pluginIncrementalTurns`(默认 0%=零变化,`BILI_ROLLOUT_PLUGIN_INCREMENTAL_TURNS=1` 或配置强制开)。客户端状态机在 src/agent/incremental-client.ts,新宿主复用勿重写。已接宿主:pi/pi-native(同一扩展工厂,后者零代码继承)、dsh-native(fetch 补丁 beforeSend/headersFor/onResponse)、opencode(http.request 钩子 incremental 适配回调换 body+盖章)、omp(无头事件通道,读 body 里 prompt_cache_key 当会话 id,直接在 init 上盖章);OpenAI 工具形状(tool_calls/role:tool)自动回退全量重发;每 URL 单飞行+30s 过期。

中文集成要点:fork 协议现为 2(服务端同时接受 1);先读取 manifest 能力及 snapshot,按原文、role、工具身份确认匹配前缀,仅提交该前缀的 orderedMessages,不猜测多模态分支点。被 `compress.protectedTools` 硬排除的消息在两个数组中均为 `"ref": null`(参与顺序与身份、无地址 ref),与其他前缀条目一样逐字提交;ref 合法值仅 `mNNNNN` 字符串或 `null`。父 revision 变化必须重新取快照并重新匹配。子会话使用独立稳定 id,首次请求可追加尚未出站的模型回复,不能重置继承的 refs/blocks。手动摘要使用 snapshot 的 refs 和 `expectedRevision: snapshot.parentRevision` 调用公开 tool;摘要期间历史发生变化时返回 409,不执行旧摘要。状态栏读取 `contextTokens`、`contextTokensSource`、`contextTokensAt`、`model`、`contextLimit`、`contextGeneration`、`sessionId` 与 `sessionRevision`,不得用累计账单 input/cache 冒充有效上下文。手动 compress/decompress 后为独立时间及 generation 的 estimate,不改累计账单或 last-usage 基线;下一次正数 usage 才恢复 usage,零值或缺失 usage 不得复活旧观测。未知来源返回 unavailable,tokens/time/generation 为 null。
中文集成要点:fork 协议现为 2(服务端同时接受 1);先读取 manifest 能力及 snapshot,按原文、role、工具身份确认匹配前缀,仅提交该前缀的 orderedMessages,不猜测多模态分支点。父会话若已 pin 宿主 msgid(snapshot 的 rawId 即宿主 id),可另附 `prefixMsgIds`(每个前缀消息的宿主 id)与 `driftFrom`(哈希前缀长度):宿主 id 全等时服务端接受字节已漂移的前缀,回执 `status: "drifted"`(跨块时 `"expanded+drifted"`)并回显已验证的 `driftFrom`;gate 失败不影响 fork 成功(回退严格字节 fork,附加字段被忽略);字段形状非法返回 400,未 pin 的父会话该轨自动无效。被 `compress.protectedTools` 硬排除的消息在两个数组中均为 `"ref": null`(参与顺序与身份、无地址 ref),与其他前缀条目一样逐字提交;ref 合法值仅 `mNNNNN` 字符串或 `null`。父 revision 变化必须重新取快照并重新匹配。子会话使用独立稳定 id,首次请求可追加尚未出站的模型回复,不能重置继承的 refs/blocks。手动摘要使用 snapshot 的 refs 和 `expectedRevision: snapshot.parentRevision` 调用公开 tool;摘要期间历史发生变化时返回 409,不执行旧摘要。状态栏读取 `contextTokens`、`contextTokensSource`、`contextTokensAt`、`model`、`contextLimit`、`contextGeneration`、`sessionId` 与 `sessionRevision`,不得用累计账单 input/cache 冒充有效上下文。手动 compress/decompress 后为独立时间及 generation 的 estimate,不改累计账单或 last-usage 基线;下一次正数 usage 才恢复 usage,零值或缺失 usage 不得复活旧观测。未知来源返回 unavailable,tokens/time/generation 为 null。

### Incremental cache-mark updates

Expand Down
6 changes: 3 additions & 3 deletions reference/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,14 +228,14 @@ billion-context/
│ │ ├── conversation-recall.ts # Fallback identity when host attribution context is missing (#4082)
│ │ ├── dsh-compaction-disable.ts # Load-time overlay standing dsh basic compaction down (#3354)
│ │ ├── dsh-compaction-gate.ts # Always-on compaction gate entry, independent of bili-native (#3662)
│ │ ├── fork-adopt.ts # Client half of fork adoption: prefix match + receipt (#2399)
│ │ ├── fork-adopt.ts # Client half of fork adoption: prefix match + receipt (#2399, msgid track #6262)
│ │ ├── host-log.ts # Host-safe log channel: durable record, zero terminal traffic (#2827)
│ │ ├── incremental-client.ts # Host-process incremental-turn client: diff, ack, resync (#3248)
│ │ ├── opencode-msgids.ts # Opencode msgid harvest + wire alignment (#4491)
│ │ ├── opencode-v2-msgids.ts # Opencode V2 per-turn msgid extraction + header stamp (#5825)
│ │ ├── pf-channel.ts # Watermark channel client state machine: learn, capture, emit (#5403)
│ │ ├── pi-inline.ts # Pi inline lane: serves INLINE_ORIGIN traffic in-process (#3278)
│ │ ├── pi-msgids.ts # Pi wire-branch lockstep walker resolving host msgids (#4491)
│ │ ├── pi-msgids.ts # Pi wire-branch lockstep walker resolving host msgids (#4491) + core-alignment proof for the full-resend envelope (#6525)
│ │ ├── pi-subagent-registry.ts # Self-registration into pi-subagents required-child extensions (#2185)
│ │ ├── tool-guardrails.ts # Tool-output guardrails migrated from billion-context-pi (#3066)
│ │ └── dsh-native-client-react-shim.d.ts # Ambient "react" types for the dsh bundle (#1590)
Expand Down Expand Up @@ -348,7 +348,7 @@ billion-context/
│ ├── src/ # 14 modules: delegate tool/lifecycle, fleet inspector/widget, config, events
│ ├── tests/ # Component unit suite (`npm --prefix pi-subagents test`, runs on TS source)
│ └── package.json # Own name/version (npm `billion-context-pi-subagents`), own build chain (tsup → dist + d.ts)
├── tests/ # 614 test files (+ hermetic e2e lanes under tests/e2e/)
├── tests/ # 615 test files (+ hermetic e2e lanes under tests/e2e/)
├── tsup.config.ts # Build config (inlines acp-kernel + billion-context-pi-subagents; zod external)
└── package.json # npm manifest (consumes kernel via `"acp-kernel": "file:./kernel"`, pi-subagents via `"billion-context-pi-subagents": "file:./pi-subagents"`; version bumped ONLY on release branches)

Expand Down
Loading
Loading