dsh-subagent-default-model 2.1.1 → 2.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,114 @@
1
1
  # Changelog
2
2
 
3
+ ## 2.1.5 (2026-10-17)
4
+
5
+ ### 兼容性核查:DSH Desktop 0.2.1-rc.1
6
+
7
+ 当前宿主为 `0.2.1-rc.1`(此前为 `0.2.0-rc.2`)。逐项核查的结论是**插件仍可正常运行**,但独立评审在复核中发现两个**与版本升级无关的既有缺陷**(恢复会话误报、半知路径渲染),已一并修复,见下节。
8
+
9
+ | 检查项 | 结论 |
10
+ | --- | --- |
11
+ | 插件加载与注入 | ✅ 派发子代理实测,注入行内容与实际路由一致(会话 `be5bae6b` / `b7df5721`) |
12
+ | 4 个事件钩子 | ✅ `agent/pre-step`、`agent/request`、`agent/request-error`、`agent/disposed` 全部仍在 |
13
+ | `preStep()` → `buildRequest()` 时序 | ✅ 未变(0.2.1-rc.1 中 `:956` → `:1075`) |
14
+ | `inbox.claim()` 先抽干 | ✅ 未变 |
15
+ | `session.requestContext()` 语义 | ⚠️ 未变 —— 但复核发现它在**恢复会话**下返回上一轮的路由,已修 |
16
+ | peer 区间覆盖 | ✅ 宿主 `evaluatePluginCompatibility()` 返回「无未满足要求」 |
17
+
18
+ 宿主的 `{{provider}}` / `{{model}}` 系统提示词变量仍读 `agent.options`(派发时值,`dsh-agent-loop` 注册处即 `context.agent?.options.provider`),不含 provider 的实时性 —— 这正是本插件注入行仍有价值的原因。
19
+
20
+ ### Fixed(独立评审发现)
21
+
22
+ - **恢复(resume)的子代理会被标上「上一轮」的路由**。`Session.fromRestore` 用上一轮的日志做种子,而 `requestContext()` 折叠的是**整段日志** —— 于是新一轮第 1 步、还没发出任何请求时,折叠结果就已经是旧路由。此时注入等于把一个**比派发种子更旧**的值当成现状。修法:仅当会话被恢复(`header.isSeeded`)**且**本轮尚未结算过请求时,不采信折叠值,保持沉默;本轮请求结算后折叠重新可信。
23
+ - **半知的路径被渲染成 `model=unknown`**。原先判定是「provider 或 model 有一个非空即采用」,于是 `{provider:"workbuddy", model:""}` 会输出 `model=unknown`,而模型可能把它当事实复述。改为**两半都已知才报告**,与服务端(`agent/request` 侧)的判定口径一致。
24
+ - **上一轮补的「直连宿主评估器」用例其实从未执行**。它 `import` 了 `app.asar` 内的路径 —— 普通 Node ESM 无法导入 asar(`ERR_MODULE_NOT_FOUND`,asar 是单个归档文件不是目录),于是走 `return` 分支**被计为 pass**,且是静默的。修法:改为**读取宿主源码文本**,在 `vm` 沙箱里用真实 `semver` 运行宿主的 `unmetRequirements`;找不到宿主时用 `t.skip` **显式跳过**,不再伪装成通过。同时该用例现在会断言「一个只拒绝 `0.2.1-rc.1` 的区间必须被宿主判为不满足」,即它要防的那个回归。
25
+
26
+ ### Tests
27
+
28
+ - **补上 `0.2.1-rc.1` 到「应当通过」的版本清单**。原先该清单从 `0.2.0-rc.2` 直接跳到稳定的 `0.2.1`,**真实在运行的 `0.2.1-rc.1` 从未被断言过**;一个只拒绝 `0.2.1-rc.1` 的区间回归会让护栏保持全绿。
29
+ - **新增直连宿主 `evaluatePluginCompatibility()` 的用例**:不再靠本地模型复述宿主规则,而是直接 `import` 宿主那个函数来断言 `0.2.1-rc.1` / `0.2.0-rc.2` / `0.2.1` / `0.1.7-rc.1` 均被接受。环境无 DSH 时自动跳过,不构成硬依赖。
30
+ - 变异验证:把上界改回 `<0.2.0-0` → 2 项失败;只让 `dsh-llm` 单独偏离区间 → 「every declared peer」用例失败。
31
+
32
+ ### Docs
33
+
34
+ `DEVELOPMENT.md` 补充两条实测结论:
35
+
36
+ 1. **`peerDependenciesMeta` 不参与宿主校验** —— `unmetRequirements()` 只遍历 `peerDependencies`。标了 `optional: true` 的 peer 区间不匹配时**照样挡住整个插件**。
37
+ 2. **校验必须用宿主的调用方式** —— 用 `semver.satisfies` 时漏掉 `{ includePrerelease: true }`,会把 `0.2.1-rc.1` 误判为不满足,从而得出「peer 区间坏了」的错误结论(本次排查即发生过)。
38
+
39
+ ## 2.1.4 (2026-10-02)
40
+
41
+ ### Fixed
42
+
43
+ - **P0:注入的路由滞后一步,导致模型上下文里出现互相矛盾的两行**。2.1.2 修掉「每步重复注入」之后,实测发现注入的**内容**仍可能错:真实日志显示,一个子代理实际在 `ds41` 上运行,却收到一行写着 `glm` 的注入,随后又收到一行 `ds41` —— 模型同时看到两行、彼此矛盾。
44
+
45
+ **根因**:取值优先级里有「派发时种子」这一档。宿主的循环顺序是 `preStep()` → `buildRequest()`,于是**第一步的 preStep 执行时,`request/context` 帧尚未产生**,插件只能回落到 `agent.options` —— 而那是**派发时的意图值**,一旦路由在派发后被切换(故障转移 / 配置变更 / 父会话选择),它就永远不再更新。第一步注入的这个「猜测值」会排队进 inbox,在**第二步**才被领取,此时真实路由早已不同。
46
+
47
+ **修复**:只报告**已知为真**的路由,优先级为
48
+ 1. `session.requestContext()` —— 宿主自己对最新 `request/context` 帧的折叠,文档原文即「the latest resolved route metadata」,也是宿主 `nextFailoverIndex` 读同一处的用法;
49
+ 2. 本插件在 `agent/request` 瀑布里捕获的**结算后**种子(对该次请求权威);
50
+ 3. **不回落**到 `agent.options`。
51
+
52
+ 第 3 条是关键取舍:注入行只是**对现实的陈述**,一个立刻被推翻的猜测比不说更糟。因此路由已知前**保持沉默**,下一步(首次请求提交后)再注入。副作用是单步子代理不再收到该行 —— 这是**刻意的**,因为那时确实无从得知真实路由;把它当作「信息缺失」而非「错误信息」更诚实。
53
+
54
+ - **同步移除死代码 `routeOfAgent()`**:修复后它不再被任何路径调用,留着会误导下一个读者以为 `agent.options` 仍是有效来源。
55
+
56
+ ### Tests
57
+
58
+ - 新增回归用例 **「路由在下一步之前被切换时,必须报告新路由、绝不陈旧」**:把 `agent.options` 故意留在派发种子(`glm`),而会话折叠推进到 `ds41`,断言**恰好一行**且内容为 `ds41`、且**绝不含 `glm`**。变异验证:把优先级改回「种子优先」,该用例连同另 2 项立即失败。
59
+ - 重写首步用例为**「未提交路由时保持沉默」**:断言首步不注入任何猜测行,并在路由已知后的下一注入一次。旧用例断言的是本次刻意反转的行为,故按新契约重写而非删除。
60
+ - **夹具修正(本轮缺陷得以漏过的原因)**:`makeAgent()` 原先把 `session.requestContext()` 固化为一个**常量**,而宿主语义是「折叠最新 `request/context` 的可变值」。夹具不模拟路由变化,注入器读到什么都会被当成「正确」。现改为可变状态,并由 `dispatchRequest()` 在瀑布结算后 `commitRoute()`,与宿主一致。
61
+
62
+ ### Note
63
+
64
+ - 当前版本序列:2.1.2 修「每步重复注入」(1228 步注入 1227 次 → 11 步注入 2 次),2.1.4 修「内容滞后一步」。两者是**独立缺陷**,均已由真实运行验证。
65
+
66
+ ## 2.1.3 (2026-10-02)
67
+
68
+ ### Changed
69
+
70
+ - **认证类失败(密钥无效)现在也触发跨供应商切换,并附带明确的 warn 日志**。此前 `AUTH` 被刻意排除在切换范围外,理由是「不要把密钥配错误当成换一家就好而掩盖真实问题」。该顾虑本身成立,但它有一个代价被忽略了:当 `models` 列表里各家供应商**密钥各自独立**时,只要其中一家的密钥失效,整个子代理就会直接失败,而**健康的其它供应商完全闲置**——实测中确实遇到了这种情况(任务因一家配额/密钥问题终止,而列表里还有可用路由)。
71
+
72
+ 现改为:
73
+ - **触发码分两类**:连接类(`RATE_LIMIT`/`QUOTA`/`SERVER`/`TIMEOUT`/`TRANSPORT`/`EMPTY_RESPONSE`)与**认证类**(`AUTH`、`INVALID_CREDENTIAL`,即宿主对 HTTP 401/403 的映射)。
74
+ - **认证类切换时必打一条 warn**,点名「失败的供应商凭据被拒绝、该供应商 API key 可能无效/过期/无权限,故障转移正在切到 X/Y,请核实该密钥,否则问题会持续复现」。
75
+ - 设计意图:**用可观测性替代抑制**。原先靠「不切换」来暴露密钥问题,现在改为「切换 + 日志」,两者兼得——任务能继续,问题也不会被静默掩盖。
76
+ - **不改变**:池耗尽仍放行真实错误(不做无限重试);每个候选每个 run 最多试一次;非上述类别的错误码(`NO_ADAPTER`、`CONTEXT_WINDOW_EXCEEDED`、`IMAGE_OFFLOAD_REQUIRED` 等)仍不切换——换一家会同样失败,切换只会掩盖真实错误。
77
+
78
+ 测试:`failover.test.mjs` 的触发码用例重写,断言 AUTH / INVALID_CREDENTIAL **会**切换、AUTH 必须产出含 `API key is likely invalid` 且点名失败供应商的 warn、且三类非路由型错误码仍**不**切换。夹具新增 `warnings` 捕获(否则「日志必须存在」这条契约无法断言)。变异验证:把 AUTH 退回排除状态,该用例立即失败。
79
+
80
+ ### Note
81
+
82
+ - 本次改动源于一次真实排障:日志显示某供应商返回 `429 soft_rate`(配额打满,供应商自身建议切换模型)后任务终止。注意**该 429 属于连接类、原本就在切换范围内**,因此上述 AUTH 改动与它无因果关系;配额场景另行调查(见下一条)。
83
+ - 同期确认了一个易混淆现象:宿主 LLM 层有自己的 `llm/retry` 策略,配额类错误会**先被它重试若干次**,之后才交由 `agent/request-error` 瀑布(即本插件的介入点)。因此插件观察到切换请求的时机晚于错误首次发生。这属于宿主分层行为,不是本插件的重试循环。
84
+
85
+ ## 2.1.2 (2026-10-02)
86
+
87
+ ### Fixed
88
+
89
+ - **P0:每个 step 都重复注入一次路由行(实测 387 步注入 479 次)**。用 8 个真实子代理实测时,探针报告「同一行反复出现,且 provider 会在轮次之间变来变去」。核对会话日志(`session.v4.jsonl.zstd`)确认:
90
+
91
+ | 探针 | step 数 | 注入次数 |
92
+ | --- | --- | --- |
93
+ | d43cab8a | 81 | 80 |
94
+ | 62ef8523 | 78 | 77 |
95
+ | 13952b6f | 24 | 23 |
96
+ | 6fb5b5d4 | 20 | 19 |
97
+ | d9474a33 | 84 | 83 |
98
+ | 31bfeacc | 79 | 78 |
99
+ | ceacf07f | 20 | 19 |
100
+
101
+ **根因**:2.1.1 的去重写成「`agent.inbox.nextStep` 里是否已有一条同样的路由行」。但宿主在每个 `preStep()` 的**开头**先调用 `inbox.claim()`,而 `claim()` 会把 `next-step` **整表抽干**(`mutate("next-step", 0, this.nextStep.length, [], false)`)——且这一步发生在 `agent/pre-step` 瀑布**之前**。于是轮到我这个监听器时,待处理列表**必然是空的**,那个判断**结构上恒为 false**,等于没有去重,每步都重新注入。
102
+ **为什么之前的两轮修复都没碰到它**:2.1.0 的问题在「首步读不到缓存」(已修),本问题是「去重依据失效」——两者独立。
103
+ **修复**:去重改为**带外状态**(`injectedRoute` 按 `agent.id` 记录上次注入的文本),不再依赖 inbox 内容。路由未变 ⇒ 不注入;路由变化 ⇒ 先清掉未认领的旧行再写新行。
104
+ **回归护栏**:新增 3 项用例——① 同路由连续 30 步必须只注入 1 次;② 中途切换 provider 时「每条路由各 1 次」而非「每步 1 次」;③ 同路由相邻两步不重复。**测试夹具同步修正**:`makeInbox()` 增加 `claim()` 并让 `dispatchPreStep()` 在瀑布前先抽干 inbox——正是这个夹具缺失让缺陷逃过了 2.1.0/2.1.1 两轮共 142 项测试。变异验证:把去重退回 inbox 方案,这 3 项立即全部失败。
105
+
106
+ - **测试记录方式修正:改为在「注入发生时」记录,而非事后读 inbox**。事后读 `inbox.nextStep` 只能看到当前这一步的那一条,因此「28 条重复」与「正好 1 条」在断言上长得一模一样——这是缺陷能藏住的第二个原因。现由 `recordInjections()` 在 `prepend` 时记录全部历史。
107
+
108
+ ### Changed
109
+
110
+ - 上述修正同时解释了实测中观察到的「provider 在轮次间跳变」现象:稳定路由被反复重新注入时,日志里会呈现为路由在变。
111
+
3
112
  ## 2.1.1 (2026-10-01)
