dsh-agent-sdk-bridge 1.1.7 → 1.2.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/src/cli.ts CHANGED
@@ -25,7 +25,7 @@
25
25
  * @module dsh-agent-sdk-bridge/cli
26
26
  */
27
27
 
28
- import { existsSync, readdirSync } from 'node:fs'
28
+ import { existsSync, readFileSync, readdirSync } from 'node:fs'
29
29
  import { createRequire } from 'node:module'
30
30
  import { homedir } from 'node:os'
31
31
  import * as path from 'node:path'
@@ -130,11 +130,15 @@ export function qoderCliOptions(brand: QoderBrand = 'cn', lookup: CliLookup = {}
130
130
  // every branch hands over the environment the CLI would have inherited anyway
131
131
  // — handing over `PATH` alone would strip the CLI of the directories it keeps
132
132
  // its own state in — plus the switch that unzeroes its token metering.
133
+ //
134
+ // `cliChildEnv` also drops a `QODERCLI_PATH` naming the *other* edition.
135
+ // Both SDKs consult that variable before any option passed here, so leaving
136
+ // it in place is what made an intl session answer with the CN account (and,
137
+ // before that was understood, refuse to start at all on a machine whose CN
138
+ // installer had exported it globally).
139
+ const env = cliChildEnv(brand)
133
140
  if (cli.nodeDir === undefined) {
134
- return {
135
- pathToQoderCLIExecutable: cli.path,
136
- env: { ...process.env, ...EXPOSE_TOKEN_USAGE },
137
- }
141
+ return { pathToQoderCLIExecutable: cli.path, env }
138
142
  }
139
143
  return {
140
144
  pathToQoderCLIExecutable: cli.path,
@@ -142,7 +146,7 @@ export function qoderCliOptions(brand: QoderBrand = 'cn', lookup: CliLookup = {}
142
146
  // resolves it against PATH, so the interpreter's own directory is put in
143
147
  // front of the inherited PATH instead of being spelled out here.
144
148
  executable: 'node',
145
- env: { ...process.env, PATH: `${cli.nodeDir}${path.delimiter}${process.env.PATH ?? ''}`, ...EXPOSE_TOKEN_USAGE },
149
+ env: { ...env, PATH: `${cli.nodeDir}${path.delimiter}${env.PATH ?? ''}` },
146
150
  }
147
151
  }
148
152
 
@@ -164,25 +168,56 @@ export function isForeignCliPath(brand: QoderBrand, candidate: string): boolean
164
168
  }
165
169
 
166
170
  /**
167
- * A `QODERCLI_PATH` that names the other edition, when this one has no CLI.
171
+ * Why this edition has no usable CLI, when `QODERCLI_PATH` explains it.
172
+ *
173
+ * `QODERCLI_PATH` predates the international edition and some installers
174
+ * export it machine-wide. Both SDKs read it from the parent process before any
175
+ * option this plugin can pass, so a value naming the *other* edition would
176
+ * hand this edition's session the other account. The lookup therefore never
177
+ * offers it ({@link isForeignCliPath}), and this reports the case where it is
178
+ * all the machine has, so the page can ask for the right CLI to be installed.
168
179
  *
169
- * The SDKs read that variable from the parent process before any option this
170
- * plugin can pass, so when it is foreign and this edition has nothing of its
171
- * own, the only honest answer is a configuration error — spawning the other
172
- * edition's CLI would answer with the other edition's account.
180
+ * This is a diagnosis, not a second rule: an edition that finds its own CLI is
181
+ * unaffected by the variable. That is what keeps one edition's install from
182
+ * blocking the other's sign-in — the earlier code treated any foreign value as
183
+ * fatal, so a machine that had only the intl CLI installed could not sign in
184
+ * to CN even after installing it if the lookup missed the new package.
173
185
  *
174
186
  * @param brand - the edition the caller is about to start.
175
187
  * @param lookup - the machine to inspect; defaults to this process's.
188
+ * @returns the foreign override when this edition has nothing of its own.
176
189
  */
177
190
  export function foreignCliOverride(brand: QoderBrand, lookup: CliLookup = {}): string | undefined {
178
191
  const env = lookup.env ?? process.env
179
192
  const override = env.QODERCLI_PATH
180
193
  if (override === undefined || override.length === 0) return undefined
181
194
  if (!isForeignCliPath(brand, override)) return undefined
195
+ // A CLI of our own always wins; the session then ignores the variable
196
+ // entirely because it names the executable explicitly.
182
197
  if (resolveQoderCli(brand, lookup) !== undefined) return undefined
183
198
  return override
184
199
  }
