dsh-agent-sdk-bridge 1.1.8 → 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/DEVELOPMENT.md CHANGED
@@ -8,7 +8,39 @@
8
8
  登录区域),其余代码按 brand 参数化。CN Qoder SDK 静态引入;另两个 SDK 按需 `import()`,
9
9
  没装时只有对应页面报错,插件照常加载。
10
10
  - **品牌隔离**:各 provider 的 CLI 查找、模型目录缓存、会话池、账户读取、模型开关全部按 brand
11
- 分开。`QODERCLI_PATH` 若指向另一 Qoder 版本,对应版本会明确报错而不是借用那个 CLI 的账号。
11
+ 分开。`QODERCLI_PATH` 是机器级变量,不少 CN 安装会全局导出它;两个 SDK 又都在读到我们传的
12
+ 选项之前就先读它,所以 `cliChildEnv()` 会从**子进程环境**里删掉指向另一版本的 `QODERCLI_PATH`
13
+ (中立路径保留)。查找本身也永远不把另一版本的路径当作本版本候选。`foreignCliOverride()`
14
+ 现在只作诊断:本版本完全没有自己的 CLI 时才指出「那个变量属于另一版本」,绝不会因为它的存在
15
+ 而让本版本拒绝启动——旧代码把它当致命错误,于是一台只装了国际版(或只装了 CN)的机器,
16
+ 另一个页面即使装好 CLI 也登不进去。
17
+ - **SDK 与 CLI 的版本是绑定的**:每个 SDK 发布版在 `dist/runtime-manifest.json` 里钉住一个
18
+ `qoderCliVersion`,两边说的是同一条 wire protocol。CLI 1.1.81 移除了旧 SDK 的 worker 会话握手,
19
+ 于是 SDK 1.0.51 的每次查询都以 `Qoder CLI process exited with code 42` 结束,CLI 自己的日志写的
20
+ 是 `sdk_worker_removed: … Upgrade to the latest Qoder SDK version, or roll back the CLI`。
21
+ 因此:`dependencies` 里的两个 Qoder SDK 锁在同一个大版本(1.0.58 ↔ CLI 1.1.81);
22
+ 两个 `setup-*.bat` 从 SDK 清单读出 `qoderCliVersion` 并安装**那个精确版本**(不是 latest);
23
+ `requiredCliVersion()` / `installedCliVersion()` 都从磁盘读(后者读 npm 包的 manifest,不 spawn),
24
+ `/setup` 据此回传 `requiredCliVersion` / `cliVersion` / `versionMismatch`,页面在登录前就红字提示;
25
+ `cliFailureText()` 把 code 42 翻译成「点一键配置装配套版本」,并把原始信息附在后面。
26
+ 另注:`sdkDir()` 要剥掉 `dist` 这一层——`resolve()` 返回的是包内入口,直接 `dirname` 得到的是
27
+ `dist`,再拼 `dist/runtime-manifest.json` 就成了 `dist/dist/…`,两个探测都会静默失败。
28
+ - **Qoder 目录要先读账号**:SDK 1.0.58 里,在 `accountInfo()` 之前调 `getAvailableModels()` 会返回
29
+ 空数组(CLI 的 `--list-models` 同账号却能打出 11 条)。先在同一个 session 里取账号、再带 `uid`
30
+ 查目录才稳定;空答案时再依次回落 `fetchStrategy: 'cache'` → `'live'`。否则设置页显示 0/0,
31
+ 看起来像「没装 CLI」,实际只是读序不对。
32
+ - **CLI 查找要认包清单**:`bundle/<name>.js` 是常见布局,不是唯一布局。`packageEntries()` 还会
33
+ 读包自己的 `package.json`(`main`/`bin`),并把 Windows 的 `<node>/node_modules` 与 unix 的
34
+ `<prefix>/lib/node_modules` 都当作全局根。只猜 `bundle/` 会把已安装的 CLI 判成未安装,
35
+ 页面就一直要你「再装一次」。
36
+ - **卸载要清干净**:npm 只删包,会留下空的 `node_modules/@qoder-ai`(或 `@qodercn-ai`)目录和
37
+ `qodercli.cmd`/`.ps1` 之类 shim,而 CLI 查找和页面的「已安装」徽标读的正是这些。两个
38
+ `setup-*.bat` 的 `--uninstall` 会在 `npm uninstall -g` 之后删掉 shim 与空 scope 目录,
39
+ 页面的「已安装」状态则来自 `readSetupStatus().installed`(每次现查 `resolveQoderCli()`),
40
+ 所以卸载后主按钮会变回「安装 CLI」,而不是继续显示「卸载」。
41
+ - **登录可取消**:`qodercli login` 会一直等浏览器回调,用户关掉标签页后旧代码只能空转。
42
+ `POST /setup {mode:'cancel'}` → `cancelSetup()` 杀掉子进程并把这次 run 标记为已结束
43
+ (`code: null`、`cancelled: true`),页面每 1.2 秒轮询一次状态,因此按钮会立刻回来。
12
44
  - **Qoder 的声明窗口必须稳定**:Qoder 的 `context_usage_ratio` 是「按 CLI 实际运行的窗口」算的,
13
45
  而 DSH 又用适配器上报的 `contextWindow` 当分母。两者一变,环就会跳。实测目录里 `dfmodel`