4
113
 
5
114
  ### Fixed
package/README.en.md CHANGED
@@ -24,7 +24,12 @@ Note this decides **which route serves the next subagent**, chosen at **delegati
24
24
  With `failoverEnabled` (on by default), when a subagent hits a **connection-class failure** mid-run, the plugin retries on another route from its own `models` list:
25
25
 
26
26
  - **Provider-agnostic** — candidates come from the whole `models` list, so failover works **across providers**. If `deepseek-official/deepseek-v4-pro` dies, the subagent can fail over to a *different vendor's* model in the list — not merely another model ID from the same vendor.
27
- - **Only genuine connection failures trigger it** — it switches on `RATE_LIMIT`, `QUOTA`, `SERVER`, `TIMEOUT`, `TRANSPORT`, or `EMPTY_RESPONSE`. Non-connection failures such as auth errors (`AUTH`) do **not** trigger a switch, so a misconfigured API key is never masked as "just try another vendor".
27
+ - **Two classes of trigger code** —
28
+ - **Connection-class**: `RATE_LIMIT`, `QUOTA`, `SERVER`, `TIMEOUT`, `TRANSPORT`, `EMPTY_RESPONSE`.
29
+ - **Auth-class**: `AUTH`, `INVALID_CREDENTIAL` (HTTP 401/403 — an invalid, expired, or unauthorised key).
30
+ - Auth-class failures **do** switch: when each provider holds its own credentials, one bad key must not kill the whole delegation while healthy providers sit unused.
31
+ - **But an auth switch always emits a warning** naming the provider whose key was refused. That is deliberate: switching buys resilience, and the **log line** is what keeps the misconfiguration from being silently hidden.
32
+ - Other codes (e.g. `NO_ADAPTER`, `CONTEXT_WINDOW_EXCEEDED`, `IMAGE_OFFLOAD_REQUIRED`) do **not** switch: another provider would fail identically, so switching would only bury the real error.
28
33
  - **Inherited reasoning strength is dropped** — after switching, the new provider/model is not sent the previous route's `reasoningEffort`; it resolves its own default. Otherwise a target that rejects that level can fail every request and burn through all remaining candidates.
