dsh-vision-router 3.0.5 → 3.1.1

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/index.js CHANGED
@@ -58,9 +58,11 @@ import {
58
58
  import { streamWithVisionSessionAffinity } from './lib/session-affinity-runtime.js'
59
59
  import {
60
60
  routingCorrectionFor,
61
+ correctionPreservesRuntimeTransport,
61
62
  toAnthropicMessages,
62
63
  callAnthropicCompatible,
63
64
  } from './lib/catalog-corrections.js'
65
+ import { providerTransportFor } from './lib/live-model-discovery.js'
64
66
  import { getOfficialDeepSeekCatalog } from './lib/official-deepseek-catalog.js'
65
67
  import {
66
68
  classifyVisionFailure,
@@ -1644,6 +1646,25 @@ export function apply(ctx, config = {}, runtime = {}) {
1644
1646
  if (correction === undefined) return undefined
1645
1647
  const rawProfile = rawChannelProfileOf(pair.provider)
1646
1648
  const resolvedProfile = resolvedPiAiProfileOf(pair.provider)
1649
+ // A built-in pi-ai catalog fact is not proof that the user's actual
1650
+ // DSH provider config still uses the official gateway. Refuse to reroute
1651
+ // another gateway's credentials into the hard-coded official endpoint.
1652
+ let activeHostTransport
1653
+ let strictHostTransport
1654
+ try {
1655
+ activeHostTransport = providerTransportFor(ctx, pair.provider)
1656
+ strictHostTransport = providerTransportFor(ctx, pair.provider, { strictBaseURL: true })
1657
+ } catch { return undefined }
1658
+ if (!correctionPreservesRuntimeTransport(
1659
+ correction,
1660
+ activeHostTransport,
1661
+ strictHostTransport,
1662
+ rawProfile,
1663
+ resolvedProfile,
1664
+ // piProvider.api is a registry of wire handlers, not a resolved
1665
+ // protocol string. Only use its baseUrl as optional transport evidence.
1666
+ { baseUrl: resolvedProfile?.piProvider?.baseUrl },
1667
+ )) return undefined
1647
1668
  const apiKeyEnv = [rawProfile, resolvedProfile]
1648
1669
  .map((profile) => (profile && typeof profile.apiKeyEnv === 'string' ? profile.apiKeyEnv : ''))
1649
1670
  .find((ref) => ref !== '')
@@ -33,7 +33,7 @@ export const CATALOG_ROUTING_CORRECTIONS = [
33
33
  // The exact broken configuration this correction recognizes. A route the
34
34
  // user pointed elsewhere (or a catalog fixed upstream) never engages it.
35
35
  wrongApi: 'openai-completions',
36
- wrongBaseURLPrefix: 'opencode.ai/zen/go',
36
+ wrongBaseURLRoot: 'https://opencode.ai/zen/go',
37
37
  },
38
38
  {
39
39
  provider: 'opencode-go',
@@ -44,10 +44,69 @@ export const CATALOG_ROUTING_CORRECTIONS = [
44
44
  api: 'anthropic-messages',
45
45
  baseURL: 'https://opencode.ai/zen/go',
46
46
  wrongApi: 'openai-completions',
47
- wrongBaseURLPrefix: 'opencode.ai/zen/go',
47
+ wrongBaseURLRoot: 'https://opencode.ai/zen/go',
48
48
  },
49
49
  ]
50
50
 
51
+ /**
52
+ * Reject lookalike/cross-origin or altered path catalog URLs. The correction
53
+ * owns only the official OpenCode Go gateway and its two documented *base*
54
+ * shapes (/zen/go and /zen/go/v1), never arbitrary custom provider gateways.
55
+ * A substring check would incorrectly match e.g. notopencode.ai/zen/go.
56
+ */
57
+ function matchesDocumentedCatalogBaseURL(actual, expectedRoot) {
58
+ try {
59
+ const url = new URL(String(actual))
60
+ const expected = new URL(String(expectedRoot))
61
+ if (url.protocol !== 'https:' || url.origin !== expected.origin) return false
62
+ if (url.username !== '' || url.password !== '' || url.search !== '' || url.hash !== '') {
63
+ return false
64
+ }
65
+ const actualPath = url.pathname.replace(/\/+$/, '')
66
+ const basePath = expected.pathname.replace(/\/+$/, '')
67
+ return actualPath === basePath || actualPath === `${basePath}/v1`
68
+ } catch {
69
+ return false
70
+ }
71
+ }
72
+
73
+ /**
74
+ * The pi-ai *catalog entry* may still be official even if a Host profile
75
+ * overrides its actual transport. Do not send that profile's credential to
76
+ * a hard-coded corrected endpoint unless every explicit Host transport fact
77
+ * we can observe agrees with the documented original route.
78
+ *
79
+ * Undefined/unconfigured profiles are not positive evidence; the caller must
80
+ * first have proven the precise broken catalog entry via routingCorrectionFor.
81
+ */
82
+ export function correctionPreservesConfiguredTransport(correction, ...profiles) {
83
+ if (!correction?.wrongBaseURLRoot || !correction?.wrongApi) return false
84
+ for (const profile of profiles) {
85
+ if (!profile || typeof profile !== 'object') continue
86
+ for (const actual of [profile.baseURL, profile.baseUrl]) {
87
+ if (actual === undefined || actual === null || actual === '') continue
88
+ if (typeof actual !== 'string' || !matchesDocumentedCatalogBaseURL(actual, correction.wrongBaseURLRoot)) {
89
+ return false
90
+ }
91
+ }
92
+ if (profile.api !== undefined && profile.api !== null && profile.api !== '') {
93
+ if (profile.api !== correction.wrongApi) return false
94
+ }
95
+ }
96
+ return true
97
+ }
98
+
99
+ /**
100
+ * A Host-configured URL with query, fragment or userinfo is allowed to remain
101
+ * a normal DSH route, but must not inherit a catalog correction that hardcodes
102
+ * a different destination. Generic model discovery historically strips those
103
+ * modifiers, so require a second, strict reading of the *same* configuration.
104
+ */
105
+ export function correctionPreservesRuntimeTransport(correction, loose, strict, ...profiles) {
106
+ if (loose !== undefined && strict === undefined) return false
107
+ return correctionPreservesConfiguredTransport(correction, ...profiles, strict)
108
+ }
109
+
51
110
  /**
52
111
  * Decide whether a routing correction engages for one resolved backend.
53
112
  *
@@ -72,12 +131,12 @@ export function routingCorrectionFor(facts, provider, model, enabled = true) {
72
131
  // The resolved route is broken in some OTHER way (or speaks yet another
73
132
  // protocol); not the configuration this correction was written for.
74
133
  if (entry.wrongApi !== undefined && entry.wrongApi !== facts.api) return undefined
75
- // A user route pointed at their own gateway keeps its own routing: only the
76
- // exact catalog baseURL this correction documents gets intercepted.
77
- if (entry.wrongBaseURLPrefix !== undefined) {
78
- const baseUrl = String(facts.baseUrl ?? '')
79
- if (!baseUrl.includes(entry.wrongBaseURLPrefix)) return undefined
80
- }
134
+ // Never override a custom DSH gateway merely because its URL happens to
135
+ // *contain* the official domain and path as text.
136
+ if (
137
+ entry.wrongBaseURLRoot !== undefined &&
138
+ !matchesDocumentedCatalogBaseURL(facts.baseUrl, entry.wrongBaseURLRoot)
139
+ ) return undefined
81
140
  return entry
82
141
  }
83
142
 
package/lib/doctor-cli.js CHANGED
@@ -8,7 +8,7 @@ import { inspectDoctorVisionLimits, formatDoctorVisionLimits } from './doctor-vi
8
8
  import { repairLegacySessionLogs } from './legacy-session-repair.js'
9
9
 
10
10
  function usage() {
11
- return `dsh-vision-router doctor [--profile <name>] [--json] [--sessions] [--runtime-url <url>] [--no-runtime] [--fix]\ndsh-vision-router repair [--profile <name>]\ndsh-vision-router repair-sessions\n\nChecks installation, profile composition, runtime routes, recent settings-save failures and local vision capabilities.\n\nCommands:\n doctor Read-only health report by default. --fix is kept for compatibility but prefer the explicit repair command.\n repair Safely remove a leading UTF-8 BOM and rewrite stale version-pinned minimumReleaseAgeExclude entries.\n repair-sessions Offline repair for exact known Vision Router session corruptions, including the legacy missing-id reminder and duplicate structured guard-stop messages. Stop DSH first.\n\nOptions:\n --profile <name> Check only one profile (for example: web).\n --json Emit a shareable, secret-minimized JSON diagnostic report.\n --sessions Also scan session logs for exact known Vision Router corruption signatures (read-only; may take longer).\n --runtime-url <url> Probe a running DSH web instance (default: DSH_WEB_URL or http://127.0.0.1:3080).\n --no-runtime Skip the read-only runtime route probe.\n --fix Backward-compatible doctor repair mode; prefer \`repair\`.\n --help Show this help.\n`
11
+ return `dsh-vision-router doctor [--profile <name>] [--json | --issue-template] [--sessions] [--runtime-url <url>] [--no-runtime] [--fix]\ndsh-vision-router repair [--profile <name>]\ndsh-vision-router repair-sessions\n\nChecks installation, profile composition, runtime routes, recent settings-save failures and local vision capabilities.\n\nCommands:\n doctor Read-only health report by default. --fix is kept for compatibility but prefer the explicit repair command.\n repair Safely remove a leading UTF-8 BOM and rewrite stale version-pinned minimumReleaseAgeExclude entries.\n repair-sessions Offline repair for exact known Vision Router session corruptions, including the legacy missing-id reminder and duplicate structured guard-stop messages. Stop DSH first.\n\nOptions:\n --profile <name> Check only one profile (for example: web).\n --json Emit a shareable, secret-minimized JSON diagnostic report.\n --issue-template Print a safe, Markdown issue template with diagnostics and fill-in reproduction fields. Read-only.\n --sessions Also scan session logs for exact known Vision Router corruption signatures (read-only; may take longer).\n --runtime-url <url> Probe a running DSH web instance (default: DSH_WEB_URL or http://127.0.0.1:3080).\n --no-runtime Skip the read-only runtime route probe.\n --fix Backward-compatible doctor repair mode; prefer \`repair\`.\n --help Show this help.\n`
12
12
  }
13
13
 
14
14
  function parseArgs(argv) {
@@ -18,6 +18,7 @@ function parseArgs(argv) {
18
18
  let profile
19
19
  let fix = command === 'repair'
20
20
  let json = false
21
+ let issueTemplate = false
21
22
  let sessions = false
22
23
  let runtime = command === 'doctor'
23
24
  let runtimeUrl
@@ -35,6 +36,11 @@ function parseArgs(argv) {
35
36
  json = true
36
37
  continue
37
38
  }
39
+ if (value === '--issue-template') {
40
+ if (command !== 'doctor') throw new Error('--issue-template is only used with doctor')
41
+ issueTemplate = true
42
+ continue
43
+ }
38
44
  if (value === '--sessions') {
39
45
  if (command !== 'doctor') throw new Error('--sessions is only used with doctor')
40
46
  sessions = true
@@ -75,6 +81,8 @@ function parseArgs(argv) {
75
81
  }
76
82
 
77
83
  if (!['doctor', 'repair', 'repair-sessions'].includes(command)) throw new Error(`unknown command: ${command}`)
84
+ if (issueTemplate && json) throw new Error('--issue-template and --json cannot be combined')
85
+ if (issueTemplate && fix) throw new Error('--issue-template is read-only and cannot be combined with --fix')
78
86
  if (profile && (!/^[A-Za-z0-9._-]+$/.test(profile) || profile === '.' || profile === '..')) {
79
87
  throw new Error(`invalid profile name: ${profile}`)
80
88
  }
@@ -83,7 +91,61 @@ function parseArgs(argv) {
83
91
  try { parsed = new URL(runtimeUrl) } catch { throw new Error(`invalid runtime URL: ${runtimeUrl}`) }
84
92
  if (!['http:', 'https:'].includes(parsed.protocol)) throw new Error(`invalid runtime URL protocol: ${parsed.protocol}`)
85
93
  }
86
- return { command, profile, fix, json, sessions, runtime, runtimeUrl }
94
+ return { command, profile, fix, json, issueTemplate, sessions, runtime, runtimeUrl }
95
+ }
96
+
97
+ /**
98
+ * Doctor's pasteable issue report is a *strict allowlist*. It must never turn
99
+ * DSH profile names, endpoint URLs, raw log/error content, dependency specs
100
+ * or local filesystem paths into a user-shared issue body.
101
+ */
102
+ function formatIssueTemplate(report) {
103
+ const number = (value) => Number.isSafeInteger(value) && value >= 0 ? value : 0
104
+ const version = (value) => typeof value === 'string' && /^v?\d+\.\d+\.\d+(?:[-+][a-zA-Z0-9.-]{1,32})?$/.test(value)
105
+ ? value : 'unknown'
106
+ const allowed = (value, values) => values.includes(value) ? value : 'unknown'
107
+ const profiles = Array.isArray(report.profiles) ? report.profiles : []
108
+ const applicable = profiles.filter((profile) => profile.installation?.applicable)
109
+ const failed = applicable.filter((profile) => !profile.validJson || profile.installation?.ok === false)
110
+ const modes = ['bundle', 'manual', 'none', 'unknown'].map((mode) =>
111
+ `${mode}: ${applicable.filter((profile) => profile.installation?.mode === mode).length}`).join(', ')
112
+ const platform = report.platform ?? {}
113
+ const runtime = report.runtime
114
+ const runtimeState = !runtime ? 'not checked'
115
+ : runtime.authenticationRequired ? 'reachable; authentication required (route health unknown)'
116
+ : !runtime.reachable ? 'unreachable (offline checks completed)'
117
+ : runtime.ok ? 'reachable; reported routes OK' : 'reachable; route issues detected'
118
+ const sessionState = !report.sessions ? 'not scanned (opt in with --sessions)'
119
+ : `${number(report.sessions.scanned)} scanned, ${number(report.sessions.affected)} known issue(s), ${number(report.sessions.errorCount)} unreadable`
120
+ const lines = [
121
+ '## DSH Vision Router diagnostic summary',
122
+ '',
123
+ '> Generated locally by `doctor --issue-template`; no report is sent automatically.',
124
+ '> Review before posting. Never include API keys, tokens, cookies, private images, raw prompts, profile paths, or unredacted error bodies.',
125
+ '',
126
+ `- Status: **${report.ok ? 'PASS' : 'NEEDS ATTENTION'}**`,
127
+ `- Doctor version: ${version(report.doctorVersion)}`,
128
+ `- OS / architecture: ${allowed(platform.platform, ['win32', 'darwin', 'linux'])} / ${allowed(platform.arch, ['x64', 'arm64', 'ia32', 'arm', 'ppc64', 's390x'])}`,
129
+ `- Node: ${version(platform.node)} (${platform.nodeSupported ? 'supported' : 'outside or unverified support window'})`,
130
+ `- Vision Router profiles: ${applicable.length} applicable; ${failed.length} installation/problem profile(s)`,
131
+ `- Install modes: ${modes}`,
132
+ `- Runtime: ${runtimeState}`,
133
+ `- Settings save failures: ${number(report.log?.currentSettingsFailureCount)} current / ${number(report.log?.historicalSettingsFailureCount)} historical`,
134
+ `- Known session issues: ${sessionState}`,
135
+ `- Local optional tools: Tesseract ${typeof platform.tesseract?.version === 'string' ? 'detected' : 'not confirmed'}, Chromium ${typeof platform.chromium?.version === 'string' ? 'detected' : 'not confirmed'}`,
136
+ '',
137
+ '## Reproduction details (fill in)',
138
+ '',
139
+ '- DSH version and installation type:',
140
+ '- Provider and exact model ID (if applicable):',
141
+ '- Operation, steps to reproduce, and expected behavior:',
142
+ '- Actual HTTP status / sanitized error code (do not paste raw secrets):',
143
+ '- Result with one small, non-sensitive test PNG:',
144
+ '- Is this intermittent? Frequency / OS if reproducible:',
145
+ '',
146
+ 'Note: The summary deliberately omits profile names, runtime URLs, paths, raw logs and all credentials.',
147
+ ]
148
+ return lines.join('\n')
87
149
  }
88
150
 
89
151
  function visionPluginLabel(plugin) {
@@ -215,11 +277,11 @@ export async function run(argv = process.argv.slice(2), io = console, env = proc
215
277
  && (runtime?.ok ?? true)
216
278
  && (!sessions || (sessions.affected === 0 && sessions.errors.length === 0))
217
279
 
218
- if (options.json) {
280
+ if (options.json || options.issueTemplate) {
219
281
  const report = supportReport({ profileReport, runtime, platform, sessions })
220
282
  report.visionLimits = visionLimits
221
283
  report.ok = overallOk
222
- io.log(JSON.stringify(report, null, 2))
284
+ io.log(options.issueTemplate ? formatIssueTemplate(report) : JSON.stringify(report, null, 2))
223
285
  return overallOk ? 0 : 1
224
286
  }
225
287
 
@@ -17,7 +17,11 @@ export const HTTP_PROVIDER_COMPAT_PRESETS = [
17
17
  {
18
18
  id: 'glm-4v-flash-max-output',
19
19
  model: GLM_4V_FLASH,
20
- // Zhipu GLM-4V-Flash rejects larger values with error 1210.
20
+ // Issue #53 measured error 1210 on Zhipu's official endpoint only.
21
+ // A different DSH-configured gateway may support the same model ID with
22
+ // a different limit: let its explicit HTTP 400/422 response set the cap.
23
+ origin: 'https://open.bigmodel.cn',
24
+ pathname: '/api/paas/v4/chat/completions',
21
25
  maxTokensCap: 1024,
22
26
  },
23
27
  ]
@@ -33,6 +37,15 @@ function asUrl(value) {
33
37
  function ruleMatches(rule, { model, url, providerName }) {
34
38
  if (rule.model && !rule.model.test(String(model ?? ''))) return false
35
39
  if (rule.provider && !rule.provider.test(String(providerName ?? ''))) return false
40
+ // Provider/model IDs are DSH-owned strings, not proof of endpoint identity.
41
+ // Only a verified vendor endpoint can activate a vendor-specific eager cap.
42
+ if (rule.origin || rule.pathname) {
43
+ const endpoint = asUrl(url)
44
+ if (!endpoint) return false
45
+ if (rule.origin && endpoint.origin !== rule.origin) return false
46
+ if (rule.pathname && endpoint.pathname.replace(/\/+$/, '') !== rule.pathname) return false
47
+ if (endpoint.username || endpoint.password || endpoint.search || endpoint.hash) return false
48
+ }
36
49
  if (rule.host) {
37
50
  const host = asUrl(url)?.hostname ?? ''
38
51
  if (!rule.host.test(host)) return false
@@ -103,6 +116,17 @@ function positiveInteger(value) {
103
116
  return Number.isInteger(n) && n > 0 ? n : undefined
104
117
  }
105
118
 
119
+ // A ceiling word or a bare field name can precede a number that measures the
120
+ // INPUT images (how many, or their pixel/resolution dimension) rather than the
121
+ // output-token cap. Treating that number as a token limit makes the corrective
122
+ // retry shrink max_tokens to a nonsense value ("at most 4 images" -> 4), which
123
+ // leaves the real 400 uncorrected. Guard the three number-capturing patterns so
124
+ // a candidate ceiling is rejected when the captured digit run is immediately
125
+ // followed by a non-token measure unit. `(?!\d)` forces a maximal digit run so
126
+ // backtracking cannot smuggle a truncated prefix (e.g. 204 of 2048) past the
127
+ // unit lookahead. Two-sided range patterns are intentionally left untouched.
128
+ const NON_TOKEN_MEASURE = String.raw`(?!\d)(?!\s*(?:images?|pixels?|px|mp|张图片|张图|幅图|图像|像素|分辨率|尺寸))`
129
+
106
130
  /** Parse a server-advertised max-token upper bound from common error wording. */
107
131
  export function parseMaxTokensLimit(detail) {
108
132
  const text = String(detail ?? '')
@@ -117,9 +141,18 @@ export function parseMaxTokensLimit(detail) {
117
141
  // The generic max_tokens fallback below would otherwise parse the lower bound.
118
142
  /(?:max(?:_completion)?[_ -]?tokens?)[^\d\n]{0,48}(?:between|from|(?:in|within)(?:\s+the)?(?:\s+(?:valid|allowed))?(?:\s+range)?)[^\d\n]{0,12}\d+\s*(?:,|and|to|[-–—])\s*(\d+)/i,
119
143
  /(?:限制数值范围|range)\s*[\[(]\s*\d+\s*,\s*(\d+)\s*[\])]/i,
120
- /(?:less than or equal to|at most|maximum(?: allowed)?|max(?:imum)?(?: value)?|<=)\D{0,24}(\d+)/i,
121
- /(?:上限|最大(?:值|输出)?)[^\d]{0,16}(\d+)/i,
122
- /(?:max(?:_completion)?[_ -]?tokens?)[^\d]{0,40}(\d+)/i,
144
+ // Explicit single-sided ceiling words only. Never match the bare "max"
145
+ // inside `max_tokens`/`max_completion_tokens`, or the request's own
146
+ // rejected value (which usually appears right after the field name) would
147
+ // be captured instead of the advertised cap, defeating the corrective retry
148
+ // for messages like "max_tokens is too large: 4096 ... supports at most 1536".
149
+ new RegExp(`(?:less than or equal to|at most|maximum|max value|max output|max limit|allowed (?:value|output|limit)|<=)\\D{0,24}(\\d+)${NON_TOKEN_MEASURE}`, 'i'),
150
+ // Chinese ceiling words. 上限/最大 alone missed 最多支持/至多, letting the
151
+ // generic field-name fallback below return the already-rejected value.
152
+ new RegExp(`(?:上限|最大(?:值|输出)?|最多|至多)[^\\d]{0,16}(\\d+)${NON_TOKEN_MEASURE}`, 'i'),
153
+ // Generic field-name fallback. Also guarded: an image count that sits right
154
+ // after `max_tokens` with no other number in range must not become the cap.
155
+ new RegExp(`(?:max(?:_completion)?[_ -]?tokens?)[^\\d]{0,40}(\\d+)${NON_TOKEN_MEASURE}`, 'i'),
123
156
  ]
124
157
  for (const pattern of patterns) {
125
158
  const match = text.match(pattern)
@@ -30,7 +30,7 @@ function nonEmpty(value) {
30
30
  return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
31
31
  }
32
32
 
33
- function normalizeBaseURL(value) {
33
+ function normalizeBaseURL(value, { strictBaseURL = false } = {}) {
34
34
  const text = nonEmpty(value)
35
35
  if (text === undefined) return undefined
36
36
  let parsed
@@ -40,6 +40,9 @@ function normalizeBaseURL(value) {
40
40
  return undefined
41
41
  }
42
42
  if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return undefined
43
+ // Only callers asserting official endpoint provenance require this mode.
44
+ // Ordinary private discovery retains its established loose normalization.
45
+ if (strictBaseURL && (parsed.search || parsed.hash || parsed.username || parsed.password)) return undefined
43
46
  parsed.hash = ''
44
47
  parsed.search = ''
45
48
  return stripTrailingSlashes(parsed.toString())
@@ -284,24 +287,24 @@ function firstString(...values) {
284
287
  return values.find((value) => typeof value === 'string' && value.trim() !== '')?.trim()
285
288
  }
286
289
 
287
- function transportForProvider(ctx, provider, rawProfile) {
290
+ function transportForProvider(ctx, provider, rawProfile, options = {}) {
288
291
  const resolved = resolvedPiProfile(ctx, provider)
289
292
  const baseURL = normalizeBaseURL(firstString(
290
293
  rawProfile?.baseURL,
291
294
  resolved?.baseURL,
292
295
  resolved?.piProvider?.baseUrl,
293
- ))
296
+ ), options)
294
297
  const api = firstString(rawProfile?.api, resolved?.api)
295
298
  const apiKeyEnv = firstString(rawProfile?.apiKeyEnv, resolved?.apiKeyEnv)
296
299
  return { baseURL, api, apiKeyEnv }
297
300
  }
298
301
 
299
- export function providerTransportFor(ctx, provider) {
302
+ export function providerTransportFor(ctx, provider, options = {}) {
300
303
  const id = nonEmpty(provider)
301
304
  if (id === undefined) return undefined
302
305
  const raw = rawPiProfiles(ctx)[id]
303
306
  if (!raw || typeof raw !== 'object') return undefined
304
- const transport = transportForProvider(ctx, id, raw)
307
+ const transport = transportForProvider(ctx, id, raw, options)
305
308
  if (transport.baseURL === undefined) return undefined
306
309
  return {
307
310
  provider: id,
@@ -311,9 +314,9 @@ export function providerTransportFor(ctx, provider) {
311
314
  }
312
315
  }
313
316
 
314
- export function configuredProviderTransports(ctx) {
317
+ export function configuredProviderTransports(ctx, options = {}) {
315
318
  return Object.keys(rawPiProfiles(ctx))
316
- .map((provider) => providerTransportFor(ctx, provider))
319
+ .map((provider) => providerTransportFor(ctx, provider, options))
317
320
  .filter(Boolean)
318
321
  }
319
322
 
@@ -444,6 +444,9 @@ function applyMatureCoreBridge(host, owners, routing, execution, core, runtime)
444
444
  const installPostCoreRuntime = () => {
445
445
  installVisionMaintenanceRoutes(coreRequestAuthorityCtx, { logger: logging.logger })
446
446
  finishSchemaBootstrapOnce()
447
+ // Core has now registered its tools. Restore masks for existing Agents
448
+ // before any new presentation can observe this HMR generation.
449
+ sessionVisionModeCompat.reconcileExistingAgents()
447
450
  installWrapperDirectoryAlias(attachmentCompatCtx, runtimeConfig, logging.logger)
448
451
  }
449
452
  const failCoreApply = (error) => {
@@ -85,7 +85,7 @@ function restrictableOwnedVisionToolNames(tools, owned) {
85
85
  return active
86
86
  }
87
87
 
88
- function assemblyOwnedVisionToolNames(registryTools, scopedTools, owned) {
88
+ function assemblyOwnedVisionToolNames(registryTools, scopedTools, owned, agent) {
89
89
  const active = restrictableOwnedVisionToolNames(registryTools, owned)
90
90
  const scopedGet = scopedTools?.get
91
91
  if (typeof scopedGet !== 'function') return new Set(active)
@@ -93,7 +93,10 @@ function assemblyOwnedVisionToolNames(registryTools, scopedTools, owned) {
93
93
  const projected = new Set()
94
94
  for (const name of active) {
95
95
  try {
96
- const visible = scopedGet.call(scopedTools, name)
96
+ // DSH RC3 get(name, scope) defaults to the *global* view, even when
97
+ // accessed through agent.ctx.tools. Supply the actual Agent to preserve
98
+ // foreign Agent-scoped shadows of DVR global tool names.
99
+ const visible = scopedGet.call(scopedTools, name, agent)
97
100
  // A foreign Agent-scoped definition is allowed to shadow DVR's global
98
101
  // name. DSH restrictions deliberately leave scoped registrations visible,
99
102
  // so the final assembly projection must preserve the same boundary.
@@ -439,7 +442,7 @@ export function installSessionVisionModeBoundary(ctx, config = {}, runtime = {})
439
442
  const transformed = typeof next === 'function' ? await next() : assembly
440
443
  const projectedOwned =
441
444
  ctx?.tools
442
- ? assemblyOwnedVisionToolNames(ctx.tools, agent?.ctx?.tools, ownedVisionTools)
445
+ ? assemblyOwnedVisionToolNames(ctx.tools, agent?.ctx?.tools, ownedVisionTools, agent)
443
446
  : ownedVisionTools
444
447
  return projectAssemblyTools(
445
448
  transformed,
@@ -559,5 +562,28 @@ export function installSessionVisionModeBoundary(ctx, config = {}, runtime = {})
559
562
  },
560
563
  })
561
564
 
562
- return { ctx: wrapped, config }
565
+ // After HMR the old plugin generation releases its Agent-scoped masks.
566
+ // Reconcile agents that were already alive before this generation mounted:
567
+ // otherwise their OFF scopes see newly registered global DVR schemas until
568
+ // the next agent/status or prompt-assembly event.
569
+ const reconcileExistingAgents = () => {
570
+ let agents
571
+ try {
572
+ const registry = ctx.get?.('agents')
573
+ agents = typeof registry?.list === 'function' ? registry.list() : undefined
574
+ } catch {
575
+ return
576
+ }
577
+ if (!Array.isArray(agents)) return
578
+ for (const agent of agents) {
579
+ try {
580
+ syncForAgent(agent)
581
+ } catch {
582
+ // Older Hosts may not expose the same Agent registry seams. Keep the
583
+ // execution guard and ordinary per-step synchronization authoritative.
584
+ }
585
+ }
586
+ }
587
+
588
+ return { ctx: wrapped, config, reconcileExistingAgents }
563
589
  }
@@ -27,6 +27,21 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
27
27
  function canonicalGuidance(rows){return arr(rows).map(function(row){return {kind:String(row&&row.kind||'').trim(),text:String(row&&row.text||'').trim()};}).filter(function(row){return row.kind&&row.text;});}
28
28
  function validGuidance(rows){return arr(rows).every(function(row){var k=String(row&&row.kind||'').trim(),t=String(row&&row.text||'').trim();return (!k&&!t)||(!!k&&!!t);});}
29
29
  function modelName(group,model){if(!model)return '';var hit=arr(group&&group.models).find(function(item){return item&&item.id===model;});return hit&&hit.name&&hit.name!==model?hit.name+' ('+model+')':model;}
30
+ // Host capability metadata is advisory, not a successful image-delivery test.
31
+ // An explicit text-only Host input declaration takes precedence over inference.
32
+ // Browser-only display preference; never changes network behavior.
33
+ var EGRESS_NOTICE_KEY='dsh-vision-router:cloud-vision-notice-hidden:v1';
34
+ function readEgressNoticeDismissed(){
35
+ try{return window.localStorage&&window.localStorage.getItem(EGRESS_NOTICE_KEY)==='1';}
36
+ catch(_){return false;}
37
+ }
38
+ function visionInputReadiness(capability,status){
39
+ if(status!=='ready'||!capability||typeof capability!=='object')return 'unknown';
40
+ if(capability.attemptable===false)return 'blocked';
41
+ var declared=Array.isArray(capability.hostInputModalities)?capability.hostInputModalities:capability.inputModalities;
42
+ if(Array.isArray(declared)&&declared.length&&!declared.includes('image'))return 'text-only';
43
+ return capability.image===true?'evidence':'unknown';
44
+ }
30
45
  function jsonEqual(left,right){if(left===right)return true;if(left===null||right===null||typeof left!=='object'||typeof right!=='object')return false;if(Array.isArray(left)||Array.isArray(right)){if(!Array.isArray(left)||!Array.isArray(right)||left.length!==right.length)return false;return left.every(function(value,index){return jsonEqual(value,right[index]);});}var lk=Object.keys(left),rk=Object.keys(right);if(lk.length!==rk.length)return false;return lk.every(function(key){return Object.prototype.hasOwnProperty.call(right,key)&&jsonEqual(left[key],right[key]);});}
31
46
  function canonicalProviders(value){return Array.isArray(value)?value.map(function(row){return row&&typeof row==='object'?Object.assign({},row,{fallbacks:row.fallbacks===undefined?[]:row.fallbacks}):row;}):value;}
32
47
  function readbackEqual(key,left,right){if(key==='providers')return jsonEqual(canonicalProviders(left),canonicalProviders(right));if(key==='allowRemoteSettings')return bool(left)===bool(right);return jsonEqual(left,right);}
@@ -93,9 +108,17 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
93
108
  var updatePair=React.useState({status:'idle'}),updateState=updatePair[0],setUpdateState=updatePair[1];
94
109
  var selfUpdatePair=React.useState({status:'idle'}),selfUpdateState=selfUpdatePair[0],setSelfUpdateState=selfUpdatePair[1];
95
110
  var actionPair=React.useState({status:'idle'}),actionState=actionPair[0],setActionState=actionPair[1];
111
+ var egressStatePair=React.useState(readEgressNoticeDismissed()),egressDismissed=egressStatePair[0],setEgressDismissed=egressStatePair[1];
96
112
  var catalogGen=React.useRef?React.useRef(0):{current:0};
97
113
  var capsGen=React.useRef?React.useRef(0):{current:0};
98
114
  var h=React.createElement;
115
+ function saveNoticeDisplay(hide){
116
+ setEgressDismissed(hide);
117
+ try{
118
+ var store=window.localStorage;
119
+ if(store){if(hide)store.setItem(EGRESS_NOTICE_KEY,'1');else store.removeItem(EGRESS_NOTICE_KEY);}
120
+ }catch(_){}
121
+ }
99
122
 
100
123
  function loadCatalog(){
101
124
  var generation=++catalogGen.current;
@@ -181,7 +204,72 @@ export const SETTINGS_IA_CLIENT_PRELUDE = String.raw`(function(){
181
204
  function modelOptions(provider,current,allowAll){var group=groupById.get(provider),models=arr(group&&group.models),listed=new Set(models.map(function(model){return model&&model.id;}).filter(Boolean)),nodes=[h('option',{value:'',key:'__empty'},allowAll?tx('全部模型','All models'):(provider?tx('选择模型…','Choose model…'):tx('先选供应商','Choose provider first')))];if(current&&!listed.has(current))nodes.push(h('option',{value:current,key:'__stale-'+current},current+' '+tx('(已保存)','(saved)')));models.forEach(function(model){if(model&&typeof model.id==='string'&&model.id)nodes.push(h('option',{value:model.id,key:model.id},modelName(group,model.id)));});return nodes;}
182
205
  function modelRow(row,index,rows,setRows,allowAll){var ready=groups.length>0;function update(next){var copy=rows.map(function(item){return Object.assign({},item);});copy[index]=next;setRows(copy);setSaveState({status:'idle'});}function providerChanged(provider){var next=Object.assign({},row,{provider:provider,model:''});if(!allowAll)next.fallbacks=[];update(next);}function remove(){var copy=rows.filter(function(_,i){return i!==index;});setRows(copy.length?copy:[{provider:'',model:'',fallbacks:[]}]);setSaveState({status:'idle'});}return h('div',{className:'vr-chain-row',key:index},ready?h('select',{className:'vr-input vr-select',value:row.provider||'',disabled:!writable||saving,onChange:function(event){providerChanged(event.target.value);}},providerOptions(row.provider||'')):h('input',{className:'vr-input',placeholder:'provider',value:row.provider||'',disabled:!writable||saving,onChange:function(event){providerChanged(event.target.value);}}),ready?h('select',{className:'vr-input vr-select',value:row.model||'',disabled:!writable||saving||!row.provider,onChange:function(event){update(Object.assign({},row,{model:event.target.value}));}},modelOptions(row.provider||'',row.model||'',allowAll)):h('input',{className:'vr-input',placeholder:allowAll?tx('model(留空=全部)','model (empty = all)'):'model',value:row.model||'',disabled:!writable||saving,onChange:function(event){update(Object.assign({},row,{model:event.target.value}));}}),h('button',{type:'button',className:'vr-reset',disabled:!writable||saving,onClick:remove},tx('移除','Remove')));}
183
206
 
184
- function generalPage(){var rows=chainRows(),configured=rows.filter(function(row){return row&&row.provider&&row.model;}),localOnly=toggleValue('localOnlyVision',false),fallback=!localOnly&&toggleValue('freeFallback',true),status=localOnly?tx('仅本地视觉策略已启用','Local-only vision policy enabled'):configured.length?tx('识图已就绪','Vision ready'):fallback?tx('已可使用内置免费识图','Built-in free vision is ready'):tx('暂无可用识图模型','No vision model configured'),ordered=configured.map(function(row){return row.model;});if(fallback)ordered.push(tx('内置免费兜底','Built-in free fallback'));var stale=catalog.status==='ready'?configured.filter(function(row){var group=groupById.get(row.provider);return !group||!arr(group.models).some(function(model){return model&&model.id===row.model;});}):[];return h(React.Fragment,null,title(tx('常规','General'),tx('这里只设置“谁负责看图”。聊天模型仍在聊天页选择。','This page only decides who reads images; the chat model is still chosen in chat.')),card([toggle('localOnlyVision',tx('仅本地视觉','Local-only vision'),tx('开启后,Vision Router 只允许回环地址上的本地视觉后端(Ollama、LM Studio 或本机自定义 HTTP);所有云端/DSH Provider 和 OVH 免费兜底都会在运行时被硬阻止。已保存的云端配置不会删除,关闭后可恢复。Vision Router 不会把图片和裁剪发送到云端视觉服务,但视觉后端返回的描述、OCR、坐标等识图结果文本仍会交给当前聊天模型;若聊天模型在云端,图片语义仍可能离开本机。严格纯本地还需同时选择本地聊天模型。此隐私开关只能在运行 DSH 的本机页面修改。','When enabled, Vision Router only allows visual backends on loopback addresses (Ollama, LM Studio, or custom local HTTP). Cloud/DSH providers and the OVH free fallback are blocked at runtime. Saved cloud settings are preserved for later restoration. Vision Router does not send image bytes or crops to cloud vision services, but derived result text—descriptions, OCR, and coordinates—is still passed to the current chat model; if that model is remote, image semantics may still leave this machine. For a strict end-to-end local workflow, select a local chat model too. This privacy control can only be changed from the local DSH settings page.'),!local),h('div',{className:'vr-ia-status',key:'status'},h('strong',null,(localOnly?'🔒 ':configured.length||fallback?'● ':'⚠ ')+status),h('p',{className:'vr-hint'},tx('需要看图时,在聊天框旁点击「👁 识图」。','Use “👁 Vision” beside the chat box when an image needs inspection.')),h('p',{className:localOnly?'vr-hint':'vr-failed',key:'egress'},localOnly?tx('当前仅本地视觉策略正在生效:云端识图行和 OVH 免费兜底会保留配置但不会执行;Vision Router 只会把图片和裁剪发往回环地址上的本地视觉端点。识图结果文本仍会交给当前聊天模型;若聊天模型在云端,图片语义仍可能离开本机。严格纯本地还需同时选择本地聊天模型。','Local-only vision is active: cloud vision rows and the OVH fallback remain saved but cannot execute; Vision Router sends image bytes and crops only to local visual endpoints on loopback addresses. Derived result text is still passed to the current chat model; if that model is remote, image semantics may still leave this machine. For a strict end-to-end local workflow, select a local chat model too.'):tx('数据流向:使用云端识图模型(包括默认 OVHcloud 匿名兜底)时,图片/裁剪、提示词和相关上下文会离开本机;免费或免 Key 不等于离线。若要阻止 Vision Router 将图片发送到远程视觉端点,请开启上方“仅本地视觉”。','Data flow: cloud vision models, including the default anonymous OVHcloud fallback, receive images/crops, prompts and related context; free or keyless does not mean offline. Enable Local-only vision above to prevent Vision Router from sending image data to remote visual endpoints.')),ordered.length?h('p',{className:'vr-ia-chain-summary'},ordered.join(' → ')):null,stale.length?h('p',{className:'vr-failed'},tx('有已保存的识图模型当前不在可调用目录中;请到“诊断”重新检测。','A saved vision model is not currently in the callable catalog; re-detect it in Diagnostics.')):null)]),card([h('div',{className:'vr-field',id:'vr-vision-backend-chain','data-vr-guide-target':'vision-backend',key:'chain'},fieldHead('providers',tx('识图模型','Vision models')),h('p',{className:'vr-hint'},tx('从上到下依次尝试;前一个失败时自动切换到下一个。','Models are tried from top to bottom and fall through automatically on failure.')),rows.map(function(row,index){return modelRow(row,index,rows,setChainDraft,false);}),h('button',{type:'button',className:'vr-btn',disabled:!writable||saving,onClick:function(){setChainDraft(rows.concat([{provider:'',model:'',fallbacks:[]}]))}},tx('+ 添加备用识图模型','+ Add fallback vision model'))),toggle('freeFallback',tx('内置免费兜底','Built-in free fallback'),localOnly?tx('仅本地视觉开启时,OVH 免费兜底由运行时强制禁用;这里保留原设置,关闭仅本地视觉后可恢复。','The OVH fallback is runtime-blocked while Local-only vision is enabled. Its saved value is preserved and becomes active again when Local-only vision is turned off.'):tx('这是远程 OVHcloud 服务;前面的模型都失败后会上传图片并自动尝试,无需 API Key。','This is a remote OVHcloud service. After earlier models fail, it uploads the image and tries automatically; no API key is required.'),localOnly)]));}
207
+ function egressInstructions(local){
208
+ if(local)return tx(
209
+ '数据流向:云端识图(含免费兜底)会上传图片、裁剪和提示词。免费或免 Key 不等于离线。要停止上传,请在本页开启「仅本地视觉」,然后点击「保存」。云端聊天模型仍可能收到识图结果文字;要完全不出网,还需在聊天页选择本地聊天模型。',
210
+ 'Data flow: Cloud vision, including the free fallback, uploads images, crops and prompts. Free or keyless is not offline. To stop uploads, enable Local-only vision here and select Save. A cloud chat model may still receive result text; choose a local chat model in the composer to keep the whole workflow local.');
211
+ return tx(
212
+ '云端识图可能上传图片。要停止上传,请在运行 DSH 的电脑上打开「设置 → Vision Router → 常规」,开启「仅本地视觉」并保存。云端聊天模型仍可能收到识图结果文字;要完全不出网,还需在聊天页选择本地聊天模型。',
213
+ 'Cloud vision may upload images. To stop uploads, open Settings → Vision Router → General on the DSH computer, enable Local-only vision and save. A cloud chat model may still receive result text; choose a local chat model in the composer to keep the whole workflow local.');
214
+ }
215
+ function egressNotice(localOnly,local){
216
+ if(localOnly)return h('p',{className:'vr-hint',key:'egress'},tx(
217
+ '图片只发给本机视觉模型;识图结果仍交给当前聊天模型,若它在云端,结果文字可能出网。要完全本地,请在聊天页选本地聊天模型。',
218
+ 'Images stay with local vision models. Results may still go to a cloud chat model; choose a local chat model in the composer to keep both local.'));
219
+ var expanded=egressDismissed!==true;
220
+ return h('div',{className:'vr-field',key:'egress','data-vr-egress-notice':expanded?'visible':'dismissed'},
221
+ h('p',{className:expanded?'vr-failed':'vr-hint'},expanded?egressInstructions(local):
222
+ tx('云端识图可能上传图片。','Cloud vision may upload images.')),
223
+ h('button',{type:'button',className:'vr-btn',onClick:function(){saveNoticeDisplay(expanded);}},
224
+ expanded?tx('不再提醒','Do not remind again'):tx('查看如何关闭出网','How to stop uploads')));
225
+ }
226
+ function generalPage(){
227
+ var rows=chainRows(),configured=rows.filter(function(row){return row&&row.provider&&row.model;});
228
+ var localOnly=toggleValue('localOnlyVision',false),activeLocalOnly=bool(saved.localOnlyVision),localOnlyPending=localOnly!==activeLocalOnly,fallback=!activeLocalOnly&&toggleValue('freeFallback',true);
229
+ var readiness=configured.map(function(row){
230
+ var providerCaps=obj(caps.capabilities)[row.provider],cap=obj(providerCaps)[row.model];
231
+ return {row:row,state:visionInputReadiness(cap,caps.status)};
232
+ });
233
+ var needsHostFix=readiness.some(function(entry){return entry.state==='text-only';});
234
+ var hasBlocked=readiness.some(function(entry){return entry.state==='blocked';});
235
+ var allEvidence=readiness.length>0&&readiness.every(function(entry){return entry.state==='evidence';});
236
+ var status=localOnlyPending?(localOnly?tx('仅本地视觉待保存','Local-only vision pending Save'):tx('关闭仅本地视觉待保存','Turning off local-only pending Save')):
237
+ activeLocalOnly?tx('仅本地视觉策略已启用','Local-only vision policy enabled'):
238
+ needsHostFix?tx('有模型可能看不了图片','Some models may not receive images'):
239
+ hasBlocked?tx('有模型暂时不可用','Some models are unavailable'):
240
+ allEvidence?tx('已添加识图模型','Vision models added'):
241
+ configured.length?tx('已添加识图模型','Vision models added'):
242
+ fallback?tx('可使用内置免费识图','Built-in free vision available'):
243
+ tx('暂无可用识图模型','No vision model configured');
244
+ var ordered=configured.map(function(row){return row.model;});
245
+ if(fallback)ordered.push(tx('内置免费兜底','Built-in free fallback'));
246
+ var stale=catalog.status==='ready'?configured.filter(function(row){
247
+ var group=groupById.get(row.provider);
248
+ return !group||!arr(group.models).some(function(model){return model&&model.id===row.model;});
249
+ }):[];
250
+ function readinessHint(entry){
251
+ if(entry.state==='text-only')return tx(
252
+ 'DSH 尚未为这个模型开启图片输入,可能无法识图。请到「设置 → 模型」开启「图片」,然后点下方「重新检测」。',
253
+ 'Image input is not enabled for this model in DSH, so vision may fail. Enable Image in Settings → Models, then choose Recheck below.');
254
+ if(entry.state==='blocked')return tx('这个模型暂时不可用,请换一个。','This model is unavailable. Choose another one.');
255
+ return tx('还不能确认这个模型是否能识图。可以先发一张图片试试。','Image support is unverified. Try sending an image.');
256
+ }
257
+ function advancedReadinessHelp(entry){
258
+ if(entry.state!=='text-only')return null;
259
+ return h('details',{className:'vr-field',key:'readiness-help-'+entry.row.provider+'/'+entry.row.model},
260
+ h('summary',null,tx('旧版 DSH 怎么设置?','Using an older DSH version?')),
261
+ h('p',{className:'vr-hint'},tx(
262
+ '旧版 DSH:llm-pi-ai 使用 input: [text, image];llm-deepseek 使用 inputModalities: [text, image]。只有模型本身支持图片时才这样配置。经验证的 HTTP Chat Completions 通道也可能直接桥接;单独添加视觉能力标记不能开启图片传输。',
263
+ 'Older DSH: llm-pi-ai uses input: [text, image]; llm-deepseek uses inputModalities: [text, image]. Only declare image input if the model supports it. Verified HTTP Chat Completions may bridge; a capability label alone cannot enable image delivery.')));
264
+ }
265
+ return h(React.Fragment,null,title(tx('常规','General'),tx('这里只设置“谁负责看图”。聊天模型仍在聊天页选择。','This page only decides who reads images; the chat model is still chosen in chat.')),card([toggle('localOnlyVision',tx('仅本地视觉','Local-only vision'),tx('只使用本机识图模型;云端识图和免费兜底暂停,原配置保留。识图结果文字仍可能发给云端聊天模型。只能在本机修改。','Use only local vision models; cloud vision and the free fallback are paused without deleting settings. Result text may still go to a cloud chat model. Change this only on the local DSH machine.'),!local),h('div',{className:'vr-ia-status',key:'status'},h('strong',null,(activeLocalOnly?'🔒 ':localOnlyPending?'⚠ ':configured.length||fallback?'● ':'⚠ ')+status),h('p',{className:'vr-hint'},tx('需要看图时,在聊天框旁点击「👁 识图」。','Use “👁 Vision” beside the chat box when an image needs inspection.')),egressNotice(activeLocalOnly,local),localOnlyPending?h('p',{className:localOnly?'vr-failed':'vr-hint',key:'local-only-pending'},localOnly?tx('尚未生效:请点击页面底部「保存」。保存前图片仍可能上传。','Not active yet: select Save at the bottom. Images may still be uploaded until saved.'):tx('还没有保存:当前仍在仅本地视觉模式,保存后才会允许云端识图。','Not saved yet: Local-only vision remains active until you save.')):null,ordered.length?h('p',{className:'vr-ia-chain-summary'},ordered.join(' → ')):null,stale.length?h('p',{className:'vr-failed'},tx('有已保存的识图模型当前不在可调用目录中;请到“诊断”重新检测。','A saved vision model is not currently in the callable catalog; re-detect it in Diagnostics.')):null)]),card([h('div',{className:'vr-field',id:'vr-vision-backend-chain','data-vr-guide-target':'vision-backend',key:'chain'},fieldHead('providers',tx('识图模型','Vision models')),h('p',{className:'vr-hint'},tx('从上到下依次尝试;前一个失败时自动切换到下一个。','Models are tried from top to bottom and fall through automatically on failure.')),rows.map(function(row,index){return modelRow(row,index,rows,setChainDraft,false);}),
266
+ readiness.filter(function(entry){return !localOnly&&(caps.status==='ready'||caps.status==='error')&&entry.state!=='evidence';}).map(function(entry,index){return h('div',{
267
+ className:'vr-field',key:'readiness-'+index,'data-vr-model-readiness':entry.state
268
+ },h('p',{className:entry.state==='text-only'||entry.state==='blocked'?'vr-failed':'vr-hint'},
269
+ entry.row.model+':'+readinessHint(entry)),advancedReadinessHelp(entry));}),
270
+ !localOnly&&(caps.status==='ready'||caps.status==='error')&&readiness.some(function(entry){return entry.state==='text-only'||entry.state==='unknown';})?
271
+ h('button',{type:'button',className:'vr-btn',onClick:invalidateCatalog},tx('重新检测','Recheck')):null,
272
+ h('button',{type:'button',className:'vr-btn',disabled:!writable||saving,onClick:function(){setChainDraft(rows.concat([{provider:'',model:'',fallbacks:[]}]))}},tx('+ 添加备用识图模型','+ Add fallback vision model'))),toggle('freeFallback',tx('内置免费兜底','Built-in free fallback'),activeLocalOnly?tx('仅本地视觉开启时,OVH 免费兜底由运行时强制禁用;这里保留原设置,关闭仅本地视觉后可恢复。','The OVH fallback is runtime-blocked while Local-only vision is enabled. Its saved value is preserved and becomes active again when Local-only vision is turned off.'):tx('这是远程 OVHcloud 服务;前面的模型都失败后会上传图片并自动尝试,无需 API Key。','This is a remote OVHcloud service. After earlier models fail, it uploads the image and tries automatically; no API key is required.'),localOnly)]));}
185
273
  function strategyPage(){
186
274
  var structured=toggleValue('structuredVisionBootstrap',false);
187
275
  var rawDepth=String(value('visionDepth','standard')||'standard');
@@ -15,8 +15,9 @@ function normalizeEndpoint(value) {
15
15
  try {
16
16
  const url = new URL(value)
17
17
  if (url.protocol !== 'https:') return undefined
18
- url.hash = ''
19
- url.search = ''
18
+ // A trusted official model hint is allowed only for the verified bare
19
+ // endpoint; don't erase caller-supplied URL modifiers before admission.
20
+ if (url.username || url.password || url.search || url.hash) return undefined
20
21
  return stripTrailingSlashes(url.toString())
21
22
  } catch {
22
23
  return undefined
@@ -42,12 +43,12 @@ export function trustedVisionHintsForTransport(transport) {
42
43
  }
43
44
 
44
45
  export function trustedVisionHintsForProvider(ctx, provider) {
45
- const transport = providerTransportFor(ctx, provider)
46
+ const transport = providerTransportFor(ctx, provider, { strictBaseURL: true })
46
47
  return trustedVisionHintsForTransport(transport)
47
48
  }
48
49
 
49
50
  export function trustedVisionHintEntries(ctx) {
50
- return configuredProviderTransports(ctx).flatMap((transport) => {
51
+ return configuredProviderTransports(ctx, { strictBaseURL: true }).flatMap((transport) => {
51
52
  const models = trustedVisionHintsForTransport(transport)
52
53
  if (models.length === 0) return []
53
54
  return [{
@@ -77,6 +77,10 @@ export function isImageInputUnsupportedFailure(failure) {
77
77
  'i',
78
78
  ),
79
79
  new RegExp(`cannot (?:accept|process|handle) (?:images?|image inputs?)${terminal}`, 'i'),
80
+ // Explicit text-only model/endpoint rejections can omit the word "image".
81
+ // Keep these end-bounded so unrelated modality or size errors do not retry.
82
+ new RegExp(`(?:model|endpoint)\\s+is\\s+not\\s+(?:a\\s+)?multimodal(?:\\s+model)?${terminal}`, 'i'),
83
+ new RegExp(`not\\s+(?:a\\s+)?multimodal\\s+(?:model|endpoint)${terminal}`, 'i'),
80
84
  new RegExp(`(?:model|adapter).*text[- ]only.*(?:images?|image inputs?)${terminal}`, 'i'),
81
85
  new RegExp(`(?:模型|适配器).*不支持(?:图片|图像)(?:输入)?${terminal}`),
82
86
  new RegExp(`(?:图片|图像)输入(?:不被支持|暂不支持|不支持)${terminal}`),