185
200
 
201
+ /**
202
+ * The environment one session's child process receives.
203
+ *
204
+ * `QODERCLI_PATH` is stripped when it names the other edition: both SDKs read
205
+ * it from the parent before honouring any option, so leaving it in place would
206
+ * hand the intl session the CN CLI (and the CN account). Every other variable
207
+ * is inherited untouched — the CLI keeps its state in `PATH`-relative dirs.
208
+ *
209
+ * @param brand - which edition's child is being started.
210
+ * @param env - the environment to derive from; defaults to this process's.
211
+ */
212
+ export function cliChildEnv(brand: QoderBrand, env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
213
+ const child: NodeJS.ProcessEnv = { ...env, ...EXPOSE_TOKEN_USAGE }
214
+ const override = env.QODERCLI_PATH
215
+ if (override !== undefined && override.length > 0 && isForeignCliPath(brand, override)) {
216
+ delete child.QODERCLI_PATH
217
+ }
218
+ return child
219
+ }
220
+
186
221
  /**
187
222
  * The error text for {@link foreignCliOverride}.
188
223
  *
@@ -195,6 +230,87 @@ export function cliConflictMessage(brand: QoderBrand): string {
195
230
  return `未检测到可用的 ${command},请先安装并登录后再使用此版本。`
196
231
  }
197
232
 
233
+ /**
234
+ * Turn a CLI failure into something a user can act on.
235
+ *
236
+ * The SDK reports an outdated CLI as `Qoder CLI process exited with code 42`,
237
+ * which says nothing about the cause: CLI 1.1.81 removed the worker-session
238
+ * handshake the older SDK spoke, and its own log says so
239
+ * (`sdk_worker_removed: … Upgrade to the latest Qoder SDK version, or roll back
240
+ * the CLI`). The only fix available to a user is reinstalling the pair through
241
+ * the bundled helper, so say that instead of echoing the number.
242
+ *
243
+ * @param detail - the error text as the SDK reported it.
244
+ * @param brand - which edition's helper the message should name.
245
+ * @returns the original detail, prefixed with the actionable explanation.
246
+ */
247
+ export function cliFailureText(detail: string, brand: QoderBrand): string {
248
+ if (!/exit(?:ed)?(?: with)? code 42|sdk_worker_removed/i.test(detail)) return detail
249
+ const profile = brandProfile(brand)
250
+ const pkg = profile.cliPackages[0]
251
+ const spec = pkg === undefined ? profile.cliCommands[0] : `${pkg.scope}/${pkg.name}`
252
+ const required = requiredCliVersion(brand)
253
+ const target = required === undefined ? spec : `${spec}@${required}`
254
+ return `本机 ${profile.cliCommands[0]} 与插件使用的 SDK 版本不匹配(CLI 已移除旧版握手,退出码 42)。`
255
+ + `请在设置页点「一键配置」重新安装配套版本,或手动执行 npm install -g ${target} 后重试。`
256
+ + `原始信息:${detail}`
257
+ }
258
+
259
+ /**
260
+ * The CLI version the installed SDK expects, read from its runtime manifest.
261
+ *
262
+ * Each SDK release pins one CLI build: the two speak a wire protocol that
263
+ * changes between them, and a mismatch fails every session with a bare exit
264
+ * code. The bundled helper reads the same file, so the page and the helper
265
+ * agree on which build to install.
266
+ *
267
+ * @param brand - which edition's SDK to inspect.
268
+ * @returns the pinned version, or undefined when the manifest is unreadable.
269
+ */
270
+ export function requiredCliVersion(brand: QoderBrand): string | undefined {
271
+ try {
272
+ const dir = sdkDir(brandProfile(brand).sdkPackage)
273
+ if (dir === undefined) return undefined
274
+ const manifest = JSON.parse(readFileSync(path.join(dir, 'dist', 'runtime-manifest.json'), 'utf8')) as {
275
+ qoderCliVersion?: unknown
276
+ }
277
+ return typeof manifest.qoderCliVersion === 'string' && manifest.qoderCliVersion.length > 0
278
+ ? manifest.qoderCliVersion
279
+ : undefined
280
+ } catch {
281
+ return undefined
282
+ }
283
+ }
284
+
285
+ /**
286
+ * The version of the installed CLI, read from its own package manifest.
287
+ *
288
+ * Read from disk rather than by running `--version`: a settings-page poll must
289
+ * not spawn a process every second, and the npm package always ships a
290
+ * manifest next to its entry. A native build without one answers undefined,
291
+ * which callers treat as "unknown" and never as a mismatch.
292
+ *
293
+ * @param brand - which edition's CLI to inspect.
294
+ * @returns the installed version, or undefined when it cannot be read.
295
+ */
296
+ export function installedCliVersion(brand: QoderBrand): string | undefined {
297
+ const cli = resolveQoderCli(brand)
298
+ if (cli === undefined) return undefined
299
+ for (const candidate of [
300
+ path.join(path.dirname(cli.path), 'package.json'),
301
+ path.join(path.dirname(path.dirname(cli.path)), 'package.json'),
302
+ ]) {
303
+ try {
304
+ const manifest = JSON.parse(readFileSync(candidate, 'utf8')) as { name?: unknown, version?: unknown }
305
+ if (typeof manifest.name !== 'string' || !manifest.name.startsWith('@')) continue
306
+ if (typeof manifest.version === 'string' && manifest.version.length > 0) return manifest.version
307
+ } catch {
308
+ // No manifest at this level: try the parent, then give up.
309
+ }
310
+ }
311
+ return undefined
312
+ }
313
+
198
314
  /** Paths the CLI may live at, most explicit first. */