29
34
  - **Sticky within a run** — after a switch, later steps of that same subagent stay on the new model instead of flip-flopping every step.
30
35
  - **Exhaustion passes the real error through** — once every candidate in the list has been tried, the real error surfaces; there is no infinite retry.
@@ -153,7 +158,7 @@ Notes:
153
158
 
154
159
  ## Host version requirement
155
160
 
156
- All eight `@deepseek-ai/*` peers are declared as **`>=0.1.7-rc.1 <0.3.0-0`**: the 0.1.7 line and the **entire 0.2.x line** (prereleases and stable releases alike) are supported; 0.3.0 and later are not declared.
161
+ All nine `@deepseek-ai/*` peers are declared as **`>=0.1.7-rc.1 <0.3.0-0`**: the 0.1.7 line and the **entire 0.2.x line** (prereleases and stable releases alike) are supported; 0.3.0 and later are not declared.
157
162
 
158
163
  To see why the range has this shape, look at how DSH **validates** it. For every `@deepseek-ai/dsh` / `dsh-*` peer, `@deepseek-ai/dsh-app-boot` runs:
159
164
 
@@ -231,7 +236,7 @@ CI runs the same suite on `ubuntu-latest`, `windows-latest`, and `macos-latest`,
231
236
  With `failoverEnabled` on (the default), when a subagent's own loop hits a connection-class failure, the plugin automatically switches models inside the `models` list and retries, following `strategy`. See [Capability 2](#capability-2--cross-provider-failover-if-one-provider-is-down-run-on-another-providers-model) above for the full account; the key points:
