dsh-agent-sdk-bridge 1.2.1 → 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/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.
707
+ *
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.
677
711
  *
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.
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
@@ -67,6 +67,7 @@ export declare class QoderModelCatalog {
67
67
  /** dsh catalog entries: the enabled live list, or the static fallback. */
68
68
  models(): Promise<readonly QoderCatalogModel[]>;
69
69
  private fetch;
70
+ private read;
70
71
  }
71
72
  /**
72
73
  * The credit multiplier upstream quotes for one model.
@@ -3,17 +3,35 @@
3
3
  *
4
4
  * The Qoder editions publish the same API under different scopes, so the rest
5
5
  * of the plugin imports this module instead of a package name. The CN SDK is a
6
- * real dependency and is loaded statically; the international one is optional
7
- * at runtime — a deployment that only has a CN account may not have it
8
- * installed — so it is imported on demand and its absence is reported to the
9
- * settings page as a plain error instead of failing the plugin's mount.
6
+ * real dependency and is loaded eagerly; the international one is optional at
7
+ * runtime — a deployment that only has a CN account may not have it installed —
8
+ * so it is imported on demand and its absence is reported to the settings page
9
+ * as a plain error instead of failing the plugin's mount.
10
10
  *
11
11
  * CodeBuddy has its own, unrelated API and is loaded dynamically for the same
12
12
  * reason: an account may never use it, and its package carries a large CLI.
13
13
  *
14
- * The Qoder module is typed against the CN package because the two are
15
- * API-compatible: every Qoder call site is shared, and the only thing that
16
- * changes is which process the protocol is spoken to.
14
+ * ## Why modules are reloaded
15
+ *
16
+ * Every Qoder SDK routes all queries through one **process-wide daemon** that
17
+ * is initialized with the first query's launch configuration (CLI path,
18
+ * interpreter, environment, proxy) and then refuses any different one for the
19
+ * life of the process:
20
+ *
21
+ * DaemonConfigurationConflictError:
22
+ * Global daemon is already initialized with different options
23
+ *
24
+ * The host is long-lived, so its configuration is not: a CLI can be
25
+ * reinstalled, an edition can appear, an installer can change the machine
26
+ * environment. When that happens the ready daemon no longer matches and every
27
+ * later query fails until the process restarts — a state the settings page
28
+ * cannot recover from on its own.
29
+ *
30
+ * So the module tracks the configuration signature it loaded under and takes a
31
+ * fresh instance whenever the signature changes; {@link resetSdk} does the same
32
+ * after a conflict is observed. A new instance has an empty daemon registry, so
33
+ * it initializes against the current configuration instead of arguing with the
34
+ * old one.
17
35
  *
18
36
  * @module dsh-agent-sdk-bridge/sdk
19
37
  */
@@ -26,12 +44,60 @@ export type QoderSdkModule = typeof QoderSdk;
26
44
  /** The CodeBuddy SDK module, typed from its declarations. */
27
45
  export type CodeBuddySdkModule = typeof CodeBuddySdk;
28
46
  /**
29
- * Load the SDK for one Qoder edition.
47
+ * The launch configuration a Qoder query would use, as a comparable string.
48
+ *
49
+ * Mirrors the fields the SDK's own daemon compares before reusing itself. The
50
+ * environment is included because the SDK hands it to the CLI verbatim, and a
51
+ * difference there is enough to make the daemon reject a query.
52
+ *
53
+ * @param brand - which edition's configuration to describe.
54
+ * @returns a stable string that changes exactly when the configuration does.
55
+ */
56
+ export declare function configurationSignature(brand: QoderBrand): string;
57
+ /**
58
+ * Load the SDK for one Qoder edition, under its current configuration.
30
59
  *
31
60
  * @param brand - which edition's SDK to load.
32
61
  * @returns the SDK module.
33
62
  */
34
63
  export declare function loadSdk(brand: QoderBrand): Promise<QoderSdkModule>;