199
315
  function candidates(brand: QoderBrand, env: NodeJS.ProcessEnv, suffix: string, nodePath: string | undefined): string[] {
200
316
  const profile = brandProfile(brand)
@@ -211,9 +327,11 @@ function candidates(brand: QoderBrand, env: NodeJS.ProcessEnv, suffix: string, n
211
327
  for (const root of nodeModulesRoots(env, nodePath)) {
212
328
  for (const pkg of profile.cliPackages) {
213
329
  const dir = path.join(root, pkg.scope, pkg.name)
214
- // npm's own global shim points at `bundle/`; a flat layout has no such dir.
215
- push(path.join(dir, 'bundle', `${pkg.name}.js`))
216
- push(path.join(dir, `${pkg.name}.js`))
330
+ // npm's own global shim points at `bundle/`; a flat layout has no such
331
+ // dir. The package's own manifest is consulted too: the entry has moved
332
+ // between releases, and guessing only `bundle/<name>.js` made a working
333
+ // install look missing — the page then insisted the CLI was not there.
334
+ for (const entry of packageEntries(dir, pkg.name, suffix)) push(entry)
217
335
  }
218
336
  }
219
337
  const sdk = sdkDir(profile.sdkPackage)
@@ -228,6 +346,40 @@ function candidates(brand: QoderBrand, env: NodeJS.ProcessEnv, suffix: string, n
228
346
  return found
229
347
  }
230
348
 
349
+ /**
350
+ * Every path one installed npm package can expose as its CLI.
351
+ *
352
+ * `main`/`bin` are read from the package's own manifest rather than guessed:
353
+ * the entry point has changed between CLI releases, and hard-coding only
354
+ * `bundle/<name>.js` reported an installed package as missing whenever it did
355
+ * not match. Unreadable manifests fall back to the conventional entries.
356
+ */
357
+ function packageEntries(dir: string, name: string, suffix: string): string[] {
358
+ const entries: string[] = [
359
+ path.join(dir, 'bundle', `${name}.js`),
360
+ path.join(dir, `${name}.js`),
361
+ path.join(dir, 'bundle', `${name}${suffix}`),
362
+ ]
363
+ try {
364
+ const manifest = JSON.parse(readFileSync(path.join(dir, 'package.json'), 'utf8')) as {
365
+ main?: unknown
366
+ bin?: unknown
367
+ }
368
+ if (typeof manifest.main === 'string') entries.push(path.join(dir, manifest.main))
369
+ const bin = manifest.bin
370
+ if (typeof bin === 'string') entries.push(path.join(dir, bin))
371
+ else if (bin !== null && typeof bin === 'object') {
372
+ for (const value of Object.values(bin)) {
373
+ if (typeof value === 'string') entries.push(path.join(dir, value))
374
+ }
375
+ }
376
+ } catch {
377
+ // No readable manifest (or no package at all): the conventional entries
378
+ // above are everything worth probing.
379
+ }
380
+ return entries
381
+ }
382
+
231
383
  /** `node_modules` roots a global install can land in. */
232
384
  function nodeModulesRoots(env: NodeJS.ProcessEnv, nodePath: string | undefined): string[] {
233
385
  const roots: string[] = []
@@ -240,7 +392,16 @@ function nodeModulesRoots(env: NodeJS.ProcessEnv, nodePath: string | undefined):
240
392
  push(env.NPM_CONFIG_PREFIX === undefined ? undefined : path.join(env.NPM_CONFIG_PREFIX, 'node_modules'))
241
393
  push(env.APPDATA === undefined ? undefined : path.join(env.APPDATA, 'npm', 'node_modules'))
242
394
  push(path.join(homedir(), '.npm-global', 'node_modules'))
243
- if (nodePath !== undefined) push(path.join(path.dirname(path.dirname(nodePath)), 'lib', 'node_modules'))
395
+ if (nodePath !== undefined) {
396
+ // A Windows install keeps globals directly under its prefix
397
+ // (`<node>\\node_modules`); a unix one under `<prefix>/lib/node_modules`.
398
+ // Only the unix shape used to be probed, so a Windows Node outside
399
+ // %APPDATA%\\npm — a portable or per-drive install — had a working CLI the
400
+ // lookup could not see, and the page kept asking to install it again.
401
+ const prefix = path.dirname(nodePath)
402
+ push(path.join(prefix, 'node_modules'))
403
+ push(path.join(path.dirname(prefix), 'lib', 'node_modules'))
404
+ }
244
405
  return roots
245
406
  }
246
407
 
@@ -283,7 +444,13 @@ function resolveNode(lookup: CliLookup): string | undefined {
283
444
  */
284
445
  function sdkDir(packageName: string): string | undefined {
285
446
  try {
286
- return path.dirname(createRequire(import.meta.url).resolve(packageName))
447
+ const entry = createRequire(import.meta.url).resolve(packageName)
448
+ // `resolve` answers the package's entry *inside* its dist directory, so
449
+ // climbing one level only lands on `dist`. Callers want the package root:
450
+ // they join `dist/runtime-manifest.json` and `dist/_bundled/<cli>`, and a
451
+ // doubled `dist/dist/…` made both probes miss.
452
+ const dir = path.dirname(entry)
453
+ return path.basename(dir) === 'dist' ? path.dirname(dir) : dir
287
454
  } catch {
288
455
  return undefined
289
456
  }
@@ -18,6 +18,7 @@ import type { CodeBuddyRegion } from './brand.ts'
18
18
  import { codeBuddyColdStream, CodeBuddyAccountReader, CodeBuddyAuth, CodeBuddyCatalog, CodeBuddySessionManager, CODEBUDDY_DEFAULT_CONTEXT_WINDOW, CODEBUDDY_DEFAULT_MAX_TOKENS, CODEBUDDY_CACHE_TTL_MS, CODEBUDDY_FETCH_TIMEOUT_MS } from './codebuddy.ts'
19
19
  import type { CodeBuddyModel, CodeBuddyUsageSnapshot } from './codebuddy.ts'
20
20
  import { reasoningInfo, planContinuation } from './adapter.ts'
21
+ import { cachedModels } from './model-cache.ts'
21
22
  import type { ImageRequestReader } from './adapter.ts'
22
23
  import type { Live } from './live.ts'
23
24
  import { readLive, readLiveOptional } from './live.ts'
@@ -199,7 +200,8 @@ export class CodeBuddyAdapter extends LlmAdapter {
199
200
  private async modelVision(model: string): Promise<boolean> {
200
201
  const target = resolveCodeBuddyModelId(model, this.aliases)
201
202
  const key = `${this.region}:${target}`
202
- const live = (await this.catalog.models().catch(() => [])).find(entry => entry.id === target)
203
+ const live = (await cachedModels(this.catalog.snapshot(), () => this.catalog.models()))
204
+ .find(entry => entry.id === target)
203
205
  if (live !== undefined) {
204
206
  this.knownVision.set(key, live.vision)
205
207
  return live.vision
@@ -301,7 +303,7 @@ export class CodeBuddyAdapter extends LlmAdapter {
301
303
 
302
304
  /** The catalog snapshot the adapter last read (empty before the first read). */
303
305
  private models(region: CodeBuddyRegion): readonly CodeBuddyModel[] {
304
- return this.catalog.snapshot(region)
306
+ return this.catalog.snapshot(region) ?? []
305
307
  }
306
308
 
307
309
  /** Whether this model lets the user pick a context budget at all. */
@@ -321,10 +323,13 @@ export class CodeBuddyAdapter extends LlmAdapter {
321
323
  override async resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
322
324
  const target = resolveCodeBuddyModelId(model, this.aliases)
323
325
  const key = `${this.region}:${target}`
324
- const live = (await this.catalog.models()).find(entry => entry.id === target)
326
+ // Cache first: a model switch must not wait on a catalogue fetch (which
327
+ // boots a CodeBuddy process) just because the TTL has expired.
328
+ const live = (await cachedModels(this.catalog.snapshot(), () => this.catalog.models()))
329
+ .find(entry => entry.id === target)
325
330
  if (live !== undefined) {
326
331
  this.knownVision.set(key, live.vision)
327
- const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, (live.reasoningEfforts?.length ?? 0) > 0)
332
+ const reasoning = reasoningInfo(live.reasoningEfforts, readLiveOptional(this.options.defaultReasoningEffort), (live.reasoningEfforts?.length ?? 0) > 0)
328
333
  return {
329
334
  provider,
330
335
  id: model,
package/src/codebuddy.ts CHANGED
@@ -352,8 +352,8 @@ export class CodeBuddyCatalog {
352
352
  * Callers that must answer synchronously (deciding whether a model exposes a
353
353
  * context-budget choice) use this instead of awaiting a refresh.
354
354
  */
355
- snapshot(requested?: CodeBuddyRegion): readonly CodeBuddyModel[] {
356
- return this.snapshots.get(requested ?? readLive(this.region, 'global'))?.models ?? []
355
+ snapshot(requested?: CodeBuddyRegion): readonly CodeBuddyModel[] | undefined {
356
+ return this.snapshots.get(requested ?? readLive(this.region, 'global'))?.models
357
357
  }
358
358
 
359
359
  /** Models for one region; a failed refresh keeps the last good list. */
package/src/config.ts CHANGED
@@ -247,7 +247,7 @@ export const Config = z.object({
247
247
  maxSessions: z.number().step(1).min(1).max(64).default(8).description('同时保持的内层会话数上限,超出后按最久未使用关闭。每个会话是一个子进程。').volatile(),
248
248
  modelCacheTtlSeconds: z.number().step(1).min(10).max(86_400).default(300).description('模型列表缓存时长(秒)。调小可更快看到账号侧变化。').volatile(),
249
249
  modelAliases: z.dict(z.string()).default({}).description('额外的模型别名映射:DSH 侧名称 → Qoder 模型 ID。内置 deepseek-v4-* 别名仍然生效。').volatile(),
250
- defaultReasoningEffort: z.string().default('').description('请求未指定思考档位时使用的默认档位;留空则用上游默认。').volatile(),
250
+ defaultReasoningEffort: z.string().default('').description('默认选用的思考档位;留空则用该模型支持的最强档位。').volatile(),
251
251
  defaultMaxTokens: z.number().step(1).min(1).default(32_000).description('模型未声明输出上限时使用的输出上限。').volatile(),
252
252
  toolResultTimeoutSeconds: z.number().step(1).min(5).max(3_600).default(120).description('仅用于未配对 handler 的兜底时限(秒):正常工具调用会等宿主下一次请求携带结果,不按此超时。').volatile(),
253
253
  catalogFetchTimeoutSeconds: z.number().step(1).min(1).max(300).default(20).description('拉取模型列表的时限(秒),超时后回退到内置列表。').volatile(),
package/src/live.ts CHANGED
@@ -47,8 +47,8 @@ export function readLive<T>(value: Live<T> | undefined, fallback: T): T {
47
47
  * Resolve one {@link Live} option that may legitimately be undefined.
48
48
  *
49
49
  * Separate from {@link readLive} because an option whose "unset" state is
50
- * itself meaningful (`defaultReasoningEffort`: empty means "follow upstream")
51
- * has no fallback to apply.
50
+ * itself meaningful (`defaultReasoningEffort`: empty means "use the model's
51
+ * strongest level") has no fallback to apply.
52
52
  *
53
53
  * @param value - the plain value or thunk, possibly undefined.
54
54
  * @returns the option's current value, or undefined when it is unset.
@@ -25,6 +25,7 @@ import {
25
25
  import type { MinimaxModel, MinimaxPromptBlock, MinimaxUsageSnapshot } from './minimax.ts'
26
26
  import { resolveMinimaxCli } from './minimax-cli.ts'
27
27
  import { reasoningInfo, planContinuation } from './adapter.ts'
28
+ import { cachedModels } from './model-cache.ts'
28
29
  import type { ImageRequestReader } from './adapter.ts'
29
30
  import type { Live } from './live.ts'
30
31
  import { readLive, readLiveOptional } from './live.ts'
@@ -255,10 +256,12 @@ export class MinimaxAdapter extends LlmAdapter {
255
256
  const region = this.region
256
257
  const target = resolveMinimaxModelId(model, this.aliases)
257
258
  const key = `${region}:${target}`
258
- const live = (await this.catalog.models(region)).find(entry => entry.id === target)
259
+ // Cache first: resolving a route may not wait on an ACP probe.
260
+ const live = (await cachedModels(this.catalog.snapshot(region), () => this.catalog.models(region)))
261
+ .find(entry => entry.id === target)
259
262
  if (live !== undefined) {
260
263
  this.knownVision.set(key, live.vision)
261
- const reasoning = reasoningInfo(live.reasoningEfforts, live.defaultEffort, live.reasoning)
264
+ const reasoning = reasoningInfo(live.reasoningEfforts, readLiveOptional(this.options.defaultReasoningEffort), live.reasoning)
262
265
  return {
263
266
  provider,
264
267
  id: model,
package/src/minimax.ts CHANGED
@@ -1527,6 +1527,16 @@ export class MinimaxCatalog {
1527
1527
  }
1528
1528
  }
1529
1529
 
1530
+ /**
1531
+ * The last successful list for a region, without probing.
1532
+ *
1533
+ * The picker resolves a route on every switch; awaiting an ACP probe there
1534
+ * cost a process round-trip whenever the TTL had just expired.
1535
+ */
1536
+ snapshot(requested?: MinimaxRegion): readonly MinimaxModel[] | undefined {
1537
+ return this.snapshots.get(requested ?? readLive(this.region, 'cn'))?.models
1538
+ }
1539
+
1530
1540
  /** Why the last refresh failed, or undefined when it succeeded. */
1531
1541
  error(requested?: MinimaxRegion): string | undefined {
1532
1542
  return this.failures.get(requested ?? readLive(this.region, 'cn'))
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Cache-first catalogue reads for the model picker.
3
+ *
4
+ * The harness resolves a route every time the user switches model or reasoning
5
+ * level, and each of the three providers answers that resolution from a
6
+ * catalogue whose fetch is expensive: Qoder cold-starts its CLI (up to the
7
+ * fetch timeout), CodeBuddy boots a process, MiniMax probes over ACP. Awaiting
8
+ * that fetch inside a resolution made the picker freeze for seconds whenever
9
+ * the cache had just expired.
10
+ *
11
+ * So a resolution reads the last successful snapshot when there is one and lets
12
+ * the catalogue refresh behind it; only the very first resolution, where there
13
+ * is nothing to show, waits. A snapshot that is merely stale still describes
14
+ * the same account's models, so answering from it is no less correct than the
15
+ * previous behaviour of answering from a failed fetch's fallback.
16
+ *
17
+ * @module dsh-agent-sdk-bridge/model-cache
18
+ */
19
+
20
+ /**
21
+ * The cached list when one exists, otherwise the awaited fetch.
22
+ *
23
+ * @param snapshot - last successful catalogue, or undefined before the first.
24
+ * @param fetch - the catalogue's normal (TTL-aware, in-flight-sharing) read.
25
+ * @returns the entries to resolve against, never empty-by-surprise when a
26
+ * snapshot exists.
27
+ */
28
+ export async function cachedModels<T>(
29
+ snapshot: readonly T[] | undefined,
30
+ fetch: () => Promise<readonly T[]>,
31
+ ): Promise<readonly T[]> {
32
+ if (snapshot !== undefined && snapshot.length > 0) {
33
+ // Kick the refresh but do not wait for it: the caller needs an answer now,
34
+ // and a failure here changes nothing because the snapshot stays published.
35
+ void fetch().catch(() => undefined)
36
+ return snapshot
37
+ }
38
+ return fetch()
39
+ }
package/src/models.ts CHANGED
@@ -17,7 +17,7 @@ import type { QoderBrand } from './brand.ts'
17
17
  import { brandProfile } from './brand.ts'
18
18
  import type { QoderCatalogModel } from './catalog.ts'
19
19
  import { QODER_MODELS } from './catalog.ts'
20
- import { cliConflictMessage, foreignCliOverride, qoderCliOptions } from './cli.ts'
20
+ import { cliConflictMessage, cliFailureText, foreignCliOverride, qoderCliOptions } from './cli.ts'
21
21
  import type { Live } from './live.ts'
22
22
  import { readLive } from './live.ts'
23
23
  import { loadSdk } from './sdk.ts'
@@ -94,13 +94,28 @@ export class QoderModelCatalog {
94
94
  this.failure = undefined
95
95
  return officialOnly(models)
96
96
  } catch (error) {
97
- this.failure = error instanceof Error ? error.message : String(error)
97
+ const detail = error instanceof Error ? error.message : String(error)
98
+ this.failure = cliFailureText(detail, this.brand)
98
99
  // A failed refresh keeps serving the last good list rather than dropping
99
100
  // to the static fallback, which would hide the account's real models.
100
101
  return officialOnly((this.cached ?? sharedSnapshots.get(this.brand))?.models ?? [])
101
102
  }
102
103
  }
103
104
 
105
+ /**
106
+ * The last successful live list, without fetching.
107
+ *
108
+ * The model picker resolves a route on every switch, and a switch must not
109
+ * wait on a CLI cold start (up to the fetch timeout). Callers that need an
110
+ * immediate answer read this and let {@link liveModels} refresh behind them;
111
+ * `undefined` means nothing has been read yet, which only the first switch
112
+ * has to wait for.
113
+ */
114
+ snapshot(): readonly ModelInfo[] | undefined {
115
+ const cached = this.cached ?? sharedSnapshots.get(this.brand)
116
+ return cached === undefined ? undefined : officialOnly(cached.models)
117
+ }
118
+
104
119
  /** Why the last refresh failed, or undefined when it succeeded. */
105
120
  get error(): string | undefined {
106
121
  return this.failure
@@ -150,7 +165,31 @@ export class QoderModelCatalog {
150
165
  },
151
166
  })
152
167
  try {
153
- return await withTimeout(q.getAvailableModels({ fetchStrategy: 'live' }), readLive(this.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS))
168
+ const timeout = readLive(this.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS)
169
+ // Read the account first, then ask for that account's catalog.
170
+ //
171
+ // On SDK 1.0.58 a `get_models` call made before any account lookup
172
+ // answers an empty list — even though the CLI's own `--list-models`
173
+ // prints eleven entries for the same login. Passing the account's `uid`
174
+ // (or simply having asked for the account in this session) returns the
175
+ // real list, so the catalogue has to be read in that order. Reporting
176
+ // the empty answer instead made the settings page show 0/0 and claim a
177
+ // working install was missing.
178
+ const account = await withTimeout(q.accountInfo(), timeout).catch(() => undefined)
179
+ const uid = account?.userId
180
+ const models = await withTimeout(
181
+ q.getAvailableModels(uid === undefined ? {} : { uid }),
182
+ timeout,
183
+ )
184
+ if (models.length > 0) return models
185
+ // Still empty: ask the CLI for its on-disk copy, then the server copy,
186
+ // before letting the page conclude the account has no models.
187
+ for (const strategy of ['cache', 'live'] as const) {
188
+ const fallback = await withTimeout(q.getAvailableModels({ ...uid === undefined ? {} : { uid }, fetchStrategy: strategy }), timeout)
189
+ .catch(() => [] as ModelInfo[])
190
+ if (fallback.length > 0) return fallback
191
+ }
192
+ return []
154
193
  } finally {
155
194
  await q.close().catch(() => undefined)
156
195
  }
package/src/session.ts CHANGED
@@ -19,7 +19,7 @@ import type {
19
19
  import { createSdkMcpServer, qodercliAuth } from '@qodercn-ai/qodercn-agent-sdk'
20
20
  import type { CanUseTool, Query } from '@qodercn-ai/qodercn-agent-sdk'
21
21
  import type { QoderBrand } from './brand.ts'
22
- import { cliConflictMessage, foreignCliOverride, qoderCliOptions } from './cli.ts'
22
+ import { cliConflictMessage, cliFailureText, foreignCliOverride, qoderCliOptions } from './cli.ts'
23
23
  import { jsonSchemaToShape } from './jsonschema.ts'
24
24
  import type { Live } from './live.ts'
25
25
  import { readLive } from './live.ts'
@@ -1220,7 +1220,7 @@ export class QoderSession {
1220
1220
  }
1221
1221
  this.endTurn({ kind: 'error', failure: { message: 'qoder session stream ended unexpectedly', code: 'STREAM_CLOSED' } })
1222
1222
  } catch (error) {
1223
- this.endTurn({ kind: 'error', failure: { message: `qoder session died: ${String(error)}`, code: 'TRANSPORT' } })
1223
+ this.endTurn({ kind: 'error', failure: { message: `qoder session died: ${cliFailureText(String(error), this.brand)}`, code: 'TRANSPORT' } })
1224
1224
  }
1225
1225
  }
1226
1226
 
package/src/setup.ts CHANGED
@@ -25,6 +25,7 @@ import { fileURLToPath } from 'node:url'
25
25
  import { TextDecoder } from 'node:util'
26
26
  import type { QoderBrand } from './brand.ts'
27
27
  import { brandProfile } from './brand.ts'
28
+ import { installedCliVersion, requiredCliVersion, resolveQoderCli } from './cli.ts'
28
29
 
29
30
  /** File name of the CN helper, shipped under this package's `scripts/` directory. */
30
31
  export const SCRIPT_NAME = 'setup-qoderclicn.bat'
@@ -65,6 +66,8 @@ interface Run {
65
66
  pending: string
66
67
  decoder: TextDecoder
67
68
  truncated: boolean
69
+ /** Set when the page cancelled this run, so it can say so instead of a code. */
70
+ cancelled?: boolean
68
71
  }
69
72
 
70
73
  /** The latest run per edition: the two installers may run independently. */
@@ -80,6 +83,27 @@ export interface SetupStatus {
80
83
  code?: number | null
81
84
  lines: string[]
82
85
  truncated: boolean
86
+ /**
87
+ * Whether this edition's CLI is on the machine right now.
88
+ *
89
+ * Read from the same lookup a session uses, not from the last run's exit
90
+ * code: after an uninstall the page must offer "install" again, and a run
91
+ * that ended successfully months ago says nothing about today's machine.
92
+ */
93
+ installed: boolean
94
+ /** Version of the installed CLI, when its package manifest could be read. */
95
+ cliVersion?: string
96
+ /** Version this plugin's SDK speaks; the helper installs exactly this one. */
97
+ requiredCliVersion?: string
98
+ /**
99
+ * The installed CLI speaks a different protocol build than the SDK.
100
+ *
101
+ * Sessions then die with a bare exit code, so the page warns here — before a
102
+ * sign-in — instead of letting the user log in and hit the failure in chat.
103
+ */
104
+ versionMismatch?: boolean
105
+ /** Whether the last run was stopped from the page rather than finishing. */
106
+ cancelled?: boolean
83
107
  }
84
108
 
85
109
  /**
@@ -210,8 +234,21 @@ export function startSetup(
210
234
  * @param brand - which edition's run to report.
211
235
  */
212
236
  export function readSetupStatus(brand: QoderBrand = 'cn'): SetupStatus {
237
+ const installed = resolveQoderCli(brand) !== undefined
238
+ const cliVersion = installed ? installedCliVersion(brand) : undefined
239
+ const required = requiredCliVersion(brand)
240
+ const build = {
241
+ installed,
242
+ ...cliVersion === undefined ? {} : { cliVersion },
243
+ ...required === undefined ? {} : { requiredCliVersion: required },
244
+ // Unknown on either side is not a mismatch: a native build carries no
245
+ // manifest, and warning about a version nobody could read would be noise.
246
+ ...cliVersion === undefined || required === undefined
247
+ ? {}
248
+ : { versionMismatch: cliVersion !== required },
249
+ }
213
250
  const run = current.get(brand)
214
- if (run === undefined) return { running: false, lines: [], truncated: false }
251
+ if (run === undefined) return { running: false, lines: [], truncated: false, ...build }
215
252
  const lines = run.pending.trim() === ''
216
253
  ? run.lines
217
254
  : [...run.lines, run.pending.trim()]
@@ -222,7 +259,38 @@ export function readSetupStatus(brand: QoderBrand = 'cn'): SetupStatus {
222
259
  ...run.finishedAt === undefined ? {} : { finishedAt: run.finishedAt, code: run.code ?? null },
223
260
  lines,
224
261
  truncated: run.truncated,
262
+ ...build,
263
+ ...run.cancelled === true ? { cancelled: true } : {},
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Abandon the running helper for one edition.
269
+ *
270
+ * `qodercli login` waits for the browser to finish the callback, so closing
271
+ * that tab left the page polling a process that would never return. Killing
272
+ * the run turns it into a finished one (`code` null) so the page can offer the
273
+ * buttons again instead of showing a spinner forever.
274
+ *
275
+ * @param brand - which edition's run to stop.
276
+ * @returns whether a run was actually in flight.
277
+ */
278
+ export function cancelSetup(brand: QoderBrand): boolean {
279
+ const run = current.get(brand)
280
+ if (run === undefined || run.finishedAt !== undefined) return false
281
+ run.lines.push('已取消:这次配置被手动终止,可以重新操作。')
282
+ run.cancelled = true
283
+ try {
284
+ run.child.kill()
285
+ } catch {
286
+ // Already gone; settling below still releases the page.
225
287
  }
288
+ // The child's `close` handler may arrive later (or never, if it never
289
+ // spawned); settle here so the page is not left waiting on it. `finish()`
290
+ // refuses to touch a settled run, so the late event cannot overwrite this.
291
+ run.finishedAt = Date.now()
292
+ run.code = null
293
+ return true
226
294
  }
227
295
 
228
296
  /**