dsh-vision-router 3.1.2 → 3.1.4

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/README.md CHANGED
@@ -22,7 +22,7 @@
22
22
  > **Data leaves your machine by default.** When a cloud vision model is used, Vision Router sends the image (or a derived crop), the vision prompt and related request metadata to that provider. A fresh install has an anonymous OVHcloud vision fallback enabled, so "free" and "no key" do **not** mean offline. Do not use the cloud chain for confidential, regulated or classified material. See [Data flow and strict local-only use](#data-flow-and-strict-local-only-use).
23
23
 
24
24
  > [!WARNING]
25
- > **v3.1.2 release candidate notes:** New Vision Router icons in DSH Plugin Manager and the native Settings navigation where available; reviewed Alpha.2/Alpha.3 Cordis compatibility, dependency security, and Host process fixes. Older DSH Settings shells keep their default icon. See [v3.1.2 notes](docs/releases/v3.1.2.md). Check [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) and npm for actual publication.
25
+ > **v3.1.4 stability patch candidate:** Fix cross-plugin script mutation (#793), visual fallback on empty recognition and bounded whole-turn timeouts (#794). Add Desktop bootstrap source-leak regression detection (#795) and canary maintenance (#790); **the specific user-reported 550/503 origins and #792 screenshot root cause are not confirmed**. No settings migration or support-floor change. See [v3.1.4 notes](docs/releases/v3.1.4.md). Verify publication through [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) or npm.
26
26
 
27
27
  ## Start here
28
28
 
@@ -611,7 +611,7 @@ exploration (LLM7.io and OVHcloud anonymous tiers) by
611
611
 
612
612
  ## Release notes and community
613
613
 
614
- Release details: [v3.1.2 release candidate notes](docs/releases/v3.1.2.md). Check GitHub Releases or npm for the published version.
614
+ Release details: [v3.1.3 release candidate notes](docs/releases/v3.1.3.md). Check GitHub Releases or npm for the published version.
615
615
 
616
616
  <p align="center">
617
617
  <sub>Ecosystem:</sub>
package/README.zh.md CHANGED
@@ -22,7 +22,7 @@
22
22
  > **默认配置会让数据出网。** 使用云端视觉模型时,Vision Router 会将图片(或由它裁剪出的局部)、识图提示词及相关请求元数据发送给对应供应商。新安装默认开启 OVHcloud 匿名视觉兜底,因此“免费”和“免 Key”不等于离线。涉密、涉案、内部或其他受限材料请勿使用云端链路。详见[数据流向与严格纯本地配置](#数据流向与严格纯本地配置)。
23
23
 
24
24
  > [!WARNING]
25
- > **v3.1.2 候选版更新说明:** 新增 Vision Router 插件管理图标及新版 DSH 的设置导航图标;纳入 Alpha.2/Alpha.3 Cordis 适配、依赖安全与 Host 进程兼容修复。旧版 DSH 的设置导航保持默认图标。详见[v3.1.2 更新说明](docs/releases/v3.1.2.md)。正式可安装版本以 [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) 或 npm 为准。
25
+ > **v3.1.4 稳定性补丁候选版:** 修复跨插件脚本误改写(#793)、空识图结果的后端回退与整轮识图超时卡住(#794),补充 Desktop 启动源码外露检测(#795)及 CI canary 维护(#790)。**用户所报 550/503 的真实来源及 #792 截图根因尚未确认**。不修改配置格式或 Host/Node 支持下限。详见 [v3.1.4 更新说明](docs/releases/v3.1.4.md)。正式可安装版本以 [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) 或 npm 为准。
26
26
 
27
27
  ## 先用起来
28
28
 
@@ -605,7 +605,7 @@ npx dsh-vision-router doctor --profile web
605
605
 
606
606
  ## 版本公告与社区链接
607
607
 
608
- 版本更新详情:[v3.1.2 候选版更新说明](docs/releases/v3.1.2.md)。正式可安装版本请以 GitHub Releases 或 npm 为准。
608
+ 版本更新详情:[v3.1.3 候选版更新说明](docs/releases/v3.1.3.md)。正式可安装版本请以 GitHub Releases 或 npm 为准。
609
609
 
610
610
  <p align="center">
611
611
  <sub>生态收录:</sub>
@@ -0,0 +1,110 @@
1
+ # DSH 0.2.2-rc.1 exact-source adaptation review
2
+
3
+ Status: RC1 source audit and evidence checklist. The authoritative acceptance
4
+ status is the latest commit's Host jobs at
5
+ https://github.com/ysr666/dsh-vision-router/pull/786; this document alone
6
+ does not establish production compatibility.
7
+
8
+ ## Provenance and source delta
9
+
10
+ - Release tag: dsh-v0.2.2-rc.1; published 2026-11-04T13:07:14Z.
11
+ - Immutable RC1 commit: 66491b05e3f05ad35bcdd4f6cd7ed26041d9e3db.
12
+ - Prior Alpha.3 exact source: 05b1cae8db6e674c5685101494d4eec24652424a.
13
+ - Git diff from Alpha.3 to RC1 changes 387 package.json versions only; no ordinary source file changed. This is a source-content comparison, not a passing runtime test.
14
+ - Cordis Core 4.1.0, Loader 1.1.0, Include 1.1.0 and Node >=24.9 are declared on RC1. Older DVR Node22 host support is preserved.
15
+
16
+ ## Validation plan
17
+
18
+ The fixed RC1 gate validates exact checkout SHA and package identity, cross-platform source/Sharp and peer/security contracts, real Host with Chromium Settings save/reload/readback, cold Vision toggle, mixed attachment and bundle recompose, macOS Desktop renderer, Windows Node24.9/24.21 Desktop, and multi-plugin ordering. Alpha surveillance and earlier Host/Node22 lanes stay separate.
19
+
20
+ ## Confirmed source incompatibility: late dynamic model routing
21
+
22
+ The RC1 Agent Loop reads the selected model *before* prompt/tool assembly and pre-step. At request preparation, RC1 packages/core/agent-loop/src/agent.ts rejects provider/model/effort modifications returned by agent/request (lines 630-639). DVR previously changed provider/model at agent/request when optional dynamic routing was enabled; the RC1 code now uses the earlier Agent model-selection boundary. The same upstream source existed at Alpha.3, meaning the earlier browser gate did not prove this active routing flow. A real Host regression must demonstrate a routed image turn, a following text-only turn, actual selected adapter, and no model-selection or permission drift. The documented modern mechanism, agent.model.select(), must be invoked before step preparation, not merely during agent/pre-step after selection was fixed.
23
+
24
+ Additional runtime scrutiny covers tools.resolve/executable, session-projection async registration, settings persistence, plugin disposal, source authentication and model/attachment decisions. A green generic Settings smoke alone does not close these risks.
25
+
26
+ ## Implementation and required acceptance
27
+
28
+ DVR now uses post-append, pre-preStep Agent inbox notifications and
29
+ running/turn-stopping boundaries to call the official Agent.model.select()
30
+ synchronously before tools.resolve fixes the step model and permissions.
31
+ It reads the true Session inbox projection rather than guessing from the
32
+ newest message. Modern agent/request handlers never mutate provider/model.
33
+ Legacy Hosts without Agent.model.select keep the previous routing path.
34
+
35
+ A text followup restores the user-selected base model only if the current
36
+ selection still matches DVR-owned image routing. Explicit manual changes
37
+ take priority. Absent projection and adapters fail closed. Tool-only mode
38
+ mounts progressive image tools before the tool-admission snapshot.
39
+ Session event is intentionally NOT used for selecting a model: Session.append
40
+ prohibits synchronous reentrant model/selection appends.
41
+
42
+ CI now verifies pinned source event ordering and runs real Desktop requests:
43
+ image to vision-chain, text followup to original provider, visible answers,
44
+ actual network requests and durable model-selection projection. Synthetic
45
+ adversarial tests cover queue, steer, offload, disable, missing adapter,
46
+ unload, and legacy nonintervention.
47
+
48
+ A published compatibility claim requires current-head real Host CI and
49
+ adversarial review, not just these unit-level assertions.
50
+
51
+ ## Real RC1 Desktop evidence from first audit run
52
+
53
+ On Windows Node24.21 with RC1 exact Host, the real Desktop completed the
54
+ image turn with its visible answer (DESKTOP_DYNAMIC_IMAGE_E2E_OK) and the
55
+ model picker showed vision-http/desktop-e2e/desktop-vision. The initial
56
+ Playwright selector then failed because the same answer occurred in three
57
+ places (session title, breadcrumb, assistant paragraph), NOT because the
58
+ runtime request failed. E2E now selects the assistant paragraph and accepts
59
+ either verified chain or direct vision-http source route, and continues to
60
+ require a text followup and accepted model-selection projection evidence.
61
+ This first audit run was not complete E2E acceptance. Subsequent current-head
62
+ results must be evaluated in the linked PR.
63
+
64
+ ## RC1 model-switch compaction: actual failure and scoped workaround
65
+
66
+ A real RC1 Windows Desktop image request passed, but its next text request
67
+ failed with MODEL_SWITCH_COMPACTION_FAILED: the synthetic adapter declared
68
+ contextWindow=32768 and maxTokens=2048, while upstream compaction-basic
69
+ defaults to headroomTokens=65536. The destination lacks a valid budget
70
+ even for a tiny history. This is an upstream documented restriction.
71
+
72
+ For the normal return-to-text E2E use a synthetic adapter whose capacity
73
+ is 131072. This changes no actual user models. Real small-window models
74
+ must configure DSH compaction-basic.modelPolicies, e.g. headroomTokens=4096
75
+ and maxTokens=4096 for a 32768 window, or retain DVR's default tool-only
76
+ routing. Never silently inflate actual model metadata, mutate global Host
77
+ compaction settings or swallow a Host model-switch error.
78
+
79
+ ## Two independent live Desktop routes
80
+
81
+ The Windows Node24.21 and macOS Desktop E2E lanes exercise optional
82
+ whole-turn image routing, visual backend HTTP and next-text restoration.
83
+ Windows Node24.9 additionally runs the default tool-only image flow:
84
+ text Agent must discover and call the vision_describe tool on the very
85
+ first image step, consume a real mock vision response, and render a
86
+ correct answer without changing the session's text model. The two
87
+ modes must not be treated as interchangeable verification.
88
+
89
+ ## Workflow trust and cache policy
90
+
91
+ Static SHA checkout is deliberately duplicated in the fixed RC1 workflow
92
+ and checked against the reviewed JSON pin. All checkouts use
93
+ persist-credentials=false; GitHub job permissions remain contents:read.
94
+ Because CI executes upstream dependencies, the RC1 lane does not restore or
95
+ save any shared Actions build cache, even on main. This removes the only
96
+ potential persistent cache-poisoning path rather than relying on a dynamic
97
+ cache key and workflow_dispatch branch heuristics. Ordinary untrusted PR
98
+ checkout is only executed in the same non-privileged test jobs.
99
+
100
+ ## Durable message attribution during both image execution modes
101
+
102
+ Real RC1 Windows Node24.21 image→text E2E completed both turns but the
103
+ shared harness then incorrectly required a DVR-authored durable message.
104
+ Whole-turn mode routes images directly to the vision adapter and may emit
105
+ zero DVR-authored synthetic messages. The E2E now checks producer-owned V4
106
+ source integrity for any such messages, while retaining the strict
107
+ *nonempty* DVR-source and DVR-message check for default tool-only mode.
108
+ Actual backend calls, rendered answers and accepted model-selection
109
+ projections are mandatory in both modes. No synthetic message is created
110
+ solely to satisfy test attribution.
@@ -0,0 +1,24 @@
1
+ # v3.1.3 — DSH RC1 dynamic visual routing compatibility / DSH RC1 动态视觉路由兼容修复
2
+
3
+ **Candidate release notes.** This document describes source changes proposed for release; publication is complete only after the protected workflow verifies the exact main commit, immutable tag, npm package identity, provenance and GitHub Release artifacts. / **候选版说明:** 本文描述待发布的源码变更;须经受保护工作流核验精确 main 提交、不可变标签、npm 包体一致性、来源证明和 GitHub Release 附件后,才能认定正式发版。
4
+
5
+ ## DSH 0.2.2-rc.1 dynamic routing fix / RC1 动态路由修复
6
+
7
+ - **#786 (fixes #787):** Adapt optional whole-turn image routing to the RC1 Agent model-selection contract. DVR selects a model via the supported `agent.model.select()` before Agent pre-step freezes provider/model, tool admission and prompt assembly; the modern `agent/request` hook no longer rewrites the chosen model. Legacy Hosts without the native selector retain their previous route path. / **#786(修复 #787):** 适配 RC1 的 Agent 预步骤模型选择契约,使用官方 `agent.model.select()` 在模型、工具和提示词固定前选择图片模型;新版 Host 不再在 `agent/request` 阶段强改模型。旧版 Host 保留原有分流路径。
8
+ - A subsequent text-only turn can restore the original text model when reverse routing is enabled, without overriding a different model manually selected by the user. Queue/steer, turn-stopping timing, missing adapters/projections, unloaded Agent state, offloaded images and failure handling have regression coverage. / 开启反向路由时,后续纯文本轮次可恢复用户原先的文字模型,且不覆盖用户手动改选的其他模型;排队、插话、轮次结束竞态、缺失适配器或投影、Agent 卸载及异常路径均有回归测试。
9
+ - The **default tool-only vision path remains the default** and gets its progressive vision tools mounted before the RC1 tool-admission snapshot; this release does not silently turn on whole-turn model switching. / **默认仍为工具识图模式**;渐进式识图工具会在 RC1 工具许可快照前注册,不会擅自开启整轮模型切换。
10
+
11
+ ## Exact-source and real Host acceptance / 精确源码及真实 Host 验收
12
+
13
+ - The DSH 0.2.2-rc.1 release is pinned to immutable source commit `66491b05e3f05ad35bcdd4f6cd7ed26041d9e3db`. Exact-source / Host Gate passed **6/6** on Linux, macOS and Windows, including real Chromium lifecycle, macOS Desktop, Windows Desktop Node 24.9 and 24.21. / DSH RC1 固定到上述不可变源码;六项门禁全部通过,涵盖三端、真实 Chromium、macOS Desktop、Windows Node 24.9/24.21 Desktop。
14
+ - The whole-turn Desktop E2E verified real HTTP delivery of an image to a distinct visual adapter, a subsequent text request to the original adapter, rendered answers, and accepted Session model-selection projection. Windows Node 24.9 independently validated the default tool-only image path. / 整轮分流 E2E 真实验证了视觉适配器收到图片、纯文本回合返回原文字适配器、界面可见回复和 Session 模型选择投影;Windows Node 24.9 另行验证默认工具识图流程。
15
+ - **Scope limits:** RC1 itself requires **Node >=24.9**; this does not raise DVR's declared Node support range on older Hosts. RC1's default model-switch compaction reserves 65,536 tokens, which cannot fit a 32K context-window destination. Such models may need explicit Host `compaction-basic.modelPolicies` headroom configuration, or can stay on the default tool-only mode. This exact RC1 validation does not promise blanket compatibility with future 0.2.x previews. / **范围限制:** RC1 自身要求 Node ≥24.9,但插件对旧 Host 的 Node 支持声明不变。RC1 的默认模型切换压缩预留 65,536 token,无法适配 32K 上下文目标;此类模型可能需要按模型设置 Host 的 `compaction-basic.modelPolicies`,或继续使用默认工具识图。当前验收仅针对固定 RC1,不代表未来 0.2.x 全部版本均已验证。
16
+
17
+ ## CI supply-chain maintenance / CI 供应链维护
18
+
19
+ - **#788 (supersedes #785):** Pin HOL AI Plugin Scanner Action to upstream **v1.2.816 / plugin-scanner 3.59.0** at immutable commit `9b169fc65d09b24726b66d70b3563ab563158b58`, fixing the stale version comment. The scanner returned **92/100**, with **0 critical, 0 high and 1 medium** finding. Existing `min_score: 90` and `fail_on_severity: high` gates remain unchanged. This changes CI only, not the plugin runtime. / **#788(替代 #785):** 将 HOL Action 固定至 3.59.0 对应的不可变上游提交并修正版本注释;扫描得分 92/100,0 严重、0 高危、1 中危;90 分门槛和 High 失败策略均不变。只改 CI,不改插件运行时。
20
+
21
+ ## Release boundaries / 发布边界
22
+
23
+ - No Settings migration, public API break, widened remote permissions, Node support-floor increase or runtime provider-secret logging. / 不新增设置迁移、不破坏公共 API、不扩大远程权限、不抬高插件最低 Node 支持要求,也不引入凭据日志。
24
+ - Release-commit CI, reproducible package build, immutable npm version, OIDC provenance, artifact digests and GitHub Release assets must still pass the protected release workflow. Source PR checks alone are not publication. / 正式发版提交仍须完成 CI、可复现构建、npm 版本唯一性、OIDC 来源证明、包体摘要与 GitHub Release 附件验收;PR 测试通过不等于已正式发布。
@@ -0,0 +1,24 @@
1
+ # v3.1.4 — Stability and cross-plugin compatibility / 稳定性与跨插件兼容补丁
2
+
3
+ **Candidate release notes / 候选发布说明。** This document describes the code changes proposed for the v3.1.4 patch; publication is complete only when the protected release workflow verifies the exact `main` SHA, immutable tag, npm registry tarball identity, OIDC provenance and GitHub Release attachments. / 本文为待发布版本的源码变更说明;须经受保护发布流程核验精确主分支 SHA、不可变标签、npm 包体、OIDC 来源证明与 GitHub Release 附件,才能视为完成正式发布。
4
+
5
+ ## Fixes / 已修复问题
6
+
7
+ - **#793 — Cross-plugin script ownership / 跨插件脚本隔离:** The index-injection hardening step now only rewrites DVR-owned scripts. It no longer edits unrelated client scripts from other plugins. A real pre-fix foreign-script mutation was reproduced and covered by tests. / 注入脚本加固只改写 DVR 自有脚本,避免误改写其他插件 JavaScript。已复现旧版缺陷,并加入回归测试。
8
+ - **#794 — Image fallback correctness / 识图回退正确性:** An image model yielding HTTP success but an empty answer no longer ends the chain and caches a misleading successful placeholder. The next eligible model may be tried under the same shared budget. Both tool-only and opt-in whole-turn routing are covered; failed-model partial text is not allowed to contaminate later candidates. / 视觉模型成功返回空内容时,不再提前终止和缓存伪成功,允许在原预算内继续尝试后端;覆盖默认工具识图与可选整轮路由,并隔离失败候选输出。
9
+ - **#794 — Bounded whole-turn execution / 整轮识图时限:** An image-bearing turn now has a bounded preflight and streaming execution even when a third-party adapter does not cooperate with abort or never settles its async iterator. Explicit Host/user cancellation remains distinguished. / 视觉整轮的模型预检查与流式等待均纳入总时限,即使第三方适配器不响应取消或流迭代不返回,也不会无限挂起;保留明确的用户/Host 取消行为。
10
+
11
+ ## Non-runtime safeguards / 非运行时防护
12
+
13
+ - **#795 — Desktop renderer gate / Desktop 启动渲染门禁:** Real Desktop E2E now catches bootstrap JS/CSS unintentionally becoming visible document text, including through exposed head/script/style elements, and checks injection markup delimiters. This is **not** a proven fix of issue #792. / 真实 Desktop E2E 检测启动 JS/CSS 意外外露与注入标签边界;**不是** #792 的已确认根因修复。
14
+ - **#790 — Latest-canary maintenance / 上游 canary 维护:** Keeps DSH latest-canary and Settings seam drift checks aligned. No production runtime behavior changed. / 维护上游 canary 及 Settings 接缝漂移检测,不修改正式运行时。
15
+
16
+ ## Acceptance / 验收边界
17
+
18
+ - Underlying fixes were reviewed with Node 22/24 and exact-source DSH Host/real Desktop gates. The **v3.1.4 release commit** must separately complete its own CI/security/Host tests and the protected publication workflow before it may be called published. / 源码修复已针对 Node 22/24 与真实 DSH Host/Desktop 门禁验收;**v3.1.4 发布提交**仍需独立通过 CI、安全、Host 测试及受保护发布流程。
19
+ - No change to default tool-only routing, user Settings schemas, Node/DSH support range, public API, runtime providers, remote privilege policy, or default cloud image-egress/privacy policy. / 默认工具识图、设置结构、Node/DSH 支持范围、公共 API、运行时模型提供商、远程权限与默认云端图片外发策略均未改变。
20
+ - **Still open:** #791's original 550/503 provider/HTTP source remains unverified. #792's startup raw-source window and possible multi-plugin conflict are not assigned a proven root cause; the regression gate does not certify a field resolution. / **仍在追踪:** #791 用户现场 550/503 来源不明;#792 启动窗口源码外露及可能的多插件冲突尚未确认根因,不宣称已经解决。
21
+
22
+ ## Upgrade / 升级
23
+
24
+ After the trusted release is verified on npm/GitHub, update the DVR plugin to `dsh-vision-router@3.1.4` using the existing profile's normal plugin manager or explicit-version install, then restart/reload DSH as appropriate. Back up existing profile configuration before changing the plugin set; never delete conversation history to troubleshoot. / 正式发布确认后,按现有 profile 的插件管理方式升级到 `dsh-vision-router@3.1.4` 并根据环境重载;排错前备份配置,不要求删除聊天记录。
package/index.js CHANGED
@@ -40,6 +40,56 @@ function throwIfVisionTaskAborted(signal, error) {
40
40
  throw aborted
41
41
  }
42
42
 
43
+ // A provider may ignore AbortSignal and leave iterator.next() pending forever.
44
+ // For whole-turn routing this adapter is the Agent stream itself (unlike
45
+ // vision_describe, it is not protected by the tool execution timeout wrapper).
46
+ // Race each next() with the task signal, and do not await a noncooperative
47
+ // iterator's return() while unwinding: the user's turn must always settle.
48
+ async function* streamVisionWithAbort(source, signal) {
49
+ const iterator = source?.[Symbol.asyncIterator]?.()
50
+ if (!iterator) throw new TypeError('vision chain expected an asynchronous stream')
51
+ let completed = false
52
+ try {
53
+ for (;;) {
54
+ throwIfVisionTaskAborted(signal)
55
+ let onAbort
56
+ const aborted = signal
57
+ ? new Promise((_, reject) => {
58
+ onAbort = () => reject(
59
+ signal.reason instanceof Error
60
+ ? signal.reason
61
+ : Object.assign(new Error('vision stream aborted'), { name: 'AbortError', code: 'ABORT_ERR' }),
62
+ )
63
+ signal.addEventListener('abort', onAbort, { once: true })
64
+ if (signal.aborted) onAbort()
65
+ })
66
+ : undefined
67
+ let step
68
+ try {
69
+ // A late rejection remains observed by Promise.race even if cancellation
70
+ // wins, avoiding unhandled rejection in a provider that later wakes.
71
+ const next = Promise.resolve().then(() => iterator.next())
72
+ step = await (aborted ? Promise.race([next, aborted]) : next)
73
+ } finally {
74
+ if (onAbort) signal.removeEventListener('abort', onAbort)
75
+ }
76
+ if (step.done) {
77
+ completed = true
78
+ return
79
+ }
80
+ yield step.value
81
+ }
82
+ } finally {
83
+ if (!completed && typeof iterator.return === 'function') {
84
+ try {
85
+ // The underlying adapter might never settle. Attempt cleanup, but
86
+ // never block the Agent waiting for a broken third-party stream.
87
+ void Promise.resolve(iterator.return()).catch(() => {})
88
+ } catch { /* noncooperative iterator; outer turn is already settling */ }
89
+ }
90
+ }
91
+ }
92
+
43
93
  export * from './lib/vision-resilience.js'
44
94
 
45
95
  import z from '@deepseek-ai/schemastery'
@@ -115,6 +165,7 @@ import { createCoalescingRunner } from './lib/adapter-update-coalescer.js'
115
165
  import { createDesktopScreenshotTool } from './lib/desktop-screenshot-tool.js'
116
166
  import { installVisionDiagnosticsRoutes } from './lib/vision-diagnostics-routes.js'
117
167
  import { blocksHaveRetainedImage, isOffloadedImageBlock, offloadedImagePlaceholder } from './lib/image-offload-compat.js'
168
+ import { installPreStepModelRouting } from './lib/agent-prestep-model-routing.js'
118
169
  import { createSessionTurnResolver } from './lib/session-turn-resolver.js'
119
170
  import { shouldBlockDegradedHostTool } from './lib/degraded-local-evidence.js'
120
171
  import {
@@ -1941,7 +1992,6 @@ export function apply(ctx, config = {}, runtime = {}) {
1941
1992
  }
1942
1993
  if (imageIds.length > 0) break
1943
1994
  }
1944
- let finalText = ''
1945
1995
  const chainPairs = routingPairs()
1946
1996
  const chainHttpEntries = new Map(httpEntries().map((entry) => [entry.id, entry]))
1947
1997
  // Fit the conversation into the target model's context window: a long
@@ -1967,7 +2017,19 @@ export function apply(ctx, config = {}, runtime = {}) {
1967
2017
  (sum, pair) => sum + routingPairWeight(pair, chainHttpEntries),
1968
2018
  0,
1969
2019
  )
2020
+ // Streaming a failed candidate is irreversible for the Host. When a
2021
+ // fallback exists, stage its events until a successful finish so a
2022
+ // second backend never appends to a broken first answer. Single-route
2023
+ // and legacy text-only streams keep their existing streaming UX.
2024
+ const holdCandidateEvents = imageIds.length > 0 && chainPairs.length > 1
2025
+ const maxHeldEventBytes = 8 * 1024 * 1024
2026
+ const maxHeldEvents = 32768
1970
2027
  for (const pair of chainPairs) {
2028
+ // Keep result text isolated by candidate; a failed stream's partial
2029
+ // output must never count as recognition by the next backend.
2030
+ let finalText = ''
2031
+ const heldEvents = []
2032
+ let heldBytes = 0
1971
2033
  const candidateWeight = routingPairWeight(pair, chainHttpEntries)
1972
2034
  const weightAtStart = Math.max(candidateWeight, remainingWeight)
1973
2035
  remainingWeight = Math.max(0, remainingWeight - candidateWeight)
@@ -2034,6 +2096,7 @@ export function apply(ctx, config = {}, runtime = {}) {
2034
2096
  let succeeded = false
2035
2097
  let failed = false
2036
2098
  let failMessage = 'unknown error'
2099
+ let failCode
2037
2100
  try {
2038
2101
  // Local backends get an independent anti-hang budget: a hung local
2039
2102
  // service must not consume the whole deadline and starve the
@@ -2085,7 +2148,7 @@ export function apply(ctx, config = {}, runtime = {}) {
2085
2148
  }
2086
2149
  yield { type: 'finish', reason: { kind: 'stop' } }
2087
2150
  }
2088
- for await (const chunk of streamPair()) {
2151
+ for await (const chunk of streamVisionWithAbort(streamPair(), attemptSignal)) {
2089
2152
  if (chunk && chunk.type === 'finish') {
2090
2153
  const kind = chunk.reason && chunk.reason.kind
2091
2154
  if (kind === 'error' || kind === 'aborted') {
@@ -2094,7 +2157,16 @@ export function apply(ctx, config = {}, runtime = {}) {
2094
2157
  failed = true
2095
2158
  break
2096
2159
  }
2097
- // 'stop' / 'max-tokens' / 'tool-calls' are success.
2160
+ // Tool-call handoffs may legitimately have no text, but a
2161
+ // completed recognition with no text is not a usable answer.
2162
+ // It must not suppress fallback or cache an earlier failed
2163
+ // candidate's partial output as this backend's result.
2164
+ if (imageIds.length > 0 && (kind === 'stop' || kind === 'max-tokens') && finalText.trim() === '') {
2165
+ failed = true
2166
+ failCode = 'EMPTY_RESPONSE'
2167
+ failMessage = 'vision chain backend returned empty content'
2168
+ break
2169
+ }
2098
2170
  succeeded = true
2099
2171
  // 视觉链成功留痕:谁识别了几张图、写入跨轮缓存——排障时
2100
2172
  // "这张图的描述是谁生成的"一眼可查(原版此处静默)。
@@ -2107,18 +2179,41 @@ export function apply(ctx, config = {}, runtime = {}) {
2107
2179
  const record = finalText.trim()
2108
2180
  for (const id of imageIds) imageMemorySet(imageMemory, id, record)
2109
2181
  }
2182
+ if (holdCandidateEvents) {
2183
+ for (const event of heldEvents) yield event
2184
+ }
2110
2185
  yield chunk
2111
2186
  break
2112
2187
  }
2113
2188
  if (chunk && typeof chunk.text === 'string') finalText += chunk.text
2114
- yield chunk
2189
+ if (holdCandidateEvents) {
2190
+ const bytes = Buffer.byteLength(JSON.stringify(chunk) ?? '', 'utf8')
2191
+ if (heldEvents.length >= maxHeldEvents || heldBytes + bytes > maxHeldEventBytes) {
2192
+ failCode = 'VISION_CHAIN_BUFFER_LIMIT'
2193
+ throw new Error('vision chain candidate output exceeded safe fallback buffer limit')
2194
+ }
2195
+ heldEvents.push(chunk)
2196
+ heldBytes += bytes
2197
+ } else {
2198
+ yield chunk
2199
+ }
2200
+ }
2201
+ if (!succeeded && !failed && imageIds.length > 0) {
2202
+ // An adapter can end iteration without emitting the mandatory
2203
+ // terminal finish. Do not silently close the Agent stream and
2204
+ // strand a later model that could recover the visual answer.
2205
+ failed = true
2206
+ failCode = 'EMPTY_RESPONSE'
2207
+ failMessage = 'vision chain backend ended without a finish event'
2115
2208
  }
2116
2209
  } catch (error) {
2117
2210
  failed = true
2118
2211
  failMessage = error && error.message ? error.message : String(error)
2119
2212
  }
2120
2213
  if (failed) {
2121
- const classification = classifyVisionFailure(failMessage)
2214
+ const classification = classifyVisionFailure(
2215
+ failCode ? { code: failCode, message: failMessage } : failMessage,
2216
+ )
2122
2217
  visionBreaker.record(backendKey, fingerprint, classification, 'chain')
2123
2218
  failures.push(`${pair.provider}/${pair.model}: ${failMessage}`)
2124
2219
  ctx.logger?.warn('vision-router: chain fallback (%s) -> %s', classification.kind, failMessage)
@@ -2138,6 +2233,50 @@ export function apply(ctx, config = {}, runtime = {}) {
2138
2233
  }
2139
2234
  },
2140
2235
  }
2236
+
2237
+ // The chain's own deadline starts after initial model-info preflight.
2238
+ // A noncooperative discovery/capability adapter can therefore keep the
2239
+ // entire Agent turn pending before the first streamed chunk. Protect the
2240
+ // COMPLETE image-bearing stream, not only individual model iterator.next()
2241
+ // calls. Text-only legacy routes retain their existing semantics.
2242
+ const innerChainStream = chainAdapter.stream
2243
+ chainAdapter.stream = async function* boundedVisionChainStream(options) {
2244
+ const imageBearing = collectImageBlocks(options?.messages ?? [])
2245
+ .some(({ block }) => !isOffloadedImageBlock(block))
2246
+ if (!imageBearing) {
2247
+ yield* innerChainStream.call(this, options)
2248
+ return
2249
+ }
2250
+ const budgetSignal = AbortSignal.timeout(visionTaskTimeoutMs())
2251
+ const signal = combineSignals(options?.signal, budgetSignal)
2252
+ try {
2253
+ for await (const chunk of streamVisionWithAbort(
2254
+ innerChainStream.call(this, { ...options, signal }),
2255
+ signal,
2256
+ )) {
2257
+ yield chunk
2258
+ // The Host only accepts one terminal event. Do not remain blocked in
2259
+ // a broken iterator's post-finish cleanup, or emit an error later.
2260
+ if (chunk?.type === 'finish') return
2261
+ }
2262
+ } catch (error) {
2263
+ if (!signal.aborted) throw error
2264
+ if (options?.signal?.aborted) {
2265
+ yield { type: 'finish', reason: { kind: 'aborted' } }
2266
+ return
2267
+ }
2268
+ yield {
2269
+ type: 'finish',
2270
+ reason: {
2271
+ kind: 'error',
2272
+ failure: {
2273
+ code: 'VISION_CHAIN_EXHAUSTED',
2274
+ message: 'vision task timed out before the model finished preparing or responding',
2275
+ },
2276
+ },
2277
+ }
2278
+ }
2279
+ }
2141
2280
  }
2142
2281
 
2143
2282
  // ── reactive routing mounts ────────────────────────────────────────────────
@@ -2306,6 +2445,26 @@ export function apply(ctx, config = {}, runtime = {}) {
2306
2445
  }
2307
2446
  })
2308
2447
 
2448
+ // DSH >= 0.2.2 fixes the step model before pre-step and tools.resolve.
2449
+ // The Agent inbox/status event boundary runs after Session append finishes,
2450
+ // while selection can still be changed for the next step without reentrancy.
2451
+ // Older Hosts without Agent.model continue to use the late request hook.
2452
+ const preStepRouting = installPreStepModelRouting(ctx, {
2453
+ routingEnabled,
2454
+ reverseRoutingEnabled,
2455
+ routingPairs,
2456
+ chainRoute,
2457
+ wrapperRoute,
2458
+ wrapperRegistered: () => wrapperRegistered,
2459
+ textProvider,
2460
+ hasAdapter: (provider) => adapterAvailable(ctx.llm, provider),
2461
+ hasImage: blocksHaveRetainedImage,
2462
+ toolEnabled,
2463
+ autoActivateOnImageEnabled,
2464
+ structuredBootstrapEnabled,
2465
+ activateDeepTools: () => activateDeepTools(),
2466
+ })
2467
+
2309
2468
  ctx.on('agent/pre-step', async (payload, next) => {
2310
2469
  let decision = await next()
2311
2470
  if (sessionVisionRuntime?.index === undefined) {
@@ -2570,6 +2729,9 @@ export function apply(ctx, config = {}, runtime = {}) {
2570
2729
  // adapters the same way).
2571
2730
  ctx.on('agent/request', async (payload, next) => {
2572
2731
  const config0 = await next()
2732
+ // The modern Host rejects any route change here. Its Agent.model already
2733
+ // selected the image/text route BEFORE tool and prompt admission.
2734
+ if (preStepRouting.nativeModel(payload.agent)) return config0
2573
2735
  if (!routingEnabled()) return config0
2574
2736
  const session = payload.agent && payload.agent.session
2575
2737
  if (!session) return config0
@@ -2952,9 +3114,13 @@ ctx.logger?.info(
2952
3114
  if (cacheEnabled()) cache.set(key, text)
2953
3115
  return text
2954
3116
  }
2955
- const empty = '(the vision model returned empty content)'
2956
- if (cacheEnabled()) cache.set(key, empty)
2957
- return empty
3117
+ // A successfully transported but empty answer is not visual evidence.
3118
+ // In particular, reasoning models can exhaust their output budget
3119
+ // before emitting any content. Never cache a fabricated success or
3120
+ // suppress a healthy later backend in the configured chain.
3121
+ const empty = new Error('vision_describe backend returned empty content')
3122
+ empty.code = 'EMPTY_RESPONSE'
3123
+ throw empty
2958
3124
  } catch (error) {
2959
3125
  const classification = classifyVisionFailure(error)
2960
3126
  visionBreaker.record(backendKey, fingerprint, classification, scope)
@@ -3083,6 +3249,11 @@ ctx.logger?.info(
3083
3249
  if (cacheEnabled()) cache.set(key, text)
3084
3250
  return text
3085
3251
  }
3252
+ // Mirror the adapter-backed branch: this HTTP response is a
3253
+ // backend failure, not a valid zero-length recognition result.
3254
+ const empty = new Error(`http provider "${provider.name}": vision response was empty`)
3255
+ empty.code = 'EMPTY_RESPONSE'
3256
+ throw empty
3086
3257
  } catch (error) {
3087
3258
  const classification = classifyVisionFailure(error)
3088
3259
  visionBreaker.record(backendKey, fingerprint, classification, scope)
@@ -0,0 +1,273 @@
1
+ import { reverseRouteTarget } from './core-primitives.js'
2
+ import { redactDiagnosticText } from './diagnostic-redaction.js'
3
+
4
+ function routeOf(value) {
5
+ if (!value || typeof value !== 'object') return undefined
6
+ if (typeof value.provider !== 'string' || !value.provider || typeof value.model !== 'string' || !value.model) return undefined
7
+ return { provider: value.provider, model: value.model }
8
+ }
9
+
10
+ function sameRoute(a, b) {
11
+ return a?.provider === b?.provider && a?.model === b?.model
12
+ }
13
+
14
+ function validMessages(value) {
15
+ return Array.isArray(value) ? value.filter((item) => item && typeof item === 'object' && item.role === 'user') : []
16
+ }
17
+
18
+ /**
19
+ * Modern DSH freezes the model BEFORE agent/pre-step, while the old
20
+ * agent/request model switch is now forbidden. The Agent's own inbox is the
21
+ * last durable, synchronously observable input before that freeze.
22
+ *
23
+ * Never select during session/event: Session.append forbids reentrant appends,
24
+ * and agent.model.select appends a model/selection event. Inbox notifications
25
+ * and status events fire only AFTER the triggering append has returned.
26
+ */
27
+ export function installPreStepModelRouting(ctx, options) {
28
+ const owned = new WeakMap()
29
+ const warning = new WeakSet()
30
+ const agentsBySession = new WeakMap()
31
+ const selecting = new WeakSet()
32
+ const manualOverride = new WeakSet()
33
+ const stopping = new WeakMap()
34
+
35
+ const warnOnce = (agent, message) => {
36
+ if (warning.has(agent)) return
37
+ warning.add(agent)
38
+ ctx.logger?.warn?.('vision-router: modern pre-step routing unavailable: %s', redactDiagnosticText(message, 180))
39
+ }
40
+ const nativeModel = (agent) => {
41
+ try {
42
+ const model = agent?.model
43
+ return model && typeof model.select === 'function' && typeof model.current === 'function'
44
+ ? model : undefined
45
+ } catch {
46
+ return undefined
47
+ }
48
+ }
49
+ const currentOf = (agent) => {
50
+ try { return nativeModel(agent)?.current() }
51
+ catch (error) {
52
+ warnOnce(agent, String(error?.message ?? error).slice(0, 180))
53
+ return undefined
54
+ }
55
+ }
56
+ const readInbox = (agent) => {
57
+ if (!agent?.session || typeof ctx.get !== 'function') return undefined
58
+ try {
59
+ const registry = ctx.get('sessionProjections')
60
+ if (typeof registry?.stateOf !== 'function') return undefined
61
+ const state = registry.stateOf(agent.session, 'inbox')
62
+ if (!state || typeof state !== 'object') return undefined
63
+ return {
64
+ nextTurn: validMessages(state['next-turn']),
65
+ nextStep: validMessages(state['next-step']),
66
+ }
67
+ } catch {
68
+ return undefined
69
+ }
70
+ }
71
+ const available = (provider) => {
72
+ try { return options.hasAdapter(provider) === true } catch { return false }
73
+ }
74
+ const select = (agent, target, previous, reason) => {
75
+ if (!target || !available(target.provider) || sameRoute(target, previous)) return false
76
+ // Keep an explicit same-route effort selection; drop provider-specific effort
77
+ // only on a cross-route transition.
78
+ try {
79
+ selecting.add(agent.session)
80
+ agent.model.select(target)
81
+ ctx.logger?.debug?.('vision-router: pre-step model selected for %s', reason)
82
+ return true
83
+ } catch (error) {
84
+ warnOnce(agent, String(error?.message ?? error).slice(0, 180))
85
+ return false
86
+ } finally {
87
+ selecting.delete(agent.session)
88
+ }
89
+ }
90
+ const hasImage = (messages) => messages.some((message) => {
91
+ try { return options.hasImage(message.content) === true } catch { return false }
92
+ })
93
+ const startDeepTools = () => {
94
+ if (options.toolEnabled() && (options.autoActivateOnImageEnabled() || options.structuredBootstrapEnabled())) {
95
+ options.activateDeepTools()
96
+ }
97
+ }
98
+ const imageTurn = (agent, messages) => {
99
+ const model = nativeModel(agent)
100
+ if (!model || !hasImage(messages)) return
101
+ // RC1 resolves step tools before agent/pre-step. Mount progressive deep
102
+ // tools even when whole-turn routing is OFF (the default).
103
+ startDeepTools()
104
+ if (!options.routingEnabled()) return
105
+ const selection = currentOf(agent)
106
+ const source = routeOf(selection)
107
+ if (!source) return
108
+ const first = options.routingPairs()[0]
109
+ if (typeof first?.provider !== 'string' || !first.provider
110
+ || typeof first.model !== 'string' || !first.model) return
111
+ const chain = options.chainRoute()
112
+ const target = chain && available(chain)
113
+ ? { provider: chain, model: first.provider + '/' + first.model }
114
+ : { provider: first.provider, model: first.model }
115
+ // Historical behavior preserves the user's model within the same
116
+ // provider when chain routing is not enabled.
117
+ if (source.provider === target.provider) return
118
+ const record = owned.get(agent)
119
+ if (record && !sameRoute(source, record.target)) owned.delete(agent)
120
+ const returnTo = owned.get(agent)?.origin ?? { ...selection }
121
+ if (select(agent, target, source, 'image turn')) {
122
+ manualOverride.delete(agent)
123
+ owned.set(agent, { origin: returnTo, target })
124
+ }
125
+ }
126
+ const textTurn = (agent) => {
127
+ const model = nativeModel(agent)
128
+ if (!model) return
129
+ const current = routeOf(currentOf(agent))
130
+ if (!current || manualOverride.has(agent)) return
131
+ const record = owned.get(agent)
132
+ if (record) {
133
+ owned.delete(agent)
134
+ // A user can manually select another vision model while an image turn
135
+ // is running. That explicit choice must not be reinterpreted as a
136
+ // request for automatic reverse routing on the next text input.
137
+ if (!sameRoute(current, record.target)) return
138
+ // reverseRouting=false explicitly keeps the visual route for later text
139
+ // turns. Only a disabled whole-turn routing switch must restore DVR's
140
+ // temporary image selection to the user's original model.
141
+ if (options.routingEnabled() && !options.reverseRoutingEnabled()) return
142
+ // Restore the actual Session model chosen before DVR routed its image.
143
+ // Never overwrite a different model explicitly selected by the user.
144
+ const origin = routeOf(record.origin)
145
+ const candidate = options.routingEnabled() && options.reverseRoutingEnabled()
146
+ ? reverseRouteTarget(origin, {
147
+ pairs: options.routingPairs(),
148
+ wrapperRoute: options.wrapperRoute(),
149
+ wrapperRegistered: options.wrapperRegistered(),
150
+ textProvider: options.textProvider(),
151
+ hasAdapter: available,
152
+ })
153
+ : undefined
154
+ if (!select(agent, candidate ?? record.origin, current, 'text restore') && !available((candidate ?? record.origin)?.provider)) {
155
+ warnOnce(agent, 'original text model is no longer registered')
156
+ }
157
+ return
158
+ }
159
+ if (!options.routingEnabled() || !options.reverseRoutingEnabled()) return
160
+ const target = reverseRouteTarget(current, {
161
+ pairs: options.routingPairs(),
162
+ wrapperRoute: options.wrapperRoute(),
163
+ wrapperRegistered: options.wrapperRegistered(),
164
+ textProvider: options.textProvider(),
165
+ hasAdapter: available,
166
+ })
167
+ select(agent, target, current, 'reverse text routing')
168
+ }
169
+ const nextTurn = (agent, inbox) => {
170
+ if (!nativeModel(agent)) return
171
+ if (!inbox) { warnOnce(agent, 'Session inbox projection unavailable'); return }
172
+ if (!inbox.nextTurn.length) return
173
+ if (hasImage(inbox.nextTurn)) imageTurn(agent, inbox.nextTurn)
174
+ else textTurn(agent)
175
+ }
176
+ const nextStep = (agent, inbox) => {
177
+ if (!nativeModel(agent) || !inbox?.nextStep.length) return
178
+ // Tool-produced context is not a new user text turn. In particular, it
179
+ // must NOT undo an image selection from an ongoing multi-step tool run.
180
+ if (hasImage(inbox.nextStep)) imageTurn(agent, inbox.nextStep)
181
+ }
182
+
183
+ const rememberAgent = (agent) => {
184
+ if (nativeModel(agent) && agent?.session) agentsBySession.set(agent.session, agent)
185
+ }
186
+ // Observing external model/selection commits is read-only: selecting inside
187
+ // session/event would reenter Session.append and crash. Invalidate only our
188
+ // auto-restore ownership when a user/Host selects a model outside DVR.
189
+ // Only accepted Host selection events carry authority; identical-route
190
+ // no-op selections produce no event and therefore no new intent signal.
191
+ ctx.on('session/event', (session, event) => {
192
+ const agent = agentsBySession.get(session)
193
+ if (event?.type === 'turn/start') {
194
+ // Clear the previous turn's closing-window marker without appending a
195
+ // Session event from inside the non-reentrant Session publication.
196
+ if (agent) stopping.delete(agent)
197
+ return
198
+ }
199
+ if (event?.type !== 'model/selection' || selecting.has(session)) return
200
+ if (agent && owned.has(agent)) {
201
+ owned.delete(agent)
202
+ manualOverride.add(agent)
203
+ }
204
+ })
205
+ const containEarlyHook = (agent, action) => {
206
+ try { action() }
207
+ catch (error) {
208
+ // agent.send() calls inbox listeners synchronously BEFORE wakeDriver().
209
+ // A plugin failure here must not strand a durably queued user message.
210
+ if (agent && typeof agent === 'object') warnOnce(agent, String(error?.message ?? error).slice(0, 180))
211
+ }
212
+ }
213
+ ctx.on('agent/inbox/inserted', ({ agent, message } = {}) => containEarlyHook(agent, () => {
214
+ if (!nativeModel(agent)) return
215
+ rememberAgent(agent)
216
+ const inbox = readInbox(agent)
217
+ if (!inbox) { warnOnce(agent, 'Session inbox projection unavailable'); return }
218
+ // An inserted next-turn message may be waiting behind an active step.
219
+ // Prefer the pending next-step image; the turn-stopping and running
220
+ // boundaries re-evaluate next-turn once the active turn finishes.
221
+ if (message?.id && inbox.nextStep.some((item) => item.id === message.id)) {
222
+ const previous = stopping.get(agent)
223
+ if (previous && !manualOverride.has(agent)) {
224
+ // A next-step steering message may arrive while turn-stopping awaits
225
+ // other hooks, after DVR temporarily selected a queued next-turn route.
226
+ // Reassert this turn's actual route, never the later queued turn's route.
227
+ const current = routeOf(currentOf(agent))
228
+ if (current && previous.route && !sameRoute(current, previous.route)) {
229
+ if (select(agent, previous.route, current, 'closing step continuation')) {
230
+ if (previous.owned) owned.set(agent, previous.owned)
231
+ else owned.delete(agent)
232
+ }
233
+ }
234
+ }
235
+ nextStep(agent, inbox)
236
+ } else if (message?.id && inbox.nextTurn.some((item) => item.id === message.id)
237
+ && (agent.status === 'idle' || stopping.has(agent))) {
238
+ // Once turn-stopping starts there can be a tiny gap before the next
239
+ // turn/start where status is still running. New queued turns must not
240
+ // miss the pre-step model selection in that window.
241
+ nextTurn(agent, inbox)
242
+ }
243
+ }))
244
+ ctx.on('agent/status', ({ agent, status } = {}) => containEarlyHook(agent, () => {
245
+ rememberAgent(agent)
246
+ if (status === 'running') nextTurn(agent, readInbox(agent))
247
+ }))
248
+ ctx.on('agent/turn-stopping', ({ agent } = {}) => {
249
+ try {
250
+ rememberAgent(agent)
251
+ const selection = currentOf(agent)
252
+ const current = routeOf(selection)
253
+ if (current) stopping.set(agent, {route: {...selection}, owned: owned.get(agent)})
254
+ const inbox = readInbox(agent)
255
+ if (inbox?.nextStep.length) nextStep(agent, inbox)
256
+ else nextTurn(agent, inbox)
257
+ } catch (error) {
258
+ // A routing plugin must never veto the Host's turn completion.
259
+ if (agent && typeof agent === 'object') warnOnce(agent, String(error?.message ?? error).slice(0, 180))
260
+ }
261
+ })
262
+ ctx.on('agent/disposed', ({ agent } = {}) => {
263
+ if (agent && typeof agent === 'object') {
264
+ owned.delete(agent)
265
+ warning.delete(agent)
266
+ manualOverride.delete(agent)
267
+ stopping.delete(agent)
268
+ if (agent.session) agentsBySession.delete(agent.session)
269
+ }
270
+ })
271
+
272
+ return { nativeModel }
273
+ }
@@ -467,9 +467,20 @@ export function hardenVisionClientSource(source) {
467
467
  return next
468
468
  }
469
469
 
470
+ // Only DVR-owned carriers may be rewritten. Other plugins can register
471
+ // arbitrary index-injection scripts with identical helper source text; editing
472
+ // those scripts silently changes their behavior and can break Desktop boot.
473
+ const OWNED_STRUCTURED_SCRIPT = /^\s*\/\*\s*data-vision-router-[a-z0-9:-]+\s*\*\//
474
+ const OWNED_HTML_SCRIPT = /(<script\s+data-vision-router-[a-z0-9:-]+>)([\s\S]*?)(<\/script\s*>)/gi
475
+
476
+ function hardenOwnedClientHtml(html) {
477
+ return html.replace(OWNED_HTML_SCRIPT, (_match, opening, source, closing) =>
478
+ `${opening}${hardenVisionClientSource(source)}${closing}`)
479
+ }
480
+
470
481
  export function hardenVisionToggleHtml(html) {
471
482
  if (typeof html !== 'string') return html
472
- let next = hardenVisionClientSource(html)
483
+ let next = hardenOwnedClientHtml(html)
473
484
 
474
485
  if (!next.includes(OWNERSHIP_MARK)) {
475
486
  const safe = CLIENT_PRELUDE.replace(/<\/script/gi, '<\\/script')
@@ -519,7 +530,8 @@ export function createVisionToggleRootHardening(ctx, config = {}) {
519
530
  webCtx.on('webserver/index-inject', (table) => {
520
531
  if (!Array.isArray(table)) return
521
532
  for (const row of table) {
522
- if (row?.kind === 'script' && typeof row.text === 'string') {
533
+ if (row?.kind === 'script' && typeof row.text === 'string'
534
+ && OWNED_STRUCTURED_SCRIPT.test(row.text)) {
523
535
  row.text = hardenVisionClientSource(row.text)
524
536
  }
525
537
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vision-router",
3
- "version": "3.1.2",
3
+ "version": "3.1.4",
4
4
  "description": "Eyes for text-only DeepSeek Harness agents: built-in free vision chain + pixel-level tools. Remote vision providers, including the default free fallback, receive image content unless strict local-only use is configured.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -92,14 +92,14 @@
92
92
  "@deepseek-ai/dsh-storage-domain": "0.2.0-rc.2"
93
93
  },
94
94
  "scripts": {
95
- "test": "node --test tests/dsh-alpha-pin.test.js tests/native-plugin-icons.test.js tests/optional-peer-import-contract.test.js tests/index-modularization.test.js tests/adapter-prepare-call-compat.test.js tests/core.test.js tests/issue-374-delegated-call-config.test.js tests/grounding-coordinate-frame.test.js tests/grounding-coordinate-runtime.test.js tests/capability-advisory.test.js tests/vision-execution-policy.test.js tests/vision-backend-diagnostics.test.js tests/live-model-discovery.test.js tests/cache-atomic-write-concurrency.test.js tests/live-model-credential-resolution.test.js tests/vision-model-registry.test.js tests/live-model-client-stability.test.js tests/providers-persistence.test.js tests/provider-directory-fallback.test.js tests/model-catalog-policy.test.js tests/settings-ia-client-prelude.test.js tests/settings-ia-fj.test.js tests/settings-ia-acceptance-regression.test.js tests/settings-migration.test.js tests/settings-section-order.test.js tests/attachment-admission-policy.test.js tests/vision-resilience.test.js tests/degraded-local-evidence.test.js tests/vision-resilience-lifecycle.test.js tests/vision-breaker-readonly.test.js tests/alpha1-browser-lifecycle-integration.test.js tests/issue-367-remote-session-inject.test.js tests/vision-mode-toggle-injection.test.js tests/dev-staged-build.test.js tests/dev-web-reload.test.js tests/client.test.js tests/issue-307-regression.test.js tests/issue-284-vision-mode-toggle.test.js tests/issue-284-vision-mode-hardening.test.js tests/issue-284-attachment-id-hint.test.js tests/issue-284-model-visibility.test.js tests/issue-284-vision-selection-effort.test.js tests/client-presentation-boundary.test.js tests/clipboard-image-paste-compat.test.js tests/remote-settings-bridge.test.js tests/remote-settings-v2-contract.test.js tests/remote-settings-risk-confirmation.test.js tests/local-remote-settings-permission.test.js tests/artifact-path-security.test.js tests/http-compat.test.js tests/catalog-corrections.test.js tests/release-registry-identity.test.js tests/update-check.test.js tests/update-check-signal-lifecycle.test.js tests/self-update.test.js tests/doctor.test.js tests/doctor-cli.test.js tests/legacy-session-repair.test.js tests/profile-pnpm-diagnostics.test.js tests/doctor-v2.test.js tests/doctor-cli-v2.test.js tests/doctor-runtime.test.js tests/dsh-host-capabilities.test.js tests/doctor-host-capabilities.test.js tests/session-repair-v2.test.js tests/activation-shim-contract.test.js tests/bundle-defaults.test.js tests/file-logger.test.js tests/official-deepseek-catalog.test.js tests/replay-delegation.test.js tests/twin-image-capability-fallback.test.js tests/twin-image-custom-wrapper.test.js tests/adversarial-hardening.test.js tests/vision-adversarial-hardening-v2.test.js tests/vision-capability-benchmark-visual-proof.test.js tests/wrapper-directory.test.js tests/logging-ui.test.js tests/manifest-dependencies.test.js tests/provider-transport-threading.test.js tests/architecture-2.3-gate.test.js tests/host-settings-seam.test.js tests/drift-canary-settings-seam.test.js tests/esm-cycle-audit.test.js tests/structured-bootstrap.test.js tests/structured-bootstrap-gate.test.js tests/vision-model-guidance-contract.test.js tests/local-ollama.test.js tests/local-only-vision.test.js tests/ollama-cold-start.test.js tests/ollama-cold-start-loaded.test.js tests/zero-regression-gate.test.js tests/runtime-e2e.test.js tests/local-vision-stabilizer.test.js tests/local-connection-probe.test.js tests/vision-diagnostics-routes.test.js tests/repetition-guard.test.js tests/guide-scroll-gate.test.js tests/settings-scroll-jank-regression.test.js tests/free-cloud-first.test.js tests/dsh-host-compat.test.js tests/native-image-coexistence.test.js tests/issue-276-session-image-ownership.test.js tests/issue-276-entry-policy-bridge.test.js tests/issue-276-policy-hardening.test.js tests/issue-289-native-nonintervention.test.js tests/issue-512-tool-restriction.test.js tests/issue-606-session-source-ownership.test.js tests/pi-ai-bridge-wire-compat.test.js tests/fetch-wrapper-lifecycle.test.js tests/fetch-wrapper-composition.test.js tests/provider-probe-proxy-scope.test.js tests/lifecycle-invariants.test.js tests/vision-tool-settings-generation.test.js tests/release-package-content-identity.test.js tests/release-state-machine.test.js tests/mixed-router.test.js tests/depth-tier.test.js tests/depth-quota-behavior.test.js tests/structured-flow-hardening.test.js tests/structured-flow-adversarial.test.js tests/vision-budget-activation.test.js tests/runtime-boundary-fixes.test.js tests/security-resource-boundaries.test.js tests/security-property-fuzz.test.js tests/security-adversarial-fuzz-contract.test.js tests/runtime-i18n.test.js tests/long-ocr-empty-retry.test.js tests/tesseract-adaptive-ocr.test.js tests/tesseract-node24-boot.test.js tests/session-vision-state.test.js tests/session-vision-state-integration.test.js tests/session-vision-event-feed.test.js tests/session-vision-policy.test.js tests/session-vision-policy-domain.test.js tests/session-vision-delegation.test.js tests/session-vision-delegation-boundary.test.js tests/subagent-vision-inheritance-characterization.test.js tests/subagent-vision-runtime-integration.test.js tests/subagent-vision-cold-resume.test.js tests/image-resource-governor.test.js tests/resource-retention-lifecycle.test.js tests/pixel-diff-stream.test.js tests/large-image-resource-integration.test.js tests/structured-guard-idempotency.test.js tests/vision-routing-product.test.js tests/vision-runtime-performance.test.js tests/vision-routing-settings-prelude.test.js tests/v2-settings-ia-integration.test.js tests/vision-capability-router.test.js tests/vision-capability-reference.test.js tests/vision-capability-benchmark.test.js tests/vision-capability-grounding-proof-contract.test.js tests/vision-capability-probe.test.js tests/vision-capability-axis-freshness.test.js tests/vision-capability-shadow-health.test.js tests/vision-capability-benchmark-service.test.js tests/vision-capability-preflight-hardening.test.js tests/vision-capability-benchmark-contract.test.js tests/vision-capability-benchmark-client.test.js tests/vision-capability-benchmark-client-productization.test.js tests/vision-capability-adapter-route.test.js tests/vision-background-benchmark.test.js tests/vision-background-lifecycle.test.js tests/vision-background-benchmark-productization.test.js tests/vision-capability-benchmark-budget.test.js tests/vision-image-input-verdict.test.js tests/vision-capability-failure-classification.test.js tests/vision-capability-gate-client.test.js tests/v2-product-review-fixes.test.js tests/qa-top5-reliability.test.js tests/qa-screenshot-runtime.test.js tests/qa-runtime-identity.test.js tests/qa-turn-budget-cancellation.test.js tests/qa-cancellation-publication.test.js tests/qa-reliability-tail.test.js tests/qa-endpoint-route-alias.test.js tests/settings-native-card-semantics.test.js tests/settings-native-card-lazy-data.test.js tests/settings-invalid-staged-dirty.test.js tests/vision-toggle-root-hardening.test.js && pnpm test:regression-closure && node --test tests/vision-backend-runtime-policy.test.js tests/vision-router-adversarial-review-fixes.test.js tests/web-panel-delegation.test.js",
95
+ "test": "node --test tests/dsh-alpha-pin.test.js tests/dsh-rc1-pin.test.js tests/agent-prestep-model-routing.test.js tests/native-plugin-icons.test.js tests/optional-peer-import-contract.test.js tests/index-modularization.test.js tests/adapter-prepare-call-compat.test.js tests/core.test.js tests/issue-374-delegated-call-config.test.js tests/grounding-coordinate-frame.test.js tests/grounding-coordinate-runtime.test.js tests/capability-advisory.test.js tests/vision-execution-policy.test.js tests/vision-backend-diagnostics.test.js tests/live-model-discovery.test.js tests/cache-atomic-write-concurrency.test.js tests/live-model-credential-resolution.test.js tests/vision-model-registry.test.js tests/live-model-client-stability.test.js tests/providers-persistence.test.js tests/provider-directory-fallback.test.js tests/model-catalog-policy.test.js tests/settings-ia-client-prelude.test.js tests/settings-ia-fj.test.js tests/settings-ia-acceptance-regression.test.js tests/settings-migration.test.js tests/settings-section-order.test.js tests/attachment-admission-policy.test.js tests/vision-resilience.test.js tests/degraded-local-evidence.test.js tests/vision-resilience-lifecycle.test.js tests/vision-breaker-readonly.test.js tests/alpha1-browser-lifecycle-integration.test.js tests/issue-367-remote-session-inject.test.js tests/vision-mode-toggle-injection.test.js tests/dev-staged-build.test.js tests/dev-web-reload.test.js tests/client.test.js tests/issue-307-regression.test.js tests/issue-284-vision-mode-toggle.test.js tests/issue-284-vision-mode-hardening.test.js tests/issue-284-attachment-id-hint.test.js tests/issue-284-model-visibility.test.js tests/issue-284-vision-selection-effort.test.js tests/client-presentation-boundary.test.js tests/clipboard-image-paste-compat.test.js tests/remote-settings-bridge.test.js tests/remote-settings-v2-contract.test.js tests/remote-settings-risk-confirmation.test.js tests/local-remote-settings-permission.test.js tests/artifact-path-security.test.js tests/http-compat.test.js tests/catalog-corrections.test.js tests/release-registry-identity.test.js tests/update-check.test.js tests/update-check-signal-lifecycle.test.js tests/self-update.test.js tests/doctor.test.js tests/doctor-cli.test.js tests/legacy-session-repair.test.js tests/profile-pnpm-diagnostics.test.js tests/doctor-v2.test.js tests/doctor-cli-v2.test.js tests/doctor-runtime.test.js tests/dsh-host-capabilities.test.js tests/doctor-host-capabilities.test.js tests/session-repair-v2.test.js tests/activation-shim-contract.test.js tests/bundle-defaults.test.js tests/file-logger.test.js tests/official-deepseek-catalog.test.js tests/replay-delegation.test.js tests/twin-image-capability-fallback.test.js tests/twin-image-custom-wrapper.test.js tests/adversarial-hardening.test.js tests/vision-adversarial-hardening-v2.test.js tests/vision-capability-benchmark-visual-proof.test.js tests/wrapper-directory.test.js tests/logging-ui.test.js tests/manifest-dependencies.test.js tests/provider-transport-threading.test.js tests/architecture-2.3-gate.test.js tests/host-settings-seam.test.js tests/drift-canary-settings-seam.test.js tests/esm-cycle-audit.test.js tests/structured-bootstrap.test.js tests/structured-bootstrap-gate.test.js tests/vision-model-guidance-contract.test.js tests/local-ollama.test.js tests/local-only-vision.test.js tests/ollama-cold-start.test.js tests/ollama-cold-start-loaded.test.js tests/zero-regression-gate.test.js tests/runtime-e2e.test.js tests/local-vision-stabilizer.test.js tests/local-connection-probe.test.js tests/vision-diagnostics-routes.test.js tests/repetition-guard.test.js tests/guide-scroll-gate.test.js tests/settings-scroll-jank-regression.test.js tests/free-cloud-first.test.js tests/dsh-host-compat.test.js tests/native-image-coexistence.test.js tests/issue-276-session-image-ownership.test.js tests/issue-276-entry-policy-bridge.test.js tests/issue-276-policy-hardening.test.js tests/issue-289-native-nonintervention.test.js tests/issue-512-tool-restriction.test.js tests/issue-606-session-source-ownership.test.js tests/pi-ai-bridge-wire-compat.test.js tests/fetch-wrapper-lifecycle.test.js tests/fetch-wrapper-composition.test.js tests/provider-probe-proxy-scope.test.js tests/lifecycle-invariants.test.js tests/vision-tool-settings-generation.test.js tests/release-package-content-identity.test.js tests/release-state-machine.test.js tests/mixed-router.test.js tests/depth-tier.test.js tests/depth-quota-behavior.test.js tests/structured-flow-hardening.test.js tests/structured-flow-adversarial.test.js tests/vision-budget-activation.test.js tests/runtime-boundary-fixes.test.js tests/security-resource-boundaries.test.js tests/security-property-fuzz.test.js tests/security-adversarial-fuzz-contract.test.js tests/runtime-i18n.test.js tests/long-ocr-empty-retry.test.js tests/tesseract-adaptive-ocr.test.js tests/tesseract-node24-boot.test.js tests/session-vision-state.test.js tests/session-vision-state-integration.test.js tests/session-vision-event-feed.test.js tests/session-vision-policy.test.js tests/session-vision-policy-domain.test.js tests/session-vision-delegation.test.js tests/session-vision-delegation-boundary.test.js tests/subagent-vision-inheritance-characterization.test.js tests/subagent-vision-runtime-integration.test.js tests/subagent-vision-cold-resume.test.js tests/image-resource-governor.test.js tests/resource-retention-lifecycle.test.js tests/pixel-diff-stream.test.js tests/large-image-resource-integration.test.js tests/structured-guard-idempotency.test.js tests/vision-routing-product.test.js tests/vision-runtime-performance.test.js tests/vision-routing-settings-prelude.test.js tests/v2-settings-ia-integration.test.js tests/vision-capability-router.test.js tests/vision-capability-reference.test.js tests/vision-capability-benchmark.test.js tests/vision-capability-grounding-proof-contract.test.js tests/vision-capability-probe.test.js tests/vision-capability-axis-freshness.test.js tests/vision-capability-shadow-health.test.js tests/vision-capability-benchmark-service.test.js tests/vision-capability-preflight-hardening.test.js tests/vision-capability-benchmark-contract.test.js tests/vision-capability-benchmark-client.test.js tests/vision-capability-benchmark-client-productization.test.js tests/vision-capability-adapter-route.test.js tests/vision-background-benchmark.test.js tests/vision-background-lifecycle.test.js tests/vision-background-benchmark-productization.test.js tests/vision-capability-benchmark-budget.test.js tests/vision-image-input-verdict.test.js tests/vision-capability-failure-classification.test.js tests/vision-capability-gate-client.test.js tests/v2-product-review-fixes.test.js tests/qa-top5-reliability.test.js tests/qa-screenshot-runtime.test.js tests/qa-runtime-identity.test.js tests/qa-turn-budget-cancellation.test.js tests/qa-cancellation-publication.test.js tests/qa-reliability-tail.test.js tests/qa-endpoint-route-alias.test.js tests/settings-native-card-semantics.test.js tests/settings-native-card-lazy-data.test.js tests/settings-invalid-staged-dirty.test.js tests/vision-toggle-root-hardening.test.js && pnpm test:regression-closure && node --test tests/vision-backend-runtime-policy.test.js tests/vision-router-adversarial-review-fixes.test.js tests/web-panel-delegation.test.js",
96
96
  "test:core": "node --test tests/core.test.js tests/degraded-local-evidence.test.js tests/runtime-e2e.test.js tests/structured-bootstrap.test.js tests/structured-flow-hardening.test.js tests/structured-flow-adversarial.test.js tests/vision-execution-policy.test.js tests/vision-backend-runtime-policy.test.js",
97
97
  "test:routing": "node --test tests/issue-374-delegated-call-config.test.js tests/twin-image-capability-fallback.test.js tests/twin-image-custom-wrapper.test.js tests/vision-routing-product.test.js tests/vision-capability-router.test.js tests/vision-capability-probe.test.js tests/vision-capability-shadow-health.test.js tests/vision-runtime-performance.test.js tests/vision-background-benchmark.test.js tests/vision-image-input-verdict.test.js",
98
98
  "test:session": "node --test tests/session-vision-state.test.js tests/session-vision-state-integration.test.js tests/session-vision-policy.test.js tests/session-vision-delegation.test.js tests/session-vision-delegation-boundary.test.js tests/subagent-vision-inheritance-characterization.test.js tests/subagent-vision-runtime-integration.test.js tests/subagent-vision-cold-resume.test.js tests/session-vision-policy-domain.test.js tests/replay-delegation.test.js tests/legacy-session-repair.test.js tests/session-repair-v2.test.js tests/issue-276-session-image-ownership.test.js",
99
99
  "test:resources": "node --test tests/artifact-path-security.test.js tests/image-resource-governor.test.js tests/resource-retention-lifecycle.test.js tests/pixel-diff-stream.test.js tests/large-image-resource-integration.test.js tests/qa-turn-budget-cancellation.test.js tests/qa-cancellation-publication.test.js",
100
100
  "test:compat": "node --test tests/adapter-prepare-call-compat.test.js tests/attachment-admission-policy.test.js tests/dsh-host-compat.test.js tests/http-compat.test.js tests/pi-ai-bridge-wire-compat.test.js tests/fetch-wrapper-lifecycle.test.js tests/fetch-wrapper-composition.test.js tests/native-image-coexistence.test.js tests/tesseract-node24-boot.test.js tests/dsh-host-capabilities.test.js",
101
101
  "test:web": "node --test tests/alpha1-browser-lifecycle-integration.test.js tests/issue-367-remote-session-inject.test.js tests/vision-mode-toggle-injection.test.js tests/client.test.js tests/client-presentation-boundary.test.js tests/clipboard-image-paste-compat.test.js tests/settings-ia-client-prelude.test.js tests/settings-ia-acceptance-regression.test.js tests/remote-settings-bridge.test.js tests/remote-settings-v2-contract.test.js tests/local-remote-settings-permission.test.js tests/v2-settings-ia-integration.test.js tests/logging-ui.test.js tests/dev-staged-build.test.js tests/dev-web-reload.test.js",
102
- "test:contract": "node --test tests/dsh-alpha-pin.test.js tests/native-plugin-icons.test.js tests/manifest-dependencies.test.js tests/bundle-defaults.test.js tests/zero-regression-gate.test.js tests/issue-289-native-nonintervention.test.js tests/issue-374-delegated-call-config.test.js tests/runtime-boundary-fixes.test.js tests/security-adversarial-fuzz-contract.test.js tests/runtime-i18n.test.js tests/adapter-prepare-call-compat.test.js tests/dsh-host-compat.test.js tests/attachment-admission-policy.test.js tests/dsh-host-capabilities.test.js tests/doctor-host-capabilities.test.js tests/structured-bootstrap.test.js tests/structured-bootstrap-gate.test.js",
102
+ "test:contract": "node --test tests/dsh-alpha-pin.test.js tests/dsh-rc1-pin.test.js tests/agent-prestep-model-routing.test.js tests/native-plugin-icons.test.js tests/manifest-dependencies.test.js tests/bundle-defaults.test.js tests/zero-regression-gate.test.js tests/issue-289-native-nonintervention.test.js tests/issue-374-delegated-call-config.test.js tests/runtime-boundary-fixes.test.js tests/security-adversarial-fuzz-contract.test.js tests/runtime-i18n.test.js tests/adapter-prepare-call-compat.test.js tests/dsh-host-compat.test.js tests/attachment-admission-policy.test.js tests/dsh-host-capabilities.test.js tests/doctor-host-capabilities.test.js tests/structured-bootstrap.test.js tests/structured-bootstrap-gate.test.js",
103
103
  "test:grounding": "node --test tests/grounding-coordinate-frame.test.js tests/grounding-coordinate-runtime.test.js tests/vision-capability-grounding-proof-contract.test.js",
104
104
  "test:stress": "node scripts/image-resource-stress.mjs && node --test tests/large-image-resource-integration.test.js tests/resource-retention-lifecycle.test.js",
105
105
  "test:adversarial-fuzz": "node scripts/security-adversarial-fuzz.mjs",