diff --git a/docs/README.zh-CN.md b/docs/README.zh-CN.md index 18ea85c43e..7f958d6f68 100644 --- a/docs/README.zh-CN.md +++ b/docs/README.zh-CN.md @@ -1,5 +1,7 @@ # 文档导航 +- [DSH 按模型使用原生压缩](dsh-native-compaction.zh-CN.md):配置、同会话切换、兼容性与补丁维护。[English](dsh-native-compaction.md) + **billion-context** 的全部系统文档都集中在这个目录。仓库根目录只保留四个核心入口文件——`README.md`、`README.zh-CN.md`、`AGENTS.md`、`CHANGELOG.md`——外加受认可的社区 README 译本(`README..md`,如 `README.ja.md`,批准于 2026-11-09 / #6000)。原根路径保留单行重定向占位(记账见 [lifecycle §5](lifecycle.md#5-卫生记录))。 > **全量目录:** [index.zh-CN.md](index.zh-CN.md) / [index.md](index.md) —— 每篇文档一行说明。本页是目录落地页:东西在哪、什么规则让它们保持新鲜。 diff --git a/docs/architecture.md b/docs/architecture.md index 6097ab54c6..cec8fd9cd0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,5 +1,7 @@ # Architecture +DSH's opt-in [native model policy](dsh-native-compaction.md) branches before bili's HTTP/WS transforms. Its adapter owns the preset-local native backend; host replacement generations isolate later bili folds. The kernel and provider adapters are unchanged. + > One hub for the system's architecture. This page holds the **overall diagram** and the **module ledger**; each module gets its own page (en + `.zh-CN` + `.ja`) in this directory, each with its own diagram. > 中文: [architecture.zh-CN.md](./architecture.zh-CN.md) > 日本語: [architecture.ja.md](./architecture.ja.md) diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index 57f0913366..92169d6a21 100644 --- a/docs/architecture.zh-CN.md +++ b/docs/architecture.zh-CN.md @@ -1,5 +1,7 @@ # 架构总览 +DSH 可选的[原生模型策略](dsh-native-compaction.zh-CN.md)在 bili HTTP/WS 改写前分流。适配器控制预设内的原生压缩后端,用宿主持久化替换代数隔离后续 bili 压缩状态;kernel 与供应商适配器保持原样。 + > 系统架构的唯一枢纽。本页放**整体架构图**与**模块总表**;每个模块在本目录下有独立页面(中英各一份),每页配自己的图。 > English: [architecture.md](./architecture.md) > 日本語: [architecture.ja.md](./architecture.ja.md) diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 4cc7d9c81f..c37926ea54 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -127,7 +127,10 @@ | `compat.degenerateTurn` | "error" \| "passthrough" | error | BILI_DEGENERATE_TURN | プラグインチャットパイプで退化ターンのリトライ後も利用可能な出力がゼロだった場合の終了処理(#4913):インバンドストリームエラー(デフォルト、#870)または空ターンを通常の完了として通過させる(#870 以前)。 | | `compat.noCacheControl` | boolean | false | BILI_NO_CACHE_CONTROL | Anthropic レーンの cache_control ブレークポイントを完全にスタンプしないようにします(独自のブレークポイントポリシーを持つ上流/リレー用のエスケープハッチ)。 | | `compat.keepResponseId` | boolean | false | ACP_KEEP_RESPONSE_ID | カーネル再構築された Responses リクエストで previous_response_id を保持します(デフォルトでは削除するため、再構築されたボディは上流が発行したことのない ID を参照しません)。 | -| `dsh` | object | {} | BILI_ALLOW_DSH_COMPACTION | セクションは認識されるが、従来のエスケープハッチは削除された(#3666、#2028 を代替):`allowDshCompaction` キーおよび `BILI_ALLOW_DSH_COMPACTION` 環境変数はもはや存在しない — dsh ネイティブコンパクションは、すべてのレーンにおいてワイヤガードによって無条件に拒否される。残存する `dsh.allowDshCompaction` の値は、一度限りの非推奨警告とともに無視される;代わりにホスト側の抑制を適用すること(#3354/#2474)。ライブキー — `dsh.authoredCompaction`、`dsh.contextTab`、`dsh.contextTabLabel` — は以下のエントリに文書化されている。 | +| `dsh` | object | {} | BILI_ALLOW_DSH_COMPACTION | セクションは認識されるが、従来のエスケープハッチは削除された(#3666、#2028 を代替):`allowDshCompaction` キーおよび `BILI_ALLOW_DSH_COMPACTION` 環境変数はもはや存在しない — ワイヤガードは管理されていないネイティブコンパクションを拒否する。明示的な `dsh.nativeCompactionModels` ルールはホストの所有権を調整し、そのワイヤレーンをバイパスする。残存する `dsh.allowDshCompaction` の値は、一度限りの非推奨警告とともに無視される;代わりにホスト側の抑制を適用すること(#3354/#2474)。ライブキー — `dsh.authoredCompaction`、`dsh.contextTab`、`dsh.contextTabLabel` — は以下のエントリに文書化されている。 | +| `dsh.nativeCompactionModels` | { provider?: string, model: string }[] | [] | — | DSH Web プリセットの選択されたモデルをネイティブコンパクションに割り当てる(#6121)。正確な provider ID は任意;model は完全一致、または末尾 * の接頭辞で一致する(例:`gpt-*`、`codex/gpt-*`)。一致しないモデルは `bili` を維持する。宿主のリスタートが必要。ネイティブ要約は `bili` をバイパスし、宿主置換の世代は後続の `bili` 状態を分離する;対応プロファイル、引き渡し上限、更新ガイドは docs/dsh-native-compaction.md を参照。 | +| `dsh.nativeCompactionModels.model` | string | required per rule | — | 各ネイティブコンパクションルールの正確なモデル ID、または末尾 * で終わる接頭辞。表示名やその他のワイルドカード形式は受け入れられない。 | +| `dsh.nativeCompactionModels.provider` | string | omitted (all providers) | — | ネイティブコンパクションのモデルルールを 1 つに制限する、任意の正確な DSH provider ID。 | | `dsh.authoredCompaction` | boolean | true (on, #3901 flip) | BILI_DSH_AUTHORED_COMPACTION | bili は dsh コンパクションの summarize 呼び出しを、拒否する代わりに折り畳みスナップショットでローカルに回答する(#3723/#3733)。0.1.203 のドッグフッド期間が維持されたため、デフォルトで ON。`false`(または環境変数 `BILI_DSH_AUTHORED_COMPACTION=0`)を設定すると、#1729 の拒否パスが復元される。 | | `dsh.contextTab` | boolean | true | BILI_DSH_CONTEXT_TAB | DSH トップバーの「上下文」/「Context」会話タブを登録する(#3862/#4237):`false` にすると、そのタブのみが削除される — コンプレッション、設定セクション、その他のすべてのサーフェスは引き続き動作する。非表示にしてもコンプレッションは無効にならない;台帳は設定セクション(会话 サブページ)、プラグインバンドル設定フェイス、Web UI、および `/acp` コマンド経由で引き続きアクセス可能。次のページ読み込み / dsh リスタート時に有効になる(スロット登録はページ読み込み時に発生);デフォルト `true` = 現在の動作は変更なし。 | | `dsh.contextTabLabel` | string | unset (built-in 「上下文」/「Context」) | — | DSH トップバーの Context タブのカスタム表示名(#4237)、例:別のプラグイン(dsh-context)が「上下文」の名前を所有している場合の "压缩账本"。トリムされた空でない文字列が組み込みラベルに優先される;空白または未設定の場合は組み込みにフォールバック。ファイル専用ティア(表示設定、#2030 に従い環境変数なし)。デフォルト未設定 = 組み込みラベルは変更なし。 | diff --git a/docs/configuration.md b/docs/configuration.md index cab7fc650a..6e468353e9 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -130,7 +130,10 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compat.degenerateTurn` | "error" \| "passthrough" | error | BILI_DEGENERATE_TURN | Terminal for the plugin chat pipe when the degenerate-turn retry ALSO ends with no usable output (#4913): in-band stream error (default, #870) or the empty turn passed through as a normal completion (pre-#870). | | `compat.noCacheControl` | boolean | false | BILI_NO_CACHE_CONTROL | Stop stamping Anthropic-lane cache_control breakpoints entirely (escape hatch for upstreams/relays with their own breakpoint policy). | | `compat.keepResponseId` | boolean | false | ACP_KEEP_RESPONSE_ID | Preserve previous_response_id on kernel-rebuilt Responses requests (default strips it so rebuilt bodies never reference ids the upstream never issued). | -| `dsh` | object | {} | BILI_ALLOW_DSH_COMPACTION | Section recognized but its former escape hatch is gone (#3666, superseding #2028): the allowDshCompaction key and the BILI_ALLOW_DSH_COMPACTION env var no longer exist — dsh native compaction is refused unconditionally by the wire guard on every lane. Leftover dsh.allowDshCompaction values are ignored with a one-time deprecation warning; apply host-side suppression instead (#3354/#2474). The live keys — dsh.authoredCompaction, dsh.contextTab, dsh.contextTabLabel — are documented in the following entries. | +| `dsh` | object | {} | BILI_ALLOW_DSH_COMPACTION | Section recognized but its former escape hatch is gone (#3666, superseding #2028): the allowDshCompaction key and the BILI_ALLOW_DSH_COMPACTION env var no longer exist — the wire guard refuses unmanaged native compaction. Explicit dsh.nativeCompactionModels rules coordinate host ownership and bypass that wire lane. Leftover dsh.allowDshCompaction values are ignored with a one-time deprecation warning; apply host-side suppression instead (#3354/#2474). The live keys — dsh.authoredCompaction, dsh.contextTab, dsh.contextTabLabel — are documented in the following entries. | +| `dsh.nativeCompactionModels` | { provider?: string, model: string }[] | [] | — | Opt selected DSH Web-preset models into native compaction (#6121). Exact provider ID is optional; model matches exactly or by a trailing * prefix, e.g. gpt-* or codex/gpt-*. Unmatched models keep bili. Requires a host restart. Native summaries bypass bili and host replacement generations isolate later bili state; see docs/dsh-native-compaction.md for supported profiles, handoff limits and update guidance. | +| `dsh.nativeCompactionModels.model` | string | required per rule | — | Each native-compaction rule's exact model ID or prefix ending in *. Display names and other wildcard forms are not accepted. | +| `dsh.nativeCompactionModels.provider` | string | omitted (all providers) | — | Optional exact DSH provider ID restricting one native-compaction model rule. | | `dsh.authoredCompaction` | boolean | true (on, #3901 flip) | BILI_DSH_AUTHORED_COMPACTION | bili answers dsh compaction summarize calls locally with the folded snapshot instead of refusing (#3723/#3733). ON by default since the 0.1.203 dogfood window held; false (or env BILI_DSH_AUTHORED_COMPACTION=0) restores the #1729 refusal path. | | `dsh.contextTab` | boolean | true | BILI_DSH_CONTEXT_TAB | Registers the DSH top-bar 「上下文」/「Context」 conversation tab at all (#3862/#4237): false removes ONLY that tab — compression, the settings section and every other surface keep working. Hiding never disables compression; the ledger stays reachable via the settings section (会话 subpage), the plugin bundle config face, the Web UI and the /acp command. Takes effect on the next page load / dsh restart (slot registration happens at page load); default true = today's behavior unchanged. | | `dsh.contextTabLabel` | string | unset (built-in 「上下文」/「Context」) | — | Custom display name for the DSH top-bar Context tab (#4237), e.g. "压缩账本" when another plugin (dsh-context) owns the name 「上下文」. Trimmed non-empty string wins over the built-in label; blank or absent falls back to the built-in. File-only tier (display preference, no env knob per #2030). Default unset = built-in label unchanged. | diff --git a/docs/configuration.zh-CN.md b/docs/configuration.zh-CN.md index ce2f4608e7..b71737960e 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -130,7 +130,10 @@ | `compat.degenerateTurn` | "error" \| "passthrough" | error | BILI_DEGENERATE_TURN | plugin chat 管道的退化回合重试后仍无可用输出时的终局(#4913):带内流错误(默认,#870)或把空回合作为正常完成放行(pre-#870)。 | | `compat.noCacheControl` | boolean | false | BILI_NO_CACHE_CONTROL | 完全停止 Anthropic 通道的 cache_control 断点打标(面向拒收该字段或有自有断点策略的上游/中继的逃生门)。 | | `compat.keepResponseId` | boolean | false | ACP_KEEP_RESPONSE_ID | 在内核重建的 Responses 请求上保留 previous_response_id(默认剔除,使重建请求体永不引用上游从未签发过的响应 id)。 | -| `dsh` | object | {} | BILI_ALLOW_DSH_COMPACTION | 段仍被识别,但其原逃生门已移除(#3666,取代 #2028):allowDshCompaction 键与 BILI_ALLOW_DSH_COMPACTION 环境变量已不存在——dsh 原生压缩现在在所有线路上被无条件拒绝。遗留的 dsh.allowDshCompaction 取值会被忽略(一次性弃用警告);请改用宿主侧抑制(#3354/#2474)。存活的键——dsh.authoredCompaction、dsh.contextTab、dsh.contextTabLabel——见接下来的条目。 | +| `dsh` | object | {} | BILI_ALLOW_DSH_COMPACTION | 段仍被识别,但其原逃生门已移除(#3666,取代 #2028):allowDshCompaction 键与 BILI_ALLOW_DSH_COMPACTION 环境变量已不存在——线级守卫拒绝未受管理的原生压缩。显式 dsh.nativeCompactionModels 规则协调宿主压缩归属并绕过该线路。遗留的 dsh.allowDshCompaction 取值会被忽略(一次性弃用警告);请改用宿主侧抑制(#3354/#2474)。存活的键——dsh.authoredCompaction、dsh.contextTab、dsh.contextTabLabel——见接下来的条目。 | +| `dsh.nativeCompactionModels` | { provider?: string, model: string }[] | [] | — | 指定 DSH Web 预设中的模型使用原生压缩(#6121)。可选 provider 精确匹配;model 精确匹配或使用末尾 * 表示前缀,例如 gpt-*、codex/gpt-*。未匹配模型继续使用 bili,需重启宿主生效。原生摘要绕过 bili,宿主替换代数隔离后续 bili 状态;支持范围、切换边界和更新方式见 docs/dsh-native-compaction.zh-CN.md。 | +| `dsh.nativeCompactionModels.model` | string | required per rule | — | 每条原生压缩规则的模型 ID,精确匹配或末尾 * 前缀匹配,不使用显示名或其他通配形式。 | +| `dsh.nativeCompactionModels.provider` | string | omitted (all providers) | — | 可选的 DSH 供应商 ID,精确限定该条原生压缩模型规则。 | | `dsh.authoredCompaction` | boolean | true (on, #3901 flip) | BILI_DSH_AUTHORED_COMPACTION | bili 用折叠快照本地应答 dsh 压缩摘要请求而非拒绝(#3723/#3733)。0.1.203 狗粮窗口守住后默认开启;false(或环境变量 BILI_DSH_AUTHORED_COMPACTION=0)恢复 #1729 拒绝路径。 | | `dsh.contextTab` | boolean | true | BILI_DSH_CONTEXT_TAB | 是否注册 DSH 顶栏「上下文」会话标签页(#3862/#4237):false 只移除该标签页——压缩、设置页一节及其余所有入口不受影响。隐藏绝不关闭压缩;账本仍可从设置页(会话子页)、插件 bundle 配置面、Web UI 与 /acp 命令查看。下次页面加载 / dsh 重启生效(槽位注册发生在页面加载时);默认 true = 现状不变。 | | `dsh.contextTabLabel` | string | unset (built-in 「上下文」/「Context」) | — | DSH 顶栏上下文标签页的自定义显示名(#4237),例如另一插件(dsh-context)已占用「上下文」时改为"压缩账本"。去空白后的非空字符串优先于内置名;留空或缺省回退内置名。仅文件层(显示偏好,按 #2030 不设 env 开关)。默认缺省 = 内置名不变。 | diff --git a/docs/dsh-native-compaction.md b/docs/dsh-native-compaction.md new file mode 100644 index 0000000000..edfd79e4a5 --- /dev/null +++ b/docs/dsh-native-compaction.md @@ -0,0 +1,62 @@ +# DSH model-selective native compaction + +Proposed in #6121. This opt-in feature targets DSH Web agent presets containing `@deepseek-ai/dsh-compaction-basic` (standard, ptc, cordis, and equivalent custom presets). Default configuration `[]` preserves bili's existing behavior. Restart the host after changing the list; existing preset instances retain their original composition. + +```json +{ + "dsh": { + "nativeCompactionModels": [ + { "model": "gpt-*" }, + { "model": "codex/gpt-*" } + ] + } +} +``` + +Rules match the actual DSH **model ID**, case-sensitively, not its display label. A trailing `*` means prefix matching; other wildcards and a standalone `*` are rejected. Optional `provider` is an exact DSH provider ID. Omit it to match the model across providers. All unmatched models keep bili. `codex/gpt-*` is needed when a gateway includes that namespace in the model ID. `passthrough` alone cannot enable the native backend. + +```mermaid +flowchart LR + A[DSH selected model] --> B{Native rule matches?} + B -->|yes| C[Unmodified DSH compaction] + C --> D[Direct provider call] + B -->|no| E[Durable host replacement generation] + E --> F[Bili conversation namespace] + F --> G[Existing bili compression] +``` + +Native thresholds, retention settings, summary prompts and summary-model resolution remain DSH-owned. On a model switch DSH can summarize using its previous routed model unless its own summary-model configuration overrides that choice. Those summary requests still bypass bili, independently of the summarization model's membership in the rules. + +This adapter only selects the compaction owner. DSH retains control of summary input, tools, output budget, model selection, prompts, call count and failure handling. The patch performs no extra budget validation, history splitting, intermediate summarization or merge prompting. An asynchronous scope marks native summary requests for direct transport without changing their content or affecting concurrent bili sessions. + +Native steps do not expose bili compression tools; bili steps do not trigger host compaction. Native HTTP requests preserve their bodies, headers and provider transport. A WebSocket reused across ownership modes rejects that frame and closes so the existing host transport recovery can reconnect. + +When switching bili → native, DSH uses its own durable history and checkpoints with its existing compaction strategy. Bili fold summaries are not assembled into a replacement native summary. If the selected history exceeds the summary model window, the native request and native failure/recovery behavior are preserved, without secretly splitting history or switching models. A switch cannot guarantee successful compaction of arbitrarily long history. Consecutive native compactions remain controlled by the stock pressure strategy. + +When switching native → bili, the host's durable `surface.replaceGeneration` changes the bili conversation namespace. On the first full replay, the local DSH adapter can reuse verified folds from the immediately preceding generation of that same session. A block needs matching original wire messages in order, complete tool pairs and originals, valid citations and the same upstream. Unmatched blocks stay as raw history. This applies to OpenAI Chat and Anthropic Messages, not Responses, auxiliary calls, partial deltas or the experimental egress plane. Existing generations and older ledgers without wire evidence are not backfilled. The value survives replay/restart and does not change on ordinary appends or model switches without a host replacement. Original DSH session IDs and append-only history are unchanged. After a replacement, negotiated aliases, fork adoption and incremental conversion are disabled for that substrate; full sends plus a fresh watermark seed provide a conservative boundary. Other sessions retain their existing path. The Context tab and `/acp` follow the active namespace; native mode reports its ownership rather than showing stale bili data. + +## Compatibility and validation + +Validated with DSH `0.2.2-rc.1` / `0.2.2-rc.5`. The integration script uses the real Cordis loader, isolated compaction realm, token meter, Session replay and native checkpoint engine, with a deterministic fake LLM (no account traffic). Run after building: + +```sh +node scripts/test-dsh-native-compaction.mjs /absolute/path/to/isolated-dsh-runtime +``` + +The caller must supply a detached runtime directory, not a running profile. No credentials, live sessions or production files are used by this test. The actual upstream model's summary quality and provider billing are not validated by a fake LLM. + +Native requests fail closed when their preset has not attached the adapter. The refusal applies to that native dispatch, not other models or sessions. A malformed rule in an otherwise readable config prevents the DSH plugin from activating; fix the rule and restart. A file that cannot be parsed follows the normal config-loader fallback; it cannot enable these rules. Both factory presets and runtime registrations use the same policy. The stock minimal preset has no compaction backend: native rules preserve that behavior and do not add compression. Root-plane CLI compositions and unknown future DSH APIs require compatibility work before enabling rules there. This feature does not silently promise native compression on those profiles. + +## Behavioral parity acceptance + +The real DSH engine integration script replays identical events through the stock engine without the routing adapter and through the routed native engine. It compares actual summary requests, compaction events, generations and token results; only newly generated host identifiers are normalized, preserving original message and tool IDs. Cases cover below-threshold, automatic/manual/region compaction, model switches, configured summary models, provider failure, cancellation and oversized histories/tool catalogs. Overflow must fail the same way in both arms rather than succeed through a new adapter fallback. + +The bili comparison uses real plugin request interception, proxy and compression tools to compare bili-only mode with an unmatched model under selective routing: tool lists, fold results and provider requests must match. Separate coverage checks round trips, checkpoint-generation replay and asynchronous isolation. A deterministic upstream removes random model-output differences; this verifies routing behavior, not summary quality or losslessness. Earlier batch-merge A/B results describe removed code and are not acceptance evidence for this revision. + +## Carrying a patch across updates + +Keep the source commit/patch and tests in version control. Build candidates from the desired upstream release, apply the patch with `git apply --check`, then run typecheck, focused tests, build, and the real-DSH integration script before packaging. Use a profile-owned local `file:` package pin so the registry updater cannot overwrite the patch. Updates become an explicit rebuild-and-install workflow, not automatic registry replacement. Preserve the original package, profile manifest/lockfile and config for rollback. Never apply an old compiled `dist` over a newer upstream tree. + +Unknown future upstream versions can conflict or change behavior even when a patch applies. Stop on conflicts or failed compatibility checks, retain the installed version, and review/rebase the patch. No finite test suite guarantees compatibility with every future release. + +To return every model to bili after using this feature, keep the key and set `nativeCompactionModels: []`. An explicitly present empty list retains generation isolation; deleting the key or removing the patch is a separate migration and can expose an earlier bili namespace. diff --git a/docs/dsh-native-compaction.zh-CN.md b/docs/dsh-native-compaction.zh-CN.md new file mode 100644 index 0000000000..e43f6ed1dc --- /dev/null +++ b/docs/dsh-native-compaction.zh-CN.md @@ -0,0 +1,62 @@ +# DSH 按模型使用原生压缩 + +对应 #6121。此可选功能用于包含 `@deepseek-ai/dsh-compaction-basic` 的 DSH Web 预设:standard、ptc、cordis 及结构相同的自定义预设。默认空列表维持既有 bili 行为。修改后需重启宿主,因为运行中的 Agent 会保留原预设实例。 + +```json +{ + "dsh": { + "nativeCompactionModels": [ + { "model": "gpt-*" }, + { "model": "codex/gpt-*" } + ] + } +} +``` + +匹配实际 DSH **模型 ID**,区分大小写,不匹配显示名。仅支持结尾 `*` 表示前缀;不接受其他通配符或单独 `*`。可选的 `provider` 精确匹配 DSH 供应商 ID;省略表示所有供应商。未匹配模型继续使用 bili。网关模型 ID 若包含 `codex/`,需配置 `codex/gpt-*`。单独设置 `passthrough` 无法恢复宿主压缩。 + +```mermaid +flowchart LR + A[DSH 本轮模型选择] --> B{命中原生规则?} + B -->|是| C[原有 DSH 压缩流程] + C --> D[直接调用供应商] + B -->|否| E[宿主持久化替换代数] + E --> F[Bili 会话命名空间] + F --> G[原有 bili 压缩流程] +``` + +原生触发阈值、近期内容保留、摘要提示词和摘要模型选择由 DSH 决定。模型切换时,DSH 可能使用上一轮模型生成摘要,除非其原生配置另行指定;这些摘要请求仍绕过 bili,不受摘要模型是否命中规则影响。 + +此适配层只决定压缩归属,原生摘要的输入、工具、输出预算、模型选择、提示词、调用次数和失败处理均由 DSH 原方法负责。补丁不进行额外预算检查,不拆分历史,不生成中间摘要,也不添加合并指令。原生摘要请求使用异步作用域标记绕过 bili;标记不改变请求内容,且不影响并发的 bili 会话。 + +原生步骤不提供 bili 压缩工具;bili 步骤不触发宿主原生压缩。原生 HTTP 请求保留请求体、请求头和供应商传输。WebSocket 若复用跨压缩模式的连接,会先阻止该帧并关闭连接,由宿主既有传输恢复机制重连。 + +**bili → 原生:** DSH 使用自身持久化的历史与检查点执行原有压缩策略,不把 bili 的折叠摘要拼接成新的原生摘要。若选中历史超过摘要模型窗口,保留原生请求及原生失败/恢复行为,不偷偷分批或更换模型。切换不保证任意长度历史都能立即压缩成功。原生本身可能连续压缩;这仍由原生压力策略决定。 + +**原生 → bili:** 使用宿主持久化的 `surface.replaceGeneration` 区分 bili 命名空间,防止旧折叠套用到新摘要上。重启重放后保持一致;普通追加消息或未发生宿主替换的模型切换不会改名。DSH 会话 ID 与原始追加日志保持原样。发生替换后,该命名空间停用旧协商别名、分叉继承和增量发送,采用完整发送及新的水位种子;其他会话沿用原路径。上下文页和 `/acp` 跟随当前命名空间,原生模式显示归属,不展示过时 bili 数据。 新一代首次完整重放时,只复用同一会话上一代中可以验证的块:原始消息的内容和顺序一致,工具调用与结果完整,原文可取回,引用可解析,上游相同。不满足条件的内容继续按原文发送。仅支持 OpenAI Chat 和 Anthropic Messages;Responses、辅助请求、增量片段和实验性 egressPlane 不参与。不会回填已有目标账本或没有原文证据的旧块。 + +## 验证与边界 + +针对 DSH `0.2.2-rc.1` / `0.2.2-rc.5` 验证。集成脚本使用真实 Cordis Loader、独立压缩作用域、token meter、Session 重放和原生检查点引擎;模型为确定性假实现,不消耗账户额度: + +```sh +node scripts/test-dsh-native-compaction.mjs /绝对路径/隔离的DSH运行时 +``` + +运行时必须是独立副本,不是正在运行的 profile。测试不使用凭据、现有会话或线上文件;不代表已经验证真实模型的摘要质量或计费。 + +预设未挂载适配器时,原生请求明确失败。拒绝仅影响这次原生请求,不影响其他模型或会话。配置可读取但规则格式无效时,DSH 插件不能激活;修正规则后重启。整份配置无法解析时,加载器沿用默认配置,原生规则不会启用。静态和运行时注册的预设使用同一路由策略。原厂 minimal 预设没有压缩后端,命中原生规则时维持其原样,不额外添加压缩。CLI 根作用域配置、未来 DSH API 版本需要额外适配,不能直接视为已支持。 + +## 行为对照验收 + +真实 DSH 引擎集成脚本将同一份事件历史分别交给未安装路由适配器的原生引擎和安装后的原生引擎。比较实际摘要请求、压缩事件、代数和 token 结果;只规范化宿主新生成的随机标识,保留原始消息及工具 ID。覆盖压力线以下、自动/手动/指定范围压缩、切换模型、指定摘要模型、供应商失败、取消和超长历史/工具目录。超限场景要求两边同样失败,不以补丁额外兜底作为成功。 + +bili 对照使用真实插件请求拦截、代理及压缩工具,比较仅 bili 与未命中原生规则时的工具列表、折叠结果和供应商请求。另测同会话双向切换、检查点代数重放及异步并发隔离。确定性上游用于消除模型随机输出造成的差异;这验证路由行为,不代表摘要质量或无损保证。此前分批合并 A/B 属于已撤销实现的历史证据,不再是当前实现的验收。 + +## 后续更新保留补丁 + +保存源码提交、补丁和测试。对目标上游版本先执行 `git apply --check`,再执行类型检查、针对性测试、构建及真实 DSH 集成验证,全部通过才打包。profile 使用其管理渠道的本地 `file:` 包固定,避免注册表更新覆盖补丁;以后更新改为明确的“重建、验证、安装”流程。保留原包、profile 清单/锁文件及配置用于回滚。不要将旧 `dist` 覆盖到新版源码上。 + +未来上游可能产生冲突或改变语义,即使补丁文本能套用也不代表兼容。检查失败时应保留已安装版本并重新审查补丁,不能保证未知的所有未来版本均可自动应用。 + +使用后若要让全部模型回到 bili,请保留配置键并设为 `nativeCompactionModels: []`;显式空列表仍保留代数隔离。删除整个配置键或移除补丁属于另一次迁移,可能重新暴露旧 bili 命名空间,不能等同于清空规则。 diff --git a/docs/index.md b/docs/index.md index dc39961796..ae2fc94636 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,5 +1,7 @@ # Documentation Index +- [DSH model-selective native compaction](dsh-native-compaction.md) / [中文](dsh-native-compaction.zh-CN.md): configuration, same-session handoff, compatibility and patch maintenance. + > All system documentation lives under `docs/`. The repo root keeps only four **core** entry files — `README.md`, `README.zh-CN.md`, `AGENTS.md`, `CHANGELOG.md` — and recognized community-maintained README translations (`README..md`, e.g. `README.ja.md`, approved 2026-11-09, #6000). Former root doc paths keep one-line redirect stubs (scheduled for removal after 1–2 releases; tracked in [lifecycle §5](lifecycle.md#5-卫生记录)). > Lazy-load procedures (architecture / env-vars / testing / release / git-pr): [reference/](../reference/README.md). diff --git a/package.json b/package.json index a2d01c347e..daaa0d5dd6 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "./server": "./dist/agent/opencode-native.js", "./dsh": "./dist/agent/dsh-native.js", "./dsh-compaction-gate": "./dist/agent/dsh-compaction-gate.js", + "./dsh-native-compaction": "./dist/agent/dsh-native-compaction.js", "./package.json": "./package.json", "./dsh/package.json": "./package.json", "./envelope-client": "./dist/agent/envelope-client.js", diff --git a/reference/architecture.md b/reference/architecture.md index 4e9fc4d2ef..0b5c28fdc5 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -208,6 +208,7 @@ billion-context/ │ ├── plugin-install.ts # `bili plugin install` driving host channels │ ├── plugin-spec.ts # `bili plugin install [spec]` version pinning: spec grammar (npm version / PR / branch / tag / sha), local copy materialization, --force/--home │ ├── dsh-channel.ts # dsh profile bundle management (refreshDshProfileCopy, #1196) +│ ├── dsh-generation-reuse.ts # Verify old folds against a new DSH generation before its first prepare │ ├── pi-channel.ts # pi npm-copy self-refresh spec form │ ├── claude-native-bootstrap.ts # Claude native bootstrap hook entry │ ├── claude-subagent-hook.ts # Claude SubagentStart hook: mint per-dispatch lane token (#5095) @@ -249,6 +250,7 @@ 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) +│ │ ├── dsh-native-compaction.ts # Model ownership, bounded native handoff and durable generation isolation (#6121) │ │ ├── envelope-client.ts # Envelope client SDK (discussions/7978): EnvelopeClientState — the ONLY sanctioned state machine for x_bili_env attach (create/append decision, ack memory, 400 recovery); integrators import it, never reimplement │ │ ├── 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) diff --git a/scripts/check-unused-exports.mjs b/scripts/check-unused-exports.mjs index 314d86a8e0..6c8972b444 100644 --- a/scripts/check-unused-exports.mjs +++ b/scripts/check-unused-exports.mjs @@ -35,6 +35,7 @@ const ENTRY_FILES = new Set([ "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", + "src/agent/dsh-native-compaction.ts", "src/agent/dsh-compaction-gate.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", diff --git a/scripts/live-files.mjs b/scripts/live-files.mjs index 6ada10878c..b36cbb592e 100644 --- a/scripts/live-files.mjs +++ b/scripts/live-files.mjs @@ -137,6 +137,9 @@ export const LIVE_FILES = [ // child binds no port and does no network I/O, so no zone band is needed — // the entry is for the tripwire alone, like #3890/#5114 "tests/integrity-worker-stderr.test.ts", + // Routing parity forks an isolated proxy per arm; all sockets use listen(0), + // state uses the test sandbox, and each child exits before the next arm. + "tests/dsh-llm-stream-attribution.test.ts", // Real npm pack/install children use mkdtemp package fixtures and the // preload's per-process XDG roots; they bind no listener ports. "tests/pack-install.test.ts", diff --git a/scripts/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs new file mode 100644 index 0000000000..cdd4811567 --- /dev/null +++ b/scripts/test-dsh-native-compaction.mjs @@ -0,0 +1,144 @@ +import assert from 'node:assert/strict'; +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; +import { readFileSync } from 'node:fs'; +if (!process.argv[2]) throw new Error('Usage: node scripts/test-dsh-native-compaction.mjs /path/to/isolated-dsh-runtime'); +const root = pathToFileURL(path.resolve(process.argv[2], 'node_modules/@deepseek-ai') + '/'); +const load = async name => import(new URL(`${name}/lib/index.js`, root)); +const { Context } = await load('cordis'); +const { default: Loader } = await load('cordis-plugin-loader'); +const { Session, SessionStore } = await load('dsh-session'); +const { SessionProjectionRegistry } = await load('dsh-session-projection'); +const { TokenMeter } = await load('dsh-token-meter'); +const { createUserMessage, createSystemMessage } = await load('dsh-llm'); +const policy = await import('../dist/agent/dsh-native-compaction.js'); +policy.configureNativeCompaction(['gpt-*', 'codex/gpt-*', 'claude-*', 'anthropic/claude-*', 'devin/claude-*', 'lumen/anti_claude-*'].map(model => ({ model }))); +const config = { auto: true, thresholdRatio: 0.8, headroomTokens: 1000, maxTokens: 200, retainTokens: 1000 }; +const catalog = Array.from({ length: 327 }, (_, i) => ({ name: `tool_${i}`, description: 'Synthetic 工具目录 description. '.repeat(40), parameters: { type: 'object', properties: {} } })); +const scenarios = [ + { name: 'below-pressure', repeats: 10, expectedCalls: 0 }, + { name: 'pressure', repeats: 450, expectedCalls: 1 }, + { name: 'native-pressure-repeat', repeats: 450, config: { thresholdRatio: 0.4, retainTokens: 6000 }, longFirst: true, expectedCalls: 2 }, + { name: 'manual', repeats: 200, method: 'manual', expectedCalls: 1 }, + { name: 'region', repeats: 200, method: 'region', expectedCalls: 1 }, + { name: 'model-switch', repeats: 450, previous: 'glm-test', method: 'switch', expectedCalls: 1 }, + { name: 'claude-pressure', model: 'anthropic/claude-test', repeats: 450, expectedCalls: 1 }, + { name: 'switch-bili-to-claude', model: 'lumen/anti_claude-test', repeats: 450, previous: 'kimi-test', method: 'switch', expectedCalls: 1 }, + { name: 'switch-gpt-to-claude', model: 'devin/claude-test', repeats: 450, previous: 'gpt-test', method: 'switch', expectedCalls: 1 }, + { name: 'configured-summary-model', repeats: 450, config: { summarizationProvider: 'summary', summarizationModel: 'glm-summary' }, expectedCalls: 1 }, + { name: 'provider-failure', repeats: 450, fail: true, expectedCalls: 1, error: 'synthetic provider failure' }, + { name: 'retry-after-failure', repeats: 450, fail: true, retry: true, expectedCalls: 2 }, + { name: 'cancelled', repeats: 450, cancel: true, expectedCalls: 0, error: 'synthetic cancellation' }, + { name: 'oversized-history', repeats: 2600, expectedCalls: 1, error: 'provider context window exceeded' }, + { name: 'large-tool-catalog', repeats: 7500, model: 'gpt-luna', tools: catalog, config: { maxTokens: 65536, headroomTokens: 65536, retainTokens: 32245 }, expectedCalls: 1, error: 'provider context window exceeded' }, + { name: 'oversized-tools', repeats: 450, tools: [{ name: 'huge', description: 'x'.repeat(800000), parameters: { type: 'object' } }], expectedCalls: 1, error: 'provider context window exceeded' }, +]; + +async function run(scenario, routed, seed) { + const ctx = new Context(), calls = []; + const model = scenario.model ?? 'gpt-test'; + const window = model === 'gpt-luna' ? 272000 : 18000; + try { + await ctx.plugin(c => c.reflect.provide('llm', { + imageRequestPricing: () => undefined, + resolveModelInfo: async () => ({ context: { contextWindow: window }, defaultMaxTokens: 100 }), + async *stream(options) { + assert.equal(policy.nativeSummaryActive(), routed); + calls.push(options); + if (scenario.fail && (!scenario.retry || calls.length === 1)) throw new Error('synthetic provider failure'); + const tokens = options.messages.reduce((n, m) => n + ctx.tokenMeter.estimateMessage(m), 0); + const tools = options.tools?.length ? Math.ceil(JSON.stringify(options.tools).length / 4) + 4 : 0; + if (tokens + tools + options.maxTokens > window) throw new Error('provider context window exceeded'); + yield { type: 'text-delta', index: 0, text: scenario.longFirst && calls.length === 1 ? 'Historical stable fact. '.repeat(400) : 'Facts retained: ROUTE-811; budget 7314; no production changes.' }; + yield { type: 'finish', reason: 'stop' }; + }, + })); + await ctx.plugin(SessionStore); + await ctx.plugin(SessionProjectionRegistry); + await ctx.plugin(TokenMeter); + await ctx.plugin(Loader, { baseUrl: root.href }); + ctx.loader.builtins.group = await load('cordis-plugin-group'); + await ctx.loader.create({ id: 'compaction', name: 'cordis:group', group: true, isolate: { compaction: true }, config: [ + { name: new URL('dsh-compaction-basic/lib/index.js', root).href, config: { ...config, ...scenario.config } }, + ...(routed ? [{ name: new URL('../dist/agent/dsh-native-compaction.js', import.meta.url).href }] : []), + ] }); + await ctx.loader.await(); + const engine = ctx.loader.resolveGroup('compaction').ctx.get('compaction'); + assert.ok(engine); + assert.equal(ctx.get('compaction'), undefined); + const id = `parity-${scenario.name}`; + const session = seed ? ctx.sessions.create(id, { seed: seed.events, meta: seed.header }) : ctx.sessions.create(id); + if (!seed) { + session.append('system/message', { message: createSystemMessage('Keep the facts.') }, { surfaceOp: 'append' }); + session.append('request/header', { header: { config: { provider: 'fake', model: scenario.previous ?? model, maxTokens: model === 'gpt-luna' ? 70464 : 200 }, ...(scenario.tools ? { tools: scenario.tools } : {}) }, reason: 'initial' }); + for (let i = 0; i < 16; i++) session.append('user/message', createUserMessage({ content: [{ type: 'text', text: `fact-${i}: `.repeat(scenario.repeats) }], source: { kind: 'user' } }), { surfaceOp: 'append' }); + if (scenario.method !== 'manual') session.append('turn/start', { turn: 'test-turn' }); + session.append('session/end-seed', {}); + } + const before = { events: session.snapshotEvents(), header: session.header }; + if (seed) assert.deepEqual(before.events, seed.events, 'both arms start from the exact same event log'); + const nodes = [...session.surface.nodes]; + let current = model; + const agent = { session, options: { provider: 'fake', model }, model: { current: () => ({ provider: 'fake', model: current }) }, runMaintenance: fn => fn(new AbortController().signal) }; + const controller = new AbortController(); + if (scenario.cancel) controller.abort(new Error('synthetic cancellation')); + let error; + try { + if (scenario.method === 'manual') await engine.compactNow(agent, controller.signal); + else if (scenario.method === 'region') await engine.compactRegion(2, 7, agent, controller.signal); + else if (scenario.method === 'switch') await engine.compactPressure(agent, { config: { provider: 'fake', model, maxTokens: 200 } }, controller.signal, true); + else await engine.compactIfNeeded(agent, 'pressure', controller.signal); + } catch (e) { error = e.message; } + if (scenario.retry) { + assert.equal(error, 'synthetic provider failure'); + assert.deepEqual(session.surface.nodes, nodes); + assert.equal(session.surface.replaceGeneration, 0); + await engine.compactIfNeeded(agent, 'pressure', controller.signal); + error = undefined; + } + assert.equal(error, scenario.error, scenario.name); + assert.equal(calls.length, scenario.expectedCalls, scenario.name); + assert.deepEqual(session.snapshotEvents().slice(0, before.events.length), before.events); + if (scenario.error) { + assert.deepEqual(session.surface.nodes, nodes); + assert.equal(session.surface.replaceGeneration, 0); + } + const nativeNamespace = policy.compactionConversationId(agent, id); + if (routed) { + current = 'glm-test'; + const generation = session.surface.replaceGeneration; + assert.equal(await engine.compactIfNeeded(agent, 'pressure'), null); + assert.equal(session.surface.replaceGeneration, generation); + const restored = Session.create(id, session.snapshotEvents(), session.header); + assert.equal(policy.compactionConversationId({ session: restored }, id), nativeNamespace); + assert.equal(nativeNamespace, generation ? `${id}|dsh-generation:${generation}` : id); + } + const output = { + calls: calls.map(({ signal, ...rest }) => rest), error, + generation: session.surface.replaceGeneration, + tokens: ctx.tokenMeter.measure(session).totalTokens, + events: session.snapshotEvents().slice(before.events.length).map(e => ({ type: e.type, data: e.data })), + }; + // Only host-generated IDs differ between independent executions; input and tool IDs stay exact. + const generated = new Map(), prior = JSON.stringify(before.events); + function canonical(value, key) { + if (typeof value === 'string' && (key === 'compactionId' || key === 'id') && !prior.includes(value)) { + if (!generated.has(value)) generated.set(value, `generated-${generated.size}`); + return generated.get(value); + } + if (Array.isArray(value)) return value.map(v => canonical(v)); + if (value && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, canonical(v, k)])); + return value; + } + return { seed: before, output: canonical(output) }; + } finally { await ctx.fiber.dispose(); } +} + +const results = []; +for (const scenario of scenarios) { + const baseline = await run(scenario, false); + const routed = await run(scenario, true, baseline.seed); + assert.deepEqual(routed.output, baseline.output, `${scenario.name}: routed native must match stock DSH`); + results.push({ scenario: scenario.name, callsPerArm: routed.output.calls.length, generation: routed.output.generation, outcome: routed.output.error ?? 'success' }); +} +console.log(JSON.stringify({ result: 'passed', realDSH: JSON.parse(readFileSync(new URL('dsh-compaction-basic/package.json', root), 'utf8')).version, parityCases: results })); diff --git a/src/agent/dsh-compaction-disable.ts b/src/agent/dsh-compaction-disable.ts index 393d227251..94540d0742 100644 --- a/src/agent/dsh-compaction-disable.ts +++ b/src/agent/dsh-compaction-disable.ts @@ -45,6 +45,8 @@ // call: the #7062 refusal storm, the #7178 model-switch dead-end, and the // #7169 landed-checkpoint rebase clobber are all that engine firing. +import { configureNativeCompaction, selectiveCompactionEnabled } from "./dsh-native-compaction.js"; + /** The two dsh packages whose backends must not instantiate while bili owns the lane. */ const DSH_COMPACTION_BASIC_PACKAGE = "@deepseek-ai/dsh-compaction-basic"; const DSH_COMMAND_COMPACT_PACKAGE = "@deepseek-ai/dsh-command-compact"; @@ -90,6 +92,7 @@ const DSH_COMPACTION_VERDICT_KEY = "__BILI_DSH_COMPACTION_VERDICT__"; /** bili-native calls this from apply() when its plan keeps the lane owned. */ export function declareDshCompactionActive(): void { + configureNativeCompaction(); (globalThis as Record)[DSH_COMPACTION_VERDICT_KEY] = "active"; } @@ -231,6 +234,30 @@ export function disableBasicCompaction(rows: readonly unknown[]): unknown[] { }); } +export function selectiveBasicCompaction(rows: readonly unknown[]): unknown[] { + const adapter = "billion-context/dsh-native-compaction"; + let attached = false; + function visit(group: readonly unknown[]): unknown[] { + let backendHere = false; + let adapterHere = false; + const result = group.map(row => { + if (!row || typeof row !== "object") return row; + const r = row as PresetRow & { disabled?: boolean }; + if (r.disabled) return row; + if (r.name === adapter) adapterHere = true; + if (r.name === DSH_COMPACTION_BASIC_PACKAGE) backendHere = true; + if (r.group && Array.isArray(r.config)) return { ...r, config: visit(r.config) }; + return row; + }); + if (backendHere && !adapterHere) result.push({ name: adapter }); + attached ||= backendHere || adapterHere; + return result; + } + const result = visit(rows); + if (!attached) result.push({ name: adapter, config: { noBackend: true } }); + return result; +} + // #7190: registered symbol so the wrap marker survives the bundle/host realm // split and a re-apply never double-wraps the same registry instance. const PRESET_REGISTER_WRAP_MARK = Symbol.for("bili.dshPresetRegisterWrapped"); @@ -271,9 +298,9 @@ export function disableRuntimePresetCompaction(definition: unknown): unknown { if (typeof def.id !== "string" || !Array.isArray(def.plugins)) return definition; if (!isDshCompactionActive()) return definition; const rows = countCompactionRows(def.plugins as readonly unknown[]); - if (rows === 0) return definition; + if (rows === 0 && !selectiveCompactionEnabled()) return definition; noteRuntimePresetCoverage(def.id.slice(0, 120), rows); - return { ...def, plugins: disableBasicCompaction(def.plugins as readonly unknown[]) }; + return { ...def, plugins: selectiveCompactionEnabled() ? selectiveBasicCompaction(def.plugins) : disableBasicCompaction(def.plugins) }; } /** @@ -339,12 +366,15 @@ export function registerCompactionDisable(ctx: CompactionDisableHost): void { // their resolved config object identity. const config = (resolved ?? {}) as { plugins?: unknown }; if (!Array.isArray(config.plugins)) return resolved; - const compactionRows = countCompactionRows(config.plugins); - if (compactionRows === 0) return resolved; const rawName = entryNameOf(fiber); const entryName = typeof rawName === "string" ? rawName : "unnamed-entry"; + const compactionRows = countCompactionRows(config.plugins); + if (compactionRows === 0) { + if (!selectiveCompactionEnabled() || entryName !== DSH_AGENT_PRESET_PACKAGE) return resolved; + return { ...config, plugins: selectiveBasicCompaction(config.plugins) }; + } noteGateCoverage(entryName.slice(0, 120), compactionRows, entryName === DSH_AGENT_PRESET_PACKAGE); - return { ...config, plugins: disableBasicCompaction(config.plugins) }; + return { ...config, plugins: selectiveCompactionEnabled() ? selectiveBasicCompaction(config.plugins) : disableBasicCompaction(config.plugins) }; }, { global: true }); } // Publish only after the middleware is registered; the host owns both lifetimes. diff --git a/src/agent/dsh-native-client.ts b/src/agent/dsh-native-client.ts index f4a074173c..191902f33a 100644 --- a/src/agent/dsh-native-client.ts +++ b/src/agent/dsh-native-client.ts @@ -506,6 +506,7 @@ function detectHostTheme(): "light" | "dark" | undefined { } const zh: Dict = { + "native_compaction": "当前模型使用 DSH 原生压缩,bili 未参与本轮上下文处理。", "nav": "bili设置", "title": "billion-context 压缩代理", "open": "打开 Web UI", @@ -535,6 +536,7 @@ const zh: Dict = { }; const en: Dict = { + "native_compaction": "This model uses DSH native compaction. bili is inactive for its current requests.", "nav": "bili", "title": "billion-context compression proxy", "open": "Open Web UI", @@ -816,7 +818,17 @@ export function apply(ctx: ClientContext): void { if (origin === undefined) return; let cancelled = false; const load = (): void => { - void fetch(`${origin}${statusPath}`) + const loadStatus = async (): Promise => { + const selective = (globalThis as { __BILI__?: { selectiveCompaction?: boolean } }).__BILI__?.selectiveCompaction; + if (!selective || hostSessionId === undefined) return fetch(`${origin}${statusPath}`); + const response = await fetch(`${winningProbeForm ?? ORIGIN_PATH}?sessionId=${encodeURIComponent(hostSessionId)}`); + if (!response.ok) throw new Error(`Policy HTTP ${response.status}`); + const policy = await response.json() as { conversationId?: string; nativeCompaction?: boolean }; + if (policy.nativeCompaction) return new Response(JSON.stringify({ ok: true, phase: "native-compaction", conversationId: hostSessionId })); + if (!policy.conversationId) throw new Error("Session compaction policy is not available yet"); + return fetch(`${origin}/__bili/plugin/status?conversationId=${encodeURIComponent(policy.conversationId)}`); + }; + void loadStatus() .then((res) => { // #3693: a non-ok answer carries no contract body — // surface its status code instead of parsing it blind. @@ -885,7 +897,9 @@ export function apply(ctx: ClientContext): void { ? null : renderProbeError(t, error, copied, () => startCopy(error)); let middle: unknown; - if (origin === undefined) { + if (status?.phase === "native-compaction") { + middle = hintP("native_compaction"); + } else if (origin === undefined) { middle = hintP("degraded"); } else if (remoteBlocked) { middle = renderRemoteBlock(t, origin, errorBox(liveEmbedError)); diff --git a/src/agent/dsh-native-compaction.ts b/src/agent/dsh-native-compaction.ts new file mode 100644 index 0000000000..f336a695cb --- /dev/null +++ b/src/agent/dsh-native-compaction.ts @@ -0,0 +1,148 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { loadConfigFile } from "../config.js"; + +export type NativeModelRule = { provider?: string; model: string }; +type Target = { provider?: unknown; model?: unknown }; +export type PolicyAgent = { + model?: { current: () => Target | undefined }; + session?: { + id?: unknown; + surface?: { replaceGeneration: number }; + requestHeader?: () => { config?: Target } | undefined; + }; +}; +type PolicyState = { + rules: readonly NativeModelRule[]; + generationIsolation: boolean; + summary: AsyncLocalStorage; + ready: Set; +}; +const key = Symbol.for("billion-context.dsh-native-compaction.v1"); +function state(): PolicyState { + const globals = globalThis as typeof globalThis & { [key]?: PolicyState }; + return globals[key] ??= { rules: [], generationIsolation: false, summary: new AsyncLocalStorage(), ready: new Set() }; +} + +export function configureNativeCompaction(value: unknown = loadConfigFile().dsh?.nativeCompactionModels): void { + if (value === undefined) { state().rules = []; state().generationIsolation = false; return; } + if (!Array.isArray(value)) throw new Error("dsh.nativeCompactionModels must be an array"); + state().rules = value.map((row: unknown) => { + if (!row || typeof row !== "object") throw new Error("native compaction rule must be an object"); + const r = row as Record; + if (Object.keys(r).some(k => k !== "provider" && k !== "model") || + typeof r.model !== "string" || !r.model || r.model === "*" || /\s/.test(r.model) || + r.model.slice(0, -1).includes("*") || + (r.provider !== undefined && (typeof r.provider !== "string" || !r.provider || r.provider.includes("*")))) { + throw new Error("native compaction rules require a model ID (optional trailing *) and optional exact provider ID"); + } + return Object.freeze({ model: r.model, ...(r.provider === undefined ? {} : { provider: r.provider as string }) }); + }); + state().generationIsolation = true; +} + +export function selectiveCompactionEnabled(): boolean { return state().rules.length > 0; } +export function compactionGenerationIsolation(): boolean { return state().generationIsolation; } +export function nativeModel(target: Target | undefined): boolean { + if (typeof target?.model !== "string") return false; + const model = target.model; + return state().rules.some(r => (r.provider === undefined || r.provider === target.provider) && + (r.model.endsWith("*") ? model.startsWith(r.model.slice(0, -1)) : model === r.model)); +} +export function nativeAgent(agent: PolicyAgent | undefined): boolean { + if (!selectiveCompactionEnabled()) return false; + return nativeModel(agent?.model?.current() ?? agent?.session?.requestHeader?.()?.config); +} +export function nativeSummaryActive(): boolean { return state().summary.getStore() === true; } +export function requireNativeCompactionReady(agent: PolicyAgent | undefined): void { + if (typeof agent?.session?.id !== "string" || !state().ready.has(agent.session.id)) { + throw new Error("bili: native compaction policy is not attached to this DSH agent; no request was sent. Check the preset and restart DSH after installing the policy adapter."); + } +} + +/** The host's durable replacement generation survives restart and changes only + * when the model-visible prefix changes, never on ordinary appends/switches. */ +export function compactionConversationId(agent: PolicyAgent | undefined, sid: string): string { + if (!compactionGenerationIsolation()) return sid; + const generation = agent?.session?.surface?.replaceGeneration; + if (generation === undefined || !Number.isSafeInteger(generation) || generation < 0) { + throw new Error("bili: selective compaction requires DSH session.surface.replaceGeneration"); + } + return generation === 0 ? sid : `${sid}|dsh-generation:${generation}`; +} + +type Block = { type: string; id?: string; toolCallId?: string; text?: string; [key: string]: unknown }; +type Message = { role: string; content: readonly Block[]; [key: string]: unknown }; +type SummaryInput = { messages: readonly Message[]; tools?: readonly unknown[] }; +type SummaryResult = { summary: readonly Block[]; [key: string]: unknown }; +type Agent = PolicyAgent & { session: NonNullable }; +type Header = { config: Target; [key: string]: unknown }; +type Engine = { + compactIfNeeded(agent: Agent, trigger: string, signal?: AbortSignal): Promise; + compactPressure(agent: Agent, header: Header, signal?: AbortSignal, requireBelow?: boolean): Promise; + compactRegion(start: number, end: number, agent: Agent, signal?: AbortSignal): Promise; + compactNow(agent: Agent, signal?: AbortSignal, command?: unknown): Promise; + summarize(input: SummaryInput, agent: Agent, signal?: AbortSignal): Promise; +}; +type Host = { + compaction: Engine; + on(event: string, handler: (payload: { agent: Agent }, next: () => unknown) => unknown, options?: { prepend: boolean }): unknown; + effect?(effect: () => (() => void)): void; + inject?(services: readonly string[], callback: (ctx: Host) => void): unknown; +}; + +export const name = "bili-native-compaction"; +export const inject = []; +export function apply(ctx: Host, config: { noBackend?: boolean } = {}): void { + if (config.noBackend) { + const owned = new Set(); + ctx.on("agent/pre-step", ({ agent }, next) => { + if (typeof agent.session.id !== "string") throw new Error("bili: native policy requires a session ID"); + owned.add(agent.session.id); + state().ready.add(agent.session.id); + return next(); + }, { prepend: true }); + ctx.effect?.(() => () => { for (const id of owned) state().ready.delete(id); }); + return; + } + if (ctx.inject) ctx.inject(["compaction"], attachEngine); + else attachEngine(ctx); +} + +function attachEngine(ctx: Host): void { + const engine = ctx.compaction; + const methods = ["compactIfNeeded", "compactPressure", "compactRegion", "compactNow", "summarize"] as const; + for (const method of methods) if (typeof engine[method] !== "function") throw new Error(`bili: unsupported DSH compaction API: ${method}`); + const originals = Object.fromEntries(methods.map(m => [m, engine[m]])) as Pick; + const owned = new Set(); + const markReady = (agent: Agent) => { + if (typeof agent.session.id !== "string") throw new Error("bili: native compaction agent has no session ID"); + owned.add(agent.session.id); + state().ready.add(agent.session.id); + }; + const allow = (agent: Agent) => { markReady(agent); return nativeAgent(agent); }; + engine.compactIfNeeded = async (agent, trigger, signal) => allow(agent) ? originals.compactIfNeeded.call(engine, agent, trigger, signal) : null; + engine.compactPressure = async (agent, header, signal, below) => { + markReady(agent); + return nativeModel(header.config) ? originals.compactPressure.call(engine, agent, header, signal, below) : null; + }; + engine.compactRegion = async (start, end, agent, signal) => { + if (!allow(agent)) throw new Error("bili owns compaction for the selected model; use its compression tools"); + return originals.compactRegion.call(engine, start, end, agent, signal); + }; + engine.compactNow = async (agent, signal, command) => { + if (!allow(agent)) throw new Error("bili owns compaction for the selected model; use its compression tools"); + return originals.compactNow.call(engine, agent, signal, command); + }; + engine.summarize = async (input, agent, signal) => { + if (!allow(agent)) throw new Error("bili: native summary refused for a bili-owned model"); + return state().summary.run(true, () => originals.summarize.call(engine, input, agent, signal)); + }; + ctx.on("agent/pre-step", ({ agent }, next) => { + markReady(agent); + return next(); + }, { prepend: true }); + ctx.effect?.(() => () => { + for (const id of owned) state().ready.delete(id); + for (const method of methods) Object.defineProperty(engine, method, { value: originals[method], configurable: true, writable: true }); + }); +} diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 724559ac4c..87a7a0887f 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -1,3 +1,5 @@ +import { compactionConversationId, compactionGenerationIsolation, nativeAgent, nativeModel, nativeSummaryActive, requireNativeCompactionReady } from "./dsh-native-compaction.js"; + // Native dsh (deepseek-harness) cordis plugin (#941): full plugin-mode // compression for dsh WITHOUT a launcher — bare `dsh` with this plugin // installed via `bili plugin install dsh` (cordis.patch.yml entry) or @@ -107,8 +109,10 @@ function regBackoffMs(failStreak: number): number { } type AgentLike = { + model?: { current: () => { provider?: unknown; model?: unknown } | undefined }; session?: { id?: unknown; + surface?: { replaceGeneration: number }; // #2381: dsh-session Session surface — the EpochHeader the NEXT request // is compared against ({config:{provider,model,...}}). dsh-agent-loop // writes each step's header into the session log BEFORE its fetch, so @@ -155,7 +159,7 @@ type ToolDefinition = { type CommandOutcome = { kind: "success" | "error"; text: string }; export type PluginContext = { - tools: { register: (definition: ToolDefinition) => unknown; get?: (name: string) => unknown }; + tools: { register: (definition: ToolDefinition, options?: { when: (context: { agent?: AgentLike; modelSelection?: { provider?: unknown; model?: unknown } }) => boolean }) => unknown; get?: (name: string) => unknown }; commands: { register: (command: { name: string; description: string; handler: (invocation?: CommandInvocation) => Promise }) => unknown }; agents: { currentInitiator?: () => AgentLike | undefined; get?: (id: string) => AgentLike | undefined }; // Runtime-info sources (#955), resolved via dynamic ctx.inject when the @@ -925,6 +929,7 @@ function toolDefinition(tool: ManifestTool): ToolDefinition { render: (_args, value) => [{ type: "text", text: typeof value === "string" ? value : String(value ?? "") }], }, execute: async (args, exec) => { + if (nativeAgent(exec.agent)) throw new Error("bili compression tools are unavailable for a native-compaction model"); // #983: read the LIVE base — a respawn after a proxy death moves // the origin, and a captured base would keep firing at a dead port. const base = register.base; @@ -935,7 +940,7 @@ function toolDefinition(tool: ManifestTool): ToolDefinition { if (typeof sid !== "string" || sid.length === 0) { throw new Error(`bili tool ${tool.name} requires an owning agent session`); } - const out = await forwardTool(base, sid, tool.name, args, exec.signal, true, exec.callId); + const out = await forwardTool(base, compactionConversationId(exec.agent, sid), tool.name, args, exec.signal, true, exec.callId); // #2204: dsh tool results are plain strings — a business failure // throws so the host renders an error, not success text. if (out.failed) throw new Error(out.text); @@ -1014,7 +1019,7 @@ function restoreTools(owner: ToolsOwner): void { // a restart or dispose removes it and tools/change lets the next // activation restore (#6702). Proxy death runs no effect — the // registration survives it (#3380). - owner.ctx.tools.register(definition); + owner.ctx.tools.register(definition, { when: ({ agent, modelSelection }) => !compactionGenerationIsolation() || !nativeModel(modelSelection ?? agent?.model?.current() ?? agent?.session?.requestHeader?.()?.config) }); } catch (err) { if (!errMessage(err).includes("already registered")) throw err; adopted++; @@ -1258,6 +1263,9 @@ type GateAttribution = interface LlmDispatchScope { sid: string; msgIds: string[] | undefined; + nativeCompaction?: boolean; + conversationId?: string; + auxiliary?: boolean; // #6525: the raw host message list (pi-ai shape: {id, role, content, // toolCallId}) — the full-resend envelope stamps biliMsgIds from these // by lockstep fingerprint walk, not from the id array alone (pairing @@ -1269,6 +1277,13 @@ interface LlmDispatchScope { } const dispatchScope = new AsyncLocalStorage(); +function compactionAgentOf(ctx: PluginContext, sid: string): AgentLike | undefined { + const direct = ctx.agents.get?.(sid); + if (direct?.session?.id === sid) return direct; + const ambient = ctx.agents.currentInitiator?.(); + return ambient?.session?.id === sid ? ambient : undefined; +} + let noticedScopedAttribution = false; // #6770: the #3962 coverage readout only ever rode the profile-bundle note, // which stays silent wherever profileContext.startedBundles cannot be read @@ -1801,6 +1816,7 @@ function latestSessionNote(status: Record, requestedSid: string } async function statusOutcome(ctx: PluginContext, invocation?: CommandInvocation): Promise { + if (compactionGenerationIsolation() && nativeAgent(invocation?.agent ?? ctx.agents.currentInitiator?.())) return { kind: "success", text: "This model uses DSH native compaction. bili compression is inactive for this session's current model." }; const base = register.base; if (!base) { // #3380 P3: toolsReady implies a proxy WAS serving this session — a @@ -1828,7 +1844,8 @@ async function statusOutcome(ctx: PluginContext, invocation?: CommandInvocation) // agent session id; fall back to ALS attribution, then the latest-session fallback. const sid = invocationSidOf(invocation) ?? sessionIdOf(ctx); let fellBackToLatest = false; - let status: Record | undefined = sid !== undefined ? await fetchStatus(base, sid) : undefined; + const cid = sid === undefined || !compactionGenerationIsolation() ? sid : compactionConversationId(invocation?.agent ?? ctx.agents.get?.(sid) ?? ctx.agents.currentInitiator?.(), sid); + let status: Record | undefined = cid !== undefined ? await fetchStatus(base, cid) : undefined; if (status === undefined) { fellBackToLatest = true; status = await fetchStatusLatest(base); @@ -1873,6 +1890,7 @@ async function statusOutcome(ctx: PluginContext, invocation?: CommandInvocation) * API passes no arguments, so this lane always shows the default * (summary-ledger) report — no `full`. */ async function cacheOutcome(ctx: PluginContext, invocation?: CommandInvocation): Promise { + if (compactionGenerationIsolation() && nativeAgent(invocation?.agent ?? ctx.agents.currentInitiator?.())) return { kind: "success", text: "This model uses DSH native compaction; bili has no cache statistics for its direct requests." }; const base = register.base; if (!base) { return { @@ -1884,7 +1902,7 @@ async function cacheOutcome(ctx: PluginContext, invocation?: CommandInvocation): // #1677: same session-resolution fix as /acp — the command path carries no ALS // attribution, so prefer the invocation's agent session id over currentInitiator(). const sid = invocationSidOf(invocation) ?? sessionIdOf(ctx); - let target = sid; + let target = sid === undefined || !compactionGenerationIsolation() ? sid : compactionConversationId(invocation?.agent ?? ctx.agents.get?.(sid) ?? ctx.agents.currentInitiator?.(), sid); let fallbackNote: string | undefined; if (target === undefined) { try { @@ -2122,6 +2140,7 @@ export async function apply(ctx: PluginContext): Promise { // gate + optional custom label), read live on every call so a web-settings // edit lands on the next page load without a proxy restart. const withCtxTabFace = (base: Record): Record => { + if (compactionGenerationIsolation()) base.selectiveCompaction = true; base.contextTab = dshContextTabEnabled(); const label = dshContextTabLabel(); if (label !== undefined) base.contextTabLabel = label; @@ -2169,13 +2188,25 @@ export async function apply(ctx: PluginContext): Promise { const originRoute = { kind: "exact" as const, path: "/bili/origin", - handler: (_req: unknown, res: { writeHead: (status: number, headers?: Record) => void; end: (body?: string) => void }): void => { + handler: (req: unknown, res: { writeHead: (status: number, headers?: Record) => void; end: (body?: string) => void }): void => { const origin = currentOrigin(); // #3373: relay mode ⇒ the client derives its base from the probe // response URL itself; the loopback origin is useless (and leaky) // to a remote browser. #4237: same Context-tab face flags as the // snapshot row. - const body = JSON.stringify(withCtxTabFace(origin !== undefined && adminRelayEnabled() ? { origin: null, relay: true } : { origin: origin ?? null })); + const face = withCtxTabFace(origin !== undefined && adminRelayEnabled() ? { origin: null, relay: true } : { origin: origin ?? null }); + if (compactionGenerationIsolation()) { + const raw = (req as { url?: unknown })?.url; + const sid = typeof raw === "string" ? new URL(raw, "http://localhost").searchParams.get("sessionId") : null; + if (sid) { + const agent = ctx.agents.get?.(sid); + if (agent) { + face.conversationId = compactionConversationId(agent, sid); + face.nativeCompaction = nativeAgent(agent); + } + } + } + const body = JSON.stringify(face); res.writeHead(200, { "content-type": "application/json" }); res.end(body); }, @@ -2201,24 +2232,29 @@ export async function apply(ctx: PluginContext): Promise { if (typeof ctx.inject === "function" && typeof ctx.on === "function") { const onEvent = ctx.on.bind(ctx); ctx.inject(["llm"], () => { - onEvent("llm/stream", (options: { sessionId?: unknown; messages?: unknown; purpose?: unknown }, next: () => AsyncIterable) => { + onEvent("llm/stream", (options: { sessionId?: unknown; messages?: unknown; provider?: unknown; model?: unknown; purpose?: unknown }, next: () => AsyncIterable) => { const sid = typeof options?.sessionId === "string" && options.sessionId.length > 0 ? options.sessionId : undefined; if (sid === undefined) return next(); // #4491: capture the host message ids riding the same options // — undefined (all-or-nothing) when any message lacks a usable // id, so sidecar shapes degrade to id-less turns. + const agent = compactionGenerationIsolation() ? compactionAgentOf(ctx, sid) : undefined; + const native = nativeSummaryActive() || (options.purpose === "compaction" ? nativeAgent(agent) : nativeModel(options)); + const auxiliary = typeof options.purpose === "string" && options.purpose.length > 0 && options.purpose !== "conversation" && options.purpose !== "compaction"; + if (native && !nativeSummaryActive() && !auxiliary) requireNativeCompactionReady(agent); + const conversationId = native || auxiliary ? sid : compactionConversationId(agent, sid); // #6880: capture the dispatch's declared purpose the same way // (dsh sets it on every auxiliary call; conversation leaves it // unset). Absent/odd values simply stay off the turn. const purpose = typeof options?.purpose === "string" && options.purpose.length > 0 && options.purpose.length <= 64 && /^[\x21-\x7e]+$/.test(options.purpose) ? options.purpose : undefined; - const scope: LlmDispatchScope = { sid, msgIds: hostMsgIdsOf(options?.messages), messages: options?.messages, purpose }; + const scope: LlmDispatchScope = { sid, msgIds: hostMsgIdsOf(options?.messages), nativeCompaction: native, conversationId, auxiliary, messages: options?.messages, purpose }; // #5403/#5418 v3: feed the per-slot id sequence into the // watermark channel (the fetch chokepoint emits count + // tail-ids; core = pf-channel.ts) — "?" slots ride id-less // elements without poisoning the rest. A failed resolution // (no usable message list at all) CLEARS like every other // adapter — never ride a stale one. - pfChannel.pfCaptureIds(sid, pfSlotIdsOf(options?.messages)); + if (!native) pfChannel.pfCaptureIds(conversationId, pfSlotIdsOf(options?.messages)); // next() may start the adapter's fetch eagerly (inside this // call), and lazy continuations resume on each advance — // runLlmDispatch covers the former, wrapScopedIterable the @@ -2527,6 +2563,7 @@ export async function apply(ctx: PluginContext): Promise { } return refuse(url, attr, body); }; + state.nativeCompactionBypass = () => dispatchScope.getStore()?.nativeCompaction === true || nativeSummaryActive(); state.takeoverGate = (url, body, init) => { // #1295: an operator-declared endpoint is explicitly "this URL IS my // model API" — declaration outranks heuristic attribution (a provider @@ -2743,7 +2780,9 @@ export async function apply(ctx: PluginContext): Promise { // sent (the proxy-side exact-match gate stays as defense in depth). const target = sessionModelTargetOf(ctx) ?? globalModelTarget(modelInfo.services); refreshModelInfo(register.base, target); - const headers: Record = { "x-bili-plugin": "dsh", "x-bili-plugin-conversation": sid }; + const scopedId = dispatchScope.getStore()?.conversationId; + const agent = compactionGenerationIsolation() && scopedId === undefined ? compactionAgentOf(ctx, sid) : undefined; + const headers: Record = { "x-bili-plugin": "dsh", "x-bili-plugin-conversation": scopedId ?? compactionConversationId(agent, sid) }; // #6880: the declared purpose rides its own header (ASCII-gated like // the model header below — an odd value degrades to no header, and // the server falls back to its content heuristics). Post-#6883 this is @@ -2754,6 +2793,11 @@ export async function apply(ctx: PluginContext): Promise { // the header alone and keys declared main traffic on the raw session // id (no persona-order ladder); the sentinel itself is not a side. const declaredPurpose = attr.purpose ?? "conversation"; + const dispatch = dispatchScope.getStore(); + if (compactionGenerationIsolation() && dispatch?.sid === sid && !dispatch.nativeCompaction && + declaredPurpose === "conversation" && dispatch.msgIds?.length && dispatch.conversationId === headers["x-bili-plugin-conversation"]) { + headers["x-bili-dsh-generation-owner"] = sid; + } const purposeHeader = asciiHeaderValue(declaredPurpose); if (purposeHeader !== undefined) headers["x-bili-plugin-purpose"] = purposeHeader; // #3370: the incremental-turn marker (and, since #3329, the turn id) @@ -2797,6 +2841,16 @@ export async function apply(ctx: PluginContext): Promise { // body to its incremental form when the lane advertises the feature — // init.body mutation propagates through withHeaders/send untouched. state.beforeSend = async (url, init) => { + // Each host replacement starts a fresh bili substrate. Do not carry a + // negotiated alias, fork adoption or incremental seed across that boundary. + if (compactionGenerationIsolation()) { + if (dispatchScope.getStore()?.auxiliary) return; + const attr = attributionOf(ctx); + if (attr.state === "ok") { + const id = dispatchScope.getStore()?.conversationId ?? compactionConversationId(compactionAgentOf(ctx, attr.sid), attr.sid); + if (id !== attr.sid) return; + } + } // #4082 review: learn + stamp run FIRST — the boundary fingerprint // must come from the ORIGINAL full history; fork-adopt and the // incremental swap both rewrite init.body afterwards (the delta form diff --git a/src/agent/native-intercept.ts b/src/agent/native-intercept.ts index ededfe7b1d..a95930c69f 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -135,6 +135,8 @@ export interface NativeInterceptState { * A wrong model's window is worse than none: resolve per request or * stay silent. */ declaredWindowForDirect?: () => number | undefined; + /** Explicit host-owned compression; unlike degraded direct, no bili mutations or refusals. */ + nativeCompactionBypass?: () => boolean; /** #3248 incremental turns: response hook — fired with the routed * Response BEFORE it is returned to the host, so response headers are * readable without consuming the stream. Native hosts use it to read @@ -1697,6 +1699,10 @@ export function installNativeFetchIntercept(initialState: NativeInterceptState): } return send(input, init); } + if (state.nativeCompactionBypass?.()) { + const direct = routedBiliModelUrl(url); + return send(direct === undefined ? input : typeof input === "string" || input instanceof URL ? direct : new Request(direct, input), init); + } // #1268: hold the request until the host's ACP tool registration has // finished its first attempt, so headersFor can stamp it into plugin // mode. Steady state costs nothing (gate already resolved). A timeout diff --git a/src/agent/native-ws-intercept.ts b/src/agent/native-ws-intercept.ts index 3bf940af93..2228fcdeba 100644 --- a/src/agent/native-ws-intercept.ts +++ b/src/agent/native-ws-intercept.ts @@ -160,9 +160,9 @@ export function rewriteCodexResponsesWsUrl(target: string, origin: string): stri return `${proxyWs}/bili/${target}`; } -function prepareWsFrames(socket: WsInstanceLike, target: string, state: NativeInterceptState, identity: Record | undefined, origin: NativeInterceptState["wsOrigin"], generation: unknown): WsInstanceLike { +function prepareWsFrames(socket: WsInstanceLike, target: string, state: NativeInterceptState, identity: Record | undefined, origin: NativeInterceptState["wsOrigin"], generation: unknown, nativeCompaction = false): WsInstanceLike { const assertCurrent = (): void => { - if ((globalThis as GlobalRecord)[ACTIVE_STATE] !== state || (globalThis as GlobalRecord)[ACTIVE_STATE_SEQ] !== generation || (state.wsOrigin ?? state.origin) !== origin) { + if ((globalThis as GlobalRecord)[ACTIVE_STATE] !== state || (globalThis as GlobalRecord)[ACTIVE_STATE_SEQ] !== generation || (!nativeCompaction && (state.wsOrigin ?? state.origin) !== origin)) { throw new Error("bili-native(ws): plugin state/origin changed; reconnect before sending"); } }; @@ -181,6 +181,8 @@ function prepareWsFrames(socket: WsInstanceLike, target: string, state: NativeIn if (failed || socket.readyState !== 1) return; assertCurrent(); if (!isCreate || typeof data !== "string") return send(data); + if ((state.nativeCompactionBypass?.() === true) !== nativeCompaction) throw new Error("bili-native(ws): compaction owner changed; reconnect before sending"); + if (nativeCompaction) return send(data); if (state.toolsReady !== undefined) await withTimeout(state.toolsReady, state.readyTimeoutMs ?? 15_000); assertCurrent(); const init: RequestInit = { body: data, headers: identity === undefined ? undefined : { ...identity } }; @@ -560,6 +562,10 @@ export function installNativeWebSocketIntercept(initialState: NativeInterceptSta // plugin → pass through direct, never hit a disposed context. const state = (globalThis as GlobalRecord)[ACTIVE_STATE] as NativeInterceptState | undefined; if (target === undefined || state === undefined) return new RoutedWebSocket(url, ...rest); + if (state.nativeCompactionBypass?.()) { + return prepareWsFrames(new RoutedWebSocket(url, ...rest), target, state, undefined, + state.wsOrigin ?? state.origin, (globalThis as GlobalRecord)[ACTIVE_STATE_SEQ], true); + } // #5838: lanes arming the per-dispatch prep hooks (dsh: async // takeover verdict, tools-ready gate, fork-adoption beforeSend, // headersFor stamps) run them INSIDE the deferred window before the diff --git a/src/config.ts b/src/config.ts index cd0475ea94..511393fff3 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1226,6 +1226,8 @@ export type ProxyOptions = { * warning, and each is ignored with a once-per-process deprecation note * (warnRemovedDshAllowKey). */ interface DshFileSettings { + /** Explicit native-compaction models; optional trailing * matches a model family. */ + nativeCompactionModels?: Array<{ provider?: string; model: string }>; /** #3723/#3901: bili-authored compaction answers (ON by default since * the 0.1.203 dogfood window; `false` or env `BILI_DSH_AUTHORED_COMPACTION=0` * restores the #1729 refusal path). */ @@ -2830,7 +2832,7 @@ function warnRemovedDshAllowKey(obj: Record): void { // authoredCompaction (#3723/#3901), contextTab + contextTabLabel // (#4237) are the LIVE keys in the section — everything else found // here is removed/unknown and gets named. - const live = new Set(["authoredCompaction", "contextTab", "contextTabLabel"]); + const live = new Set(["authoredCompaction", "contextTab", "contextTabLabel", "nativeCompactionModels"]); for (const key of Object.keys(d as Record)) if (!live.has(key)) hits.push(`dsh.${key}`); } hits.sort(); diff --git a/src/dsh-generation-reuse.ts b/src/dsh-generation-reuse.ts new file mode 100644 index 0000000000..893e6f85e7 --- /dev/null +++ b/src/dsh-generation-reuse.ts @@ -0,0 +1,390 @@ +// A DSH replacement is a new ledger. Only the first full request can seed it. +// Wire witnesses are made before prepare: CoreMessage.id omits e.g. tool ids, +// signatures and media. Never infer that an older, unwitnessed fold is safe. +import { createHash } from "node:crypto"; +import { + BLOCKED_REF, + collectBlockContent, + createContentStore, + collectLatestProtected, + collectProtectedToolCallIds, + isMessageLatestProtected, + isMessageProtectedWithPairing, + type Config, + type CoreMessage, + type CompressionBlock, +} from "acp-kernel"; +import { openaiToCore, anthropicToCore } from "acp-kernel/wire"; +import { markDirty, type Session } from "./session.js"; +import { getStore } from "./persist.js"; +import { adoptContentStore, cloneStoreForRefs, contentStoreOf } from "./store.js"; + +const hash = (s: string) => createHash("sha256").update(s).digest("hex"); +type Witness = { + sid: string; + generation: number; + wire: string; + order: string[]; + hashes: Record; + ccr: Record; +}; +function witnessOf(s?: Session): Witness | undefined { + const w = s?.metadata.dshGenerationWitness as Partial | undefined; + return w && + typeof w.sid === "string" && + Number.isSafeInteger(w.generation) && + Array.isArray(w.order) && + w.hashes && + typeof w.hashes === "object" && + typeof w.wire === "string" + ? (w as Witness) + : undefined; +} +type Row = CoreMessage & { wireIndex?: number }; +export function generationScope(sid: unknown, cid: string) { + if (typeof sid !== "string" || !/^session-[a-zA-Z0-9-]{1,100}$/.test(sid)) return; + if (cid === sid) return { sid, generation: 0 }; + const prefix = sid + "|dsh-generation:"; + if (!cid.startsWith(prefix)) return; + const n = Number(cid.slice(prefix.length)); + if (Number.isSafeInteger(n) && n > 0 && prefix + n === cid) + return { sid, generation: n, parentId: n === 1 ? sid : prefix + (n - 1) }; +} + +// Conservative v1: only full OpenAI chat / Anthropic messages. An unknown, +// opaque or multipart media row remains visible even if its raw id matches. +function simple(row: Record) { + const parts = row.content; + if ( + Object.keys(row).some( + (k) => !["role", "content", "name", "tool_calls", "tool_call_id", "reasoning_content"].includes(k), + ) + ) + return false; + if (parts == null || typeof parts === "string") return true; + return ( + Array.isArray(parts) && + parts.every( + (p) => + p && + ((p.type === "text" && typeof p.text === "string") || + (p.type === "tool_use" && typeof p.name === "string") || + (p.type === "tool_result" && + (typeof p.content === "string" || + (Array.isArray(p.content) && + p.content.every((c: { type?: string }) => c?.type === "text"))))) && + !("signature" in p || "thoughtSignature" in p), + ) + ); +} + +function frame(wire: string, parsed: unknown) { + const body = parsed as { messages?: Record[] }; + if (!Array.isArray(body?.messages)) return; + let rows: Row[]; + if (wire === "openai") rows = openaiToCore(body as Parameters[0]).msgs; + else if (wire === "anthropic") rows = anthropicToCore(body as Parameters[0]).msgs; + else return; + const hashes: Record = {}; + const units = new Map(), + grouped = new Map(); + for (const m of rows) { + const i = m.wireIndex; + if (i === undefined || !body.messages[i]) continue; + const unit = grouped.get(i) ?? []; + unit.push(m.id); + grouped.set(i, unit); + if (!units.has(i)) units.set(i, simple(body.messages[i]!) ? hash(JSON.stringify(body.messages[i])) : ""); + const proof = units.get(i)!; + // Cluster suffixes are occurrence numbers, not host identities. Don't + // move a fold between indistinguishable duplicate occurrences. + hashes[m.id] = m.id in hashes ? "" : proof; + } + for (const m of rows) { + const base = m.id.replace(/^(h_[0-9a-f]+)_\d+$/, "$1"); + if (base !== m.id) { + hashes[base] = ""; + hashes[m.id] = ""; + } + } + return { rows, hashes, grouped }; +} + +function fresh(s: Session) { + return ( + s.stats.requests === 0 && + !s.state.blocks.length && + s.blockContents.size === 0 && + !Object.keys(s.state.messageRefs.byRaw).length && + !Object.keys(s.state.messageRefs.byRef).length && + !s.metadata.derivedFromSessionId && + !s.metadata.publicForkReceipt && + !s.state.lastPassIds?.length && + !s.metadata.dshGenerationWitness && + !s.pluginSnapshot?.length + ); +} + +// Called under the target lock, without yielding between source lookup, +// validation, staging and publication. No reusable stale plan handle. +export function visitGeneration( + target: Session, + scope: NonNullable>, + wire: string, + parsed: unknown, + config: Config, + parentOf: (id: string) => Session | undefined, + preview = false, +) { + const expected = generationScope(scope.sid, target.id); + if (!expected || expected.generation !== scope.generation || expected.parentId !== scope.parentId) return; + let view: ReturnType; + try { + view = frame(wire, parsed); + } catch { + /* Unsupported provider extension: normal prepare owns the request. */ + } + if (!view || !view.rows.length) { + if (!preview && target.metadata.dshGenerationWitness) { + delete target.metadata.dshGenerationWitness; + markDirty(target); + } + return; + } + const previous = witnessOf(target); + const hashes: Record = {}; + const known = previous?.wire === wire ? previous.hashes : {}; + for (const [id, digest] of Object.entries(view.hashes)) { + // An old installation may already have issued refs before observing + // the bytes. Never retroactively attest those ids. + hashes[id] = + id in known ? (known[id] === digest ? digest : "") : target.state.messageRefs.byRaw[id] ? "" : digest; + } + const witness: Witness = { + sid: scope.sid, + generation: scope.generation, + wire, + order: view.rows.map((m) => m.id), + hashes, + ccr: { ...previous?.ccr }, + }; + const storeOf = (s: Session) => + preview + ? (s.contentStore ?? + getStore().unifiedCcrFor(s.id) ?? + getStore().loadContentStore(s) ?? + createContentStore()) + : contentStoreOf(s); + const emptyTarget = !!scope.parentId && fresh(target) && !Object.keys(storeOf(target).byRef).length; + const p = scope.parentId && emptyTarget ? parentOf(scope.parentId) : undefined; + const old = witnessOf(p); + const rejected: Record = {}, + adopted: string[] = []; + if ( + p && + p.inFlight === 0 && + p.id === scope.parentId && + p.metadata.pluginAgent === "dsh" && + old?.sid === scope.sid && + old.generation === scope.generation - 1 && + old.wire === wire && + p.meta.upstreamOrigin === target.meta.upstreamOrigin + ) { + const refs = p.state.messageRefs; + const from = new Map(old.order.map((id, i) => [id, i])), + to = new Map(view.rows.map((m, i) => [m.id, i])); + const calls = collectProtectedToolCallIds(view.rows, config), + latest = collectLatestProtected(view.rows, config); + // A truncate can move a formerly old row to the current question. + const lastUser = view.rows.findLast((m) => m.role === "user" && m.contentType === "text")?.id; + const pairs = new Map(); + for (const m of view.rows) + if (m.toolCallId) { + const a = pairs.get(m.toolCallId) ?? []; + a.push(m); + pairs.set(m.toolCallId, a); + } + const store = storeOf(p); + const byId = new Map(p.state.blocks.map((b) => [b.blockId, b])); + const consumed = new Set(p.state.blocks.flatMap((b) => b.directBlockIds)); + const roots = p.state.blocks.filter( + (b) => b.active && !b.expanded && !b.retired && !b.restoredInline && !consumed.has(b.blockId), + ); + const counts = new Map(); + for (const b of roots) for (const id of b.effectiveMessageIds) counts.set(id, (counts.get(id) ?? 0) + 1); + const selected = new Set(), + selectedRefs = new Set(); + for (const root of roots) { + const ids = new Set(root.effectiveMessageIds), + closure = new Set(); + function check(b: CompressionBlock, ancestors: Set): string | undefined { + if (ancestors.has(b.blockId) || b.expanded || b.restoredInline || b.retired || (b !== root && b.active)) + return "dependency-conflict"; + if (closure.has(b.blockId)) return; + closure.add(b.blockId); + const originals = p!.blockContents.get(b.blockId); + if ( + !originals?.full.text || + !b.effectiveMessageIds.length || + originals.full.count !== b.effectiveMessageIds.length + ) + return "missing-original"; + const union = new Set([ + ...b.directMessageIds, + ...b.directBlockIds.flatMap((k) => byId.get(k)?.effectiveMessageIds ?? []), + ]); + if (union.size !== b.effectiveMessageIds.length || !b.effectiveMessageIds.every((id) => union.has(id))) + return "dependency-conflict"; + if (!b.directMessageIds.every((id) => b.effectiveMessageIds.includes(id))) return "dependency-conflict"; + let oldPos = -1, + newPos = -1; + const ordered = [...b.effectiveMessageIds].sort((a, c) => (from.get(a) ?? -1) - (from.get(c) ?? -1)); + if (ordered.some((id) => !from.has(id) || !to.has(id))) return "missing-source"; + for (const id of ordered) { + const a = from.get(id), + z = to.get(id); + if (a === undefined || z === undefined) return "missing-source"; + if (!ids.has(id) || counts.get(id)! > 1) return "overlap"; + if (a <= oldPos || z <= newPos) return "order-conflict"; + oldPos = a; + newPos = z; + if (!old!.hashes[id] || old!.hashes[id] !== view!.hashes[id]) return "unproven-content"; + const m = view!.rows[z]!, + ref = refs.byRaw[id]; + if (id === lastUser || z === view!.rows.length - 1) return "protected"; + if ( + !ref || + ref === BLOCKED_REF || + refs.byRef[ref] !== id || + isMessageProtectedWithPairing(m, config, calls) || + isMessageLatestProtected(m, latest) + ) + return "protected"; + if (!view!.grouped.get(m.wireIndex!)?.every((k) => ids.has(k))) return "split-wire-unit"; + if (m.toolCallId) { + const pair = pairs.get(m.toolCallId)!; + if ( + pair.length !== 2 || + pair[0]?.contentType !== "tool-call" || + pair[1]?.contentType !== "tool-result" || + !pair.every((x) => ids.has(x.id)) + ) + return "tool-pair"; + } + const entry = store.byRef[ref]; + // CCR is optional. Distinguish "never stored" (full + // block archive below is authoritative) from a lost payload. + if (old!.ccr?.[id] && old!.ccr[id] !== entry?.hash) return "missing-original"; + if ( + entry && + (entry.rawId !== id || + store.byHash[entry.hash] !== (m.text ?? "") || + hash(store.byHash[entry.hash]!) !== entry.hash) + ) + return "missing-original"; + } + let pos = 0; + for (const id of ordered) { + const m = view!.rows[to.get(id)!]!; + const plain = collectBlockContent(p!.state, { ...b, effectiveMessageIds: [id] }, [m], { + full: true, + }).text; + const header = plain.slice(0, plain.indexOf("\n") + 1); + if (!originals.full.text.startsWith(header, pos)) return "missing-original"; + pos += header.length; + const marker = /\x3cacp(?: [a-z_]+="[^"\x3c\x3e\n]{0,128}")\x3e(m\d+)\x3c\/acp\x3e\n/y; + marker.lastIndex = pos; + const match = marker.exec(originals.full.text); + if (match && match[1] === refs.byRaw[id]) pos = marker.lastIndex; + const text = m.text ?? ""; + if (!originals.full.text.startsWith(text, pos)) return "missing-original"; + pos += text.length; + if (id !== ordered.at(-1)) { + if (!originals.full.text.startsWith("\n\n", pos)) return "missing-original"; + pos += 2; + } + } + if (pos !== originals.full.text.length) return "missing-original"; + for (const id of b.directBlockIds) { + const child = byId.get(id); + if (!child || !child.effectiveMessageIds.every((k) => b.effectiveMessageIds.includes(k))) + return "dependency-conflict"; + const issue = check(child, new Set([...ancestors, b.blockId])); + if (issue) return issue; + } + } + let issue = check(root, new Set()); + for (const bid of closure) { + const b = byId.get(bid)!; + // Do not rewrite free text. A dangling citation disqualifies + // the block; all inherited references retain their old names. + for (const [ref] of (b.summary + " " + (b.previousSummary ?? "")).matchAll(/\b(?:m\d{4,}|b\d+)\b/g)) { + if (!(ref.startsWith("m") ? ids.has(refs.byRef[ref]!) : closure.has(ref))) + issue ??= "unresolved-citation"; + } + } + if (issue) { + rejected[root.blockId] = issue; + continue; + } + adopted.push(root.blockId); + for (const id of closure) selected.add(id); + for (const id of ids) selectedRefs.add(refs.byRaw[id]!); + } + if (selected.size && !preview) { + const entries = [...selected].map((id) => { + const b = structuredClone(byId.get(id)!); + // Seq intervals refer to the OLD unified transcript. Only + // exact raw-id membership is valid in the child. + delete b.startSeq; + delete b.endSeq; + return { b, original: structuredClone(p.blockContents.get(id)!) }; + }); + const slice = cloneStoreForRefs(store, selectedRefs); + // Reserve even dead ref seats: a future ledgerSeq assignment + // may choose a hole below the ordinary high-water mark. + const refMap = structuredClone(refs); + for (const [id, ref] of Object.entries(refMap.byRaw)) { + if (ref !== BLOCKED_REF && (!old.hashes[id] || old.hashes[id] !== view.hashes[id])) { + delete refMap.byRaw[id]; + if (refMap.byRef[ref] === id) { + const seat = "dsh-reserved:" + ref; + refMap.byRef[ref] = seat; + refMap.byRaw[seat] = ref; + } + } + } + target.state.messageRefs = refMap; + target.state.nextBlockId = p.state.nextBlockId; + target.state.nextRunId = p.state.nextRunId; + for (const { b, original } of entries) { + target.state.blocks.push(b); + target.blockContents.set(b.blockId, original); + } + if (slice) { + for (const entry of Object.values(slice.byRef)) witness.ccr[entry.rawId] = entry.hash; + adoptContentStore(target, slice); + } + target.metadata.dshGenerationParent = p.id; + } + } + if (!preview) { + target.metadata.dshGenerationWitness = witness; + markDirty(target); + } + return { + adopted, + rejected, + skipped: !scope.parentId + ? "base-generation" + : !emptyTarget + ? "existing-target" + : !p + ? "missing-parent" + : !old + ? "unwitnessed-parent" + : p.inFlight + ? "parent-busy" + : undefined, + }; +} diff --git a/src/persist.ts b/src/persist.ts index f335e2ff69..6aa92114d0 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -2079,7 +2079,7 @@ export class SessionStore { * excluded by seqByRaw itself — their legacy refs stay put. */ private maybeRestampToLedger(session: Session): void { const state = session.state as (CompressionState & { refLedgerAligned?: boolean }); - if (state.refLedgerAligned === true) return; + if (state.refLedgerAligned === true || session.metadata.dshGenerationParent !== undefined) return; // inherited citations retain parent numbering if (!state.messageRefs || Object.keys(state.messageRefs.byRaw).length === 0) return; try { const seqByRawId = this.unifiedSeqByRaw(session.id); diff --git a/src/server/handle.ts b/src/server/handle.ts index ce0da3d428..3013dfe95f 100644 --- a/src/server/handle.ts +++ b/src/server/handle.ts @@ -49,6 +49,7 @@ function onSessionResolveEvent(rawId: string, r: SessionOrderResolution): void { import { prefixAffinity, describeResumeMiss, type AnonymousAffinity } from "../prefix-affinity.js"; import { buildAnonymousProvenance, type AnonymousProvenance } from "../anon-provenance.js"; import { maybeAdoptForkBlocks, maybeAdoptResume, maybeAdoptDerivedFork } from "../fork-adoption.js"; +import { generationScope, visitGeneration } from "../dsh-generation-reuse.js"; import { executeThreadsReforge, threadsBetaToDecline } from "./threads-lane.js"; import { resetThreadTailTracking } from "./thread-tracking.js"; import { resolveClaudeTranscriptLineage } from "../claude-transcript-lineage.js"; @@ -188,6 +189,7 @@ function persistLineageLinkNow(session: Session): void { * lookup miss read as "compression chose not to", and a line per request would * be noise on a stream that re-sends the same id every turn. */ const vertexModelNormalised = new Set(); +const generationAwaitingSave = new WeakSet(); const VERTEX_MODEL_LOG_CAP = 64; export async function handle( @@ -372,6 +374,8 @@ async function handleRequest( admission: DecodedRequestAdmission, decodingSignal: AbortSignal, ): Promise { + const generationOwner = req.headers["x-bili-dsh-generation-owner"]; + delete req.headers["x-bili-dsh-generation-owner"]; // host-to-proxy evidence, never forward // #1073/#3245: an absolute-form request addressed to THIS instance's own // endpoint is a fetch of us, not a tunnel — strip the authority so every // downstream stage (admin gate, /bili/ tunnel admission, protocol detection) @@ -2034,6 +2038,10 @@ async function handleRequest( // be able to reload from the DB instead of starting a fresh session. const session = await getSessionAsync(sessionId, { protocol, upstreamOrigin, label: clientLabel ?? (anonAffinity ? `prefix-affinity ${anonAffinity.tailHash.slice(0, 8)}` : undefined) }); memProbe(opts.debug, log, sessionId, "inbound-parsed", bodyBuffer.length); + const isolatedGeneration = pluginAgent === "dsh" && pluginConversation?.includes("|dsh-generation:"); + const dshScope = generationOwner !== undefined && pluginAgent === "dsh" && pluginConversation === sessionId && + rawDeclaredPurpose === PLUGIN_PURPOSE_CONVERSATION && !designNamespaced && !sideRequestLike && !countTokens && !responsesCompact && + !adminGateDenial(req, opts.host) ? generationScope(generationOwner, sessionId) : undefined; // #5490: the first-sight warn above needs no session identity; this one // does — recurrence across DISTINCT sessions is what turns "a model I // haven't declared" into "an alias this host resolves internally that @@ -2308,7 +2316,7 @@ async function handleRequest( // now set) skips the redundant read-only link; on a miss the link // lands on the SAME first request (pi RLM children: no replay, link // as before — no deferral, no timing change). - if (clientProvided && !anonAffinity && session.stats.requests === 0 && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined && opts.resumeInheritance !== false) { + if (!isolatedGeneration && clientProvided && !anonAffinity && session.stats.requests === 0 && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined && opts.resumeInheritance !== false) { const loadParent = (id: string): Session | undefined => peekSession(id) ?? getStore().loadSync(id, { protocol, upstreamOrigin }) ?? undefined; // #5608-B: where the honest-NULL arm actually lives — the PROVEN // identity paths only: weak/strong resume adoptions (maybeAdoptResume, @@ -2524,7 +2532,7 @@ async function handleRequest( // the gate is idempotence, not first-request. Runs AFTER the #1486 // resume match above: a replay-fork child that already inherited has // derivedFromSessionId set and skips this link. - if (derivedParent !== undefined && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined) { + if (!isolatedGeneration && derivedParent !== undefined && session.metadata.derivedFromSessionId === undefined && session.metadata.publicForkReceipt === undefined) { try { // #7421: resolveConversation is memory-only (conversations map + // peekSession), so after a proxy restart even a corrected parent @@ -3913,7 +3921,23 @@ async function handleRequest( // stamp; mode relearned as "full" via the header. let pendingForward; try { - pendingForward = await withSessionLock(session, () => runPreparedPipeline!(true)); + pendingForward = await withSessionLock(session, () => { + if (dshScope && !subagentFallback.present && opts.resumeInheritance !== false && !egressPlaneGateOn() && + req.headers["x-bili-pf-delta"] === undefined && (protocol === "openai" || protocol === "anthropic")) { + const result = visitGeneration(session, dshScope, protocol, JSON.parse(bodyBuffer.toString("utf8")), reqConfig, + id => peekSession(id) ?? getStore().loadSync(id, { protocol, upstreamOrigin }) ?? undefined); + if (result?.adopted.length && getStore().enabled) generationAwaitingSave.add(session); + if (result && (result.adopted.length || Object.keys(result.rejected).length)) log("info", "[dsh-generation] " + JSON.stringify(result)); + } else if (session.metadata.dshGenerationWitness) { + delete session.metadata.dshGenerationWitness; + markDirty(session); + } + if (generationAwaitingSave.has(session)) { + if (!getStore().flushSync(session)) throw new Error("DSH generation inheritance could not be persisted; retry before forwarding"); + generationAwaitingSave.delete(session); + } + return runPreparedPipeline!(true); + }); } catch (err) { if (err instanceof DeltaReanchorError && !res.destroyed && !res.writableEnded) { log("warn", `[${session.id}] watermark delta re-anchor 400 (${err.reason}) — client resends in full form`); diff --git a/src/store.ts b/src/store.ts index fe180fe99c..86e0413472 100644 --- a/src/store.ts +++ b/src/store.ts @@ -156,6 +156,10 @@ export function adoptContentStore(session: Session, store: MessageContentStore): if (added.length === 0) return; let saved = 0; for (const [ref, entry] of added) { + // A future DSH generation must not mistake a lost CCR binding for + // a session that never enabled CCR. No plaintext is duplicated. + const witness = session.metadata.dshGenerationWitness as {ccr?: Record} | undefined; + if (witness?.ccr) witness.ccr[entry.rawId] = entry.hash; const placeholder = buildStoredPlaceholder({ ref, kind: entry.kind, diff --git a/tests/dsh-generation-reuse.test.ts b/tests/dsh-generation-reuse.test.ts new file mode 100644 index 0000000000..5535723a68 --- /dev/null +++ b/tests/dsh-generation-reuse.test.ts @@ -0,0 +1,209 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + BLOCKED_REF, + collectBlockContent, + createContentStore, + storeOriginal, + defaultConfig, + type CompressionBlock, +} from "acp-kernel"; +import { anthropicToCore } from "acp-kernel/wire"; +import { createSession } from "../src/session.js"; +import { adoptContentStore } from "../src/store.js"; +import { generationScope, visitGeneration } from "../src/dsh-generation-reuse.js"; +import { _setStoreForTest, SessionStore } from "../src/persist.js"; +_setStoreForTest(new SessionStore({ enabled: false })); +const sid = "session-unit", + childId = sid + "|dsh-generation:1", + config = defaultConfig(1000000); +const messages = [ + { role: "user", content: "opening" }, + { role: "assistant", content: [{ type: "tool_use", id: "call-1", name: "read", input: { path: "a" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "call-1", content: "tool original" }] }, + { role: "assistant", content: "unrelated independent material" }, + { role: "user", content: "tail" }, +]; +function fixture() { + const source = createSession(sid), + target = createSession(childId); + for (const s of [source, target]) { + s.metadata.pluginAgent = "dsh"; + s.contentStore = createContentStore(); + } + const body = { messages: structuredClone(messages) }; + visitGeneration(source, generationScope(sid, sid)!, "anthropic", body, config, () => undefined); + const rows = anthropicToCore(body as Parameters[0]).msgs; + rows.forEach((m, i) => { + const ref = "m" + String(i + 8).padStart(5, "0"); + source.state.messageRefs.byRef[ref] = m.id; + source.state.messageRefs.byRaw[m.id] = ref; + }); + adoptContentStore( + source, + storeOriginal(source.contentStore!, { + ref: "m00010", + rawId: rows[2]!.id, + text: rows[2]!.text!, + tokens: 3, + kind: "tool result", + head: "tool original", + }), + ); + const block = (bid: string, positions: number[]) => { + const ids = positions.map((i) => rows[i]!.id); + const b: CompressionBlock = { + blockId: bid, + runId: "r1", + tier: 1, + summary: "stable summary " + bid, + directMessageIds: ids, + directBlockIds: [], + effectiveMessageIds: ids, + compressedTokens: 20, + createdAt: 1, + survivedCount: 0, + generation: "young", + active: true, + }; + source.state.blocks.push(b); + source.blockContents.set(bid, { one: null, full: collectBlockContent(source.state, b, rows, { full: true }) }); + return b; + }; + const b1 = block("b1", [1, 2]), + b2 = block("b2", [3]); + source.state.nextBlockId = 3; + const run = (preview = false) => + visitGeneration(target, generationScope(sid, childId)!, "anthropic", body, config, () => source, preview); + return { body, source, target, rows, b1, b2, run }; +} +for (const [label, change, reason] of [ + ["missing result", (f: F) => f.body.messages.splice(2, 1), "missing-source"], + [ + "lost CCR binding", + (f: F) => { + delete f.source.contentStore!.byRef.m00010; + }, + "missing-original", + ], + [ + "changed tool id", + (f: F) => { + f.body.messages[1]!.content = [{ type: "tool_use", id: "another", name: "read", input: { path: "a" } }]; + f.body.messages[2]!.content = [{ type: "tool_result", tool_use_id: "another", content: "tool original" }]; + }, + "unproven-content", + ], + [ + "corrupt original", + (f: F) => { + f.source.blockContents.get("b1")!.full.text = "corrupt"; + }, + "missing-original", + ], + ["missing block cache", (f: F) => f.source.blockContents.delete("b1"), "missing-original"], + [ + "blocked ref", + (f: F) => { + f.source.state.messageRefs.byRaw[f.rows[1]!.id] = BLOCKED_REF; + }, + "protected", + ], + [ + "outside citation", + (f: F) => { + f.b1.summary += " see m00199"; + }, + "unresolved-citation", + ], + [ + "dependency unavailable", + (f: F) => { + f.b1.directBlockIds = ["b99"]; + }, + "dependency-conflict", + ], + [ + "incomplete CCR", + (f: F) => { + f.source.contentStore!.byRef.m00009 = { rawId: f.rows[1]!.id, hash: "no-object" } as never; + }, + "missing-original", + ], +] as const) + test("generation rejects only the affected block: " + label, () => { + const f = fixture(); + change(f); + const report = f.run(true); + assert.equal(f.target.state.blocks.length, 0); + assert.equal(f.target.metadata.dshGenerationWitness, undefined); + assert.deepEqual(report?.adopted, ["b2"]); + assert.equal(report?.rejected.b1, reason); + assert.deepEqual(f.run(), report); + assert.deepEqual( + f.target.state.blocks.map((b) => b.blockId), + ["b2"], + ); + f.target.state.blocks[0]!.summary = "changed in child"; + assert.notEqual(f.b2.summary, "changed in child"); + }); +type F = ReturnType; +test("reorder, opaque part, partial tool unit, existing target and unrelated source fail closed", () => { + for (const kind of ["reorder", "opaque", "split", "existing", "other", "busy", "expanded", "truncated"]) { + const f = fixture(); + if (kind === "reorder") { + f.b1.directMessageIds = f.b1.effectiveMessageIds = [f.rows[0]!.id, f.rows[1]!.id, f.rows[2]!.id]; + f.source.blockContents.get("b1")!.full = collectBlockContent(f.source.state, f.b1, f.rows, { full: true }); + f.body.messages.unshift(f.body.messages.splice(1, 1)[0]!); + } + if (kind === "opaque") Object.assign(f.body.messages[1]!, { thoughtSignature: "opaque" }); + if (kind === "split") { + f.b1.directMessageIds = f.b1.effectiveMessageIds = [f.rows[1]!.id]; + f.source.blockContents.get("b1")!.full = collectBlockContent(f.source.state, f.b1, f.rows, { full: true }); + } + if (kind === "existing") f.target.state.messageRefs.byRaw.other = "m00009"; + if (kind === "other") f.source.metadata.pluginAgent = "pi"; + if (kind === "busy") f.source.inFlight++; + if (kind === "expanded") f.b1.expanded = true; + if (kind === "truncated") f.body.messages.length = 3; + assert.ok(!f.run()?.adopted.includes("b1"), kind); + } +}); +test("nested blocks retain child inactivity; missing nested original rejects parent", () => { + for (const broken of [false, true]) { + const f = fixture(); + f.b1.active = f.b2.active = false; + const nested = { + ...f.b2, + blockId: "b3", + tier: 2 as const, + directMessageIds: [], + directBlockIds: ["b1", "b2"], + effectiveMessageIds: [...f.b1.effectiveMessageIds, ...f.b2.effectiveMessageIds], + active: true, + summary: "combined b1 b2", + }; + f.source.state.blocks.push(nested); + f.source.state.nextBlockId++; + f.source.blockContents.set("b3", { + one: null, + full: collectBlockContent(f.source.state, nested, f.rows, { full: true }), + }); + if (broken) f.source.blockContents.delete("b2"); + assert.deepEqual(f.run()?.adopted, broken ? [] : ["b3"]); + assert.deepEqual( + f.target.state.blocks.filter((b) => b.active).map((b) => b.blockId), + broken ? [] : ["b3"], + ); + } +}); +test("unsupported wire, forged owner, legacy source, changed pair payload cannot seed", () => { + const f = fixture(); + assert.equal(generationScope("session-other", childId), undefined); + assert.equal( + visitGeneration(f.target, generationScope(sid, childId)!, "google", {}, config, () => f.source), + undefined, + ); + delete f.source.metadata.dshGenerationWitness; + assert.deepEqual(f.run()?.adopted, []); +}); diff --git a/tests/dsh-llm-stream-attribution.test.ts b/tests/dsh-llm-stream-attribution.test.ts index c5840939e4..0d41c533c8 100644 --- a/tests/dsh-llm-stream-attribution.test.ts +++ b/tests/dsh-llm-stream-attribution.test.ts @@ -38,9 +38,183 @@ import { import { __resetConversationRecallForTests } from "../src/agent/conversation-recall.ts"; import { installNativeWebSocketIntercept, _resetForTest as resetWsIntercept } from "../src/agent/native-ws-intercept.ts"; import { WebSocket, WebSocketServer } from "ws"; +import { apply as applyNativePolicy, configureNativeCompaction, nativeModel } from "../src/agent/dsh-native-compaction.ts"; +import { installNativeFetchIntercept, _resetForTest as resetFetchIntercept } from "../src/agent/native-intercept.ts"; + +for (const nativeModelName of ["codex/gpt-test", "anthropic/claude-test"]) test(`DSH dispatch switches ${nativeModelName}/bili/native with unchanged native wire and a new bili generation`, async () => { + await withSetup(async (handle, proxy) => { + const savedFetch = globalThis.fetch; + resetFetchIntercept(); + installNativeFetchIntercept(_nativeStateForTest()); + const { createServer } = await import("node:http"); + const direct: Array<{ headers: import("node:http").IncomingHttpHeaders; body: string }> = []; + const routed: Array<{ url: string; conversation: string | string[] | undefined; owner: string | string[] | undefined }> = []; + proxy.server.on("request", req => { + if (req.url?.startsWith("/bili/")) routed.push({ url: req.url, conversation: req.headers["x-bili-plugin-conversation"], owner:req.headers["x-bili-dsh-generation-owner"] }); + }); + const upstream = createServer(async (req, res) => { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + direct.push({ headers: req.headers, body: Buffer.concat(chunks).toString() }); + res.end("native"); + }); + await new Promise(resolve => upstream.listen(0, "127.0.0.1", resolve)); + const address = upstream.address(); + assert.ok(address && typeof address === "object"); + const url = `http://127.0.0.1:${address.port}/v1/responses`; + let model = nativeModelName; + const agent = { model: { current: () => ({ provider: "test", model }) }, session: { id: "native-switch-http", surface: { replaceGeneration: 0 } } }; + handle.ctx.agents.get = sid => sid === agent.session.id ? agent : undefined; + configureNativeCompaction([{ model: "codex/gpt-*" }, { model: "anthropic/claude-*" }]); + applyNativePolicy({ + on: (_event, callback) => callback({ agent }, () => undefined), + } as Parameters[0], { noBackend: true }); + const send = async (body: string) => { + const stream = runWaterfall(handle.events, { sessionId: agent.session.id, provider: "test", model, messages:[{id:"host-message-1"}] }, async function* () { + await Promise.resolve(); + await fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-test-signed": "verbatim" }, body }); + yield 1; + }); + for await (const _ of stream) { /* Drain the adapter inside its dispatch scope. */ } + }; + try { + const firstBody = JSON.stringify({ model, input: "native one" }); + await send(firstBody); + assert.equal(direct.length, 1); + assert.equal(routed.length, 0); + assert.equal(direct[0].headers["x-bili-plugin"], undefined); + assert.equal(direct[0].headers["x-test-signed"], "verbatim"); + assert.equal(direct[0].body, firstBody); + agent.session.surface.replaceGeneration = 2; + model = "kimi"; + await send('{"model":"kimi","input":"checkpoint plus tail"}'); + assert.equal(routed.length, 1); + assert.equal(routed[0].conversation, "native-switch-http|dsh-generation:2"); + assert.equal(routed[0].owner,agent.session.id); + assert.equal(direct[0].headers["x-bili-dsh-generation-owner"],undefined); + model = nativeModelName; + await send(JSON.stringify({ model, input: "native two" })); + assert.equal(direct.length, 2); + assert.equal(routed.length, 1); + assert.equal(direct[1].headers["x-bili-plugin"], undefined); + } finally { + configureNativeCompaction([]); + resetFetchIntercept({ anchor: savedFetch }); + globalThis.fetch = savedFetch; + upstream.close(); + upstream.closeAllConnections(); + } + }); +}); const MODEL_URL = "https://api.anthropic.com/v1/messages"; +// The kernel stamps wall-clock `yyyy-mm-dd hh:mm:ss` timestamps into the +// payload in two places: the ACP tag's time="…" attribute (local time of +// occurrence) and the compress tool-result's block time range "[start – end]". +// The arms below fork separate proxies that run at different wall-clock times, +// so those values legitimately differ across arms even when the payload is +// otherwise byte-identical. Mask every wall-clock timestamp before the +// cross-arm deepEqual so the comparison tests payload fidelity, not the clock +// (same sanctioned normalization as issue5403-watermark-fastpath.test.ts). All +// message content here is test-controlled, so no user timestamp can be masked. +function maskWallClockTime(value: unknown): unknown { + if (typeof value === "string") return value.replace(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/g, "T"); + if (Array.isArray(value)) return value.map(maskWallClockTime); + if (value !== null && typeof value === "object") { + return Object.fromEntries(Object.entries(value as Record).map(([k, v]) => [k, maskWallClockTime(v)])); + } + return value; +} + +test("bili-only and model-routed bili have identical real proxy folds and forwarded requests", { timeout: 30_000 }, async () => { + const { createServer } = await import("node:http"); + const { fork } = await import("node:child_process"); + const forwards: unknown[] = []; + const upstream = createServer(async (req, res) => { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(Buffer.from(chunk)); + forwards.push(JSON.parse(Buffer.concat(chunks).toString())); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ id: "fixed-response", object: "chat.completion", choices: [{ index: 0, message: { role: "assistant", content: "ACK" }, finish_reason: "stop" }], usage: { prompt_tokens: 30000, completion_tokens: 3, total_tokens: 30003 } })); + }); + await new Promise(resolve => upstream.listen(0, "127.0.0.1", resolve)); + const address = upstream.address(); assert.ok(address && typeof address === "object"); + const url = `http://127.0.0.1:${address.port}/v1/chat/completions`; + const outcomes: unknown[] = []; + try { + for (const mode of ["bili-only", "routed-bili", "routed-after-native-checkpoint"]) { + let child: import("node:child_process").ChildProcess; + let diagnostics = ""; + type Snapshot = { sessions: Array<{ id: string; refs: Record; blocks: import("acp-kernel").CompressionBlock[] }> }; + const snapshot = () => new Promise(resolve => { child.once("message", data => resolve(data as Snapshot)); child.send("snapshot"); }); + forwards.length = 0; + await withSetup(async (handle, proxy) => { + configureNativeCompaction(mode === "bili-only" ? undefined : [{ model: "gpt-*" }]); + assert.equal(nativeModel({ model: "gpt-test" }), mode !== "bili-only"); + assert.equal(nativeModel({ model: "glm-test" }), false); + const savedFetch = globalThis.fetch; + const agent = { model: { current: () => ({ provider: "test", model: "glm-test" }) }, session: { id: "bili-parity", surface: { replaceGeneration: mode === "routed-after-native-checkpoint" ? 2 : 0 } } }; + handle.ctx.agents.get = sid => sid === agent.session.id ? agent : undefined; + const manifest = await (await fetch(proxy.origin + "/__bili/plugin/manifest")).json() as { tools: { openai: unknown[] } }; + const messages: Array<{ id: string; role: string; content: string | null; tool_calls?: unknown[]; tool_call_id?: string }> = Array.from({ length: 24 }, (_, i) => ({ id: `history-${i}`, role: i % 2 ? "assistant" : "user", content: `Archive ${i}: keep ROUTE-811 and never modify production. `.repeat(240) })); + resetFetchIntercept(); installNativeFetchIntercept(_nativeStateForTest()); + const send = async () => { + const body = JSON.stringify({ model: "glm-test", max_tokens: 64000, messages: messages.map(({ id, ...m }) => m), tools: [{ type: "function", function: { name: "read", description: "Read a test fixture", parameters: { type: "object", properties: {} } } }, ...manifest.tools.openai] }); + const stream = runWaterfall(handle.events, { sessionId: agent.session.id, provider: "test", model: "glm-test", messages }, async function* () { + const response = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body }); + assert.equal(response.status, 200, await response.text()); + yield 1; + }); + for await (const _ of stream) { /* Drain the actual attributed request. */ } + }; + try { + await send(); + const sessions = (await snapshot()).sessions; assert.equal(sessions.length, 1); + const session = sessions[0]; + assert.equal(session.id, mode === "routed-after-native-checkpoint" ? "bili-parity|dsh-generation:2" : "bili-parity"); + const refs = session.refs; + assert.equal(Object.keys(refs).length, 24); + const startId = Object.values(refs)[0], endId = Object.values(refs)[9]; + const tool = handle.registered.find(t => t.name === "compress") as RegisteredToolLike & { execute: (args: unknown, context: unknown) => Promise }; + assert.ok(tool); + const args = { content: [{ startId, endId, summary: "ROUTE-811; never modify production; archive rows 0-9 received." }] }; + const result = await tool.execute(args, { agent }); + const compressed = (await snapshot()).sessions[0]; + assert.equal(compressed.blocks.length, 1, JSON.stringify(result)); + messages.push({ id: "compression-call", role: "assistant", content: null, tool_calls: [{ id: "compress-1", type: "function", function: { name: "compress", arguments: JSON.stringify(args) } }] }, { id: "compression-result", role: "tool", tool_call_id: "compress-1", content: String(result) }, { id: "current-task", role: "user", content: "Continue with the retained facts." }); + await send(); + const after = (await snapshot()).sessions[0]; + assert.equal(after.blocks.length, 1); + assert.equal(after.blocks[0].active, true); + assert.ok(JSON.stringify(forwards[1]).includes(args.content[0].summary)); + assert.ok(JSON.stringify(forwards[1]).length < JSON.stringify(forwards[0]).length); + outcomes.push({ forwards: structuredClone(forwards).map(maskWallClockTime), blocks: after.blocks.map(({ createdAt, compressCallId, durationMs, ...b }) => b), tools: handle.registered.map(t => t.name) }); + } finally { resetFetchIntercept({ anchor: savedFetch }); globalThis.fetch = savedFetch; } + }, async () => { + child = fork(new URL("./fixtures/dsh-compaction-parity-proxy.mjs", import.meta.url), [`http://127.0.0.1:${address.port}`], { execArgv: ["--import", "tsx"], stdio: ["ignore", "pipe", "pipe", "ipc"], env: { ...process.env, BILI_PERSIST: "0" } }); + child.stderr?.on("data", data => { diagnostics += String(data); }); + child.stdout?.on("data", data => { diagnostics += String(data); }); + const origin = await new Promise((resolve, reject) => { + child.once("message", data => resolve((data as { origin: string }).origin)); + child.once("error", reject); + child.once("exit", code => reject(new Error(`proxy child exited ${code}: ${diagnostics}`))); + }); + return { server: createServer(), origin, dispose: async () => { + const exited = new Promise(resolve => child.once("exit", () => resolve())); + child.disconnect(); await exited; + } }; + }); + } + assert.deepEqual(outcomes[1], outcomes[0], "routing must not change bili's tool surface, folding or provider payloads"); + assert.deepEqual(outcomes[2], outcomes[0], "a fresh generation must use the same bili algorithm on the same visible history"); + } finally { + configureNativeCompaction(undefined); + upstream.closeAllConnections(); + await new Promise(resolve => upstream.close(() => resolve())); + } +}); + interface RegisteredToolLike { name: string; } @@ -111,26 +285,27 @@ function runWaterfall( return composed(options, () => base()) as AsyncIterable; } -async function withSetup(fn: (handle: CtxHandle, proxy: MockProxy) => Promise): Promise { +async function withSetup(fn: (handle: CtxHandle, proxy: MockProxy) => Promise, factory = startMockProxy): Promise { __resetConversationRecallForTests(); const home = mkdtempSync(join(tmpdir(), "dsh-llm-stream-")); const saved: Record = {}; for (const key of ["BILLION_CONTEXT_PROXY", "DSH_HOME", "BILLION_CONTEXT_PLUGIN", "BILI_NATIVE_DSH", "BILI_PROVIDER_REWRITES"]) { saved[key] = process.env[key]; } - const proxy = await startMockProxy(); + const proxy = await factory(); process.env.BILLION_CONTEXT_PROXY = proxy.origin; process.env.DSH_HOME = home; _resetRegisterForTest(proxy.origin); const handle = makeCtx(); try { await apply(handle.ctx); - await waitFor(() => handle.registered.length === 1, "attach tool registration"); + await waitFor(() => handle.registered.length >= 1, "attach tool registration"); await fn(handle, proxy); } finally { await _settleNativeForTest(); proxy.server.close(); proxy.server.closeIdleConnections?.(); + await proxy.dispose?.(); for (const [key, value] of Object.entries(saved)) { if (value === undefined) delete process.env[key]; else process.env[key] = value; @@ -140,6 +315,7 @@ async function withSetup(fn: (handle: CtxHandle, proxy: MockProxy) => Promise Promise; origin: string; server: import("node:http").Server; } @@ -495,3 +671,22 @@ test("#6770: compaction overlay coverage is logged once on the first routed requ } }); }); + +test("declared agentless auxiliary calls never look up a conversation generation or seed its recall", async () => { + await withSetup(async (handle) => { + configureNativeCompaction([{ model: "gpt-*" }]); + try { + for (const purpose of ["session-title", "session-tag"]) { + const stream = runWaterfall(handle.events, { sessionId: "side-only", model: "glm-test", purpose }, async function* () { + const init: RequestInit = { body: JSON.stringify({ messages: [{ role: "user", content: "side only" }] }) }; + await _stateBeforeSendForTest()!(MODEL_URL, init); + const headers = _stateHeadersForTest()!(MODEL_URL); + assert.equal(headers?.["x-bili-plugin-purpose"], purpose); + assert.equal(headers?.["x-bili-plugin-conversation"], "side-only"); + yield 1; + }); + for await (const _ of stream) { /* drain */ } + } + } finally { configureNativeCompaction([]); } + }); +}); diff --git a/tests/dsh-native-compaction.test.ts b/tests/dsh-native-compaction.test.ts new file mode 100644 index 0000000000..226acc6f35 --- /dev/null +++ b/tests/dsh-native-compaction.test.ts @@ -0,0 +1,183 @@ +import test, { afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { apply, compactionConversationId, configureNativeCompaction, nativeAgent, nativeModel, nativeSummaryActive, requireNativeCompactionReady } from "../src/agent/dsh-native-compaction.ts"; +import { selectiveBasicCompaction } from "../src/agent/dsh-compaction-disable.ts"; + +afterEach(() => configureNativeCompaction([])); +const message = (text: string) => ({ role: "user", content: [{ type: "text", text }] }); + +test("native ownership is opt-in, exact provider, explicit model family, never substring", () => { + configureNativeCompaction([]); + assert.equal(nativeModel({ model: "gpt-5" }), false); + configureNativeCompaction([{ model: "gpt-*", provider: "openai" }, { model: "exact" }]); + assert.equal(nativeModel({ provider: "openai", model: "gpt-5" }), true); + assert.equal(nativeModel({ provider: "other", model: "gpt-5" }), false); + assert.equal(nativeModel({ provider: "openai", model: "fake-gpt-5" }), false); + assert.equal(nativeModel({ provider: "other", model: "exact" }), true); + assert.equal(nativeModel(undefined), false); + for (const invalid of [{}, "gpt-*", [{ model: "*" }], [{ model: "g*t" }], [{ model: "gpt-*", typo: true }]]) { + assert.throws(() => configureNativeCompaction(invalid)); + } +}); + +test("pending model selection outranks last request; persistent surface generation isolates old folds", () => { + configureNativeCompaction([{ model: "gpt-*" }]); + const agent = { model: { current: () => ({ model: "gpt-5" }) }, session: { surface: { replaceGeneration: 0 }, requestHeader: () => ({ config: { model: "kimi" } }) } }; + assert.equal(nativeAgent(agent), true); + assert.equal(compactionConversationId(agent, "session-a"), "session-a"); + agent.session.surface.replaceGeneration = 3; + assert.equal(compactionConversationId(agent, "session-a"), "session-a|dsh-generation:3"); + assert.equal(compactionConversationId({ session: { surface: { replaceGeneration: 3 } } }, "session-a"), "session-a|dsh-generation:3"); + configureNativeCompaction([]); + assert.equal(nativeAgent(agent), false); + assert.equal(compactionConversationId(agent, "session-a"), "session-a|dsh-generation:3", "clearing rules must not resurrect old folds"); + assert.throws(() => compactionConversationId({}, "session-a")); + assert.throws(() => requireNativeCompactionReady(agent)); +}); + +test("preset rewrite keeps stock settings, respects disabled rows, adds adapter in the compaction group once", () => { + const inner = [{ name: "@deepseek-ai/dsh-compaction-basic", config: { thresholdRatio: 0.75 } }, { name: "@deepseek-ai/dsh-command-compact", disabled: true }]; + const rows = [{ group: true, config: inner }]; + const output = selectiveBasicCompaction(rows) as typeof rows; + assert.deepEqual(output[0].config.slice(0, 2), inner); + assert.equal(output[0].config.length, 3); + assert.deepEqual(selectiveBasicCompaction(output), output); + assert.equal(inner.length, 2); +}); + +test("adapter gates native methods and scopes summary bypass without leaking to concurrent bili sessions", async () => { + configureNativeCompaction([{ model: "gpt-*" }]); + let model = "kimi"; + const agent = { model: { current: () => ({ provider: "test", model }) }, session: { id: "a", surface: { replaceGeneration: 0 }, requestHeader: () => ({ config: { provider: "test", model } }) } }; + const calls: string[] = []; + const engine = { + compactIfNeeded: async () => { calls.push("auto"); return "auto"; }, + compactPressure: async () => { calls.push("pressure"); return "pressure"; }, + compactRegion: async () => { calls.push("region"); return "region"; }, + compactNow: async () => { calls.push("manual"); return "manual"; }, + summarize: async () => { assert.equal(nativeSummaryActive(), true); await Promise.resolve(); assert.equal(nativeSummaryActive(), true); return { summary: [{ type: "text", text: "summary" }] }; }, + }; + const ctx: Parameters[0] = { compaction: engine, on: () => undefined }; + apply(ctx); + assert.equal(await ctx.compaction.compactIfNeeded(agent, "pressure"), null); + await assert.rejects(ctx.compaction.compactNow(agent), /bili owns/); + model = "gpt-5"; + assert.equal(await ctx.compaction.compactIfNeeded(agent, "pressure"), "auto"); + requireNativeCompactionReady(agent); + const summary = ctx.compaction.summarize({ messages: [message("fact")] }, agent); + assert.equal(nativeSummaryActive(), false); + await summary; + assert.equal(nativeSummaryActive(), false); + model = "kimi"; + assert.equal(await ctx.compaction.compactPressure(agent, { config: { model } }), null); + assert.deepEqual(calls, ["auto"]); +}); + +test("overlapping native summary and bili work keep separate ownership across awaits and failure", async () => { + configureNativeCompaction([{ model: "gpt-*" }]); + const native = { model: { current: () => ({ provider: "test", model: "gpt-test" }) }, session: { id: "native-overlap", surface: { replaceGeneration: 0 } } }; + const bili = { model: { current: () => ({ provider: "test", model: "glm" }) }, session: { id: "bili-overlap", surface: { replaceGeneration: 0 } } }; + let release!: () => void; + const held = new Promise(resolve => { release = resolve; }); + let entered!: () => void; + const ready = new Promise(resolve => { entered = resolve; }); + const engine: Parameters[0]["compaction"] = { + compactIfNeeded: async () => { throw new Error("bili must not call native backend"); }, + compactPressure: async () => null, compactRegion: async () => null, compactNow: async () => null, + summarize: async () => { + assert.equal(nativeSummaryActive(), true); + entered(); + await held; + assert.equal(nativeSummaryActive(), true); + throw new Error("held summary failed"); + }, + }; + apply({ compaction: engine, on: () => undefined }); + const pending = engine.summarize({ messages: [message("fact")] }, native); + await ready; + assert.equal(nativeSummaryActive(), false); + assert.equal(await engine.compactIfNeeded(bili, "pressure"), null); + await Promise.resolve(); + assert.equal(nativeSummaryActive(), false); + assert.equal(compactionConversationId(bili, "bili-overlap"), "bili-overlap"); + const rejected = assert.rejects(pending, /held summary failed/); + release(); + await rejected; + assert.equal(nativeSummaryActive(), false); +}); + +test("native summary delegates the identical input once without budget, splitting or prompt changes", async () => { + configureNativeCompaction([{ model: "gpt-*" }]); + const agent = { session: { id: "transparent-native" }, model: { current: () => ({ model: "gpt-test" }) } }; + const input = { messages: [message("x".repeat(800000)), { role: "tool", toolCallId: "host-owned", content: [{ type: "text", text: "original" }] }], tools: [{ name: "large", description: "工具".repeat(200000) }] }; + const before = structuredClone(input); + const controller = new AbortController(); + const result = { summary: [{ type: "text", text: "host summary" }], usage: { inputTokens: 12 }, hostMetadata: "unchanged" }; + let calls = 0; + const engine: Parameters[0]["compaction"] = { + compactIfNeeded: async () => null, compactPressure: async () => null, + compactRegion: async () => null, compactNow: async () => null, + summarize: async function (actual, owner, signal) { + calls++; + assert.equal(this, engine); + assert.equal(actual, input); + assert.equal(owner, agent); + assert.equal(signal, controller.signal); + assert.equal(nativeSummaryActive(), true); + return result; + }, + }; + apply({ compaction: engine, on: () => undefined }); + assert.equal(await engine.summarize(input, agent, controller.signal), result); + assert.equal(calls, 1); + assert.deepEqual(input, before); + assert.equal(nativeSummaryActive(), false); +}); + +test("native summary preserves host errors and aborted signals without adapter retries or validation", async () => { + configureNativeCompaction([{ model: "gpt-*" }]); + const agent = { session: { id: "native-error" }, model: { current: () => ({ model: "gpt-test" }) } }; + const input = { messages: [message("fact")] }; + const error = new Error("provider context window exceeded"); + const controller = new AbortController(); controller.abort(new Error("host cancellation")); + let calls = 0; + const engine: Parameters[0]["compaction"] = { + compactIfNeeded: async () => null, compactPressure: async () => null, + compactRegion: async () => null, compactNow: async () => null, + summarize: async (actual, owner, signal) => { + calls++; + assert.equal(actual, input); assert.equal(owner, agent); assert.equal(signal, controller.signal); + throw error; + }, + }; + apply({ compaction: engine, on: () => undefined }); + await assert.rejects(engine.summarize(input, agent, controller.signal), e => e === error); + assert.equal(calls, 1); + assert.equal(nativeSummaryActive(), false); +}); + +test("runtime registration preserves stock rows in selective mode, including a second pass after preset resolution", async () => { + const gate = await import("../src/agent/dsh-compaction-disable.ts"); + gate.declareDshCompactionActive(); + configureNativeCompaction([{ model: "gpt-*" }]); + try { + const basic = { name: "@deepseek-ai/dsh-compaction-basic", config: { thresholdRatio: 0.7 } }; + const compact = { name: "@deepseek-ai/dsh-command-compact" }; + const adapter = { name: "billion-context/dsh-native-compaction" }; + for (const [plugins, expected] of [ + [[basic, compact], [basic, compact, adapter]], + [[{ group: true, config: [basic, compact] }], [{ group: true, config: [basic, compact, adapter] }]], + [[compact], [compact, { ...adapter, config: { noBackend: true } }]], + [[{ ...basic, disabled: true }], [{ ...basic, disabled: true }, { ...adapter, config: { noBackend: true } }]], + [[], [{ ...adapter, config: { noBackend: true } }]], + ]) { + const def = { id: "dynamic", plugins }; + const result = gate.disableRuntimePresetCompaction(def); + assert.deepEqual(result, { id: "dynamic", plugins: expected }); + assert.deepEqual(gate.disableRuntimePresetCompaction(result), result); + } + } finally { + gate._resetDshCompactionVerdictForTest(); + gate._resetDshCompactionGateTelemetryForTest(); + } +}); diff --git a/tests/fixtures/dsh-compaction-parity-proxy.mjs b/tests/fixtures/dsh-compaction-parity-proxy.mjs new file mode 100644 index 0000000000..8c72b1db5e --- /dev/null +++ b/tests/fixtures/dsh-compaction-parity-proxy.mjs @@ -0,0 +1,15 @@ +import { startServer } from '../../src/server.ts'; +import { loadOptions } from '../../src/config.ts'; +import { defaultConfig } from 'acp-kernel'; +import { SessionStore, _setStoreForTest } from '../../src/persist.ts'; +import { listSessions } from '../../src/session.ts'; + +_setStoreForTest(new SessionStore({ enabled: false })); +const kernelConfig = defaultConfig(400000); +kernelConfig.preserveRecentMessages = 2; +kernelConfig.preserveRecentTokens = 0; +const server = await startServer({ ...loadOptions({}), port: 0, host: '127.0.0.1', upstream: process.argv[2], modelContextLimit: 400000, kernelConfig, autoUpdate: false, autoRestartOnUpdate: false, advisoryCheck: false, releaseNotesCheck: false, log: false, debug: false }); +if (!server.listening) await new Promise(resolve => server.once('listening', resolve)); +process.send({ origin: `http://127.0.0.1:${server.address().port}` }); +process.on('message', () => process.send({ sessions: listSessions().map(s => ({ id: s.id, refs: s.state.messageRefs.byRaw, blocks: s.state.blocks })) })); +process.on('disconnect', () => { server.closeAllConnections(); server.close(); process.exit(0); }); diff --git a/tests/fixtures/dsh-generation-worker.mjs b/tests/fixtures/dsh-generation-worker.mjs new file mode 100644 index 0000000000..980cbc3899 --- /dev/null +++ b/tests/fixtures/dsh-generation-worker.mjs @@ -0,0 +1,36 @@ +// Disposable child for the process-restart/egress regression. +import { startServer } from "../../src/server.ts"; +import { loadOptions } from "../../src/config.ts"; +import { defaultConfig } from "acp-kernel"; +import { SessionStore, _setStoreForTest } from "../../src/persist.ts"; +import { listSessions } from "../../src/session.ts"; +const [dir, upstream, limit] = process.argv.slice(2), + n = Number(limit); +const store = new SessionStore({ dir: dir + "/sessions", enabled: true, debounceMs: 60000 }); +_setStoreForTest(store); +const server = await startServer({ + ...loadOptions({}), + port: 0, + host: "127.0.0.1", + upstream, + modelContextLimit: n, + routes: { [upstream]: { models: { "claude-test": { context: n } } } }, + kernelConfig: defaultConfig(n), + compress: { + injectTool: true, + injectNudge: true, + preserveRecentMessages: 1, + preserveRecentTokens: 0, + minCompressRangeChars: 100, + }, + log: false, + debug: false, + autoUpdate: false, + autoRestartOnUpdate: false, +}); +if (!server.listening) await new Promise((resolve) => server.once("listening", resolve)); +process.send(server.address().port); +process.on("message", async () => { + await store.flushAll(listSessions()); + process.exit(0); +}); diff --git a/tests/fork-side-request-lane.test.ts b/tests/fork-side-request-lane.test.ts index 2afb2ffc67..fc72463e00 100644 --- a/tests/fork-side-request-lane.test.ts +++ b/tests/fork-side-request-lane.test.ts @@ -80,6 +80,36 @@ async function harness() { return { request, messages, forwarded, dshSend, upstreamUrl: upstream.url, origin, close: async () => { store.cancelAll(); proxy.close(); upstream.close(); await new Promise((r2) => setTimeout(r2, 50)); } }; } +test("a full-history DSH title replay cannot overwrite the main generation witness", async () => { + const h = await harness(); + const sid = "session-generation-side"; + const previous = process.env.BILI_ROLLOUT_EGRESS_PLANE; + process.env.BILI_ROLLOUT_EGRESS_PLANE = "0"; + try { + const send = async (purpose: string, messages: typeof h.messages) => { + const response = await fetch(h.origin + "/bili/" + h.upstreamUrl + "/v1/messages", { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": sid, + "x-bili-dsh-generation-owner": sid, "x-bili-plugin-purpose": purpose }, + body: JSON.stringify({ model: "claude-test", max_tokens: 4096, messages }), + }); + assert.equal(response.status, 200, await response.text()); + }; + await send("conversation", h.messages); + const session = resolveConversation(sid).session!; + const witness = structuredClone(session.metadata.dshGenerationWitness); + assert.ok(witness, "the equivalent main request records its evidence"); + const before = session.stats.requests; + await send("session-title", [...h.messages, { role: "user", content: "Give this conversation a title." }]); + assert.equal(session.stats.requests, before); + assert.deepEqual(session.metadata.dshGenerationWitness, witness, "a side replay cannot replace proof of the main history"); + } finally { + if (previous === undefined) delete process.env.BILI_ROLLOUT_EGRESS_PLANE; + else process.env.BILI_ROLLOUT_EGRESS_PLANE = previous; + await h.close(); + } +}); + test("fork-child title-gen rides the #388 passthrough and never pollutes the child's main session", async () => { const h = await harness(); try { diff --git a/tests/native-intercept.test.ts b/tests/native-intercept.test.ts index 8b859ec21a..ecab32ad6e 100644 --- a/tests/native-intercept.test.ts +++ b/tests/native-intercept.test.ts @@ -8,6 +8,26 @@ import { parseModelEndpointPatterns } from "../src/model-endpoints.ts"; import { makeRecordingFetch, runHotReplace, type RecordedCall } from "./helpers/hot-replace.ts"; import * as pfChannel from "../src/agent/pf-channel.ts"; +test("explicit native compaction bypass preserves request bytes and headers before bili gates", async () => { + const original = globalThis.fetch; + const calls: Array<{ input: string | URL | Request; init?: RequestInit }> = []; + const anchor: typeof fetch = async (input, init) => { calls.push({ input, init }); return new Response("ok"); }; + _resetForTest({ anchor }); + globalThis.fetch = anchor; + const no = () => { throw new Error("bili hook must not run for native compaction"); }; + try { + installNativeFetchIntercept({ origin: undefined, ready: Promise.resolve(undefined), nativeCompactionBypass: () => true, takeoverGate: no, beforeSend: no, headersFor: no }); + const init = { method: "POST", body: '{"purpose":"compaction","signed":"unchanged"}', headers: { authorization: "test-signature" } }; + await fetch("https://provider.invalid/v1/responses", init); + assert.equal(calls.length, 1); + assert.equal(calls[0].input, "https://provider.invalid/v1/responses"); + assert.equal(calls[0].init, init); + await fetch("http://127.0.0.1:9999/bili/https://provider.invalid/v1/responses", init); + assert.equal(calls[1].input, "https://provider.invalid/v1/responses"); + assert.equal(calls[1].init, init); + } finally { _resetForTest({ anchor: original }); globalThis.fetch = original; } +}); + test("isModelApiUrl: matches model-API endpoint shapes", () => { assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/messages"), true); assert.equal(isModelApiUrl("http://127.0.0.1:8199/v1/chat/completions"), true); diff --git a/tests/native-ws-intercept.test.ts b/tests/native-ws-intercept.test.ts index e58508dd11..2e755ed59a 100644 --- a/tests/native-ws-intercept.test.ts +++ b/tests/native-ws-intercept.test.ts @@ -686,6 +686,28 @@ test("#5838 e2e: stamped headers actually ride the real WebSocket upgrade reques } }); +test("native-compaction sockets stay direct and refuse reuse after ownership changes", async () => { + await withPatchedGlobal(async () => { + let native = true; + const no = () => { throw new Error("bili hooks must not run on a native socket"); }; + const state: NativeInterceptState = { origin: ORIGIN, ready: Promise.resolve(ORIGIN), nativeCompactionBypass: () => native, beforeSend: no, headersFor: no, takeoverGate: no }; + installNativeWebSocketIntercept(state); + const ws = new (WsCtor())(UPSTREAM_WS, {}); + await tick(); + const [real] = FakeWs.instances; + real.readyState = FakeWs.OPEN; + const frame = JSON.stringify({ type: "response.create", model: "gpt-5", input: [] }); + ws.send(frame); + await tick(); + assert.deepEqual(real.sent, [frame]); + native = false; + ws.send(frame); + await tick(); + assert.deepEqual(real.sent, [frame]); + assert.equal(real.closed, true); + }); +}); + test("DSH prepares every response.create in sender scope, preserves continuation, and refuses model changes", async () => { await withPatchedGlobal(async () => { const scope = new AsyncLocalStorage(); diff --git a/tests/plugin-fork.test.ts b/tests/plugin-fork.test.ts index 74a25abd60..8247bd0c06 100644 --- a/tests/plugin-fork.test.ts +++ b/tests/plugin-fork.test.ts @@ -1700,3 +1700,286 @@ test("fork protocol v2: revision is stable across state churn that does not move assert.notEqual(moved.body.parentRevision, before.body.parentRevision, "a snapshot change must flip the v2 revision"); } finally { await h.close(); } }); + +for (const lane of ["plugin", "proxy"]) + test("DSH generation first send, original lookup and retry: " + lane, async () => { + const h = await harness(true, false); + try { + const sid = "session-reuse-test", + child = sid + "|dsh-generation:1"; + const send = async (id: string, messages: typeof h.messages, system: string) => { + const r = await fetch(h.origin + "/bili/" + h.upstreamUrl + "/v1/messages", { + method: "POST", + headers: { + "content-type": "application/json", + "x-bili-plugin": "dsh", + "x-bili-plugin-conversation": id, + "x-bili-plugin-purpose": "conversation", + "x-bili-dsh-generation-owner": sid, + "x-bili-plugin-agent": "main", + ...(lane === "proxy" ? { "x-bili-plugin-compression": "proxy" } : {}), + }, + body: JSON.stringify({ model: "claude-test", max_tokens: 4096, system, messages }), + }); + assert.equal(r.status, 200, await r.text()); + }; + const history = [{ role: "user", content: "pinned first request" }, ...h.messages]; + await send(sid, history, "old instructions"); + await compress(h, sid, "m00002", "m00003"); + const source = getSession(sid); + assert.ok(source.metadata.dshGenerationWitness, "source identity/wire witness"); + assert.ok(h.store.flushSync(source)); + _resetSessionsForTest(); // parent must be found without a resident session + const withHole = [ + ...history.slice(0, 2), + { role: "user", content: "hole stays visible" }, + ...h.messages.slice(1), + ]; + const n = h.forwarded.length; + await send(child, withHole, "new instructions"); + assert.equal(h.forwarded.length, n + 1, "no extra summarizer call"); + const body = JSON.stringify(h.forwarded.at(-1)); + assert.ok(body.includes(summary), body.slice(-600)); + assert.ok(body.includes("hole stays visible")); + assert.ok(!body.includes("first original ".repeat(4))); + assert.equal(getSession(child).metadata.dshGenerationParent, sid); + for (const path of ["status", "snapshot"]) + assert.equal( + (await h.request("/__bili/plugin/" + path + "?conversationId=" + encodeURIComponent(child))).status, + 200, + ); + const d = await h.request("/__bili/plugin/tool", { + conversationId: child, + tool: "decompress", + args: { blockId: "b1", full: true }, + }); + assert.match(d.body.result, /second original/); + const search = await h.request("/__bili/plugin/tool", { + conversationId: child, + tool: "search_context", + args: { query: "second original" }, + }); + assert.match(search.body.result, /b1/); + await send(child, withHole, "new instructions"); + assert.equal(getSession(child).state.blocks.length, 1); + } finally { + await h.close(); + } + }); + +test( + "DSH process restart: large raw replay folds before window guard; concurrent retries and crash recovery", + { timeout: 60000 }, + async (t) => { + const h = await harness(false, false); + const dir = mkdtempSync(join(testRoot, "generation-process-")); + let worker: ReturnType | undefined; + const start = async (n: number) => { + worker = spawn( + process.execPath, + ["--import", "tsx", "tests/fixtures/dsh-generation-worker.mjs", dir, h.upstreamUrl, String(n)], + { + cwd: fileURLToPath(new URL("../", import.meta.url)), + stdio: ["ignore", "ignore", "inherit", "ipc"], + env: { + ...process.env, + TMPDIR: dir, + TEMP: dir, + TMP: dir, + BILI_SESSIONS_DIR: dir + "/sessions", + XDG_DATA_HOME: dir, + XDG_STATE_HOME: dir, + XDG_CONFIG_HOME: dir, + XDG_CACHE_HOME: dir, + }, + }, + ); + const [port] = await once(worker, "message"); + return "http://127.0.0.1:" + String(port); + }; + const stop = async (crash = false) => { + if (!worker || worker.exitCode !== null || worker.signalCode !== null) return; + const done = once(worker, "exit"); + if (crash) worker.kill("SIGKILL"); + else worker.send!("flush"); + await done; + }; + try { + const sid = "session-restart", + child = sid + "|dsh-generation:1"; + const messages = [ + { role: "user", content: "pinned opening" }, + { role: "assistant", content: "alpha beta gamma delta ".repeat(12000) }, + { role: "user", content: "long original to retrieve ".repeat(8500) }, + { role: "assistant", content: "kept tail" }, + { role: "user", content: "continue from here" }, + ]; + const turn = async (base: string, id: string, system: string) => { + const r = await fetch(base + "/bili/" + h.upstreamUrl + "/v1/messages", { + method: "POST", + headers: { + "content-type": "application/json", + "x-bili-plugin": "dsh", + "x-bili-plugin-conversation": id, + "x-bili-plugin-purpose": "conversation", + "x-bili-dsh-generation-owner": sid, + }, + body: JSON.stringify({ model: "claude-test", system, max_tokens: 1024, messages }), + }); + const result = await r.text(); + assert.equal(r.status, 200, result.slice(0, 350)); + }; + const tool = async (base: string, id: string, name: string, args: unknown) => { + const r = await fetch(base + "/__bili/plugin/tool", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ conversationId: id, tool: name, args }), + }); + const j = (await r.json()) as { result: string }; + assert.equal(r.status, 200); + assert.ok(!j.result.includes("FAILED"), j.result.slice(0, 250)); + return j.result; + }; + let base = await start(400000); + await turn(base, sid, "system before upgrade"); + await tool(base, sid, "compress", { content: [{ startId: "m00002", endId: "m00003", summary }] }); + await stop(); + base = await start(24000); + const prev = h.forwarded.length; + await Promise.all([turn(base, child, "system after upgrade"), turn(base, child, "system after upgrade")]); + assert.equal(h.forwarded.length - prev, 2, "preflight must not invoke the summarizer for inherited folds"); + const { estimateRawBodyBreakdown } = await import("../src/preflight.js"); + const raw = estimateRawBodyBreakdown({ + model: "claude-test", + system: "system after upgrade", + max_tokens: 1024, + messages, + }); + const folded = estimateRawBodyBreakdown(h.forwarded[prev]); + assert.ok(raw.total > 24000 && folded.total + 1024 < 24000); + t.diagnostic(JSON.stringify({ raw, folded, window: 24000, requestedOutput: 1024 })); + for (const body of h.forwarded.slice(prev)) { + const out = JSON.stringify(body); + assert.equal(out.split(summary).length, 2); + assert.ok(out.length < 24000); + assert.ok(!out.includes("alpha beta gamma delta ".repeat(2))); + assert.ok(out.includes("continue from here")); + } + await stop(true); + base = await start(24000); + await turn(base, child, "system after upgrade"); + const original = await tool(base, child, "decompress", { blockId: "b1", full: true }); + const exported = /written to: ([^\r\n]+)/.exec(original)?.[1]; + assert.ok(exported?.startsWith(join(dir, "acp-decompress-"))); + assert.ok(readFileSync(exported!, "utf8").includes(messages[2]!.content)); + const snapshot = await fetch(base + "/__bili/plugin/snapshot?conversationId=" + encodeURIComponent(child)); + const s = (await snapshot.json()) as SnapshotResponse; + assert.equal(s.sessionId, child); + assert.equal(s.messages.find((m) => m.text?.startsWith("alpha beta gamma"))?.ref, "m00002"); + } finally { + await stop(); + await h.close(); + } + }, +); + +for (const wire of ["openai", "anthropic"]) + test("DSH " + wire + " real tool pair keeps original content and ref", async () => { + const h = await harness(false, false); + try { + const sid = "session-pair-test", + child = sid + "|dsh-generation:1"; + const original = "retrievable tool record ".repeat(300); + const rows = + wire === "openai" + ? [ + { role: "user", content: "pinned" }, + { + role: "assistant", + content: null, + tool_calls: [ + { + type: "function", + id: "call_a", + function: { name: "read", arguments: '{"path":"a"}' }, + }, + ], + }, + { role: "tool", tool_call_id: "call_a", content: original }, + { role: "user", content: "what next?" }, + ] + : [ + { role: "user", content: "pinned" }, + { + role: "assistant", + content: [{ type: "tool_use", id: "call_a", name: "read", input: { path: "a" } }], + }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: "call_a", content: original }], + }, + { role: "user", content: "what next?" }, + ]; + const send = async (id: string) => { + const r = await fetch( + h.origin + "/bili/" + h.upstreamUrl + (wire === "openai" ? "/v1/chat/completions" : "/v1/messages"), + { + method: "POST", + headers: { + "content-type": "application/json", + "x-bili-plugin": "dsh", + "x-bili-plugin-conversation": id, + "x-bili-plugin-purpose": "conversation", + "x-bili-dsh-generation-owner": sid, + }, + body: JSON.stringify({ model: "claude-test", max_tokens: 4096, messages: rows }), + }, + ); + assert.equal(r.status, 200, await r.text()); + }; + await send(sid); + await compress(h, sid, "m00002", "m00003"); + await send(child); + const out = JSON.stringify(h.forwarded.at(-1)); + assert.ok(out.includes(summary), "first child send lacks summary"); + assert.ok(!out.includes(original)); + const d = await h.request("/__bili/plugin/tool", { + conversationId: child, + tool: "decompress", + args: { blockId: "b1", full: true }, + }); + assert.ok(d.body.result.includes(original)); + assert.equal( + getSession(child).state.messageRefs.byRef.m00003, + getSession(sid).state.messageRefs.byRef.m00003, + ); + } finally { + await h.close(); + } + }); + +test("DSH reuse requires a declared main request and the supported storage plane", async () => { + const h = await harness(true, false); + const prior = process.env.BILI_ROLLOUT_EGRESS_PLANE; + try { + for (const kind of ["no-purpose", "auxiliary", "egress-plane"]) { + const sid = "session-gate-" + kind; + if (kind === "egress-plane") process.env.BILI_ROLLOUT_EGRESS_PLANE = "1"; + const r = await fetch(h.origin + "/bili/" + h.upstreamUrl + "/v1/messages", { + method: "POST", + headers: { + "content-type": "application/json", "x-bili-plugin": "dsh", + "x-bili-plugin-conversation": sid, "x-bili-dsh-generation-owner": sid, + ...(kind === "no-purpose" ? {} : { "x-bili-plugin-purpose": kind === "auxiliary" ? "session-title" : "conversation" }), + }, + body: JSON.stringify({ model: "test", max_tokens: 4096, messages: h.messages }), + }); + assert.equal(r.status, 200, await r.text()); + assert.equal(getSession(sid).metadata.dshGenerationWitness, undefined, kind); + } + } finally { + if (prior === undefined) delete process.env.BILI_ROLLOUT_EGRESS_PLANE; + else process.env.BILI_ROLLOUT_EGRESS_PLANE = prior; + await h.close(); + } +}); diff --git a/tsup.config.ts b/tsup.config.ts index d32dd4f364..82f610e83c 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from "tsup"; export default [ defineConfig({ - entry: ["src/index.ts", "src/mcp.ts", "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/claude-subagent-hook.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/envelope-client.ts", "src/agent/omp.ts", "src/agent/omp-native.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", "src/agent/dsh-compaction-gate.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts", "src/inline-engine.ts"], + entry: ["src/index.ts", "src/mcp.ts", "src/claude-mcp-entry.ts", "src/claude-native-bootstrap.ts", "src/claude-subagent-hook.ts", "src/agent/pi.ts", "src/agent/pi-native.ts", "src/agent/envelope-client.ts", "src/agent/omp.ts", "src/agent/omp-native.ts", "src/agent/opencode.ts", "src/agent/opencode-native.ts", "src/agent/dsh-acp.ts", "src/agent/dsh-native.ts", "src/agent/dsh-compaction-gate.ts", "src/agent/dsh-native-compaction.ts", "src/kimi/native-mcp.ts", "src/kimi/bootstrap-hook.ts", "src/zcode/mcp-entry.ts", "src/zcode/bootstrap-hook.ts", "src/inline-engine.ts"], format: ["esm"], target: "node20", platform: "node", diff --git a/website/config-reference/server.yaml b/website/config-reference/server.yaml index 2fb3278f2d..54cd8763a8 100644 --- a/website/config-reference/server.yaml +++ b/website/config-reference/server.yaml @@ -436,9 +436,30 @@ entries: default: "{}" env: BILI_ALLOW_DSH_COMPACTION group: behavior - desc_en: "Section recognized but its former escape hatch is gone (#3666, superseding #2028): the allowDshCompaction key and the BILI_ALLOW_DSH_COMPACTION env var no longer exist — dsh native compaction is refused unconditionally by the wire guard on every lane. Leftover dsh.allowDshCompaction values are ignored with a one-time deprecation warning; apply host-side suppression instead (#3354/#2474). The live keys — dsh.authoredCompaction, dsh.contextTab, dsh.contextTabLabel — are documented in the following entries." - desc_zh: "段仍被识别,但其原逃生门已移除(#3666,取代 #2028):allowDshCompaction 键与 BILI_ALLOW_DSH_COMPACTION 环境变量已不存在——dsh 原生压缩现在在所有线路上被无条件拒绝。遗留的 dsh.allowDshCompaction 取值会被忽略(一次性弃用警告);请改用宿主侧抑制(#3354/#2474)。存活的键——dsh.authoredCompaction、dsh.contextTab、dsh.contextTabLabel——见接下来的条目。" - desc_ja: "セクションは認識されるが、従来のエスケープハッチは削除された(#3666、#2028 を代替):`allowDshCompaction` キーおよび `BILI_ALLOW_DSH_COMPACTION` 環境変数はもはや存在しない — dsh ネイティブコンパクションは、すべてのレーンにおいてワイヤガードによって無条件に拒否される。残存する `dsh.allowDshCompaction` の値は、一度限りの非推奨警告とともに無視される;代わりにホスト側の抑制を適用すること(#3354/#2474)。ライブキー — `dsh.authoredCompaction`、`dsh.contextTab`、`dsh.contextTabLabel` — は以下のエントリに文書化されている。" + desc_en: "Section recognized but its former escape hatch is gone (#3666, superseding #2028): the allowDshCompaction key and the BILI_ALLOW_DSH_COMPACTION env var no longer exist — the wire guard refuses unmanaged native compaction. Explicit dsh.nativeCompactionModels rules coordinate host ownership and bypass that wire lane. Leftover dsh.allowDshCompaction values are ignored with a one-time deprecation warning; apply host-side suppression instead (#3354/#2474). The live keys — dsh.authoredCompaction, dsh.contextTab, dsh.contextTabLabel — are documented in the following entries." + desc_zh: "段仍被识别,但其原逃生门已移除(#3666,取代 #2028):allowDshCompaction 键与 BILI_ALLOW_DSH_COMPACTION 环境变量已不存在——线级守卫拒绝未受管理的原生压缩。显式 dsh.nativeCompactionModels 规则协调宿主压缩归属并绕过该线路。遗留的 dsh.allowDshCompaction 取值会被忽略(一次性弃用警告);请改用宿主侧抑制(#3354/#2474)。存活的键——dsh.authoredCompaction、dsh.contextTab、dsh.contextTabLabel——见接下来的条目。" + desc_ja: "セクションは認識されるが、従来のエスケープハッチは削除された(#3666、#2028 を代替):`allowDshCompaction` キーおよび `BILI_ALLOW_DSH_COMPACTION` 環境変数はもはや存在しない — ワイヤガードは管理されていないネイティブコンパクションを拒否する。明示的な `dsh.nativeCompactionModels` ルールはホストの所有権を調整し、そのワイヤレーンをバイパスする。残存する `dsh.allowDshCompaction` の値は、一度限りの非推奨警告とともに無視される;代わりにホスト側の抑制を適用すること(#3354/#2474)。ライブキー — `dsh.authoredCompaction`、`dsh.contextTab`、`dsh.contextTabLabel` — は以下のエントリに文書化されている。" + - key: dsh.nativeCompactionModels + type: "{ provider?: string, model: string }[]" + default: "[]" + group: behavior + desc_en: "Opt selected DSH Web-preset models into native compaction (#6121). Exact provider ID is optional; model matches exactly or by a trailing * prefix, e.g. gpt-* or codex/gpt-*. Unmatched models keep bili. Requires a host restart. Native summaries bypass bili and host replacement generations isolate later bili state; see docs/dsh-native-compaction.md for supported profiles, handoff limits and update guidance." + desc_zh: "指定 DSH Web 预设中的模型使用原生压缩(#6121)。可选 provider 精确匹配;model 精确匹配或使用末尾 * 表示前缀,例如 gpt-*、codex/gpt-*。未匹配模型继续使用 bili,需重启宿主生效。原生摘要绕过 bili,宿主替换代数隔离后续 bili 状态;支持范围、切换边界和更新方式见 docs/dsh-native-compaction.zh-CN.md。" + desc_ja: "DSH Web プリセットの選択されたモデルをネイティブコンパクションに割り当てる(#6121)。正確な provider ID は任意;model は完全一致、または末尾 * の接頭辞で一致する(例:`gpt-*`、`codex/gpt-*`)。一致しないモデルは `bili` を維持する。宿主のリスタートが必要。ネイティブ要約は `bili` をバイパスし、宿主置換の世代は後続の `bili` 状態を分離する;対応プロファイル、引き渡し上限、更新ガイドは docs/dsh-native-compaction.md を参照。" + - key: dsh.nativeCompactionModels.model + type: string + default: "required per rule" + group: behavior + desc_en: "Each native-compaction rule's exact model ID or prefix ending in *. Display names and other wildcard forms are not accepted." + desc_zh: "每条原生压缩规则的模型 ID,精确匹配或末尾 * 前缀匹配,不使用显示名或其他通配形式。" + desc_ja: "各ネイティブコンパクションルールの正確なモデル ID、または末尾 * で終わる接頭辞。表示名やその他のワイルドカード形式は受け入れられない。" + - key: dsh.nativeCompactionModels.provider + type: string + default: "omitted (all providers)" + group: behavior + desc_en: "Optional exact DSH provider ID restricting one native-compaction model rule." + desc_zh: "可选的 DSH 供应商 ID,精确限定该条原生压缩模型规则。" + desc_ja: "ネイティブコンパクションのモデルルールを 1 つに制限する、任意の正確な DSH provider ID。" - key: dsh.authoredCompaction type: boolean default: "true (on, #3901 flip)"