From 9cd10f1ed048dba189791e1c9252d81e761fae08 Mon Sep 17 00:00:00 2001 From: awork Date: Sun, 18 Oct 2026 23:39:09 +0800 Subject: [PATCH 1/2] fix: keep dsh presets bootable when bili-native is disabled (#3662) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Disabling or kill-switching the dsh plugin removed the only provider of biliBasicCompactionPolicy while the bundle patch kept gating all four web-profile presets on it — every preset stayed pending forever and new/ resumed sessions failed with "Unknown agent preset: standard". The load-time overlay + gate service now live in their own always-on cordis entry (bili-compaction-gate), mounted alongside bili-native by both patch carriers (dsh.bundle.patch.yml, launcher overlay). The entry registers the transform and provides the service atomically (the #3354 ordering guarantee survives the split); whether it disables the preset compaction rows is decided per process by a verdict bili-native sets from apply() — an absent verdict (entry disabled, kill-switched, module failed to load) leaves every row stock. Behavior changes: - disabling/kill-switching bili-native: presets used to pend forever (session creation bricked); they now boot with STOCK native compaction — compression off, dsh fully usable. - bili-native module failing to load: previously a deliberate fail-safe brick; now falls back to stock with the #1729 wire-level refusal guard as backstop (availability over fail-safe-brick). - new visible cordis entry bili-compaction-gate; disabling IT re-creates the pending state (documented in bundle patch header + CLIENTS / CONFIGURATION en+zh). Full uninstall: remove billion-context from dsh.profile.bundles. Closes #3662 --- CLIENTS.md | 44 ++++- CLIENTS.zh-CN.md | 3 +- CONFIGURATION.md | 4 +- CONFIGURATION.zh-CN.md | 4 +- dsh.bundle.patch.yml | 15 +- package.json | 1 + scripts/check-test-import-graph.mjs | 1 + scripts/check-unused-exports.mjs | 1 + src/agent/dsh-compaction-disable.ts | 63 +++++-- src/agent/dsh-compaction-gate.ts | 20 +++ src/agent/dsh-native.ts | 29 ++-- src/launcher.ts | 19 ++- tests/dsh-native.test.ts | 62 +++---- .../issue3354-dsh-compaction-disable.test.ts | 63 ++++--- tests/issue3662-dsh-gate-fallback.test.ts | 154 ++++++++++++++++++ tests/launcher.test.ts | 25 ++- tsup.config.ts | 2 +- 17 files changed, 396 insertions(+), 114 deletions(-) create mode 100644 src/agent/dsh-compaction-gate.ts create mode 100644 tests/issue3662-dsh-gate-fallback.test.ts diff --git a/CLIENTS.md b/CLIENTS.md index 5fe1b9d4d3..34e031c453 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -98,12 +98,16 @@ Two lanes, same plugin (#941): No patch layer can address that NESTED row by id — dsh's patch engine indexes only top-level rows and true group children — so the bundled `auto: false` lands on web-app's already-disabled host-plane row and - changes nothing. Since #3354 bili closes the gap at LOAD TIME: the - `bili-native` bundle entry registers a cordis `internal/config` overlay - (vendored from deshark42/dsh-compaction-basic-disable, MIT) that marks - the preset's `compaction-basic` and `command-compact` rows - `disabled: true`, and the preset gate rows in the bundle patch make each - Web preset wait for that overlay before it can register. Native + changes nothing. Since #3354 bili closes the gap at LOAD TIME: an + always-on bundle entry `bili-compaction-gate` — a separate cordis entry + beside `bili-native`, mounted by the same patch layers, so it stays + alive when `bili-native` is disabled or kill-switched (#3662) — + registers a cordis `internal/config` overlay (vendored from + deshark42/dsh-compaction-basic-disable, MIT) that marks the preset's + `compaction-basic` and `command-compact` rows `disabled: true` while + bili owns the lane, and the preset gate rows in the bundle patch make + each Web preset wait for that overlay's service before it can register. + Native auto-compaction is OFF in these profiles too (and `/compact` is unavailable there); ACP compression is unaffected. The overlay rides an INTERNAL dsh hook and is version-sensitive — if you still see a dsh @@ -118,9 +122,31 @@ Two lanes, same plugin (#941): leave the preset unrecognized by the roster — and `- insert:` with the same id appends a second dead row instead of merging. The snapshot also freezes the roster until re-copied after a dsh preset update. The plugin - logs a one-time `[dsh-client]` note naming both paths at boot in such - profiles. - - **Global copy shadows the profile copy at load time (#2891):** dsh resolves + logs a one-time `[dsh-client]` note naming both paths at boot in such + profiles. + - **Disabling vs removing the plugin (#3662):** pre-#3662, disabling + `bili-native` (dsh plugin manager, or `disabled: true` in any patch + layer) removed the ONLY provider of the gate service while the preset + rows kept waiting on it — all four Web presets stayed pending forever + and every new/resumed session failed with + `Unknown agent preset: standard`. The service now lives in the + separate always-on `bili-compaction-gate` entry: disabling or + kill-switching (`BILLION_CONTEXT_PLUGIN=0`) `bili-native` hands the + lane back to STOCK dsh behavior — presets boot normally and native + auto-compaction returns; compression is simply off. Do NOT disable + `bili-compaction-gate` itself — that re-creates the brick. To fully + uninstall, remove `billion-context` from the profile's + `dsh.profile.bundles` (and its dependency) and restart: the whole + patch layer disappears and `compaction-basic` returns to stock + `auto: true`. If you are stuck on a pre-#3662 version with the plugin + already disabled, upgrading self-heals (the patch layer mounts from + whatever package is listed in bundles, regardless of `bili-native`'s + state); the manual un-brick is appending four rows to the HOME-layer + patch `$DSH_HOME/cordis.patch.yml` (`~/.dsh/cordis.patch.yml` when + `DSH_HOME` is unset) — `- id: preset-standard` / `preset-ptc` / + `preset-minimal` / `preset-cordis`, each with `inject: null`. Top-level + keys are replaced wholesale, clearing the pending latch. + - **Global copy shadows the profile copy at load time (#2891):** dsh resolves the bare `billion-context` name in `dsh.profile.bundles` installation- anchor-first — from its own install tree (the global npm root) before the profile's `node_modules`. So if a machine-global `billion-context` exists diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index 8ede678fdc..e477a54855 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -14,7 +14,8 @@ - **桌面应用(Electron 宿主):** 同一插件也运行在 deepseek-harness **desktop** 应用内(经其应用内插件管理器安装)。此时 bootstrap 在应用进程内拉起代理:该进程的 `process.execPath` 是 Electron 二进制而非 Node,GUI 的 PATH 又不含常规安装目录 —— `resolveNodeRuntime`(#819/#1429)先探测众所周知的安装位置(`/opt/homebrew/bin`、`/usr/local/bin`、Volta 等),再回退到以纯 Node 方式运行应用自身二进制(`ELECTRON_RUN_AS_NODE=1`,强制注入子进程 env),于是无需 PATH 里有独立 Node 也能零配置压缩;设 `BILLION_CONTEXT_NODE` 可强制指定某个 Node(优先于两者)。#1429 之前该路径在 spawn 前抛错,所有会话静默降级为直连(不压缩),只能从 bili.log 里发现。 - **自动更新保持各 profile 同步:** 刷新有两个触发器 —— 全局自更新完成后,以及**profile 自己的代理**在周期检查里发现注册表有新版本时(全局 bili 从不运行也一样刷新,#1196 —— 插件市场安装的用户往往根本没有全局安装)。两种触发器都扫描 `~/.dsh/profiles/*/package.json`,把注册表钉住的 `billion-context` 依赖刷新到目标版本(全局触发器刷到新全局版本,自触发刷到注册表最新),统一经 dsh 自己的 `plugin add` 通道,绝不在位覆盖 —— 加载的插件与代理从此不再漂移(#953);钉在本地源的 profile 不动。刷新是尽力而为,失败下个周期重试,绝不会让代理或更新本身失败。 - **已报告:Profile 安装下部分传输零代理流量(#1158,调查中):** dsh `llm-pi-ai` 层的部分传输服务会话**从未有任何模型请求到达代理**(日志无 `processTurn`,调用 bili 工具返回 404 "no model request has arrived"),而同宿主的其他 provider 正常。根因仍在用运行时证据定性 —— 候选:传输层 fetch 形态(SDK 注入 fetch / 非全局 dispatcher)或宿主侧归属缺口导致流量未被 takeover gate 认领。检测:此类情况会打一次性 `[plugin] NO MODEL REQUESTS seen for conversation …` 告警,dsh 插件还会把归属 gate 放行的每个端点各记一条日志(每进程一次)。期间可靠规避:改用 `bili dsh` 启动 —— 启动器的 settings overlay 会把那些 provider 的 `baseURL` 重写为 `/bili/` URL,无论传输层使用哪种 fetch、归属状态如何,流量都必然过代理。 -- **Web profile 压缩(#1772,#3354 解决):** 当 profile 的 bundles 含 `@deepseek-ai/dsh-web-app` 时,真正运行的 `compaction-basic` 实例位于 agent preset(`preset-standard.config.plugins`)内部 —— dsh 的 patch 引擎只按 id 索引顶层条目与真 group(`group: true` 且 config 为数组)的子项,preset 内的嵌套行任何 patch 层都无法**按 id 直寻**。于是 bundle 里的 `auto: false` 落在 web-app 已禁用的宿主平面行上、什么都没改。#3354 起 bili 在**加载期**补上这一环:`bili-native` bundle 条目注册一个 cordis `internal/config` overlay(移植自 deshark42/dsh-compaction-basic-disable,MIT),把 preset 里的 `compaction-basic` 与 `command-compact` 行标记为 `disabled: true`;bundle patch 里的 preset 门控行让每个 Web preset 在注册前等待该 overlay。这些 profile 里原生自动压缩同样关闭(且 `/compact` 在那里不可用);ACP 压缩不受影响。overlay 依赖 dsh 的内部钩子、对版本敏感 —— 若在新/旧 dsh 构建上仍见到 dsh 压缩 checkpoint 落地,回退到 #2474 配方:profile 层 patch(你 profile 自己的 `cordis.patch.yml`,在所有 bundle 之后生效)用同 id + **完整快照** `config` 整体覆盖 preset-standard —— 从 `dsh --profile --dump-config` 抄下完整的 preset config,在其 `compaction-basic` 行下加 `config.auto: false`,把结果追加进 `cordis.patch.yml`。Config 替换是**整体语义**(片段会静默丢掉一切未重述的键 —— 不只是其他插件,连 preset 自己的 `id`/`order` 身份也会丢,可能使 roster 无法识别该 preset);`- insert:` 同 id 则是在末尾追加一条死行而非合并。dsh 升级 preset 后快照冻结 roster、需重抄一次。此类 profile 启动时插件打一条一次性 `[dsh-client]` 日志,说明两条路径。 +- **Web profile 压缩(#1772,#3354 解决):** 当 profile 的 bundles 含 `@deepseek-ai/dsh-web-app` 时,真正运行的 `compaction-basic` 实例位于 agent preset(`preset-standard.config.plugins`)内部 —— dsh 的 patch 引擎只按 id 索引顶层条目与真 group(`group: true` 且 config 为数组)的子项,preset 内的嵌套行任何 patch 层都无法**按 id 直寻**。于是 bundle 里的 `auto: false` 落在 web-app 已禁用的宿主平面行上、什么都没改。#3354 起 bili 在**加载期**补上这一环:一个**常驻**的 bundle 条目 `bili-compaction-gate`(与 `bili-native` 并列的独立 cordis 条目,由同一组 patch 层挂载,因此 `bili-native` 被禁用或 kill-switch 时它仍然存活,#3662)注册一个 cordis `internal/config` overlay(移植自 deshark42/dsh-compaction-basic-disable,MIT),在 bili 持有该泳道期间把 preset 里的 `compaction-basic` 与 `command-compact` 行标记为 `disabled: true`;bundle patch 里的 preset 门控行让每个 Web preset 在注册前等待该 overlay 的服务。这些 profile 里原生自动压缩同样关闭(且 `/compact` 在那里不可用);ACP 压缩不受影响。overlay 依赖 dsh 的内部钩子、对版本敏感 —— 若在新/旧 dsh 构建上仍见到 dsh 压缩 checkpoint 落地,回退到 #2474 配方:profile 层 patch(你 profile 自己的 `cordis.patch.yml`,在所有 bundle 之后生效)用同 id + **完整快照** `config` 整体覆盖 preset-standard —— 从 `dsh --profile --dump-config` 抄下完整的 preset config,在其 `compaction-basic` 行下加 `config.auto: false`,把结果追加进 `cordis.patch.yml`。Config 替换是**整体语义**(片段会静默丢掉一切未重述的键 —— 不只是其他插件,连 preset 自己的 `id`/`order` 身份也会丢,可能使 roster 无法识别该 preset);`- insert:` 同 id 则是在末尾追加一条死行而非合并。dsh 升级 preset 后快照冻结 roster、需重抄一次。此类 profile 启动时插件打一条一次性 `[dsh-client]` 日志,说明两条路径。 +- **禁用与移除插件的区别(#3662):** #3662 之前,禁用 `bili-native`(dsh 插件管理器,或任何 patch 层里写 `disabled: true`)会把门控服务的**唯一**提供方一并移除,而 preset 行仍在等它 —— 四个 Web preset 永久 pending,新建/恢复会话全部报 `Unknown agent preset: standard`。现在该服务住在独立的常驻条目 `bili-compaction-gate` 里:禁用或 kill-switch(`BILLION_CONTEXT_PLUGIN=0`)`bili-native` 只是把泳道交还 dsh **原生行为** —— preset 正常注册、原生自动压缩恢复,bili 压缩则完全关闭。请勿禁用 `bili-compaction-gate` 本身 —— 那会重新造成「砖」。要彻底卸载:从 profile 的 `dsh.profile.bundles`(及其依赖)里移除 `billion-context` 后重启 —— 整个 patch 层消失,`compaction-basic` 回到原生默认 `auto: true`。若卡在 #3662 之前的版本且插件已被禁用:升级即自愈(patch 层按 bundles 里列出的包装载,与 `bili-native` 的启用状态无关);手动解砖是在 HOME 层 patch `$DSH_HOME/cordis.patch.yml`(`DSH_HOME` 未设时为 `~/.dsh/cordis.patch.yml`)追加四行 `- id: preset-standard` / `preset-ptc` / `preset-minimal` / `preset-cordis`,各配 `inject: null` —— 顶层键为整体替换,清掉 pending 锁。 - **全局副本在加载期抢占 profile 副本(#2891):** dsh 解析 `dsh.profile.bundles` 里的裸包名 `billion-context` 时是 installation-anchor-first —— 先在自己的安装树(全局 npm root)里找,再找 profile 的 `node_modules`。因此只要机器上存在一份全局 `billion-context`,dsh 就加载**全局那份**,profile 里装的被静默忽略 —— 不崩溃、无日志。两者版本不一致时,实际运行的可能与 profile 声明的不同(例如 #1590 之前的全局没有 `dsh.client` web 面,设置页菜单凭空消失)。这一事实默认情况下处处不可见:`bili doctor` 现在会按 profile 逐一标记任何版本不一致的全局/本地对(#2891);用 `dsh --profile --dump-config`(读该 bundle 的 `name:` 行)可核对 dsh 实际加载了哪份。 `bili dsh` 启动下插件**附看**(attach)启动器的代理(不二次拉起)。裸上游 URL 与 spawn 模式一样重写为 `/bili/`(回环代理目标永不被代理 env 拦截,等于直接绕开 MITM);已经路由的 `/bili/` 前缀请求原样放行、只盖章。已知局限:手动 `/compact` 没有 dsh 侧事件钩子,其边界交给内核的自然 ingest diff(自动压缩现已处处关闭 —— 宿主平面经 bundle patch,web profile 的 preset 经 #3354 加载期 overlay;见上方 Web profile 说明)。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 1528ab3fe4..884c3bfafb 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -2248,10 +2248,12 @@ Two compressors on one conversation double-compress and corrupt message refs, so #### Turning dsh native auto-compaction OFF in a web profile (#1772/#3354, automatic since #3354; #2474 recipe as fallback) - **Automatic since #3354.** In a profile bundling `@deepseek-ai/dsh-web-app` the running compaction-basic instance lives inside an agent preset (`preset-standard.config.plugins`) where no patch layer can address the nested row by id (#1772) — the bundled `- id: compaction-basic` row lands on web-app's already-disabled host-plane row and changes nothing. bili now closes that gap at LOAD TIME: the `bili-native` bundle entry registers a cordis `internal/config` overlay (vendored from [deshark42/dsh-compaction-basic-disable](https://github.com/deshark42/dsh-compaction-basic-disable), MIT) that marks the preset's `compaction-basic` and `command-compact` rows `disabled: true`, and the preset gate rows in `dsh.bundle.patch.yml` / the launcher overlay make each Web preset wait for that overlay before it can register. Native auto-compaction is off in these profiles with no user action; ACP compression is unaffected. + **Automatic since #3354.** In a profile bundling `@deepseek-ai/dsh-web-app` the running compaction-basic instance lives inside an agent preset (`preset-standard.config.plugins`) where no patch layer can address the nested row by id (#1772) — the bundled `- id: compaction-basic` row lands on web-app's already-disabled host-plane row and changes nothing. bili now closes that gap at LOAD TIME: an always-on bundle entry `bili-compaction-gate` — a separate cordis entry beside `bili-native`, mounted by the same patch layers, so it stays alive when `bili-native` is disabled or kill-switched (#3662) — registers a cordis `internal/config` overlay (vendored from [deshark42/dsh-compaction-basic-disable](https://github.com/deshark42/dsh-compaction-basic-disable), MIT) that marks the preset's `compaction-basic` and `command-compact` rows `disabled: true` while bili owns the lane, and the preset gate rows in `dsh.bundle.patch.yml` / the launcher overlay make each Web preset wait for that overlay's service before it can register. Native auto-compaction is off in these profiles with no user action; ACP compression is unaffected. The overlay rides an INTERNAL dsh hook and is version-sensitive. If you still see a dsh compaction checkpoint land on a newer/older dsh build, use the fallback below. + **Disabling vs removing (#3662).** Disabling `bili-native` (dsh plugin manager or `disabled: true` in a patch layer) no longer bricks session creation: the gate service survives in the separate always-on `bili-compaction-gate` entry, so the presets fall back to STOCK native compaction instead of pending forever — compression off, dsh fully usable. Never disable `bili-compaction-gate` itself (that re-creates the brick); to fully uninstall remove `billion-context` from the profile's `dsh.profile.bundles` and restart. Pre-#3662 installs left bricked self-heal on upgrade; manually, append `- id: preset-standard` / `preset-ptc` / `preset-minimal` / `preset-cordis`, each with `inject: null`, to `$DSH_HOME/cordis.patch.yml` (home layer; default `~/.dsh/cordis.patch.yml`) — top-level keys replace wholesale, clearing the pending latch. + **Fallback recipe (#2474)** (verified on dsh `0.2.1-alpha.1`, Windows 11, profile bundles including `@deepseek-ai/dsh-web-app`). A profile-layer patch can turn it off — presets are ordinary top-level rows inserted by the bundle layer, and the profile patch layer is applied after it. What does not work is addressing the nested row by id; what does work is overriding the preset row's `config` wholesale. ```bash diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 8088265ac6..4acefd054b 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -2218,10 +2218,12 @@ bili plugin remove pi # 撤销(原文件一次性备份为 *.bili-bak) #### 在 web profile 下关掉 dsh 原生自动压缩(#1772/#3354,#3354 起自动;#2474 配方为回退) - **#3354 起自动完成。** 在 bundles 含 `@deepseek-ai/dsh-web-app` 的 profile 里,真正运行的 compaction-basic 实例位于 agent preset(`preset-standard.config.plugins`)内部,任何 patch 层都无法按 id 直寻那条嵌套行(#1772)—— 随包的 `- id: compaction-basic` 行落在 web-app 已禁用的宿主平面行上、什么都没改。bili 现在在**加载期**补上这一环:`bili-native` bundle 条目注册一个 cordis `internal/config` overlay(移植自 [deshark42/dsh-compaction-basic-disable](https://github.com/deshark42/dsh-compaction-basic-disable),MIT),把 preset 里的 `compaction-basic` 与 `command-compact` 行标记为 `disabled: true`;`dsh.bundle.patch.yml` / 启动器 overlay 里的 preset 门控行让每个 Web preset 在注册前等待该 overlay。这些 profile 里原生自动压缩无需任何用户操作即关闭;ACP 压缩不受影响。 + **#3354 起自动完成。** 在 bundles 含 `@deepseek-ai/dsh-web-app` 的 profile 里,真正运行的 compaction-basic 实例位于 agent preset(`preset-standard.config.plugins`)内部,任何 patch 层都无法按 id 直寻那条嵌套行(#1772)—— 随包的 `- id: compaction-basic` 行落在 web-app 已禁用的宿主平面行上、什么都没改。bili 现在在**加载期**补上这一环:一个**常驻**的 bundle 条目 `bili-compaction-gate`(与 `bili-native` 并列的独立 cordis 条目,由同一组 patch 层挂载,因此 `bili-native` 被禁用或 kill-switch 时它仍然存活,#3662)注册一个 cordis `internal/config` overlay(移植自 [deshark42/dsh-compaction-basic-disable](https://github.com/deshark42/dsh-compaction-basic-disable),MIT),在 bili 持有该泳道期间把 preset 里的 `compaction-basic` 与 `command-compact` 行标记为 `disabled: true`;`dsh.bundle.patch.yml` / 启动器 overlay 里的 preset 门控行让每个 Web preset 在注册前等待该 overlay 的服务。这些 profile 里原生自动压缩无需任何用户操作即关闭;ACP 压缩不受影响。 overlay 依赖 dsh 的内部钩子,对版本敏感。若在新/旧 dsh 构建上仍见到 dsh 压缩 checkpoint 落地,用下面的回退配方。 + **禁用与移除的区别(#3662)。** 禁用 `bili-native`(dsh 插件管理器或 patch 层里的 `disabled: true`)不再会导致会话创建被「砖」:门控服务存活在独立的常驻条目 `bili-compaction-gate` 里,preset 回落到**原生**自动压缩而不是永久 pending —— 压缩关闭、dsh 完全可用。请勿禁用 `bili-compaction-gate` 本身(那会重新造成「砖」);要彻底卸载,从 profile 的 `dsh.profile.bundles` 移除 `billion-context` 后重启。卡在 #3662 之前版本且已被禁用的安装,升级即自愈;手动解砖是在 `$DSH_HOME/cordis.patch.yml`(HOME 层;默认 `~/.dsh/cordis.patch.yml`)追加 `- id: preset-standard` / `preset-ptc` / `preset-minimal` / `preset-cordis`,各配 `inject: null` —— 顶层键为整体替换,清掉 pending 锁。 + **回退配方(#2474)**(已在 dsh `0.2.1-alpha.1`、Windows 11、bundles 含 `@deepseek-ai/dsh-web-app` 的 profile 上实测)。profile 层补丁可以关掉它 —— preset 是 bundle 层插入的普通顶层条目,而 profile 补丁层在其之后应用。不能用「按 id 定位嵌套行」的写法,可行的是**整体覆盖 preset 行的 `config`**。 ```bash diff --git a/dsh.bundle.patch.yml b/dsh.bundle.patch.yml index 6fec7ae17f..d7b815f249 100644 --- a/dsh.bundle.patch.yml +++ b/dsh.bundle.patch.yml @@ -6,14 +6,23 @@ # compaction-basic row. In profiles bundling @deepseek-ai/dsh-web-app that row # is disabled and the running instance lives inside the agent presets, whose # nested rows no patch layer can address by id — the preset gate rows below -# make each Web preset wait for the load-time overlay the bili-native entry -# registers (vendored from deshark42/dsh-compaction-basic-disable, MIT, #3354; -# see src/agent/dsh-compaction-disable.ts). A profile-level full-snapshot +# make each Web preset wait for the load-time overlay the bili-compaction-gate +# entry registers (vendored from deshark42/dsh-compaction-basic-disable, MIT, +# #3354; see src/agent/dsh-compaction-disable.ts). A profile-level full-snapshot # override of preset-standard (#2474) remains the fallback for dsh builds # whose internal 'internal/config' hook moved. +# #3662: the gate lives in its OWN always-on entry, not in bili-native — +# disabling or kill-switching bili-native must leave the gate service alive so +# the presets fall back to STOCK dsh compaction instead of pending forever +# (the old wiring bricked session creation on exactly that path). Do NOT +# disable the bili-compaction-gate entry itself: it carries the service the +# presets wait on; to uninstall, remove billion-context from +# dsh.profile.bundles instead. - insert: - id: bili-native name: billion-context + - id: bili-compaction-gate + name: billion-context/dsh-compaction-gate - id: compaction-basic config: auto: false diff --git a/package.json b/package.json index 4902df5118..2aa68f38a0 100644 --- a/package.json +++ b/package.json @@ -8,6 +8,7 @@ ".": "./dist/agent/dsh-native.js", "./server": "./dist/agent/opencode-native.js", "./dsh": "./dist/agent/dsh-native.js", + "./dsh-compaction-gate": "./dist/agent/dsh-compaction-gate.js", "./package.json": "./package.json", "./dsh/package.json": "./package.json", "./client": "./dist/agent/dsh-native-client.js" diff --git a/scripts/check-test-import-graph.mjs b/scripts/check-test-import-graph.mjs index d60dd5171f..f515ec9b47 100644 --- a/scripts/check-test-import-graph.mjs +++ b/scripts/check-test-import-graph.mjs @@ -45,6 +45,7 @@ const ENTRY_FILES = new Set([ "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", diff --git a/scripts/check-unused-exports.mjs b/scripts/check-unused-exports.mjs index 13d5229d14..083b393768 100644 --- a/scripts/check-unused-exports.mjs +++ b/scripts/check-unused-exports.mjs @@ -34,6 +34,7 @@ const ENTRY_FILES = new Set([ "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", diff --git a/src/agent/dsh-compaction-disable.ts b/src/agent/dsh-compaction-disable.ts index 8fe9dbfc3e..53d935341d 100644 --- a/src/agent/dsh-compaction-disable.ts +++ b/src/agent/dsh-compaction-disable.ts @@ -14,6 +14,13 @@ // (auto:false); web profiles run their instance INSIDE an agent preset whose // nested rows no patch layer can address by id (#1772/#2360) — this module is // what reaches them. +// #3662: the overlay lives in its OWN always-on entry (dsh-compaction-gate.ts) +// rather than in bili-native — disabling or kill-switching bili-native must +// leave the gate service alive so the presets fall back to STOCK dsh +// compaction instead of pending forever (the old wiring bricked session +// creation on exactly that path). The transform honors the process verdict +// declared by bili-native's apply(); an absent declaration means bili-native +// never ran and every row passes through stock. /** The two dsh packages whose backends must not instantiate while bili owns the lane. */ const DSH_COMPACTION_BASIC_PACKAGE = "@deepseek-ai/dsh-compaction-basic"; @@ -24,10 +31,13 @@ const DSH_AGENT_PRESET_PACKAGE = "@deepseek-ai/dsh-agent-preset"; * dsh.bundle.patch.yml and the launcher overlay patch. A preset cannot * register until this service is provided, so the middleware below is * guaranteed registered before any protected preset resolves its config even - * when sibling imports finish out of order; if this module fails to load the - * presets stay pending (fail-safe: no unprotected start). Coexistence with - * the upstream plugin is safe: its service name differs and both overlays are - * idempotent (disabled:true twice = disabled:true). */ + * when sibling imports finish out of order. #3662: the provider is the + * always-on gate entry (dsh-compaction-gate.ts), NOT bili-native — disabling + * or kill-switching bili-native must keep the latch satisfiable so the + * presets fall back to stock instead of pending forever; only disabling the + * gate entry itself leaves them pending (see the bundle patch header). + * Coexistence with the upstream plugin is safe: its service name differs and + * both overlays are idempotent (disabled:true twice = disabled:true). */ export const BILI_COMPACTION_DISABLE_SERVICE = "biliBasicCompactionPolicy"; /** The four Web agent presets the overlay must reach (dsh-web-app roster; * preset-minimal ships no compaction group today — the row is a no-op there @@ -44,6 +54,31 @@ export function compactionDisablePatchRows(): string { return DSH_WEB_PRESET_IDS.map((id) => `- id: ${id}\n inject: [${BILI_COMPACTION_DISABLE_SERVICE}]\n`).join(""); } +// #3662: process-level verdict between the two entries. They are SEPARATE +// bundles in the dsh host (separate module instances — module state cannot +// cross them), and globalThis is the only surface both share. bili-native's +// apply() declares active once its plan says bili owns the lane; an ABSENT +// declaration means bili-native never ran in this process (entry disabled, +// kill-switched before the declaration, or its module failed to load) and the +// transform leaves every row stock. Availability over fail-safe-brick: a dead +// bili-native hands the lane back to stock dsh compaction, with the wire-level +// refusal guard (#1729) as backstop. +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 { + (globalThis as Record)[DSH_COMPACTION_VERDICT_KEY] = "active"; +} + +export function isDshCompactionActive(): boolean { + return (globalThis as Record)[DSH_COMPACTION_VERDICT_KEY] === "active"; +} + +/** Test hook: forget any declaration (back to "bili-native never ran"). */ +export function _resetDshCompactionVerdictForTest(): void { + delete (globalThis as Record)[DSH_COMPACTION_VERDICT_KEY]; +} + type PresetRow = { name?: unknown; group?: unknown; config?: unknown }; /** Mark every compaction row of a preset plugins tree disabled. Pure: returns @@ -63,24 +98,28 @@ export function disableBasicCompaction(rows: readonly unknown[]): unknown[] { }); } -type CompactionDisableHost = { +export type CompactionDisableHost = { on?: (event: string, listener: (raw: unknown, next: () => unknown) => unknown, options?: { global?: boolean }) => void; reflect?: { provide?: (name: string, value: unknown) => void } | undefined; }; type MiddlewareSelf = { entry?: { options?: { name?: unknown } } | undefined }; -/** Register the load-time overlay + publish the gate. Must run during - * apply() — the provide happens AFTER the middleware registers so the inject - * gate can never be satisfied before the transform is live. Degradation is - * per-layer and fail-safe: no `on` → the host predates the internal/config - * hook, the wire-level refusal guard (#1729) stays the backstop; no - * `reflect.provide` → the presets simply never see the gate and boot as they - * did pre-#3354. */ +/** Register the load-time overlay + publish the gate. Runs from the always-on + * gate entry's apply() (dsh-compaction-gate.ts, #3662) — NOT from bili-native, + * whose disable/kill-switch must not take the service with it. The provide + * happens AFTER the middleware registers so the inject gate can never be + * satisfied before the transform is live. Degradation is per-layer and + * fail-safe: no `on` → the host predates the internal/config hook, the + * wire-level refusal guard (#1729) stays the backstop; no `reflect.provide` + * → the presets simply never see the gate and boot as they did pre-#3354. */ export function registerCompactionDisable(ctx: CompactionDisableHost): void { if (typeof ctx.on === "function") { // Preset entries must carry the gate: sibling imports may finish out of order. ctx.on("internal/config", function (this: MiddlewareSelf, _raw: unknown, next: () => unknown): unknown { const resolved = next(); + // #3662: honor the process verdict — without an active declaration + // from bili-native every row passes through stock. + if (!isDshCompactionActive()) return resolved; if (this?.entry?.options?.name !== DSH_AGENT_PRESET_PACKAGE) return resolved; const config = (resolved ?? {}) as { plugins?: unknown }; if (!Array.isArray(config.plugins)) return resolved; diff --git a/src/agent/dsh-compaction-gate.ts b/src/agent/dsh-compaction-gate.ts new file mode 100644 index 0000000000..bf64452f19 --- /dev/null +++ b/src/agent/dsh-compaction-gate.ts @@ -0,0 +1,20 @@ +// #3662: the always-on half of the #3354 compaction gate. bili-native used to +// own BOTH the load-time overlay and the service the four web-profile presets +// inject — so disabling or kill-switching it removed the service and left the +// presets pending forever, bricking session creation. The overlay now lives in +// this separate entry, which has no dependencies of its own and therefore +// activates whenever the bundle patch / launcher overlay is mounted, whatever +// bili-native's state. It registers the transform and provides the gate +// service atomically (the #3354 ordering guarantee survives the split); +// WHETHER the transform actually disables rows is decided per process by the +// verdict bili-native declares — see dsh-compaction-disable.ts. +import { registerCompactionDisable, type CompactionDisableHost } from "./dsh-compaction-disable.js"; + +type PluginContext = CompactionDisableHost; + +export const name = "bili-compaction-gate"; +export const inject: string[] = []; + +export function apply(ctx: PluginContext): void { + registerCompactionDisable(ctx); +} diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index 9044d4081a..bb87081411 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -35,9 +35,13 @@ // truncated first user message. Both services are optional — older // hosts degrade to the pre-#2604 labelless behavior, never block boot. // Native auto-compaction stands down on BOTH planes: the INSTALLER/LAUNCHER -// patch file keeps the host-plane row at auto:false, and this module disables -// the web-profile PRESET instances at load time (#3354, vendored from -// deshark42/dsh-compaction-basic-disable — see dsh-compaction-disable.ts). +// patch file keeps the host-plane row at auto:false, and the always-on +// bili-compaction-gate entry (dsh-compaction-gate.ts) disables the web-profile +// PRESET instances at load time (#3354, vendored from +// deshark42/dsh-compaction-basic-disable — see dsh-compaction-disable.ts); +// this module only DECLARES that the lane is owned, so a disabled or +// kill-switched bili-native leaves the presets bootable with stock compaction +// instead of pending on a service no one provides anymore (#3662). // dsh has no compaction event hook to observe a manual /compact, so its // boundary is left to the kernel's natural ingest diff (#395 gap, acceptable: // manual /compact is rare and auto mode is off). @@ -58,7 +62,7 @@ import { installNativeFetchIntercept, liveStateSlotEffect, noteRoutedOrigin, obs import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportAttributionHealth, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js"; import { createForkAdopter, sideShapedBody } from "./fork-adopt.js"; import { clearIncrementalProbe, createPrepareDirectSend, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, rememberOriginalBody, sweepStale, type IncrementalWireMessage } from "./incremental-client.js"; -import { detectCompactionOverlayGap, registerCompactionDisable } from "./dsh-compaction-disable.js"; +import { declareDshCompactionActive, detectCompactionOverlayGap } from "./dsh-compaction-disable.js"; import { maskUrlForDiagnostics } from "../log-mask.js"; import { conversationRecallStats, learnConversation, recallBoundaryOfMessages, recallConversation, recallHistoryFingerprints, recallLaneHasEntries, recallLaneKey } from "./conversation-recall.js"; export { sideShapedBody } from "./fork-adopt.js"; @@ -1528,12 +1532,14 @@ export function apply(ctx: PluginContext): void { // nothing: invalidating recoveries on a kill-switch could strand the lane. originGen += 1; - // #3354: stand dsh's native basic compaction down at LOAD TIME — reaches - // the web-profile preset instances no patch layer can address by id - // (#1772/#2360); the host plane already stands down via the bundle patch - // (auto:false). Gated on plan.mode: a kill-switched bili must hand the - // lane back to stock dsh behavior, so this runs only when bili is on. - registerCompactionDisable(ctx); + // #3354/#3662: declare that THIS process owns compression so the always-on + // gate entry's load-time overlay (#3354) actually disables the web-profile + // preset instances no patch layer can address by id (#1772/#2360). The + // declaration — not the registration — is what's gated on plan.mode: a + // kill-switched or disabled bili-native never declares, and the gate then + // leaves every row stock while its service still lets the presets boot + // (disabling the plugin must not brick session creation, #3662). + declareDshCompactionActive(); // #2082: a fresh activation invalidates the "host tearing down" verdict. // Without this reset, ONE registerTools rejection carrying "inactive @@ -2323,7 +2329,8 @@ export function apply(ctx: PluginContext): void { // compaction-basic instance sits inside an agent preset (preset-standard's // config.plugins) where no patch layer can address the NESTED row by id // (#1772/#2360). Since #3354 bili disables those preset rows at LOAD TIME - // (registerCompactionDisable above, vendored from + // (the always-on bili-compaction-gate entry, active while this module's + // verdict holds — #3662; vendored from // deshark42/dsh-compaction-basic-disable, MIT), so native auto-compaction // is off in these profiles too. The durable note confirms the stance and // keeps the #2474 full-snapshot recipe as the fallback for dsh builds diff --git a/src/launcher.ts b/src/launcher.ts index 240a61b11f..3ae0e8f6d0 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -3118,9 +3118,14 @@ const DSH_BARE_ENTRY = "billion-context"; * `dsh.client` declaration the scanner reads plus two SYMLINKS into bili's * live dist — an auto-update that moves dist self-heals on the next launch. * Returns false when nothing was written (existing shims stay untouched). */ -export function writeDshClientShimFiles(shimDir: string, hostBundle: string, clientBundle: string, version: string): boolean { +export function writeDshClientShimFiles(shimDir: string, hostBundle: string, clientBundle: string, version: string, gateBundle?: string): boolean { try { if (!fs.existsSync(hostBundle) || !fs.existsSync(clientBundle)) return false; + // #3662: the always-on gate entry rides the same shim (a dangling + // symlink would break its load, so it joins only when present). + const hasGate = gateBundle !== undefined && fs.existsSync(gateBundle); + const exportsMap: Record = { ".": "./index.js", "./dsh": "./index.js", "./package.json": "./package.json", "./dsh/package.json": "./package.json", "./client": "./bundle.js" }; + if (hasGate) exportsMap["./dsh-compaction-gate"] = "./gate.js"; fs.rmSync(shimDir, { recursive: true, force: true }); fs.mkdirSync(shimDir, { recursive: true }); fs.writeFileSync( @@ -3129,12 +3134,13 @@ export function writeDshClientShimFiles(shimDir: string, hostBundle: string, cli name: "billion-context", version, type: "module", - exports: { ".": "./index.js", "./dsh": "./index.js", "./package.json": "./package.json", "./dsh/package.json": "./package.json", "./client": "./bundle.js" }, + exports: exportsMap, dsh: { client: { platform: "web" } }, })}\n`, ); fs.symlinkSync(hostBundle, path.join(shimDir, "index.js")); fs.symlinkSync(clientBundle, path.join(shimDir, "bundle.js")); + if (hasGate) fs.symlinkSync(gateBundle, path.join(shimDir, "gate.js")); return true; } catch { return false; @@ -3152,7 +3158,7 @@ export function writeDshClientShim(dshHome: string): boolean { try { version = JSON.parse(fs.readFileSync(path.join(selfPackageRoot(), "package.json"), "utf8")).version ?? version; } catch {} - return writeDshClientShimFiles(path.join(dshHome, "node_modules", "billion-context"), hostBundle, clientBundle, version); + return writeDshClientShimFiles(path.join(dshHome, "node_modules", "billion-context"), hostBundle, clientBundle, version, selfDistFile("agent/dsh-compaction-gate.js")); } /** #1590: entry name for the launcher's --patch overlay. The BARE package @@ -3178,6 +3184,11 @@ export function dshPluginEntry(dshHome: string): string { export function writeDshAcpPatch(dshHome: string, entryName?: string): string | undefined { const pluginUrl = entryName ?? pathToFileURL(selfDistFile("agent/dsh-native.js")).href; + // #3662: the gate entry mounts alongside bili-native in BOTH lanes (bare + // subpath through the shim; file URL otherwise) — dropping it would leave + // the preset inject rows below pending forever whenever bili-native does + // not run. + const gateUrl = pluginUrl === DSH_BARE_ENTRY ? `${DSH_BARE_ENTRY}/dsh-compaction-gate` : pathToFileURL(selfDistFile("agent/dsh-compaction-gate.js")).href; const dir = `${dshHome}-bili`; try { fs.mkdirSync(dir, { recursive: true }); @@ -3187,7 +3198,7 @@ export function writeDshAcpPatch(dshHome: string, entryName?: string): string | writeOverlayFileAtomic( dir, ".bili-acp.patch.yml", - `- insert:\n - id: bili-native\n name: ${pluginUrl}\n- id: compaction-basic\n config:\n auto: false\n# #3354: keep in sync with dsh.bundle.patch.yml — web-profile presets run their own compaction-basic in nested rows no patch layer can address by id (#1772); these gates make them wait for the load-time overlay the injected plugin registers (vendored from deshark42/dsh-compaction-basic-disable, MIT)\n${compactionDisablePatchRows()}# #2605: keep in sync with dsh.bundle.patch.yml — a patch replaces the row's whole config, so every default code is restated\n- id: llm-deepseek\n config:\n retryPolicy:\n mode: normal\n retryableCodes: [EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT, MALFORMED_RESPONSE]\n- id: llm-deepseek-account\n config:\n retryPolicy:\n mode: normal\n retryableCodes: [EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT, MALFORMED_RESPONSE]\n`, + `- insert:\n - id: bili-native\n name: ${pluginUrl}\n - id: bili-compaction-gate\n name: ${gateUrl}\n- id: compaction-basic\n config:\n auto: false\n# #3354/#3662: keep in sync with dsh.bundle.patch.yml — web-profile presets run their own compaction-basic in nested rows no patch layer can address by id (#1772); these gates make them wait for the load-time overlay the always-on bili-compaction-gate entry registers (vendored from deshark42/dsh-compaction-basic-disable, MIT)\n${compactionDisablePatchRows()}# #2605: keep in sync with dsh.bundle.patch.yml — a patch replaces the row's whole config, so every default code is restated\n- id: llm-deepseek\n config:\n retryPolicy:\n mode: normal\n retryableCodes: [EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT, MALFORMED_RESPONSE]\n- id: llm-deepseek-account\n config:\n retryPolicy:\n mode: normal\n retryableCodes: [EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT, MALFORMED_RESPONSE]\n`, ); const file = path.join(dir, ".bili-acp.patch.yml"); try { diff --git a/tests/dsh-native.test.ts b/tests/dsh-native.test.ts index cb85af04d5..bf62516633 100644 --- a/tests/dsh-native.test.ts +++ b/tests/dsh-native.test.ts @@ -7,7 +7,7 @@ import http from "node:http"; import { pathToFileURL } from "node:url"; import { apply, planNativeDsh, shouldBootstrapNativeDsh, persistClientEvent, mediaBytesOfWireBody, bodyProvablyOverWindow, _attributionHealthForTest, _resetAttributionHealthForTest, _registerStateForTest, _resetRegisterForTest, _setModelInfoForTest, _setSpawnForTest, _setThrewRetryForTest, _settleNativeForTest, _stateHeadersForTest, _stateRespawnForTest, _stateTakeoverGateForTest, _stateToolsReadyForTest, _stateBeforeSendForTest, _stateOnResponseForTest, _noteRoutedForTest, _resetRoutedForTest, _resetWebProfileWarningForTest, _resetNonWebTraceForTest, _resetTitlesForTest, type PluginContext } from "../src/agent/dsh-native.ts"; import { __resetIncrementalClientForTests } from "../src/agent/incremental-client.ts"; -import { BILI_COMPACTION_DISABLE_SERVICE } from "../src/agent/dsh-compaction-disable.ts"; +import { isDshCompactionActive, _resetDshCompactionVerdictForTest } from "../src/agent/dsh-compaction-disable.ts"; import { once } from "node:events"; import { startServer } from "../src/server.ts"; import { defaultConfig } from "acp-kernel"; @@ -587,11 +587,10 @@ function mockCtx() { type HostCtx = Parameters[0]; type HostListener = Parameters>[1]; const listeners: Record = {}; - // #3354: capture the load-time compaction-disable overlay — event order, - // provided services, and the internal/config middleware for simulation. + // #3354/#3662: capture registration event order + provided services + // (the overlay itself now lives in the always-on gate entry). const order: string[] = []; const providedServices: Array<{ name: string; value: unknown }> = []; - let compactionMiddleware: ((raw: unknown, next: () => unknown) => unknown) | undefined; // Stable service identities (like real cordis services: one facade per // process whose state mutates underneath); getters gate exposure on the // backing fakes so T4's no-services degradation still reads absent. @@ -617,7 +616,6 @@ function mockCtx() { registeredCommands: commands, on: (event: string, listener: HostListener, _options?: { global?: boolean }) => { order.push(`on:${event}`); - if (event === "internal/config") compactionMiddleware = listener as (raw: unknown, next: () => unknown) => unknown; (listeners[event] ??= []).push(listener); }, emit: (event: string, ...args: unknown[]) => { for (const l of listeners[event] ?? []) (l as (...a: unknown[]) => void)(...args); }, @@ -651,7 +649,6 @@ function mockCtx() { reflect: { provide: (name: string, value: unknown) => { order.push(`provide:${name}`); providedServices.push({ name, value }); } }, providedServices, registrationOrder: () => [...order], - compactionMiddleware: () => compactionMiddleware, }; } @@ -1065,19 +1062,23 @@ test("apply() inactive-context registration failure is silent and terminal (dsh test("apply() is a no-op under the kill switches", async () => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-off-")); try { + _resetDshCompactionVerdictForTest(); await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PLUGIN: "0" }, () => { _resetRegisterForTest(undefined); const ctx = mockCtx(); apply(ctx); assert.equal(ctx.registeredTools.length, 0); assert.equal(ctx.registeredCommands.length, 0); - // #3354: a kill-switched bili must not register the load-time - // overlay either — the lane goes back to stock dsh behavior. + // #3354/#3662: a kill-switched bili must neither register the + // overlay nor declare the lane owned — the gate entry then leaves + // every preset row stock while its service keeps them bootable. assert.ok(!ctx.registrationOrder().some((e) => e.startsWith("on:internal/config"))); assert.equal(ctx.providedServices.length, 0); + assert.ok(!isDshCompactionActive(), "kill switch must not declare the lane owned"); }); } finally { rmrf(home); + _resetDshCompactionVerdictForTest(); } }); @@ -1222,54 +1223,29 @@ test("#3806 apply(): a degraded web profile alarms loudly instead of the silent } }); -test("#3354 apply(): registers the load-time compaction-disable overlay and publishes its gate", async () => { +test("#3354/#3662 apply(): declares lane ownership instead of registering the overlay", async () => { const proxy = await startMockProxy([]); const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-cd-")); try { + _resetDshCompactionVerdictForTest(); await withEnv({ DSH_HOME: home, BILLION_CONTEXT_PROXY: proxy.origin }, async () => { _resetRegisterForTest(proxy.origin); const ctx = mockCtx(); apply(ctx); - // the gate service publishes AFTER the middleware registers — the - // preset inject latch can never be satisfied before the transform - // is live - const iOn = ctx.registrationOrder().indexOf("on:internal/config"); - const iProvide = ctx.registrationOrder().indexOf(`provide:${BILI_COMPACTION_DISABLE_SERVICE}`); - assert.ok(iOn >= 0, "internal/config middleware must be registered"); - assert.ok(iProvide > iOn, "gate service must publish after the middleware registers"); - assert.deepEqual(ctx.providedServices.map((s) => s.name), [BILI_COMPACTION_DISABLE_SERVICE]); - - const mw = ctx.compactionMiddleware(); - assert.equal(typeof mw, "function"); - const run = (self: unknown, cfg: Record) => - (mw as (raw: unknown, next: () => unknown) => unknown).call(self, null, () => cfg); - // agent-preset entry: both compaction rows disabled, everything else untouched - const plugins: Array> = [ - { name: "@deepseek-ai/dsh-compaction-basic", config: { auto: true } }, - { name: "@deepseek-ai/dsh-command-compact" }, - { name: "@deepseek-ai/dsh-other" }, - ]; - const presetCfg: Record = { plugins, x: 1 }; - const out = run({ entry: { options: { name: "@deepseek-ai/dsh-agent-preset" } } }, presetCfg) as { plugins?: Array>; x?: number }; - assert.equal(out.x, 1); - assert.deepEqual(out.plugins?.[0]?.config, { auto: true }); - assert.equal(out.plugins?.[0]?.disabled, true); - assert.equal(out.plugins?.[1]?.disabled, true); - assert.equal(out.plugins?.[2]?.disabled, undefined); - // the original input is not mutated — detached copies only - assert.equal(plugins[0].disabled, undefined); - // non-preset entries pass through verbatim - const otherCfg: Record = { plugins }; - assert.equal(run({ entry: { options: { name: "something-else" } } }, otherCfg), otherCfg); - // a preset config without a plugins key passes through verbatim - const emptyCfg: Record = {}; - assert.equal(run({ entry: { options: { name: "@deepseek-ai/dsh-agent-preset" } } }, emptyCfg), emptyCfg); + // #3662: the overlay + gate service moved to the always-on + // bili-compaction-gate entry; bili-native only declares the verdict + // that transform honors (tests/issue3662-dsh-gate-fallback.test.ts + // pins the transform + service side). + assert.ok(isDshCompactionActive(), "active plan must declare the lane owned"); + assert.ok(!ctx.registrationOrder().some((e) => e.startsWith("on:internal/config"))); + assert.equal(ctx.providedServices.length, 0); await _stateToolsReadyForTest(); }); } finally { proxy.close(); rmrf(home); _resetRegisterForTest(undefined); + _resetDshCompactionVerdictForTest(); } }); diff --git a/tests/issue3354-dsh-compaction-disable.test.ts b/tests/issue3354-dsh-compaction-disable.test.ts index 22137faa3b..e2a9e0d8ce 100644 --- a/tests/issue3354-dsh-compaction-disable.test.ts +++ b/tests/issue3354-dsh-compaction-disable.test.ts @@ -4,7 +4,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; -import { BILI_COMPACTION_DISABLE_SERVICE, compactionDisablePatchRows, detectCompactionOverlayGap, disableBasicCompaction, registerCompactionDisable } from "../src/agent/dsh-compaction-disable.ts"; +import { BILI_COMPACTION_DISABLE_SERVICE, compactionDisablePatchRows, declareDshCompactionActive, detectCompactionOverlayGap, disableBasicCompaction, registerCompactionDisable, _resetDshCompactionVerdictForTest } from "../src/agent/dsh-compaction-disable.ts"; import { writeDshAcpPatch } from "../src/launcher.ts"; // #3354: the vendored dsh basic-compaction disable overlay (deshark42/ @@ -14,6 +14,10 @@ import { writeDshAcpPatch } from "../src/launcher.ts"; const TESTS_DIR = path.dirname(fileURLToPath(import.meta.url)); const PRESET_ROWS = compactionDisablePatchRows(); +// #3662: both carriers must mount the always-on gate entry alongside +// bili-native — without it the preset inject rows pend forever whenever +// bili-native does not run. +const GATE_INSERT = `- insert:\n - id: bili-native\n name: billion-context\n - id: bili-compaction-gate\n name: billion-context/dsh-compaction-gate\n`; test("#3354 disableBasicCompaction: marks both compaction rows at any depth", () => { const rows = [ @@ -99,30 +103,37 @@ test("#3354 registerCompactionDisable: transform honors the entry predicate and type Mw = (raw: unknown, next: () => unknown) => unknown; let mw: Mw | undefined; let options: unknown; - registerCompactionDisable({ - on: (_event, listener, opts) => { mw = listener as Mw; options = opts; }, - reflect: {}, - }); - assert.equal(typeof mw, "function"); - assert.deepEqual(options, { global: true }); - const plugins = [ - { name: "@deepseek-ai/dsh-compaction-basic", config: { auto: true } }, - { name: "@deepseek-ai/dsh-command-compact" }, - { name: "@deepseek-ai/dsh-tool-result-pruner" }, - ]; - const cfg: Record = { plugins, isolate: { compaction: true } }; - const self = { entry: { options: { name: "@deepseek-ai/dsh-agent-preset" } } }; - const out = mw?.call(self, null, () => cfg) as { plugins?: Array>; isolate?: Record }; - assert.deepEqual(out.isolate, { compaction: true }); - assert.equal(out.plugins?.[0]?.disabled, true); - assert.equal(out.plugins?.[1]?.disabled, true); - assert.equal(out.plugins?.[2]?.disabled, undefined); - // a different entry (or a host that passes none) must not be transformed - const other: Record = { plugins }; - assert.equal(mw?.call({ entry: { options: { name: "other-entry" } } }, null, () => other), other); - assert.equal(mw?.call(undefined, null, () => other), other); - // next() returning nothing → verbatim passthrough - assert.equal(mw?.call(self, null, () => undefined), undefined); + // #3662: the transform acts only while bili-native declared the lane owned. + _resetDshCompactionVerdictForTest(); + declareDshCompactionActive(); + try { + registerCompactionDisable({ + on: (_event, listener, opts) => { mw = listener as Mw; options = opts; }, + reflect: {}, + }); + assert.equal(typeof mw, "function"); + assert.deepEqual(options, { global: true }); + const plugins = [ + { name: "@deepseek-ai/dsh-compaction-basic", config: { auto: true } }, + { name: "@deepseek-ai/dsh-command-compact" }, + { name: "@deepseek-ai/dsh-tool-result-pruner" }, + ]; + const cfg: Record = { plugins, isolate: { compaction: true } }; + const self = { entry: { options: { name: "@deepseek-ai/dsh-agent-preset" } } }; + const out = mw?.call(self, null, () => cfg) as { plugins?: Array>; isolate?: Record }; + assert.deepEqual(out.isolate, { compaction: true }); + assert.equal(out.plugins?.[0]?.disabled, true); + assert.equal(out.plugins?.[1]?.disabled, true); + assert.equal(out.plugins?.[2]?.disabled, undefined); + // a different entry (or a host that passes none) must not be transformed + const other: Record = { plugins }; + assert.equal(mw?.call({ entry: { options: { name: "other-entry" } } }, null, () => other), other); + assert.equal(mw?.call(undefined, null, () => other), other); + // next() returning nothing → verbatim passthrough + assert.equal(mw?.call(self, null, () => undefined), undefined); + } finally { + _resetDshCompactionVerdictForTest(); + } }); test("#3354 patch carriers agree: root bundle yml and launcher overlay carry the identical preset gate rows", () => { @@ -133,6 +144,7 @@ test("#3354 patch carriers agree: root bundle yml and launcher overlay carry the assert.ok(bundle.includes(row), `bundle yml must carry the ${id} gate row`); } assert.ok(bundle.includes(PRESET_ROWS), "bundle yml must carry the gate rows contiguously"); + assert.ok(bundle.includes(GATE_INSERT), "bundle yml must mount the always-on gate entry (#3662)"); const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-dsh-cd-patch-")); try { @@ -140,6 +152,7 @@ test("#3354 patch carriers agree: root bundle yml and launcher overlay carry the assert.ok(file, "overlay patch must be written"); const overlay = fs.readFileSync(file!, "utf8").replaceAll("\r\n", "\n"); assert.ok(overlay.includes(PRESET_ROWS), "launcher overlay must carry the same gate rows"); + assert.ok(overlay.includes(GATE_INSERT), "launcher overlay must mount the same gate entry (#3662)"); // the overlay still stands down the host plane and keeps the #2605 retries assert.ok(overlay.includes("- id: compaction-basic\n config:\n auto: false\n")); assert.match(overlay, /retryableCodes: \[EMPTY_RESPONSE, RATE_LIMIT, SERVER, TIMEOUT, TRANSPORT, MALFORMED_RESPONSE\]/); diff --git a/tests/issue3662-dsh-gate-fallback.test.ts b/tests/issue3662-dsh-gate-fallback.test.ts new file mode 100644 index 0000000000..d4667f544b --- /dev/null +++ b/tests/issue3662-dsh-gate-fallback.test.ts @@ -0,0 +1,154 @@ +// #3662: disabling or kill-switching bili-native used to remove the ONLY +// provider of biliBasicCompactionPolicy while the bundle patch kept gating all +// four web-profile presets on it — dsh then booted with every preset pending +// forever and session creation bricked (new + resume + preset list). The gate +// now lives in its own always-on entry; these tests pin both trigger paths +// (entry disabled / env kill-switch ⇒ absent verdict) and that the fallback is +// STOCK dsh compaction, not a third state. +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { BILI_COMPACTION_DISABLE_SERVICE, declareDshCompactionActive, isDshCompactionActive, _resetDshCompactionVerdictForTest } from "../src/agent/dsh-compaction-disable.ts"; +import * as gate from "../src/agent/dsh-compaction-gate.ts"; +import { writeDshAcpPatch } from "../src/launcher.ts"; + +const TESTS_DIR = path.dirname(fileURLToPath(import.meta.url)); +const GATE_INSERT = `- insert:\n - id: bili-native\n name: billion-context\n - id: bili-compaction-gate\n name: billion-context/dsh-compaction-gate\n`; + +type GateHost = { + on?: (event: string, listener: (raw: unknown, next: () => unknown) => unknown, options?: { global?: boolean }) => void; + reflect?: { provide?: (name: string, value: unknown) => void } | undefined; +}; +function mockGateHost() { + const order: string[] = []; + const provided: Array<{ name: string; value: unknown }> = []; + let onOptions: { global?: boolean } | undefined; + let mw: ((raw: unknown, next: () => unknown) => unknown) | undefined; + const host: GateHost = { + on: (event, listener, options) => { + order.push(`on:${event}`); + if (event === "internal/config") { + onOptions = options; + mw = listener; + } + }, + reflect: { provide: (name, value) => { order.push(`provide:${name}`); provided.push({ name, value }); } }, + }; + return { + host, + order, + provided, + middleware: () => mw, + globalFlag: () => onOptions?.global === true, + }; +} +const PRESET_SELF = { entry: { options: { name: "@deepseek-ai/dsh-agent-preset" } } }; +function presetPlugins(): Array> { + return [ + { name: "@deepseek-ai/dsh-compaction-basic", config: { auto: true } }, + { name: "@deepseek-ai/dsh-command-compact" }, + { name: "@deepseek-ai/dsh-other" }, + ]; +} + +test("#3662: the gate entry exposes its own minimal surface", () => { + assert.equal(gate.name, "bili-compaction-gate"); + // no inject of its own: it must activate whenever the patch layer mounts it, + // independently of bili-native's state + assert.deepEqual(gate.inject, []); + assert.equal(typeof gate.apply, "function"); +}); + +test("#3662: verdict channel semantics (absent ⇒ stock)", () => { + try { + _resetDshCompactionVerdictForTest(); + assert.equal(isDshCompactionActive(), false, "absent declaration means bili-native never ran"); + declareDshCompactionActive(); + assert.equal(isDshCompactionActive(), true); + } finally { + _resetDshCompactionVerdictForTest(); + } +}); + +test("#3662: bili-native absent (disabled / kill-switched) — service still provided, presets boot STOCK", () => { + try { + _resetDshCompactionVerdictForTest(); + assert.ok(!isDshCompactionActive()); + const m = mockGateHost(); + gate.apply(m.host); + // the latch stays satisfiable even though bili-native never ran + assert.deepEqual(m.provided.map((p) => p.name), [BILI_COMPACTION_DISABLE_SERVICE]); + // transform registered BEFORE the service publishes (the #3354 ordering guarantee survives the split) + const iOn = m.order.indexOf("on:internal/config"); + const iProvide = m.order.indexOf(`provide:${BILI_COMPACTION_DISABLE_SERVICE}`); + assert.ok(iOn >= 0, "internal/config middleware must be registered"); + assert.ok(iProvide > iOn, "gate service must publish after the middleware registers"); + assert.ok(m.globalFlag(), "middleware must be global"); + // and without a verdict it leaves every row stock — this is what keeps + // the four presets resolvable instead of pending forever + const raw = m.middleware(); + assert.equal(typeof raw, "function"); + const mw = raw as (raw: unknown, next: () => unknown) => unknown; + const plugins = presetPlugins(); + const cfg: Record = { plugins, x: 1 }; + const out = mw.call(PRESET_SELF, null, () => cfg) as Record; + assert.equal(out, cfg, "absent verdict must pass the resolved config through verbatim"); + for (const row of plugins) assert.equal(row.disabled, undefined); + } finally { + _resetDshCompactionVerdictForTest(); + } +}); + +test("#3662: normal boot (verdict active) — the gate entry disables the compaction rows", () => { + try { + _resetDshCompactionVerdictForTest(); + declareDshCompactionActive(); + const m = mockGateHost(); + gate.apply(m.host); + assert.deepEqual(m.provided.map((p) => p.name), [BILI_COMPACTION_DISABLE_SERVICE]); + const raw = m.middleware(); + assert.equal(typeof raw, "function"); + const mw = raw as (raw: unknown, next: () => unknown) => unknown; + const plugins = presetPlugins(); + const cfg: Record = { plugins, x: 1 }; + const out = mw.call(PRESET_SELF, null, () => cfg) as { plugins?: Array>; x?: number }; + assert.equal(out.x, 1); + assert.deepEqual(out.plugins?.[0]?.config, { auto: true }); + assert.equal(out.plugins?.[0]?.disabled, true); + assert.equal(out.plugins?.[1]?.disabled, true); + assert.equal(out.plugins?.[2]?.disabled, undefined); + // non-preset entries pass through verbatim even when active + const otherCfg: Record = { plugins }; + assert.equal(mw.call({ entry: { options: { name: "something-else" } } }, null, () => otherCfg), otherCfg); + } finally { + _resetDshCompactionVerdictForTest(); + } +}); + +test("#3662: both patch carriers mount the gate entry alongside bili-native", () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), "bili-3662-carrier-")); + try { + const bundle = fs.readFileSync(path.join(TESTS_DIR, "..", "dsh.bundle.patch.yml"), "utf8").replaceAll("\r\n", "\n"); + assert.ok(bundle.includes(GATE_INSERT), "bundle patch must insert the always-on gate entry after bili-native"); + for (const id of ["preset-standard", "preset-ptc", "preset-minimal", "preset-cordis"]) { + assert.ok(bundle.includes(`- id: ${id}\n inject: [${BILI_COMPACTION_DISABLE_SERVICE}]\n`)); + } + // launcher overlay, bare lane (shim resolves the subpath export) + const file = writeDshAcpPatch(home, "billion-context"); + assert.ok(file, "writeDshAcpPatch must produce the overlay file"); + const overlay = fs.readFileSync(file, "utf8").replaceAll("\r\n", "\n"); + assert.ok(overlay.includes(GATE_INSERT)); + // launcher overlay, URL lane (no shim): the gate rides the same dist root + const file2 = writeDshAcpPatch(home, "file:///does/not/matter/agent/dsh-native.js"); + assert.ok(file2); + const overlay2 = fs.readFileSync(file2, "utf8").replaceAll("\r\n", "\n"); + assert.match(overlay2, /^ {4}- id: bili-compaction-gate\n {6}name: file:\/\/.+dsh-compaction-gate\.js$/m); + assert.ok(overlay2.includes(`- id: preset-standard\n inject: [${BILI_COMPACTION_DISABLE_SERVICE}]\n`)); + } finally { + fs.rmSync(home, { recursive: true, force: true }); + fs.rmSync(`${home}-bili`, { recursive: true, force: true }); + } +}); diff --git a/tests/launcher.test.ts b/tests/launcher.test.ts index 4646a91b2d..e57df05acf 100644 --- a/tests/launcher.test.ts +++ b/tests/launcher.test.ts @@ -4027,6 +4027,8 @@ test("writeDshAcpPatch: writes insert overlay with file:// plugin URL into { const root = selfPackageRoot(); - if (!fs.existsSync(path.join(root, "dist", "agent", "dsh-native.js")) || !fs.existsSync(path.join(root, "dist", "agent", "dsh-native-client.js"))) { + if (!fs.existsSync(path.join(root, "dist", "agent", "dsh-native.js")) || !fs.existsSync(path.join(root, "dist", "agent", "dsh-native-client.js")) || !fs.existsSync(path.join(root, "dist", "agent", "dsh-compaction-gate.js"))) { t.skip("needs a built dist (npm run build first)"); return; } @@ -4144,6 +4161,8 @@ test("writeDshClientShim: stamps the real bili version into the shim package.jso const shimPkg = JSON.parse(fs.readFileSync(path.join(home, "node_modules", "billion-context", "package.json"), "utf8")); const repoPkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); assert.equal(shimPkg.version, repoPkg.version); + // #3662: the real-dist shim carries the gate subpath export for the bare lane + assert.equal(shimPkg.exports["./dsh-compaction-gate"], "./gate.js"); } finally { rmrf(dir); } diff --git a/tsup.config.ts b/tsup.config.ts index 3d1d757a4c..693fbb9dd1 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/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/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/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"], format: ["esm"], target: "node20", platform: "node", From 69cf20039ca7a0b1d93610d4a016b3ebfde26b20 Mon Sep 17 00:00:00 2001 From: ranxianglei Date: Wed, 21 Oct 2026 22:20:11 +0800 Subject: [PATCH 2/2] fix: cover custom presets structurally in the compaction overlay + surface real coverage (#4147/#3962/#4002) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #4147: the #3354 load-time overlay matched the factory @deepseek-ai/dsh-agent-preset entry by name, leaving custom and profile-local presets' nested compaction-basic/command-compact rows ARMED — a landed dsh checkpoint then destroyed the compression substrate (#4147 consequence A). The transform now matches STRUCTURALLY: any entry whose resolved config.plugins nests a compaction row gets those rows disabled; entries without them keep their resolved config object identity untouched. #3962: every rewrite is recorded on the shared globalThis telemetry channel (covered entries + row counts + factory flag) and the durable [dsh-client] boot notes append the actual coverage, so bundle-patch gate rows missing a renamed roster are visible without the host loader log. #4002: CLIENTS.md en+zh state that preset sessions have no /compact menu by design (bili owns compression; no re-enable switch, #3651). Rebased onto current master (594 commits) — resolves the dsh-native/issue3354/tsup conflicts by union. --- CLIENTS.md | 15 +- CLIENTS.zh-CN.md | 2 +- scripts/check-unused-exports.mjs | 5 + src/agent/dsh-compaction-disable.ts | 79 +++++++++- src/agent/dsh-native.ts | 22 ++- .../issue3354-dsh-compaction-disable.test.ts | 13 +- tests/issue3662-dsh-gate-fallback.test.ts | 9 +- .../issue4147-dsh-overlay-structural.test.ts | 136 ++++++++++++++++++ 8 files changed, 269 insertions(+), 12 deletions(-) create mode 100644 tests/issue4147-dsh-overlay-structural.test.ts diff --git a/CLIENTS.md b/CLIENTS.md index 34e031c453..21fe8ae71f 100644 --- a/CLIENTS.md +++ b/CLIENTS.md @@ -109,7 +109,20 @@ Two lanes, same plugin (#941): each Web preset wait for that overlay's service before it can register. Native auto-compaction is OFF in these profiles too (and `/compact` is - unavailable there); ACP compression is unaffected. The overlay rides an + unavailable there — that is EXPECTED, not a bug (#4002): bili owns + compression on the lane, so the preset's compact command and its + auto-compaction are both stood down deliberately; there is no + re-enable switch by design (#3651/#3666), see CONFIGURATION.md); + ACP compression is unaffected. Since #4147 the overlay matches + STRUCTURALLY — any entry whose resolved `config.plugins` nests + `compaction-basic`/`command-compact` rows gets them disabled, custom + and profile-local presets exactly like the factory ones (the four + gate-row ids in `dsh.bundle.patch.yml` are ordering insurance for the + factory roster, not the coverage boundary — a profile shipping other + preset ids is covered by the structural walk). The one-time `[dsh-client]` + boot note names the actual entries the overlay rewrote (#3962), so a + patch-row miss on a renamed roster is visible without reading the host + loader log. The overlay rides an INTERNAL dsh hook and is version-sensitive — if you still see a dsh compaction checkpoint land on a newer/older dsh build, fall back to the #2474 recipe: a profile-level patch (your profile's `cordis.patch.yml`, diff --git a/CLIENTS.zh-CN.md b/CLIENTS.zh-CN.md index e477a54855..ebd59e72ba 100644 --- a/CLIENTS.zh-CN.md +++ b/CLIENTS.zh-CN.md @@ -14,7 +14,7 @@ - **桌面应用(Electron 宿主):** 同一插件也运行在 deepseek-harness **desktop** 应用内(经其应用内插件管理器安装)。此时 bootstrap 在应用进程内拉起代理:该进程的 `process.execPath` 是 Electron 二进制而非 Node,GUI 的 PATH 又不含常规安装目录 —— `resolveNodeRuntime`(#819/#1429)先探测众所周知的安装位置(`/opt/homebrew/bin`、`/usr/local/bin`、Volta 等),再回退到以纯 Node 方式运行应用自身二进制(`ELECTRON_RUN_AS_NODE=1`,强制注入子进程 env),于是无需 PATH 里有独立 Node 也能零配置压缩;设 `BILLION_CONTEXT_NODE` 可强制指定某个 Node(优先于两者)。#1429 之前该路径在 spawn 前抛错,所有会话静默降级为直连(不压缩),只能从 bili.log 里发现。 - **自动更新保持各 profile 同步:** 刷新有两个触发器 —— 全局自更新完成后,以及**profile 自己的代理**在周期检查里发现注册表有新版本时(全局 bili 从不运行也一样刷新,#1196 —— 插件市场安装的用户往往根本没有全局安装)。两种触发器都扫描 `~/.dsh/profiles/*/package.json`,把注册表钉住的 `billion-context` 依赖刷新到目标版本(全局触发器刷到新全局版本,自触发刷到注册表最新),统一经 dsh 自己的 `plugin add` 通道,绝不在位覆盖 —— 加载的插件与代理从此不再漂移(#953);钉在本地源的 profile 不动。刷新是尽力而为,失败下个周期重试,绝不会让代理或更新本身失败。 - **已报告:Profile 安装下部分传输零代理流量(#1158,调查中):** dsh `llm-pi-ai` 层的部分传输服务会话**从未有任何模型请求到达代理**(日志无 `processTurn`,调用 bili 工具返回 404 "no model request has arrived"),而同宿主的其他 provider 正常。根因仍在用运行时证据定性 —— 候选:传输层 fetch 形态(SDK 注入 fetch / 非全局 dispatcher)或宿主侧归属缺口导致流量未被 takeover gate 认领。检测:此类情况会打一次性 `[plugin] NO MODEL REQUESTS seen for conversation …` 告警,dsh 插件还会把归属 gate 放行的每个端点各记一条日志(每进程一次)。期间可靠规避:改用 `bili dsh` 启动 —— 启动器的 settings overlay 会把那些 provider 的 `baseURL` 重写为 `/bili/` URL,无论传输层使用哪种 fetch、归属状态如何,流量都必然过代理。 -- **Web profile 压缩(#1772,#3354 解决):** 当 profile 的 bundles 含 `@deepseek-ai/dsh-web-app` 时,真正运行的 `compaction-basic` 实例位于 agent preset(`preset-standard.config.plugins`)内部 —— dsh 的 patch 引擎只按 id 索引顶层条目与真 group(`group: true` 且 config 为数组)的子项,preset 内的嵌套行任何 patch 层都无法**按 id 直寻**。于是 bundle 里的 `auto: false` 落在 web-app 已禁用的宿主平面行上、什么都没改。#3354 起 bili 在**加载期**补上这一环:一个**常驻**的 bundle 条目 `bili-compaction-gate`(与 `bili-native` 并列的独立 cordis 条目,由同一组 patch 层挂载,因此 `bili-native` 被禁用或 kill-switch 时它仍然存活,#3662)注册一个 cordis `internal/config` overlay(移植自 deshark42/dsh-compaction-basic-disable,MIT),在 bili 持有该泳道期间把 preset 里的 `compaction-basic` 与 `command-compact` 行标记为 `disabled: true`;bundle patch 里的 preset 门控行让每个 Web preset 在注册前等待该 overlay 的服务。这些 profile 里原生自动压缩同样关闭(且 `/compact` 在那里不可用);ACP 压缩不受影响。overlay 依赖 dsh 的内部钩子、对版本敏感 —— 若在新/旧 dsh 构建上仍见到 dsh 压缩 checkpoint 落地,回退到 #2474 配方:profile 层 patch(你 profile 自己的 `cordis.patch.yml`,在所有 bundle 之后生效)用同 id + **完整快照** `config` 整体覆盖 preset-standard —— 从 `dsh --profile --dump-config` 抄下完整的 preset config,在其 `compaction-basic` 行下加 `config.auto: false`,把结果追加进 `cordis.patch.yml`。Config 替换是**整体语义**(片段会静默丢掉一切未重述的键 —— 不只是其他插件,连 preset 自己的 `id`/`order` 身份也会丢,可能使 roster 无法识别该 preset);`- insert:` 同 id 则是在末尾追加一条死行而非合并。dsh 升级 preset 后快照冻结 roster、需重抄一次。此类 profile 启动时插件打一条一次性 `[dsh-client]` 日志,说明两条路径。 +- **Web profile 压缩(#1772,#3354 解决):** 当 profile 的 bundles 含 `@deepseek-ai/dsh-web-app` 时,真正运行的 `compaction-basic` 实例位于 agent preset(`preset-standard.config.plugins`)内部 —— dsh 的 patch 引擎只按 id 索引顶层条目与真 group(`group: true` 且 config 为数组)的子项,preset 内的嵌套行任何 patch 层都无法**按 id 直寻**。于是 bundle 里的 `auto: false` 落在 web-app 已禁用的宿主平面行上、什么都没改。#3354 起 bili 在**加载期**补上这一环:一个**常驻**的 bundle 条目 `bili-compaction-gate`(与 `bili-native` 并列的独立 cordis 条目,由同一组 patch 层挂载,因此 `bili-native` 被禁用或 kill-switch 时它仍然存活,#3662)注册一个 cordis `internal/config` overlay(移植自 deshark42/dsh-compaction-basic-disable,MIT),在 bili 持有该泳道期间把 preset 里的 `compaction-basic` 与 `command-compact` 行标记为 `disabled: true`;#4147 起该匹配是**结构化**的 —— 任何 entry 的 `config.plugins` 里嵌套了这两个包的行都会被禁用,自定义/本地 preset 与官方 preset 一视同仁(`dsh.bundle.patch.yml` 里的四个门控 id 只是对官方 roster 的顺序保险,不是覆盖边界);bundle patch 里的 preset 门控行让每个 Web preset 在注册前等待该 overlay 的服务。这些 profile 里原生自动压缩同样关闭(且 `/compact` 在那里不可用 —— 这是**预期行为而非 bug**(#4002):该泳道的压缩由 bili 接管,preset 的 compact 命令与自动压缩被有意一并撤下;按设计**没有**重新打开的开关(#3651/#3666),见 CONFIGURATION.md);ACP 压缩不受影响。启动的一次性 `[dsh-client]` 日志会列出 overlay 实际改写过的 entry(#3962),patch 行落空(如 roster 改名)无需翻宿主 loader 日志即可见。overlay 依赖 dsh 的内部钩子、对版本敏感 —— 若在新/旧 dsh 构建上仍见到 dsh 压缩 checkpoint 落地,回退到 #2474 配方:profile 层 patch(你 profile 自己的 `cordis.patch.yml`,在所有 bundle 之后生效)用同 id + **完整快照** `config` 整体覆盖 preset-standard —— 从 `dsh --profile --dump-config` 抄下完整的 preset config,在其 `compaction-basic` 行下加 `config.auto: false`,把结果追加进 `cordis.patch.yml`。Config 替换是**整体语义**(片段会静默丢掉一切未重述的键 —— 不只是其他插件,连 preset 自己的 `id`/`order` 身份也会丢,可能使 roster 无法识别该 preset);`- insert:` 同 id 则是在末尾追加一条死行而非合并。dsh 升级 preset 后快照冻结 roster、需重抄一次。此类 profile 启动时插件打一条一次性 `[dsh-client]` 日志,说明两条路径。 - **禁用与移除插件的区别(#3662):** #3662 之前,禁用 `bili-native`(dsh 插件管理器,或任何 patch 层里写 `disabled: true`)会把门控服务的**唯一**提供方一并移除,而 preset 行仍在等它 —— 四个 Web preset 永久 pending,新建/恢复会话全部报 `Unknown agent preset: standard`。现在该服务住在独立的常驻条目 `bili-compaction-gate` 里:禁用或 kill-switch(`BILLION_CONTEXT_PLUGIN=0`)`bili-native` 只是把泳道交还 dsh **原生行为** —— preset 正常注册、原生自动压缩恢复,bili 压缩则完全关闭。请勿禁用 `bili-compaction-gate` 本身 —— 那会重新造成「砖」。要彻底卸载:从 profile 的 `dsh.profile.bundles`(及其依赖)里移除 `billion-context` 后重启 —— 整个 patch 层消失,`compaction-basic` 回到原生默认 `auto: true`。若卡在 #3662 之前的版本且插件已被禁用:升级即自愈(patch 层按 bundles 里列出的包装载,与 `bili-native` 的启用状态无关);手动解砖是在 HOME 层 patch `$DSH_HOME/cordis.patch.yml`(`DSH_HOME` 未设时为 `~/.dsh/cordis.patch.yml`)追加四行 `- id: preset-standard` / `preset-ptc` / `preset-minimal` / `preset-cordis`,各配 `inject: null` —— 顶层键为整体替换,清掉 pending 锁。 - **全局副本在加载期抢占 profile 副本(#2891):** dsh 解析 `dsh.profile.bundles` 里的裸包名 `billion-context` 时是 installation-anchor-first —— 先在自己的安装树(全局 npm root)里找,再找 profile 的 `node_modules`。因此只要机器上存在一份全局 `billion-context`,dsh 就加载**全局那份**,profile 里装的被静默忽略 —— 不崩溃、无日志。两者版本不一致时,实际运行的可能与 profile 声明的不同(例如 #1590 之前的全局没有 `dsh.client` web 面,设置页菜单凭空消失)。这一事实默认情况下处处不可见:`bili doctor` 现在会按 profile 逐一标记任何版本不一致的全局/本地对(#2891);用 `dsh --profile --dump-config`(读该 bundle 的 `name:` 行)可核对 dsh 实际加载了哪份。 diff --git a/scripts/check-unused-exports.mjs b/scripts/check-unused-exports.mjs index 083b393768..ea21f73e74 100644 --- a/scripts/check-unused-exports.mjs +++ b/scripts/check-unused-exports.mjs @@ -87,6 +87,11 @@ const WAIVERS = new Map([ // structurally via Awaited>); keep the // export so the wire shape stays named at its definition site. ["src/update.ts", new Set(["LastInstallRecord"])], + // #3962 gate telemetry: the coverage record crosses the gate/dsh-native + // BUNDLE boundary on the globalThis channel — consumers use it + // structurally through dshCompactionGateTelemetry()'s return type; keep + // the export so the channel payload stays named at its definition site. + ["src/agent/dsh-compaction-disable.ts", new Set(["DshCompactionGateTelemetry"])], ]); const findings = []; diff --git a/src/agent/dsh-compaction-disable.ts b/src/agent/dsh-compaction-disable.ts index 53d935341d..4970e3d159 100644 --- a/src/agent/dsh-compaction-disable.ts +++ b/src/agent/dsh-compaction-disable.ts @@ -21,6 +21,17 @@ // creation on exactly that path). The transform honors the process verdict // declared by bili-native's apply(); an absent declaration means bili-native // never ran and every row passes through stock. +// #4147: the transform matches STRUCTURALLY — any entry whose resolved config +// nests compaction-basic/command-compact rows in a plugins tree gets them +// disabled, not just the factory @deepseek-ai/dsh-agent-preset entry. Custom +// presets (preset-general, profile-local rosters, …) run their compaction +// inside their own nested rows no patch layer can address by id (#1772), so +// the row-name match is the only coverage that does not rot when a profile +// ships ids the bundle patch never knew about (#3962). +// #3962: every rewrite is recorded in a process-global telemetry record so +// bili-native can surface which entries the overlay actually covered (the +// bundle-patch gate rows may target ids a profile does not ship — their miss +// is otherwise visible only in the host loader log). /** The two dsh packages whose backends must not instantiate while bili owns the lane. */ const DSH_COMPACTION_BASIC_PACKAGE = "@deepseek-ai/dsh-compaction-basic"; @@ -79,8 +90,65 @@ export function _resetDshCompactionVerdictForTest(): void { delete (globalThis as Record)[DSH_COMPACTION_VERDICT_KEY]; } +// #3962: the gate entry and bili-native are SEPARATE bundles (module state +// cannot cross them), so the rewrite telemetry rides the same globalThis +// channel as the verdict. bili-native reads it when composing its durable +// coverage note; an absent record means the transform has not rewritten +// anything yet in this process. +const DSH_COMPACTION_GATE_TELEMETRY_KEY = "__BILI_DSH_COMPACTION_GATE_TELEMETRY__"; + +export type DshCompactionGateTelemetry = { + /** Entry option names whose resolved config the transform rewrote, with + * the compaction row count disabled per entry (max across resolutions). */ + covered: Array<{ entry: string; rows: number }>; + /** True once at least one covered entry is the factory agent-preset + * package (the only entry the pre-#4147 name filter ever reached). */ + sawFactoryPreset: boolean; +}; + +function noteGateCoverage(entryName: string, rows: number, isFactory: boolean): void { + const store = globalThis as Record; + const current = store[DSH_COMPACTION_GATE_TELEMETRY_KEY] as DshCompactionGateTelemetry | undefined; + const telemetry: DshCompactionGateTelemetry = current ?? { covered: [], sawFactoryPreset: false }; + const existing = telemetry.covered.find((c) => c.entry === entryName); + if (existing === undefined) { + telemetry.covered = [...telemetry.covered, { entry: entryName, rows }]; + } else if (rows > existing.rows) { + existing.rows = rows; + } + if (isFactory) telemetry.sawFactoryPreset = true; + store[DSH_COMPACTION_GATE_TELEMETRY_KEY] = telemetry; +} + +/** Coverage record of the #3354 load-time overlay in this process (null = + * the transform has not rewritten any entry yet). */ +export function dshCompactionGateTelemetry(): DshCompactionGateTelemetry | null { + const record = (globalThis as Record)[DSH_COMPACTION_GATE_TELEMETRY_KEY]; + return record === undefined ? null : record as DshCompactionGateTelemetry; +} + +/** Test hook: forget any recorded coverage. */ +export function _resetDshCompactionGateTelemetryForTest(): void { + delete (globalThis as Record)[DSH_COMPACTION_GATE_TELEMETRY_KEY]; +} + type PresetRow = { name?: unknown; group?: unknown; config?: unknown }; +/** Count compaction-basic/command-compact rows the disable walk would mark + * (recursing through group rows with the SAME shape gate as + * disableBasicCompaction, so telemetry counts never drift from what the + * rewrite actually did). Zero = nothing to rewrite here. */ +function countCompactionRows(rows: readonly unknown[]): number { + let n = 0; + for (const row of rows) { + if (row === null || typeof row !== "object") continue; + const r = row as PresetRow; + if (r.name === DSH_COMPACTION_BASIC_PACKAGE || r.name === DSH_COMMAND_COMPACT_PACKAGE) n += 1; + else if (r.group && Array.isArray(r.config)) n += countCompactionRows(r.config); + } + return n; +} + /** Mark every compaction row of a preset plugins tree disabled. Pure: returns * detached copies and never mutates the input rows (the resolved config may * be shared with other consumers). */ @@ -120,9 +188,18 @@ export function registerCompactionDisable(ctx: CompactionDisableHost): void { // #3662: honor the process verdict — without an active declaration // from bili-native every row passes through stock. if (!isDshCompactionActive()) return resolved; - if (this?.entry?.options?.name !== DSH_AGENT_PRESET_PACKAGE) return resolved; + // #4147: match STRUCTURALLY, not by entry name — custom presets run + // their compaction inside nested rows under their own entry, and a + // name filter leaves exactly those armed. Rewrite only when the + // tree actually nests a compaction row, so unrelated entries keep + // 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"; + noteGateCoverage(entryName.slice(0, 120), compactionRows, entryName === DSH_AGENT_PRESET_PACKAGE); return { ...config, plugins: disableBasicCompaction(config.plugins) }; }, { global: true }); } diff --git a/src/agent/dsh-native.ts b/src/agent/dsh-native.ts index bb87081411..fd3845cdb2 100644 --- a/src/agent/dsh-native.ts +++ b/src/agent/dsh-native.ts @@ -62,7 +62,7 @@ import { installNativeFetchIntercept, liveStateSlotEffect, noteRoutedOrigin, obs import { asciiHeaderValue, fetchManifest, fetchProxyVersion, fetchStatus, fetchStatusLatest, forwardTool, reportAttributionHealth, reportRuntimeInfo, waitForProxyVersion, type ManifestTool } from "./shared.js"; import { createForkAdopter, sideShapedBody } from "./fork-adopt.js"; import { clearIncrementalProbe, createPrepareDirectSend, INCREMENTAL_TURN_MARKER_HEADER, INCREMENTAL_TURN_ID_HEADER, newIncrementalTurnId, noteIncrementalRejection, noteIncrementalAck, planIncrementalTurn, probeIncrementalTurns, rememberOriginalBody, sweepStale, type IncrementalWireMessage } from "./incremental-client.js"; -import { declareDshCompactionActive, detectCompactionOverlayGap } from "./dsh-compaction-disable.js"; +import { declareDshCompactionActive, detectCompactionOverlayGap, dshCompactionGateTelemetry } from "./dsh-compaction-disable.js"; import { maskUrlForDiagnostics } from "../log-mask.js"; import { conversationRecallStats, learnConversation, recallBoundaryOfMessages, recallConversation, recallHistoryFingerprints, recallLaneHasEntries, recallLaneKey } from "./conversation-recall.js"; export { sideShapedBody } from "./fork-adopt.js"; @@ -274,6 +274,22 @@ let nonWebTraceLogged = false; // not repeat per attempt (same discipline as webProfileWarned). let regAdoptLogged = false; +/** #3962: one-line overlay-coverage suffix for the durable profile notes. + * The bundle-patch gate rows target four factory preset ids a profile may not + * ship (their miss is visible only in the host loader log); the #4147 + * structural transform records every entry it actually rewrote on the shared + * globalThis channel, so the note can state real coverage instead of leaving + * the gate rows' fate implied. Best-effort by necessity: preset configs + * resolve lazily, so "so far" is the honest frame. */ +function gateCoverageSuffix(): string { + const t = dshCompactionGateTelemetry(); + if (t === null || t.covered.length === 0) { + return " Overlay coverage so far: no preset entry rewritten in this process (preset configs resolve lazily — zero at this point does not mean zero later)."; + } + const entries = t.covered.map((c) => `${c.entry}\u00d7${c.rows}`).join(", "); + return ` Overlay coverage so far: ${t.covered.length} preset ${t.covered.length === 1 ? "entry" : "entries"} rewritten (${entries}).`; +} + /** #1590/#1809: origin of the proxy as currently reachable — register.base * once bound (attach synchronously, spawn after bootstrap), else the preset * env origin. Shared by the index-inject row and the live /bili/origin route. */ @@ -2357,7 +2373,7 @@ export function apply(ctx: PluginContext): void { if (gap !== null) { persistClientEvent(`profile bundles include @deepseek-ai/dsh-web-app and the load-time compaction-disable overlay (#3354) could not latch on this dsh build (${gap}) — dsh native auto-compaction is likely ARMED here. bili's wire-level refusal (#1729) refuses routed compaction calls but CANNOT stop dsh writing its checkpoint locally, so a landed checkpoint will destroy the compression substrate and surface later as a 'compression conflict' banner. Apply the #2474 full-snapshot override of preset-standard in your profile's cordis.patch.yml now (a partial snippet silently drops everything not restated; see CONFIGURATION.md)`); } else { - persistClientEvent("profile bundles include @deepseek-ai/dsh-web-app — its agent presets run their own compaction-basic in nested rows no patch layer can address by id (#1772/#2360); bili disables those preset rows at load time via a vendored overlay (deshark42/dsh-compaction-basic-disable, MIT, #3354), so dsh native auto-compaction stays OFF in this profile (ACP compression unaffected). If you still see a dsh compaction checkpoint land on a newer/older dsh build — the overlay rides cordis' INTERNAL 'internal/config' hook and is version-sensitive — fall back to the #2474 full-snapshot override of preset-standard in your profile's cordis.patch.yml (a partial snippet silently drops everything not restated; see CONFIGURATION.md)"); + persistClientEvent("profile bundles include @deepseek-ai/dsh-web-app — its agent presets run their own compaction-basic in nested rows no patch layer can address by id (#1772/#2360); bili disables those preset rows at load time via a vendored overlay (deshark42/dsh-compaction-basic-disable, MIT, #3354; since #4147 the match is structural, covering custom presets too), so dsh native auto-compaction stays OFF in this profile (ACP compression unaffected). If you still see a dsh compaction checkpoint land on a newer/older dsh build — the overlay rides cordis' INTERNAL 'internal/config' hook and is version-sensitive — fall back to the #2474 full-snapshot override of preset-standard in your profile's cordis.patch.yml (a partial snippet silently drops everything not restated; see CONFIGURATION.md)." + gateCoverageSuffix()); } } else if (bundles !== undefined && !nonWebTraceLogged) { // #3651: the web-profile note above is the ONLY confirmation that @@ -2367,7 +2383,7 @@ export function apply(ctx: PluginContext): void { // trace so a field log can tell "overlay registered" from "profile // shape unconfirmed". nonWebTraceLogged = true; - persistClientEvent("profile bundles do not include @deepseek-ai/dsh-web-app — the #3354 load-time compaction-disable middleware is registered anyway (it rewrites agent-preset compaction-basic/command-compact rows through cordis' version-sensitive internal 'internal/config' hook), but no web-profile disable note applies here; if dsh native auto-compaction still lands in this profile, apply the #2474 full-snapshot override of preset-standard (CONFIGURATION.md) — and note the #1729 wire guard now refuses such native compaction calls unconditionally (the #2028 allowDshCompaction opt-in was removed in #3651)"); + persistClientEvent("profile bundles do not include @deepseek-ai/dsh-web-app — the #3354 load-time compaction-disable middleware is registered anyway (it rewrites any entry's nested compaction-basic/command-compact rows through cordis' version-sensitive internal 'internal/config' hook, covering custom presets as of #4147), but no web-profile disable note applies here; if dsh native auto-compaction still lands in this profile, apply the #2474 full-snapshot override of preset-standard (CONFIGURATION.md) — and note the #1729 wire guard now refuses such native compaction calls unconditionally (the #2028 allowDshCompaction opt-in was removed in #3651)." + gateCoverageSuffix()); } } diff --git a/tests/issue3354-dsh-compaction-disable.test.ts b/tests/issue3354-dsh-compaction-disable.test.ts index e2a9e0d8ce..0474d9ef2a 100644 --- a/tests/issue3354-dsh-compaction-disable.test.ts +++ b/tests/issue3354-dsh-compaction-disable.test.ts @@ -125,10 +125,15 @@ test("#3354 registerCompactionDisable: transform honors the entry predicate and assert.equal(out.plugins?.[0]?.disabled, true); assert.equal(out.plugins?.[1]?.disabled, true); assert.equal(out.plugins?.[2]?.disabled, undefined); - // a different entry (or a host that passes none) must not be transformed - const other: Record = { plugins }; - assert.equal(mw?.call({ entry: { options: { name: "other-entry" } } }, null, () => other), other); - assert.equal(mw?.call(undefined, null, () => other), other); + // #4147: the match is STRUCTURAL — a non-agent-preset entry nesting + // compaction rows is rewritten too (custom presets), while an entry + // whose plugins carry none keeps its resolved config object identity. + const custom: Record = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + const customOut = mw?.call({ entry: { options: { name: "preset-general" } } }, null, () => custom) as { plugins?: Array> }; + assert.equal(customOut.plugins?.[0]?.disabled, true); + const untouched: Record = { plugins: [{ name: "@deepseek-ai/dsh-other" }] }; + assert.equal(mw?.call({ entry: { options: { name: "other-entry" } } }, null, () => untouched), untouched); + assert.equal(mw?.call(undefined, null, () => untouched), untouched); // next() returning nothing → verbatim passthrough assert.equal(mw?.call(self, null, () => undefined), undefined); } finally { diff --git a/tests/issue3662-dsh-gate-fallback.test.ts b/tests/issue3662-dsh-gate-fallback.test.ts index d4667f544b..dfd5869d12 100644 --- a/tests/issue3662-dsh-gate-fallback.test.ts +++ b/tests/issue3662-dsh-gate-fallback.test.ts @@ -120,9 +120,14 @@ test("#3662: normal boot (verdict active) — the gate entry disables the compac assert.equal(out.plugins?.[0]?.disabled, true); assert.equal(out.plugins?.[1]?.disabled, true); assert.equal(out.plugins?.[2]?.disabled, undefined); - // non-preset entries pass through verbatim even when active - const otherCfg: Record = { plugins }; + // #4147: non-agent-preset entries pass through verbatim ONLY when + // they nest no compaction rows — a custom preset nesting them is + // rewritten (structural match), unrelated config keeps identity. + const otherCfg: Record = { plugins: [{ name: "@deepseek-ai/dsh-other" }] }; assert.equal(mw.call({ entry: { options: { name: "something-else" } } }, null, () => otherCfg), otherCfg); + const customCfg: Record = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + const customOut = mw.call({ entry: { options: { name: "preset-general" } } }, null, () => customCfg) as { plugins?: Array> }; + assert.equal(customOut.plugins?.[0]?.disabled, true); } finally { _resetDshCompactionVerdictForTest(); } diff --git a/tests/issue4147-dsh-overlay-structural.test.ts b/tests/issue4147-dsh-overlay-structural.test.ts new file mode 100644 index 0000000000..6cadef1222 --- /dev/null +++ b/tests/issue4147-dsh-overlay-structural.test.ts @@ -0,0 +1,136 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { + _resetDshCompactionGateTelemetryForTest, + _resetDshCompactionVerdictForTest, + declareDshCompactionActive, + dshCompactionGateTelemetry, + registerCompactionDisable, +} from "../src/agent/dsh-compaction-disable.ts"; + +// #4147: the #3354 load-time overlay matches STRUCTURALLY — any entry whose +// resolved config.plugins nests compaction-basic/command-compact rows gets +// them disabled, custom presets included; the pre-#4147 entry-name filter +// left exactly those armed and a landed dsh checkpoint destroyed the +// compression substrate. #3962: every rewrite is recorded on the shared +// globalThis telemetry channel so the durable boot note can state actual +// coverage (patch-row misses are otherwise loader-log-only). + +type Mw = (raw: unknown, next: () => unknown) => unknown; + +function middleware(): Mw { + let mw: Mw | undefined; + registerCompactionDisable({ + on: (_event, listener) => { mw = listener as Mw; }, + reflect: {}, + }); + assert.equal(typeof mw, "function"); + return mw as Mw; +} + +test("#4147: custom preset entries nesting compaction rows are rewritten (group recursion included)", () => { + try { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + declareDshCompactionActive(); + const mw = middleware(); + // the #4147 reporter's shape: a profile-local preset entry, NOT the + // factory agent-preset package, nesting its own compaction rows + const cfg = { + plugins: [ + { name: "@deepseek-ai/dsh-other" }, + { group: true, config: [{ name: "@deepseek-ai/dsh-compaction-basic", config: { auto: true } }] }, + { name: "@deepseek-ai/dsh-command-compact" }, + ], + }; + const out = mw.call({ entry: { options: { name: "preset-general" } } }, null, () => cfg) as { plugins: Array> }; + assert.equal(out.plugins[0].disabled, undefined, "unrelated sibling row untouched"); + const group = out.plugins[1] as { config: Array> }; + assert.equal(group.config[0].disabled, true, "nested group row disabled"); + assert.deepEqual(group.config[0].config, { auto: true }, "row config preserved verbatim"); + assert.equal(out.plugins[2].disabled, true, "top-level command-compact row disabled"); + const t = dshCompactionGateTelemetry(); + assert.ok(t, "telemetry recorded"); + assert.deepEqual(t!.covered, [{ entry: "preset-general", rows: 2 }]); + assert.equal(t!.sawFactoryPreset, false, "a custom preset is not the factory entry"); + } finally { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + } +}); + +test("#4147 negative: no compaction rows → resolved config object identity kept, no telemetry entry", () => { + try { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + declareDshCompactionActive(); + const mw = middleware(); + const unrelated = { plugins: [{ name: "@deepseek-ai/dsh-tool-result-pruner" }] }; + assert.equal(mw.call({ entry: { options: { name: "preset-shipin" } } }, null, () => unrelated), unrelated); + const noPlugins = { other: 1 }; + assert.equal(mw.call({ entry: { options: { name: "preset-shipin" } } }, null, () => noPlugins), noPlugins); + assert.equal(dshCompactionGateTelemetry(), null, "no rewrite, no coverage record"); + } finally { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + } +}); + +test("#4147/#3662 negative: absent verdict → stock passthrough records nothing", () => { + try { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + const mw = middleware(); + const cfg = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + const out = mw.call({ entry: { options: { name: "preset-general" } } }, null, () => cfg) as { plugins: Array> }; + assert.equal(out, cfg, "verbatim passthrough"); + assert.equal((cfg.plugins as Array>)[0].disabled, undefined); + assert.equal(dshCompactionGateTelemetry(), null, "stock passthrough leaves no coverage record"); + } finally { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + } +}); + +test("#3962: telemetry dedups per entry, keeps the max row count, flags the factory preset, survives reset", () => { + try { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + declareDshCompactionActive(); + const mw = middleware(); + const one = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + mw.call({ entry: { options: { name: "preset-general" } } }, null, () => one); + const two = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }, { name: "@deepseek-ai/dsh-command-compact" }] }; + mw.call({ entry: { options: { name: "preset-general" } } }, null, () => two); + const factory = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + mw.call({ entry: { options: { name: "@deepseek-ai/dsh-agent-preset" } } }, null, () => factory); + const unnamed = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + mw.call(undefined, null, () => unnamed); + const t = dshCompactionGateTelemetry()!; + assert.deepEqual(t.covered.find((c) => c.entry === "preset-general"), { entry: "preset-general", rows: 2 }, "dedup keeps the max count"); + assert.equal(t.covered.some((c) => c.entry === "unnamed-entry"), true, "missing entry name still recorded"); + assert.equal(t.sawFactoryPreset, true); + _resetDshCompactionGateTelemetryForTest(); + assert.equal(dshCompactionGateTelemetry(), null); + } finally { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + } +}); + +test("#3962: long entry names (URLs) are truncated for the durable note", () => { + try { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + declareDshCompactionActive(); + const mw = middleware(); + const longName = "file:///".padEnd(200, "x"); + const cfg = { plugins: [{ name: "@deepseek-ai/dsh-compaction-basic" }] }; + mw.call({ entry: { options: { name: longName } } }, null, () => cfg); + const t = dshCompactionGateTelemetry()!; + assert.equal(t.covered[0].entry.length, 120); + } finally { + _resetDshCompactionVerdictForTest(); + _resetDshCompactionGateTelemetryForTest(); + } +});