dsh-agent-sdk-bridge 1.2.1 → 1.2.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/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
  }