dsh-agent-sdk-bridge 1.2.0 → 1.2.2

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
@@ -33,6 +33,12 @@
33
33
  读包自己的 `package.json`(`main`/`bin`),并把 Windows 的 `<node>/node_modules` 与 unix 的
34
34
  `<prefix>/lib/node_modules` 都当作全局根。只猜 `bundle/` 会把已安装的 CLI 判成未安装,
35
35
  页面就一直要你「再装一次」。
36
+ - **退出登录要清凭据并关会话**:Qoder CLI 没有 `logout` 子命令,登录态只保存在加密的
37
+ `~/.qoder-cn/.auth/user`(国际版 `~/.qoder/.auth/user`);`machine_id` 属于机器而不是账号,保留。
38
+ 两个 `setup-*.bat` 的 `--logout` 删除该文件后再跑一次 `status`,确认不再打印 `Username`;
39
+ `POST /setup {mode:'logout'}` 成功后调用 `closeSessions()`,因为热会话里的 CLI 进程在启动时
40
+ 已加载旧凭据,不关掉就会继续以刚退出的账号作答。页面同时清空额度缓存(`resetSignal`),
41
+ 避免旧账号的积分继续显示。
36
42
  - **卸载要清干净**:npm 只删包,会留下空的 `node_modules/@qoder-ai`(或 `@qodercn-ai`)目录和
37
43
  `qodercli.cmd`/`.ps1` 之类 shim,而 CLI 查找和页面的「已安装」徽标读的正是这些。两个
38
44
  `setup-*.bat` 的 `--uninstall` 会在 `npm uninstall -g` 之后删掉 shim 与空 scope 目录,
