dsh-vision-router 3.1.3 → 3.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/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.3 release candidate:** Fix optional dynamic image→text model routing on DSH 0.2.2-rc.1 by selecting models before Agent pre-step; preserve the default tool-only mode and legacy Host behavior. RC1 requires Node >=24.9; small-context models may need Host compaction headroom configuration for model switching. Update the CI-only HOL scanner pin without changing security thresholds. See [v3.1.3 notes](docs/releases/v3.1.3.md). Verify publication through [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) or npm.
25
+ > **v3.1.5 stability patch:** Bound canceled visual streams and empty-result caching (#798–#799), preserve fallback time across multiple backends (#800), classify and bound repeated HTTP 5xx failures including silent OCR/grounding transports (#804, #805, #810), fix picker-selected visual model dispatch (#801), correct misleading progressive Vision activation messages across deferred Host Fibers (#809), and add read-only Host-core dependency warnings (#802/#797). **The original #791 550/503 and #792 Windows screenshot remain unverified field incidents.** No settings, permission, privacy or Node/DSH support-floor change. See [v3.1.5 notes](docs/releases/v3.1.5.md). Confirm publication at [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) or npm.
26
26
 
27
27
  ## Start here
28
28
 
package/README.zh.md CHANGED
@@ -22,7 +22,7 @@
22
22
  > **默认配置会让数据出网。** 使用云端视觉模型时,Vision Router 会将图片(或由它裁剪出的局部)、识图提示词及相关请求元数据发送给对应供应商。新安装默认开启 OVHcloud 匿名视觉兜底,因此“免费”和“免 Key”不等于离线。涉密、涉案、内部或其他受限材料请勿使用云端链路。详见[数据流向与严格纯本地配置](#数据流向与严格纯本地配置)。
23
23
 
24
24
  > [!WARNING]
25
- > **v3.1.3 候选版更新说明:** 修复 DSH 0.2.2-rc.1 下可选的图片轮次动态模型切换与后续纯文本回切问题,模型选择提前到 Agent pre-step 之前;默认工具识图模式及旧版 Host 兼容行为不变。RC1 本身要求 Node ≥24.9;上下文窗口较小的模型在跨模型切换时可能需要调整 Host 压缩预留量。同步更新 CI 专用安全扫描器,不降低安全门槛。详见[v3.1.3 更新说明](docs/releases/v3.1.3.md)。正式可安装版本以 [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) 或 npm 为准。
25
+ > **v3.1.5 稳定性补丁:** 修复视觉流停止卡住与空结果缓存(#798–#799)、多模型回退预算耗尽(#800)、连续 HTTP 5xx 与无响应 OCR/定位回退无法及时结束(#804、#805、#810)、视觉复合模型分发错误(#801)、渐进式视觉工具已挂载却错误提示不可用(#809);doctor 增加 Host 核心依赖只读风险提示(#802/#797)。**#791 原用户 550/503 来源和 #792 Windows 启动截图根因仍未确认。** 不更改设置、权限、隐私策略或 Node/DSH 支持下限。详见 [v3.1.5 更新说明](docs/releases/v3.1.5.md),是否正式发布以 [GitHub Releases](https://github.com/ysr666/dsh-vision-router/releases/latest) 或 npm 为准。
26
26
 
27
27
  ## 先用起来
28
28
 
@@ -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` 并根据环境重载;排错前备份配置,不要求删除聊天记录。
@@ -0,0 +1,27 @@
1
+ # v3.1.5 — Vision reliability and model routing / 视觉稳定性与模型路由
2
+
3
+ **Publication status / 发布状态:** This document describes the v3.1.5 source contents; publication is proven only by a matching immutable GitHub Release, npm tarball and provenance from the protected Release workflow. Before that verification it is a candidate, not a released artifact. / 本文描述 v3.1.5 的源代码内容;只有受保护工作流形成并验证对应的不可变 GitHub Release、npm 包体及来源证明,才算正式发布。在验收完成之前仅为候选代码。
4
+
5
+ ## Runtime fixes / 运行时修复
6
+
7
+ - **#798: responsive cancellation / 取消后及时结束。** Vision Chain, direct `vision-http` and DVR-owned transparent adapters now bound waits on noncooperative visual iterators and cap abort cleanup at 1 second. Empty/whitespace/JSON-null answers are no longer cached as valid recognition. / 识图流遇到不响应取消的后端时不再无限等待;空白或 JSON 空结果不再写入成功缓存。
8
+ - **#799: cancellation is not backend failure / 主动取消不触发后端熔断。** A user/Host abort no longer records a provider failure in the breaker or turn-scoped memory. Actual HTTP 550/503 and timeouts retain failure classification. / 主动停止不会污染本轮后端故障记忆,真实错误处理规则保持不变。
9
+ - **#800: fair fallback budgets / 备用模型保留超时预算。** For multiple visual backends, `vision_describe`, vision OCR and opt-in whole-turn remote Vision Chain give later candidates a bounded opportunity after an earlier model hangs. Slow single-provider success and text-only routing preserve existing timeouts. / 前一个识图模型卡住时仍可尝试后续健康模型,覆盖视觉 OCR 和整轮视觉路由,不无故缩短单模型与纯文本超时。
10
+ - **#801: injected composite model dispatch / 注入模型正确分发。** A model-picker composite visual entry matching a live configured routing pair is dispatched through the registered `vision-chain`, with image blocks preserved, rather than sent as a foreign model ID to `deepseek-official`. Ordinary DeepSeek mirror models remain unchanged. / 模型列表中的有效视觉复合模型走实际视觉链,普通 DeepSeek 模型仍使用原委托路径。
11
+ - **#804 and #805: bounded server-error recovery / 有界服务端故障恢复。** Repeated HTTP 5xx failures, including status codes exposed as unbranded adapter text, no longer allow a silent vision fallback to consume the full request budget. / 连续 5xx 错误和不响应取消的视觉兜底请求会有界结束,兼容仅通过异常文本报告状态码的适配器。
12
+ - **#810: OCR and grounding fallback recovery / OCR 与定位回退恢复。** The same timeout guard also covers `vision_ocr`, `vision_ground`, `vision_pixel_diff` and shared visual-evidence helpers. / OCR、视觉定位、像素比对等工具同样受有界回退保护。
13
+ - **#809: progressive mount status / 渐进式工具挂载状态。** Use the Core-owned deferred Host-Fiber mount state to distinguish tools that have actually mounted from an i18n proxy that missed registration. This corrects an erroneous “unavailable” message but does not establish the original macOS reporter’s Vision-ON `UNKNOWN_TOOL` failure was fully resolved. / 正确识别延迟 Host Fiber 已挂载的深看工具,修复误报不可用;原用户 macOS 工具不可见现场仍未证实恢复。
14
+
15
+ ## Offline doctor / 离线诊断
16
+
17
+ - **#802 / issue #797: potential Host-core shadowing / Host 核心依赖覆盖风险。** A bounded, read-only scan reports profile-local `@deepseek-ai/dsh-*` manifests and third-party plugins declaring direct runtime Host-core dependencies. Findings are **possible/unverified**, not proof of actual Host module resolution. No automatic removal or profile mutation. Shareable reports contain only safe counts, not package paths or raw configuration. / 只读有界检查可疑核心包及第三方运行时依赖,仅作未验证风险提示,不自动修改用户文件;可分享报告只输出安全统计。
18
+
19
+ ## Open user reports / 尚未确认的现场反馈
20
+
21
+ - **#791 remains open:** The original reporter's 550 → 503 source is unknown and their restored image recognition was achieved independently; the fixes above address separately reproduced bugs, not proven provenance of those errors. / 原用户 550、503 的供应商或 Host 来源尚不确定,不能声称本版已确认解决原始问题。
22
+ - **#792 remains open:** Windows Desktop raw JS/CSS display has no verified field root cause. The prior renderer regression gate and new doctor advisory do not prove it is fixed. / Windows Desktop 启动源码外露的现场根因未确认,不能将检测门禁或诊断告警当作已修复证据。
23
+ - No Settings migration, new runtime dependencies/providers, public API break, Node/DSH support floor rise, broader permissions, or change to the default cloud image-egress/privacy policy. / 不变更设置结构、运行时依赖、公共 API、最低支持窗口、权限和默认云端识图外发政策。
24
+
25
+ ## Upgrade / 升级
26
+
27
+ **Only after verified publication**, update through the existing DSH profile plugin manager or an explicit `dsh-vision-router@3.1.5` install. Back up configuration before plugin changes; preserve all session data. / **仅在确认正式发布后**,通过原有插件管理器或指定版本升级,不需要删除配置或聊天历史。
package/index.js CHANGED
@@ -40,6 +40,78 @@ 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
+
93
+ /**
94
+ * A third-party provider transport can ignore AbortSignal indefinitely.
95
+ * Bound the caller's wait independently from the transport's cooperation,
96
+ * while still passing the signal downstream so a real HTTP socket can close.
97
+ * The losing promise remains observed by Promise.race if it settles later.
98
+ */
99
+ async function awaitVisionBackendAttempt(signal, operation) {
100
+ if (!signal) return operation()
101
+ if (signal.aborted) throw signal.reason ?? new Error('vision backend attempt aborted')
102
+ let onAbort
103
+ const canceled = new Promise((_, reject) => {
104
+ onAbort = () => reject(signal.reason ?? new Error('vision backend attempt aborted'))
105
+ signal.addEventListener('abort', onAbort, { once: true })
106
+ if (signal.aborted) onAbort()
107
+ })
108
+ try {
109
+ return await Promise.race([Promise.resolve().then(operation), canceled])
110
+ } finally {
111
+ signal.removeEventListener('abort', onAbort)
112
+ }
113
+ }
114
+
43
115
  export * from './lib/vision-resilience.js'
44
116
 
45
117
  import z from '@deepseek-ai/schemastery'
@@ -411,6 +483,7 @@ import {
411
483
  DEFAULT_HTTP_PROVIDERS,
412
484
  httpProviderFallbackWeight,
413
485
  weightedFallbackBudget,
486
+ postServerOutageBudgetMs,
414
487
  localOnlyVisionEnabled,
415
488
  isLoopbackVisionBaseURL,
416
489
  localOllamaProvidersOf,
@@ -1084,6 +1157,15 @@ export function apply(ctx, config = {}, runtime = {}) {
1084
1157
  return undefined
1085
1158
  }
1086
1159
  }
1160
+ const officialStream = createWrapperStreamBody(ctx, {
1161
+ imageMemory,
1162
+ delegateProvider: wrapperDelegateRoute,
1163
+ instantLocal: instantLocalProvider,
1164
+ instantLocalStyle,
1165
+ instantLocalTimeoutMs: timeoutMs,
1166
+ instantLocalMaxPixels,
1167
+ providerTransport,
1168
+ }).stream
1087
1169
  wrapperAdapter = {
1088
1170
  providerInfo(provider) {
1089
1171
  return { id: provider, name: 'DeepSeek + 自动识图' }
@@ -1180,15 +1262,25 @@ export function apply(ctx, config = {}, runtime = {}) {
1180
1262
  inputModalities: ['text', 'image'],
1181
1263
  }
1182
1264
  },
1183
- ...createWrapperStreamBody(ctx, {
1184
- imageMemory,
1185
- delegateProvider: wrapperDelegateRoute,
1186
- instantLocal: instantLocalProvider,
1187
- instantLocalStyle,
1188
- instantLocalTimeoutMs: timeoutMs,
1189
- instantLocalMaxPixels,
1190
- providerTransport,
1191
- }),
1265
+ // The DeepSeek wrapper also advertises composite vision-chain entries
1266
+ // while whole-turn routing is enabled. Those entries are NOT DeepSeek
1267
+ // model ids: dispatching them through the normal wrapper stream sends
1268
+ // e.g. "remote-vlm/qwen-vl" to deepseek-official and always fails.
1269
+ // Delegate only exact live routing pairs to the registered vision
1270
+ // chain. The regular DeepSeek mirror keeps its normal text/image bridge.
1271
+ async *stream(options) {
1272
+ const isRoutingPair = routingEnabled() && routingPairs().some(
1273
+ (pair) => `${pair.provider}/${pair.model}` === options?.model
1274
+ && adapterAvailable(ctx.llm, pair.provider),
1275
+ )
1276
+ if (isRoutingPair) {
1277
+ // Keep the image blocks intact; the Host must route this
1278
+ // image-capable model through the actual visual chain.
1279
+ yield* ctx.llm.stream({ ...options, provider: chainRoute() })
1280
+ return
1281
+ }
1282
+ yield* officialStream(options)
1283
+ },
1192
1284
  }
1193
1285
  }
1194
1286
 
@@ -1942,7 +2034,6 @@ export function apply(ctx, config = {}, runtime = {}) {
1942
2034
  }
1943
2035
  if (imageIds.length > 0) break
1944
2036
  }
1945
- let finalText = ''
1946
2037
  const chainPairs = routingPairs()
1947
2038
  const chainHttpEntries = new Map(httpEntries().map((entry) => [entry.id, entry]))
1948
2039
  // Fit the conversation into the target model's context window: a long
@@ -1968,7 +2059,19 @@ export function apply(ctx, config = {}, runtime = {}) {
1968
2059
  (sum, pair) => sum + routingPairWeight(pair, chainHttpEntries),
1969
2060
  0,
1970
2061
  )
2062
+ // Streaming a failed candidate is irreversible for the Host. When a
2063
+ // fallback exists, stage its events until a successful finish so a
2064
+ // second backend never appends to a broken first answer. Single-route
2065
+ // and legacy text-only streams keep their existing streaming UX.
2066
+ const holdCandidateEvents = imageIds.length > 0 && chainPairs.length > 1
2067
+ const maxHeldEventBytes = 8 * 1024 * 1024
2068
+ const maxHeldEvents = 32768
1971
2069
  for (const pair of chainPairs) {
2070
+ // Keep result text isolated by candidate; a failed stream's partial
2071
+ // output must never count as recognition by the next backend.
2072
+ let finalText = ''
2073
+ const heldEvents = []
2074
+ let heldBytes = 0
1972
2075
  const candidateWeight = routingPairWeight(pair, chainHttpEntries)
1973
2076
  const weightAtStart = Math.max(candidateWeight, remainingWeight)
1974
2077
  remainingWeight = Math.max(0, remainingWeight - candidateWeight)
@@ -2035,11 +2138,14 @@ export function apply(ctx, config = {}, runtime = {}) {
2035
2138
  let succeeded = false
2036
2139
  let failed = false
2037
2140
  let failMessage = 'unknown error'
2141
+ let failCode
2038
2142
  try {
2039
- // Local backends get an independent anti-hang budget: a hung local
2040
- // service must not consume the whole deadline and starve the
2041
- // existing chain. Regular providers keep main's per-call timeout.
2042
- const attemptBudgetMs = isLocalBackendPair(pair)
2143
+ // In an image-bearing whole-turn chain, every candidate (remote
2144
+ // included) must leave a real share of the deadline for fallbacks.
2145
+ // Keep the existing local-backend guard and preserve text-only
2146
+ // remote routes' original per-call timeout semantics.
2147
+ const fairShare = imageIds.length > 0 || isLocalBackendPair(pair)
2148
+ const attemptBudgetMs = fairShare
2043
2149
  ? weightedFallbackBudget(
2044
2150
  deadline.remaining(),
2045
2151
  timeoutMs(),
@@ -2086,7 +2192,7 @@ export function apply(ctx, config = {}, runtime = {}) {
2086
2192
  }
2087
2193
  yield { type: 'finish', reason: { kind: 'stop' } }
2088
2194
  }
2089
- for await (const chunk of streamPair()) {
2195
+ for await (const chunk of streamVisionWithAbort(streamPair(), attemptSignal)) {
2090
2196
  if (chunk && chunk.type === 'finish') {
2091
2197
  const kind = chunk.reason && chunk.reason.kind
2092
2198
  if (kind === 'error' || kind === 'aborted') {
@@ -2095,7 +2201,16 @@ export function apply(ctx, config = {}, runtime = {}) {
2095
2201
  failed = true
2096
2202
  break
2097
2203
  }
2098
- // 'stop' / 'max-tokens' / 'tool-calls' are success.
2204
+ // Tool-call handoffs may legitimately have no text, but a
2205
+ // completed recognition with no text is not a usable answer.
2206
+ // It must not suppress fallback or cache an earlier failed
2207
+ // candidate's partial output as this backend's result.
2208
+ if (imageIds.length > 0 && (kind === 'stop' || kind === 'max-tokens') && finalText.trim() === '') {
2209
+ failed = true
2210
+ failCode = 'EMPTY_RESPONSE'
2211
+ failMessage = 'vision chain backend returned empty content'
2212
+ break
2213
+ }
2099
2214
  succeeded = true
2100
2215
  // 视觉链成功留痕:谁识别了几张图、写入跨轮缓存——排障时
2101
2216
  // "这张图的描述是谁生成的"一眼可查(原版此处静默)。
@@ -2108,18 +2223,41 @@ export function apply(ctx, config = {}, runtime = {}) {
2108
2223
  const record = finalText.trim()
2109
2224
  for (const id of imageIds) imageMemorySet(imageMemory, id, record)
2110
2225
  }
2226
+ if (holdCandidateEvents) {
2227
+ for (const event of heldEvents) yield event
2228
+ }
2111
2229
  yield chunk
2112
2230
  break
2113
2231
  }
2114
2232
  if (chunk && typeof chunk.text === 'string') finalText += chunk.text
2115
- yield chunk
2233
+ if (holdCandidateEvents) {
2234
+ const bytes = Buffer.byteLength(JSON.stringify(chunk) ?? '', 'utf8')
2235
+ if (heldEvents.length >= maxHeldEvents || heldBytes + bytes > maxHeldEventBytes) {
2236
+ failCode = 'VISION_CHAIN_BUFFER_LIMIT'
2237
+ throw new Error('vision chain candidate output exceeded safe fallback buffer limit')
2238
+ }
2239
+ heldEvents.push(chunk)
2240
+ heldBytes += bytes
2241
+ } else {
2242
+ yield chunk
2243
+ }
2244
+ }
2245
+ if (!succeeded && !failed && imageIds.length > 0) {
2246
+ // An adapter can end iteration without emitting the mandatory
2247
+ // terminal finish. Do not silently close the Agent stream and
2248
+ // strand a later model that could recover the visual answer.
2249
+ failed = true
2250
+ failCode = 'EMPTY_RESPONSE'
2251
+ failMessage = 'vision chain backend ended without a finish event'
2116
2252
  }
2117
2253
  } catch (error) {
2118
2254
  failed = true
2119
2255
  failMessage = error && error.message ? error.message : String(error)
2120
2256
  }
2121
2257
  if (failed) {
2122
- const classification = classifyVisionFailure(failMessage)
2258
+ const classification = classifyVisionFailure(
2259
+ failCode ? { code: failCode, message: failMessage } : failMessage,
2260
+ )
2123
2261
  visionBreaker.record(backendKey, fingerprint, classification, 'chain')
2124
2262
  failures.push(`${pair.provider}/${pair.model}: ${failMessage}`)
2125
2263
  ctx.logger?.warn('vision-router: chain fallback (%s) -> %s', classification.kind, failMessage)
@@ -2139,6 +2277,50 @@ export function apply(ctx, config = {}, runtime = {}) {
2139
2277
  }
2140
2278
  },
2141
2279
  }
2280
+
2281
+ // The chain's own deadline starts after initial model-info preflight.
2282
+ // A noncooperative discovery/capability adapter can therefore keep the
2283
+ // entire Agent turn pending before the first streamed chunk. Protect the
2284
+ // COMPLETE image-bearing stream, not only individual model iterator.next()
2285
+ // calls. Text-only legacy routes retain their existing semantics.
2286
+ const innerChainStream = chainAdapter.stream
2287
+ chainAdapter.stream = async function* boundedVisionChainStream(options) {
2288
+ const imageBearing = collectImageBlocks(options?.messages ?? [])
2289
+ .some(({ block }) => !isOffloadedImageBlock(block))
2290
+ if (!imageBearing) {
2291
+ yield* innerChainStream.call(this, options)
2292
+ return
2293
+ }
2294
+ const budgetSignal = AbortSignal.timeout(visionTaskTimeoutMs())
2295
+ const signal = combineSignals(options?.signal, budgetSignal)
2296
+ try {
2297
+ for await (const chunk of streamVisionWithAbort(
2298
+ innerChainStream.call(this, { ...options, signal }),
2299
+ signal,
2300
+ )) {
2301
+ yield chunk
2302
+ // The Host only accepts one terminal event. Do not remain blocked in
2303
+ // a broken iterator's post-finish cleanup, or emit an error later.
2304
+ if (chunk?.type === 'finish') return
2305
+ }
2306
+ } catch (error) {
2307
+ if (!signal.aborted) throw error
2308
+ if (options?.signal?.aborted) {
2309
+ yield { type: 'finish', reason: { kind: 'aborted' } }
2310
+ return
2311
+ }
2312
+ yield {
2313
+ type: 'finish',
2314
+ reason: {
2315
+ kind: 'error',
2316
+ failure: {
2317
+ code: 'VISION_CHAIN_EXHAUSTED',
2318
+ message: 'vision task timed out before the model finished preparing or responding',
2319
+ },
2320
+ },
2321
+ }
2322
+ }
2323
+ }
2142
2324
  }
2143
2325
 
2144
2326
  // ── reactive routing mounts ────────────────────────────────────────────────
@@ -2860,6 +3042,7 @@ export function apply(ctx, config = {}, runtime = {}) {
2860
3042
  const errors = [...rejectedPairs]
2861
3043
  const attempted = []
2862
3044
  const primaryWeight = DEFAULT_HTTP_PROVIDERS.length
3045
+ let consecutiveServerFailures = 0
2863
3046
  let remainingWeight =
2864
3047
  usablePairs.length * primaryWeight +
2865
3048
  httpFallbacks.reduce(
@@ -2976,11 +3159,21 @@ ctx.logger?.info(
2976
3159
  if (cacheEnabled()) cache.set(key, text)
2977
3160
  return text
2978
3161
  }
2979
- const empty = '(the vision model returned empty content)'
2980
- if (cacheEnabled()) cache.set(key, empty)
2981
- return empty
3162
+ // A successfully transported but empty answer is not visual evidence.
3163
+ // In particular, reasoning models can exhaust their output budget
3164
+ // before emitting any content. Never cache a fabricated success or
3165
+ // suppress a healthy later backend in the configured chain.
3166
+ const empty = new Error('vision_describe backend returned empty content')
3167
+ empty.code = 'EMPTY_RESPONSE'
3168
+ throw empty
2982
3169
  } catch (error) {
3170
+ // A user/Host cancel is not a backend outage. Otherwise the
3171
+ // canceled attempt poisons this turn's breaker/failure memory and
3172
+ // a healthy retry returns BACKEND_UNAVAILABLE_THIS_TURN.
3173
+ throwIfVisionTaskAborted(currentVisionTurnBudgetSignal(), error)
2983
3174
  const classification = classifyVisionFailure(error)
3175
+ consecutiveServerFailures = classification.kind === VISION_FAILURE_KINDS.SERVER
3176
+ ? consecutiveServerFailures + 1 : 0
2984
3177
  visionBreaker.record(backendKey, fingerprint, classification, scope)
2985
3178
  visionTurnMemory.record(scope, backendKey, classification.kind)
2986
3179
  attempted.push({
@@ -3044,13 +3237,22 @@ ctx.logger?.info(
3044
3237
  [{ role: 'user', content: openAIBlocks }],
3045
3238
  promptText,
3046
3239
  ).messages
3240
+ // A stalled HTTP fallback must leave a real share of the shared
3241
+ // turn deadline for later configured providers. The weighting
3242
+ // preserves a full single-provider budget and prioritizes
3243
+ // user-configured providers over built-in anonymous fallbacks.
3244
+ const attemptBudgetMs = postServerOutageBudgetMs(
3245
+ weightedFallbackBudget(deadline.remaining(), timeoutMs(), candidateWeight, weightAtStart),
3246
+ visionTaskTimeoutMs(),
3247
+ consecutiveServerFailures,
3248
+ )
3047
3249
  const attemptSignal = combineSignals(
3048
3250
  currentVisionTurnBudgetSignal(),
3049
3251
  deadline.signal(),
3050
- AbortSignal.timeout(timeoutMs()),
3252
+ AbortSignal.timeout(attemptBudgetMs),
3051
3253
  )
3052
3254
  const askHttp = async (correction) => {
3053
- const answer = await callOpenAIWithProviderTransport(
3255
+ const answer = await awaitVisionBackendAttempt(attemptSignal, () => callOpenAIWithProviderTransport(
3054
3256
  provider,
3055
3257
  correction === undefined
3056
3258
  ? openAIBaseMessages
@@ -3064,7 +3266,7 @@ ctx.logger?.info(
3064
3266
  sessionId,
3065
3267
  resolveCredential,
3066
3268
  },
3067
- )
3269
+ ))
3068
3270
  return answer
3069
3271
  }
3070
3272
  let text = await askHttp(undefined)
@@ -3107,8 +3309,19 @@ ctx.logger?.info(
3107
3309
  if (cacheEnabled()) cache.set(key, text)
3108
3310
  return text
3109
3311
  }
3312
+ // Mirror the adapter-backed branch: this HTTP response is a
3313
+ // backend failure, not a valid zero-length recognition result.
3314
+ const empty = new Error(`http provider "${provider.name}": vision response was empty`)
3315
+ empty.code = 'EMPTY_RESPONSE'
3316
+ throw empty
3110
3317
  } catch (error) {
3318
+ // A user/Host cancel is not a backend outage. Otherwise the
3319
+ // canceled attempt poisons this turn's breaker/failure memory and
3320
+ // a healthy retry returns BACKEND_UNAVAILABLE_THIS_TURN.
3321
+ throwIfVisionTaskAborted(currentVisionTurnBudgetSignal(), error)
3111
3322
  const classification = classifyVisionFailure(error)
3323
+ consecutiveServerFailures = classification.kind === VISION_FAILURE_KINDS.SERVER
3324
+ ? consecutiveServerFailures + 1 : 0
3112
3325
  visionBreaker.record(backendKey, fingerprint, classification, scope)
3113
3326
  visionTurnMemory.record(scope, backendKey, classification.kind)
3114
3327
  attempted.push({
@@ -3497,6 +3710,7 @@ ctx.logger?.info(
3497
3710
  (sum, provider) => sum + httpProviderFallbackWeight(provider),
3498
3711
  0,
3499
3712
  )
3713
+ let consecutiveServerFailures = 0
3500
3714
  const pairCapabilities = new Map()
3501
3715
  for (const pair of pairs()) {
3502
3716
  if (!pair || pair.provider === HTTP_ROUTE) continue
@@ -3582,6 +3796,8 @@ ctx.logger?.info(
3582
3796
  } catch (error) {
3583
3797
  throwIfVisionTaskAborted(taskSignal, error)
3584
3798
  const classification = classifyVisionFailure(error)
3799
+ consecutiveServerFailures = classification.kind === VISION_FAILURE_KINDS.SERVER
3800
+ ? consecutiveServerFailures + 1 : 0
3585
3801
  visionBreaker.record(pairKey, fingerprint, classification, scope)
3586
3802
  recordFailure(pairKey, classification, error && error.message ? error.message : String(error))
3587
3803
  }
@@ -3609,25 +3825,43 @@ ctx.logger?.info(
3609
3825
  continue
3610
3826
  }
3611
3827
  try {
3612
- const text = await callOpenAIWithProviderTransport(
3828
+ // Shared across OCR, grounding and visual evidence helpers: a
3829
+ // hanging HTTP model must leave time for the next candidate. A
3830
+ // transport that ignores AbortSignal must not outlive its share
3831
+ // either, and after two consecutive server failures the recovery
3832
+ // tail is tightened like the vision_describe walk.
3833
+ const attemptBudgetMs = postServerOutageBudgetMs(
3834
+ weightedFallbackBudget(
3835
+ deadline.remaining(),
3836
+ timeoutMs(),
3837
+ candidateWeight,
3838
+ weightAtStart,
3839
+ ),
3840
+ visionTaskTimeoutMs(),
3841
+ consecutiveServerFailures,
3842
+ )
3843
+ const attemptSignal = combineSignals(
3844
+ taskSignal,
3845
+ deadline.signal(),
3846
+ AbortSignal.timeout(attemptBudgetMs),
3847
+ )
3848
+ const text = await awaitVisionBackendAttempt(attemptSignal, () => callOpenAIWithProviderTransport(
3613
3849
  provider,
3614
3850
  [{ role: 'user', content: [...httpContent, { type: 'text', text: instruction }] }],
3615
3851
  {
3616
3852
  maxTokens: provider.maxTokens ?? 4096,
3617
- signal: combineSignals(
3618
- taskSignal,
3619
- deadline.signal(),
3620
- AbortSignal.timeout(timeoutMs()),
3621
- ),
3853
+ signal: attemptSignal,
3622
3854
  sessionId: options.sessionId,
3623
3855
  resolveCredential,
3624
3856
  },
3625
- )
3857
+ ))
3626
3858
  throwIfVisionTaskAborted(taskSignal)
3627
3859
  if (text && text.trim() !== '') return { ok: true, text: text.trim() }
3628
3860
  } catch (error) {
3629
3861
  throwIfVisionTaskAborted(taskSignal, error)
3630
3862
  const classification = classifyVisionFailure(error)
3863
+ consecutiveServerFailures = classification.kind === VISION_FAILURE_KINDS.SERVER
3864
+ ? consecutiveServerFailures + 1 : 0
3631
3865
  visionBreaker.record(backendKey, fingerprint, classification, scope)
3632
3866
  recordFailure(backendKey, classification, error && error.message ? error.message : String(error))
3633
3867
  }
@@ -4776,6 +5010,13 @@ ctx.logger?.info(
4776
5010
  )
4777
5011
 
4778
5012
  if (progressive) {
5013
+ // Delayed Cordis Fiber registrations may run outside the i18n decorator's
5014
+ // AsyncLocalStorage scope. Report the Core-owned mount state directly
5015
+ // rather than inferring success from which proxy observed registration.
5016
+ const activationExecute = async () => activateDeepTools()
5017
+ Object.defineProperty(activationExecute, Symbol.for('dsh-vision-router.deep-tools-mounted'), {
5018
+ value: () => deepActive,
5019
+ })
4779
5020
  ctx.effect(
4780
5021
  () =>
4781
5022
  ctx.tools.register({
@@ -4787,9 +5028,7 @@ ctx.logger?.info(
4787
5028
  'automatically on image turns; call this only when you need them on a text-only turn.',
4788
5029
  parameters: { type: 'object', properties: {}, additionalProperties: false },
4789
5030
  output: stringOutput,
4790
- async execute() {
4791
- return activateDeepTools()
4792
- },
5031
+ execute: activationExecute,
4793
5032
  }),
4794
5033
  'vision-router: progressive bootstrap tool',
4795
5034
  )
@@ -1819,6 +1819,24 @@ export function weightedFallbackBudget(
1819
1819
  return Math.max(1, Math.min(remaining, callLimit, share))
1820
1820
  }
1821
1821
 
1822
+ /**
1823
+ * After two consecutive server-side 5xx failures, a later HTTP backend that
1824
+ * never responds must not consume the full default 120-second task. Keep a
1825
+ * full budget for normal single/first-provider calls and for recoverable
1826
+ * one-off failures; only tighten the post-outage recovery tail.
1827
+ *
1828
+ * With the default task timeout, this limits a silent third HTTP backend to
1829
+ * 20 seconds. Explicit smaller timeouts remain authoritative.
1830
+ */
1831
+ export function postServerOutageBudgetMs(attemptBudgetMs, taskTimeoutMs, consecutiveServerFailures) {
1832
+ if (!Number.isInteger(consecutiveServerFailures) || consecutiveServerFailures < 2) return attemptBudgetMs
1833
+ const taskBudget = Math.max(1, Math.floor(Number(taskTimeoutMs) || 1))
1834
+ // A deliberately extended task allowance takes precedence over this
1835
+ // default-only outage recovery policy (the regular per-call limit remains).
1836
+ if (taskBudget > 120_000) return attemptBudgetMs
1837
+ return Math.max(1, Math.min(attemptBudgetMs, 20_000, Math.floor(taskBudget / 4)))
1838
+ }
1839
+
1822
1840
  /**
1823
1841
  * dsh-vision 并入:本地 Ollama 视觉后端条目。
1824
1842
  * 启用时返回单个 local-ollama provider(OpenAI 兼容、无 Key)。
package/lib/doctor-cli.js CHANGED
@@ -129,6 +129,7 @@ function formatIssueTemplate(report) {
129
129
  `- Node: ${version(platform.node)} (${platform.nodeSupported ? 'supported' : 'outside or unverified support window'})`,
130
130
  `- Vision Router profiles: ${applicable.length} applicable; ${failed.length} installation/problem profile(s)`,
131
131
  `- Install modes: ${modes}`,
132
+ `- Offline Host core advisories: ${applicable.filter((profile) => (profile.hostCore?.advisoryCount ?? 0) > 0).length} profile(s), unverified (no Host resolution test)`,
132
133
  `- Runtime: ${runtimeState}`,
133
134
  `- Settings save failures: ${number(report.log?.currentSettingsFailureCount)} current / ${number(report.log?.historicalSettingsFailureCount)} historical`,
134
135
  `- Known session issues: ${sessionState}`,
@@ -341,6 +341,10 @@ export function supportReport({ profileReport, runtime, platform, sessions }) {
341
341
  pluginBundle: item.pluginBundle,
342
342
  installedVersion: item.installedPlugin?.version,
343
343
  installation: safeInstallation(item.installation),
344
+ hostCore: {
345
+ advisoryCount: item.hostCore?.advisories?.length ?? 0,
346
+ scanLimited: item.hostCore?.scanLimited === true,
347
+ },
344
348
  workspacePinnedCount: item.workspace?.pinned?.length ?? 0,
345
349
  patch: item.patch ? {
346
350
  visionRouterRows: item.patch.visionRouterRows,
package/lib/doctor.js CHANGED
@@ -1,4 +1,4 @@
1
- import { closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs'
1
+ import { closeSync, existsSync, fstatSync, openSync, opendirSync, readFileSync, readSync, readdirSync, realpathSync, statSync, writeFileSync } from 'node:fs'
2
2
  import { homedir } from 'node:os'
3
3
  import path from 'node:path'
4
4
  import { inspectCoexistingVisionPlugins } from './profile-pnpm-diagnostics.js'
@@ -60,6 +60,74 @@ function readJsonIfPresent(filePath, maxBytes = INSTALLED_MANIFEST_MAX_BYTES) {
60
60
  }
61
61
  }
62
62
 
63
+
64
+ const HOST_CORE_PACKAGE = /^@deepseek-ai\/dsh-[a-z0-9][a-z0-9._-]*$/
65
+ const PROFILE_PACKAGE = /^(?:@[a-z0-9._-]+\/)?[a-z0-9][a-z0-9._-]*$/
66
+ const HOST_CORE_SCAN_MAX = 64
67
+
68
+ function readBoundedProfilePackage(profileDir, packageName) {
69
+ if (!PROFILE_PACKAGE.test(packageName) || packageName.length > 100) return undefined
70
+ try {
71
+ const root = realpathSync(profileDir)
72
+ const file = path.join(profileDir, 'node_modules', packageName, 'package.json')
73
+ // Keep the offline probe inside the requested profile, even for pnpm links.
74
+ if (!realpathSync(file).startsWith(root + path.sep)) return undefined
75
+ if (!statSync(file).isFile()) return undefined
76
+ const manifest = readJsonIfPresent(file, 64 * 1024)
77
+ return manifest?.name === packageName ? manifest : undefined
78
+ } catch {
79
+ return undefined
80
+ }
81
+ }
82
+
83
+ /** Advisory only: local package presence is not proof of Host module resolution. */
84
+ export function inspectProfileHostCore(profileDir, manifest) {
85
+ const advisories = []
86
+ let scanLimited = false
87
+ const add = (item) => {
88
+ if (advisories.length >= 16) { scanLimited = true; return }
89
+ advisories.push({ ...item, verification: 'unverified' })
90
+ }
91
+ try {
92
+ const scope = path.join(profileDir, 'node_modules', '@deepseek-ai')
93
+ if (!realpathSync(scope).startsWith(realpathSync(profileDir) + path.sep)) {
94
+ throw new Error('outside profile scope')
95
+ }
96
+ const dir = opendirSync(scope)
97
+ try {
98
+ let count = 0
99
+ let entry
100
+ while (count < HOST_CORE_SCAN_MAX && (entry = dir.readSync()) !== null) {
101
+ count += 1
102
+ const packageName = '@deepseek-ai/' + entry.name
103
+ if (!HOST_CORE_PACKAGE.test(packageName) || packageName.length > 100) continue
104
+ const pkg = readBoundedProfilePackage(profileDir, packageName)
105
+ if (pkg) {
106
+ const version = typeof pkg.version === 'string' && pkg.version.length <= 64
107
+ && /^v?\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(pkg.version) ? pkg.version : undefined
108
+ add({ kind: 'profile-local-host-core', packageName, version })
109
+ }
110
+ }
111
+ if (count === HOST_CORE_SCAN_MAX && dir.readSync() !== null) scanLimited = true
112
+ } finally { dir.closeSync() }
113
+ } catch {
114
+ // Missing or unreadable scope directory is not positive evidence.
115
+ }
116
+ const dependencies = manifest?.dependencies
117
+ const names = dependencies && typeof dependencies === 'object' && !Array.isArray(dependencies)
118
+ ? Object.keys(dependencies).filter((name) => PROFILE_PACKAGE.test(name) && name.length <= 100
119
+ && name !== PLUGIN_NAME && !name.startsWith('@deepseek-ai/')) : []
120
+ if (names.length > HOST_CORE_SCAN_MAX) scanLimited = true
121
+ for (const pluginName of names.slice(0, HOST_CORE_SCAN_MAX)) {
122
+ const pkg = readBoundedProfilePackage(profileDir, pluginName)
123
+ const runtimeDeps = pkg?.dependencies
124
+ if (!runtimeDeps || typeof runtimeDeps !== 'object' || Array.isArray(runtimeDeps)) continue
125
+ const hostPackages = Object.keys(runtimeDeps).filter((name) => HOST_CORE_PACKAGE.test(name)).slice(0, 8)
126
+ if (hostPackages.length > 0) add({ kind: 'third-party-runtime-host-core', pluginName, hostPackages })
127
+ }
128
+ return { advisories, scanLimited }
129
+ }
130
+
63
131
  function dependencySpecKind(value) {
64
132
  if (typeof value !== 'string' || value.trim() === '') return undefined
65
133
  const spec = value.trim()
@@ -457,6 +525,19 @@ export function classifyProfileInstallation(profile, { requested = false } = {})
457
525
  if (profile?.patch?.disablesOfficialDeepSeek) {
458
526
  warnings.push('cordis.patch.yml statically disables llm-deepseek; legacy stealth patches can make the official model disappear when Vision Router is disabled')
459
527
  }
528
+ for (const item of profile?.hostCore?.advisories ?? []) {
529
+ if (item.kind === 'profile-local-host-core') {
530
+ warnings.push('Possible Host core shadowing (unverified): profile-local '
531
+ + item.packageName + (item.version ? '@' + item.version : '')
532
+ + '; check actual Host module resolution before changing dependencies')
533
+ } else if (item.kind === 'third-party-runtime-host-core') {
534
+ warnings.push('Third-party plugin ' + item.pluginName + ' declares DSH Host core runtime dependencies ('
535
+ + item.hostPackages.join(', ') + '); possible profile hoisting conflict, unverified')
536
+ }
537
+ }
538
+ if (profile?.hostCore?.scanLimited) {
539
+ warnings.push('Host core advisory scan reached its bounded inspection limit; results may be incomplete')
540
+ }
460
541
  return {
461
542
  applicable,
462
543
  mode,
@@ -583,6 +664,7 @@ export function doctorProfiles({ dshHome = resolveDshHome(), profile, fix = fals
583
664
  patch,
584
665
  installedPlugin,
585
666
  workspace,
667
+ hostCore: inspectProfileHostCore(profileDir),
586
668
  pluginBundleCount: 0,
587
669
  pluginBundle: false,
588
670
  }
@@ -597,6 +679,7 @@ export function doctorProfiles({ dshHome = resolveDshHome(), profile, fix = fals
597
679
  exists: true,
598
680
  ...manifestReport,
599
681
  coexistingVisionPlugins: manifestReport.validJson ? inspectCoexistingVisionPlugins(profileDir) : [],
682
+ hostCore: inspectProfileHostCore(profileDir, manifestReport.manifest),
600
683
  workspace,
601
684
  patch,
602
685
  installedPlugin,
@@ -5,6 +5,7 @@ import { captureFetchDelegate, installFetchWrapper } from './fetch-wrapper-lifec
5
5
  import { visionRouterMessageSource } from './session-message-source-compat.js'
6
6
 
7
7
  const PLUGIN_NAME = 'dsh-vision-router'
8
+ const DEEP_TOOL_MOUNT_PROBE = Symbol.for('dsh-vision-router.deep-tools-mounted')
8
9
  const DEEP_TOOL_NAMES = new Set([
9
10
  'vision_bootstrap',
10
11
  'vision_describe',
@@ -445,6 +446,16 @@ function addAutoMountReminder(decision, payload, i18n) {
445
446
  return decision && typeof decision === 'object' ? { ...decision, messages } : { messages }
446
447
  }
447
448
 
449
+ function deepToolsMounted(state) {
450
+ // The Core-owned probe is authoritative: registrations performed in a later
451
+ // Host Fiber phase need not pass through this locale-scoped tools proxy.
452
+ if (typeof state.activationStateProbe === 'function') {
453
+ try { return state.activationStateProbe() === true } catch { return false }
454
+ }
455
+ // Older direct boundary consumers do not supply the Core probe.
456
+ return state.deepActive === true
457
+ }
458
+
448
459
  function createToolBoundary(tools, i18n, liveConfig, state) {
449
460
  if (!objectLike(tools)) return tools
450
461
  return new Proxy(tools, {
@@ -460,13 +471,14 @@ function createToolBoundary(tools, i18n, liveConfig, state) {
460
471
  if (DEEP_TOOL_NAMES.has(def.name)) state.deepActive = true
461
472
  if (def.name === 'vision_activate' && typeof def.execute === 'function') {
462
473
  state.activationExecute = def.execute
474
+ state.activationStateProbe = def.execute[DEEP_TOOL_MOUNT_PROBE]
463
475
  const original = def.execute
464
476
  def = {
465
477
  ...def,
466
478
  async execute(args, exec) {
467
- const before = state.deepActive
479
+ const before = deepToolsMounted(state)
468
480
  await original(args, exec)
469
- const code = state.deepActive
481
+ const code = deepToolsMounted(state)
470
482
  ? before
471
483
  ? DEEP_TOOL_MOUNT_STATE.alreadyMounted
472
484
  : DEEP_TOOL_MOUNT_STATE.mounted
@@ -492,10 +504,10 @@ function createToolBoundary(tools, i18n, liveConfig, state) {
492
504
  }
493
505
 
494
506
  async function ensureDeepTools(state) {
495
- if (state.deepActive) return DEEP_TOOL_MOUNT_STATE.alreadyMounted
507
+ if (deepToolsMounted(state)) return DEEP_TOOL_MOUNT_STATE.alreadyMounted
496
508
  if (typeof state.activationExecute !== 'function') return DEEP_TOOL_MOUNT_STATE.unavailable
497
509
  await state.activationExecute({}, undefined)
498
- return state.deepActive ? DEEP_TOOL_MOUNT_STATE.mounted : DEEP_TOOL_MOUNT_STATE.unavailable
510
+ return deepToolsMounted(state) ? DEEP_TOOL_MOUNT_STATE.mounted : DEEP_TOOL_MOUNT_STATE.unavailable
499
511
  }
500
512
 
501
513
  function localizeRequestBody(value, i18n) {
@@ -566,6 +578,7 @@ export function installRuntimeI18nBoundary(ctx, config = {}) {
566
578
  const state = {
567
579
  deepActive: false,
568
580
  activationExecute: undefined,
581
+ activationStateProbe: undefined,
569
582
  autoMountNotified: false,
570
583
  }
571
584
  const contextCache = new WeakMap()
@@ -64,6 +64,46 @@ export function ensureSentencePunctuation(value) {
64
64
  const AUTH_PATTERNS = [/\b401\b/, /\b403\b/, /unauthorized/i, /invalid api[ -]?key/i, /forbidden/i, /authentication/i, /check the api key/i]
65
65
  const RATE_LIMIT_PATTERNS = [/\b429\b/, /rate.?limit/i, /quota temporarily/i, /too many requests/i]
66
66
  const TIMEOUT_PATTERNS = [/abort/i, /timeout/i, /etimedout/i, /timed ?out/i, /deadline exceeded/i]
67
+ // An adapter may throw plain Error("HTTP 550 ...") instead of retaining
68
+ // Response.status. Parse explicit 5xx notation (including 520/550) without
69
+ // a backtracking regex, scanning only the first 4096 untrusted characters.
70
+ const HTTP_STATUS_PREFIXES = [
71
+ 'request failed with status code', 'response failed with status code',
72
+ 'request failed with status', 'response failed with status',
73
+ 'http/1.0', 'http/1.1', 'http/2.0', 'http/2', 'http/3',
74
+ 'http status code', 'http status', 'http error', 'http response',
75
+ 'http', 'status code', 'status',
76
+ ]
77
+ function isAsciiWord(code) {
78
+ return (code >= 48 && code <= 57) || (code >= 97 && code <= 122) || code === 95
79
+ }
80
+ function extractExplicitHttp5xxStatus(message) {
81
+ const text = message.slice(0, 4096).toLowerCase()
82
+ const isSpace = (ch) => ch === ' ' || ch === '\t' || ch === '\r' || ch === '\n'
83
+ const skipSpace = (start) => {
84
+ let pos = start
85
+ while (pos < text.length && pos - start < 16 && isSpace(text[pos])) pos += 1
86
+ return pos
87
+ }
88
+ for (let i = 0; i < text.length; i += 1) {
89
+ if (text[i] !== 'h' && text[i] !== 'r' && text[i] !== 's'
90
+ || isAsciiWord(text.charCodeAt(i - 1))) continue
91
+ for (const prefix of HTTP_STATUS_PREFIXES) {
92
+ if (!text.startsWith(prefix, i) || isAsciiWord(text.charCodeAt(i + prefix.length))) continue
93
+ let pos = skipSpace(i + prefix.length)
94
+ if (text[pos] === ':' || text[pos] === '=' || text[pos] === '#' || text[pos] === '-') {
95
+ pos = skipSpace(pos + 1)
96
+ }
97
+ if (text[pos] !== '5') continue
98
+ const digit1 = text.charCodeAt(pos + 1)
99
+ const digit2 = text.charCodeAt(pos + 2)
100
+ if (digit1 < 48 || digit1 > 57 || digit2 < 48 || digit2 > 57
101
+ || isAsciiWord(text.charCodeAt(pos + 3))) continue
102
+ return Number(text.slice(pos, pos + 3))
103
+ }
104
+ }
105
+ return undefined
106
+ }
67
107
  const SERVER_PATTERNS = [/\b500\b/, /\b502\b/, /\b503\b/, /\b504\b/, /bad gateway/i, /service unavailable/i]
68
108
  const INVALID_REQUEST_PATTERNS = [/\b400\b/, /\b404\b/, /\b422\b/, /invalid request/i, /does not support image/i, /unsupported/i, /invalid model/i, /no such model/i, /model not exist/i]
69
109
  const NETWORK_PATTERNS = [/econn/i, /enotfound/i, /network/i, /fetch failed/i, /socket/i, /connection reset/i, /dns/i]
@@ -100,12 +140,19 @@ const KIND_BY_PATTERN = [
100
140
  ]
101
141
 
102
142
  /** Status → kind for HTTP-level failures. */
143
+ function numericHttpStatus(status) {
144
+ if (typeof status === 'number') return Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined
145
+ if (typeof status === 'string' && /^[1-5]\d{2}$/.test(status)) return Number(status)
146
+ return undefined
147
+ }
148
+
103
149
  export function kindForHttpStatus(status) {
104
- if (status === 401 || status === 403) return VISION_FAILURE_KINDS.AUTH
105
- if (status === 429) return VISION_FAILURE_KINDS.RATE_LIMIT
106
- if (status === 402) return VISION_FAILURE_KINDS.QUOTA
107
- if (status === 400 || status === 404 || status === 422) return VISION_FAILURE_KINDS.INVALID_REQUEST
108
- if (status >= 500 && status <= 599) return VISION_FAILURE_KINDS.SERVER
150
+ const code = numericHttpStatus(status)
151
+ if (code === 401 || code === 403) return VISION_FAILURE_KINDS.AUTH
152
+ if (code === 429) return VISION_FAILURE_KINDS.RATE_LIMIT
153
+ if (code === 402) return VISION_FAILURE_KINDS.QUOTA
154
+ if (code === 400 || code === 404 || code === 422) return VISION_FAILURE_KINDS.INVALID_REQUEST
155
+ if (code !== undefined && code >= 500) return VISION_FAILURE_KINDS.SERVER
109
156
  return undefined
110
157
  }
111
158
 
@@ -147,7 +194,21 @@ function kindForCode(code) {
147
194
  */
148
195
  export function classifyVisionFailure(error) {
149
196
  const message = safeFailureText(error)
150
- let kind = kindForCode(safeFailureField(error, 'code')) ?? kindForHttpStatus(safeFailureField(error, 'status'))
197
+ // Some HTTP adapters surface response.status / statusCode rather than
198
+ // error.status. Inspect only shallow, narrowly named fields and never
199
+ // invoke arbitrary object coercion or an untrusted getter.
200
+ const reportedStatuses = [
201
+ safeFailureField(error, 'status'),
202
+ safeFailureField(error, 'statusCode'),
203
+ safeFailureField(safeFailureField(error, 'response'), 'status'),
204
+ safeFailureField(safeFailureField(error, 'cause'), 'status'),
205
+ ]
206
+ // A concrete HTTP status beats incidental words such as "authentication"
207
+ // or "timeout" in the server's error body; a branded adapter code still
208
+ // takes precedence over both. Return the extracted numeric status for logs.
209
+ const status = reportedStatuses.map(numericHttpStatus).find((code) => kindForHttpStatus(code) !== undefined)
210
+ ?? extractExplicitHttp5xxStatus(message)
211
+ let kind = kindForCode(safeFailureField(error, 'code')) ?? kindForHttpStatus(status)
151
212
  if (kind === undefined) {
152
213
  for (const [candidate, patterns] of KIND_BY_PATTERN) {
153
214
  if (patterns.some((pattern) => pattern.test(message))) {
@@ -157,10 +218,9 @@ export function classifyVisionFailure(error) {
157
218
  }
158
219
  if (kind === undefined) kind = VISION_FAILURE_KINDS.OTHER
159
220
  }
160
- const retryAfterMs =
161
- Number.isFinite(error && error.providerRetryAfterMs) && error.providerRetryAfterMs > 0
162
- ? error.providerRetryAfterMs
163
- : undefined
221
+ const retryAfter = safeFailureField(error, 'providerRetryAfterMs')
222
+ const retryAfterMs = typeof retryAfter === 'number' && Number.isFinite(retryAfter) && retryAfter > 0
223
+ ? retryAfter : undefined
164
224
  const retryable = kind === VISION_FAILURE_KINDS.TIMEOUT ||
165
225
  kind === VISION_FAILURE_KINDS.SERVER ||
166
226
  kind === VISION_FAILURE_KINDS.NETWORK
@@ -169,7 +229,7 @@ export function classifyVisionFailure(error) {
169
229
  // Whether the SAME backend may be retried as-is (not "may the next backend run").
170
230
  retryableProvider: retryable,
171
231
  retryAfterMs,
172
- status: Number.isInteger(error && error.status) ? error.status : undefined,
232
+ status,
173
233
  }
174
234
  }
175
235
 
@@ -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
  }
@@ -28,18 +28,28 @@ const wrappedAdapters = new WeakMap()
28
28
  const wrappedDelegatingAdapters = new WeakMap()
29
29
  const wrappedTransparentAdapters = new WeakMap()
30
30
  const MAX_TRANSPARENT_REASONING_MEMORY = 512
31
+ // An adapter may ignore cancellation and never settle iterator.return().
32
+ // Always attempt teardown, but do not let a broken third-party cleanup pin
33
+ // the caller indefinitely. Healthy cleanup still completes normally.
34
+ const STREAM_ITERATOR_CLEANUP_GRACE_MS = 1000
31
35
  const VISION_FAILURE_RESULT_CODES = new Set(Object.values(VISION_RESULT_CODES))
32
36
 
33
37
  function cacheableVisionDescribeResult(value) {
38
+ // Empty model/tool output is not evidence. Caching it makes a transient
39
+ // backend failure permanent for the same attachment and question.
40
+ if (value === null || value === undefined) return false
34
41
  let parsed = value
35
42
  if (typeof value === 'string') {
43
+ if (value.trim() === '') return false
36
44
  try {
37
45
  parsed = JSON.parse(value)
38
46
  } catch {
39
47
  return true
40
48
  }
41
49
  }
42
- if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return true
50
+ if (parsed === null || parsed === undefined) return false
51
+ if (typeof parsed === 'string' && parsed.trim() === '') return false
52
+ if (typeof parsed !== 'object' || Array.isArray(parsed)) return true
43
53
  return !(parsed.ok === false && VISION_FAILURE_RESULT_CODES.has(parsed.code))
44
54
  }
45
55
 
@@ -411,7 +421,12 @@ function wrapVisionHttpAdapter(adapter, runtimeState) {
411
421
  return async function* streamWithEndpointAlias(options) {
412
422
  const mapped = runtimeState.endpoints.mapModelId(options?.model)
413
423
  const next = mapped === options?.model ? options : { ...(options ?? {}), model: mapped }
414
- for await (const chunk of stream.call(target, next)) yield chunk
424
+ const parent = toolRuntime.getStore()
425
+ const state = {
426
+ ...(parent && typeof parent === 'object' ? parent : {}),
427
+ signal: combineSignals(parent?.signal, next?.signal),
428
+ }
429
+ yield* iterateUnderRuntimeState(stream.call(target, next), state)
415
430
  }
416
431
  },
417
432
  })
@@ -481,12 +496,37 @@ function projectTransparentCallConfig(options, state, runtimeState) {
481
496
  return rest
482
497
  }
483
498
 
499
+ async function closeStreamIterator(iterator, state) {
500
+ if (typeof iterator.return !== 'function') return
501
+ let timeout
502
+ try {
503
+ // The race installs a rejection handler even if the grace period wins, so
504
+ // a late adapter failure does not surface as an unhandled rejection.
505
+ await Promise.race([
506
+ Promise.resolve().then(() => toolRuntime.run(state, () => iterator.return())),
507
+ new Promise((resolve) => {
508
+ timeout = setTimeout(resolve, STREAM_ITERATOR_CLEANUP_GRACE_MS)
509
+ }),
510
+ ])
511
+ } catch (error) {
512
+ // A cancelled request must remain a cancellation, not become a secondary
513
+ // adapter teardown failure. Preserve cleanup errors on normal closes.
514
+ if (!state.signal?.aborted) throw error
515
+ } finally {
516
+ clearTimeout(timeout)
517
+ }
518
+ }
519
+
484
520
  async function* iterateUnderRuntimeState(iterable, state) {
485
521
  const iterator = toolRuntime.run(state, () => iterable[Symbol.asyncIterator]())
486
522
  let completed = false
487
523
  try {
488
524
  while (true) {
489
- const item = await toolRuntime.run(state, () => iterator.next())
525
+ // A noncooperative adapter may ignore the signal and never resolve next.
526
+ // Race the caller's cancellation without mutating the original iterator.
527
+ const item = await executeAbortable(state.signal, () =>
528
+ toolRuntime.run(state, () => iterator.next()))
529
+ if (state.signal?.aborted) throw toolAbortError()
490
530
  if (item.done) {
491
531
  completed = true
492
532
  return
@@ -494,9 +534,7 @@ async function* iterateUnderRuntimeState(iterable, state) {
494
534
  yield item.value
495
535
  }
496
536
  } finally {
497
- if (!completed && typeof iterator.return === 'function') {
498
- await toolRuntime.run(state, () => iterator.return())
499
- }
537
+ if (!completed) await closeStreamIterator(iterator, state)
500
538
  }
501
539
  }
502
540
 
@@ -521,6 +559,7 @@ function wrapDelegatingAdapter(adapter, runtimeState) {
521
559
  const parent = toolRuntime.getStore()
522
560
  const state = {
523
561
  ...(parent && typeof parent === 'object' ? parent : {}),
562
+ signal: combineSignals(parent?.signal, options?.signal),
524
563
  callConfigAuthority: 'target',
525
564
  delegationOwner: 'vision-chain',
526
565
  }
@@ -554,6 +593,7 @@ function wrapTransparentAdapter(adapter, runtimeState) {
554
593
  const parent = toolRuntime.getStore()
555
594
  const state = {
556
595
  ...(parent && typeof parent === 'object' ? parent : {}),
596
+ signal: combineSignals(parent?.signal, options?.signal),
557
597
  callConfigAuthority: 'transparent',
558
598
  transparentExplicitReasoning: explicitReasoningEffort(options),
559
599
  transparentSessionId: sessionIdentity(options),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vision-router",
3
- "version": "3.1.3",
3
+ "version": "3.1.5",
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/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",
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/vision-stream-iterator-cancellation.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/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",
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/vision-stream-iterator-cancellation.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",