232
237
 
233
238
  - **Cross-provider** — candidates are the whole `models` list, so it can fail over to a model from another provider, not just another model ID from the same vendor.
234
- - **Connection-class failures only** — the switch triggers only on these error codes: `RATE_LIMIT`, `QUOTA`, `SERVER`, `TIMEOUT`, `TRANSPORT`, `EMPTY_RESPONSE`. Non-connection failures (e.g. `AUTH`) do **not** trigger a switch.
239
+ - **Trigger codes** — connection-class: `RATE_LIMIT`, `QUOTA`, `SERVER`, `TIMEOUT`, `TRANSPORT`, `EMPTY_RESPONSE`; auth-class: `AUTH`, `INVALID_CREDENTIAL` (invalid/expired key — switches, with a warning). Other codes do not switch.
235
240
  - `round-robin`: advance to the next model in the list (the queue).
236
241
  - `random`: pick any model (without checking whether it was used before).
237
242
  - **Needs ≥ 2 models** — with fewer than 2 entries in `models`, the feature is inactive.
package/README.md CHANGED
@@ -24,7 +24,12 @@
24
24
  开启 `failoverEnabled`(默认开启)后,子代理在运行中遇到**连接类失败**时,会自动在本插件的 `models` 列表内换一条路由重试:
25
25
 