64
+ /**
65
+ * Drop the loaded instance so the next {@link loadSdk} starts a new daemon.
66
+ *
67
+ * @param brand - which edition to reset.
68
+ */
69
+ export declare function resetSdk(brand: QoderBrand): void;
70
+ /**
71
+ * Whether an error is the SDK's daemon refusing a different configuration.
72
+ *
73
+ * @param error - whatever a query threw.
74
+ */
75
+ export declare function isDaemonConflict(error: unknown): boolean;
76
+ /**
77
+ * Run one idempotent SDK operation, recovering from a daemon conflict once.
78
+ *
79
+ * A conflict means the daemon was initialized under a configuration that no
80
+ * longer applies. A fresh module instance starts an empty daemon with the
81
+ * current one, so the retry succeeds without a restart. Only use this for
82
+ * operations that can be repeated without side effects (reads), never for a
83
+ * turn that may already have emitted output.
84
+ *
85
+ * @param brand - which edition to query.
86
+ * @param run - the operation, given the module to use.
87
+ */
88
+ export declare function withSdk<T>(brand: QoderBrand, run: (sdk: QoderSdkModule) => Promise<T>): Promise<T>;
89
+ /**
90
+ * Open one cheap control query so a stale daemon is discovered before a turn
91
+ * starts streaming.
92
+ *
93
+ * A turn cannot be retried once it has emitted output, so the session path has
94
+ * to find out about a configuration conflict first. `getUsageInfo` is a
95
+ * control request: it initializes the daemon and reads the account without
96
+ * running a model turn.
97
+ *
98
+ * @param brand - which edition to probe.
99
+ */
100
+ export declare function probeDaemon(brand: QoderBrand): Promise<void>;
35
101
  /**
36
102
  * Load the CodeBuddy Agent SDK.
37
103
  *
@@ -67,4 +67,5 @@ export declare class QoderUsage {
67
67
  /** The reading for a machine whose CLI is not installed. */
68
68
  private missingCli;
69
69
  private fetch;
70
+ private readSnapshot;
70
71
  }
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "dsh-agent-sdk-bridge",
3
3
  "displayName": "Agent SDK Bridge",
4
4
  "description": "DeepSeek Harness LLM adapter bridge for Qoder CN, Qoder International, Tencent CodeBuddy and MiniMax Code subscriptions. It reuses each provider's own SDK or official ACP server and CLI login, shows available quota, and exposes per-provider settings pages with independent international and mainland login regions.",
5
- "version": "1.2.1",
5
+ "version": "1.2.2",
6
6
  "type": "module",
7
7
  "license": "MIT",
8
8
  "author": "k1-h2",