14
46
  等模型声明 `availableContextWindows: [200000, 400000, 1000000]`、默认 200000,用户选 1M 是
package/FAQ.md CHANGED
@@ -2,11 +2,35 @@
2
2
 
3
3
  使用中遇到的问题与历史修复记录。返回 [README](./README.md)。
4
4
 
5
- **国际版页面提示「QODERCLI_PATH 指向了另一版本的 CLI」?** 这是有意的隔离。部分 CN 安装会在
6
- 环境里设置 `QODERCLI_PATH`,而两个官方 SDK 都会在读取任何参数之前先看这个变量。如果放行,国际版
7
- 会话会启动 `qoderclicn`、拿 CN 账号作答——模型目录和额度都会串台。插件因此只在它不指向另一版本
8
- 时采用;国际版自己的覆盖变量是 `QODER_CLI_PATH`。要么装好 `qodercli`(插件会优先用它),要么把
9
- 该变量指向国际版 CLI。
5
+ **登录后对话直接报 `Qoder CLI process exited with code 42`?** 这是 CLI 与插件 SDK 的版本不匹配:
6
+ 每个 SDK 发布版都钉住一个 CLI 版本,两边说的是同一条协议。CLI 1.1.81 移除了旧 SDK 的会话握手,
7
+ 旧 SDK 每次查询都会被 CLI 以退出码 42 结束(CLI 日志原文 `sdk_worker_removed: … Upgrade to the
8
+ latest Qoder SDK version, or roll back the CLI`)。插件已把两个 SDK 升到 1.0.58(对应 CLI 1.1.81),
9
+ 并且「一键配置」现在按 SDK 清单安装**精确版本**而不是 latest。升级插件后:设置页会直接显示
10
+ 「CLI 版本与插件不匹配:本机 x,插件需要 y」,点「安装 CLI」重装即可;如果版本已经一致还报 42,
11
+ 重启 DSH Web 让新版 SDK 生效。
12
+
13
+ **只启用国内版 / 只启用国际版,另一个版本没装,会不会互相影响?** 不会(这是修过的 bug)。
14
+ `QODERCLI_PATH` 是机器级变量,不少 CN 安装会全局导出它;两个官方 SDK 又都在读到插件传的参数
15
+ 之前先看它。旧代码一旦发现它指向另一版本就判为致命错误,于是一台只装了国际版的机器,国内版
16
+ 页面即使后来装好了 `qoderclicn` 也登不进去——两个版本被这个变量绑在一起。现在查找各自只认
17
+ 自己的包与状态目录,并且会把指向另一版本的 `QODERCLI_PATH` 从**子进程环境**里删掉(中立路径
18
+ 保留);只有本版本完全没有自己的 CLI 时,页面才会提示「那个变量属于另一版本」。两个版本的
19
+ 安装、登录、卸载因此完全独立。
20
+
21
+ **卸载了 CLI,页面上还是「卸载」按钮、目录里还有残留?** 已修复。npm 只删包,会留下空的
22
+ `node_modules/@qoder-ai`(或 `@qodercn-ai`)目录和 `qodercli.cmd` / `.ps1` 这些 shim,而插件的
23
+ CLI 查找和页面徽标读的正是它们。现在 `--uninstall` 会在 `npm uninstall -g` 之后删掉 shim 与空
24
+ scope 目录;页面上的「已安装」也改成每次现查机器,所以卸载后主按钮立刻变回「安装 CLI」,
25
+ 登录 / 卸载按钮只在已安装时出现。
26
+
27
+ **点「重新登录」后关掉了浏览器,页面就一直转圈?** 已修复,并新增「取消」。`qodercli login`
28
+ 会一直等浏览器回调,关掉标签页就没有返回值。现在运行中会出现「取消」按钮:点它会终止这次
29
+ 脚本、把状态标记为已取消,按钮立刻恢复,可以重新登录。
30
+
31
+ **国际版页面提示「QODERCLI_PATH 指向了另一版本的 CLI」?** 只有在国际版本机完全没有自己的
32
+ `qodercli` 时才会这样提示,属于诊断而非拦截。装好 `qodercli`(或把 `QODER_CLI_PATH` 指向它)
33
+ 即可;插件绝不会把 CN 的 CLI 借给国际版会话,因为那会拿 CN 账号作答。
10
34
 
11
35
  **额度卡片显示「无法读取额度」?** 卡片里的文字就是原因:CLI 未安装 / 未登录 / 额度接口暂时
12
36
  不可用。额度读取走的是 CLI 自己的凭证,所以先确认对应版本的 `status` 能列出用户名;点「刷新额度」