26
26
  - **不区分供应商** —— 候选来自整个 `models` 列表,**跨 provider 生效**。主选 `deepseek-official/deepseek-v4-pro` 挂了,可以切到列表里另一个供应商的模型,而不只是在同一家换个型号。
27
- - **只在真正的连接类故障时触发** —— 命中 `RATE_LIMIT`、`QUOTA`、`SERVER`、`TIMEOUT`、`TRANSPORT`、`EMPTY_RESPONSE` 才切换。认证错误(`AUTH`)等非连接类失败**不会**触发,避免把「密钥配错」误当成「换一家就好」而掩盖真实问题。
27
+ - **触发码分两类** ——
28
+ - **连接类**:`RATE_LIMIT`、`QUOTA`、`SERVER`、`TIMEOUT`、`TRANSPORT`、`EMPTY_RESPONSE`。
29
+ - **认证类**:`AUTH`、`INVALID_CREDENTIAL`(HTTP 401/403,密钥无效/过期/无权限)。
30
+ - 认证类**也会切换**:当各家供应商密钥各自独立时,其中一家密钥失效不应该让整个任务死掉、而健康的供应商却在闲置。
31
+ - **但切换时一定会打 warn 日志**,明确指出「该供应商的密钥可能无效」——这是刻意设计:允许切换是为了可用性,而**日志**保证这个配置问题不会被静默掩盖。
32
+ - 其余失败码(如 `NO_ADAPTER`、`CONTEXT_WINDOW_EXCEEDED`、`IMAGE_OFFLOAD_REQUIRED`)**不切换**:换一家也会同样失败,切换只会掩盖真实错误。
28
33
  - **切换时丢弃继承的推理强度** —— 换到新 provider/model 后不沿用旧路由的 `reasoningEffort`,按目标自己的默认档位请求;否则目标模型可能因「不支持该强度」而直接拒绝请求,导致把剩余候选全部烧光。
29
34
  - **同一次运行内粘住** —— 切换后该子代理后续步骤继续跑在新模型上,不会每步来回跳。
30
35
  - **耗尽即放行** —— 列表内全部候选都试过仍失败,就抛出真实错误,不做无限重试。
@@ -153,7 +158,7 @@ npm install dsh-subagent-default-model
153
158
 
154
159
  ## 宿主版本要求
155
160
 
156
- 全部 8 个 `@deepseek-ai/*` peer 声明为 **`>=0.1.7-rc.1 <0.3.0-0`**:支持 0.1.7 线及其后的**整个 0.2.x 线**(prerelease 与正式版都放行),0.3.0 起不再声明支持。
161
+ 全部 9 个 `@deepseek-ai/*` peer 声明为 **`>=0.1.7-rc.1 <0.3.0-0`**:支持 0.1.7 线及其后的**整个 0.2.x 线**(prerelease 与正式版都放行),0.3.0 起不再声明支持。
157
162
 
158
163
  要理解这个区间为什么长这样,得先知道 DSH **怎么校验**它。`@deepseek-ai/dsh-app-boot` 对每个 `@deepseek-ai/dsh` / `dsh-*` peer 执行:
159
164
 