package/src/cli.ts CHANGED
@@ -245,6 +245,17 @@ export function cliConflictMessage(brand: QoderBrand): string {
245
245
  * @returns the original detail, prefixed with the actionable explanation.
246
246
  */
247
247
  export function cliFailureText(detail: string, brand: QoderBrand): string {
248
+ // The SDK routes every query through one process-wide daemon pinned to the
249
+ // first launch configuration it saw. When the machine changes under it (a
250
+ // reinstall, a new edition, a different environment) every query is rejected
251
+ // with this message until the process restarts. The plugin now drops the SDK
252
+ // instance at that point, so the next request recovers; say that instead of
253
+ // echoing an English internal error into the page.
254
+ if (/DaemonConfigurationConflict|Global daemon is already initialized with different options/i.test(detail)) {
255
+ const command = brandProfile(brand).cliCommands[0]
256
+ return `本机 ${command} 的运行配置在本次会话期间发生了变化,SDK 的本地守护进程仍按旧配置运行。`
257
+ + `插件已重置这部分运行时,请重试一次;若仍失败,重启 DSH Web。原始信息:${detail}`
258
+ }
248
259
  if (!/exit(?:ed)?(?: with)? code 42|sdk_worker_removed/i.test(detail)) return detail
249
260
  const profile = brandProfile(brand)
250
261
  const pkg = profile.cliPackages[0]
package/src/models.ts CHANGED
@@ -17,10 +17,11 @@ 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, cliFailureText, foreignCliOverride, qoderCliOptions } from './cli.ts'
20
+ import { cliConflictMessage, cliFailureText, foreignCliOverride, qoderCliOptions, resolveQoderCli } from './cli.ts'
21
21
  import type { Live } from './live.ts'
22
22
  import { readLive } from './live.ts'
23
- import { loadSdk } from './sdk.ts'
23
+ import type { QoderSdkModule } from './sdk.ts'
24
+ import { withSdk } from './sdk.ts'
24
25
 
25
26
  /** How long a fetched catalog stays fresh by default. */
26
27
  export const DEFAULT_MODEL_CACHE_TTL_MS = 5 * 60_000
@@ -152,7 +153,15 @@ export class QoderModelCatalog {
152
153
  private async fetch(): Promise<readonly ModelInfo[]> {
153
154
  const conflict = foreignCliOverride(this.brand)
154
155
  if (conflict !== undefined) throw new Error(cliConflictMessage(this.brand))
155
- const sdk = await loadSdk(this.brand)
156
+ // Without a CLI of our own there is no configuration to initialize the
157
+ // SDK's daemon with. Asking anyway pinned it to the SDK's defaults, and the
158
+ // first query after the CLI was installed then conflicted with it for the
159
+ // rest of the process's life (see `sdk.ts`).
160
+ if (resolveQoderCli(this.brand) === undefined) throw new Error(cliConflictMessage(this.brand))
161
+ return withSdk(this.brand, sdk => this.read(sdk))
162
+ }
163
+
164
+ private async read(sdk: QoderSdkModule): Promise<readonly ModelInfo[]> {
156
165
  const q = sdk.query({
157
166
  prompt: inertInput(),
158
167
  options: {
package/src/sdk.ts CHANGED
@@ -3,65 +3,215 @@
3
3
  *
4
4
  * The Qoder editions publish the same API under different scopes, so the rest
5
5
  * of the plugin imports this module instead of a package name. The CN SDK is a
6
- * real dependency and is loaded statically; the international one is optional
7
- * at runtime — a deployment that only has a CN account may not have it
8
- * installed — so it is imported on demand and its absence is reported to the
9
- * settings page as a plain error instead of failing the plugin's mount.
6
+ * real dependency and is loaded eagerly; the international one is optional at
7
+ * runtime — a deployment that only has a CN account may not have it installed —
8
+ * so it is imported on demand and its absence is reported to the settings page
9
+ * as a plain error instead of failing the plugin's mount.
10
10
  *
11
11
  * CodeBuddy has its own, unrelated API and is loaded dynamically for the same
12
12
  * reason: an account may never use it, and its package carries a large CLI.
13
13
  *
14
- * The Qoder module is typed against the CN package because the two are
15
- * API-compatible: every Qoder call site is shared, and the only thing that
16
- * changes is which process the protocol is spoken to.
14
+ * ## Why modules are reloaded
15
+ *
16
+ * Every Qoder SDK routes all queries through one **process-wide daemon** that
17
+ * is initialized with the first query's launch configuration (CLI path,
18
+ * interpreter, environment, proxy) and then refuses any different one for the
19
+ * life of the process:
20
+ *
21
+ * DaemonConfigurationConflictError:
22
+ * Global daemon is already initialized with different options
23
+ *
24
+ * The host is long-lived, so its configuration is not: a CLI can be
25
+ * reinstalled, an edition can appear, an installer can change the machine
26
+ * environment. When that happens the ready daemon no longer matches and every
27
+ * later query fails until the process restarts — a state the settings page
28
+ * cannot recover from on its own.
29
+ *
30
+ * So the module tracks the configuration signature it loaded under and takes a
31
+ * fresh instance whenever the signature changes; {@link resetSdk} does the same
32
+ * after a conflict is observed. A new instance has an empty daemon registry, so
33
+ * it initializes against the current configuration instead of arguing with the
34
+ * old one.
17
35
  *
18
36
  * @module dsh-agent-sdk-bridge/sdk
19
37
  */
20
38
 
39
+ import { createRequire } from 'node:module'
40
+ import { pathToFileURL } from 'node:url'
21
41
  import * as cnSdk from '@qodercn-ai/qodercn-agent-sdk'
22
42
  import type * as QoderSdk from '@qodercn-ai/qodercn-agent-sdk'
23
43
  import type * as CodeBuddySdk from '@tencent-ai/agent-sdk'
24
44
  import type { CodeBuddyRegion, QoderBrand } from './brand.ts'
25
45
  import { brandProfile, codeBuddyEnvironment } from './brand.ts'
46
+ import { qoderCliOptions } from './cli.ts'
26
47
 
27
48
  /** The subset of the Qoder SDK surface this plugin uses, as one module type. */
28
49
  export type QoderSdkModule = typeof QoderSdk
29
50
  /** The CodeBuddy SDK module, typed from its declarations. */
30
51
  export type CodeBuddySdkModule = typeof CodeBuddySdk
31
52
 
32
- let globalSdk: Promise<QoderSdkModule> | undefined
53
+ /** One loaded generation: the configuration it was loaded for, and the module. */
54
+ interface Generation {
55
+ signature: string
56
+ module: Promise<QoderSdkModule>
57
+ }
58
+
59
+ const generations = new Map<QoderBrand, Generation>()
60
+ /** Brands whose next load must take a fresh instance even if the signature matches. */
61
+ const forced = new Set<QoderBrand>()
62
+ let counter = 0
33
63
  let codeBuddySdk: Promise<CodeBuddySdkModule> | undefined
34
64
 
65
+ const require = createRequire(import.meta.url)
66
+
35
67
  /**
36
- * Load the SDK for one Qoder edition.
68
+ * The launch configuration a Qoder query would use, as a comparable string.
37
69
  *
38
- * @param brand - which edition's SDK to load.
39
- * @returns the SDK module.
70
+ * Mirrors the fields the SDK's own daemon compares before reusing itself. The
71
+ * environment is included because the SDK hands it to the CLI verbatim, and a
72
+ * difference there is enough to make the daemon reject a query.
73
+ *
74
+ * @param brand - which edition's configuration to describe.
75
+ * @returns a stable string that changes exactly when the configuration does.
40
76
  */
41
- export function loadSdk(brand: QoderBrand): Promise<QoderSdkModule> {
42
- if (brand === 'cn') return Promise.resolve(cnSdk as QoderSdkModule)
43
- globalSdk ??= importGlobalSdk()
44
- return globalSdk
77
+ export function configurationSignature(brand: QoderBrand): string {
78
+ const options = qoderCliOptions(brand)
79
+ const env = Object.entries(options.env ?? {})
80
+ .filter(([, value]) => value !== undefined)
81
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
82
+ return JSON.stringify({
83
+ path: options.pathToQoderCLIExecutable ?? null,
84
+ executable: options.executable ?? null,
85
+ env,
86
+ })
45
87
  }
46
88
 
47
89
  /**
48
- * Import the international SDK by a variable specifier.
90
+ * Import one edition's SDK.
91
+ *
92
+ * A fresh instance is the same file imported under a unique URL: the module's
93
+ * top-level daemon state is per instance, while the implementation is shared by
94
+ * the module loader as usual.
49
95
  *
50
- * A literal specifier would make TypeScript and the bundler require the package
51
- * at build time, which is exactly what an optional edition must not do.
96
+ * @param brand - which edition to load.
97
+ * @param fresh - ignore the already-loaded instance and take a new one.
52
98
  */
53
- async function importGlobalSdk(): Promise<QoderSdkModule> {
54
- const specifier = brandProfile('global').sdkPackage
99
+ async function importSdk(brand: QoderBrand, fresh: boolean): Promise<QoderSdkModule> {
100
+ const specifier = brandProfile(brand).sdkPackage
55
101
  try {
56
- return await import(/* @vite-ignore */ specifier) as QoderSdkModule
102
+ if (!fresh) return await import(/* @vite-ignore */ specifier) as QoderSdkModule
103
+ const entry = pathToFileURL(require.resolve(specifier)).href
104
+ counter += 1
105
+ return await import(/* @vite-ignore */ `${entry}?generation=${counter}`) as QoderSdkModule
57
106
  } catch (error) {
58
107
  // Let a later read retry: the package may be installed while DSH is running.
59
- globalSdk = undefined
108
+ generations.delete(brand)
109
+ forced.delete(brand)
110
+ if (brand === 'cn') throw error
60
111
  const detail = error instanceof Error ? error.message : String(error)
61
112
  throw new Error(`未安装国际版 SDK(${specifier}):${detail}`)
62
113
  }
63
114
  }
64
115
 
116
+ /**
117
+ * Load the SDK for one Qoder edition, under its current configuration.
118
+ *
119
+ * @param brand - which edition's SDK to load.
120
+ * @returns the SDK module.
121
+ */
122
+ export function loadSdk(brand: QoderBrand): Promise<QoderSdkModule> {
123
+ const signature = configurationSignature(brand)
124
+ const current = generations.get(brand)
125
+ if (current !== undefined && current.signature === signature && !forced.has(brand)) {
126
+ return current.module
127
+ }
128
+ const mustReload = current !== undefined || forced.delete(brand)
129
+ const module = importSdk(brand, mustReload)
130
+ const generation = { signature, module }
131
+ generations.set(brand, generation)
132
+ module.catch(() => {
133
+ if (generations.get(brand) === generation) generations.delete(brand)
134
+ })
135
+ return module
136
+ }
137
+
138
+ /**
139
+ * Drop the loaded instance so the next {@link loadSdk} starts a new daemon.
140
+ *
141
+ * @param brand - which edition to reset.
142
+ */
143
+ export function resetSdk(brand: QoderBrand): void {
144
+ generations.delete(brand)
145
+ forced.add(brand)
146
+ }
147
+
148
+ /**
149
+ * Whether an error is the SDK's daemon refusing a different configuration.
150
+ *
151
+ * @param error - whatever a query threw.
152
+ */
153
+ export function isDaemonConflict(error: unknown): boolean {
154
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error)
155
+ return text.includes('DaemonConfigurationConflictError')
156
+ || text.includes('Global daemon is already initialized with different options')
157
+ }
158
+
159
+ /**
160
+ * Run one idempotent SDK operation, recovering from a daemon conflict once.
161
+ *
162
+ * A conflict means the daemon was initialized under a configuration that no
163
+ * longer applies. A fresh module instance starts an empty daemon with the
164
+ * current one, so the retry succeeds without a restart. Only use this for
165
+ * operations that can be repeated without side effects (reads), never for a
166
+ * turn that may already have emitted output.
167
+ *
168
+ * @param brand - which edition to query.
169
+ * @param run - the operation, given the module to use.
170
+ */
171
+ export async function withSdk<T>(
172
+ brand: QoderBrand,
173
+ run: (sdk: QoderSdkModule) => Promise<T>,
174
+ ): Promise<T> {
175
+ try {
176
+ return await run(await loadSdk(brand))
177
+ } catch (error) {
178
+ if (!isDaemonConflict(error)) throw error
179
+ resetSdk(brand)
180
+ return await run(await loadSdk(brand))
181
+ }
182
+ }
183
+
184
+ /**
185
+ * Open one cheap control query so a stale daemon is discovered before a turn
186
+ * starts streaming.
187
+ *
188
+ * A turn cannot be retried once it has emitted output, so the session path has
189
+ * to find out about a configuration conflict first. `getUsageInfo` is a
190
+ * control request: it initializes the daemon and reads the account without
191
+ * running a model turn.
192
+ *
193
+ * @param brand - which edition to probe.
194
+ */
195
+ export async function probeDaemon(brand: QoderBrand): Promise<void> {
196
+ const sdk = await loadSdk(brand)
197
+ const q = sdk.query({
198
+ prompt: (async function* () { await new Promise<never>(() => {}) })(),
199
+ options: {
200
+ ...qoderCliOptions(brand),
201
+ auth: sdk.qodercliAuth(),
202
+ tools: [],
203
+ allowedTools: [],
204
+ settingSources: [],
205
+ maxTurns: 1,
206
+ },
207
+ })
208
+ try {
209
+ await q.getUsageInfo()
210
+ } finally {
211
+ await q.close().catch(() => undefined)
212
+ }
213
+ }
214
+
65
215
  /**
66
216
  * Load the CodeBuddy Agent SDK.
67
217
  *
package/src/session.ts CHANGED
@@ -16,15 +16,15 @@ import {
16
16
  import type {
17
17
  ContentBlock, FinishReason, GenerateOptions, RequestMessage, StreamChunk, ToolSchema, TokenUsage,
18
18
  } from '@deepseek-ai/dsh-llm'
19
- import { createSdkMcpServer, qodercliAuth } from '@qodercn-ai/qodercn-agent-sdk'
19
+ import { createSdkMcpServer } 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, cliFailureText, foreignCliOverride, qoderCliOptions } from './cli.ts'
22
+ import { cliConflictMessage, cliFailureText, foreignCliOverride, qoderCliOptions, resolveQoderCli } 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'
26
26
  import { feedImageRefs, feedTextLength, feedWideCharCount, renderInitialFeed } from './render.ts'
27
- import { loadSdk } from './sdk.ts'
27
+ import { isDaemonConflict, loadSdk, probeDaemon, resetSdk } from './sdk.ts'
28
28
  import { TurnOutputAccounting, estimateTextTokens } from './tokens.ts'
29
29
 
30
30
  /** MCP server name this adapter exposes host tools under. */
@@ -830,6 +830,20 @@ export class QoderSession {
830
830
  // account's CLI. See `cli.ts`.
831
831
  const conflict = foreignCliOverride(this.brand)
832
832
  if (conflict !== undefined) throw new Error(cliConflictMessage(this.brand))
833
+ // No CLI of our own: do not let the SDK initialize its daemon from nothing,
834
+ // or the first query after the CLI is installed conflicts with it (see
835
+ // `sdk.ts`).
836
+ if (resolveQoderCli(this.brand) === undefined) throw new Error(cliConflictMessage(this.brand))
837
+ // A turn that has started streaming cannot be retried, so make the daemon
838
+ // prove it accepts the current configuration first. A failure here is not
839
+ // fatal by itself (the account may simply be signed out); only the
840
+ // configuration conflict matters, and it is answered by dropping the SDK
841
+ // instance so the query below is built on a fresh daemon.
842
+ try {
843
+ await probeDaemon(this.brand)
844
+ } catch (error) {
845
+ if (isDaemonConflict(error)) resetSdk(this.brand)
846
+ }
833
847
  // The SDK is brand-specific: the CN module speaks to qoderclicn and the
834
848
  // international one to qodercli, each against its own credentials.
835
849
  const sdk = await loadSdk(this.brand)
@@ -840,7 +854,7 @@ export class QoderSession {
840
854
  // this process that thread's sharp fights the host's own over the
841
855
  // libvips DLL every image needs. See `cli.ts`.
842
856
  ...qoderCliOptions(this.brand),
843
- auth: qodercliAuth(),
857
+ auth: sdk.qodercliAuth(),
844
858
  tools: [],
845
859
  allowedTools: [],
846
860
  canUseTool: this.canUseTool as CanUseTool,
@@ -1220,6 +1234,15 @@ export class QoderSession {
1220
1234
  }
1221
1235
  this.endTurn({ kind: 'error', failure: { message: 'qoder session stream ended unexpectedly', code: 'STREAM_CLOSED' } })
1222
1236
  } catch (error) {
1237
+ // The SDK's daemon refuses a configuration that changed after it started.
1238
+ // That poisons the whole module instance, so every later query would fail
1239
+ // the same way; dropping it here lets the next turn start a fresh daemon
1240
+ // instead of inheriting the broken one.
1241
+ if (isDaemonConflict(error)) {
1242
+ resetSdk(this.brand)
1243
+ this.q = null
1244
+ void q.close().catch(() => undefined)
1245
+ }
1223
1246
  this.endTurn({ kind: 'error', failure: { message: `qoder session died: ${cliFailureText(String(error), this.brand)}`, code: 'TRANSPORT' } })
1224
1247
  }
1225
1248
  }
@@ -1526,12 +1549,13 @@ export class QoderSessionManager {
1526
1549
  const brand = this.runtime.brand ?? 'cn'
1527
1550
  const conflict = foreignCliOverride(brand)
1528
1551
  if (conflict !== undefined) throw new Error(cliConflictMessage(brand))
1552
+ if (resolveQoderCli(brand) === undefined) throw new Error(cliConflictMessage(brand))
1529
1553
  const sdk = await loadSdk(brand)
1530
1554
  const q = sdk.query({
1531
1555
  prompt,
1532
1556
  options: {
1533
1557
  ...qoderCliOptions(brand),
1534
- auth: qodercliAuth(),
1558
+ auth: sdk.qodercliAuth(),
1535
1559
  tools: [],
1536
1560
  allowedTools: [],
1537
1561
  canUseTool: gateTools as CanUseTool,
@@ -1565,7 +1589,12 @@ export class QoderSessionManager {
1565
1589
  // Abandoning this loop on a host abort runs the iterator's return(),
1566
1590
  // whose close chain rejects once the child process is already gone;
1567
1591
  // that is the abort, not a transport failure.
1568
- if (signal?.aborted !== true) throw error
1592
+ if (signal?.aborted !== true) {
1593
+ // Same poisoning as the warm path: drop the instance so the next
1594
+ // request starts a daemon that matches the current configuration.
1595
+ if (isDaemonConflict(error)) resetSdk(brand)
1596
+ throw error
1597
+ }
1569
1598
  }
1570
1599
  if (signal?.aborted === true) {
1571
1600
  yield { type: 'finish', reason: { kind: 'aborted', failure: { message: 'aborted by host', code: 'ABORTED' } } }
package/src/usage.ts CHANGED
@@ -22,7 +22,8 @@ import { cliConflictMessage, cliFailureText, foreignCliOverride, qoderCliOptions
22
22
  import { withTimeout } from './models.ts'
23
23
  import type { QoderBrand } from './brand.ts'
24
24
  import { brandProfile } from './brand.ts'
25
- import { loadSdk } from './sdk.ts'
25
+ import type { QoderSdkModule } from './sdk.ts'
26
+ import { withSdk } from './sdk.ts'
26
27
 
27
28
  /** How long one quota reading stays fresh by default. */
28
29
  export const DEFAULT_USAGE_CACHE_TTL_MS = 60_000
@@ -117,32 +118,7 @@ export class QoderUsage {
117
118
  if (conflict !== undefined) {
118
119
  return { at, cliMissing: true, error: cliConflictMessage(this.brand) }
119
120
  }
120
- const sdk = await loadSdk(this.brand)
121
- const timeoutMs = readLive(this.timeoutMs, DEFAULT_USAGE_TIMEOUT_MS)
122
- const q = sdk.query({
123
- prompt: inertInput(),
124
- options: {
125
- ...qoderCliOptions(this.brand),
126
- auth: sdk.qodercliAuth(),
127
- tools: [],
128
- allowedTools: [],
129
- settingSources: [],
130
- maxTurns: 1,
131
- },
132
- })
133
- try {
134
- const usage = await withTimeout(q.getUsageInfo(), timeoutMs)
135
- // Account identity is secondary: a CLI that predates the control request
136
- // still delivers the quota, and the card simply omits the account line.
137
- const account = await withTimeout(q.accountInfo(), timeoutMs).catch(() => undefined)
138
- return {
139
- at,
140
- ...usage === null || usage === undefined ? { error: 'CLI 未返回额度信息' } : { usage },
141
- ...account === undefined ? {} : { account },
142
- }
143
- } finally {
144
- await q.close().catch(() => undefined)
145
- }
121
+ return await withSdk(this.brand, sdk => this.readSnapshot(sdk, at))
146
122
  } catch (error) {
147
123
  const detail = error instanceof Error ? error.message : String(error)
148
124
  // The quota card is the first thing a user sees on a machine without the
@@ -155,4 +131,32 @@ export class QoderUsage {
155
131
  }
156
132
  }
157
133
  }
134
+
135
+ private async readSnapshot(sdk: QoderSdkModule, at: number): Promise<UsageSnapshot> {
136
+ const timeoutMs = readLive(this.timeoutMs, DEFAULT_USAGE_TIMEOUT_MS)
137
+ const q = sdk.query({
138
+ prompt: inertInput(),
139
+ options: {
140
+ ...qoderCliOptions(this.brand),
141
+ auth: sdk.qodercliAuth(),
142
+ tools: [],
143
+ allowedTools: [],
144
+ settingSources: [],
145
+ maxTurns: 1,
146
+ },
147
+ })
148
+ try {
149
+ const usage = await withTimeout(q.getUsageInfo(), timeoutMs)
150
+ // Account identity is secondary: a CLI that predates the control request
151
+ // still delivers the quota, and the card simply omits the account line.
152
+ const account = await withTimeout(q.accountInfo(), timeoutMs).catch(() => undefined)
153
+ return {
154
+ at,
155
+ ...usage === null || usage === undefined ? { error: 'CLI 未返回额度信息' } : { usage },
156
+ ...account === undefined ? {} : { account },
157
+ }
158
+ } finally {
159
+ await q.close().catch(() => undefined)
160
+ }
161
+ }
158
162
  }