dsh-vision-router 3.3.0 → 3.4.0

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.3.0 minor release — confirm publication through GitHub Releases/npm:** Brings the v3.2.2 attachment/Session timeout and security fixes, bounded VTracer subprocess isolation, Windows portability, and a SHA-verified **owner-installed** PP-OCRv6/ncnn OCR preference on supported Mac ARM64/Windows x64. Native model weights and executables are **not included in npm**; optional native archive redistribution remains separately gated. Without an installed native worker, auto can still use local Tesseract, which also remains explicitly selectable. DSH >=0.2.1-rc.5 <0.3.0-0 and Node.js >=24.9.0 remain required; no profile auto-migration. The default cloud vision fallback may transmit images externally unless strict local-only is enabled. Back up, run read-only `doctor --upgrade-preflight`, and keep a rollback option. See [v3.3.0 release notes](docs/releases/v3.3.0.md).
25
+ > **v3.4.0 minor release — confirm publication through GitHub Releases/npm:** Local OCR is now strictly **opt-in**. In Settings → Local & device → Optional local OCR, a working system Tesseract with `chi_sim` + `eng` is reused without another installation; otherwise you can install/remove a plugin-owned, SHA-verified Tesseract.js/WASM engine and Chinese/English models on demand. PP-OCRv6/ncnn can be installed or removed only from a user-provided, SHA-verified offline bundle on supported macOS ARM64/Windows x64; **public native binary/model redistribution remains NOT cleared**, with no automatic download. Most users need install neither engine: the existing consent/policy-governed vision-model fallback remains unchanged, including cloud image egress unless strict local-only is enabled. DSH >=0.2.1-rc.5 <0.3.0-0 and Node.js >=24.9.0 remain required. No automatic profile migration. Back up your profile, run read-only `doctor --upgrade-preflight`, and retain v3.3.0 for rollback. See [v3.4.0 release notes](docs/releases/v3.4.0.md).
26
26
 
27
27
  ## Start here
28
28
 
@@ -427,7 +427,8 @@ ollama pull qwen2.5vl
427
427
  - No API key for the default free chain; a credential reference (`apiKeyEnv`) only for paid `httpProviders`.
428
428
  - Chrome / Chromium / Edge is needed only for `vision_html_screenshot`; every other tool works without a browser.
429
429
  - Desktop capture is opt-in. Windows and macOS use OS-provided capture facilities; Linux needs ImageMagick `import` or `scrot` and a capturable desktop session (Wayland support depends on the environment).
430
- - Tesseract is optional. `vision_ocr` defaults to `ocrEngine: auto` (local Tesseract first, vision fallback), and Settings → Advanced → **Default OCR engine** can force Tesseract-only or vision-model-only behavior without uninstalling Tesseract. An explicit per-call `engine=tesseract|vision` always overrides the default.
430
+ - Local OCR engines are **optional**. `vision_ocr` defaults to `ocrEngine: auto`: verified owner-installed PP-OCRv6/ncnn on supported Mac ARM64 / Windows x64 → managed or system Tesseract → authorized vision-model fallback. Settings → Advanced → **Default OCR engine** can force Tesseract-only or vision-model-only behavior; per-call `engine=tesseract|vision` overrides it.
431
+ - **On-demand setup (new optional feature):** Settings → Local & device → Optional local OCR shows independent installation states and controls. A system Tesseract with both `chi_sim` and `eng` is reused automatically, without a redundant download or a system uninstall option. If missing, the user can install or remove a private Tesseract.js/WASM with Chinese and English models; installation happens only after a click. PP-OCRv6 can be imported and removed from a user-supplied verified offline archive. Public PP-OCRv6 binary distribution remains unapproved; **there is no automatic native download** yet. Most users can continue with the authorized vision-model fallback without installing either engine.
431
432
 
432
433
  ## Install and lifecycle
433
434
 
@@ -611,7 +612,7 @@ exploration (LLM7.io and OVHcloud anonymous tiers) by
611
612
 
612
613
  ## Release notes and community
613
614
 
614
- Release details: [v3.3.0 notes](docs/releases/v3.3.0.md). Check GitHub Releases or npm for the actually published version.
615
+ Release details: [v3.4.0 notes](docs/releases/v3.4.0.md). Check GitHub Releases or npm for the actually published version.
615
616
 
616
617
  <p align="center">
617
618
  <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.3.0 次版本更新(正式发布状态请核实 GitHub Releases/npm):** 集成附件 ID/会话恢复的完整任务超时和权限加固、VTracer 独立进程隔离、Windows 兼容修复,以及 Mac ARM64/Windows x64 **用户自行安装**的 SHA-256 校验 PP-OCRv6/ncnn 主力 OCR 路线;`auto` 对不确定识别在授权和预算内核查。**npm 包不包含原生模型或可执行文件**,原生离线包公开分发仍须独立完成许可证和供应链审核。未安装原生 ncnn 时仍可回退到 Tesseract,也可以显式指定兼容引擎。最低要求仍为 DSH >=0.2.1-rc.5 <0.3.0-0、Node.js >=24.9.0;不自动迁移 Profile。默认云端视觉兜底可能发送图片,敏感内容应使用严格纯本地。升级前请备份、运行只读 `doctor --upgrade-preflight` 并保留回滚版本。详见 [v3.3.0 发布说明](docs/releases/v3.3.0.md)。
25
+ > **v3.4.0 次版本更新(正式发布状态请核实 GitHub Releases/npm):** 本地 OCR 改为**完全按需安装**,普通用户无需预装任何引擎。设置 → 本地与设备 → 可选本地 OCR 可分别管理 Tesseract 和 PP-OCRv6:若系统 Tesseract 已具备简体中文 `chi_sim` 与英文 `eng`,直接复用,不会重复安装或卸载系统组件;否则用户可主动一键安装/卸载插件私有 Tesseract.js/WASM 与中英文语言数据。PP-OCRv6/ncnn 可从用户自行提供的、经 SHA-256 验证的可信离线包导入和卸载(支持 Mac ARM64 / Windows x64),**原生二进制和模型公开分发仍未获放行,不提供一键公网下载**。不安装两者时照旧根据既有授权与隐私设置回退视觉模型,默认云端兜底可能发送图片;敏感场景须开启严格本地模式。最低要求仍为 DSH >=0.2.1-rc.5 <0.3.0-0、Node.js >=24.9.0;不自动迁移 Profile。升级前备份,运行只读 `doctor --upgrade-preflight`,保留 v3.3.0 回滚方案。详见 [v3.4.0 发布说明](docs/releases/v3.4.0.md)。
26
26
 
27
27
  ## 先用起来
28
28
 
@@ -428,6 +428,8 @@ ollama pull qwen2.5vl
428
428
  - 桌面截屏必须显式开启。Windows/macOS 使用系统截屏能力;Linux 需安装 ImageMagick `import` 或 `scrot`,且必须处于可截取的桌面会话(Wayland 支持取决于环境)。
429
429
  - tesseract 可选。`vision_ocr` 默认使用 `ocrEngine: auto`:在 **Mac ARM64 / Windows x64** 上优先使用已安装且 SHA-256 校验通过的 PP-OCRv6 small/ncnn,未安装或失败才使用本地 Tesseract,最后按照现有隐私设置决定是否回退视觉模型。其他系统暂时保持 Tesseract 优先。针对 Issue #836,Tesseract 自适应识别增加 PSM 7(单行);只有低置信度时才按需尝试底部字幕的灰度、放大与暗底反相预处理。`auto` 遇到非空但低置信度的本地结果时,在非严格本地模式、未触发熔断且剩余时间允许的情况下,可继续调用视觉模型核查(可能产生服务商用量);否则保留带不确定性标记的本地结果。仍可在「设置 → 高级 → OCR 默认引擎」强制仅 Tesseract 或直接使用视觉模型。单次调用显式 `engine=tesseract|vision` 始终优先,`engine=tesseract` 绝不触发云端视觉请求。
430
430
 