package/FAQ.md CHANGED
@@ -24,6 +24,11 @@ CLI 查找和页面徽标读的正是它们。现在 `--uninstall` 会在 `npm u
24
24
  scope 目录;页面上的「已安装」也改成每次现查机器,所以卸载后主按钮立刻变回「安装 CLI」,
25
25
  登录 / 卸载按钮只在已安装时出现。
26
26
 
27
+ **想换账号或退出登录?** Qoder 页面在已安装 CLI 时会显示「退出登录」。Qoder CLI 本身没有 `logout`
28
+ 子命令,插件改为删除该版本加密保存的凭据(国内版 `~/.qoder-cn/.auth/user`,国际版
29
+ `~/.qoder/.auth/user`;`machine_id` 保留),并在成功后关闭已打开的会话、清空额度缓存。因此旧账号
30
+ 不会继续作答,旧积分也不会挂在卡片上;CLI 保持安装,点「重新登录」即可换号。
31
+
27
32
  **点「重新登录」后关掉了浏览器,页面就一直转圈?** 已修复,并新增「取消」。`qodercli login`
28
33
  会一直等浏览器回调,关掉标签页就没有返回值。现在运行中会出现「取消」按钮:点它会终止这次
29
34
  脚本、把状态标记为已取消,按钮立刻恢复,可以重新登录。
package/README.md CHANGED
@@ -93,8 +93,8 @@ npm install -g @qoder-ai/qodercli && qodercli login # 国际版
93
93
  剩余积分,以及 Token Plan 的 5 小时 / 每周剩余百分比、重置时间与进度条(与官网控制台同源)。
94
94
  - **模型清单**:来自账号实时目录,逐个启用 / 关闭、指定上下文窗口;倍率取自上游报价。
95
95
  - **高级设置**:并发会话数、目录缓存、超时、默认思考档位、模型别名、分组名称等,可折叠。
96
- - **CLI 分组**:Qoder 页面有一键配置 / 重新登录 / 卸载 CLI;MiniMax Code 页面有安装 / 更新 /
97
- 卸载 CLI(卸载前确认,保留登录凭证),均附实时输出。
96
+ - **CLI 分组**:Qoder 页面有一键配置 / 重新登录 / 退出登录 / 卸载 CLI;MiniMax Code 页面有安装 /
97
+ 更新 / 卸载 CLI(卸载前确认,保留登录凭证),均附实时输出。
98
98
  - 再次打开页面时**先显示上次快照**,模型与账户在后台更新,不再每次都停在「正在读取」。
99
99
 
100
100
  每个 provider 只注册一条路由(`qoder-cn` / `qoder-intl` / `codebuddy` / `minimax-acp`),只服务
package/client.js CHANGED
@@ -91,6 +91,10 @@ window.__ModuleLoader__.load({
91
91
  cliCancel: '取消',
92
92
  cliCancelling: '正在取消…',
93
93
  cliCancelled: '已取消,可以重新操作',
94
+ cliLogout: '退出登录',
95
+ cliLogoutConfirm: '确定要退出当前 Qoder 账号吗?退出后会关闭已打开的会话并清空额度,需要重新登录才能继续使用;CLI 本身不会被卸载。',
96
+ cliLoggingOut: '正在退出登录…',
97
+ cliLogoutOk: '已退出登录',
94
98
  cliVersionMismatch: 'CLI 版本与插件不匹配:本机',
95
99
  cliVersionMismatchTail: ',插件需要',
96
100
  intlNav: 'Qoder 国际版',
@@ -121,6 +125,8 @@ window.__ModuleLoader__.load({
121
125
  usageUnknownPlan: '未知套餐',
122
126
  usageStale: '显示上次读数,刷新失败',
123
127
  usageCliMissing: '未检测到本机 CLI,安装并登录后才会显示额度。',
128
+ usageSignedOut: '已退出登录,重新登录后显示额度。',
129
+ modelsSignedOut: '已退出登录,重新登录后才会显示模型。',
124
130
  pluginOptionsTitle: '启用的版本',
125
131
  pluginOptionsHint: '关闭后,对应设置页、模型列表与模型分组都会移除;已保存的模型选择保留,重新打开即可恢复。',
126
132
  pluginOptionsOn: '显示中',
@@ -288,6 +294,10 @@ window.__ModuleLoader__.load({
288
294
  cliCancel: 'Cancel',
289
295
  cliCancelling: 'Cancelling…',
290
296
  cliCancelled: 'Cancelled — you can start again',
297
+ cliLogout: 'Sign out',
298
+ cliLogoutConfirm: 'Sign out of the current Qoder account? Open sessions will be closed and quota cleared; you will need to sign in again. The CLI itself stays installed.',
299
+ cliLoggingOut: 'Signing out…',
300
+ cliLogoutOk: 'Signed out',
291
301
  cliVersionMismatch: 'CLI version does not match the plugin: this machine has',
292
302
  cliVersionMismatchTail: 'but the plugin needs',
293
303
  intlNav: 'Qoder International',
@@ -318,6 +328,8 @@ window.__ModuleLoader__.load({
318
328
  usageUnknownPlan: 'Unknown plan',
319
329
  usageStale: 'Showing the last reading; refresh failed',
320
330
  usageCliMissing: 'This machine has no CLI for this edition; quota appears after it is installed and signed in.',
331
+ usageSignedOut: 'Signed out. Sign in again to see quota.',
332
+ modelsSignedOut: 'Signed out. Sign in again to see the models.',
321
333
  pluginOptionsTitle: 'Enabled editions',
322
334
  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.',
323
335
  pluginOptionsOn: 'Shown',
@@ -890,13 +902,16 @@ window.__ModuleLoader__.load({
890
902
  * upgrade/usage links. It is fetched from the host (which asks the CLI), not
891
903
  * from the provider directly, because only the CLI holds a usable token.
892
904
  */
893
- function UsageCard({ t, brand, refreshSignal }) {
905
+ function UsageCard({ t, brand, refreshSignal, resetSignal }) {
894
906
  const [snapshot, setSnapshot] = useState(() => readCache(brand.id, 'usage'))
895
907
  const [failure, setFailure] = useState(undefined)
896
908
  const [busy, setBusy] = useState(false)
897
909
  /** The CLI is not installed: show that, and never any cached numbers. */
898
910
  const [missing, setMissing] = useState(false)
911
+ /** The user just signed out from this page: no reading is expected. */
912
+ const [signedOut, setSignedOut] = useState(false)
899
913
  const ticket = useRef(0)
914
+ const lastReset = useRef(resetSignal)
900
915
 
901
916
  const load = useCallback(async (fresh = false) => {
902
917
  const mine = ++ticket.current
@@ -913,6 +928,7 @@ window.__ModuleLoader__.load({
913
928
  clearCache(brand.id, 'usage')
914
929
  setSnapshot(undefined)
915
930
  setMissing(true)
931
+ setSignedOut(false)
916
932
  setFailure(String(payload.error ?? t('usageCliMissing')))
917
933
  return
918
934
  }
@@ -924,6 +940,7 @@ window.__ModuleLoader__.load({
924
940
  return
925
941
  }
926
942
  setMissing(false)
943
+ setSignedOut(false)
927
944
  setSnapshot(payload)
928
945
  writeCache(brand.id, 'usage', payload)
929
946
  } catch (err) {
@@ -938,6 +955,23 @@ window.__ModuleLoader__.load({
938
955
  // make the cached account reading describe a machine state that is gone.
939
956
  useEffect(() => { void load() }, [load, refreshSignal])
940
957
 
958
+ // A sign-out makes the stored reading describe an account that is no
959
+ // longer signed in — the same lie the uninstall case told. `resetSignal`
960
+ // changes only for that action, so an ordinary refresh keeps its
961
+ // stale-while-revalidate behaviour.
962
+ useEffect(() => {
963
+ if (lastReset.current === resetSignal) return
964
+ lastReset.current = resetSignal
965
+ clearCache(brand.id, 'usage')
966
+ setSnapshot(undefined)
967
+ setMissing(false)
968
+ setFailure(undefined)
969
+ // Do not fetch: the CLI has just been signed out, so a read would only
970
+ // produce an authentication error that looks like a malfunction. The
971
+ // refresh button and the next sign-in both still work.
972
+ setSignedOut(true)
973
+ }, [resetSignal, brand.id])
974
+
941
975
  const usage = snapshot?.usage
942
976
  const account = snapshot?.account
943
977
  const error = failure ?? (snapshot?.usage === undefined && snapshot?.error !== undefined ? String(snapshot.error) : undefined)
@@ -965,9 +999,11 @@ window.__ModuleLoader__.load({
965
999
  // state any more.
966
1000
  missing
967
1001
  ? 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}`),