@@ -231,7 +236,7 @@ CI 在 `ubuntu-latest`、`windows-latest`、`macos-latest` 三个平台上同时
231
236
  开启 `failoverEnabled`(默认开启)后,子代理自身的循环遇到连接类失败时,插件会在 `models` 列表内按 `strategy` 自动切换模型并重试。完整说明见上文「[功能二:跨供应商故障转移](#功能二跨供应商故障转移--这条通了那条不通就换另一个供应商的模型)」,要点复述:
232
237
 
233
238
  - **跨供应商** —— 候选是整个 `models` 列表,可以切到另一个 provider 的模型,不限于同一家换型号。
234
- - **连接类失败才切换** —— 命中以下任一错误码才切换:`RATE_LIMIT`、`QUOTA`、`SERVER`、`TIMEOUT`、`TRANSPORT`、`EMPTY_RESPONSE`。认证错误(如 `AUTH`)等非连接类失败**不会**触发切换。
239
+ - **触发码** —— 连接类:`RATE_LIMIT`、`QUOTA`、`SERVER`、`TIMEOUT`、`TRANSPORT`、`EMPTY_RESPONSE`;认证类:`AUTH`、`INVALID_CREDENTIAL`(密钥无效/过期,会切换并打 warn 日志)。其余码不切换。
235
240
  - `round-robin`:按列表顺序切到下一个模型(队列)。
236
241
  - `random`:随机挑一个模型(不判断之前是否用过)。
237
242
  - **需要 ≥ 2 个模型** —— 当 `models` 少于 2 项时本功能不生效。
package/lib/index.js CHANGED
@@ -156,6 +156,35 @@ const WRAPPED = Symbol.for("dsh-subagent-default-model.wrapped");
156
156
  */
157
157
  const FAILOVER_TRIGGER_CODES = ["RATE_LIMIT", "QUOTA", "SERVER", "TIMEOUT", "TRANSPORT", "EMPTY_RESPONSE"];
158
158
 
159
+ /**
160
+ * Auth failures, handled SEPARATELY from the connection codes above.
161
+ *
162
+ * `AUTH` (HTTP 401/403 — a bad, expired, or unauthorised key) is not a
163
+ * connectivity problem, so switching on it is only right when the pool entries
164
+ * hold INDEPENDENT credentials. With per-provider keys — the normal setup — one
165
+ * provider's key going bad must not kill the whole delegation while healthy
166
+ * providers sit unused, which is what excluding AUTH entirely used to do.
167
+ *
168
+ * The reason AUTH was originally excluded still stands, though: silently
169
+ * rerouting around a broken key HIDES a misconfiguration. So an AUTH switch is
170
+ * always accompanied by a loud warning naming the provider whose credentials
171
+ * were refused, and pool exhaustion still passes the real error through.
172
+ * Observability replaces suppression.
173
+ *
174
+ * When several entries share ONE credential (e.g. the same env var), switching
175
+ * cannot help — but it also cannot loop: every candidate is tried at most once
176
+ * per run, and exhaustion surfaces the real error.
177
+ */
178
+ const AUTH_FAILURE_CODES = ["AUTH", "INVALID_CREDENTIAL"];
179
+
180
+ /** Every failure code that may trigger a switch. */
181
+ const FAILOVER_ELIGIBLE_CODES = [...FAILOVER_TRIGGER_CODES, ...AUTH_FAILURE_CODES];
182
+
183
+ /** True when a failure code is an auth-class failure (picks the log wording). */
184
+ function isAuthFailure(code) {
185
+ return AUTH_FAILURE_CODES.includes(code);
186
+ }
187
+
159
188
  /** Resolve one model entry to `{provider, model}`, or undefined. */
160
189
  function resolveEntry(section, entry) {
161
190
  if (typeof entry === "string") {
@@ -288,7 +317,7 @@ function installFailover(ctx, state) {
288
317
  const { agent, turn, step, failure, signal } = payload;
289
318
  if (signal?.aborted) return next();
290
319
  if (!isSubagentAgent(agent)) return next();
291
- if (failure === void 0 || !FAILOVER_TRIGGER_CODES.includes(failure.code)) return next();
320
+ if (failure === void 0 || !FAILOVER_ELIGIBLE_CODES.includes(failure.code)) return next();
292
321
  const current = pending.get(agent.id);
293
322
  // The primary already failed (that triggered the first switch), so the
294
323
  // remaining candidates are the other pool entries: at most
@@ -316,6 +345,18 @@ function installFailover(ctx, state) {
316
345
  view.entries.length,
317
346
  view.strategy
318
347
  );
348
+ // An auth switch is called out explicitly: the point of allowing it is
349
+ // resilience, and the risk it introduces is that a broken credential
350
+ // becomes invisible. This line is what keeps it visible — without it,
351
+ // silently rerouting around a bad key would hide a real misconfiguration.
352
+ if (isAuthFailure(failure.code)) {
353
+ ctx.logger.warn(
354
+ `[dsh-subagent-default-model] the credentials for the failing provider ${payload.provider ?? "(unknown)"} were refused (%s). This is NOT a connection problem: that provider's API key is likely invalid, expired, or unauthorised. Failover is switching the subagent to %s/%s — verify that provider's key, because the failure will keep recurring until it is fixed.`,
355
+ failure.code,
356
+ view.entries[index].provider,
357
+ view.entries[index].model
358
+ );
359
+ }
319
360
  return { kind: "retry" };
320
361
  });
321
362
 
@@ -404,30 +445,78 @@ function isRouteContextMessage(message) {
404
445
  }
405
446
 
406
447
  /**
407
- * Read the route an agent's loop will actually request, at PRE-STEP time.
448
+ * Has this agent built a request yet in the CURRENT run?
408
449
  *
409
- * This is the loop's own resolved route (`agent.options.provider` / `.model`) —
410
- * the exact pair `prepareRequest()` copies into the request it is about to
411
- * build (`dsh-agent-loop`: `const route = { provider: this.options.provider,
412
- * model: this.options.model }`).
450
+ * `session.requestContext()` folds over the session's whole event log, and a
451
+ * RESTORED session (`Session.fromRestore`) starts with the PREVIOUS run's log as
452
+ * its seed. So on step 1 of a resumed subagent the fold already returns the old
453
+ * run's route — before this run has chosen anything. Trusting it would label the
454
+ * new run with the previous run's provider/model: the same "authoritative but
455
+ * wrong" failure as the dispatch-seed bug, only older.
413
456
  *
414
- * WHY NOT `agent/request` ALONE: the loop calls `preStep()` BEFORE
415
- * `buildRequest()` on every iteration, so on the FIRST step no `agent/request`
416
- * has fired yet and a request-driven cache is empty exactly when the first
417
- * (often only) step needs it. That ordering is why an earlier build of this
418
- * feature silently injected nothing for single-step subagents. Reading
419
- * `agent.options` here is earlier and just as authoritative.
457
+ * The plugin's own `agent/request` listener records a route only once a request
458
+ * settles, so a per-agent "has requested" flag separates "this run has chosen"
459
+ * from "history says something".
420
460
  *
421
- * @param {object} agent - the loop agent for this step.
422
- * @returns {{provider: string, model: string}|undefined} the route, when known.
461
+ * @param {object} agent - the loop agent.
462
+ * @param {Map} settled - per-agent settled-seed cache (its key presence is the flag).
463
+ * @returns {boolean} true when the fold can only be describing an earlier run.
423
464
  */
424
- function routeOfAgent(agent) {
425
- const options = agent?.options;
426
- if (options === void 0 || options === null) return void 0;
427
- const provider = typeof options.provider === "string" ? options.provider : "";
428
- const model = typeof options.model === "string" ? options.model : "";
429
- if (provider === "" && model === "") return void 0;
430
- return { provider, model };
465
+ function isStaleFold(agent, settled) {
466
+ // Only a actually-restored session can carry another run's log. A fresh
467
+ // session's fold is always produced by this run, so never second-guess it.
468
+ const seeded = agent?.session?.header?.isSeeded;
469
+ if (seeded !== true) return false;
470
+ return settled.has(agent?.id) === false;
471
+ }
472
+
473
+ /**
474
+ * Resolve the route the agent is ACTUALLY using, or `undefined` when that is
475
+ * not yet knowable.
476
+ *
477
+ * The FIRST step is the hard case. `preStep()` runs BEFORE `buildRequest()`, so
478
+ * on step 1 no `request/context` frame exists and no `agent/request` waterfall
479
+ * has settled. The only value available is `agent.options` — the DISPATCH-TIME
480
+ * seed, which the parent may already have superseded (a switch during dispatch,
481
+ * or a route chosen after this agent was created).
482
+ *
483
+ * Guessing from `agent.options` is what produced the reported contradiction: a
484
+ * subagent whose real route was `ds41` got a step-1 line saying `glm` (the
485
+ * dispatch seed), queued into the inbox, claimed on step 2 — so the model saw
486
+ * `glm` and `ds41` side by side. Since the line is only a report about reality,
487
+ * a guess that is immediately contradicted is worse than saying nothing.
488
+ *
489
+ * Therefore: report only what is KNOWN, and stay silent otherwise. The route
490
+ * becomes knowable one step later (the session fold updates as soon as the
491
+ * first request commits), so the line still lands early in the run.
492
+ *
493
+ * @param {object} agent - the loop agent.
494
+ * @param {Map} settled - per-agent settled-seed cache.
495
+ * @returns {{provider: string, model: string}|undefined} the known route.
496
+ */
497
+ function routeForInjection(agent, settled) {
498
+ // The session's fold of the latest `request/context` — authoritative and
499
+ // current FOR THE RUN THAT PRODUCED IT, and what the host itself treats as
500
+ // "the latest resolved route".
501
+ //
502
+ // BOTH halves must be known: a half-filled fold (`{provider:"workbuddy",
503
+ // model:""}`) used to render as `model=unknown`, which is exactly the
504
+ // "report a guess" failure this function exists to avoid. The request side
505
+ // rejects the same shape, so both ends agree on what a route is.
506
+ const live = agent?.session?.requestContext?.();
507
+ if (live !== void 0 && live !== null) {
508
+ const provider = typeof live.provider === "string" ? live.provider : "";
509
+ const model = typeof live.model === "string" ? live.model : "";
510
+ if (provider !== "" && model !== "" && !isStaleFold(agent, settled)) return { provider, model };
511
+ }
512
+ // A request already built by this plugin's own waterfall: still authoritative
513
+ // for that request, and normally identical to the fold above.
514
+ const captured = settled.get(agent.id);
515
+ if (captured !== void 0) return captured;
516
+ // Nothing has committed yet. Deliberately do NOT fall back to
517
+ // `agent.options`: that is the dispatch seed and is exactly the stale guess
518
+ // this function exists to avoid.
519
+ return void 0;
431
520
  }
432
521
 
433
522
  /**
@@ -440,13 +529,7 @@ function routeOfAgent(agent) {
440
529
  * conversation. This injects one line stating the route the child is ACTUALLY
441
530
  * using.
442
531
  *
443
- * SOURCE OF TRUTH: two sources, in priority order.
444
- * 1. `agent.options` at pre-step time (see `routeOfAgent`) — always available,
445
- * including the very first step.
446
- * 2. The SETTLED seed from the `agent/request` waterfall, once a request has
447
- * been built. It reflects every listener's rewrite (including this
448
- * plugin's own failover swap), so after a mid-run switch the injected line
449
- * follows the new route rather than the one the agent started on.
532
+ * SOURCE OF TRUTH: see `routeForInjection` — the session's own live route first.
450
533
  *
451
534
  * Injected on every step whose route differs from the line already present, so
452
535
  * a failover switch or a route change is reflected immediately; an unchanged
@@ -476,41 +559,56 @@ function installRouteContextInjector(ctx, state) {
476
559
 
477
560
  // Inject on the pre-step, where the message list for the step about to run
478
561
  // is still mutable and the agent's own route is already known.
562
+ //
563
+ // DEDUPE MUST BE OUT-OF-BAND, NOT "is a copy still pending?".
564
+ // The loop calls `inbox.claim()` at the TOP of `preStep()` — BEFORE this
565
+ // waterfall — and `claim()` DRAINS `next-step`
566
+ // (`mutate("next-step", 0, this.nextStep.length, [], false)`). So by the time
567
+ // this listener runs, the pending list is always empty and a "does a route
568
+ // line already exist in the inbox?" test is structurally always false. An
569
+ // earlier build did exactly that and re-injected on EVERY step: a real
570
+ // 29-step subagent ended up with 28 identical route lines, which also made
571
+ // the reported route churn between turns. Track what was last injected for
572
+ // this agent instead.
573
+ const injectedRoute = new Map();
574
+
479
575
  const disposePreStep = ctx.on("agent/pre-step", async ({ agent, messages }, next) => {
480
576
  const decision = await next();
481
577
  if (decision === void 0 || decision === null || decision.kind === "reject") return decision;
482
578
  if (state.getSection()?.injectRouteContext === false) return decision;
483
579
  if (!isSubagentAgent(agent)) return decision;
484
580
 
485
- // Prefer the settled request route (post-failover); fall back to the
486
- // agent's own live route, which is all the first step has.
487
- const route = resolvedRoute.get(agent.id) ?? routeOfAgent(agent);
581
+ // The live session route wins; see `routeForInjection` for why the
582
+ // dispatch-time `agent.options` must NOT be preferred.
583
+ const route = routeForInjection(agent, resolvedRoute);
488
584
  if (route === void 0) return decision;
489
585
  // Defensive: only the loop's live Agent exposes an inbox. A test double
490
586
  // or a future agent shape without one must not break the step.
491
587
  if (agent.inbox === void 0 || !Array.isArray(agent.inbox.nextStep)) return decision;
492
588
 
493
- // Reuse the pending message when the route is unchanged; replace it when
494
- // the route moved (failover / config change). Without the remove step a
495
- // stale line would linger alongside the fresh one.
496
- const pending = agent.inbox.nextStep.filter(isRouteContextMessage);
497
589
  const wanted = routeContextText(route.provider, route.model);
498
- const existing = pending.find((message) => message.content?.[0]?.text === wanted);
499
- for (const message of pending) {
500
- if (message !== existing) agent.inbox.remove(message.id);
590
+ // Same route as last time => the line already placed in this session is
591
+ // still accurate; inject nothing (no duplicate, no churn).
592
+ if (injectedRoute.get(agent.id)?.text === wanted) return decision;
593
+
594
+ // Route moved (failover / config change): drop any not-yet-claimed copy so
595
+ // the stale route does not linger beside the fresh one.
596
+ for (const message of agent.inbox.nextStep.filter(isRouteContextMessage)) {
597
+ agent.inbox.remove(message.id);
501
598
  }
502
- if (existing !== void 0) return decision;
503
599
 
504
600
  const message = createUserMessage({
505
601
  content: [{ type: "text", text: wanted }],
506
602
  source: { kind: ROUTE_CONTEXT_SOURCE, form: ROUTE_CONTEXT_FORM }
507
603
  });
508
604
  agent.inbox.prepend("next-step", message);
605
+ injectedRoute.set(agent.id, { text: wanted });
509
606
  return decision;
510
607
  });
511
608
 
512
609
  const disposeDisposed = ctx.on("agent/disposed", ({ agent }) => {
513
610
  resolvedRoute.delete(agent.id);
611
+ injectedRoute.delete(agent.id);
514
612
  });
515
613
 
516
614
  ctx.effect(() => () => {
@@ -518,6 +616,7 @@ function installRouteContextInjector(ctx, state) {
518
616
  disposePreStep();
519
617
  disposeDisposed();
520
618
  resolvedRoute.clear();
619
+ injectedRoute.clear();
521
620
  }, "dsh-subagent-default-model: route context injector");
522
621
  }
523
622
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-subagent-default-model",
3
- "version": "2.1.1",
3
+ "version": "2.1.5",
4
4
  "description": "为 DeepSeek Harness 子代理配置默认模型:多模型顺序/随机分配、跨供应商连接失败故障转移,并在轨迹/对话视图显示当前供应商与模型,同时以一行真实提示词把当前路由注入子代理上下文。",
5
5
  "keywords": [
6
6
  "deepseek-harness",