431
+ **按需安装与卸载(此开发分支的新功能):** 在「设置 → 本地与设备 → 可选本地 OCR」查看两个引擎的状态。若检测到系统 Tesseract 及 `chi_sim`、`eng`,直接使用,不再重复安装;缺少时可点击安装插件私有的 Tesseract.js/WASM 和中英文模型,之后可只卸载插件副本。PP-OCRv6 支持从用户已取得的可信离线包导入、安装和卸载;**原生包尚未获公开分发放行,暂不提供自动下载**。两者均非必装;未安装时继续遵守既有隐私授权并回退到视觉模型。
432
+
431
433
  本地安装已验证的 PP-OCRv6 引擎(Mac ARM64 已验证;Windows x64 已通过本地安装与正式 \`auto\` 调用,公开发行仍待最终审查):拿到经来源核验的单文件包后运行下面一条命令即可,不需要自行编译;安装器会逐项校验二进制与五个模型资产。当前两个包均为**本地验证候选,尚未上传公共 Release**;Windows 版本仍需完成许可证审核。
432
434
 
433
435
  ```bash
@@ -620,7 +622,7 @@ npx dsh-vision-router doctor --profile web
620
622
 
621
623
  ## 版本公告与社区链接
622
624
 
623
- 版本更新详情:[v3.3.0 发布说明](docs/releases/v3.3.0.md)。正式可安装版本请以 GitHub Releases 或 npm 为准。
625
+ 版本更新详情:[v3.4.0 发布说明](docs/releases/v3.4.0.md)。正式可安装版本请以 GitHub Releases 或 npm 为准。
624
626
 
625
627
  <p align="center">
626
628
  <sub>生态收录:</sub>
@@ -0,0 +1,41 @@
1
+ # v3.4.0 — Optional local OCR engines / 按需安装本地 OCR 引擎
2
+
3
+ **Release identity / 发布状态:** This document describes the contents of v3.4.0, not proof that the version is already published. Publication requires an immutable GitHub tag/Release, npm `latest` and successful signed-package identity verification by the protected Release workflow. / 本文说明 3.4.0 更新内容;正式发布须以受保护工作流、不可变 GitHub tag/Release 和 npm `latest` 的包体核验结果为准。
4
+
5
+ ## Overview / 主要变化
6
+
7
+ **Both local OCR engines are optional. No native OCR executable or model is installed during ordinary `dsh-vision-router` plugin installation.** Most users can continue to use the existing, authorized vision-model fallback for image transcription without installing either local engine. / 两个本地 OCR 引擎完全可选。用户正常安装 Vision Router 不会自动安装 OCR 程序或模型;多数用户无需配置,继续按既有策略回退视觉模型。
8
+
9
+ Open **DSH Settings → Vision Router → Local & device → Optional local OCR** (本地与设备 → 可选本地 OCR) to inspect and manage the two local engine choices:
10
+
11
+ ### Tesseract / 系统优先,插件私有版可选
12
+
13
+ - If the machine already has usable system `tesseract` with **both** `chi_sim` and `eng` language data, **reuse it directly** and disable the redundant Install button. Never uninstall or modify the user's global Tesseract. / 系统已有可用的简体中文和英文 Tesseract 时直接复用,不重复下载、不改动系统安装。
14
+ - Otherwise an explicit **Install Tesseract** click can install a **private Tesseract.js 7.0.0/WASM** runtime and Chinese/English traineddata. It is not installed by npm during plugin installation and does not require a system-wide package manager operation. Pinned npm SHA-512 and language-data SHA-256 are checked, staged atomically, and removed only by the plugin-owned uninstall. / 未检测到完整系统版时,用户可以在设置里主动安装插件私有的 WASM 与中英文模型,或独立卸载。
15
+ - Managed recognition executes in a bounded Node subprocess with cancellation, resource limits and Electron Host compatibility. Installation and recognition can require temporary network access for the opt-in download, but later inference uses locally installed assets. / 安装时需联网,安装完成后的识别在本机进行;执行有超时、取消与资源限制。
16
+ - Native system `tesseract` is never owned by the plugin. The private WASM and system binary are distinct providers of the same `engine=tesseract` OCR compatibility path; neither is guaranteed to transcribe stylized Chinese typography perfectly. / 系统版与插件版均归入 Tesseract 兼容路径,复杂文字效果仍有局限。
17
+
18
+ ### PP-OCRv6 small / ncnn — verified offline archive only
19
+
20
+ - macOS ARM64 and Windows x64 can install and uninstall a **trusted user-supplied local archive** through the Settings file picker. The existing owner-installed binary and five model assets are SHA-pinned, and native execution retains the earlier supervision/deadline gates. / 支持从用户自备的可信离线包在设置页安装和卸载,保持完整性校验和子进程边界。
21
+ - **The public PP-OCRv6 native archive remains NOT CLEARED FOR REDISTRIBUTION.** This release does **not** host, download or attach worker executables or model weights to npm or GitHub Release; a file picker is **not** an automatic public installer. / 原生包仍未通过公开分发审核,不提供官方公网一键下载,也不会把原生二进制和模型随 npm 打包。
22
+ - Damaged but verifiably plugin-owned PP installations may now be removed safely without relying on intact worker/model hashes; system/unowned paths remain protected. / 插件管理的损坏安装也可卸载,不允许清理无关用户目录。
23
+
24
+ ## Fallback, privacy and defaults / 回退、隐私与默认行为
25
+
26
+ - `vision_ocr(auto)` continues to prefer an installed, verified PP-OCRv6 native worker where supported, then available managed/system Tesseract, and then the existing model fallback if local OCR is unavailable/empty. An explicit `engine=tesseract` never invokes the cloud vision chain; explicit `engine=vision` continues to bypass local engines. / 原来的 `auto` 优先级保持,新引擎未安装时不会影响视觉模型后备。
27
+ - **Default free vision fallback may transmit the image (or crop) and request metadata to an external provider.** Installing a local OCR engine does not make the full plugin or the chat model offline. Strict local-only vision continues to prevent the plugin's cloud visual requests; user must also use a local chat model for fully local end-to-end processing. / 云端后备依旧可能传图;严格本地模式按既有策略执行。
28
+ - No automatic first-run downloads, prompt to force-install either engine, change to existing user settings, or automatic Host/profile migration. / 不强制下载、不自动迁移、不更改用户现有设置。
29
+
30
+ ## Review evidence and known limits / 审核与限制
31
+
32
+ - **#856 final head `c8d3b9278ec3259862a40926608d139be560aea7`: 14/14 GitHub Actions workflows passed, including two Node full-test versions (24.9.0/24.21.0), complete 28-job CI, exact minimum/recommended/current DSH Host and latest Alpha Host/Desktop gates, security analysis and browser Settings acceptance.**
33
+ - **Real Mac and Windows x64 isolated private install → image OCR → uninstall:** Both passed without altering global packages. Both recognized a generated `HELLO 123` screenshot (confidence 87/88). The Mac Chinese sample `你好世界 123` came back as `你 好 世界 123` (confidence 94), highlighting spacing limitations rather than perfect transcription. / Mac、Windows 真实安装/识别/卸载通过,中文可能出现空格。
34
+ - Existing PP native worker tests are from earlier 3.3.0/isolated work and do not constitute approval of public native asset redistribution, nor do they prove original Issue #836 reporter-specific images were recognized exactly. / 仍不可将实验室验证误当作公开原生包放行。
35
+
36
+ ## Compatibility and upgrade / 兼容与升级
37
+
38
+ - DSH `>=0.2.1-rc.5 <0.3.0-0`; Node.js `>=24.9.0`. No support-floor change.
39
+ - Before upgrading, back up DSH Profile, Settings, Sessions and attachments; run the read-only `doctor --upgrade-preflight`; keep `v3.3.0` available as rollback. No automatic migration.
40
+ - Third-party Desktop builders and unreviewed installations are not certified solely by official Host CI. / 第三方打包器需另行验收。
41
+ - Verify the protected release SHA, GitHub Release asset SHA256SUMS and npm tarball identity/provenance before assuming the installed build is v3.4.0. / 以正式工作流和包体哈希为准。
package/index.js CHANGED
@@ -120,6 +120,7 @@ import path from 'node:path'
120
120
  import { existsSync } from 'node:fs'
121
121
  import { runExperimentalNativeOcrCanary } from './lib/native-ocr-canary.js'
122
122
  import { localNativeOcrInstallPaths } from './lib/native-ocr-installation.js'
123
+ import { managedTesseractPaths, runManagedTesseractOcr, systemTesseract } from './lib/optional-ocr-engines.js'
123
124
  import { prepareTesseractSubtitleRetry } from './lib/tesseract-image-preprocess.js'
124
125
 
125
126
  import { pathToFileURL } from 'node:url'
@@ -4492,15 +4493,38 @@ ctx.logger?.info(
4492
4493
  let localAttempted = false
4493
4494
  try {
4494
4495
  localAttempted = true
4495
- const local = await ocrWithTesseractAdaptive(
4496
- bytes,
4497
- tesseractSlice,
4498
- {
4499
- signal: taskSignal,
4500
- preprocess: (source, context) =>
4501
- prepareTesseractSubtitleRetry(source, { ...context, loadSharp }),
4502
- },
4503
- )
4496
+ const managed = existsSync(managedTesseractPaths().manifest)
4497
+ let local
4498
+ if (managed) {
4499
+ try {
4500
+ const result = await runManagedTesseractOcr(bytes, {
4501
+ timeoutMs: Math.min(tesseractSlice, deadline.remaining()), signal: taskSignal,
4502
+ })
4503
+ const quality = Math.min(100, Math.max(0, result.confidence))
4504
+ local = {
4505
+ text: result.text, quality,
4506
+ uncertain: quality < 85 || /[0-9OIlL]{3,}/.test(result.text),
4507
+ psm: 6, attemptedPsms: [6],
4508
+ riskyTokens: [], variant: 'tesseract-js-wasm',
4509
+ }
4510
+ } catch (error) {
4511
+ throwIfVisionTaskAborted(taskSignal, error)
4512
+ ctx.logger?.warn('vision-router: managed Tesseract failed; trying system Tesseract')
4513
+ }
4514
+ }
4515
+ if ((!local || !local.text.trim()) && (!managed || await systemTesseract())) {
4516
+ const native = await ocrWithTesseractAdaptive(
4517
+ bytes,
4518
+ Math.min(tesseractSlice, deadline.remaining()),
4519
+ {
4520
+ signal: taskSignal,
4521
+ preprocess: (source, context) =>
4522
+ prepareTesseractSubtitleRetry(source, { ...context, loadSharp }),
4523
+ },
4524
+ )
4525
+ if (!local || native.text.trim()) local = native
4526
+ }
4527
+ if (!local) local = { text: '', uncertain: true, quality: 0, psm: 6, attemptedPsms: [6], riskyTokens: [] }
4504
4528
  if (local.text.trim() !== '') {
4505
4529
  if (session) {
4506
4530
  visionTurnMemory.recordLocalOcr(
@@ -4704,12 +4728,26 @@ ctx.logger?.info(
4704
4728
  let used = 'none'
4705
4729
  if (engine !== 'vision') {
4706
4730
  try {
4707
- const out = await ocrWithTesseract(
4708
- chunk,
4709
- Math.min(12000, deadline.remaining()),
4710
- { signal: taskSignal },
4711
- )
4712
- text = out.trim()
4731
+ const hasManagedTesseract = existsSync(managedTesseractPaths().manifest)
4732
+ if (hasManagedTesseract) {
4733
+ try {
4734
+ const managed = await runManagedTesseractOcr(chunk, {
4735
+ timeoutMs: Math.min(12000, deadline.remaining()), signal: taskSignal,
4736
+ })
4737
+ text = managed.text.trim()
4738
+ } catch (error) {
4739
+ throwIfVisionTaskAborted(taskSignal, error)
4740
+ ctx.logger?.warn('vision-router: managed Tesseract chunk failed; checking for system binary')
4741
+ }
4742
+ }
4743
+ if (!text && (!hasManagedTesseract || await systemTesseract())) {
4744
+ const out = await ocrWithTesseract(
4745
+ chunk,
4746
+ Math.min(12000, deadline.remaining()),
4747
+ { signal: taskSignal },
4748
+ )
4749
+ text = out.trim()
4750
+ }
4713
4751
  used = 'tesseract'
4714
4752
  } catch (error) {
4715
4753
  throwIfVisionTaskAborted(taskSignal, error)
@@ -2,6 +2,7 @@ import { randomBytes } from 'node:crypto'
2
2
  import { createCachedUpdateChecker } from './update-check.js'
3
3
  import { isLocalUiRequest } from './web-capability-boundary.js'
4
4
  import { detectDshSelfUpdatePlan, runDshPluginUpdate } from './self-update.js'
5
+ import { installOptionalOcrRoutes } from './optional-ocr-routes.js'
5
6
 
6
7
  function json(res, status, body, headers = {}) {
7
8
  res.writeHead(status, {
@@ -20,6 +21,7 @@ function json(res, status, body, headers = {}) {
20
21
  */
21
22
  export function installVisionMaintenanceRoutes(ctx, options = {}) {
22
23
  if (!ctx || typeof ctx.inject !== 'function') return
24
+ installOptionalOcrRoutes(ctx, options.optionalOcr)
23
25
  const logger = options.logger ?? ctx.logger
24
26
  const updateChecker = options.updateChecker ?? createCachedUpdateChecker()
25
27
  const selfUpdatePlan = options.selfUpdatePlan ?? detectDshSelfUpdatePlan()
@@ -0,0 +1,33 @@
1
+ // Only spawned by the owner-scoped OCR manager. The parent enforces
2
+ // input/output bounds, cancellation and a hard process deadline.
3
+ import { readFile } from 'node:fs/promises'
4
+ import { join } from 'node:path'
5
+ import { pathToFileURL } from 'node:url'
6
+
7
+ async function main() {
8
+ const [root] = process.argv.slice(2)
9
+ if (!root) throw Error('missing managed Tesseract root')
10
+ const data = []
11
+ let length = 0
12
+ for await (const part of process.stdin) {
13
+ length += part.length
14
+ if (length > 24 * 1024 * 1024) throw Error('OCR image too large')
15
+ data.push(part)
16
+ }
17
+ const entry = pathToFileURL(join(root, 'node_modules', 'tesseract.js', 'src', 'index.js')).href
18
+ const mod = await import(entry)
19
+ const createWorker = mod.createWorker ?? mod.default?.createWorker
20
+ if (typeof createWorker !== 'function') throw Error('missing managed Tesseract worker')
21
+ let worker
22
+ try {
23
+ worker = await createWorker(['chi_sim', 'eng'], 1, {
24
+ langPath: join(root, 'models'), gzip: true, cacheMethod: 'none', logger: () => {},
25
+ })
26
+ const result = await worker.recognize(Buffer.concat(data, length))
27
+ process.stdout.write(JSON.stringify({
28
+ text: String(result?.data?.text ?? '').slice(0, 32768),
29
+ confidence: Number.isFinite(result?.data?.confidence) ? result.data.confidence : 0,
30
+ }) + '\n')
31
+ } finally { await worker?.terminate?.() }
32
+ }
33
+ main().catch(() => { process.stderr.write('managed Tesseract OCR failed\n'); process.exitCode = 1 })
@@ -0,0 +1,330 @@
1
+ import { createHash, randomUUID } from 'node:crypto'
2
+ import { spawn, spawnSync } from 'node:child_process'
3
+ import { lstat, mkdir, readFile, writeFile, copyFile, rename, rm, chmod } from 'node:fs/promises'
4
+ import { existsSync } from 'node:fs'
5
+ import { homedir, tmpdir } from 'node:os'
6
+ import { join, dirname, delimiter } from 'node:path'
7
+ import { fileURLToPath, pathToFileURL } from 'node:url'
8
+ import { localNativeOcrInstallPaths } from './native-ocr-installation.js'
9
+ import { verifyExperimentalNativeOcrBinary } from './native-ocr-canary.js'
10
+ import { verifyNativeOcrAssets } from './native-ocr-integrity.js'
11
+
12
+ // Optional by design. Do not modify the DSH profile or global system packages.
13
+ // npm downloads happen only after a local user explicitly selects Install.
14
+ export const OPTIONAL_TESSERACT_PACKAGES = Object.freeze({
15
+ 'tesseract.js': ['7.0.0', 'sha512-exPBkd+z+wM1BuMkx/Bjv43OeLBxhL5kKWsz/9JY+DXcXdiBjiAch0V49QR3oAJqCaL5qURE0vx9Eo+G5YE7mA=='],
16
+ '@tesseract.js-data/chi_sim': ['1.0.0', 'sha512-iuErURkPbECDUazgsLn/r3c+tU2y5o5S/w14d0A/YiagfsjYyZKgTo75RUpsGJ311qtu0dIX4hqnXAAjmqf2CA=='],
17
+ '@tesseract.js-data/eng': ['1.0.0', 'sha512-mbTumm6KQPUHyzTPQaF3ObXYnx0SqqfV2nabqFVQBwD6Kl7PhGSLSzOlfFTWy0P3BjghaSKA2W9GB19Jk+ZcTg=='],
18
+ })
19
+ const TESS_LANGUAGES = Object.freeze({
20
+ chi_sim: Object.freeze({ bytes: 1718768, sha256: 'b8a23f10c7de500891eb458a8adc9cc58ab7f242f08b7d149f5e9aea4ad5db7c' }),
21
+ eng: Object.freeze({ bytes: 2952873, sha256: '45b4cb346724ac1774f1c36f42f182b887bcdb28ebe63e6fff90ac41f3fcff91' }),
22
+ })
23
+ const MANAGED_MARK = 'dvr-tesseract-js-v1'
24
+ const TESS_VERSION = '7.0.0'
25
+ const MAX_BINARY_UPLOAD = 64 * 1024 * 1024
26
+ const TESS_INSTALL_TIMEOUT_MS = 180_000
27
+ let mutating = false
28
+ let activeManagedRuns = 0
29
+ export const managedTesseractPaths = ({ home = homedir() } = {}) => {
30
+ const root = join(home, '.dsh-vision-router', 'ocr', 'tesseract-js')
31
+ return Object.freeze({ root, manifest: join(root, 'DVR-MANAGED.json'), models: join(root, 'models') })
32
+ }
33
+ const hash = bytes => createHash('sha256').update(bytes).digest('hex')
34
+ function installedLockRow(lock, name) {
35
+ const key = 'node_modules/' + name
36
+ // npm --prefix <absolute staging directory> can write canonicalized,
37
+ // prefix-relative lockfile keys (not just 'node_modules/...'). The package
38
+ // lock is moved atomically with the staged tree; resolve by exact suffix.
39
+ const rows = Object.entries(lock?.packages ?? {}).filter(([path]) =>
40
+ path === key || path.endsWith('/' + key))
41
+ return rows.length === 1 ? rows[0][1] : undefined
42
+ }
43
+ const readJSON = async path => JSON.parse(await readFile(path, 'utf8'))
44
+ async function regularFile(path, maxBytes = 20 * 1024 * 1024) {
45
+ try {
46
+ const st = await lstat(path)
47
+ return st.isFile() && !st.isSymbolicLink() && st.size > 0 && st.size <= maxBytes
48
+ } catch { return false }
49
+ }
50
+ async function directory(path) {
51
+ try { const st = await lstat(path); return st.isDirectory() && !st.isSymbolicLink() }
52
+ catch { return false }
53
+ }
54
+ async function ownedNativeDirectory(root) {
55
+ if (!await directory(root)) return false
56
+ const notice = join(root, 'SOURCE-NOTICE.md')
57
+ if (!await regularFile(notice, 32 * 1024)) return false
58
+ try {
59
+ const contents = await readFile(notice, 'utf8')
60
+ return contents.startsWith('# Locally installed native OCR assets\n') &&
61
+ contents.includes('Runtime: Tencent/ncnn @')
62
+ } catch { return false }
63
+ }
64
+ async function verifyManaged(root) {
65
+ const manifest = join(root, 'DVR-MANAGED.json')
66
+ if (!await directory(root) || !await regularFile(manifest, 4096)) return false
67
+ let marker
68
+ try { marker = await readJSON(manifest) } catch { return false }
69
+ if (marker?.kind !== MANAGED_MARK || marker.version !== TESS_VERSION) return false
70
+ const pkgs = marker.packages
71
+ for (const [name, [version, integrity]] of Object.entries(OPTIONAL_TESSERACT_PACKAGES)) {
72
+ if (pkgs?.[name]?.version !== version || pkgs?.[name]?.integrity !== integrity) return false
73
+ const base = join(root, 'node_modules', ...name.split('/'))
74
+ if (!await directory(base) || !await regularFile(join(base, 'package.json'), 200_000)) return false
75
+ let pkg
76
+ try { pkg = await readJSON(join(base, 'package.json')) } catch { return false }
77
+ if (pkg?.name !== name || pkg?.version !== version) return false
78
+ }
79
+ const lock = await readJSON(join(root, 'package-lock.json')).catch(() => null)
80
+ if (!lock?.packages) return false
81
+ for (const [name, [version, integrity]] of Object.entries(OPTIONAL_TESSERACT_PACKAGES)) {
82
+ const row = installedLockRow(lock, name)
83
+ if (row?.version !== version || row?.integrity !== integrity) return false
84
+ }
85
+ for (const [name, expected] of Object.entries(TESS_LANGUAGES)) {
86
+ const file = join(root, 'models', name + '.traineddata.gz')
87
+ if (!await regularFile(file, 10 * 1024 * 1024)) return false
88
+ const bytes = await readFile(file)
89
+ if (bytes.length !== expected.bytes || hash(bytes) !== expected.sha256) return false
90
+ }
91
+ return true
92
+ }
93
+ export async function systemTesseract() {
94
+ const probe = spawnSync('tesseract', ['--list-langs'], { encoding: 'utf8', timeout: 3000, windowsHide: true, maxBuffer: 16384 })
95
+ const names = (probe.stdout ?? '') + '\n' + (probe.stderr ?? '')
96
+ return probe.status === 0 && /(?:^|\s)chi_sim(?:\s|$)/.test(names) && /(?:^|\s)eng(?:\s|$)/.test(names)
97
+ }
98
+ export async function optionalOcrStatus({
99
+ home = homedir(),
100
+ probeSystem = systemTesseract,
101
+ resolveNativePaths = localNativeOcrInstallPaths,
102
+ } = {}) {
103
+ const tess = managedTesseractPaths({ home })
104
+ const pp = resolveNativePaths({ home })
105
+ const [managedTesseract, nativeReady, systemReady, nativeOwned] = await Promise.all([
106
+ verifyManaged(tess.root).catch(() => false),
107
+ pp && await directory(pp.root)
108
+ ? Promise.all([verifyExperimentalNativeOcrBinary(pp.binaryPath), verifyNativeOcrAssets(pp.modelDir)]).then(() => true, () => false)
109
+ : false,
110
+ Promise.resolve().then(() => probeSystem()).catch(() => false),
111
+ pp ? ownedNativeDirectory(pp.root) : false,
112
+ ])
113
+ return {
114
+ ok: true,
115
+ busy: mutating,
116
+ tesseract: { managedInstalled: managedTesseract, systemInstalled: !!systemReady, installed: managedTesseract || !!systemReady, canInstall: !mutating && !managedTesseract && !systemReady, canUninstall: !mutating && managedTesseract && activeManagedRuns === 0 },
117
+ ppocrv6: { installed: nativeReady, damaged: nativeOwned && !nativeReady, supported: !!pp, canInstallFromFile: !mutating && !!pp, canUninstall: !mutating && nativeOwned },
118
+ }
119
+ }
120
+ export function nodeChildEnvironment({ env = process.env, electron = process.versions?.electron } = {}) {
121
+ // Electron's process.execPath is the app executable. It must be launched
122
+ // with the supported Node mode; never inherit Host runtime preload flags.
123
+ return {
124
+ ...env, NODE_OPTIONS: '',
125
+ ...(electron ? { ELECTRON_RUN_AS_NODE: '1' } : {}),
126
+ }
127
+ }
128
+ async function npmCommand() {
129
+ if (process.platform !== 'win32') return { exe: 'npm', prefix: [] }
130
+ const searchDirs = [dirname(process.execPath),
131
+ ...String(process.env.PATH ?? '').split(delimiter)
132
+ .map(path => path.replace(/^["']|["']$/g, '').trim()).filter(Boolean)]
133
+ for (const base of [...new Set(searchDirs)]) {
134
+ const candidate = join(base, 'node_modules', 'npm', 'bin', 'npm-cli.js')
135
+ if (await regularFile(candidate, 100_000))
136
+ return { exe: process.execPath, prefix: [candidate] }
137
+ }
138
+ throw Error('npm CLI unavailable for portable Tesseract installation')
139
+ }
140
+ function execBounded(exe, args, { cwd, timeout = TESS_INSTALL_TIMEOUT_MS } = {}) {
141
+ return new Promise((resolve, reject) => {
142
+ const child = spawn(exe, args, { cwd, shell: false, windowsHide: true, stdio: ['ignore', 'ignore', 'pipe'],
143
+ env: { ...nodeChildEnvironment({ electron: exe === process.execPath ? process.versions?.electron : undefined }), npm_config_update_notifier: 'false', npm_config_audit: 'false' } })
144
+ let log = ''
145
+ let settled = false
146
+ const finish = (error) => {
147
+ if (settled) return
148
+ settled = true
149
+ clearTimeout(timer)
150
+ if (error) reject(error)
151
+ else resolve()
152
+ }
153
+ child.stderr.on('data', chunk => { log = (log + String(chunk)).slice(-1200) })
154
+ child.on('error', error => finish(Error('optional OCR installer unavailable: ' + error.message)))
155
+ child.on('close', code => finish(code === 0 ? null : Error('optional OCR install failed (' + code + '): ' + log.slice(-400))))
156
+ const timer = setTimeout(() => {
157
+ child.kill()
158
+ finish(Error('optional OCR package installation timed out'))
159
+ }, timeout)
160
+ timer.unref?.()
161
+ })
162
+ }
163
+ async function assertOwned(root) {
164
+ if (!await directory(root)) throw Error('the OCR directory is not a real managed directory')
165
+ if (!await regularFile(join(root, 'DVR-MANAGED.json'), 4096)) throw Error('refusing to remove unowned OCR directory')
166
+ const marker = await readJSON(join(root, 'DVR-MANAGED.json'))
167
+ if (marker?.kind !== MANAGED_MARK) throw Error('refusing to remove unowned OCR installation')
168
+ }
169
+ export async function installTesseract({ home = homedir(), npm = npmCommand, exec = execBounded, probeSystem = systemTesseract } = {}) {
170
+ // A valid system installation already meets this optional capability.
171
+ // Do not download a second Tesseract implementation or touch system files.
172
+ if (await probeSystem()) return { ok: true, installed: false, reusedSystem: true, engine: 'tesseract' }
173
+ const dest = managedTesseractPaths({ home })
174
+ if (await directory(dest.root)) throw Error('Tesseract managed directory already exists; refusing to overwrite')
175
+ const parent = dirname(dest.root)
176
+ await mkdir(parent, { recursive: true, mode: 0o700 })
177
+ const stage = join(parent, '.tesseract-stage-' + randomUUID())
178
+ await mkdir(stage, { mode: 0o700 })
179
+ try {
180
+ const cli = await npm()
181
+ const packages = Object.entries(OPTIONAL_TESSERACT_PACKAGES).map(([name, [version]]) => name + '@' + version)
182
+ await exec(cli.exe, [...cli.prefix, 'install', ...packages, '--prefix', stage,
183
+ '--save-exact', '--ignore-scripts', '--no-audit', '--no-fund',
184
+ '--registry=https://registry.npmjs.org/', '--no-progress'], { cwd: stage })
185
+ await mkdir(join(stage, 'models'), { mode: 0o700 })
186
+ for (const [language, expected] of Object.entries(TESS_LANGUAGES)) {
187
+ const input = join(stage, 'node_modules', '@tesseract.js-data', language,
188
+ '4.0.0_best_int', language + '.traineddata.gz')
189
+ if (!await regularFile(input, 10 * 1024 * 1024)) throw Error('missing Tesseract language model: ' + language)
190
+ const raw = await readFile(input)
191
+ if (raw.length !== expected.bytes || hash(raw) !== expected.sha256) throw Error('Tesseract model integrity mismatch: ' + language)
192
+ const out = join(stage, 'models', language + '.traineddata.gz')
193
+ await copyFile(input, out)
194
+ await chmod(out, 0o600)
195
+ }
196
+ const packagesLock = await readJSON(join(stage, 'package-lock.json'))
197
+ for (const [name, [version, integrity]] of Object.entries(OPTIONAL_TESSERACT_PACKAGES)) {
198
+ const row = installedLockRow(packagesLock, name)
199
+ if (row?.version !== version || row?.integrity !== integrity) throw Error('untrusted npm package identity: ' + name)
200
+ }
201
+ await writeFile(join(stage, 'DVR-MANAGED.json'), JSON.stringify({
202
+ kind: MANAGED_MARK, version: TESS_VERSION,
203
+ packages: Object.fromEntries(Object.entries(OPTIONAL_TESSERACT_PACKAGES).map(([name, [version, integrity]]) => [name, { version, integrity }])),
204
+ }), { mode: 0o600 })
205
+ if (!await verifyManaged(stage)) throw Error('Tesseract installation verification failed')
206
+ await rename(stage, dest.root)
207
+ return { ok: true, installed: true, engine: 'tesseract' }
208
+ } finally { await rm(stage, { recursive: true, force: true }) }
209
+ }
210
+ export async function uninstallTesseract({ home = homedir() } = {}) {
211
+ if (activeManagedRuns > 0) throw Error('Tesseract is busy; retry after OCR completes')
212
+ const dest = managedTesseractPaths({ home })
213
+ await assertOwned(dest.root)
214
+ const tomb = dest.root + '.removing-' + randomUUID()
215
+ await rename(dest.root, tomb)
216
+ await rm(tomb, { recursive: true, force: true })
217
+ return { ok: true, installed: false, engine: 'tesseract' }
218
+ }
219
+ function nativeInstallerPath() {
220
+ // source checkout: src/lib -> repo/scripts; packed runtime: lib -> repo/scripts
221
+ const adjacent = fileURLToPath(new URL('../scripts/install-native-ocr.mjs', import.meta.url))
222
+ if (existsSync(adjacent)) return adjacent
223
+ return fileURLToPath(new URL('../../scripts/install-native-ocr.mjs', import.meta.url))
224
+ }
225
+ export async function installNativeBundle(bytes, { home = homedir(), exec = execBounded } = {}) {
226
+ const dest = localNativeOcrInstallPaths({ home })
227
+ if (!dest) throw Error('PP-OCRv6 is not approved for this platform')
228
+ if (!Buffer.isBuffer(bytes) || bytes.length < 128 || bytes.length > MAX_BINARY_UPLOAD) throw Error('invalid PP-OCRv6 archive')
229
+ const archive = join(tmpdir(), 'dvr-ocr-bundle-' + randomUUID() + '.tar.gz')
230
+ try {
231
+ await writeFile(archive, bytes, { mode: 0o600, flag: 'wx' })
232
+ await exec(process.execPath, [nativeInstallerPath(), '--bundle', archive], { timeout: 180_000 })
233
+ await verifyExperimentalNativeOcrBinary(dest.binaryPath)
234
+ await verifyNativeOcrAssets(dest.modelDir)
235
+ return { ok: true, installed: true, engine: 'ppocrv6' }
236
+ } finally { await rm(archive, { force: true }) }
237
+ }
238
+ export async function uninstallNative({
239
+ home = homedir(),
240
+ resolvePaths = localNativeOcrInstallPaths,
241
+ } = {}) {
242
+ const dest = resolvePaths({ home })
243
+ if (!dest || !await directory(dest.root)) throw Error('PP-OCRv6 is not installed')
244
+ // A corrupt model/worker is precisely when the user must still be able
245
+ // to remove an optional installation. Require the installer-created
246
+ // owner notice and exact managed directory instead of full model hashes.
247
+ // Never mutate a system binary, a symlink, or an arbitrary caller path.
248
+ if (!await ownedNativeDirectory(dest.root))
249
+ throw Error('refusing to remove unowned PP-OCRv6 installation')
250
+ const tomb = dest.root + '.removing-' + randomUUID()
251
+ await rename(dest.root, tomb)
252
+ await rm(tomb, { recursive: true, force: true })
253
+ return { ok: true, installed: false, engine: 'ppocrv6' }
254
+ }
255
+ export async function mutateOptionalOcr({ engine, action, archive, adapters = {} }) {
256
+ if (mutating) throw Error('another OCR installation operation is already running')
257
+ if (!['tesseract', 'ppocrv6'].includes(engine) || !['install', 'uninstall'].includes(action)) throw Error('invalid OCR operation')
258
+ if (engine === 'ppocrv6' && action === 'install' && !Buffer.isBuffer(archive)) throw Error('a local PP-OCRv6 bundle is required')
259
+ mutating = true
260
+ try {
261
+ if (engine === 'tesseract') {
262
+ return action === 'install' ? await (adapters.installTesseract ?? installTesseract)()
263
+ : await (adapters.uninstallTesseract ?? uninstallTesseract)()
264
+ }
265
+ return action === 'install'
266
+ ? await (adapters.installNativeBundle ?? installNativeBundle)(archive)
267
+ : await (adapters.uninstallNative ?? uninstallNative)()
268
+ } finally { mutating = false }
269
+ }
270
+ export async function runManagedTesseractOcr(bytes, { timeoutMs = 12000, signal } = {}) {
271
+ const dest = managedTesseractPaths()
272
+ if (!await verifyManaged(dest.root)) throw Error('managed Tesseract unavailable')
273
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 8 || bytes.byteLength > 24 * 1024 * 1024)
274
+ throw Error('OCR image outside managed Tesseract bounds')
275
+ if (signal?.aborted) throw Error('OCR aborted')
276
+ if (activeManagedRuns >= 2) throw Error('managed Tesseract busy')
277
+ activeManagedRuns++
278
+ try {
279
+ const script = fileURLToPath(new URL('./managed-tesseract-child.js', import.meta.url))
280
+ return await new Promise((resolve, reject) => {
281
+ const child = spawn(process.execPath, [script, dest.root], {
282
+ shell: false, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'],
283
+ env: { ...nodeChildEnvironment(), DVR_OCR_CHILD: '1' },
284
+ })
285
+ let output = ''
286
+ let expired = false
287
+ let done = false
288
+ const finish = (error, result) => {
289
+ if (done) return
290
+ done = true
291
+ clearTimeout(timer)
292
+ signal?.removeEventListener('abort', onAbort)
293
+ if (error) reject(error)
294
+ else resolve(result)
295
+ }
296
+ const onAbort = () => {
297
+ expired = true
298
+ child.kill()
299
+ finish(Error('OCR aborted'))
300
+ }
301
+ const timer = setTimeout(() => {
302
+ expired = true
303
+ child.kill()
304
+ finish(Error('managed Tesseract timeout'))
305
+ }, Math.max(1, Math.min(120000, timeoutMs)))
306
+ timer.unref?.()
307
+ signal?.addEventListener('abort', onAbort, { once: true })
308
+ child.stdout.on('data', part => {
309
+ output += String(part)
310
+ if (output.length > 128 * 1024) {
311
+ child.kill()
312
+ finish(Error('managed Tesseract output too large'))
313
+ }
314
+ })
315
+ child.stderr.resume()
316
+ child.on('error', () => finish(Error('managed Tesseract could not start')))
317
+ child.on('close', code => {
318
+ if (expired || done) return
319
+ if (code !== 0) return finish(Error('managed Tesseract worker failed'))
320
+ try {
321
+ const data = JSON.parse(output)
322
+ if (typeof data?.text !== 'string' || !Number.isFinite(data.confidence)) throw Error('invalid result')
323
+ finish(null, { engine: 'tesseract', text: data.text.trim(), confidence: data.confidence })
324
+ } catch { finish(Error('managed Tesseract output invalid')) }
325
+ })
326
+ child.stdin.on('error', () => {})
327
+ child.stdin.end(Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength))
328
+ })
329
+ } finally { activeManagedRuns-- }
330
+ }
@@ -0,0 +1,87 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { isLocalUiRequest } from './web-capability-boundary.js'
3
+ import { mutateOptionalOcr, optionalOcrStatus } from './optional-ocr-engines.js'
4
+
5
+ export const OPTIONAL_OCR_ROUTE = '/_dsh/vision-router/local-ocr'
6
+ const MAX_BUNDLE_BYTES = 64 * 1024 * 1024
7
+ function respond(res, status, data) {
8
+ res.writeHead(status, {
9
+ 'content-type': 'application/json; charset=utf-8',
10
+ 'cache-control': 'no-store',
11
+ 'x-content-type-options': 'nosniff',
12
+ })
13
+ res.end(JSON.stringify(data))
14
+ }
15
+ async function archiveFromRequest(req) {
16
+ const len = req.headers?.['content-length']
17
+ if (len !== undefined && (!/^\d+$/.test(String(len)) || Number(len) > MAX_BUNDLE_BYTES))
18
+ throw Error('bundle too large')
19
+ if (String(req.headers?.['content-type'] ?? '').split(';')[0].trim() !== 'application/octet-stream')
20
+ throw Error('expected a single binary OCR archive')
21
+ const blocks = []
22
+ let length = 0
23
+ for await (const part of req) {
24
+ length += part.length
25
+ if (length > MAX_BUNDLE_BYTES) throw Error('bundle too large')
26
+ blocks.push(part)
27
+ }
28
+ if (length < 128) throw Error('missing OCR bundle')
29
+ return Buffer.concat(blocks, length)
30
+ }
31
+ export function installOptionalOcrRoutes(ctx, {
32
+ statusReader = optionalOcrStatus,
33
+ mutate = mutateOptionalOcr,
34
+ tokenFactory = () => randomBytes(24).toString('base64url'),
35
+ } = {}) {
36
+ if (!ctx || typeof ctx.inject !== 'function') return
37
+ let token = tokenFactory()
38
+ let inFlight = false
39
+ ctx.inject(['webServer'], (webCtx) => {
40
+ webCtx.effect(() => webCtx.webServer.register({
41
+ kind: 'exact',
42
+ path: OPTIONAL_OCR_ROUTE,
43
+ handler: async (req, res) => {
44
+ if (!isLocalUiRequest(req)) return respond(res, 403, { ok: false, error: 'local DSH UI required' })
45
+ if (req.method === 'GET') {
46
+ try {
47
+ const state = await statusReader()
48
+ return respond(res, 200, { ...state, token })
49
+ } catch {
50
+ return respond(res, 500, { ok: false, error: 'local OCR status unavailable' })
51
+ }
52
+ }
53
+ if (req.method !== 'POST') {
54
+ res.setHeader('Allow', 'GET, POST')
55
+ return respond(res, 405, { ok: false, error: 'method not allowed' })
56
+ }
57
+ const fetchSite = String(req.headers?.['sec-fetch-site'] ?? '')
58
+ if (fetchSite && fetchSite !== 'same-origin' && fetchSite !== 'none')
59
+ return respond(res, 403, { ok: false, error: 'cross-origin OCR operation rejected' })
60
+ if (String(req.headers?.['x-dsh-vision-router-ocr-token'] ?? '') !== token || !token)
61
+ return respond(res, 403, { ok: false, error: 'invalid OCR operation token' })
62
+ let url
63
+ try { url = new URL(req.url, 'http://localhost') }
64
+ catch { return respond(res, 400, { ok: false, error: 'invalid request' }) }
65
+ const engine = url.searchParams.get('engine')
66
+ const action = url.searchParams.get('action')
67
+ if (!['tesseract', 'ppocrv6'].includes(engine) || !['install', 'uninstall'].includes(action))
68
+ return respond(res, 400, { ok: false, error: 'unsupported OCR operation' })
69
+ if (inFlight) return respond(res, 409, { ok: false, error: 'OCR installation already running' })
70
+ inFlight = true
71
+ try {
72
+ const archive = engine === 'ppocrv6' && action === 'install'
73
+ ? await archiveFromRequest(req) : undefined
74
+ const result = await mutate({ engine, action, archive })
75
+ token = tokenFactory()
76
+ return respond(res, 200, result)
77
+ } catch (error) {
78
+ const message = String(error?.message ?? '')
79
+ const expected = /(?:missing|not installed|already exists|unavailable|busy|invalid|integrity|unsupported|untrusted|not approved|too large|OCR bundle|unowned|refusing|timed out|failed|mismatch)/i.test(message)
80
+ return respond(res, expected ? 409 : 500, {
81
+ ok: false, error: expected ? message.slice(0, 240) : 'local OCR management failed',
82
+ })
83
+ } finally { inFlight = false }
84
+ },
85
+ }), 'vision-router: optional local OCR manager')
86
+ })
87
+ }
@@ -108,6 +108,8 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
108
108
  var updatePair=React.useState({status:'idle'}),updateState=updatePair[0],setUpdateState=updatePair[1];
109
109
  var selfUpdatePair=React.useState({status:'idle'}),selfUpdateState=selfUpdatePair[0],setSelfUpdateState=selfUpdatePair[1];
110
110
  var actionPair=React.useState({status:'idle'}),actionState=actionPair[0],setActionState=actionPair[1];
111
+ var ocrPair=React.useState({status:'idle'}),ocrState=ocrPair[0],setOcrState=ocrPair[1];
112
+ var ocrFilePair=React.useState(undefined),ocrFile=ocrFilePair[0],setOcrFile=ocrFilePair[1];
111
113
  var egressStatePair=React.useState(readEgressNoticeDismissed()),egressDismissed=egressStatePair[0],setEgressDismissed=egressStatePair[1];
112
114
  var catalogGen=React.useRef?React.useRef(0):{current:0};
113
115
  var capsGen=React.useRef?React.useRef(0):{current:0};
@@ -137,6 +139,58 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
137
139
  function invalidateCatalog(){catalogGen.current+=1;capsGen.current+=1;setCatalog({status:'idle',groups:[],failures:[]});setCaps({status:'idle',capabilities:{},builtinFallback:[],anonymousRpmPerModel:2});void loadCatalog();void loadCapabilities(false);}
138
140
  React.useEffect(function(){var disposed=false,stops=[];function refresh(){if(!disposed)invalidateCatalog();}void loadCatalog();void loadCapabilities(false);try{if(typeof helpers.subscribeCatalogInvalidations==='function')stops.push(helpers.subscribeCatalogInvalidations(props&&props.remote,refresh));else if(props&&props.remote&&typeof props.remote.$on==='function'){stops.push(props.remote.$on('llm/adapters-updated',refresh));stops.push(props.remote.$on('settings/document-updated',refresh));stops.push(props.remote.$on('credentials/updated',refresh));}}catch(_){}try{if(props&&typeof props.subscribeConnectionReset==='function')stops.push(props.subscribeConnectionReset(refresh));}catch(_){}return function(){disposed=true;catalogGen.current+=1;capsGen.current+=1;stops.forEach(function(stop){try{if(typeof stop==='function')stop();}catch(_){}});};},[props&&props.getConnection,props&&props.remote,props&&props.subscribeConnectionReset]);
139
141
 
142
+ function refreshOptionalOcr(){
143
+ if(!localPage()||typeof fetch!=='function')return Promise.resolve();
144
+ setOcrState(function(previous){return {status:'loading',value:previous.value};});
145
+ return fetch('/_dsh/vision-router/local-ocr',{cache:'no-store'}).then(function(response){
146
+ return response.json().then(function(body){if(!response.ok||!body||body.ok!==true)throw Error(body&&body.error?body.error:'HTTP '+response.status);return body;});
147
+ }).then(function(value){setOcrState({status:'ready',value:value});},function(error){setOcrState({status:'error',error:error&&error.message?error.message:String(error)});});
148
+ }
149
+ React.useEffect(function(){if(localPage())void refreshOptionalOcr();},[]);
150
+ function runOptionalOcr(engine,action){
151
+ var value=ocrState.value;
152
+ if(!localPage()||!value||!value.token||ocrState.status!=='ready'||typeof fetch!=='function')return Promise.resolve();
153
+ if(engine==='ppocrv6'&&action==='install'&&!ocrFile)return Promise.resolve();
154
+ if(action==='uninstall'){
155
+ try{if(typeof window.confirm==='function'&&!window.confirm(tx('卸载此插件管理的 '+(engine==='ppocrv6'?'PP-OCRv6':'Tesseract')+' 文件?不会卸载系统其他软件。','Remove plugin-managed '+(engine==='ppocrv6'?'PP-OCRv6':'Tesseract')+' files? System-wide packages will be untouched.')))return Promise.resolve();}catch(_){}
156
+ }
157
+ setOcrState({status:'running',value:value});
158
+ var headers={'x-dsh-vision-router-ocr-token':value.token};
159
+ var file=engine==='ppocrv6'&&action==='install'?ocrFile:undefined;
160
+ if(file)headers['content-type']='application/octet-stream';
161
+ return fetch('/_dsh/vision-router/local-ocr?engine='+encodeURIComponent(engine)+'&action='+encodeURIComponent(action),{
162
+ method:'POST',cache:'no-store',headers:headers,body:file
163
+ }).then(function(response){return response.json().then(function(body){if(!response.ok||!body||body.ok!==true)throw Error(body&&body.error?body.error:'HTTP '+response.status);return body;});})
164
+ .then(function(){if(action==='install')setOcrFile(undefined);return refreshOptionalOcr();},function(error){setOcrState({status:'error',value:value,error:error&&error.message?error.message:String(error)});});
165
+ }
166
+ function optionalOcrPanel(){
167
+ var value=ocrState.value||{},tess=value.tesseract||{},pp=value.ppocrv6||{},busy=ocrState.status==='running'||value.busy===true;
168
+ if(!localPage())return h('p',{className:'vr-hint'},tx('本地 OCR 管理仅可在运行 DSH 的本机打开。','Local OCR management is only available in the local DSH UI.'));
169
+ return card([
170
+ h('h4',{className:'vr-ia-subtitle',key:'heading'},tx('可选本地 OCR','Optional local OCR')),
171
+ h('p',{className:'vr-hint',key:'hint'},tx('两套引擎都不强制安装。没安装时仍可按照既有隐私设置使用视觉模型回退;云端回退可能上传图片。','Both engines are optional. Without a local OCR engine, the configured vision model may handle OCR; a cloud model may receive the image.')),
172
+ h('div',{className:'vr-ia-actions',key:'refresh'},h('button',{type:'button',className:'vr-btn',disabled:busy,onClick:function(){void refreshOptionalOcr();}},tx('刷新安装状态','Refresh installation status'))),
173
+ h('div',{className:'vr-field',key:'tesseract'},
174
+ h('strong',null,'Tesseract (WASM)'),
175
+ h('p',{className:'vr-hint'},ocrState.status==='loading'?tx('检测中…','Checking…'):tess.managedInstalled?tx('插件私有安装已就绪(简体中文+英文,离线识别)。','Plugin-managed installation ready (Chinese + English, offline).'):tess.systemInstalled?tx('系统 Tesseract(简体中文+英文)已可使用,无需额外安装。','System Tesseract with Chinese and English is ready; no additional installation needed.'):tx('未安装。仅点击安装时才下载 WASM 与语言数据;卸载不会修改系统软件。','Not installed. WASM and languages are downloaded only on request. Uninstall never changes system packages.')),
176
+ h('div',{className:'vr-ia-actions'},
177
+ h('button',{type:'button',className:'vr-btn vr-btn-save',disabled:busy||ocrState.status!=='ready'||tess.managedInstalled||tess.canInstall!==true,onClick:function(){void runOptionalOcr('tesseract','install');}},tx('安装 Tesseract','Install Tesseract')),
178
+ h('button',{type:'button',className:'vr-btn',disabled:busy||ocrState.status!=='ready'||tess.canUninstall!==true,onClick:function(){void runOptionalOcr('tesseract','uninstall');}},tx('卸载插件版','Remove plugin copy'))
179
+ )
180
+ ),
181
+ h('div',{className:'vr-field',key:'ppocrv6'},
182
+ h('strong',null,'PP-OCRv6 small / ncnn'),
183
+ h('p',{className:'vr-hint'},!pp.supported?tx('此平台暂无审核通过的本地原生引擎。','Native engine not qualified for this platform.'):pp.installed?tx('已经安装且完整性校验通过。','Installed and integrity-verified.'):pp.damaged?tx('检测到插件管理的安装文件损坏;可点击卸载后重新导入可信离线包。','Managed installation is damaged; you may remove it and import a trusted bundle again.'):tx('尚未安装。原生包公开分发审核未完成;当前只能选择你已合法获得的可信本地安装包。','Not installed. Public native-bundle redistribution is not cleared; only an owner-provided trusted local archive can be imported.')),
184
+ pp.supported?h('input',{className:'vr-input',type:'file',accept:'.tar.gz,.tgz,application/gzip','aria-label':tx('选择 PP-OCRv6 离线包','Choose PP-OCRv6 offline bundle'),disabled:busy||ocrState.status!=='ready',onChange:function(event){setOcrFile(event.target.files&&event.target.files[0]||undefined);}}):null,
185
+ h('div',{className:'vr-ia-actions'},
186
+ h('button',{type:'button',className:'vr-btn vr-btn-save',disabled:busy||ocrState.status!=='ready'||!pp.supported||!ocrFile||ocrFile.size>64*1024*1024,onClick:function(){void runOptionalOcr('ppocrv6','install');}},tx('安装所选离线包','Install selected bundle')),
187
+ h('button',{type:'button',className:'vr-btn',disabled:busy||ocrState.status!=='ready'||!pp.canUninstall,onClick:function(){void runOptionalOcr('ppocrv6','uninstall');}},tx('卸载 PP-OCRv6','Remove PP-OCRv6'))
188
+ )
189
+ ),
190
+ ocrState.status==='running'?h('p',{className:'vr-hint',key:'busy',role:'status'},tx('安装或卸载正在进行,请保持此页面打开。','Installation or removal in progress. Keep this page open.')):null,
191
+ ocrState.status==='error'?h('p',{className:'vr-failed',key:'error',role:'alert'},String(ocrState.error||tx('本地 OCR 操作失败','Local OCR operation failed'))):null
192
+ ]);
193
+ }
140
194
  function runTestConnection(){if(!localPage()||typeof fetch!=='function'||testState.status==='running')return Promise.resolve();setTestState({status:'running'});return fetch('/_dsh/vision-router/test-connection',{cache:'no-store'}).then(function(response){return response.json().catch(function(){return undefined;}).then(function(body){if(!response.ok)throw new Error(body&&body.error?body.error:'HTTP '+response.status);return body;});}).then(function(body){setTestState({status:'done',result:body||{ok:false,error:'empty response'}});},function(error){setTestState({status:'done',result:{ok:false,error:error&&error.message?error.message:String(error)}});});}
141
195
  function runUpdateCheck(force){if(!localPage()||typeof fetch!=='function'||updateState.status==='running')return Promise.resolve();setUpdateState({status:'running',result:updateState.result});return fetch('/_dsh/vision-router/update-check'+(force?'?force=1':''),{cache:'no-store'}).then(function(response){return response.json().catch(function(){return undefined;}).then(function(body){if(!response.ok)throw new Error(body&&body.error?body.error:'HTTP '+response.status);return body;});}).then(function(body){setUpdateState({status:'done',result:body});},function(error){setUpdateState({status:'done',result:{ok:false,error:error&&error.message?error.message:String(error)}});});}
142
196
  function runSelfUpdate(){var checked=updateState.result,auto=checked&&checked.autoUpdate;if(!localPage()||selfUpdateState.status==='running'||!checked||checked.ok!==true||checked.updateAvailable!==true||!auto||!auto.token)return Promise.resolve();try{if(typeof window.confirm==='function'&&window.confirm(tx('确认更新 Vision Router?更新完成后需要重启 DSH。','Update Vision Router? Restart DSH after the update.'))!==true)return Promise.resolve();}catch(_){}setSelfUpdateState({status:'running'});return fetch('/_dsh/vision-router/self-update',{method:'POST',cache:'no-store',headers:{'x-dsh-vision-router-update-token':auto.token}}).then(function(response){return response.json().catch(function(){return undefined;}).then(function(body){if(!response.ok||!body||body.ok!==true)throw new Error(body&&body.error?body.error:'HTTP '+response.status);return body;});}).then(function(body){setSelfUpdateState({status:'done',result:body});void runUpdateCheck(true);},function(error){setSelfUpdateState({status:'done',error:error&&error.message?error.message:String(error)});});}
@@ -360,7 +414,7 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
360
414
  );
361
415
  }
362
416
  function localProviderCard(key,label,defaults,which){var current=Object.assign({},defaults,obj(value(key,{}))),opened=which==='ollama'?open.ollama:open.lmstudio;function update(patch){setValue(key,Object.assign({},current,patch));}function sample(name,min,max){return h('div',{className:'vr-field'},h('span',{className:'vr-label'},name),h('input',{className:'vr-input',type:'number',step:'0.1',min:min,max:max,value:current[name]===undefined?'':current[name],disabled:!writable||saving,onChange:function(event){var patch={};patch[name]=event.target.value===''?undefined:Number(event.target.value);update(patch);}}));}return card([h('div',{className:'vr-ia-backend-head',key:'head'},h('div',null,h('div',{className:'vr-ia-field-head'},h('strong',null,label),override(key)),h('p',{className:'vr-hint'},current.enabled?tx('已启用','Enabled'):tx('未启用','Disabled'))),h('input',{type:'checkbox',checked:current.enabled===true,disabled:!writable||saving,onChange:function(event){update({enabled:event.target.checked});}})),h('div',{className:'vr-field',key:'model'},h('span',{className:'vr-label'},tx('模型','Model')),h('input',{className:'vr-input',value:String(current.model||''),disabled:!writable||saving,onChange:function(event){update({model:event.target.value});}}),key==='localLmStudio'&&invalidKeys.includes(key)?h('p',{className:'vr-failed'},tx('启用 LM Studio 时必须填写真实模型标识。','A real model id is required when LM Studio is enabled.')):null),h('div',{className:'vr-field',key:'url'},h('span',{className:'vr-label'},tx('服务地址','Service URL')),h('input',{className:'vr-input',value:String(current.baseURL||''),disabled:!writable||saving,onChange:function(event){update({baseURL:event.target.value});}})),h('button',{type:'button',className:'vr-btn',onClick:function(){setOpen(Object.assign({},open,which==='ollama'?{ollama:!opened}:{lmstudio:!opened}));}},opened?tx('收起高级连接设置','Hide advanced connection settings'):tx('高级连接设置','Advanced connection settings')),opened?h('div',{className:'vr-ia-subgrid',key:'advanced'},h('div',{className:'vr-field'},h('span',{className:'vr-label'},tx('请求协议','Request protocol')),h('select',{className:'vr-input',value:current.format==='anthropic'?'anthropic':current.format==='lmstudio'?'lmstudio':'openai',disabled:!writable||saving,onChange:function(event){update({format:event.target.value});}},h('option',{value:'openai'},'OpenAI'),h('option',{value:'anthropic'},'Anthropic'),which==='lmstudio'?h('option',{value:'lmstudio'},tx('LM Studio 原生','LM Studio native')):null)),h('div',{className:'vr-field'},h('span',{className:'vr-label'},tx('最大输出 token','Max output tokens')),h('input',{className:'vr-input',type:'number',step:'256',min:'256',max:'32768',value:String(current.maxTokens||4096),disabled:!writable||saving,onChange:function(event){update({maxTokens:Number(event.target.value)});}})),h('div',{className:'vr-field'},h('span',{className:'vr-label'},tx('推理强度','Reasoning effort')),h('select',{className:'vr-input',value:String(current.reasoningEffort||defaults.reasoningEffort||'provider_default'),disabled:!writable||saving||(which==='lmstudio'?current.format!=='lmstudio':current.format==='anthropic'),onChange:function(event){update({reasoningEffort:event.target.value});}},h('option',{value:'provider_default'},tx('服务端默认','Provider default')),h('option',{value:'none'},tx('关闭推理','Disable reasoning')),h('option',{value:'low'},'low'),h('option',{value:'medium'},'medium'),h('option',{value:'high'},'high'),h('option',{value:'max'},'max'))),sample('temperature',0,2),sample('top_p',0,1)):null]);}
363
- function localPageContent(){return h(React.Fragment,null,title(tx('本地与设备','Local & device'),tx('本地视觉可让图像像素留在本机;但若云端识图行或免费兜底仍开启,失败时仍可能出网,识图结果也会交给当前聊天模型。','Local vision can keep image pixels on this machine. Cloud vision rows or the free fallback may still send them off-device after a failure, and vision result text is still passed to the current chat model.')),localProviderCard('localOllama','Ollama',{enabled:false,baseURL:'http://127.0.0.1:11434/v1',model:'qwen2.5vl',format:'openai',maxTokens:4096,reasoningEffort:'none'},'ollama'),localProviderCard('localLmStudio','LM Studio',{enabled:false,baseURL:'http://localhost:1234/v1',model:'',format:'openai',maxTokens:4096,reasoningEffort:'none'},'lmstudio'),card([toggle('desktopScreenshot',tx('允许 Agent 读取桌面截图','Allow the agent to capture the desktop'),tx('这是独立的隐私权限;macOS 上保存为开启后会立即触发屏幕录制权限检查。','This is a separate privacy permission; on macOS saving it enabled immediately triggers the screen-recording permission check.'))]));}
417
+ function localPageContent(){return h(React.Fragment,null,title(tx('本地与设备','Local & device'),tx('本地视觉可让图像像素留在本机;但若云端识图行或免费兜底仍开启,失败时仍可能出网,识图结果也会交给当前聊天模型。','Local vision can keep image pixels on this machine. Cloud vision rows or the free fallback may still send them off-device after a failure, and vision result text is still passed to the current chat model.')),localProviderCard('localOllama','Ollama',{enabled:false,baseURL:'http://127.0.0.1:11434/v1',model:'qwen2.5vl',format:'openai',maxTokens:4096,reasoningEffort:'none'},'ollama'),localProviderCard('localLmStudio','LM Studio',{enabled:false,baseURL:'http://localhost:1234/v1',model:'',format:'openai',maxTokens:4096,reasoningEffort:'none'},'lmstudio'),optionalOcrPanel(),card([toggle('desktopScreenshot',tx('允许 Agent 读取桌面截图','Allow the agent to capture the desktop'),tx('这是独立的隐私权限;macOS 上保存为开启后会立即触发屏幕录制权限检查。','This is a separate privacy permission; on macOS saving it enabled immediately triggers the screen-recording permission check.'))]));}
364
418
  function wrappersEditor(){var rows=wrapperRows();return h('div',{className:'vr-field'},fieldHead('wrappedProviders',tx('哪些聊天模型可以开启识图','Which chat models can use Vision mode')),h('p',{className:'vr-hint'},tx('通常无需修改;模型留空表示整个 Provider。','Usually leave this alone; an empty model means the whole provider.')),rows.map(function(row,index){return modelRow(row,index,rows,setWrapperDraft,true);}),h('button',{type:'button',className:'vr-btn',disabled:!writable||saving,onClick:function(){setWrapperDraft(rows.concat([{provider:'',model:''}]))}},tx('+ 添加范围','+ Add scope')));}
365
419
  function textProviderEditor(){var current=Object.assign({provider:'',model:''},obj(value('textProvider',{}))),ready=groups.length>0;return h('div',{className:'vr-field'},fieldHead('textProvider',tx('文字回退模型','Text fallback model')),h('div',{className:'vr-chain-row'},ready?h('select',{className:'vr-input',value:current.provider||'',disabled:!writable||saving,onChange:function(event){setValue('textProvider',{provider:event.target.value,model:''});}},providerOptions(current.provider||'')):h('input',{className:'vr-input',value:current.provider||'',disabled:!writable||saving,onChange:function(event){setValue('textProvider',{provider:event.target.value,model:current.model||''});}}),ready?h('select',{className:'vr-input',value:current.model||'',disabled:!writable||saving||!current.provider,onChange:function(event){setValue('textProvider',{provider:current.provider||'',model:event.target.value});}},modelOptions(current.provider||'',current.model||'',false)):h('input',{className:'vr-input',value:current.model||'',disabled:!writable||saving,onChange:function(event){setValue('textProvider',{provider:current.provider||'',model:event.target.value});}})),invalidKeys.includes('textProvider')?h('p',{className:'vr-failed'},tx('Provider 和 model 必须同时填写,或同时留空恢复默认。','Provider and model must both be filled, or both left empty to restore the default.')):null);}
366
420
  function advancedPage(){var routing=toggleValue('routing',false),turnBudget=Number(value('visionTurnBudgetMs',0))||0,customBudget=turnBudget>0;return h(React.Fragment,null,title(tx('高级','Advanced'),tx('这些默认值对大多数用户已经合适。','Defaults are suitable for most users.')),card([h('h4',{className:'vr-ia-subtitle',key:'p'},tx('性能与稳定性','Performance & stability')),toggle('downscale',tx('自动缩放','Auto downscale')),numberField('downscaleMaxPixels',tx('图片像素上限','Image pixel limit'),null,1000,100000000),toggle('cache',tx('识图缓存','Vision answer cache')),numberField('cacheTtlSeconds',tx('缓存有效期(秒)','Cache TTL (seconds)'),null,0,31536000),numberField('cacheMaxEntries',tx('最大缓存数量','Maximum cached answers'),null,1,100000),h('h4',{className:'vr-ia-subtitle',key:'t'},tx('超时','Timeouts')),numberField('timeoutMs',tx('单次模型请求','Single model request'),tx('毫秒。','Milliseconds.'),1000,600000),numberField('visionTaskTimeoutMs',tx('单个视觉任务','Single visual task'),tx('包含该任务内部的重试和备用模型;不是每个后端各自一份。','Includes retries and fallbacks inside the task; it is not a fresh budget per backend.'),1000,180000),numberField('ocrTimeoutMs',tx('OCR 任务','OCR task'),null,1000,120000),h('div',{className:'vr-field',key:'ocr-engine'},fieldHead('ocrEngine',tx('OCR 默认引擎','Default OCR engine')),h('select',{className:'vr-input',value:String(value('ocrEngine','auto')||'auto'),disabled:!writable||saving,onChange:function(event){setValue('ocrEngine',event.target.value);}},h('option',{value:'auto'},tx('自动(PP-OCRv6 → Tesseract → 视觉模型)','Auto (PP-OCRv6 → Tesseract → vision)')),h('option',{value:'tesseract'},tx('仅 Tesseract','Tesseract only')),h('option',{value:'vision'},tx('仅视觉模型','Vision model only'))),h('p',{className:'vr-hint'},tx('vision_ocr 未显式指定 engine 时使用;单次调用的 engine=tesseract/vision 始终优先。','Used when vision_ocr does not explicitly choose an engine; per-call engine=tesseract/vision always wins.'))),h('div',{className:'vr-field',key:'budget'},fieldHead('visionTurnBudgetMs',tx('整轮视觉工具上限','Whole-turn vision-tool limit')),h('select',{className:'vr-input',value:customBudget?'custom':'unlimited',disabled:!writable||saving,onChange:function(event){setValue('visionTurnBudgetMs',event.target.value==='unlimited'?0:(turnBudget>0?turnBudget:180000));}},h('option',{value:'unlimited'},tx('不限制(推荐)','Unlimited (recommended)')),h('option',{value:'custom'},tx('自定义','Custom'))),customBudget?numberField('visionTurnBudgetMs',tx('上限(毫秒)','Limit (ms)'),null,10000,600000):null)]),card([h('h4',{className:'vr-ia-subtitle',key:'cost'},tx('模型顺序与成本','Model order & cost')),toggle('freeCloudFirst',tx('免费云模型优先','Try free cloud models first'))]),card([h('h4',{className:'vr-ia-subtitle',key:'scope'},tx('识图模式范围','Vision mode scope')),toggle('autoWrapProviders',tx('自动允许已启用模型使用识图','Automatically allow enabled models to use Vision mode')),wrappersEditor()]),card([h('h4',{className:'vr-ia-subtitle',key:'network'},tx('网络与远程','Network & remote')),h('p',{className:'vr-hint',key:'network-authority'},tx('默认沿用 DSH/Host 的网络出口;只有需要让视觉请求走不同出口时才填写下方覆盖。','By default Vision Router follows the DSH/Host network path. Use the override below only when vision requests need a different egress route.')),local?toggle('allowRemoteSettings',tx('允许可信 Host 远程修改设置','Allow trusted-host remote settings'),tx('默认关闭;trustedHosts 不是身份认证。','Off by default; trustedHosts is not authentication.')):null,textField('proxy',tx('视觉专用代理覆盖','Vision-only proxy override'),tx('留空即沿用 DSH/Host;支持 http(s)://、socks5://,并兼容旧 socks5h://。','Leave empty to follow DSH/Host; supports http(s):// and socks5://, with legacy socks5h:// compatibility.')),textareaArray('proxyHosts',tx('视觉代理覆盖域名','Vision proxy override hosts'),tx('仅在上方覆盖非空时生效;每行一个,其余请求继续沿用 DSH/Host。','Used only when the override above is non-empty; one host per line. All other requests keep the DSH/Host path.'))]),card([h('h4',{className:'vr-ia-subtitle',key:'compat'},tx('兼容模式','Compatibility')),toggle('rewriteImages',tx('保护纯文本模型','Protect text-only models')),toggle('routing',tx('整轮视觉路由(旧工作流)','Whole-turn vision routing (legacy workflow)')),routing?toggle('reverseRouting',tx('纯文字消息继续使用聊天模型','Keep text-only messages on the chat model')):null,routing?textProviderEditor():null]),card([h('button',{type:'button',className:'vr-btn',key:'dev',onClick:function(){setOpen(Object.assign({},open,{developer:!open.developer}));}},open.developer?tx('隐藏开发者设置','Hide developer settings'):tx('显示开发者设置','Show developer settings')),open.developer?h('div',{className:'vr-ia-dev',key:'body'},toggle('progressiveTools',tx('渐进式工具暴露','Progressive tool exposure')),h('p',{className:'vr-hint',key:'progressive-restart'},tx('保存后需重启 DSH 才生效。','Restart DSH after saving for this change to take effect.')),toggle('stealth','Stealth'),textField('wrapperRoute',tx('包装路由名','Wrapper route name')),textField('chainRoute',tx('视觉链路由名','Vision chain route name')),textareaArray('extraVisionModels',tx('额外视觉能力标记','Extra vision capability labels'),tx('只有诊断发现模型未声明图片能力时才需要。','Needed only when diagnostics show missing image-capability metadata.'))):null]));}
@@ -23,6 +23,10 @@ const ROUTE_CAPABILITY_POLICIES = new Map([
23
23
  ['/_dsh/vision-router/self-update', new Map([
24
24
  ['POST', { remote: WEB_ROUTE_REMOTE_CAPABILITY.LOCAL_ONLY, legacyMutation: true }],
25
25
  ])],
26
+ ['/_dsh/vision-router/local-ocr', new Map([
27
+ ['GET', { remote: WEB_ROUTE_REMOTE_CAPABILITY.LOCAL_ONLY }],
28
+ ['POST', { remote: WEB_ROUTE_REMOTE_CAPABILITY.LOCAL_ONLY, legacyMutation: true }],
29
+ ])],
26
30
  ['/_dsh/vision-router/logs', new Map([
27
31
  ['GET', { remote: WEB_ROUTE_REMOTE_CAPABILITY.REDACT_REMOTE }],
28
32
  ['POST', { remote: WEB_ROUTE_REMOTE_CAPABILITY.LOCAL_ONLY, legacyMutation: true }],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-vision-router",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
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": {
@@ -86,8 +86,8 @@
86
86
  "typescript": "6.0.3"
87
87
  },
88
88
  "scripts": {
89
- "test": "node --test tests/dsh-alpha-pin.test.js tests/dsh-rc1-pin.test.js tests/dsh-rc2-pin.test.js tests/dsh-rc3-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/desktop-e2e-watchdog.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/required-ci-contract.test.js tests/ci-electron-download-retry.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/vision-tool-stage.test.js tests/vision-image-input-reader.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 && node --test tests/vision-trace-vtracer.test.js tests/vision-trace-image-quality.test.js && pnpm license:check && node --test tests/native-ocr-annotation-risk.test.js tests/native-ocr-bundle.test.js tests/native-ocr-canary.test.js tests/native-ocr-chemistry-review.test.js tests/native-ocr-document.test.js tests/native-ocr-host-canary.test.js tests/native-ocr-installation.test.js tests/native-ocr-integrity.test.js tests/native-ocr-provenance.test.js tests/native-ocr-question-labels.test.js tests/native-ocr-supervisor.test.js tests/issue-836-ocr-regression.test.js",
90
- "test:core": "node --test tests/vision-image-input-reader.test.js tests/vision-tool-stage.test.js 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",
89
+ "test": "node --test tests/dsh-alpha-pin.test.js tests/dsh-rc1-pin.test.js tests/dsh-rc2-pin.test.js tests/dsh-rc3-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/desktop-e2e-watchdog.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/required-ci-contract.test.js tests/ci-electron-download-retry.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/vision-tool-stage.test.js tests/vision-image-input-reader.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 && node --test tests/vision-trace-vtracer.test.js tests/vision-trace-image-quality.test.js && pnpm license:check && node --test tests/native-ocr-annotation-risk.test.js tests/native-ocr-bundle.test.js tests/native-ocr-canary.test.js tests/native-ocr-chemistry-review.test.js tests/native-ocr-document.test.js tests/native-ocr-host-canary.test.js tests/native-ocr-installation.test.js tests/native-ocr-integrity.test.js tests/native-ocr-provenance.test.js tests/native-ocr-question-labels.test.js tests/native-ocr-supervisor.test.js tests/issue-836-ocr-regression.test.js tests/optional-local-ocr.test.js",
90
+ "test:core": "node --test tests/vision-image-input-reader.test.js tests/vision-tool-stage.test.js 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 tests/optional-local-ocr.test.js",
91
91
  "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",
92
92
  "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",
93
93
  "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",