package/client.js CHANGED
@@ -86,6 +86,13 @@ window.__ModuleLoader__.load({
86
86
  cliUninstallConfirm: '确定要卸载本机的 Qoder CLI 吗?卸载后需要重新安装才能继续使用,登录凭证会保留。',
87
87
  cliUninstalling: '正在卸载…',
88
88
  cliUninstallOk: 'CLI 已卸载',
89
+ cliInstall: '安装 CLI',
90
+ cliInstalled: '已安装',
91
+ cliCancel: '取消',
92
+ cliCancelling: '正在取消…',
93
+ cliCancelled: '已取消,可以重新操作',
94
+ cliVersionMismatch: 'CLI 版本与插件不匹配:本机',
95
+ cliVersionMismatchTail: ',插件需要',
89
96
  intlNav: 'Qoder 国际版',
90
97
  intlTitle: 'Qoder 国际版',
91
98
  intlIntro: '国际版账户(qoder.com)的模型与额度。勾选要启用的模型,并为需要的模型指定上下文窗口。改动即时生效,无需重启。',
@@ -113,6 +120,7 @@ window.__ModuleLoader__.load({
113
120
  usageUpdated: '更新于',
114
121
  usageUnknownPlan: '未知套餐',
115
122
  usageStale: '显示上次读数,刷新失败',
123
+ usageCliMissing: '未检测到本机 CLI,安装并登录后才会显示额度。',
116
124
  pluginOptionsTitle: '启用的版本',
117
125
  pluginOptionsHint: '关闭后,对应设置页、模型列表与模型分组都会移除;已保存的模型选择保留,重新打开即可恢复。',
118
126
  pluginOptionsOn: '显示中',
@@ -275,6 +283,13 @@ window.__ModuleLoader__.load({
275
283
  cliUninstallConfirm: 'Uninstall the Qoder CLI from this machine? It must be installed again to keep using this edition. Sign-in files are kept.',
276
284
  cliUninstalling: 'Uninstalling…',
277
285
  cliUninstallOk: 'CLI uninstalled',
286
+ cliInstall: 'Install CLI',
287
+ cliInstalled: 'Installed',
288
+ cliCancel: 'Cancel',
289
+ cliCancelling: 'Cancelling…',
290
+ cliCancelled: 'Cancelled — you can start again',
291
+ cliVersionMismatch: 'CLI version does not match the plugin: this machine has',
292
+ cliVersionMismatchTail: 'but the plugin needs',
278
293
  intlNav: 'Qoder International',
279
294
  intlTitle: 'Qoder International',
280
295
  intlIntro: 'Models and quota for the international account (qoder.com). Tick the models you want available and set a context window where needed. Changes apply immediately.',
@@ -302,6 +317,7 @@ window.__ModuleLoader__.load({
302
317
  usageUpdated: 'Updated',
303
318
  usageUnknownPlan: 'Unknown plan',
304
319
  usageStale: 'Showing the last reading; refresh failed',
320
+ usageCliMissing: 'This machine has no CLI for this edition; quota appears after it is installed and signed in.',
305
321
  pluginOptionsTitle: 'Enabled editions',
306
322
  pluginOptionsHint: 'Turning one off removes its settings page, model list, and model group. Saved model choices are kept, so turning it back on restores them.',
307
323
  pluginOptionsOn: 'Shown',
@@ -644,6 +660,24 @@ window.__ModuleLoader__.load({
644
660
  }
645
661
  }
646
662
 
663
+ /**
664
+ * Forget one cached answer.
665
+ *
666
+ * Needed when the cache has become wrong rather than merely old: after an
667
+ * uninstall the stored quota describes an account read through a CLI that
668
+ * is no longer on the machine, and painting it again on the next render
669
+ * would keep showing numbers nobody can reproduce.
670
+ */
671
+ function clearCache(brand, kind) {
672
+ const key = cacheKey(brand, kind)
673
+ cacheMemory.delete(key)
674
+ try {
675
+ window.localStorage.removeItem(key)
676
+ } catch {
677
+ /* storage unavailable: the in-memory copy is already gone */
678
+ }
679
+ }
680
+
647
681
  /** Call the plugin's model API. */
648
682
  async function api(path, options) {
649
683
  const { timeout = 30_000, ...rest } = options ?? {}
@@ -860,6 +894,8 @@ window.__ModuleLoader__.load({
860
894
  const [snapshot, setSnapshot] = useState(() => readCache(brand.id, 'usage'))
861
895
  const [failure, setFailure] = useState(undefined)
862
896
  const [busy, setBusy] = useState(false)
897
+ /** The CLI is not installed: show that, and never any cached numbers. */
898
+ const [missing, setMissing] = useState(false)
863
899
  const ticket = useRef(0)
864
900
 
865
901
  const load = useCallback(async (fresh = false) => {
@@ -869,12 +905,25 @@ window.__ModuleLoader__.load({
869
905
  try {
870
906
  const payload = await api(`/usage?brand=${brand.id}${fresh ? '&fresh=1' : ''}`, { timeout: 45_000 })
871
907
  if (mine !== ticket.current) return
872
- // A failed account lookup (signed out, endpoint down) must not replace
908
+ // The CLI is gone: the stored reading describes an installation that
909
+ // no longer exists, so drop it (memory and storage) instead of
910
+ // labelling old credits "last reading". This is what makes the card
911
+ // empty out after an uninstall.
912
+ if (payload?.cliMissing === true) {
913
+ clearCache(brand.id, 'usage')
914
+ setSnapshot(undefined)
915
+ setMissing(true)
916
+ setFailure(String(payload.error ?? t('usageCliMissing')))
917
+ return
918
+ }
919
+ // Any other failed lookup (signed out, endpoint down) must not replace
873
920
  // the last good reading with an empty card: keep it and say so.
874
921
  if (payload?.usage === undefined && payload?.error !== undefined) {
922
+ setMissing(false)
875
923
  setFailure(String(payload.error))
876
924
  return
877
925
  }
926
+ setMissing(false)
878
927
  setSnapshot(payload)
879
928
  writeCache(brand.id, 'usage', payload)
880
929
  } catch (err) {
@@ -911,9 +960,14 @@ window.__ModuleLoader__.load({
911
960
  if (snapshot === undefined || usage === undefined) {
912
961
  return h('div', { style: css.usageCard },
913
962
  head,
914
- error === undefined
915
- ? h('div', { style: css.note }, t('usageLoading'))
916
- : h('div', { style: css.err }, `${t('usageUnavailable')}:${error}`),
963
+ // Nothing is shown for a missing CLI beyond the reason: the account,
964
+ // plan and credits a previous install reported are not this machine's
965
+ // state any more.
966
+ missing
967
+ ? h('div', { style: css.note }, error ?? t('usageCliMissing'))
968
+ : error === undefined
969
+ ? h('div', { style: css.note }, t('usageLoading'))
970
+ : h('div', { style: css.err }, `${t('usageUnavailable')}:${error}`),
917
971
  error === undefined
918
972
  ? null
919
973
  : h('div', { style: css.bar },
@@ -2077,6 +2131,14 @@ window.__ModuleLoader__.load({
2077
2131
  const setupCode = setup !== undefined && setup.running === false ? setup.code : undefined
2078
2132
  const setupFinishedAt = setup?.finishedAt
2079
2133
  const setupLines = Array.isArray(setup?.lines) ? setup.lines : []
2134
+ // `installed` is read from the host's own CLI lookup, so the button
2135
+ // follows the machine rather than the last run: after an uninstall it
2136
+ // reads false even though that run exited 0, and the page offers
2137
+ // "install" again instead of a dead "uninstall". Until the first status
2138
+ // arrives the old layout is kept, so opening the page does not flash an
2139
+ // "install" button on a machine that already has the CLI.
2140
+ const cliInstalled = setup === undefined ? true : setup.installed === true
2141
+ const setupCancelled = setup?.cancelled === true
2080
2142
 
2081
2143
  useEffect(() => { void pollSetup() }, [pollSetup])
2082
2144
  useEffect(() => {
@@ -2311,10 +2373,36 @@ window.__ModuleLoader__.load({
2311
2373
  brand.kind !== 'qoder' ? null : h('div', { style: css.group },
2312
2374
  h('h3', { style: css.h3 }, t(brand.cliGroupKey)),
2313
2375
  h('div', { style: css.note }, t(brand.cliHintKey)),
2376
+ // Each SDK release pins one CLI build; a mismatch kills every session
2377
+ // with a bare exit code, so warn before the user signs in or chats.
2378
+ setup?.versionMismatch === true
2379
+ ? h('div', { style: { ...css.err, marginTop: '6px' } },
2380
+ `${t('cliVersionMismatch')} ${setup.cliVersion ?? '?'} ${t('cliVersionMismatchTail')} ${setup.requiredCliVersion ?? '?'}`)
2381
+ : null,
2314
2382
  h('div', { style: { ...css.bar, flexWrap: 'nowrap' } },
2315
- h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('configure') }, t('cliRun')),
2316
- h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('login') }, t('cliLogin')),
2317
- h('button', { style: { ...css.btn, ...css.btnAlert }, disabled: setupRunning, onClick: uninstallCli }, t('cliUninstall')),
2383
+ // The primary action follows the machine: install when the CLI is
2384
+ // gone, configure/re-login when it is there. Offering "uninstall"
2385
+ // on a machine that has none was the confusing half of the old
2386
+ // fixed trio.
2387
+ cliInstalled
2388
+ ? h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('configure') },
2389
+ setup?.versionMismatch === true ? t('cliInstall') : t('cliRun'))
2390
+ : h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('configure') }, t('cliInstall')),
2391
+ cliInstalled
2392
+ ? h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('login') }, t('cliLogin'))
2393
+ : null,
2394
+ cliInstalled
2395
+ ? h('button', { style: { ...css.btn, ...css.btnAlert }, disabled: setupRunning, onClick: uninstallCli }, t('cliUninstall'))
2396
+ : null,
2397
+ // The login step waits for a browser callback; closing that tab
2398
+ // used to leave this row spinning forever. Cancelling settles the
2399
+ // run so the buttons come back.
2400
+ setupRunning
2401
+ ? h('button', {
2402
+ style: { ...css.btn, ...css.btnAlert },
2403
+ onClick: () => void startCliSetup('cancel'),
2404
+ }, t('cliCancel'))
2405
+ : null,
2318
2406
  setupLines.length > 0 && !setupRunning
2319
2407
  ? h('button', { style: css.btn, onClick: () => setLogOpen(value => !value) }, logOpen ? t('cliHideLog') : t('cliShowLog'))
2320
2408
  : null,
@@ -2322,14 +2410,16 @@ window.__ModuleLoader__.load({
2322
2410
  ? (setup?.mode === 'uninstall' ? t('cliUninstalling') : t('cliRunning'))
2323
2411
  : setupError !== undefined
2324
2412
  ? setupError
2325
- : setupCode === 0
2326
- ? (setup?.mode === 'uninstall' ? t('cliUninstallOk') : t('cliExitOk'))
2327
- : setupCode === undefined || setupCode === null
2328
- ? ''
2329
- : `${t('cliExitFail')} ${setupCode}`),
2413
+ : setupCancelled
2414
+ ? t('cliCancelled')
2415
+ : setupCode === 0
2416
+ ? (setup?.mode === 'uninstall' ? t('cliUninstallOk') : t('cliExitOk'))
2417
+ : setupCode === undefined || setupCode === null
2418
+ ? ''
2419
+ : `${t('cliExitFail')} ${setupCode}`),
2330
2420
  ),
2331
2421
  logOpen && setupLines.length > 0
2332
- ? h('pre', { ref: logRef, style: css.log }, setupLines.join('\n'))
2422
+ ? h('pre', { ref: logRef, style: css.log }, setupLines.join('\\n'))
2333
2423
  : null,
2334
2424
  ),
2335
2425
 
package/lib/index.js CHANGED
@@ -364,20 +364,17 @@ function resolveQoderCli(brand = "cn", lookup = {}) {
364
364
  function qoderCliOptions(brand = "cn", lookup = {}) {
365
365
  const cli = resolveQoderCli(brand, lookup);
366
366
  if (cli === void 0) return {};
367
+ const env = cliChildEnv(brand);
367
368
  if (cli.nodeDir === void 0) return {
368
369
  pathToQoderCLIExecutable: cli.path,
369
- env: {
370
- ...process.env,
371
- ...EXPOSE_TOKEN_USAGE
372
- }
370
+ env
373
371
  };
374
372
  return {
375
373
  pathToQoderCLIExecutable: cli.path,
376
374
  executable: "node",
377
375
  env: {
378
- ...process.env,
379
- PATH: `${cli.nodeDir}${path.delimiter}${process.env.PATH ?? ""}`,
380
- ...EXPOSE_TOKEN_USAGE
376
+ ...env,
377
+ PATH: `${cli.nodeDir}${path.delimiter}${env.PATH ?? ""}`
381
378
  }
382
379
  };
383
380
  }
@@ -397,15 +394,24 @@ function isForeignCliPath(brand, candidate) {
397
394
  return brand === "global" ? chinese : global;
398
395
  }
399
396
  /**
400
- * A `QODERCLI_PATH` that names the other edition, when this one has no CLI.
397
+ * Why this edition has no usable CLI, when `QODERCLI_PATH` explains it.
401
398
  *
402
- * The SDKs read that variable from the parent process before any option this
403
- * plugin can pass, so when it is foreign and this edition has nothing of its
404
- * own, the only honest answer is a configuration error — spawning the other
405
- * edition's CLI would answer with the other edition's account.
399
+ * `QODERCLI_PATH` predates the international edition and some installers
400
+ * export it machine-wide. Both SDKs read it from the parent process before any
401
+ * option this plugin can pass, so a value naming the *other* edition would
402
+ * hand this edition's session the other account. The lookup therefore never
403
+ * offers it ({@link isForeignCliPath}), and this reports the case where it is
404
+ * all the machine has, so the page can ask for the right CLI to be installed.
405
+ *
406
+ * This is a diagnosis, not a second rule: an edition that finds its own CLI is
407
+ * unaffected by the variable. That is what keeps one edition's install from
408
+ * blocking the other's sign-in — the earlier code treated any foreign value as
409
+ * fatal, so a machine that had only the intl CLI installed could not sign in
410
+ * to CN even after installing it if the lookup missed the new package.
406
411
  *
407
412
  * @param brand - the edition the caller is about to start.
408
413
  * @param lookup - the machine to inspect; defaults to this process's.
414
+ * @returns the foreign override when this edition has nothing of its own.
409
415
  */
410
416
  function foreignCliOverride(brand, lookup = {}) {
411
417
  const override = (lookup.env ?? process.env).QODERCLI_PATH;
@@ -415,6 +421,26 @@ function foreignCliOverride(brand, lookup = {}) {
415
421
  return override;
416
422
  }
417
423
  /**
424
+ * The environment one session's child process receives.
425
+ *
426
+ * `QODERCLI_PATH` is stripped when it names the other edition: both SDKs read
427
+ * it from the parent before honouring any option, so leaving it in place would
428
+ * hand the intl session the CN CLI (and the CN account). Every other variable
429
+ * is inherited untouched — the CLI keeps its state in `PATH`-relative dirs.
430
+ *
431
+ * @param brand - which edition's child is being started.
432
+ * @param env - the environment to derive from; defaults to this process's.
433
+ */
434
+ function cliChildEnv(brand, env = process.env) {
435
+ const child = {
436
+ ...env,
437
+ ...EXPOSE_TOKEN_USAGE
438
+ };
439
+ const override = env.QODERCLI_PATH;
440
+ if (override !== void 0 && override.length > 0 && isForeignCliPath(brand, override)) delete child.QODERCLI_PATH;
441
+ return child;
442
+ }
443
+ /**
418
444
  * The error text for {@link foreignCliOverride}.
419
445
  *
420
446
  * Deliberately says nothing about the variable or the path that caused it: the
@@ -424,6 +450,70 @@ function foreignCliOverride(brand, lookup = {}) {
424
450
  function cliConflictMessage(brand) {
425
451
  return `未检测到可用的 ${brandProfile(brand).cliCommands[0]},请先安装并登录后再使用此版本。`;
426
452
  }
453
+ /**
454
+ * Turn a CLI failure into something a user can act on.
455
+ *
456
+ * The SDK reports an outdated CLI as `Qoder CLI process exited with code 42`,
457
+ * which says nothing about the cause: CLI 1.1.81 removed the worker-session
458
+ * handshake the older SDK spoke, and its own log says so
459
+ * (`sdk_worker_removed: … Upgrade to the latest Qoder SDK version, or roll back
460
+ * the CLI`). The only fix available to a user is reinstalling the pair through
461
+ * the bundled helper, so say that instead of echoing the number.
462
+ *
463
+ * @param detail - the error text as the SDK reported it.
464
+ * @param brand - which edition's helper the message should name.
465
+ * @returns the original detail, prefixed with the actionable explanation.
466
+ */
467
+ function cliFailureText(detail, brand) {
468
+ if (!/exit(?:ed)?(?: with)? code 42|sdk_worker_removed/i.test(detail)) return detail;
469
+ const profile = brandProfile(brand);
470
+ const pkg = profile.cliPackages[0];
471
+ const spec = pkg === void 0 ? profile.cliCommands[0] : `${pkg.scope}/${pkg.name}`;
472
+ const required = requiredCliVersion(brand);
473
+ const target = required === void 0 ? spec : `${spec}@${required}`;
474
+ return `本机 ${profile.cliCommands[0]} 与插件使用的 SDK 版本不匹配(CLI 已移除旧版握手,退出码 42)。请在设置页点「一键配置」重新安装配套版本,或手动执行 npm install -g ${target} 后重试。原始信息:${detail}`;
475
+ }
476
+ /**
477
+ * The CLI version the installed SDK expects, read from its runtime manifest.
478
+ *
479
+ * Each SDK release pins one CLI build: the two speak a wire protocol that
480
+ * changes between them, and a mismatch fails every session with a bare exit
481
+ * code. The bundled helper reads the same file, so the page and the helper
482
+ * agree on which build to install.
483
+ *
484
+ * @param brand - which edition's SDK to inspect.
485
+ * @returns the pinned version, or undefined when the manifest is unreadable.
486
+ */
487
+ function requiredCliVersion(brand) {
488
+ try {
489
+ const dir = sdkDir(brandProfile(brand).sdkPackage);
490
+ if (dir === void 0) return void 0;
491
+ const manifest = JSON.parse(readFileSync(path.join(dir, "dist", "runtime-manifest.json"), "utf8"));
492
+ return typeof manifest.qoderCliVersion === "string" && manifest.qoderCliVersion.length > 0 ? manifest.qoderCliVersion : void 0;
493
+ } catch {
494
+ return;
495
+ }
496
+ }
497
+ /**
498
+ * The version of the installed CLI, read from its own package manifest.
499
+ *
500
+ * Read from disk rather than by running `--version`: a settings-page poll must
501
+ * not spawn a process every second, and the npm package always ships a
502
+ * manifest next to its entry. A native build without one answers undefined,
503
+ * which callers treat as "unknown" and never as a mismatch.
504
+ *
505
+ * @param brand - which edition's CLI to inspect.
506
+ * @returns the installed version, or undefined when it cannot be read.
507
+ */
508
+ function installedCliVersion(brand) {
509
+ const cli = resolveQoderCli(brand);
510
+ if (cli === void 0) return void 0;
511
+ for (const candidate of [path.join(path.dirname(cli.path), "package.json"), path.join(path.dirname(path.dirname(cli.path)), "package.json")]) try {
512
+ const manifest = JSON.parse(readFileSync(candidate, "utf8"));
513
+ if (typeof manifest.name !== "string" || !manifest.name.startsWith("@")) continue;
514
+ if (typeof manifest.version === "string" && manifest.version.length > 0) return manifest.version;
515
+ } catch {}
516
+ }
427
517
  /** Paths the CLI may live at, most explicit first. */
428
518
  function candidates(brand, env, suffix, nodePath) {
429
519
  const profile = brandProfile(brand);
@@ -435,8 +525,7 @@ function candidates(brand, env, suffix, nodePath) {
435
525
  if (env.QODERCLI_PATH !== void 0 && !isForeignCliPath(brand, env.QODERCLI_PATH)) push(env.QODERCLI_PATH);
436
526
  for (const root of nodeModulesRoots(env, nodePath)) for (const pkg of profile.cliPackages) {
437
527
  const dir = path.join(root, pkg.scope, pkg.name);
438
- push(path.join(dir, "bundle", `${pkg.name}.js`));
439
- push(path.join(dir, `${pkg.name}.js`));
528
+ for (const entry of packageEntries(dir, pkg.name, suffix)) push(entry);
440
529
  }
441
530
  const sdk = sdkDir(profile.sdkPackage);
442
531
  if (sdk !== void 0) for (const pkg of profile.cliPackages) push(path.join(sdk, "dist", "_bundled", `${pkg.name}${suffix}`));
@@ -444,6 +533,31 @@ function candidates(brand, env, suffix, nodePath) {
444
533
  for (const pkg of profile.cliPackages) push(path.join(home, profile.configDirName, "local", `${pkg.name}${suffix}`));
445
534
  return found;
446
535
  }
536
+ /**
537
+ * Every path one installed npm package can expose as its CLI.
538
+ *
539
+ * `main`/`bin` are read from the package's own manifest rather than guessed:
540
+ * the entry point has changed between CLI releases, and hard-coding only
541
+ * `bundle/<name>.js` reported an installed package as missing whenever it did
542
+ * not match. Unreadable manifests fall back to the conventional entries.
543
+ */
544
+ function packageEntries(dir, name, suffix) {
545
+ const entries = [
546
+ path.join(dir, "bundle", `${name}.js`),
547
+ path.join(dir, `${name}.js`),
548
+ path.join(dir, "bundle", `${name}${suffix}`)
549
+ ];
550
+ try {
551
+ const manifest = JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
552
+ if (typeof manifest.main === "string") entries.push(path.join(dir, manifest.main));
553
+ const bin = manifest.bin;
554
+ if (typeof bin === "string") entries.push(path.join(dir, bin));
555
+ else if (bin !== null && typeof bin === "object") {
556
+ for (const value of Object.values(bin)) if (typeof value === "string") entries.push(path.join(dir, value));
557
+ }
558
+ } catch {}
559
+ return entries;
560
+ }
447
561
  /** `node_modules` roots a global install can land in. */
448
562
  function nodeModulesRoots(env, nodePath) {
449
563
  const roots = [];
@@ -453,7 +567,11 @@ function nodeModulesRoots(env, nodePath) {
453
567
  push(env.NPM_CONFIG_PREFIX === void 0 ? void 0 : path.join(env.NPM_CONFIG_PREFIX, "node_modules"));
454
568
  push(env.APPDATA === void 0 ? void 0 : path.join(env.APPDATA, "npm", "node_modules"));
455
569
  push(path.join(homedir(), ".npm-global", "node_modules"));
456
- if (nodePath !== void 0) push(path.join(path.dirname(path.dirname(nodePath)), "lib", "node_modules"));
570
+ if (nodePath !== void 0) {
571
+ const prefix = path.dirname(nodePath);
572
+ push(path.join(prefix, "node_modules"));
573
+ push(path.join(path.dirname(prefix), "lib", "node_modules"));
574
+ }
457
575
  return roots;
458
576
  }
459
577
  /**
@@ -492,7 +610,9 @@ function resolveNode(lookup) {
492
610
  */
493
611
  function sdkDir(packageName) {
494
612
  try {
495
- return path.dirname(createRequire(import.meta.url).resolve(packageName));
613
+ const entry = createRequire(import.meta.url).resolve(packageName);
614
+ const dir = path.dirname(entry);
615
+ return path.basename(dir) === "dist" ? path.dirname(dir) : dir;
496
616
  } catch {
497
617
  return;
498
618
  }
@@ -664,7 +784,8 @@ var QoderModelCatalog = class {
664
784
  this.failure = void 0;
665
785
  return officialOnly(models);
666
786
  } catch (error) {
667
- this.failure = error instanceof Error ? error.message : String(error);
787
+ const detail = error instanceof Error ? error.message : String(error);
788
+ this.failure = cliFailureText(detail, this.brand);
668
789
  return officialOnly((this.cached ?? sharedSnapshots.get(this.brand))?.models ?? []);
669
790
  }
670
791
  }
@@ -724,7 +845,18 @@ var QoderModelCatalog = class {
724
845
  }
725
846
  });
726
847
  try {
727
- return await withTimeout$2(q.getAvailableModels({ fetchStrategy: "live" }), readLive(this.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS));
848
+ const timeout = readLive(this.fetchTimeoutMs, DEFAULT_FETCH_TIMEOUT_MS);
849
+ const uid = (await withTimeout$2(q.accountInfo(), timeout).catch(() => void 0))?.userId;
850
+ const models = await withTimeout$2(q.getAvailableModels(uid === void 0 ? {} : { uid }), timeout);
851
+ if (models.length > 0) return models;
852
+ for (const strategy of ["cache", "live"]) {
853
+ const fallback = await withTimeout$2(q.getAvailableModels({
854
+ ...uid === void 0 ? {} : { uid },
855
+ fetchStrategy: strategy
856
+ }), timeout).catch(() => []);
857
+ if (fallback.length > 0) return fallback;
858
+ }
859
+ return [];
728
860
  } finally {
729
861
  await q.close().catch(() => void 0);
730
862
  }
@@ -2290,7 +2422,7 @@ var QoderSession = class {
2290
2422
  this.endTurn({
2291
2423
  kind: "error",
2292
2424
  failure: {
2293
- message: `qoder session died: ${String(error)}`,
2425
+ message: `qoder session died: ${cliFailureText(String(error), this.brand)}`,
2294
2426
  code: "TRANSPORT"
2295
2427
  }
2296
2428
  });
@@ -2750,6 +2882,10 @@ var QoderUsage = class {
2750
2882
  * @returns the reading; `error` carries a failed lookup instead of throwing.
2751
2883
  */
2752
2884
  async read(fresh = false) {
2885
+ if (resolveQoderCli(this.brand) === void 0) {
2886
+ this.cached = void 0;
2887
+ return this.missingCli();
2888
+ }
2753
2889
  const ttlMs = readLive(this.ttlMs, DEFAULT_USAGE_CACHE_TTL_MS);
2754
2890
  if (!fresh && this.cached !== void 0 && Date.now() - this.cached.at < ttlMs) return this.cached;
2755
2891
  this.inflight ??= this.fetch().finally(() => {
@@ -2763,11 +2899,21 @@ var QoderUsage = class {
2763
2899
  invalidate() {
2764
2900
  this.cached = void 0;
2765
2901
  }
2902
+ /** The reading for a machine whose CLI is not installed. */
2903
+ missingCli() {
2904
+ const command = brandProfile(this.brand).cliCommands[0];
2905
+ return {
2906
+ at: Date.now(),
2907
+ cliMissing: true,
2908
+ error: `未检测到可用的 ${command},请先安装并登录后再使用此版本。`
2909
+ };
2910
+ }
2766
2911
  async fetch() {
2767
2912
  const at = Date.now();
2768
2913
  try {
2769
2914
  if (foreignCliOverride(this.brand) !== void 0) return {
2770
2915
  at,
2916
+ cliMissing: true,
2771
2917
  error: cliConflictMessage(this.brand)
2772
2918
  };
2773
2919
  const sdk = await loadSdk(this.brand);
@@ -2799,7 +2945,7 @@ var QoderUsage = class {
2799
2945
  const command = brandProfile(this.brand).cliCommands[0];
2800
2946
  return {
2801
2947
  at,
2802
- error: /ENOENT|not found|Cannot find package|未安装国际版 SDK/i.test(detail) ? `未检测到可用的 ${command},请先安装并登录后再读取额度。` : detail
2948
+ error: /ENOENT|not found|Cannot find package|未安装国际版 SDK/i.test(detail) ? `未检测到可用的 ${command},请先安装并登录后再读取额度。` : cliFailureText(detail, this.brand)
2803
2949
  };
2804
2950
  }
2805
2951
  }
@@ -8253,11 +8399,21 @@ function startSetup(brand, mode, onFinish) {
8253
8399
  * @param brand - which edition's run to report.
8254
8400
  */
8255
8401
  function readSetupStatus(brand = "cn") {
8402
+ const installed = resolveQoderCli(brand) !== void 0;
8403
+ const cliVersion = installed ? installedCliVersion(brand) : void 0;
8404
+ const required = requiredCliVersion(brand);
8405
+ const build = {
8406
+ installed,
8407
+ ...cliVersion === void 0 ? {} : { cliVersion },
8408
+ ...required === void 0 ? {} : { requiredCliVersion: required },
8409
+ ...cliVersion === void 0 || required === void 0 ? {} : { versionMismatch: cliVersion !== required }
8410
+ };
8256
8411
  const run = current.get(brand);
8257
8412
  if (run === void 0) return {
8258
8413
  running: false,
8259
8414
  lines: [],
8260
- truncated: false
8415
+ truncated: false,
8416
+ ...build
8261
8417
  };
8262
8418
  const lines = run.pending.trim() === "" ? run.lines : [...run.lines, run.pending.trim()];
8263
8419
  return {
@@ -8269,10 +8425,35 @@ function readSetupStatus(brand = "cn") {
8269
8425
  code: run.code ?? null
8270
8426
  },
8271
8427
  lines,
8272
- truncated: run.truncated
8428
+ truncated: run.truncated,
8429
+ ...build,
8430
+ ...run.cancelled === true ? { cancelled: true } : {}
8273
8431
  };
8274
8432
  }
8275
8433
  /**
8434
+ * Abandon the running helper for one edition.
8435
+ *
8436
+ * `qodercli login` waits for the browser to finish the callback, so closing
8437
+ * that tab left the page polling a process that would never return. Killing
8438
+ * the run turns it into a finished one (`code` null) so the page can offer the
8439
+ * buttons again instead of showing a spinner forever.
8440
+ *
8441
+ * @param brand - which edition's run to stop.
8442
+ * @returns whether a run was actually in flight.
8443
+ */
8444
+ function cancelSetup(brand) {
8445
+ const run = current.get(brand);
8446
+ if (run === void 0 || run.finishedAt !== void 0) return false;
8447
+ run.lines.push("已取消:这次配置被手动终止,可以重新操作。");
8448
+ run.cancelled = true;
8449
+ try {
8450
+ run.child.kill();
8451
+ } catch {}
8452
+ run.finishedAt = Date.now();
8453
+ run.code = null;
8454
+ return true;
8455
+ }
8456
+ /**
8276
8457
  * Abandon the running helper, if any.
8277
8458
  *
8278
8459
  * Called when the plugin is disposed. Killing `cmd.exe` does not reap the CLI it
@@ -8580,8 +8761,13 @@ async function handleApi(req, res, adapters) {
8580
8761
  send(res, 200, readMinimaxSetupStatus());
8581
8762
  return;
8582
8763
  }
8764
+ if (parsed.mode === "cancel") {
8765
+ cancelSetup(postBrand);
8766
+ send(res, 200, readSetupStatus(postBrand));
8767
+ return;
8768
+ }
8583
8769
  if (!isSetupMode(parsed.mode)) {
8584
- send(res, 400, { error: "mode 只接受 configure、login 或 uninstall" });
8770
+ send(res, 400, { error: "mode 只接受 configure、login、uninstall 或 cancel" });
8585
8771
  return;
8586
8772
  }
8587
8773
  const qoder = adapters[postBrand];