1002
+ : signedOut
1003
+ ? h('div', { style: css.note }, t('usageSignedOut'))
1004
+ : error === undefined
1005
+ ? h('div', { style: css.note }, t('usageLoading'))
1006
+ : h('div', { style: css.err }, `${t('usageUnavailable')}:${error}`),
971
1007
  error === undefined
972
1008
  ? null
973
1009
  : h('div', { style: css.bar },
@@ -1789,6 +1825,9 @@ window.__ModuleLoader__.load({
1789
1825
  const [onlyEnabled, setOnlyEnabled] = useState(false)
1790
1826
  const [showAdvanced, setShowAdvanced] = useState(false)
1791
1827
  const [usageTick, setUsageTick] = useState(0)
1828
+ // Bumped only by a successful sign-out: the quota card must drop its
1829
+ // stored account rather than label it "last reading".
1830
+ const [usageReset, setUsageReset] = useState(0)
1792
1831
  const ticket = useRef(0)
1793
1832
  /** Separate from `ticket`: `load()` bumps that one, so sharing it would
1794
1833
  * make every write look stale the moment its own refresh landed. */
@@ -2168,9 +2207,21 @@ window.__ModuleLoader__.load({
2168
2207
  // and the host has already dropped its cached answers for that case.
2169
2208
  useEffect(() => {
2170
2209
  if (setupCode !== 0) return
2210
+ if (setup?.mode === 'logout') {
2211
+ // Signing out invalidates the account itself, not just its freshness:
2212
+ // the stored catalog and quota were read through credentials that no
2213
+ // longer exist. Drop both instead of refetching — a read now would
2214
+ // only fail with an authentication error that looks like a fault.
2215
+ clearCache(brand.id, modelsKind)
2216
+ setModels([])
2217
+ setCatalogNotice(t('modelsSignedOut'))
2218
+ setSignedIn(regional ? false : undefined)
2219
+ setUsageReset(value => value + 1)
2220
+ return
2221
+ }
2171
2222
  void load(true)
2172
2223
  setUsageTick(value => value + 1)
2173
- }, [setupCode, setupFinishedAt, load])
2224
+ }, [setupCode, setupFinishedAt, setup?.mode, load, brand.id, modelsKind, regional, t])
2174
2225
 
2175
2226
  /** Ask before running the destructive CLI action. */
2176
2227
  const uninstallCli = useCallback(() => {
@@ -2179,6 +2230,13 @@ window.__ModuleLoader__.load({
2179
2230
  void startCliSetup('uninstall')
2180
2231
  }, [startCliSetup, t])
2181
2232
 
2233
+ /** Signing out is reversible, but it clears the account and quota. */
2234
+ const logoutCli = useCallback(() => {
2235
+ if (typeof window.confirm !== 'function') return
2236
+ if (!window.confirm(t('cliLogoutConfirm'))) return
2237
+ void startCliSetup('logout')
2238
+ }, [startCliSetup, t])
2239
+
2182
2240
  useEffect(() => {
2183
2241
  const node = logRef.current
2184
2242
  if (node !== null) node.scrollTop = node.scrollHeight
@@ -2327,7 +2385,7 @@ window.__ModuleLoader__.load({
2327
2385
  h('p', { style: css.intro }, t(brand.introKey)),
2328
2386
  regional
2329
2387
  ? authCard
2330
- : h(UsageCard, { t, brand, refreshSignal: usageTick }),
2388
+ : h(UsageCard, { t, brand, refreshSignal: usageTick, resetSignal: usageReset }),
2331
2389
 
2332
2390
  // Search row: the field grows, the checkbox sits beside it.
2333
2391
  h('div', { style: css.bar },
@@ -2391,6 +2449,9 @@ window.__ModuleLoader__.load({
2391
2449
  cliInstalled
2392
2450
  ? h('button', { style: css.btn, disabled: setupRunning, onClick: () => void startCliSetup('login') }, t('cliLogin'))
2393
2451
  : null,
2452
+ cliInstalled
2453
+ ? h('button', { style: css.btn, disabled: setupRunning, onClick: logoutCli }, t('cliLogout'))
2454
+ : null,
2394
2455
  cliInstalled
2395
2456
  ? h('button', { style: { ...css.btn, ...css.btnAlert }, disabled: setupRunning, onClick: uninstallCli }, t('cliUninstall'))
2396
2457
  : null,
@@ -2407,13 +2468,17 @@ window.__ModuleLoader__.load({
2407
2468
  ? h('button', { style: css.btn, onClick: () => setLogOpen(value => !value) }, logOpen ? t('cliHideLog') : t('cliShowLog'))
2408
2469
  : null,
2409
2470
  h('span', { style: css.count }, setupRunning
2410
- ? (setup?.mode === 'uninstall' ? t('cliUninstalling') : t('cliRunning'))
2471
+ ? (setup?.mode === 'uninstall'
2472
+ ? t('cliUninstalling')
2473
+ : setup?.mode === 'logout' ? t('cliLoggingOut') : t('cliRunning'))
2411
2474
  : setupError !== undefined
2412
2475
  ? setupError
2413
2476
  : setupCancelled
2414
2477
  ? t('cliCancelled')
2415
2478
  : setupCode === 0
2416
- ? (setup?.mode === 'uninstall' ? t('cliUninstallOk') : t('cliExitOk'))
2479
+ ? (setup?.mode === 'uninstall'
2480
+ ? t('cliUninstallOk')
2481
+ : setup?.mode === 'logout' ? t('cliLogoutOk') : t('cliExitOk'))
2417
2482
  : setupCode === undefined || setupCode === null
2418
2483
  ? ''
2419
2484
  : `${t('cliExitFail')} ${setupCode}`),
package/lib/index.js CHANGED
@@ -4,16 +4,15 @@ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSyn
4
4
  import { homedir, tmpdir } from "node:os";
5
5
  import * as path from "node:path";
6
6
  import { delimiter, dirname, join } from "node:path";
7
- import * as cnSdk from "@qodercn-ai/qodercn-agent-sdk";
8
- import { createSdkMcpServer, qodercliAuth } from "@qodercn-ai/qodercn-agent-sdk";
7
+ import { fileURLToPath, pathToFileURL } from "node:url";
9
8
  import { createHash, randomBytes, randomUUID } from "node:crypto";
9
+ import { createSdkMcpServer } from "@qodercn-ai/qodercn-agent-sdk";
10
10
  import { z } from "zod";
11
11
  import { spawn } from "node:child_process";
12
12
  import { createServer } from "node:http";
13
13
  import { Readable, Writable } from "node:stream";
14
14
  import { ClientSideConnection, PROTOCOL_VERSION, ndJsonStream } from "@agentclientprotocol/sdk";
15
15
  import { TextDecoder } from "node:util";
16
- import { fileURLToPath } from "node:url";
17
16
  import { isVolatile } from "@deepseek-ai/cosmokit";
18
17
  import z$1 from "@deepseek-ai/schemastery";
19
18
  //#region src/brand.ts
@@ -465,6 +464,7 @@ function cliConflictMessage(brand) {
465
464
  * @returns the original detail, prefixed with the actionable explanation.
466
465
  */
467
466
  function cliFailureText(detail, brand) {
467
+ if (/DaemonConfigurationConflict|Global daemon is already initialized with different options/i.test(detail)) return `本机 ${brandProfile(brand).cliCommands[0]} 的运行配置在本次会话期间发生了变化,SDK 的本地守护进程仍按旧配置运行。插件已重置这部分运行时,请重试一次;若仍失败,重启 DSH Web。原始信息:${detail}`;
468
468
  if (!/exit(?:ed)?(?: with)? code 42|sdk_worker_removed/i.test(detail)) return detail;
469
469
  const profile = brandProfile(brand);
470
470
  const pkg = profile.cliPackages[0];
@@ -645,53 +645,187 @@ function isWorkerRuntime(entry) {
645
645
  *
646
646
  * The Qoder editions publish the same API under different scopes, so the rest
647
647
  * of the plugin imports this module instead of a package name. The CN SDK is a
648
- * real dependency and is loaded statically; the international one is optional
649
- * at runtime — a deployment that only has a CN account may not have it
650
- * installed — so it is imported on demand and its absence is reported to the
651
- * settings page as a plain error instead of failing the plugin's mount.
648
+ * real dependency and is loaded eagerly; the international one is optional at
649
+ * runtime — a deployment that only has a CN account may not have it installed —
650
+ * so it is imported on demand and its absence is reported to the settings page
651
+ * as a plain error instead of failing the plugin's mount.
652
652
  *
653
653
  * CodeBuddy has its own, unrelated API and is loaded dynamically for the same
654
654
  * reason: an account may never use it, and its package carries a large CLI.
655
655
  *
656
- * The Qoder module is typed against the CN package because the two are
657
- * API-compatible: every Qoder call site is shared, and the only thing that
658
- * changes is which process the protocol is spoken to.
656
+ * ## Why modules are reloaded
657
+ *
658
+ * Every Qoder SDK routes all queries through one **process-wide daemon** that
659
+ * is initialized with the first query's launch configuration (CLI path,
660
+ * interpreter, environment, proxy) and then refuses any different one for the
661
+ * life of the process:
662
+ *
663
+ * DaemonConfigurationConflictError:
664
+ * Global daemon is already initialized with different options
665
+ *
666
+ * The host is long-lived, so its configuration is not: a CLI can be
667
+ * reinstalled, an edition can appear, an installer can change the machine
668
+ * environment. When that happens the ready daemon no longer matches and every
669
+ * later query fails until the process restarts — a state the settings page
670
+ * cannot recover from on its own.
671
+ *
672
+ * So the module tracks the configuration signature it loaded under and takes a
673
+ * fresh instance whenever the signature changes; {@link resetSdk} does the same
674
+ * after a conflict is observed. A new instance has an empty daemon registry, so
675
+ * it initializes against the current configuration instead of arguing with the
676
+ * old one.
659
677
  *
660
678
  * @module dsh-agent-sdk-bridge/sdk
661
679
  */
662
- let globalSdk;
680
+ const generations = /* @__PURE__ */ new Map();
681
+ /** Brands whose next load must take a fresh instance even if the signature matches. */
682
+ const forced = /* @__PURE__ */ new Set();
683
+ let counter = 0;
663
684
  let codeBuddySdk;
685
+ const require = createRequire(import.meta.url);
664
686
  /**
665
- * Load the SDK for one Qoder edition.
687
+ * The launch configuration a Qoder query would use, as a comparable string.
666
688
  *
667
- * @param brand - which edition's SDK to load.
668
- * @returns the SDK module.
689
+ * Mirrors the fields the SDK's own daemon compares before reusing itself. The
690
+ * environment is included because the SDK hands it to the CLI verbatim, and a
691
+ * difference there is enough to make the daemon reject a query.
692
+ *
693
+ * @param brand - which edition's configuration to describe.
694
+ * @returns a stable string that changes exactly when the configuration does.
669
695
  */
670
- function loadSdk(brand) {
671
- if (brand === "cn") return Promise.resolve(cnSdk);
672
- globalSdk ??= importGlobalSdk();
673
- return globalSdk;
696
+ function configurationSignature(brand) {
697
+ const options = qoderCliOptions(brand);
698
+ const env = Object.entries(options.env ?? {}).filter(([, value]) => value !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
699
+ return JSON.stringify({
700
+ path: options.pathToQoderCLIExecutable ?? null,
701
+ executable: options.executable ?? null,
702
+ env
703
+ });
674
704
  }
675
705
  /**
676
- * Import the international SDK by a variable specifier.
706
+ * Import one edition's SDK.
677
707
  *
678
- * A literal specifier would make TypeScript and the bundler require the package
679
- * at build time, which is exactly what an optional edition must not do.
708
+ * A fresh instance is the same file imported under a unique URL: the module's
709
+ * top-level daemon state is per instance, while the implementation is shared by
710
+ * the module loader as usual.
711
+ *
712
+ * @param brand - which edition to load.
713
+ * @param fresh - ignore the already-loaded instance and take a new one.
680
714
  */
681
- async function importGlobalSdk() {
682
- const specifier = brandProfile("global").sdkPackage;
715
+ async function importSdk(brand, fresh) {
716
+ const specifier = brandProfile(brand).sdkPackage;
683
717
  try {
684
- return await import(
718
+ if (!fresh) return await import(
685
719
  /* @vite-ignore */
686
720
  specifier
721
+ );
722
+ const entry = pathToFileURL(require.resolve(specifier)).href;
723
+ counter += 1;
724
+ return await import(
725
+ /* @vite-ignore */
726
+ `${entry}?generation=${counter}`
687
727
  );
688
728
  } catch (error) {
689
- globalSdk = void 0;
729
+ generations.delete(brand);
730
+ forced.delete(brand);
731
+ if (brand === "cn") throw error;
690
732
  const detail = error instanceof Error ? error.message : String(error);
691
733
  throw new Error(`未安装国际版 SDK(${specifier}):${detail}`);
692
734
  }
693
735
  }
694
736
  /**
737
+ * Load the SDK for one Qoder edition, under its current configuration.
738
+ *
739
+ * @param brand - which edition's SDK to load.
740
+ * @returns the SDK module.
741
+ */
742
+ function loadSdk(brand) {
743
+ const signature = configurationSignature(brand);
744
+ const current = generations.get(brand);
745
+ if (current !== void 0 && current.signature === signature && !forced.has(brand)) return current.module;
746
+ const module = importSdk(brand, current !== void 0 || forced.delete(brand));
747
+ const generation = {
748
+ signature,
749
+ module
750
+ };
751
+ generations.set(brand, generation);
752
+ module.catch(() => {
753
+ if (generations.get(brand) === generation) generations.delete(brand);
754
+ });
755
+ return module;
756
+ }
757
+ /**
758
+ * Drop the loaded instance so the next {@link loadSdk} starts a new daemon.
759
+ *
760
+ * @param brand - which edition to reset.
761
+ */
762
+ function resetSdk(brand) {
763
+ generations.delete(brand);
764
+ forced.add(brand);
765
+ }
766
+ /**
767
+ * Whether an error is the SDK's daemon refusing a different configuration.
768
+ *
769
+ * @param error - whatever a query threw.
770
+ */
771
+ function isDaemonConflict(error) {
772
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
773
+ return text.includes("DaemonConfigurationConflictError") || text.includes("Global daemon is already initialized with different options");
774
+ }
775
+ /**
776
+ * Run one idempotent SDK operation, recovering from a daemon conflict once.
777
+ *
778
+ * A conflict means the daemon was initialized under a configuration that no
779
+ * longer applies. A fresh module instance starts an empty daemon with the
780
+ * current one, so the retry succeeds without a restart. Only use this for
781
+ * operations that can be repeated without side effects (reads), never for a
782
+ * turn that may already have emitted output.
783
+ *
784
+ * @param brand - which edition to query.
785
+ * @param run - the operation, given the module to use.
786
+ */
787
+ async function withSdk(brand, run) {
788
+ try {
789
+ return await run(await loadSdk(brand));
790
+ } catch (error) {
791
+ if (!isDaemonConflict(error)) throw error;
792
+ resetSdk(brand);
793
+ return await run(await loadSdk(brand));
794
+ }
795
+ }
796
+ /**
797
+ * Open one cheap control query so a stale daemon is discovered before a turn
798
+ * starts streaming.
799
+ *
800
+ * A turn cannot be retried once it has emitted output, so the session path has
801
+ * to find out about a configuration conflict first. `getUsageInfo` is a
802
+ * control request: it initializes the daemon and reads the account without
803
+ * running a model turn.
804
+ *
805
+ * @param brand - which edition to probe.
806
+ */
807
+ async function probeDaemon(brand) {
808
+ const sdk = await loadSdk(brand);
809
+ const q = sdk.query({
810
+ prompt: (async function* () {
811
+ await new Promise(() => {});
812
+ })(),
813
+ options: {
814
+ ...qoderCliOptions(brand),
815
+ auth: sdk.qodercliAuth(),
816
+ tools: [],
817
+ allowedTools: [],
818
+ settingSources: [],
819
+ maxTurns: 1
820
+ }
821
+ });
822
+ try {
823
+ await q.getUsageInfo();
824
+ } finally {
825
+ await q.close().catch(() => void 0);
826
+ }
827
+ }
828
+ /**
695
829
  * Load the CodeBuddy Agent SDK.
696
830
  *
697
831
  * Kept lazy because the package ships its own ~200 MB CLI and is useless to a
@@ -832,7 +966,10 @@ var QoderModelCatalog = class {
832
966
  }
833
967
  async fetch() {
834
968
  if (foreignCliOverride(this.brand) !== void 0) throw new Error(cliConflictMessage(this.brand));
835
- const sdk = await loadSdk(this.brand);
969
+ if (resolveQoderCli(this.brand) === void 0) throw new Error(cliConflictMessage(this.brand));
970
+ return withSdk(this.brand, (sdk) => this.read(sdk));
971
+ }
972
+ async read(sdk) {
836
973
  const q = sdk.query({
837
974
  prompt: inertInput$2(),
838
975
  options: {
@@ -2057,11 +2194,18 @@ var QoderSession = class {
2057
2194
  async ensureStarted() {
2058
2195
  if (this.q !== null) return this.q;
2059
2196
  if (foreignCliOverride(this.brand) !== void 0) throw new Error(cliConflictMessage(this.brand));
2060
- const q = (await loadSdk(this.brand)).query({
2197
+ if (resolveQoderCli(this.brand) === void 0) throw new Error(cliConflictMessage(this.brand));
2198
+ try {
2199
+ await probeDaemon(this.brand);
2200
+ } catch (error) {
2201
+ if (isDaemonConflict(error)) resetSdk(this.brand);
2202
+ }
2203
+ const sdk = await loadSdk(this.brand);
2204
+ const q = sdk.query({
2061
2205
  prompt: this.channel,
2062
2206
  options: {
2063
2207
  ...qoderCliOptions(this.brand),
2064
- auth: qodercliAuth(),
2208
+ auth: sdk.qodercliAuth(),
2065
2209
  tools: [],
2066
2210
  allowedTools: [],
2067
2211
  canUseTool: this.canUseTool,
@@ -2419,6 +2563,11 @@ var QoderSession = class {
2419
2563
  }
2420
2564
  });
2421
2565
  } catch (error) {
2566
+ if (isDaemonConflict(error)) {
2567
+ resetSdk(this.brand);
2568
+ this.q = null;
2569
+ q.close().catch(() => void 0);
2570
+ }
2422
2571
  this.endTurn({
2423
2572
  kind: "error",
2424
2573
  failure: {
@@ -2738,11 +2887,13 @@ var QoderSessionManager = class {
2738
2887
  const systemPrompt = options.system;
2739
2888
  const brand = this.runtime.brand ?? "cn";
2740
2889
  if (foreignCliOverride(brand) !== void 0) throw new Error(cliConflictMessage(brand));
2741
- const q = (await loadSdk(brand)).query({
2890
+ if (resolveQoderCli(brand) === void 0) throw new Error(cliConflictMessage(brand));
2891
+ const sdk = await loadSdk(brand);
2892
+ const q = sdk.query({
2742
2893
  prompt,
2743
2894
  options: {
2744
2895
  ...qoderCliOptions(brand),
2745
- auth: qodercliAuth(),
2896
+ auth: sdk.qodercliAuth(),
2746
2897
  tools: [],
2747
2898
  allowedTools: [],
2748
2899
  canUseTool: gateTools,
@@ -2775,7 +2926,10 @@ var QoderSessionManager = class {
2775
2926
  }
2776
2927
  }
2777
2928
  } catch (error) {
2778
- if (signal?.aborted !== true) throw error;
2929
+ if (signal?.aborted !== true) {
2930
+ if (isDaemonConflict(error)) resetSdk(brand);
2931
+ throw error;
2932
+ }
2779
2933
  }
2780
2934
  if (signal?.aborted === true) {
2781
2935
  yield {
@@ -2916,30 +3070,7 @@ var QoderUsage = class {
2916
3070
  cliMissing: true,
2917
3071
  error: cliConflictMessage(this.brand)
2918
3072
  };
2919
- const sdk = await loadSdk(this.brand);
2920
- const timeoutMs = readLive(this.timeoutMs, DEFAULT_USAGE_TIMEOUT_MS);
2921
- const q = sdk.query({
2922
- prompt: inertInput$1(),
2923
- options: {
2924
- ...qoderCliOptions(this.brand),
2925
- auth: sdk.qodercliAuth(),
2926
- tools: [],
2927
- allowedTools: [],
2928
- settingSources: [],
2929
- maxTurns: 1
2930
- }
2931
- });
2932
- try {
2933
- const usage = await withTimeout$2(q.getUsageInfo(), timeoutMs);
2934
- const account = await withTimeout$2(q.accountInfo(), timeoutMs).catch(() => void 0);
2935
- return {
2936
- at,
2937
- ...usage === null || usage === void 0 ? { error: "CLI 未返回额度信息" } : { usage },
2938
- ...account === void 0 ? {} : { account }
2939
- };
2940
- } finally {
2941
- await q.close().catch(() => void 0);
2942
- }
3073
+ return await withSdk(this.brand, (sdk) => this.readSnapshot(sdk, at));
2943
3074
  } catch (error) {
2944
3075
  const detail = error instanceof Error ? error.message : String(error);
2945
3076
  const command = brandProfile(this.brand).cliCommands[0];
@@ -2949,6 +3080,31 @@ var QoderUsage = class {
2949
3080
  };
2950
3081
  }
2951
3082
  }
3083
+ async readSnapshot(sdk, at) {
3084
+ const timeoutMs = readLive(this.timeoutMs, DEFAULT_USAGE_TIMEOUT_MS);
3085
+ const q = sdk.query({
3086
+ prompt: inertInput$1(),
3087
+ options: {
3088
+ ...qoderCliOptions(this.brand),
3089
+ auth: sdk.qodercliAuth(),
3090
+ tools: [],
3091
+ allowedTools: [],
3092
+ settingSources: [],
3093
+ maxTurns: 1
3094
+ }
3095
+ });
3096
+ try {
3097
+ const usage = await withTimeout$2(q.getUsageInfo(), timeoutMs);
3098
+ const account = await withTimeout$2(q.accountInfo(), timeoutMs).catch(() => void 0);
3099
+ return {
3100
+ at,
3101
+ ...usage === null || usage === void 0 ? { error: "CLI 未返回额度信息" } : { usage },
3102
+ ...account === void 0 ? {} : { account }
3103
+ };
3104
+ } finally {
3105
+ await q.close().catch(() => void 0);
3106
+ }
3107
+ }
2952
3108
  };
2953
3109
  //#endregion
2954
3110
  //#region src/adapter.ts
@@ -3501,6 +3657,17 @@ var QoderAdapter = class extends LlmAdapter {
3501
3657
  }
3502
3658
  return pixels === 0 ? content.map((block) => block.type === "text" ? block.text : "").join("\n\n") : content;
3503
3659
  }
3660
+ /**
3661
+ * Drop every warm inner session without unloading the plugin.
3662
+ *
3663
+ * Signing out has to invalidate them: each holds a CLI process that already
3664
+ * loaded its credentials, so it would keep answering as the account that was
3665
+ * just signed out. The next turn starts a fresh process, which then reports
3666
+ * the signed-out state honestly.
3667
+ */
3668
+ closeSessions() {
3669
+ this.sessions.closeAll();
3670
+ }
3504
3671
  /** Tear down every warm inner session (plugin dispose). */
3505
3672
  close() {
3506
3673
  this.sessions.closeAll();
@@ -8277,11 +8444,12 @@ function scriptNameOf(brand) {
8277
8444
  const FLAGS = {
8278
8445
  configure: "--gui",
8279
8446
  login: "--login",
8447
+ logout: "--logout",
8280
8448
  uninstall: "--uninstall"
8281
8449
  };
8282
8450
  /** Whether a value is one of the modes the page may request. */
8283
8451
  function isSetupMode(value) {
8284
- return value === "configure" || value === "login" || value === "uninstall";
8452
+ return value === "configure" || value === "login" || value === "logout" || value === "uninstall";
8285
8453
  }
8286
8454
  /** Cap on kept output, so a chatty `npm install` cannot grow without bound. */
8287
8455
  const MAX_LINES = 400;
@@ -8335,7 +8503,7 @@ function startSetup(brand, mode, onFinish) {
8335
8503
  return {
8336
8504
  started: false,
8337
8505
  reason: "unsupported",
8338
- error: `一键${mode === "uninstall" ? "卸载" : "配置"}只支持 Windows,请在 CLI 所在机器上手动处理 ${command}。`
8506
+ error: `一键${mode === "uninstall" ? "卸载" : mode === "logout" ? "退出登录" : mode === "login" ? "重新登录" : "配置"}只支持 Windows,请在 CLI 所在机器上手动处理 ${command}。`
8339
8507
  };
8340
8508
  }
8341
8509
  const script = setupScriptPath(brand);
@@ -8767,15 +8935,16 @@ async function handleApi(req, res, adapters) {
8767
8935
  return;
8768
8936
  }
8769
8937
  if (!isSetupMode(parsed.mode)) {
8770
- send(res, 400, { error: "mode 只接受 configure、login、uninstall 或 cancel" });
8938
+ send(res, 400, { error: "mode 只接受 configure、login、logout、uninstall 或 cancel" });
8771
8939
  return;
8772
8940
  }
8773
8941
  const qoder = adapters[postBrand];
8774
- const result = startSetup(postBrand, parsed.mode, (code) => {
8775
- if (code === 0) {
8776
- qoder.invalidateCatalog();
8777
- qoder.invalidateUsage();
8778
- }
8942
+ const mode = parsed.mode;
8943
+ const result = startSetup(postBrand, mode, (code) => {
8944
+ if (code !== 0) return;
8945
+ qoder.invalidateCatalog();
8946
+ qoder.invalidateUsage();
8947
+ if (mode === "logout") qoder.closeSessions();
8779
8948
  });
8780
8949
  if (!result.started) {
8781
8950
  send(res, result.reason === "busy" ? 409 : result.reason === "unsupported" ? 501 : 500, { error: result.error });