From b85e79714b39faa3c365a21bccec7467e9804b21 Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:59:18 +0800 Subject: [PATCH 1/9] feat(dsh): select models for native compaction with safe handoff --- docs/README.zh-CN.md | 2 + docs/architecture.md | 2 + docs/architecture.zh-CN.md | 2 + docs/configuration.md | 5 +- docs/configuration.zh-CN.md | 5 +- docs/dsh-native-compaction.md | 59 ++++++ docs/dsh-native-compaction.zh-CN.md | 59 ++++++ docs/index.md | 2 + package.json | 1 + reference/architecture.md | 1 + scripts/check-unused-exports.mjs | 1 + scripts/test-dsh-native-compaction.mjs | 81 ++++++++ src/agent/dsh-compaction-disable.ts | 25 ++- src/agent/dsh-native-client.ts | 18 +- src/agent/dsh-native-compaction.ts | 223 +++++++++++++++++++++++ src/agent/dsh-native.ts | 70 +++++-- src/agent/native-intercept.ts | 6 + src/agent/native-ws-intercept.ts | 10 +- src/config.ts | 4 +- tests/dsh-llm-stream-attribution.test.ts | 65 +++++++ tests/dsh-native-compaction.test.ts | 110 +++++++++++ tests/native-intercept.test.ts | 20 ++ tests/native-ws-intercept.test.ts | 22 +++ tsup.config.ts | 2 +- website/config-reference/server.yaml | 22 ++- 25 files changed, 793 insertions(+), 24 deletions(-) create mode 100644 docs/dsh-native-compaction.md create mode 100644 docs/dsh-native-compaction.zh-CN.md create mode 100644 scripts/test-dsh-native-compaction.mjs create mode 100644 src/agent/dsh-native-compaction.ts create mode 100644 tests/dsh-native-compaction.test.ts 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 6aeef6e88e..49c0b98ad2 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`) in this directory, each with its own diagram. > 中文: [architecture.zh-CN.md](./architecture.zh-CN.md) > diff --git a/docs/architecture.zh-CN.md b/docs/architecture.zh-CN.md index 6b512f93ad..4cfe56955a 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) > diff --git a/docs/configuration.md b/docs/configuration.md index 780706a255..7f8b7ea233 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -122,7 +122,10 @@ This index is generated from `website/config-reference/*.yaml` — edit the seed | `compat.streamErrorShape` | "protocol" \| "completion" | protocol | BILI_STREAM_ERROR_SHAPE | How upstream stream failures are presented after the 200 is committed: protocol-native error frames (default) or the legacy synthesized-completion shape. | | `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 da99ac3aff..c59be022ad 100644 --- a/docs/configuration.zh-CN.md +++ b/docs/configuration.zh-CN.md @@ -122,7 +122,10 @@ | `compat.streamErrorShape` | "protocol" \| "completion" | protocol | BILI_STREAM_ERROR_SHAPE | 200 已提交后上游流失败的呈现方式:协议原生错误帧(默认)或旧版合成完成形态。 | | `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..a1a4ce565f --- /dev/null +++ b/docs/dsh-native-compaction.md @@ -0,0 +1,59 @@ +# 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 captured model selection] --> B{Native model rule?} + B -->|yes| C[Original native compaction backend] + C --> D{Summary fits?} + D -->|yes| E[Original summarizer] + D -->|no| F[Balanced bounded summary batches] + F --> E + E --> G[DSH checkpoint transaction] + G --> H[Direct provider transport] + B -->|no| I[DSH durable replacement generation] + I --> J[Bili conversation namespace] + J --> K[Existing bili compression pipeline] +``` + +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. + +The adapter gates automatic/manual native compression for bili-owned models and hides bili tools on native-owned steps. Native HTTP requests retain the original body, headers and provider transport. WebSocket connections cannot carry a request under a different compression owner: the mismatched frame is withheld and the connection is closed so the host can reconnect, using its existing transport recovery. + +When switching bili → native, all selected raw messages go through DSH's summarizer. Oversized input is reduced in balanced groups; a tool call and all its results are indivisible. System messages and tool schemas are retained in each batch. A failed/cancelled/no-progress summary, or one indivisible message/group larger than the summary window, fails visibly; no partial replacement checkpoint is committed. Normal LLM summarization is lossy; this feature cannot guarantee retention of every detail. + +When switching native → bili, the host's durable `surface.replaceGeneration` changes the bili conversation namespace. New folds cannot reuse an earlier substrate. 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`. 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 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. + +## 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..c0d32cc750 --- /dev/null +++ b/docs/dsh-native-compaction.zh-CN.md @@ -0,0 +1,59 @@ +# 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[原生压缩后端] + C --> D{摘要输入能放下?} + D -->|能| E[原生摘要器] + D -->|不能| F[保持工具配对的分批摘要] + F --> E + E --> G[DSH 检查点事务] + G --> H[直接调用供应商] + B -->|否| I[宿主持久化替换代数] + I --> J[Bili 会话命名空间] + J --> K[原有 bili 压缩流程] +``` + +原生触发阈值、近期内容保留、摘要提示词和摘要模型选择由 DSH 决定。模型切换时,DSH 可能使用上一轮模型生成摘要,除非其原生配置另行指定;这些摘要请求仍绕过 bili,不受摘要模型是否命中规则影响。 + +原生步骤不提供 bili 压缩工具;bili 步骤不触发宿主原生压缩。原生 HTTP 请求保留原始请求体、请求头和供应商传输。WebSocket 若复用跨压缩模式的连接,会先阻止该帧并关闭连接,由宿主既有传输恢复机制重连。 + +**bili → 原生:** 选中的原始历史进入 DSH 摘要器。超长输入分批缩减,工具调用及其全部结果不可拆开,系统消息和工具定义随每批保留。失败、取消、无法缩短或单个消息/工具组超出摘要窗口时明确报错,不提交部分替换检查点。摘要仍然有损,无法保证每个细节都保留。 + +**原生 → bili:** 使用宿主持久化的 `surface.replaceGeneration` 区分 bili 命名空间,防止旧折叠套用到新摘要上。重启重放后保持一致;普通追加消息或未发生宿主替换的模型切换不会改名。DSH 会话 ID 与原始追加日志保持原样。发生替换后,该命名空间停用旧协商别名、分叉继承和增量发送,采用完整发送及新的水位种子;其他会话沿用原路径。上下文页和 `/acp` 跟随当前命名空间,原生模式显示归属,不展示过时 bili 数据。 + +## 验证与边界 + +针对 DSH `0.2.2-rc.1` 验证。集成脚本使用真实 Cordis Loader、独立压缩作用域、token meter、Session 重放和原生检查点引擎;模型为确定性假实现,不消耗账户额度: + +```sh +node scripts/test-dsh-native-compaction.mjs /绝对路径/隔离的DSH运行时 +``` + +运行时必须是独立副本,不是正在运行的 profile。测试不使用凭据、现有会话或线上文件;不代表已经验证真实模型的摘要质量或计费。 + +预设未挂载适配器时,原生请求明确失败。原厂 minimal 预设没有压缩后端,命中原生规则时维持其原样,不额外添加压缩。CLI 根作用域配置、未来 DSH API 版本需要额外适配,不能直接视为已支持。 + +## 后续更新保留补丁 + +保存源码提交、补丁和测试。对目标上游版本先执行 `git apply --check`,再执行类型检查、针对性测试、构建及真实 DSH 集成验证,全部通过才打包。profile 使用其管理渠道的本地 `file:` 包固定,避免注册表更新覆盖补丁;以后更新改为明确的“重建、验证、安装”流程。保留原包、profile 清单/锁文件及配置用于回滚。不要将旧 `dist` 覆盖到新版源码上。 + +未来上游可能产生冲突或改变语义,即使补丁文本能套用也不代表兼容。检查失败时应保留已安装版本并重新审查补丁,不能保证未知的所有未来版本均可自动应用。 + +使用后若要让全部模型回到 bili,请保留配置键并设为 `nativeCompactionModels: []`;显式空列表仍保留代数隔离。删除整个配置键或移除补丁属于另一次迁移,可能重新暴露旧 bili 命名空间,不能等同于清空规则。 diff --git a/docs/index.md b/docs/index.md index a6c702e829..9ba14e1fb5 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 13ff1da560..4dc87934a4 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", "./client": "./dist/agent/dsh-native-client.js" diff --git a/reference/architecture.md b/reference/architecture.md index d42f41e411..785535a69b 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -222,6 +222,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) │ │ ├── fork-adopt.ts # Client half of fork adoption: prefix match + receipt (#2399) │ │ ├── host-log.ts # Host-safe log channel: durable record, zero terminal traffic (#2827) │ │ ├── incremental-client.ts # Host-process incremental-turn client: diff, ack, resync (#3248) diff --git a/scripts/check-unused-exports.mjs b/scripts/check-unused-exports.mjs index 023de50059..12716574b0 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/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs new file mode 100644 index 0000000000..ebe9c792ab --- /dev/null +++ b/scripts/test-dsh-native-compaction.mjs @@ -0,0 +1,81 @@ +import assert from 'node:assert/strict'; +import { pathToFileURL } from 'node:url'; +import path from 'node:path'; +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 { BasicCompactionEngine } = await load('dsh-compaction-basic'); +const { createUserMessage, createSystemMessage } = await load('dsh-llm'); +const policy = await import('../dist/agent/dsh-native-compaction.js'); +policy.configureNativeCompaction([{ model: 'gpt-*' }]); +const ctx = new Context(); +const calls = []; +let fail = false; +await ctx.plugin(c => c.reflect.provide('llm', { + imageRequestPricing: () => undefined, + resolveModelInfo: async () => ({ context: { contextWindow: 18000 }, defaultMaxTokens: 100 }), + async *stream(options) { + assert.equal(policy.nativeSummaryActive(), true); + const cost = options.messages.reduce((n, m) => n + ctx.tokenMeter.estimateMessage(m), 0); + assert.ok(cost + options.maxTokens < 18000, `summary overflow: ${cost}`); + calls.push(options); + if (fail) throw new Error('synthetic provider failure'); + yield { type: 'text-delta', index: 0, text: 'Facts retained: checkpoint integration verified.' }; + 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: { auto: true, thresholdRatio: 0.8, headroomTokens: 1000, maxTokens: 200, retainTokens: 1000 } }, + { 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, 'isolated preset group provides its compaction engine'); +assert.equal(ctx.get('compaction'), undefined, 'preset engine does not leak to the host plane'); +function fixture(id, model, count = 16) { + const session = ctx.sessions.create(id); + session.append('system/message', { message: createSystemMessage('Keep the facts.') }, { surfaceOp: 'append' }); + session.append('request/header', { header: { config: { provider: 'fake', model, maxTokens: 200 } }, reason: 'initial' }); + for (let i = 0; i < count; i++) session.append('user/message', createUserMessage({ content: [{ type: 'text', text: `fact-${i}: `.repeat(2600) }], source: { kind: 'user' } }), { surfaceOp: 'append' }); + session.append('turn/start', { turn: 'test-turn' }); + return { session, options: { provider: 'fake', model }, model: { current: () => ({ provider: 'fake', model }), select: next => { model = next; } } }; +} +try { + const bili = fixture('bili-test', 'kimi'); + const before = bili.session.surface.replaceGeneration; + assert.equal(await engine.compactIfNeeded(bili, 'pressure'), null); + assert.equal(bili.session.surface.replaceGeneration, before); + const agent = fixture('switch-test', 'kimi'); + agent.model.select('gpt-5'); + const old = agent.session.snapshotEvents(); + const originalCount = agent.session.surface.nodes.length; + const result = await engine.compactPressure(agent, { config: { provider: 'fake', model: 'gpt-5', maxTokens: 200 } }, undefined, true); + assert.ok(result); + assert.ok(calls.length > 1, 'oversized handoff uses multiple bounded native calls'); + assert.ok(agent.session.surface.nodes.length < originalCount); + assert.ok(agent.session.surface.replaceGeneration > 0); + assert.deepEqual(agent.session.snapshotEvents().slice(0, old.length), old, 'raw log remains immutable'); + const resumed = Session.create(agent.session.id, agent.session.snapshotEvents(), agent.session.header); + assert.equal(policy.compactionConversationId({ session: resumed }, resumed.id), policy.compactionConversationId(agent, agent.session.id)); + agent.model.select('kimi'); + const generation = agent.session.surface.replaceGeneration; + assert.equal(await engine.compactIfNeeded(agent, 'pressure'), null); + assert.equal(agent.session.surface.replaceGeneration, generation); + const broken = fixture('failed-test', 'gpt-5'); + const nodes = [...broken.session.surface.nodes]; + fail = true; + await assert.rejects(engine.compactIfNeeded(broken, 'pressure'), /synthetic provider failure/); + assert.deepEqual(broken.session.surface.nodes, nodes); + assert.equal(broken.session.surface.replaceGeneration, 0); + console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', summaryCalls: calls.length, originalSurfaceNodes: originalCount, finalSurfaceNodes: agent.session.surface.nodes.length, generation: agent.session.surface.replaceGeneration })); +} finally { await ctx.fiber.dispose(); } diff --git a/src/agent/dsh-compaction-disable.ts b/src/agent/dsh-compaction-disable.ts index 4970e3d159..a3002d74d9 100644 --- a/src/agent/dsh-compaction-disable.ts +++ b/src/agent/dsh-compaction-disable.ts @@ -33,6 +33,8 @@ // bundle-patch gate rows may target ids a profile does not ship — their miss // is otherwise visible only in the host loader log). +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"; @@ -78,6 +80,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"; } @@ -166,6 +169,19 @@ export function disableBasicCompaction(rows: readonly unknown[]): unknown[] { }); } +export function selectiveBasicCompaction(rows: readonly unknown[]): unknown[] { + const result = rows.map(row => { + if (row === null || typeof row !== "object") return row; + const r = row as PresetRow; + return r.group && Array.isArray(r.config) ? { ...r, config: selectiveBasicCompaction(r.config) } : row; + }); + if (rows.some(row => row !== null && typeof row === "object" && (row as PresetRow).name === DSH_COMPACTION_BASIC_PACKAGE) && + !rows.some(row => row !== null && typeof row === "object" && (row as PresetRow).name === "billion-context/dsh-native-compaction")) { + result.push({ name: "billion-context/dsh-native-compaction" }); + } + return result; +} + export type CompactionDisableHost = { on?: (event: string, listener: (raw: unknown, next: () => unknown) => unknown, options?: { global?: boolean }) => void; reflect?: { provide?: (name: string, value: unknown) => void } | undefined; @@ -195,12 +211,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 = this?.entry?.options?.name; 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: [...config.plugins, { name: "billion-context/dsh-native-compaction", config: { noBackend: true } }] }; + } 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..81ee9fc5d5 --- /dev/null +++ b/src/agent/dsh-native-compaction.ts @@ -0,0 +1,223 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { randomUUID } from "node:crypto"; +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 PolicyConfig = { summarizationProvider: string; summarizationModel: string; maxTokens: number; modelPolicies?: readonly (Target & Partial)[] }; +type Engine = { + config: PolicyConfig; + 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; + tokenMeter: { estimateMessage(message: Message): number }; + llm: { resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<{ context?: { contextWindow: number } }> }; + 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; +}; + +/** Balanced groups are indivisible: never separate a tool call from its result. */ +export function summaryGroups(messages: readonly Message[]): Message[][] { + const groups: Message[][] = []; + let pending = new Set(); + let group: Message[] = []; + for (const message of messages) { + group.push(message); + if (message.role === "tool") { + if (typeof message.toolCallId !== "string" || !pending.delete(message.toolCallId)) throw new Error("unpaired tool result in native handoff"); + } + for (const block of message.content) { + if (block.type === "tool-call") { + if (!block.id || pending.has(block.id)) throw new Error("invalid tool call in native handoff"); + pending.add(block.id); + } + } + if (!pending.size) { groups.push(group); group = []; } + } + if (pending.size) throw new Error("unfinished tool calls in native handoff"); + return groups; +} + +export async function boundedNativeSummary( + input: SummaryInput, budget: number, estimate: (message: Message) => number, + summarize: (input: SummaryInput) => Promise, signal?: AbortSignal, +): Promise { + const total = (messages: readonly Message[]) => messages.reduce((n, m) => n + estimate(m), 0); + let messages = [...input.messages]; + const system: Message[] = []; + while (messages[0]?.role === "system") system.push(messages.shift()!); + const available = budget - total(system); + if (available <= 0) throw new Error("native handoff system prompt exceeds summary input budget"); + for (let round = 0; round < 16; round++) { + signal?.throwIfAborted(); + if (total(messages) <= available) return summarize({ ...input, messages: [...system, ...messages] }); + const chunks: Message[][] = []; + let chunk: Message[] = [], size = 0; + for (const group of summaryGroups(messages)) { + const cost = total(group); + if (cost > available) throw new Error("native handoff contains a single tool group/message larger than the summary window; history was preserved"); + if (size + cost > available) { chunks.push(chunk); chunk = []; size = 0; } + chunk.push(...group); size += cost; + } + if (chunk.length) chunks.push(chunk); + const reduced: Message[] = []; + for (const part of chunks) { + signal?.throwIfAborted(); + const result = await summarize({ ...input, messages: [...system, ...part] }); + reduced.push({ id: randomUUID(), role: "user", content: result.summary, source: { kind: "user" } }); + } + if (total(reduced) >= total(messages)) throw new Error("native handoff summary made no progress; history was preserved"); + messages = reduced; + } + throw new Error("native handoff exceeded its reduction bound; history was preserved"); +} + +export const name = "bili-native-compaction"; +export const inject = ["tokenMeter", "llm"]; +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"); + const target = agent.session.requestHeader?.()?.config ?? agent.model?.current(); + const override = engine.config.modelPolicies?.find(p => p.provider === target?.provider && p.model === target?.model); + const config = { ...engine.config, ...override }; + const provider = config.summarizationProvider || target?.provider; + const model = config.summarizationModel || target?.model; + if (typeof provider !== "string" || typeof model !== "string") throw new Error("native summary has no model target"); + const info = await ctx.llm.resolveModelInfo(provider, model, signal); + const window = info.context?.contextWindow; + if (!window) throw new Error("native summary model has no context window"); + // Reserve output, instruction and tool-schema overhead. The meter uses + // the host's tokenizer; the schema fallback deliberately overestimates. + const budget = Math.floor(window * 0.9) - config.maxTokens - 4096 - Buffer.byteLength(JSON.stringify(input.tools ?? [])); + if (budget <= 0) throw new Error("native summary model has insufficient input budget"); + return state().summary.run(true, () => boundedNativeSummary(input, budget, m => ctx.tokenMeter.estimateMessage(m), + part => originals.summarize.call(engine, part, agent, signal), 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 c7dd3ffded..f60cfb3e2c 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 @@ -104,8 +106,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 @@ -148,7 +152,7 @@ type ToolDefinition = { type CommandOutcome = { kind: "success" | "error"; text: string }; export type PluginContext = { - tools: { register: (definition: ToolDefinition) => unknown }; + tools: { register: (definition: ToolDefinition, options?: { when: (context: { agent?: AgentLike; modelSelection?: { provider?: unknown; model?: unknown } }) => boolean }) => 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 @@ -926,6 +930,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; @@ -936,7 +941,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); + const out = await forwardTool(base, compactionConversationId(exec.agent, sid), tool.name, args, exec.signal, true); // #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); @@ -994,7 +999,7 @@ async function registerTools(ctx: PluginContext): Promise { let adopted = 0; for (const tool of tools) { try { - target.tools.register(toolDefinition(tool)); + target.tools.register(toolDefinition(tool), { when: ({ agent, modelSelection }) => !compactionGenerationIsolation() || !nativeModel(modelSelection ?? agent?.model?.current() ?? agent?.session?.requestHeader?.()?.config) }); } catch (err) { // #3380: idempotent adoption — a name this process ALREADY // holds in the host tool layer throws "already registered"; @@ -1187,9 +1192,19 @@ type GateAttribution = interface LlmDispatchScope { sid: string; msgIds: string[] | undefined; + nativeCompaction?: boolean; + conversationId?: string; + titleRequest?: boolean; } 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; /** #4491: extract the host message ids from llm/stream `options.messages`, @@ -1619,6 +1634,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 @@ -1646,7 +1662,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); @@ -1691,6 +1708,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 { @@ -1702,7 +1720,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 { @@ -1961,6 +1979,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; @@ -2008,13 +2027,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); }, @@ -2040,20 +2071,25 @@ 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 }, 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 scope: LlmDispatchScope = { sid, msgIds: hostMsgIdsOf(options?.messages) }; + const agent = compactionGenerationIsolation() ? compactionAgentOf(ctx, sid) : undefined; + const native = nativeSummaryActive() || (options.purpose === "compaction" ? nativeAgent(agent) : nativeModel(options)); + const titleRequest = options.purpose === "session-title"; + if (native && !nativeSummaryActive() && !titleRequest) requireNativeCompactionReady(agent); + const conversationId = native || titleRequest ? sid : compactionConversationId(agent, sid); + const scope: LlmDispatchScope = { sid, msgIds: hostMsgIdsOf(options?.messages), nativeCompaction: native, conversationId, titleRequest }; // #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 @@ -2356,6 +2392,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) => { const attr = attributionOf(ctx); if (attr.state === "ok") { @@ -2548,7 +2585,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) }; // #3370: the incremental-turn marker (and, since #3329, the turn id) // is no longer stamped here — a closure-level armed flag shared by // every session raced concurrent requests across the awaited @@ -2590,6 +2629,15 @@ 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() && !dispatchScope.getStore()?.titleRequest) { + 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 e2412cb1d9..ccfe800bea 100644 --- a/src/agent/native-intercept.ts +++ b/src/agent/native-intercept.ts @@ -132,6 +132,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 @@ -1599,6 +1601,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 0e17c2b20f..13f80ee739 100644 --- a/src/agent/native-ws-intercept.ts +++ b/src/agent/native-ws-intercept.ts @@ -151,9 +151,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"); } }; @@ -172,6 +172,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 } }; @@ -529,6 +531,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 30e31d0154..2b6016acdc 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1151,6 +1151,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). */ @@ -2706,7 +2708,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/tests/dsh-llm-stream-attribution.test.ts b/tests/dsh-llm-stream-attribution.test.ts index 70d6790a24..e72e5fe13e 100644 --- a/tests/dsh-llm-stream-attribution.test.ts +++ b/tests/dsh-llm-stream-attribution.test.ts @@ -37,6 +37,71 @@ 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 } from "../src/agent/dsh-native-compaction.ts"; +import { installNativeFetchIntercept, _resetForTest as resetFetchIntercept } from "../src/agent/native-intercept.ts"; + +test("DSH dispatch switches native/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 }> = []; + proxy.server.on("request", req => { + if (req.url?.startsWith("/bili/")) routed.push({ url: req.url, conversation: req.headers["x-bili-plugin-conversation"] }); + }); + 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 = "codex/gpt-test"; + 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-*" }]); + 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 }, 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 { + await send('{"model":"codex/gpt-test","input":"native one"}'); + 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, '{"model":"codex/gpt-test","input":"native one"}'); + 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"); + model = "codex/gpt-test"; + await send('{"model":"codex/gpt-test","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"; diff --git a/tests/dsh-native-compaction.test.ts b/tests/dsh-native-compaction.test.ts new file mode 100644 index 0000000000..02b5652e3a --- /dev/null +++ b/tests/dsh-native-compaction.test.ts @@ -0,0 +1,110 @@ +import test, { afterEach } from "node:test"; +import assert from "node:assert/strict"; +import { apply, boundedNativeSummary, compactionConversationId, configureNativeCompaction, nativeAgent, nativeModel, nativeSummaryActive, requireNativeCompactionReady, summaryGroups } 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 }] }); +const estimate = (m: { content: readonly { text?: string }[] }) => m.content.reduce((n, b) => n + (b.text?.length ?? 0), 0); + +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("handoff groups retain complete parallel tool calls/results", () => { + const messages = [{ role: "assistant", content: [{ type: "tool-call", id: "a" }, { type: "tool-call", id: "b" }] }, + { role: "tool", toolCallId: "a", content: [{ type: "text", text: "A" }] }, + { role: "tool", toolCallId: "b", content: [{ type: "text", text: "B" }] }, message("tail")]; + assert.deepEqual(summaryGroups(messages), [messages.slice(0, 3), [messages[3]]]); + assert.throws(() => summaryGroups(messages.slice(0, 2)), /unfinished/); + assert.throws(() => summaryGroups(messages.slice(1)), /unpaired/); +}); + +test("bounded summary covers every original message, retains system and tool schema, does not mutate input", async () => { + const input = { messages: [{ ...message("system"), role: "system" }, ...Array.from({ length: 10 }, (_, i) => message(`fact-${i} `.repeat(5)))], tools: [{ name: "read" }] }; + const before = structuredClone(input); + const seen: string[] = []; + const result = await boundedNativeSummary(input, 110, estimate, async part => { + assert.equal(part.messages[0].role, "system"); + assert.deepEqual(part.tools, input.tools); + assert.ok(part.messages.reduce((n, m) => n + estimate(m as ReturnType), 0) <= 110); + seen.push(...part.messages.slice(1).flatMap(m => m.content.map(b => b.text ?? ""))); + return { summary: [{ type: "text", text: "summary" }] }; + }); + assert.deepEqual(result.summary, [{ type: "text", text: "summary" }]); + for (let i = 0; i < 10; i++) assert.ok(seen.some(text => text.includes(`fact-${i}`))); + assert.deepEqual(input, before); +}); + +test("bounded summary propagates cancellation/failure and rejects no-progress or oversized indivisible messages", async () => { + const input = { messages: [message("x".repeat(60)), message("y".repeat(60))] }; + const stop = new AbortController(); stop.abort(new Error("cancelled")); + await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { throw new Error("should not run"); }, stop.signal), /cancelled/); + await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { throw new Error("provider failure"); }), /provider failure/); + await assert.rejects(boundedNativeSummary(input, 100, estimate, async p => ({ summary: p.messages[0].content })), /no progress/); + await assert.rejects(boundedNativeSummary(input, 30, estimate, async () => ({ summary: [] })), /larger/); +}); + +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 = { + config: { summarizationProvider: "", summarizationModel: "", maxTokens: 100 }, + 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, tokenMeter: { estimateMessage: () => 20 }, llm: { resolveModelInfo: async () => ({ context: { contextWindow: 20000 } }) }, 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"]); +}); diff --git a/tests/native-intercept.test.ts b/tests/native-intercept.test.ts index c3e16b75d0..beb3fe11f5 100644 --- a/tests/native-intercept.test.ts +++ b/tests/native-intercept.test.ts @@ -7,6 +7,26 @@ import { createLiveOriginResolver, installNativeFetchIntercept, isModelApiUrl, l 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/tsup.config.ts b/tsup.config.ts index 0d806a1677..494a453b5e 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/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"], + 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/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"], format: ["esm"], target: "node20", platform: "node", diff --git a/website/config-reference/server.yaml b/website/config-reference/server.yaml index beb75a8ca5..36cc668cb3 100644 --- a/website/config-reference/server.yaml +++ b/website/config-reference/server.yaml @@ -380,8 +380,26 @@ 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_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——见接下来的条目。" + - 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。" + - 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,精确匹配或末尾 * 前缀匹配,不使用显示名或其他通配形式。" + - 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,精确限定该条原生压缩模型规则。" - key: dsh.authoredCompaction type: boolean default: "true (on, #3901 flip)" From a0ece877513b042d5df609550530cfa41edbcec5 Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Tue, 10 Nov 2026 21:56:14 +0800 Subject: [PATCH 2/9] fix(dsh): meter summary tool schemas in host tokens --- docs/dsh-native-compaction.md | 2 ++ docs/dsh-native-compaction.zh-CN.md | 2 ++ scripts/test-dsh-native-compaction.mjs | 36 +++++++++++++++++++++----- src/agent/dsh-native-compaction.ts | 10 ++++--- tests/dsh-native-compaction.test.ts | 36 ++++++++++++++++++++++++++ 5 files changed, 76 insertions(+), 10 deletions(-) diff --git a/docs/dsh-native-compaction.md b/docs/dsh-native-compaction.md index a1a4ce565f..d762d837f2 100644 --- a/docs/dsh-native-compaction.md +++ b/docs/dsh-native-compaction.md @@ -32,6 +32,8 @@ flowchart LR 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. +The summary input budget reserves output, summary instructions and a safety margin. Tool definitions are priced with the host's `tokenMeter.estimateMessage`, in the same units as messages; the temporary text message used for metering is never sent. UTF-8 schema bytes must not be subtracted directly as tokens, which can falsely exhaust the budget for a large MCP catalog. Every summary batch still carries the complete original schemas. A catalog whose token estimate truly exceeds the available budget fails while preserving history. + The adapter gates automatic/manual native compression for bili-owned models and hides bili tools on native-owned steps. Native HTTP requests retain the original body, headers and provider transport. WebSocket connections cannot carry a request under a different compression owner: the mismatched frame is withheld and the connection is closed so the host can reconnect, using its existing transport recovery. When switching bili → native, all selected raw messages go through DSH's summarizer. Oversized input is reduced in balanced groups; a tool call and all its results are indivisible. System messages and tool schemas are retained in each batch. A failed/cancelled/no-progress summary, or one indivisible message/group larger than the summary window, fails visibly; no partial replacement checkpoint is committed. Normal LLM summarization is lossy; this feature cannot guarantee retention of every detail. diff --git a/docs/dsh-native-compaction.zh-CN.md b/docs/dsh-native-compaction.zh-CN.md index c0d32cc750..2447756f81 100644 --- a/docs/dsh-native-compaction.zh-CN.md +++ b/docs/dsh-native-compaction.zh-CN.md @@ -32,6 +32,8 @@ flowchart LR 原生触发阈值、近期内容保留、摘要提示词和摘要模型选择由 DSH 决定。模型切换时,DSH 可能使用上一轮模型生成摘要,除非其原生配置另行指定;这些摘要请求仍绕过 bili,不受摘要模型是否命中规则影响。 +摘要输入预算预留输出、摘要指令和安全余量。工具定义经宿主 `tokenMeter.estimateMessage` 估算 token,采用与消息相同的计量单位;用于计量的临时文本消息不会发送给模型。不能把工具 JSON 的 UTF-8 字节数直接当成 token 扣除,否则大型 MCP 工具目录会错误耗尽预算。工具定义仍完整随每批摘要请求发送;如果其 token 估算确实超过可用预算,则保留历史并报错。 + 原生步骤不提供 bili 压缩工具;bili 步骤不触发宿主原生压缩。原生 HTTP 请求保留原始请求体、请求头和供应商传输。WebSocket 若复用跨压缩模式的连接,会先阻止该帧并关闭连接,由宿主既有传输恢复机制重连。 **bili → 原生:** 选中的原始历史进入 DSH 摘要器。超长输入分批缩减,工具调用及其全部结果不可拆开,系统消息和工具定义随每批保留。失败、取消、无法缩短或单个消息/工具组超出摘要窗口时明确报错,不提交部分替换检查点。摘要仍然有损,无法保证每个细节都保留。 diff --git a/scripts/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs index ebe9c792ab..eb1da69ed8 100644 --- a/scripts/test-dsh-native-compaction.mjs +++ b/scripts/test-dsh-native-compaction.mjs @@ -18,11 +18,13 @@ const calls = []; let fail = false; await ctx.plugin(c => c.reflect.provide('llm', { imageRequestPricing: () => undefined, - resolveModelInfo: async () => ({ context: { contextWindow: 18000 }, defaultMaxTokens: 100 }), + resolveModelInfo: async (_provider, model) => ({ context: { contextWindow: model === 'gpt-luna' ? 272000 : 18000 }, defaultMaxTokens: 100 }), async *stream(options) { assert.equal(policy.nativeSummaryActive(), true); const cost = options.messages.reduce((n, m) => n + ctx.tokenMeter.estimateMessage(m), 0); - assert.ok(cost + options.maxTokens < 18000, `summary overflow: ${cost}`); + const toolsTokens = options.tools?.length ? Math.ceil(JSON.stringify(options.tools).length / 4) + 4 : 0; + const window = options.model === 'gpt-luna' ? 272000 : 18000; + assert.ok(cost + toolsTokens + options.maxTokens < window, `summary overflow: ${cost} + ${toolsTokens}`); calls.push(options); if (fail) throw new Error('synthetic provider failure'); yield { type: 'text-delta', index: 0, text: 'Facts retained: checkpoint integration verified.' }; @@ -35,18 +37,18 @@ 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: { auto: true, thresholdRatio: 0.8, headroomTokens: 1000, maxTokens: 200, retainTokens: 1000 } }, + { name: new URL('dsh-compaction-basic/lib/index.js', root).href, config: { auto: true, thresholdRatio: 0.8, headroomTokens: 1000, maxTokens: 200, retainTokens: 1000, modelPolicies: [{ provider: 'fake', model: 'gpt-luna', headroomTokens: 65536, maxTokens: 65536, retainTokens: 32245 }] } }, { 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, 'isolated preset group provides its compaction engine'); assert.equal(ctx.get('compaction'), undefined, 'preset engine does not leak to the host plane'); -function fixture(id, model, count = 16) { +function fixture(id, model, count = 16, tools = [], repeats = 2600) { const session = ctx.sessions.create(id); session.append('system/message', { message: createSystemMessage('Keep the facts.') }, { surfaceOp: 'append' }); - session.append('request/header', { header: { config: { provider: 'fake', model, maxTokens: 200 } }, reason: 'initial' }); - for (let i = 0; i < count; i++) session.append('user/message', createUserMessage({ content: [{ type: 'text', text: `fact-${i}: `.repeat(2600) }], source: { kind: 'user' } }), { surfaceOp: 'append' }); + session.append('request/header', { header: { config: { provider: 'fake', model, maxTokens: model === 'gpt-luna' ? 70464 : 200 }, ...(tools.length ? { tools } : {}) }, reason: 'initial' }); + for (let i = 0; i < count; i++) session.append('user/message', createUserMessage({ content: [{ type: 'text', text: `fact-${i}: `.repeat(repeats) }], source: { kind: 'user' } }), { surfaceOp: 'append' }); session.append('turn/start', { turn: 'test-turn' }); return { session, options: { provider: 'fake', model }, model: { current: () => ({ provider: 'fake', model }), select: next => { model = next; } } }; } @@ -71,11 +73,31 @@ try { const generation = agent.session.surface.replaceGeneration; assert.equal(await engine.compactIfNeeded(agent, 'pressure'), null); assert.equal(agent.session.surface.replaceGeneration, generation); + const tools = Array.from({ length: 327 }, (_, i) => ({ name: `tool_${i}`, description: 'Synthetic 工具目录 description. '.repeat(40), parameters: { type: 'object', properties: {} } })); + assert.ok(Buffer.byteLength(JSON.stringify(tools)) > 272000); + const large = fixture('large-tool-test', 'gpt-luna', 12, tools, 7500); + const largeHistory = large.session.snapshotEvents(); + const largeBefore = ctx.tokenMeter.measure(large.session).totalTokens; + const beforeCalls = calls.length; + assert.ok(await engine.compactIfNeeded(large, 'pressure')); + const largeCalls = calls.slice(beforeCalls); + assert.ok(largeCalls.length > 1, 'large catalog still allows bounded multi-batch summary'); + for (const call of largeCalls) assert.deepEqual(call.tools, tools); + assert.deepEqual(large.session.snapshotEvents().slice(0, largeHistory.length), largeHistory); + assert.equal(large.session.surface.replaceGeneration, 1); + assert.ok(ctx.tokenMeter.measure(large.session).totalTokens < 136000, 'native pressure drops below the Luna threshold'); + const oversized = fixture('oversized-tools-test', 'gpt-luna', 16, [{ name: 'too_large', description: 'x'.repeat(800000), parameters: { type: 'object' } }]); + const oversizedSurface = [...oversized.session.surface.nodes]; + const beforeOversize = calls.length; + await assert.rejects(engine.compactIfNeeded(oversized, 'pressure'), /insufficient input budget/); + assert.equal(calls.length, beforeOversize); + assert.deepEqual(oversized.session.surface.nodes, oversizedSurface); + assert.equal(oversized.session.surface.replaceGeneration, 0); const broken = fixture('failed-test', 'gpt-5'); const nodes = [...broken.session.surface.nodes]; fail = true; await assert.rejects(engine.compactIfNeeded(broken, 'pressure'), /synthetic provider failure/); assert.deepEqual(broken.session.surface.nodes, nodes); assert.equal(broken.session.surface.replaceGeneration, 0); - console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', summaryCalls: calls.length, originalSurfaceNodes: originalCount, finalSurfaceNodes: agent.session.surface.nodes.length, generation: agent.session.surface.replaceGeneration })); + console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', summaryCalls: calls.length, originalSurfaceNodes: originalCount, finalSurfaceNodes: agent.session.surface.nodes.length, generation: agent.session.surface.replaceGeneration, largeCatalog: { tools: tools.length, summaryCalls: largeCalls.length, beforeTokens: largeBefore, afterTokens: ctx.tokenMeter.measure(large.session).totalTokens } })); } finally { await ctx.fiber.dispose(); } diff --git a/src/agent/dsh-native-compaction.ts b/src/agent/dsh-native-compaction.ts index 81ee9fc5d5..7e4715a61f 100644 --- a/src/agent/dsh-native-compaction.ts +++ b/src/agent/dsh-native-compaction.ts @@ -205,9 +205,13 @@ function attachEngine(ctx: Host): void { const info = await ctx.llm.resolveModelInfo(provider, model, signal); const window = info.context?.contextWindow; if (!window) throw new Error("native summary model has no context window"); - // Reserve output, instruction and tool-schema overhead. The meter uses - // the host's tokenizer; the schema fallback deliberately overestimates. - const budget = Math.floor(window * 0.9) - config.maxTokens - 4096 - Buffer.byteLength(JSON.stringify(input.tools ?? [])); + // Price schema text with the same host heuristic as messages, never UTF-8 bytes. + // The synthetic message is only metered, not sent; its framing adds a small reserve. + const toolsTokens = input.tools?.length ? ctx.tokenMeter.estimateMessage({ + role: "user", content: [{ type: "text", text: JSON.stringify(input.tools) }], + }) : 0; + if (!Number.isFinite(toolsTokens) || toolsTokens < 0) throw new Error("native summary tool token estimate is invalid"); + const budget = Math.floor(window * 0.9) - config.maxTokens - 4096 - toolsTokens; if (budget <= 0) throw new Error("native summary model has insufficient input budget"); return state().summary.run(true, () => boundedNativeSummary(input, budget, m => ctx.tokenMeter.estimateMessage(m), part => originals.summarize.call(engine, part, agent, signal), signal)); diff --git a/tests/dsh-native-compaction.test.ts b/tests/dsh-native-compaction.test.ts index 02b5652e3a..b85f27ef25 100644 --- a/tests/dsh-native-compaction.test.ts +++ b/tests/dsh-native-compaction.test.ts @@ -108,3 +108,39 @@ test("adapter gates native methods and scopes summary bypass without leaking to assert.equal(await ctx.compaction.compactPressure(agent, { config: { model } }), null); assert.deepEqual(calls, ["auto"]); }); + +test("native summary budgets large multilingual tool catalogs in host tokens, preserving schemas on every batch", async () => { + configureNativeCompaction([{ model: "gpt-*" }]); + const agent = { session: { id: "large-tools", requestHeader: () => ({ config: { provider: "test", model: "gpt-luna" } }) } }; + const meter = (m: Parameters[0]["tokenMeter"]["estimateMessage"]>[0]) => + m.content.reduce((n, b) => n + Math.ceil((b.text?.length ?? 0) / 4) + 4, 4); + const tools = Array.from({ length: 327 }, (_, i) => ({ name: `tool_${i}`, description: "Synthetic 工具目录 description. ".repeat(40), parameters: { type: "object", properties: {} } })); + assert.ok(Buffer.byteLength(JSON.stringify(tools)) > 272000); + const input = { tools, messages: [{ ...message("System rules."), role: "system" }, ...Array.from({ length: 6 }, (_, i) => message(`fact-${i} `.repeat(15000)))] }; + const before = structuredClone(input); + let calls = 0; + const seen = new Set(); + const engine: Parameters[0]["compaction"] = { + config: { summarizationProvider: "", summarizationModel: "", maxTokens: 65536 }, + compactIfNeeded: async () => null, compactPressure: async () => null, + compactRegion: async () => null, compactNow: async () => null, + summarize: async part => { + calls++; + assert.equal(nativeSummaryActive(), true); + assert.deepEqual(part.tools, tools); + const schemaTokens = meter(message(JSON.stringify(part.tools))); + assert.ok(part.messages.reduce((n, m) => n + meter(m), 0) + schemaTokens + 65536 + 4096 <= Math.floor(272000 * 0.9)); + for (const m of part.messages) for (const b of m.content) for (const fact of b.text?.match(/fact-\d/g) ?? []) seen.add(fact); + return { summary: [{ type: "text", text: "Short retained facts." }] }; + }, + }; + const ctx: Parameters[0] = { compaction: engine, tokenMeter: { estimateMessage: meter }, llm: { resolveModelInfo: async () => ({ context: { contextWindow: 272000 } }) }, on: () => undefined }; + apply(ctx); + await engine.summarize(input, agent); + assert.ok(calls > 1, "the tool reservation must force bounded batches"); + assert.equal(seen.size, 6); + assert.deepEqual(input, before); + const previousCalls = calls; + await assert.rejects(engine.summarize({ messages: [message("fact")], tools: [{ description: "x".repeat(800000) }] }, agent), /insufficient input budget/); + assert.equal(calls, previousCalls, "genuinely oversized schemas fail before egress"); +}); From cd7b492dda9c745a8b4d90e3eccb1e407715cd49 Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Wed, 11 Nov 2026 15:03:01 +0800 Subject: [PATCH 3/9] test(dsh): cover partial summary failure and concurrent ownership --- docs/dsh-native-compaction.md | 6 +++ docs/dsh-native-compaction.zh-CN.md | 6 +++ scripts/test-dsh-native-compaction.mjs | 16 ++++++- tests/dsh-native-compaction.test.ts | 64 ++++++++++++++++++++++++++ 4 files changed, 91 insertions(+), 1 deletion(-) diff --git a/docs/dsh-native-compaction.md b/docs/dsh-native-compaction.md index d762d837f2..b7fecd64ed 100644 --- a/docs/dsh-native-compaction.md +++ b/docs/dsh-native-compaction.md @@ -52,6 +52,12 @@ The caller must supply a detached runtime directory, not a running profile. No c Native requests fail closed when their preset has not attached the adapter. 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. +## Extended live acceptance + +The deterministic tests also fail the second summary batch after the first succeeds, assert that no replacement or raw-history mutation is committed, and retry the same session. Unit coverage cancels a later reduction and overlaps native summarization with bili-owned work to check asynchronous ownership isolation. + +For live acceptance, use a separate DSH home, bili state and ports with real provider calls. Exercise compressed bili → native → bili twice, including raw history larger than the native model's window. Explicitly set DSH's summarization model when testing its smaller budget: selecting the main model alone can leave the previous model as the summarizer. Inject failure or hold the second summary request only after the first succeeds; check that no checkpoint is committed, then retry and recall planted facts without repeating their values. While a native summary is held, another bili session must finish under its own identity without the first session's facts. Finally restart the isolated host and proxy, verify the same conversation namespace and unchanged earlier event hashes, and recall the facts again. Require a new assistant answer in each turn; an older answer visible after a failed turn is not success. These checks demonstrate selected facts and lifecycle behavior, not lossless summarization. + ## 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. diff --git a/docs/dsh-native-compaction.zh-CN.md b/docs/dsh-native-compaction.zh-CN.md index 2447756f81..82eadd3478 100644 --- a/docs/dsh-native-compaction.zh-CN.md +++ b/docs/dsh-native-compaction.zh-CN.md @@ -52,6 +52,12 @@ node scripts/test-dsh-native-compaction.mjs /绝对路径/隔离的DSH运行时 预设未挂载适配器时,原生请求明确失败。原厂 minimal 预设没有压缩后端,命中原生规则时维持其原样,不额外添加压缩。CLI 根作用域配置、未来 DSH API 版本需要额外适配,不能直接视为已支持。 +## 扩展真实会话验收 + +确定性测试增加了“第一批摘要成功、第二批失败”场景,断言不提交部分替换、不改变原始历史,并验证同会话可以重试。单元测试还覆盖后续批次取消,以及原生摘要与 bili 会话并发时的异步所有权隔离。 + +真实模型验收使用独立 DSH home、bili 状态和端口,执行两轮“已压缩 bili → 原生 → bili”,包括原始历史大于原生模型窗口的情况。测试较小的摘要预算时,要显式设置 DSH 的摘要模型:只切换主模型,摘要仍可能使用此前的模型。第一批成功后,对第二批注入错误或挂起,确认没有提交检查点;解除故障后在同会话重试,不重复事实值地追问关键事实。原生摘要挂起期间,另一个 bili 会话应以自己的身份正常完成,不混入前一会话的内容。最后重启隔离宿主与代理,核对命名空间、旧事件哈希与事实召回。每轮必须出现新的回答,失败轮界面上残留的旧回答不能作为成功证据。这些检查只验证所选事实与生命周期,不代表摘要无损。 + ## 后续更新保留补丁 保存源码提交、补丁和测试。对目标上游版本先执行 `git apply --check`,再执行类型检查、针对性测试、构建及真实 DSH 集成验证,全部通过才打包。profile 使用其管理渠道的本地 `file:` 包固定,避免注册表更新覆盖补丁;以后更新改为明确的“重建、验证、安装”流程。保留原包、profile 清单/锁文件及配置用于回滚。不要将旧 `dist` 覆盖到新版源码上。 diff --git a/scripts/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs index eb1da69ed8..634d25decf 100644 --- a/scripts/test-dsh-native-compaction.mjs +++ b/scripts/test-dsh-native-compaction.mjs @@ -16,6 +16,7 @@ policy.configureNativeCompaction([{ model: 'gpt-*' }]); const ctx = new Context(); const calls = []; let fail = false; +let failAt = Infinity; await ctx.plugin(c => c.reflect.provide('llm', { imageRequestPricing: () => undefined, resolveModelInfo: async (_provider, model) => ({ context: { contextWindow: model === 'gpt-luna' ? 272000 : 18000 }, defaultMaxTokens: 100 }), @@ -26,7 +27,7 @@ await ctx.plugin(c => c.reflect.provide('llm', { const window = options.model === 'gpt-luna' ? 272000 : 18000; assert.ok(cost + toolsTokens + options.maxTokens < window, `summary overflow: ${cost} + ${toolsTokens}`); calls.push(options); - if (fail) throw new Error('synthetic provider failure'); + if (fail || calls.length === failAt) throw new Error('synthetic provider failure'); yield { type: 'text-delta', index: 0, text: 'Facts retained: checkpoint integration verified.' }; yield { type: 'finish', reason: 'stop' }; } @@ -99,5 +100,18 @@ try { await assert.rejects(engine.compactIfNeeded(broken, 'pressure'), /synthetic provider failure/); assert.deepEqual(broken.session.surface.nodes, nodes); assert.equal(broken.session.surface.replaceGeneration, 0); + fail = false; + const late = fixture('late-failed-test', 'gpt-5'); + const lateNodes = [...late.session.surface.nodes]; + const lateHistory = late.session.snapshotEvents(); + failAt = calls.length + 2; + await assert.rejects(engine.compactIfNeeded(late, 'pressure'), /synthetic provider failure/); + assert.equal(calls.length, failAt, 'first batch completed before the second failed'); + assert.deepEqual(late.session.surface.nodes, lateNodes, 'no partial checkpoint becomes visible'); + assert.equal(late.session.surface.replaceGeneration, 0); + assert.deepEqual(late.session.snapshotEvents().slice(0, lateHistory.length), lateHistory); + failAt = Infinity; + assert.ok(await engine.compactIfNeeded(late, 'pressure'), 'the failed session remains retryable'); + assert.equal(late.session.surface.replaceGeneration, 1); console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', summaryCalls: calls.length, originalSurfaceNodes: originalCount, finalSurfaceNodes: agent.session.surface.nodes.length, generation: agent.session.surface.replaceGeneration, largeCatalog: { tools: tools.length, summaryCalls: largeCalls.length, beforeTokens: largeBefore, afterTokens: ctx.tokenMeter.measure(large.session).totalTokens } })); } finally { await ctx.fiber.dispose(); } diff --git a/tests/dsh-native-compaction.test.ts b/tests/dsh-native-compaction.test.ts index b85f27ef25..db17b66a45 100644 --- a/tests/dsh-native-compaction.test.ts +++ b/tests/dsh-native-compaction.test.ts @@ -144,3 +144,67 @@ test("native summary budgets large multilingual tool catalogs in host tokens, pr await assert.rejects(engine.summarize({ messages: [message("fact")], tools: [{ description: "x".repeat(800000) }] }, agent), /insufficient input budget/); assert.equal(calls, previousCalls, "genuinely oversized schemas fail before egress"); }); + +test("multi-batch handoff discards partial reductions after a later failure or cancellation and can retry", async () => { + const input = { messages: Array.from({ length: 4 }, (_, i) => message(`fact-${i} `.repeat(8))) }; + const before = structuredClone(input); + let failedCalls = 0; + await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { + if (++failedCalls === 2) throw new Error("second batch failed"); + return { summary: [{ type: "text", text: "partial" }] }; + }), /second batch failed/); + assert.equal(failedCalls, 2); + assert.deepEqual(input, before); + + const controller = new AbortController(); + let cancelledCalls = 0; + await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { + if (++cancelledCalls === 2) controller.abort(new Error("cancelled during reduction")); + return { summary: [{ type: "text", text: "partial" }] }; + }, controller.signal), /cancelled during reduction/); + assert.equal(cancelledCalls, 2); + assert.deepEqual(input, before); + + const seen = new Set(); + const recovered = await boundedNativeSummary(input, 100, estimate, async part => { + for (const m of part.messages) for (const b of m.content) for (const fact of b.text?.match(/fact-\d/g) ?? []) seen.add(fact); + return { summary: [{ type: "text", text: "recovered" }] }; + }); + assert.equal(seen.size, 4); + assert.equal(recovered.summary[0].text, "recovered"); + assert.deepEqual(input, before); +}); + +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"] = { + config: { summarizationProvider: "", summarizationModel: "", maxTokens: 100 }, + 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, tokenMeter: { estimateMessage: () => 10 }, llm: { resolveModelInfo: async () => ({ context: { contextWindow: 20000 } }) }, 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); +}); From c07914fb1c28214db5ff383f2906f1e7df451c58 Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Wed, 11 Nov 2026 19:45:27 +0800 Subject: [PATCH 4/9] fix(dsh): preserve complementary facts across summary merges --- docs/dsh-native-compaction.md | 4 ++ docs/dsh-native-compaction.zh-CN.md | 4 ++ scripts/test-dsh-native-compaction.mjs | 7 ++ src/agent/dsh-native-compaction.ts | 25 +++++-- tests/dsh-native-compaction.test.ts | 90 ++++++++++++++++++++++---- 5 files changed, 112 insertions(+), 18 deletions(-) diff --git a/docs/dsh-native-compaction.md b/docs/dsh-native-compaction.md index b7fecd64ed..fa7804951d 100644 --- a/docs/dsh-native-compaction.md +++ b/docs/dsh-native-compaction.md @@ -38,6 +38,10 @@ The adapter gates automatic/manual native compression for bili-owned models and When switching bili → native, all selected raw messages go through DSH's summarizer. Oversized input is reduced in balanced groups; a tool call and all its results are indivisible. System messages and tool schemas are retained in each batch. A failed/cancelled/no-progress summary, or one indivisible message/group larger than the summary window, fails visibly; no partial replacement checkpoint is committed. Normal LLM summarization is lossy; this feature cannot guarantee retention of every detail. +Intermediate summaries carry a chronological segment number, reduction round, input-message range within that round and the host's `compacted-summary` framing. Their text stays verbatim. Every subsequent merge also receives a separate assembly instruction: these segments are complementary history, not successive replacements of the entire checkpoint. Missing facts or `(none)` in one segment do not revoke earlier facts; only explicit corrections or revocations supersede them. Standing facts and constraints must survive even when the latest task is complete. The framing and assembly instruction both count against the input budget, including recursive reductions. Requests that fit without splitting retain the original native messages and instruction path. + +A live Luna replay on 2026-11-11 held the three previously captured partial-summary texts, system prompt, tools, native summarization instruction and model parameters fixed. Five interleaved A/B pairs retained all five planted facts and constraints in 0/5 original merges versus 5/5 merges with framing plus assembly instructions. An earlier framing-only pilot retained all of them in 3/5 corrected merges and was rejected; those observations were retained. This is a small, single-fixture merge-stage acceptance test, not a guarantee of lossless summaries or accurate task-state reconciliation in arbitrary histories. It does not rerun the original long-history reduction or install the candidate into production. + When switching native → bili, the host's durable `surface.replaceGeneration` changes the bili conversation namespace. New folds cannot reuse an earlier substrate. 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 diff --git a/docs/dsh-native-compaction.zh-CN.md b/docs/dsh-native-compaction.zh-CN.md index 82eadd3478..53f3252785 100644 --- a/docs/dsh-native-compaction.zh-CN.md +++ b/docs/dsh-native-compaction.zh-CN.md @@ -38,6 +38,10 @@ flowchart LR **bili → 原生:** 选中的原始历史进入 DSH 摘要器。超长输入分批缩减,工具调用及其全部结果不可拆开,系统消息和工具定义随每批保留。失败、取消、无法缩短或单个消息/工具组超出摘要窗口时明确报错,不提交部分替换检查点。摘要仍然有损,无法保证每个细节都保留。 +中间摘要标明时间顺序、缩减轮次及该轮输入消息范围,并采用宿主的 `compacted-summary` 包装;摘要正文逐字保留。后续每次合并另有独立指令:各段是互补的历史,不能把后段当成全量覆盖前段;某段未提及或写 `(none)` 不代表撤销旧事实,只有明确更正或撤销才能覆盖。即使最新任务结束,长期事实和约束也应保留。包装与合并指令都计入输入预算,递归缩减同样受限。不需要分批的原生摘要维持原始消息和指令路径。 + +2026-11-11 的真实 Luna 回放固定了此前保存的三段摘要正文、系统提示、工具、原生摘要指令和模型参数,交替执行五组 A/B。五项预设事实及约束的完整保留率:原方案 0/5,分段包装加独立合并指令 5/5。此前仅加分段包装的试验为 3/5,未验收通过,全部记录保留。这只是单一样本、少量重复的合并阶段验证,不保证任意历史无损或任务状态完全准确;未重新运行整段长历史缩减,也未把候选包部署到生产。 + **原生 → bili:** 使用宿主持久化的 `surface.replaceGeneration` 区分 bili 命名空间,防止旧折叠套用到新摘要上。重启重放后保持一致;普通追加消息或未发生宿主替换的模型切换不会改名。DSH 会话 ID 与原始追加日志保持原样。发生替换后,该命名空间停用旧协商别名、分叉继承和增量发送,采用完整发送及新的水位种子;其他会话沿用原路径。上下文页和 `/acp` 跟随当前命名空间,原生模式显示归属,不展示过时 bili 数据。 ## 验证与边界 diff --git a/scripts/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs index 634d25decf..c83ae1bfdf 100644 --- a/scripts/test-dsh-native-compaction.mjs +++ b/scripts/test-dsh-native-compaction.mjs @@ -15,6 +15,7 @@ const policy = await import('../dist/agent/dsh-native-compaction.js'); policy.configureNativeCompaction([{ model: 'gpt-*' }]); const ctx = new Context(); const calls = []; +let mergeCalls = 0; let fail = false; let failAt = Infinity; await ctx.plugin(c => c.reflect.provide('llm', { @@ -22,6 +23,11 @@ await ctx.plugin(c => c.reflect.provide('llm', { resolveModelInfo: async (_provider, model) => ({ context: { contextWindow: model === 'gpt-luna' ? 272000 : 18000 }, defaultMaxTokens: 100 }), async *stream(options) { assert.equal(policy.nativeSummaryActive(), true); + if (options.messages.some(m => m.content?.some(b => b.text?.startsWith('Partial historical summary:')))) { + mergeCalls++; + assert.match(options.messages.at(-2).content[0].text, /Summary assembly instruction/); + assert.match(options.messages.at(-1).content[0].text, /You are now acting as a compaction engine/); + } const cost = options.messages.reduce((n, m) => n + ctx.tokenMeter.estimateMessage(m), 0); const toolsTokens = options.tools?.length ? Math.ceil(JSON.stringify(options.tools).length / 4) + 4 : 0; const window = options.model === 'gpt-luna' ? 272000 : 18000; @@ -113,5 +119,6 @@ try { failAt = Infinity; assert.ok(await engine.compactIfNeeded(late, 'pressure'), 'the failed session remains retryable'); assert.equal(late.session.surface.replaceGeneration, 1); + assert.ok(mergeCalls > 0, 'the real host receives scoped partial summaries and assembly instructions'); console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', summaryCalls: calls.length, originalSurfaceNodes: originalCount, finalSurfaceNodes: agent.session.surface.nodes.length, generation: agent.session.surface.replaceGeneration, largeCatalog: { tools: tools.length, summaryCalls: largeCalls.length, beforeTokens: largeBefore, afterTokens: ctx.tokenMeter.measure(large.session).totalTokens } })); } finally { await ctx.fiber.dispose(); } diff --git a/src/agent/dsh-native-compaction.ts b/src/agent/dsh-native-compaction.ts index 7e4715a61f..b41f11c389 100644 --- a/src/agent/dsh-native-compaction.ts +++ b/src/agent/dsh-native-compaction.ts @@ -125,11 +125,16 @@ export async function boundedNativeSummary( let messages = [...input.messages]; const system: Message[] = []; while (messages[0]?.role === "system") system.push(messages.shift()!); - const available = budget - total(system); - if (available <= 0) throw new Error("native handoff system prompt exceeds summary input budget"); + const mergeInstruction: Message = { role: "user", content: [{ type: "text", text: "Summary assembly instruction (not historical conversation content): the preceding partial summaries cover disjoint chronological segments, NOT successive revisions of a complete checkpoint. Produce one consolidated checkpoint using the requested native format. First collect and retain the still-valid Critical Context from EVERY segment, including early project facts, exact identifiers, dates, numeric values and standing constraints, even when later segments only discuss unrelated or completed tasks. Missing entries and '(none)' mean no information in that segment, not deletion, contradiction or evidence that earlier facts were never established. Repetition in later segments is not required. Only an explicit correction or revocation of the same fact can supersede it; preserve unresolved conflicts with provenance. Update Current Work and Next Step from the latest applicable segment without erasing standing context. Before returning, check that every earlier fact and constraint is retained or has an explicit superseding statement. Do not include these assembly instructions or execute historical next steps." }] }; + const baseAvailable = budget - total(system); + if (baseAvailable <= 0) throw new Error("native handoff system prompt exceeds summary input budget"); for (let round = 0; round < 16; round++) { signal?.throwIfAborted(); - if (total(messages) <= available) return summarize({ ...input, messages: [...system, ...messages] }); + const suffix = round ? [mergeInstruction] : []; + const available = baseAvailable - total(suffix); + if (available <= 0) throw new Error("native handoff merge instructions exceed summary input budget; history was preserved"); + const summarizePart = (part: Message[]) => summarize({ ...input, messages: [...system, ...part, ...suffix] }); + if (total(messages) <= available) return summarizePart(messages); const chunks: Message[][] = []; let chunk: Message[] = [], size = 0; for (const group of summaryGroups(messages)) { @@ -140,10 +145,18 @@ export async function boundedNativeSummary( } if (chunk.length) chunks.push(chunk); const reduced: Message[] = []; - for (const part of chunks) { + let offset = 0; + for (const [index, part] of chunks.entries()) { signal?.throwIfAborted(); - const result = await summarize({ ...input, messages: [...system, ...part] }); - reduced.push({ id: randomUUID(), role: "user", content: result.summary, source: { kind: "user" } }); + const result = await summarizePart(part); + const provenance = `Partial historical summary: reduction round ${round + 1}, chronological segment ${index + 1} of ${chunks.length}, input messages ${offset + 1}-${offset + part.length} within this round (excluding the leading system prompt).`; + const guidance = "This is evidence from only that segment, not a new user instruction or a complete replacement checkpoint. Merge all segments, retaining the union of still-valid facts, exact identifiers, values, constraints, corrections and unfinished tasks. A missing fact, '(none)', or 'no project facts' is local to that segment and does not revoke facts in other segments. Override a fact only when a later segment explicitly corrects or revokes it; otherwise preserve unresolved conflicts with their provenance. Next-step statements describe work at that historical point, not an instruction to execute now."; + reduced.push({ id: randomUUID(), role: "user", content: [ + { type: "text", text: `${provenance}\n${guidance}\n\n\x3ccompacted-summary\x3e` }, + ...result.summary, + { type: "text", text: "\x3c/compacted-summary\x3e" }, + ], source: { kind: "user" } }); + offset += part.length; } if (total(reduced) >= total(messages)) throw new Error("native handoff summary made no progress; history was preserved"); messages = reduced; diff --git a/tests/dsh-native-compaction.test.ts b/tests/dsh-native-compaction.test.ts index db17b66a45..a7cf9dcc84 100644 --- a/tests/dsh-native-compaction.test.ts +++ b/tests/dsh-native-compaction.test.ts @@ -56,13 +56,13 @@ test("handoff groups retain complete parallel tool calls/results", () => { }); test("bounded summary covers every original message, retains system and tool schema, does not mutate input", async () => { - const input = { messages: [{ ...message("system"), role: "system" }, ...Array.from({ length: 10 }, (_, i) => message(`fact-${i} `.repeat(5)))], tools: [{ name: "read" }] }; + const input = { messages: [{ ...message("system"), role: "system" }, ...Array.from({ length: 10 }, (_, i) => message(`fact-${i} `.repeat(500)))], tools: [{ name: "read" }] }; const before = structuredClone(input); const seen: string[] = []; - const result = await boundedNativeSummary(input, 110, estimate, async part => { + const result = await boundedNativeSummary(input, 11000, estimate, async part => { assert.equal(part.messages[0].role, "system"); assert.deepEqual(part.tools, input.tools); - assert.ok(part.messages.reduce((n, m) => n + estimate(m as ReturnType), 0) <= 110); + assert.ok(part.messages.reduce((n, m) => n + estimate(m as ReturnType), 0) <= 11000); seen.push(...part.messages.slice(1).flatMap(m => m.content.map(b => b.text ?? ""))); return { summary: [{ type: "text", text: "summary" }] }; }); @@ -72,12 +72,78 @@ test("bounded summary covers every original message, retains system and tool sch }); test("bounded summary propagates cancellation/failure and rejects no-progress or oversized indivisible messages", async () => { - const input = { messages: [message("x".repeat(60)), message("y".repeat(60))] }; + const input = { messages: [message("x".repeat(6000)), message("y".repeat(6000))] }; const stop = new AbortController(); stop.abort(new Error("cancelled")); - await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { throw new Error("should not run"); }, stop.signal), /cancelled/); - await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { throw new Error("provider failure"); }), /provider failure/); - await assert.rejects(boundedNativeSummary(input, 100, estimate, async p => ({ summary: p.messages[0].content })), /no progress/); - await assert.rejects(boundedNativeSummary(input, 30, estimate, async () => ({ summary: [] })), /larger/); + await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { throw new Error("should not run"); }, stop.signal), /cancelled/); + await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { throw new Error("provider failure"); }), /provider failure/); + await assert.rejects(boundedNativeSummary(input, 10000, estimate, async p => ({ summary: p.messages[0].content })), /no progress/); + await assert.rejects(boundedNativeSummary(input, 3000, estimate, async () => ({ summary: [] })), /larger/); +}); + +test("partial summaries carry scoped provenance and merge semantics without changing their facts", async () => { + const input = { messages: [{ ...message("system"), role: "system" }, ...Array.from({ length: 3 }, (_, i) => message(`source-${i} `.repeat(1000)))], tools: [{ name: "read" }] }; + const partials = ["Project ALDER; budget 7314 credits; never modify production configuration.", "No project facts in this archive segment.", "(none); no work in progress in this archive segment."]; + const before = structuredClone(input); + let calls = 0; + await boundedNativeSummary(input, 10020, estimate, async part => { + assert.ok(part.messages.reduce((n, m) => n + estimate(m), 0) <= 10020); + assert.deepEqual(part.tools, input.tools); + if (calls < 3) return { summary: [{ type: "text", text: partials[calls++] }] }; + assert.equal(part.messages.length, 5); + assert.match(part.messages.at(-1)!.content[0].text!, /NOT successive revisions/); + assert.match(part.messages.at(-1)!.content[0].text!, /EVERY segment/); + assert.match(part.messages.at(-1)!.content[0].text!, /not deletion/); + for (const [i, m] of part.messages.slice(1, -1).entries()) { + assert.equal(m.content[1].text, partials[i], "the generated evidence must stay verbatim"); + assert.match(m.content[0].text!, new RegExp(`segment ${i + 1} of 3`)); + assert.match(m.content[0].text!, new RegExp(`input messages ${i + 1}-${i + 1}`)); + assert.match(m.content[0].text!, /not a new user instruction/); + assert.match(m.content[0].text!, /does not revoke/); + assert.match(m.content[0].text!, /explicitly corrects or revokes/); + assert.match(m.content[0].text!, //); + assert.equal(m.content.at(-1)?.text, ""); + } + calls++; + return { summary: [{ type: "text", text: "merged" }] }; + }); + assert.equal(calls, 4); + assert.deepEqual(input, before); +}); + +test("a native summary that already fits keeps its original message body", async () => { + const input = { messages: [message("ordinary native history")], tools: [{ name: "read" }] }; + let calls = 0; + await boundedNativeSummary(input, 10000, estimate, async part => { + calls++; + assert.deepEqual(part, input); + return { summary: [{ type: "text", text: "ordinary summary" }] }; + }); + assert.equal(calls, 1); +}); + +test("recursive merges meter their framing and keep provenance scoped to each reduction round", async () => { + const input = { messages: Array.from({ length: 8 }, () => message("x".repeat(3500))) }; + let calls = 0, recursive = false; + await boundedNativeSummary(input, 5000, estimate, async part => { + calls++; + const size = part.messages.reduce((n, m) => n + estimate(m), 0); + assert.ok(size <= 5000, "framing must be included in every provider input budget"); + if (part.messages.some(m => m.content[0].text?.includes("reduction round 2"))) recursive = true; + return { summary: [{ type: "text", text: "small summary" }] }; + }); + assert.ok(calls > 9, "framed summaries need a second bounded reduction"); + assert.equal(recursive, true); +}); + +test("framing that cannot shrink within a tiny budget fails before an oversized merge call", async () => { + const input = { messages: [message("x".repeat(60)), message("y".repeat(60))] }; + let calls = 0; + await assert.rejects(boundedNativeSummary(input, 100, estimate, async part => { + calls++; + assert.ok(part.messages.reduce((n, m) => n + estimate(m), 0) <= 100); + return { summary: [{ type: "text", text: "tiny" }] }; + }), /no progress/); + assert.equal(calls, 2); }); test("adapter gates native methods and scopes summary bypass without leaking to concurrent bili sessions", async () => { @@ -146,10 +212,10 @@ test("native summary budgets large multilingual tool catalogs in host tokens, pr }); test("multi-batch handoff discards partial reductions after a later failure or cancellation and can retry", async () => { - const input = { messages: Array.from({ length: 4 }, (_, i) => message(`fact-${i} `.repeat(8))) }; + const input = { messages: Array.from({ length: 4 }, (_, i) => message(`fact-${i} `.repeat(800))) }; const before = structuredClone(input); let failedCalls = 0; - await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { + await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { if (++failedCalls === 2) throw new Error("second batch failed"); return { summary: [{ type: "text", text: "partial" }] }; }), /second batch failed/); @@ -158,7 +224,7 @@ test("multi-batch handoff discards partial reductions after a later failure or c const controller = new AbortController(); let cancelledCalls = 0; - await assert.rejects(boundedNativeSummary(input, 100, estimate, async () => { + await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { if (++cancelledCalls === 2) controller.abort(new Error("cancelled during reduction")); return { summary: [{ type: "text", text: "partial" }] }; }, controller.signal), /cancelled during reduction/); @@ -166,7 +232,7 @@ test("multi-batch handoff discards partial reductions after a later failure or c assert.deepEqual(input, before); const seen = new Set(); - const recovered = await boundedNativeSummary(input, 100, estimate, async part => { + const recovered = await boundedNativeSummary(input, 10000, estimate, async part => { for (const m of part.messages) for (const b of m.content) for (const fact of b.text?.match(/fact-\d/g) ?? []) seen.add(fact); return { summary: [{ type: "text", text: "recovered" }] }; }); From 5f826512675c80723ddf1b1b874ceb16ab83611c Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:07:28 +0800 Subject: [PATCH 5/9] fix(dsh): keep model routing transparent to native compaction --- docs/dsh-native-compaction.md | 33 +-- docs/dsh-native-compaction.zh-CN.md | 31 +-- scripts/test-dsh-native-compaction.mjs | 232 ++++++++++-------- src/agent/dsh-native-compaction.ts | 96 +------- tests/dsh-llm-stream-attribution.test.ts | 98 +++++++- tests/dsh-native-compaction.test.ts | 225 ++++------------- .../fixtures/dsh-compaction-parity-proxy.mjs | 15 ++ 7 files changed, 311 insertions(+), 419 deletions(-) create mode 100644 tests/fixtures/dsh-compaction-parity-proxy.mjs diff --git a/docs/dsh-native-compaction.md b/docs/dsh-native-compaction.md index fa7804951d..109d1c92b3 100644 --- a/docs/dsh-native-compaction.md +++ b/docs/dsh-native-compaction.md @@ -17,30 +17,21 @@ Rules match the actual DSH **model ID**, case-sensitively, not its display label ```mermaid flowchart LR - A[DSH captured model selection] --> B{Native model rule?} - B -->|yes| C[Original native compaction backend] - C --> D{Summary fits?} - D -->|yes| E[Original summarizer] - D -->|no| F[Balanced bounded summary batches] - F --> E - E --> G[DSH checkpoint transaction] - G --> H[Direct provider transport] - B -->|no| I[DSH durable replacement generation] - I --> J[Bili conversation namespace] - J --> K[Existing bili compression pipeline] + 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. -The summary input budget reserves output, summary instructions and a safety margin. Tool definitions are priced with the host's `tokenMeter.estimateMessage`, in the same units as messages; the temporary text message used for metering is never sent. UTF-8 schema bytes must not be subtracted directly as tokens, which can falsely exhaust the budget for a large MCP catalog. Every summary batch still carries the complete original schemas. A catalog whose token estimate truly exceeds the available budget fails while preserving history. +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. -The adapter gates automatic/manual native compression for bili-owned models and hides bili tools on native-owned steps. Native HTTP requests retain the original body, headers and provider transport. WebSocket connections cannot carry a request under a different compression owner: the mismatched frame is withheld and the connection is closed so the host can reconnect, using its existing transport recovery. +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, all selected raw messages go through DSH's summarizer. Oversized input is reduced in balanced groups; a tool call and all its results are indivisible. System messages and tool schemas are retained in each batch. A failed/cancelled/no-progress summary, or one indivisible message/group larger than the summary window, fails visibly; no partial replacement checkpoint is committed. Normal LLM summarization is lossy; this feature cannot guarantee retention of every detail. - -Intermediate summaries carry a chronological segment number, reduction round, input-message range within that round and the host's `compacted-summary` framing. Their text stays verbatim. Every subsequent merge also receives a separate assembly instruction: these segments are complementary history, not successive replacements of the entire checkpoint. Missing facts or `(none)` in one segment do not revoke earlier facts; only explicit corrections or revocations supersede them. Standing facts and constraints must survive even when the latest task is complete. The framing and assembly instruction both count against the input budget, including recursive reductions. Requests that fit without splitting retain the original native messages and instruction path. - -A live Luna replay on 2026-11-11 held the three previously captured partial-summary texts, system prompt, tools, native summarization instruction and model parameters fixed. Five interleaved A/B pairs retained all five planted facts and constraints in 0/5 original merges versus 5/5 merges with framing plus assembly instructions. An earlier framing-only pilot retained all of them in 3/5 corrected merges and was rejected; those observations were retained. This is a small, single-fixture merge-stage acceptance test, not a guarantee of lossless summaries or accurate task-state reconciliation in arbitrary histories. It does not rerun the original long-history reduction or install the candidate into production. +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. New folds cannot reuse an earlier substrate. 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. @@ -56,11 +47,11 @@ The caller must supply a detached runtime directory, not a running profile. No c Native requests fail closed when their preset has not attached the adapter. 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. -## Extended live acceptance +## Behavioral parity acceptance -The deterministic tests also fail the second summary batch after the first succeeds, assert that no replacement or raw-history mutation is committed, and retry the same session. Unit coverage cancels a later reduction and overlaps native summarization with bili-owned work to check asynchronous ownership isolation. +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. -For live acceptance, use a separate DSH home, bili state and ports with real provider calls. Exercise compressed bili → native → bili twice, including raw history larger than the native model's window. Explicitly set DSH's summarization model when testing its smaller budget: selecting the main model alone can leave the previous model as the summarizer. Inject failure or hold the second summary request only after the first succeeds; check that no checkpoint is committed, then retry and recall planted facts without repeating their values. While a native summary is held, another bili session must finish under its own identity without the first session's facts. Finally restart the isolated host and proxy, verify the same conversation namespace and unchanged earlier event hashes, and recall the facts again. Require a new assistant answer in each turn; an older answer visible after a failed turn is not success. These checks demonstrate selected facts and lifecycle behavior, not lossless summarization. +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 diff --git a/docs/dsh-native-compaction.zh-CN.md b/docs/dsh-native-compaction.zh-CN.md index 53f3252785..4d12e2bfa3 100644 --- a/docs/dsh-native-compaction.zh-CN.md +++ b/docs/dsh-native-compaction.zh-CN.md @@ -18,29 +18,20 @@ ```mermaid flowchart LR A[DSH 本轮模型选择] --> B{命中原生规则?} - B -->|是| C[原生压缩后端] - C --> D{摘要输入能放下?} - D -->|能| E[原生摘要器] - D -->|不能| F[保持工具配对的分批摘要] - F --> E - E --> G[DSH 检查点事务] - G --> H[直接调用供应商] - B -->|否| I[宿主持久化替换代数] - I --> J[Bili 会话命名空间] - J --> K[原有 bili 压缩流程] + B -->|是| C[原有 DSH 压缩流程] + C --> D[直接调用供应商] + B -->|否| E[宿主持久化替换代数] + E --> F[Bili 会话命名空间] + F --> G[原有 bili 压缩流程] ``` 原生触发阈值、近期内容保留、摘要提示词和摘要模型选择由 DSH 决定。模型切换时,DSH 可能使用上一轮模型生成摘要,除非其原生配置另行指定;这些摘要请求仍绕过 bili,不受摘要模型是否命中规则影响。 -摘要输入预算预留输出、摘要指令和安全余量。工具定义经宿主 `tokenMeter.estimateMessage` 估算 token,采用与消息相同的计量单位;用于计量的临时文本消息不会发送给模型。不能把工具 JSON 的 UTF-8 字节数直接当成 token 扣除,否则大型 MCP 工具目录会错误耗尽预算。工具定义仍完整随每批摘要请求发送;如果其 token 估算确实超过可用预算,则保留历史并报错。 +此适配层只决定压缩归属,原生摘要的输入、工具、输出预算、模型选择、提示词、调用次数和失败处理均由 DSH 原方法负责。补丁不进行额外预算检查,不拆分历史,不生成中间摘要,也不添加合并指令。原生摘要请求使用异步作用域标记绕过 bili;标记不改变请求内容,且不影响并发的 bili 会话。 -原生步骤不提供 bili 压缩工具;bili 步骤不触发宿主原生压缩。原生 HTTP 请求保留原始请求体、请求头和供应商传输。WebSocket 若复用跨压缩模式的连接,会先阻止该帧并关闭连接,由宿主既有传输恢复机制重连。 +原生步骤不提供 bili 压缩工具;bili 步骤不触发宿主原生压缩。原生 HTTP 请求保留请求体、请求头和供应商传输。WebSocket 若复用跨压缩模式的连接,会先阻止该帧并关闭连接,由宿主既有传输恢复机制重连。 -**bili → 原生:** 选中的原始历史进入 DSH 摘要器。超长输入分批缩减,工具调用及其全部结果不可拆开,系统消息和工具定义随每批保留。失败、取消、无法缩短或单个消息/工具组超出摘要窗口时明确报错,不提交部分替换检查点。摘要仍然有损,无法保证每个细节都保留。 - -中间摘要标明时间顺序、缩减轮次及该轮输入消息范围,并采用宿主的 `compacted-summary` 包装;摘要正文逐字保留。后续每次合并另有独立指令:各段是互补的历史,不能把后段当成全量覆盖前段;某段未提及或写 `(none)` 不代表撤销旧事实,只有明确更正或撤销才能覆盖。即使最新任务结束,长期事实和约束也应保留。包装与合并指令都计入输入预算,递归缩减同样受限。不需要分批的原生摘要维持原始消息和指令路径。 - -2026-11-11 的真实 Luna 回放固定了此前保存的三段摘要正文、系统提示、工具、原生摘要指令和模型参数,交替执行五组 A/B。五项预设事实及约束的完整保留率:原方案 0/5,分段包装加独立合并指令 5/5。此前仅加分段包装的试验为 3/5,未验收通过,全部记录保留。这只是单一样本、少量重复的合并阶段验证,不保证任意历史无损或任务状态完全准确;未重新运行整段长历史缩减,也未把候选包部署到生产。 +**bili → 原生:** DSH 使用自身持久化的历史与检查点执行原有压缩策略,不把 bili 的折叠摘要拼接成新的原生摘要。若选中历史超过摘要模型窗口,保留原生请求及原生失败/恢复行为,不偷偷分批或更换模型。切换不保证任意长度历史都能立即压缩成功。原生本身可能连续压缩;这仍由原生压力策略决定。 **原生 → bili:** 使用宿主持久化的 `surface.replaceGeneration` 区分 bili 命名空间,防止旧折叠套用到新摘要上。重启重放后保持一致;普通追加消息或未发生宿主替换的模型切换不会改名。DSH 会话 ID 与原始追加日志保持原样。发生替换后,该命名空间停用旧协商别名、分叉继承和增量发送,采用完整发送及新的水位种子;其他会话沿用原路径。上下文页和 `/acp` 跟随当前命名空间,原生模式显示归属,不展示过时 bili 数据。 @@ -56,11 +47,11 @@ node scripts/test-dsh-native-compaction.mjs /绝对路径/隔离的DSH运行时 预设未挂载适配器时,原生请求明确失败。原厂 minimal 预设没有压缩后端,命中原生规则时维持其原样,不额外添加压缩。CLI 根作用域配置、未来 DSH API 版本需要额外适配,不能直接视为已支持。 -## 扩展真实会话验收 +## 行为对照验收 -确定性测试增加了“第一批摘要成功、第二批失败”场景,断言不提交部分替换、不改变原始历史,并验证同会话可以重试。单元测试还覆盖后续批次取消,以及原生摘要与 bili 会话并发时的异步所有权隔离。 +真实 DSH 引擎集成脚本将同一份事件历史分别交给未安装路由适配器的原生引擎和安装后的原生引擎。比较实际摘要请求、压缩事件、代数和 token 结果;只规范化宿主新生成的随机标识,保留原始消息及工具 ID。覆盖压力线以下、自动/手动/指定范围压缩、切换模型、指定摘要模型、供应商失败、取消和超长历史/工具目录。超限场景要求两边同样失败,不以补丁额外兜底作为成功。 -真实模型验收使用独立 DSH home、bili 状态和端口,执行两轮“已压缩 bili → 原生 → bili”,包括原始历史大于原生模型窗口的情况。测试较小的摘要预算时,要显式设置 DSH 的摘要模型:只切换主模型,摘要仍可能使用此前的模型。第一批成功后,对第二批注入错误或挂起,确认没有提交检查点;解除故障后在同会话重试,不重复事实值地追问关键事实。原生摘要挂起期间,另一个 bili 会话应以自己的身份正常完成,不混入前一会话的内容。最后重启隔离宿主与代理,核对命名空间、旧事件哈希与事实召回。每轮必须出现新的回答,失败轮界面上残留的旧回答不能作为成功证据。这些检查只验证所选事实与生命周期,不代表摘要无损。 +bili 对照使用真实插件请求拦截、代理及压缩工具,比较仅 bili 与未命中原生规则时的工具列表、折叠结果和供应商请求。另测同会话双向切换、检查点代数重放及异步并发隔离。确定性上游用于消除模型随机输出造成的差异;这验证路由行为,不代表摘要质量或无损保证。此前分批合并 A/B 属于已撤销实现的历史证据,不再是当前实现的验收。 ## 后续更新保留补丁 diff --git a/scripts/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs index c83ae1bfdf..c9a9bb5e0f 100644 --- a/scripts/test-dsh-native-compaction.mjs +++ b/scripts/test-dsh-native-compaction.mjs @@ -9,116 +9,132 @@ 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 { BasicCompactionEngine } = await load('dsh-compaction-basic'); const { createUserMessage, createSystemMessage } = await load('dsh-llm'); const policy = await import('../dist/agent/dsh-native-compaction.js'); policy.configureNativeCompaction([{ model: 'gpt-*' }]); -const ctx = new Context(); -const calls = []; -let mergeCalls = 0; -let fail = false; -let failAt = Infinity; -await ctx.plugin(c => c.reflect.provide('llm', { - imageRequestPricing: () => undefined, - resolveModelInfo: async (_provider, model) => ({ context: { contextWindow: model === 'gpt-luna' ? 272000 : 18000 }, defaultMaxTokens: 100 }), - async *stream(options) { - assert.equal(policy.nativeSummaryActive(), true); - if (options.messages.some(m => m.content?.some(b => b.text?.startsWith('Partial historical summary:')))) { - mergeCalls++; - assert.match(options.messages.at(-2).content[0].text, /Summary assembly instruction/); - assert.match(options.messages.at(-1).content[0].text, /You are now acting as a compaction engine/); +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: '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 cost = options.messages.reduce((n, m) => n + ctx.tokenMeter.estimateMessage(m), 0); - const toolsTokens = options.tools?.length ? Math.ceil(JSON.stringify(options.tools).length / 4) + 4 : 0; - const window = options.model === 'gpt-luna' ? 272000 : 18000; - assert.ok(cost + toolsTokens + options.maxTokens < window, `summary overflow: ${cost} + ${toolsTokens}`); - calls.push(options); - if (fail || calls.length === failAt) throw new Error('synthetic provider failure'); - yield { type: 'text-delta', index: 0, text: 'Facts retained: checkpoint integration verified.' }; - 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: { auto: true, thresholdRatio: 0.8, headroomTokens: 1000, maxTokens: 200, retainTokens: 1000, modelPolicies: [{ provider: 'fake', model: 'gpt-luna', headroomTokens: 65536, maxTokens: 65536, retainTokens: 32245 }] } }, - { 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, 'isolated preset group provides its compaction engine'); -assert.equal(ctx.get('compaction'), undefined, 'preset engine does not leak to the host plane'); -function fixture(id, model, count = 16, tools = [], repeats = 2600) { - const session = ctx.sessions.create(id); - session.append('system/message', { message: createSystemMessage('Keep the facts.') }, { surfaceOp: 'append' }); - session.append('request/header', { header: { config: { provider: 'fake', model, maxTokens: model === 'gpt-luna' ? 70464 : 200 }, ...(tools.length ? { tools } : {}) }, reason: 'initial' }); - for (let i = 0; i < count; i++) session.append('user/message', createUserMessage({ content: [{ type: 'text', text: `fact-${i}: `.repeat(repeats) }], source: { kind: 'user' } }), { surfaceOp: 'append' }); - session.append('turn/start', { turn: 'test-turn' }); - return { session, options: { provider: 'fake', model }, model: { current: () => ({ provider: 'fake', model }), select: next => { model = next; } } }; + 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' }); } -try { - const bili = fixture('bili-test', 'kimi'); - const before = bili.session.surface.replaceGeneration; - assert.equal(await engine.compactIfNeeded(bili, 'pressure'), null); - assert.equal(bili.session.surface.replaceGeneration, before); - const agent = fixture('switch-test', 'kimi'); - agent.model.select('gpt-5'); - const old = agent.session.snapshotEvents(); - const originalCount = agent.session.surface.nodes.length; - const result = await engine.compactPressure(agent, { config: { provider: 'fake', model: 'gpt-5', maxTokens: 200 } }, undefined, true); - assert.ok(result); - assert.ok(calls.length > 1, 'oversized handoff uses multiple bounded native calls'); - assert.ok(agent.session.surface.nodes.length < originalCount); - assert.ok(agent.session.surface.replaceGeneration > 0); - assert.deepEqual(agent.session.snapshotEvents().slice(0, old.length), old, 'raw log remains immutable'); - const resumed = Session.create(agent.session.id, agent.session.snapshotEvents(), agent.session.header); - assert.equal(policy.compactionConversationId({ session: resumed }, resumed.id), policy.compactionConversationId(agent, agent.session.id)); - agent.model.select('kimi'); - const generation = agent.session.surface.replaceGeneration; - assert.equal(await engine.compactIfNeeded(agent, 'pressure'), null); - assert.equal(agent.session.surface.replaceGeneration, generation); - const tools = Array.from({ length: 327 }, (_, i) => ({ name: `tool_${i}`, description: 'Synthetic 工具目录 description. '.repeat(40), parameters: { type: 'object', properties: {} } })); - assert.ok(Buffer.byteLength(JSON.stringify(tools)) > 272000); - const large = fixture('large-tool-test', 'gpt-luna', 12, tools, 7500); - const largeHistory = large.session.snapshotEvents(); - const largeBefore = ctx.tokenMeter.measure(large.session).totalTokens; - const beforeCalls = calls.length; - assert.ok(await engine.compactIfNeeded(large, 'pressure')); - const largeCalls = calls.slice(beforeCalls); - assert.ok(largeCalls.length > 1, 'large catalog still allows bounded multi-batch summary'); - for (const call of largeCalls) assert.deepEqual(call.tools, tools); - assert.deepEqual(large.session.snapshotEvents().slice(0, largeHistory.length), largeHistory); - assert.equal(large.session.surface.replaceGeneration, 1); - assert.ok(ctx.tokenMeter.measure(large.session).totalTokens < 136000, 'native pressure drops below the Luna threshold'); - const oversized = fixture('oversized-tools-test', 'gpt-luna', 16, [{ name: 'too_large', description: 'x'.repeat(800000), parameters: { type: 'object' } }]); - const oversizedSurface = [...oversized.session.surface.nodes]; - const beforeOversize = calls.length; - await assert.rejects(engine.compactIfNeeded(oversized, 'pressure'), /insufficient input budget/); - assert.equal(calls.length, beforeOversize); - assert.deepEqual(oversized.session.surface.nodes, oversizedSurface); - assert.equal(oversized.session.surface.replaceGeneration, 0); - const broken = fixture('failed-test', 'gpt-5'); - const nodes = [...broken.session.surface.nodes]; - fail = true; - await assert.rejects(engine.compactIfNeeded(broken, 'pressure'), /synthetic provider failure/); - assert.deepEqual(broken.session.surface.nodes, nodes); - assert.equal(broken.session.surface.replaceGeneration, 0); - fail = false; - const late = fixture('late-failed-test', 'gpt-5'); - const lateNodes = [...late.session.surface.nodes]; - const lateHistory = late.session.snapshotEvents(); - failAt = calls.length + 2; - await assert.rejects(engine.compactIfNeeded(late, 'pressure'), /synthetic provider failure/); - assert.equal(calls.length, failAt, 'first batch completed before the second failed'); - assert.deepEqual(late.session.surface.nodes, lateNodes, 'no partial checkpoint becomes visible'); - assert.equal(late.session.surface.replaceGeneration, 0); - assert.deepEqual(late.session.snapshotEvents().slice(0, lateHistory.length), lateHistory); - failAt = Infinity; - assert.ok(await engine.compactIfNeeded(late, 'pressure'), 'the failed session remains retryable'); - assert.equal(late.session.surface.replaceGeneration, 1); - assert.ok(mergeCalls > 0, 'the real host receives scoped partial summaries and assembly instructions'); - console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', summaryCalls: calls.length, originalSurfaceNodes: originalCount, finalSurfaceNodes: agent.session.surface.nodes.length, generation: agent.session.surface.replaceGeneration, largeCatalog: { tools: tools.length, summaryCalls: largeCalls.length, beforeTokens: largeBefore, afterTokens: ctx.tokenMeter.measure(large.session).totalTokens } })); -} finally { await ctx.fiber.dispose(); } +console.log(JSON.stringify({ result: 'passed', realDSH: '0.2.2-rc.1', parityCases: results })); diff --git a/src/agent/dsh-native-compaction.ts b/src/agent/dsh-native-compaction.ts index b41f11c389..f336a695cb 100644 --- a/src/agent/dsh-native-compaction.ts +++ b/src/agent/dsh-native-compaction.ts @@ -1,5 +1,4 @@ import { AsyncLocalStorage } from "node:async_hooks"; -import { randomUUID } from "node:crypto"; import { loadConfigFile } from "../config.js"; export type NativeModelRule = { provider?: string; model: string }; @@ -77,9 +76,7 @@ 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 PolicyConfig = { summarizationProvider: string; summarizationModel: string; maxTokens: number; modelPolicies?: readonly (Target & Partial)[] }; type Engine = { - config: PolicyConfig; 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; @@ -88,84 +85,13 @@ type Engine = { }; type Host = { compaction: Engine; - tokenMeter: { estimateMessage(message: Message): number }; - llm: { resolveModelInfo(provider: string, model: string, signal?: AbortSignal): Promise<{ context?: { contextWindow: number } }> }; 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; }; -/** Balanced groups are indivisible: never separate a tool call from its result. */ -export function summaryGroups(messages: readonly Message[]): Message[][] { - const groups: Message[][] = []; - let pending = new Set(); - let group: Message[] = []; - for (const message of messages) { - group.push(message); - if (message.role === "tool") { - if (typeof message.toolCallId !== "string" || !pending.delete(message.toolCallId)) throw new Error("unpaired tool result in native handoff"); - } - for (const block of message.content) { - if (block.type === "tool-call") { - if (!block.id || pending.has(block.id)) throw new Error("invalid tool call in native handoff"); - pending.add(block.id); - } - } - if (!pending.size) { groups.push(group); group = []; } - } - if (pending.size) throw new Error("unfinished tool calls in native handoff"); - return groups; -} - -export async function boundedNativeSummary( - input: SummaryInput, budget: number, estimate: (message: Message) => number, - summarize: (input: SummaryInput) => Promise, signal?: AbortSignal, -): Promise { - const total = (messages: readonly Message[]) => messages.reduce((n, m) => n + estimate(m), 0); - let messages = [...input.messages]; - const system: Message[] = []; - while (messages[0]?.role === "system") system.push(messages.shift()!); - const mergeInstruction: Message = { role: "user", content: [{ type: "text", text: "Summary assembly instruction (not historical conversation content): the preceding partial summaries cover disjoint chronological segments, NOT successive revisions of a complete checkpoint. Produce one consolidated checkpoint using the requested native format. First collect and retain the still-valid Critical Context from EVERY segment, including early project facts, exact identifiers, dates, numeric values and standing constraints, even when later segments only discuss unrelated or completed tasks. Missing entries and '(none)' mean no information in that segment, not deletion, contradiction or evidence that earlier facts were never established. Repetition in later segments is not required. Only an explicit correction or revocation of the same fact can supersede it; preserve unresolved conflicts with provenance. Update Current Work and Next Step from the latest applicable segment without erasing standing context. Before returning, check that every earlier fact and constraint is retained or has an explicit superseding statement. Do not include these assembly instructions or execute historical next steps." }] }; - const baseAvailable = budget - total(system); - if (baseAvailable <= 0) throw new Error("native handoff system prompt exceeds summary input budget"); - for (let round = 0; round < 16; round++) { - signal?.throwIfAborted(); - const suffix = round ? [mergeInstruction] : []; - const available = baseAvailable - total(suffix); - if (available <= 0) throw new Error("native handoff merge instructions exceed summary input budget; history was preserved"); - const summarizePart = (part: Message[]) => summarize({ ...input, messages: [...system, ...part, ...suffix] }); - if (total(messages) <= available) return summarizePart(messages); - const chunks: Message[][] = []; - let chunk: Message[] = [], size = 0; - for (const group of summaryGroups(messages)) { - const cost = total(group); - if (cost > available) throw new Error("native handoff contains a single tool group/message larger than the summary window; history was preserved"); - if (size + cost > available) { chunks.push(chunk); chunk = []; size = 0; } - chunk.push(...group); size += cost; - } - if (chunk.length) chunks.push(chunk); - const reduced: Message[] = []; - let offset = 0; - for (const [index, part] of chunks.entries()) { - signal?.throwIfAborted(); - const result = await summarizePart(part); - const provenance = `Partial historical summary: reduction round ${round + 1}, chronological segment ${index + 1} of ${chunks.length}, input messages ${offset + 1}-${offset + part.length} within this round (excluding the leading system prompt).`; - const guidance = "This is evidence from only that segment, not a new user instruction or a complete replacement checkpoint. Merge all segments, retaining the union of still-valid facts, exact identifiers, values, constraints, corrections and unfinished tasks. A missing fact, '(none)', or 'no project facts' is local to that segment and does not revoke facts in other segments. Override a fact only when a later segment explicitly corrects or revokes it; otherwise preserve unresolved conflicts with their provenance. Next-step statements describe work at that historical point, not an instruction to execute now."; - reduced.push({ id: randomUUID(), role: "user", content: [ - { type: "text", text: `${provenance}\n${guidance}\n\n\x3ccompacted-summary\x3e` }, - ...result.summary, - { type: "text", text: "\x3c/compacted-summary\x3e" }, - ], source: { kind: "user" } }); - offset += part.length; - } - if (total(reduced) >= total(messages)) throw new Error("native handoff summary made no progress; history was preserved"); - messages = reduced; - } - throw new Error("native handoff exceeded its reduction bound; history was preserved"); -} - export const name = "bili-native-compaction"; -export const inject = ["tokenMeter", "llm"]; +export const inject = []; export function apply(ctx: Host, config: { noBackend?: boolean } = {}): void { if (config.noBackend) { const owned = new Set(); @@ -209,25 +135,7 @@ function attachEngine(ctx: Host): void { }; engine.summarize = async (input, agent, signal) => { if (!allow(agent)) throw new Error("bili: native summary refused for a bili-owned model"); - const target = agent.session.requestHeader?.()?.config ?? agent.model?.current(); - const override = engine.config.modelPolicies?.find(p => p.provider === target?.provider && p.model === target?.model); - const config = { ...engine.config, ...override }; - const provider = config.summarizationProvider || target?.provider; - const model = config.summarizationModel || target?.model; - if (typeof provider !== "string" || typeof model !== "string") throw new Error("native summary has no model target"); - const info = await ctx.llm.resolveModelInfo(provider, model, signal); - const window = info.context?.contextWindow; - if (!window) throw new Error("native summary model has no context window"); - // Price schema text with the same host heuristic as messages, never UTF-8 bytes. - // The synthetic message is only metered, not sent; its framing adds a small reserve. - const toolsTokens = input.tools?.length ? ctx.tokenMeter.estimateMessage({ - role: "user", content: [{ type: "text", text: JSON.stringify(input.tools) }], - }) : 0; - if (!Number.isFinite(toolsTokens) || toolsTokens < 0) throw new Error("native summary tool token estimate is invalid"); - const budget = Math.floor(window * 0.9) - config.maxTokens - 4096 - toolsTokens; - if (budget <= 0) throw new Error("native summary model has insufficient input budget"); - return state().summary.run(true, () => boundedNativeSummary(input, budget, m => ctx.tokenMeter.estimateMessage(m), - part => originals.summarize.call(engine, part, agent, signal), signal)); + return state().summary.run(true, () => originals.summarize.call(engine, input, agent, signal)); }; ctx.on("agent/pre-step", ({ agent }, next) => { markReady(agent); diff --git a/tests/dsh-llm-stream-attribution.test.ts b/tests/dsh-llm-stream-attribution.test.ts index e72e5fe13e..aa64c7ded6 100644 --- a/tests/dsh-llm-stream-attribution.test.ts +++ b/tests/dsh-llm-stream-attribution.test.ts @@ -37,7 +37,7 @@ 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 } from "../src/agent/dsh-native-compaction.ts"; +import { apply as applyNativePolicy, configureNativeCompaction, nativeModel } from "../src/agent/dsh-native-compaction.ts"; import { installNativeFetchIntercept, _resetForTest as resetFetchIntercept } from "../src/agent/native-intercept.ts"; test("DSH dispatch switches native/bili/native with unchanged native wire and a new bili generation", async () => { @@ -105,6 +105,94 @@ test("DSH dispatch switches native/bili/native with unchanged native wire and a const MODEL_URL = "https://api.anthropic.com/v1/messages"; +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), 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; } @@ -175,26 +263,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; @@ -204,6 +293,7 @@ async function withSetup(fn: (handle: CtxHandle, proxy: MockProxy) => Promise Promise; origin: string; server: import("node:http").Server; } diff --git a/tests/dsh-native-compaction.test.ts b/tests/dsh-native-compaction.test.ts index a7cf9dcc84..6d5bc2f085 100644 --- a/tests/dsh-native-compaction.test.ts +++ b/tests/dsh-native-compaction.test.ts @@ -1,11 +1,10 @@ import test, { afterEach } from "node:test"; import assert from "node:assert/strict"; -import { apply, boundedNativeSummary, compactionConversationId, configureNativeCompaction, nativeAgent, nativeModel, nativeSummaryActive, requireNativeCompactionReady, summaryGroups } from "../src/agent/dsh-native-compaction.ts"; +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 }] }); -const estimate = (m: { content: readonly { text?: string }[] }) => m.content.reduce((n, b) => n + (b.text?.length ?? 0), 0); test("native ownership is opt-in, exact provider, explicit model family, never substring", () => { configureNativeCompaction([]); @@ -46,120 +45,19 @@ test("preset rewrite keeps stock settings, respects disabled rows, adds adapter assert.equal(inner.length, 2); }); -test("handoff groups retain complete parallel tool calls/results", () => { - const messages = [{ role: "assistant", content: [{ type: "tool-call", id: "a" }, { type: "tool-call", id: "b" }] }, - { role: "tool", toolCallId: "a", content: [{ type: "text", text: "A" }] }, - { role: "tool", toolCallId: "b", content: [{ type: "text", text: "B" }] }, message("tail")]; - assert.deepEqual(summaryGroups(messages), [messages.slice(0, 3), [messages[3]]]); - assert.throws(() => summaryGroups(messages.slice(0, 2)), /unfinished/); - assert.throws(() => summaryGroups(messages.slice(1)), /unpaired/); -}); - -test("bounded summary covers every original message, retains system and tool schema, does not mutate input", async () => { - const input = { messages: [{ ...message("system"), role: "system" }, ...Array.from({ length: 10 }, (_, i) => message(`fact-${i} `.repeat(500)))], tools: [{ name: "read" }] }; - const before = structuredClone(input); - const seen: string[] = []; - const result = await boundedNativeSummary(input, 11000, estimate, async part => { - assert.equal(part.messages[0].role, "system"); - assert.deepEqual(part.tools, input.tools); - assert.ok(part.messages.reduce((n, m) => n + estimate(m as ReturnType), 0) <= 11000); - seen.push(...part.messages.slice(1).flatMap(m => m.content.map(b => b.text ?? ""))); - return { summary: [{ type: "text", text: "summary" }] }; - }); - assert.deepEqual(result.summary, [{ type: "text", text: "summary" }]); - for (let i = 0; i < 10; i++) assert.ok(seen.some(text => text.includes(`fact-${i}`))); - assert.deepEqual(input, before); -}); - -test("bounded summary propagates cancellation/failure and rejects no-progress or oversized indivisible messages", async () => { - const input = { messages: [message("x".repeat(6000)), message("y".repeat(6000))] }; - const stop = new AbortController(); stop.abort(new Error("cancelled")); - await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { throw new Error("should not run"); }, stop.signal), /cancelled/); - await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { throw new Error("provider failure"); }), /provider failure/); - await assert.rejects(boundedNativeSummary(input, 10000, estimate, async p => ({ summary: p.messages[0].content })), /no progress/); - await assert.rejects(boundedNativeSummary(input, 3000, estimate, async () => ({ summary: [] })), /larger/); -}); - -test("partial summaries carry scoped provenance and merge semantics without changing their facts", async () => { - const input = { messages: [{ ...message("system"), role: "system" }, ...Array.from({ length: 3 }, (_, i) => message(`source-${i} `.repeat(1000)))], tools: [{ name: "read" }] }; - const partials = ["Project ALDER; budget 7314 credits; never modify production configuration.", "No project facts in this archive segment.", "(none); no work in progress in this archive segment."]; - const before = structuredClone(input); - let calls = 0; - await boundedNativeSummary(input, 10020, estimate, async part => { - assert.ok(part.messages.reduce((n, m) => n + estimate(m), 0) <= 10020); - assert.deepEqual(part.tools, input.tools); - if (calls < 3) return { summary: [{ type: "text", text: partials[calls++] }] }; - assert.equal(part.messages.length, 5); - assert.match(part.messages.at(-1)!.content[0].text!, /NOT successive revisions/); - assert.match(part.messages.at(-1)!.content[0].text!, /EVERY segment/); - assert.match(part.messages.at(-1)!.content[0].text!, /not deletion/); - for (const [i, m] of part.messages.slice(1, -1).entries()) { - assert.equal(m.content[1].text, partials[i], "the generated evidence must stay verbatim"); - assert.match(m.content[0].text!, new RegExp(`segment ${i + 1} of 3`)); - assert.match(m.content[0].text!, new RegExp(`input messages ${i + 1}-${i + 1}`)); - assert.match(m.content[0].text!, /not a new user instruction/); - assert.match(m.content[0].text!, /does not revoke/); - assert.match(m.content[0].text!, /explicitly corrects or revokes/); - assert.match(m.content[0].text!, //); - assert.equal(m.content.at(-1)?.text, ""); - } - calls++; - return { summary: [{ type: "text", text: "merged" }] }; - }); - assert.equal(calls, 4); - assert.deepEqual(input, before); -}); - -test("a native summary that already fits keeps its original message body", async () => { - const input = { messages: [message("ordinary native history")], tools: [{ name: "read" }] }; - let calls = 0; - await boundedNativeSummary(input, 10000, estimate, async part => { - calls++; - assert.deepEqual(part, input); - return { summary: [{ type: "text", text: "ordinary summary" }] }; - }); - assert.equal(calls, 1); -}); - -test("recursive merges meter their framing and keep provenance scoped to each reduction round", async () => { - const input = { messages: Array.from({ length: 8 }, () => message("x".repeat(3500))) }; - let calls = 0, recursive = false; - await boundedNativeSummary(input, 5000, estimate, async part => { - calls++; - const size = part.messages.reduce((n, m) => n + estimate(m), 0); - assert.ok(size <= 5000, "framing must be included in every provider input budget"); - if (part.messages.some(m => m.content[0].text?.includes("reduction round 2"))) recursive = true; - return { summary: [{ type: "text", text: "small summary" }] }; - }); - assert.ok(calls > 9, "framed summaries need a second bounded reduction"); - assert.equal(recursive, true); -}); - -test("framing that cannot shrink within a tiny budget fails before an oversized merge call", async () => { - const input = { messages: [message("x".repeat(60)), message("y".repeat(60))] }; - let calls = 0; - await assert.rejects(boundedNativeSummary(input, 100, estimate, async part => { - calls++; - assert.ok(part.messages.reduce((n, m) => n + estimate(m), 0) <= 100); - return { summary: [{ type: "text", text: "tiny" }] }; - }), /no progress/); - assert.equal(calls, 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 = { - config: { summarizationProvider: "", summarizationModel: "", maxTokens: 100 }, 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, tokenMeter: { estimateMessage: () => 20 }, llm: { resolveModelInfo: async () => ({ context: { contextWindow: 20000 } }) }, on: () => undefined }; + 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/); @@ -175,72 +73,6 @@ test("adapter gates native methods and scopes summary bypass without leaking to assert.deepEqual(calls, ["auto"]); }); -test("native summary budgets large multilingual tool catalogs in host tokens, preserving schemas on every batch", async () => { - configureNativeCompaction([{ model: "gpt-*" }]); - const agent = { session: { id: "large-tools", requestHeader: () => ({ config: { provider: "test", model: "gpt-luna" } }) } }; - const meter = (m: Parameters[0]["tokenMeter"]["estimateMessage"]>[0]) => - m.content.reduce((n, b) => n + Math.ceil((b.text?.length ?? 0) / 4) + 4, 4); - const tools = Array.from({ length: 327 }, (_, i) => ({ name: `tool_${i}`, description: "Synthetic 工具目录 description. ".repeat(40), parameters: { type: "object", properties: {} } })); - assert.ok(Buffer.byteLength(JSON.stringify(tools)) > 272000); - const input = { tools, messages: [{ ...message("System rules."), role: "system" }, ...Array.from({ length: 6 }, (_, i) => message(`fact-${i} `.repeat(15000)))] }; - const before = structuredClone(input); - let calls = 0; - const seen = new Set(); - const engine: Parameters[0]["compaction"] = { - config: { summarizationProvider: "", summarizationModel: "", maxTokens: 65536 }, - compactIfNeeded: async () => null, compactPressure: async () => null, - compactRegion: async () => null, compactNow: async () => null, - summarize: async part => { - calls++; - assert.equal(nativeSummaryActive(), true); - assert.deepEqual(part.tools, tools); - const schemaTokens = meter(message(JSON.stringify(part.tools))); - assert.ok(part.messages.reduce((n, m) => n + meter(m), 0) + schemaTokens + 65536 + 4096 <= Math.floor(272000 * 0.9)); - for (const m of part.messages) for (const b of m.content) for (const fact of b.text?.match(/fact-\d/g) ?? []) seen.add(fact); - return { summary: [{ type: "text", text: "Short retained facts." }] }; - }, - }; - const ctx: Parameters[0] = { compaction: engine, tokenMeter: { estimateMessage: meter }, llm: { resolveModelInfo: async () => ({ context: { contextWindow: 272000 } }) }, on: () => undefined }; - apply(ctx); - await engine.summarize(input, agent); - assert.ok(calls > 1, "the tool reservation must force bounded batches"); - assert.equal(seen.size, 6); - assert.deepEqual(input, before); - const previousCalls = calls; - await assert.rejects(engine.summarize({ messages: [message("fact")], tools: [{ description: "x".repeat(800000) }] }, agent), /insufficient input budget/); - assert.equal(calls, previousCalls, "genuinely oversized schemas fail before egress"); -}); - -test("multi-batch handoff discards partial reductions after a later failure or cancellation and can retry", async () => { - const input = { messages: Array.from({ length: 4 }, (_, i) => message(`fact-${i} `.repeat(800))) }; - const before = structuredClone(input); - let failedCalls = 0; - await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { - if (++failedCalls === 2) throw new Error("second batch failed"); - return { summary: [{ type: "text", text: "partial" }] }; - }), /second batch failed/); - assert.equal(failedCalls, 2); - assert.deepEqual(input, before); - - const controller = new AbortController(); - let cancelledCalls = 0; - await assert.rejects(boundedNativeSummary(input, 10000, estimate, async () => { - if (++cancelledCalls === 2) controller.abort(new Error("cancelled during reduction")); - return { summary: [{ type: "text", text: "partial" }] }; - }, controller.signal), /cancelled during reduction/); - assert.equal(cancelledCalls, 2); - assert.deepEqual(input, before); - - const seen = new Set(); - const recovered = await boundedNativeSummary(input, 10000, estimate, async part => { - for (const m of part.messages) for (const b of m.content) for (const fact of b.text?.match(/fact-\d/g) ?? []) seen.add(fact); - return { summary: [{ type: "text", text: "recovered" }] }; - }); - assert.equal(seen.size, 4); - assert.equal(recovered.summary[0].text, "recovered"); - assert.deepEqual(input, before); -}); - 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 } } }; @@ -250,7 +82,6 @@ test("overlapping native summary and bili work keep separate ownership across aw let entered!: () => void; const ready = new Promise(resolve => { entered = resolve; }); const engine: Parameters[0]["compaction"] = { - config: { summarizationProvider: "", summarizationModel: "", maxTokens: 100 }, compactIfNeeded: async () => { throw new Error("bili must not call native backend"); }, compactPressure: async () => null, compactRegion: async () => null, compactNow: async () => null, summarize: async () => { @@ -261,7 +92,7 @@ test("overlapping native summary and bili work keep separate ownership across aw throw new Error("held summary failed"); }, }; - apply({ compaction: engine, tokenMeter: { estimateMessage: () => 10 }, llm: { resolveModelInfo: async () => ({ context: { contextWindow: 20000 } }) }, on: () => undefined }); + apply({ compaction: engine, on: () => undefined }); const pending = engine.summarize({ messages: [message("fact")] }, native); await ready; assert.equal(nativeSummaryActive(), false); @@ -274,3 +105,53 @@ test("overlapping native summary and bili work keep separate ownership across aw 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); +}); 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); }); From c4a91e9c4d882b8dcd4c5530436e39740509f304 Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Wed, 11 Nov 2026 21:13:29 +0800 Subject: [PATCH 6/9] test(dsh): register isolated parity proxy workers for CI --- scripts/live-files.mjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/scripts/live-files.mjs b/scripts/live-files.mjs index 014f5c22d4..2f6233cabb 100644 --- a/scripts/live-files.mjs +++ b/scripts/live-files.mjs @@ -134,6 +134,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", ]; /** Band width per live file: the zone ladder drifts +1 per EADDRINUSE retry; From 08bf768002591bdba011ccb125f64a58ce9fe33b Mon Sep 17 00:00:00 2001 From: ci-check Date: Fri, 13 Nov 2026 05:06:00 +0800 Subject: [PATCH 7/9] test: mask wall-clock timestamps in the dsh compaction parity test The parity test compares forwarded payloads across three forked proxy arms with deepEqual, but the kernel stamps wall-clock yyyy-mm-dd hh:mm:ss timestamps into the ACP tag time= attribute and the compress tool-result block time range. Arms running on different seconds differ in those bytes alone, so the comparison flaked. Mask every wall-clock timestamp before the cross-arm comparison (same sanctioned normalization as issue5403-watermark-fastpath.test.ts). --- tests/dsh-llm-stream-attribution.test.ts | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/tests/dsh-llm-stream-attribution.test.ts b/tests/dsh-llm-stream-attribution.test.ts index aa64c7ded6..06aa99c431 100644 --- a/tests/dsh-llm-stream-attribution.test.ts +++ b/tests/dsh-llm-stream-attribution.test.ts @@ -105,6 +105,24 @@ test("DSH dispatch switches native/bili/native with unchanged native wire and a 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"); @@ -167,7 +185,7 @@ test("bili-only and model-routed bili have identical real proxy folds and forwar 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), blocks: after.blocks.map(({ createdAt, compressCallId, durationMs, ...b }) => b), tools: handle.registered.map(t => t.name) }); + 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" } }); From 7bb2966240a003b04e551337811d4f49c48ef12f Mon Sep 17 00:00:00 2001 From: ci-check Date: Wed, 18 Nov 2026 18:28:32 +0800 Subject: [PATCH 8/9] docs: regenerate docs/configuration.ja.md for dsh.nativeCompactionModels (#6123) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PR added the dsh.nativeCompactionModels seed entries and regenerated the EN/ZH config docs, but the Japanese artifact was left stale — the docs-sync drift guard (gen-config-docs generate + git diff --exit-code) went red on the merge ref. This commit is the generator's own output; no manual edits. --- docs/configuration.ja.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/docs/configuration.ja.md b/docs/configuration.ja.md index 215a6ffc3e..a4d6ff8f96 100644 --- a/docs/configuration.ja.md +++ b/docs/configuration.ja.md @@ -122,7 +122,10 @@ | `compat.streamErrorShape` | "protocol" \| "completion" | protocol | BILI_STREAM_ERROR_SHAPE | 200 がコミットされた後、上流ストリーム失敗がどのように提示されるか:プロトコルネイティブのエラーフレーム(デフォルト)またはレガシーの合成完了形状。 | | `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 に従い環境変数なし)。デフォルト未設定 = 組み込みラベルは変更なし。 | From fb4e82c6385253c2a3fbecd0fd4551db87452a12 Mon Sep 17 00:00:00 2001 From: bluesmilery <19263500+bluesmilery@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:36:20 +0800 Subject: [PATCH 9/9] Keep selective compaction intact for runtime presets and scoped auxiliary calls --- docs/dsh-native-compaction.md | 4 +-- docs/dsh-native-compaction.zh-CN.md | 4 +-- scripts/test-dsh-native-compaction.mjs | 8 ++++-- src/agent/dsh-compaction-disable.ts | 33 ++++++++++++++++-------- src/agent/dsh-native.ts | 13 +++++----- tests/dsh-llm-stream-attribution.test.ts | 19 ++++++++++++++ tests/dsh-native-compaction.test.ts | 26 +++++++++++++++++++ 7 files changed, 84 insertions(+), 23 deletions(-) diff --git a/docs/dsh-native-compaction.md b/docs/dsh-native-compaction.md index 109d1c92b3..59bde7411d 100644 --- a/docs/dsh-native-compaction.md +++ b/docs/dsh-native-compaction.md @@ -37,7 +37,7 @@ When switching native → bili, the host's durable `surface.replaceGeneration` c ## Compatibility and validation -Validated with DSH `0.2.2-rc.1`. 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: +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 @@ -45,7 +45,7 @@ node scripts/test-dsh-native-compaction.mjs /absolute/path/to/isolated-dsh-runti 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 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. +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 diff --git a/docs/dsh-native-compaction.zh-CN.md b/docs/dsh-native-compaction.zh-CN.md index 4d12e2bfa3..79663db534 100644 --- a/docs/dsh-native-compaction.zh-CN.md +++ b/docs/dsh-native-compaction.zh-CN.md @@ -37,7 +37,7 @@ flowchart LR ## 验证与边界 -针对 DSH `0.2.2-rc.1` 验证。集成脚本使用真实 Cordis Loader、独立压缩作用域、token meter、Session 重放和原生检查点引擎;模型为确定性假实现,不消耗账户额度: +针对 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运行时 @@ -45,7 +45,7 @@ node scripts/test-dsh-native-compaction.mjs /绝对路径/隔离的DSH运行时 运行时必须是独立副本,不是正在运行的 profile。测试不使用凭据、现有会话或线上文件;不代表已经验证真实模型的摘要质量或计费。 -预设未挂载适配器时,原生请求明确失败。原厂 minimal 预设没有压缩后端,命中原生规则时维持其原样,不额外添加压缩。CLI 根作用域配置、未来 DSH API 版本需要额外适配,不能直接视为已支持。 +预设未挂载适配器时,原生请求明确失败。拒绝仅影响这次原生请求,不影响其他模型或会话。配置可读取但规则格式无效时,DSH 插件不能激活;修正规则后重启。整份配置无法解析时,加载器沿用默认配置,原生规则不会启用。静态和运行时注册的预设使用同一路由策略。原厂 minimal 预设没有压缩后端,命中原生规则时维持其原样,不额外添加压缩。CLI 根作用域配置、未来 DSH API 版本需要额外适配,不能直接视为已支持。 ## 行为对照验收 diff --git a/scripts/test-dsh-native-compaction.mjs b/scripts/test-dsh-native-compaction.mjs index c9a9bb5e0f..cdd4811567 100644 --- a/scripts/test-dsh-native-compaction.mjs +++ b/scripts/test-dsh-native-compaction.mjs @@ -1,6 +1,7 @@ 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)); @@ -11,7 +12,7 @@ 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([{ model: 'gpt-*' }]); +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 = [ @@ -21,6 +22,9 @@ const scenarios = [ { 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 }, @@ -137,4 +141,4 @@ for (const scenario of scenarios) { 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: '0.2.2-rc.1', parityCases: results })); +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 52ab579688..94540d0742 100644 --- a/src/agent/dsh-compaction-disable.ts +++ b/src/agent/dsh-compaction-disable.ts @@ -235,15 +235,26 @@ export function disableBasicCompaction(rows: readonly unknown[]): unknown[] { } export function selectiveBasicCompaction(rows: readonly unknown[]): unknown[] { - const result = rows.map(row => { - if (row === null || typeof row !== "object") return row; - const r = row as PresetRow; - return r.group && Array.isArray(r.config) ? { ...r, config: selectiveBasicCompaction(r.config) } : row; - }); - if (rows.some(row => row !== null && typeof row === "object" && (row as PresetRow).name === DSH_COMPACTION_BASIC_PACKAGE) && - !rows.some(row => row !== null && typeof row === "object" && (row as PresetRow).name === "billion-context/dsh-native-compaction")) { - result.push({ name: "billion-context/dsh-native-compaction" }); + 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; } @@ -287,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) }; } /** @@ -360,7 +371,7 @@ export function registerCompactionDisable(ctx: CompactionDisableHost): void { const compactionRows = countCompactionRows(config.plugins); if (compactionRows === 0) { if (!selectiveCompactionEnabled() || entryName !== DSH_AGENT_PRESET_PACKAGE) return resolved; - return { ...config, plugins: [...config.plugins, { name: "billion-context/dsh-native-compaction", config: { noBackend: true } }] }; + return { ...config, plugins: selectiveBasicCompaction(config.plugins) }; } noteGateCoverage(entryName.slice(0, 120), compactionRows, entryName === DSH_AGENT_PRESET_PACKAGE); return { ...config, plugins: selectiveCompactionEnabled() ? selectiveBasicCompaction(config.plugins) : disableBasicCompaction(config.plugins) }; diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index b081512409..fb1ca0b824 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -1265,7 +1265,7 @@ interface LlmDispatchScope { msgIds: string[] | undefined; nativeCompaction?: boolean; conversationId?: string; - titleRequest?: boolean; + 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 @@ -2240,14 +2240,14 @@ export async function apply(ctx: PluginContext): Promise { // 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 titleRequest = options.purpose === "session-title"; - if (native && !nativeSummaryActive() && !titleRequest) requireNativeCompactionReady(agent); - const conversationId = native || titleRequest ? sid : compactionConversationId(agent, sid); + 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), nativeCompaction: native, conversationId, titleRequest, 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 @@ -2838,7 +2838,8 @@ export async function apply(ctx: PluginContext): Promise { 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() && !dispatchScope.getStore()?.titleRequest) { + 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); diff --git a/tests/dsh-llm-stream-attribution.test.ts b/tests/dsh-llm-stream-attribution.test.ts index c6ef89cf51..c1003e83a7 100644 --- a/tests/dsh-llm-stream-attribution.test.ts +++ b/tests/dsh-llm-stream-attribution.test.ts @@ -668,3 +668,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 index 6d5bc2f085..226acc6f35 100644 --- a/tests/dsh-native-compaction.test.ts +++ b/tests/dsh-native-compaction.test.ts @@ -155,3 +155,29 @@ test("native summary preserves host errors and aborted signals without adapter r 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(); + } +});