dsh-agent-sdk-bridge 1.2.3 → 1.3.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/src/models.ts CHANGED
@@ -2,8 +2,9 @@
2
2
  * Live model catalog retrieval from one edition's local Qoder CLI. One
3
3
  * short-lived inner session sends the SDK's `get_models` control request; the
4
4
  * response (including account-custom models) stays fresh for a TTL, concurrent
5
- * callers share one in-flight fetch, and the static CN catalog is the fallback
6
- * while that edition's CLI is unreachable.
5
+ * callers share one in-flight fetch, and the static CN catalog is a fallback
6
+ * only while that edition's CLI is installed but cannot answer — never for an
7
+ * account that answered with an empty list (see {@link emptyCatalogFallback}).
7
8
  *
8
9
  * The CN and international editions publish different catalogs, so cache and
9
10
  * fallback are kept per brand: a list fetched from one account must never be
@@ -50,12 +51,32 @@ interface CatalogSnapshot {
50
51
  */
51
52
  const sharedSnapshots = new Map<QoderBrand, CatalogSnapshot>()
52
53
 
54
+ /**
55
+ * Brands whose CLI has answered a catalogue read successfully at least once.
56
+ *
57
+ * An empty answer is the account speaking — signed out, or a plan with no
58
+ * official models — and it must not be confused with a read that never
59
+ * happened. Deliberately NOT cleared by {@link QoderModelCatalog.invalidate}:
60
+ * a sign-out drops the catalogue, and the next read may fail outright (the CLI
61
+ * was just re-authenticated, the network hiccuped), which would otherwise look
62
+ * like "never reachable" and republish the static plan to an account with
63
+ * nothing. Any successful read counts, including one whose models are all
64
+ * switched off upstream: the plan only ever stands in for silence.
65
+ */
66
+ const answeredCatalogs = new Set<QoderBrand>()
67
+
53
68
  /** Cached live CLI catalog with a static fallback. */
54
69
  export class QoderModelCatalog {
55
70
  private cached: CatalogSnapshot | undefined
56
- private inflight: Promise<readonly ModelInfo[]> | undefined
71
+ private inflight: { epoch: number, promise: Promise<readonly ModelInfo[]> } | undefined
57
72
  /** Why the last refresh failed, for the settings page's guidance. */
58
73
  private failure: string | undefined
74
+ /**
75
+ * Bumped by {@link invalidate}. A fetch that started before a sign-in carries
76
+ * the previous account's entries, so it must not republish them after the
77
+ * cache was dropped for that account change.
78
+ */
79
+ private epoch = 0
59
80
 
60
81
  /**
61
82
  * @param brand - which edition's CLI answers.
@@ -78,6 +99,7 @@ export class QoderModelCatalog {
78
99
  */
79
100
  async liveModels(): Promise<readonly ModelInfo[]> {
80
101
  const ttlMs = readLive(this.ttlMs, DEFAULT_MODEL_CACHE_TTL_MS)
102
+ const epoch = this.epoch
81
103
  const fresh = (snapshot: CatalogSnapshot | undefined): boolean =>
82
104
  snapshot !== undefined && Date.now() - snapshot.at < ttlMs
83
105
  // Own cache first, then the process-wide one a previous adapter left behind.
@@ -86,17 +108,34 @@ export class QoderModelCatalog {
86
108
  this.cached = cached
87
109
  return officialOnly(cached.models)
88
110
  }
89
- this.inflight ??= this.fetch().finally(() => { this.inflight = undefined })
111
+ let entry = this.inflight
112
+ if (entry === undefined || entry.epoch !== epoch) {
113
+ const promise = this.fetch()
114
+ entry = { epoch, promise }
115
+ this.inflight = entry
116
+ const settled = entry
117
+ const clear = (): void => {
118
+ if (this.inflight === settled) this.inflight = undefined
119
+ }
120
+ void promise.then(clear, clear)
121
+ }
90
122
  try {
91
- const models = await this.inflight
123
+ const models = await entry.promise
124
+ // Read before the account changed: answer this reader, but leave the
125
+ // cache to the fetch that the post-change read already started.
126
+ if (epoch !== this.epoch) return officialOnly(models)
92
127
  const snapshot: CatalogSnapshot = { at: Date.now(), models }
93
128
  this.cached = snapshot
94
129
  sharedSnapshots.set(this.brand, snapshot)
95
130
  this.failure = undefined
131
+ // A successful read — empty or not — is an answer. A later failed read
132
+ // must not mistake it for "the CLI was never reachable" and publish the
133
+ // captured plan.
134
+ answeredCatalogs.add(this.brand)
96
135
  return officialOnly(models)
97
136
  } catch (error) {
98
137
  const detail = error instanceof Error ? error.message : String(error)
99
- this.failure = cliFailureText(detail, this.brand)
138
+ if (epoch === this.epoch) this.failure = cliFailureText(detail, this.brand)
100
139
  // A failed refresh keeps serving the last good list rather than dropping
101
140
  // to the static fallback, which would hide the account's real models.
102
141
  return officialOnly((this.cached ?? sharedSnapshots.get(this.brand))?.models ?? [])
@@ -129,17 +168,27 @@ export class QoderModelCatalog {
129
168
  * is installed at all, and which account is signed in — and an empty answer is
130
169
  * cached like any other. So after the setup helper has run, the page's next
131
170
  * read must not be served from a snapshot taken before that login existed.
171
+ *
172
+ * The remembered empty answer is deliberately kept: it says the account has
173
+ * nothing, which a later failed read must not turn back into the static plan.
132
174
  */
133
175
  invalidate(): void {
134
176
  this.cached = undefined
135
177
  sharedSnapshots.delete(this.brand)
136
178
  this.failure = undefined
179
+ this.epoch += 1
180
+ this.inflight = undefined
137
181
  }
138
182
 
139
- /** dsh catalog entries: the enabled live list, or the static fallback. */
183
+ /** dsh catalog entries: the enabled live list, or the fallback {@link emptyCatalogFallback} allows. */
140
184
  async models(): Promise<readonly QoderCatalogModel[]> {
141
185
  const live = (await this.liveModels()).filter(model => model.isEnabled !== false)
142
- if (live.length === 0) return brandProfile(this.brand).staticCatalog ? QODER_MODELS : []
186
+ if (live.length === 0) {
187
+ return emptyCatalogFallback(this.brand, {
188
+ cliInstalled: resolveQoderCli(this.brand) !== undefined,
189
+ answered: answeredCatalogs.has(this.brand),
190
+ })
191
+ }
143
192
  return live.map(model => ({
144
193
  id: model.value,
145
194
  name: model.displayName.length > 0 ? model.displayName : model.value,
@@ -205,6 +254,34 @@ export class QoderModelCatalog {
205
254
  }
206
255
  }
207
256
 
257
+ /**
258
+ * What the picker may show when the live catalogue came back empty.
259
+ *
260
+ * The captured CN plan is a stand-in for exactly one situation: this edition's
261
+ * CLI is installed, and the catalogue could not be read because the CLI or the
262
+ * network was unavailable. Two cases must stay empty:
263
+ *
264
+ * - The CLI answered. That is the account speaking — signed out, or a plan
265
+ * with no official models — and publishing the plan here is what put every
266
+ * Qoder CN model back into the picker after a sign-out, where selecting one
267
+ * could only fail. `getAvailableModels()` answers a *successful* empty list
268
+ * while signed out (its `cache` and `live` strategies included, even with a
269
+ * populated `~/.qoder-cn/.models`), so this is the ordinary sign-out path,
270
+ * not an edge case.
271
+ * - The CLI is not installed at all, so none of those models could run.
272
+ *
273
+ * @param brand - which edition's catalogue is empty.
274
+ * @param state - whether that edition's CLI is on the machine, and whether a
275
+ * successful read has ever produced an answer.
276
+ */
277
+ export function emptyCatalogFallback(
278
+ brand: QoderBrand,
279
+ state: { cliInstalled: boolean, answered: boolean },
280
+ ): readonly QoderCatalogModel[] {
281
+ if (!state.cliInstalled || state.answered) return []
282
+ return brandProfile(brand).staticCatalog ? QODER_MODELS : []
283
+ }
284
+
208
285
  /**
209
286
  * Keep only the subscription's official models.
210
287
  *
package/src/render.ts CHANGED
@@ -102,6 +102,24 @@ const BACKEND_ROLE = [
102
102
  '不要复述对话,不要解释你的角色。',
103
103
  ].join('\n')
104
104
 
105
+ /**
106
+ * Preamble for a side-channel call whose last user message *is* the task.
107
+ *
108
+ * Compaction and session titles are not "what would the assistant say next":
109
+ * DSH appends an instruction as the final user message — compaction sends
110
+ * `Condense the conversation ABOVE into a structured checkpoint…` — and
111
+ * expects exactly that to be carried out. Rendering such a request with
112
+ * {@link BACKEND_ROLE} buried the instruction inside "background" and then
113
+ * closed with "output the next assistant reply", so a compaction run dutifully
114
+ * reproduced the previous assistant message instead of summarising. The
115
+ * transcript then showed the last reply restated where the checkpoint belonged.
116
+ */
117
+ const SIDE_CHANNEL_ROLE = [
118
+ '你在为一个编码 agent(宿主)充当 LLM API 后端。',
119
+ '这一次不是继续对话:最后一条用户消息就是你要执行的任务,请直接完成它。',
120
+ '不要把最后一条消息当成新的聊天内容来回应,也不要复述对话或解释你的角色。',
121
+ ].join('\n')
122
+
105
123
  /**
106
124
  * Join feed sections into one feed. While no section carries an image the
107
125
  * result is the historical text shape, sections separated by a blank line;
@@ -243,6 +261,39 @@ export function feedWideCharCount(feed: Feed): number {
243
261
  return feed.reduce((total, part) => total + (part.type === 'text' ? countWideChars(part.text) : 0), 0)
244
262
  }
245
263
 
264
+ /**
265
+ * Compose the feed for a one-shot side-channel request (compaction, a session
266
+ * title): its last user message is the instruction to carry out, not a turn to
267
+ * continue.
268
+ *
269
+ * The history is still rendered, because compaction must see the conversation
270
+ * it is condensing, but the role preamble and the closing line both name the
271
+ * trailing instruction as the task. See {@link SIDE_CHANNEL_ROLE} for the
272
+ * misread this replaces.
273
+ */
274
+ export function renderSideChannelFeed(
275
+ system: string | undefined,
276
+ messages: readonly RequestMessage[],
277
+ imagePath?: ImagePathResolver,
278
+ ): Feed {
279
+ const history: Feed[] = []
280
+ for (const message of messages) {
281
+ const entry = renderMessage(message, imagePath)
282
+ if (feedToText(entry, imagePath).length > 0) history.push(entry)
283
+ }
284
+ const sections: Feed[] = [SIDE_CHANNEL_ROLE]
285
+ if (system !== undefined && system.length > 0) {
286
+ sections.push(`---- 宿主系统提示(作为你的行为准则) ----\n${system}`)
287
+ }
288
+ const first = history[0]
289
+ if (first !== undefined) {
290
+ sections.push(label('---- 宿主对话记录 ----\n', first))
291
+ sections.push(...history.slice(1))
292
+ }
293
+ sections.push('---- 以上是背景。请执行最后一条用户消息给出的任务。 ----')
294
+ return joinFeeds(sections)
295
+ }
296
+
246
297
  /**
247
298
  * Compose the first feed for a fresh session: backend role, the host system
248
299
  * prompt, and the existing conversation as compact context. Messages of the
package/src/sdk.ts CHANGED
@@ -145,6 +145,31 @@ export function resetSdk(brand: QoderBrand): void {
145
145
  forced.add(brand)
146
146
  }
147
147
 
148
+ /**
149
+ * Drop the loaded generation and stop the daemon it started.
150
+ *
151
+ * A daemon loads the CLI's credentials when it initializes, and those
152
+ * credentials are not part of the configuration signature: signing in as
153
+ * another account leaves the daemon answering as the account it started with.
154
+ * Shutting it down and forcing a new instance makes the next query read the
155
+ * credentials that are on disk now.
156
+ *
157
+ * The generation is dropped synchronously, so a read that starts as soon as the
158
+ * sign-in helper exits already gets the new instance; the old daemon is stopped
159
+ * in the background because no caller can wait on the shutdown.
160
+ *
161
+ * @param brand - which edition's daemon to replace.
162
+ */
163
+ export function discardSdk(brand: QoderBrand): void {
164
+ const generation = generations.get(brand)
165
+ generations.delete(brand)
166
+ forced.add(brand)
167
+ if (generation === undefined) return
168
+ void generation.module
169
+ .then(sdk => sdk.shutdownDaemon())
170
+ .catch(() => undefined)
171
+ }
172
+
148
173
  /**
149
174
  * Whether an error is the SDK's daemon refusing a different configuration.
150
175
  *
package/src/session.ts CHANGED
@@ -23,6 +23,7 @@ import { cliConflictMessage, cliFailureText, foreignCliOverride, qoderCliOptions
23
23
  import { jsonSchemaToShape } from './jsonschema.ts'
24
24
  import type { Live } from './live.ts'
25
25
  import { readLive } from './live.ts'
26
+ import { stripMcpNamespace } from './mcp-naming.ts'
26
27
  import { feedImageRefs, feedTextLength, feedWideCharCount, renderInitialFeed } from './render.ts'
27
28
  import { isDaemonConflict, loadSdk, probeDaemon, resetSdk } from './sdk.ts'
28
29
  import { TurnOutputAccounting, estimateTextTokens } from './tokens.ts'
@@ -123,6 +124,194 @@ export interface ToolResultPayload {
123
124
  */
124
125
  export type ResolvedImages = ReadonlyMap<string, { data: string, mediaType: string }>
125
126
 
127
+ /** The handle the MCP SDK returns from (and exposes on) `registerTool`. */
128
+ export interface RegisteredToolHandle {
129
+ /**
130
+ * Replace this tool's definition in place.
131
+ *
132
+ * The SDK also toggles `enabled`, which is what lets a tool the host withdrew
133
+ * actually disappear from `tools/list` instead of only stopping its handler.
134
+ */
135
+ update(updates: { description?: string, paramsSchema?: Record<string, unknown>, enabled?: boolean }): void
136
+ /** Unregister this tool, so the next `registerTool` on the name succeeds. */
137
+ remove(): void
138
+ }
139
+
140
+ /** What this module needs from the SDK's MCP server instance. */
141
+ export interface ToolRegistryHost {
142
+ registerTool(
143
+ name: string,
144
+ config: { description: string, inputSchema: Record<string, unknown> },
145
+ handler: (args: unknown) => Promise<{ content: McpContent[], isError?: boolean }>,
146
+ ): RegisteredToolHandle
147
+ /** `markdown|json` — the tool list changed, so a client must re-read it. */
148
+ sendToolListChanged?(): void
149
+ /**
150
+ * Declare the tools capability now, before any transport is connected.
151
+ *
152
+ * The MCP SDK (`McpServer`) only installs its `tools/list` + `tools/call`
153
+ * request handlers — and only registers the `tools` capability, with
154
+ * `listChanged` — the first time a tool is registered. A server created with
155
+ * an empty tool list therefore connects with **no tools capability at all**,
156
+ * and every later `registerTool` throws `Cannot register capabilities after
157
+ * connecting to transport`. The client then answers `tools/list` with
158
+ * `Method not found (-32601)`.
159
+ *
160
+ * That is exactly this bridge's first turn: `ensureTools()` runs when the host
161
+ * has not published its tools yet, so the server connects empty. The next turn
162
+ * brings `ops_bash` and friends, the registration throws, the tool never
163
+ * appears in `tools/list`, and the model — which the host's own prompt and
164
+ * `tool-addition` blocks say does have those tools — calls one anyway and is
165
+ * told `Tool "…" does not exist in the current tool set.` Calling this before
166
+ * `connect()` fixes it: the capability is declared up front, so tools can be
167
+ * added and removed for the life of the session.
168
+ */
169
+ setToolRequestHandlers?(): void
170
+ }
171
+
172
+ /**
173
+ * Keeps one in-process MCP server's tool set equal to the host's live set.
174
+ *
175
+ * The host's tool list is not fixed for a session's lifetime: `dsh-ops` adds
176
+ * and withdraws tools as a session's mode changes and as `ops_discover_tools`
177
+ * pulls a deferred capability in, and DSH republishes that change to the model
178
+ * as `tool-addition` / `tool-removal` blocks. The MCP SDK, however, refuses a
179
+ * second `registerTool` for a name it already holds ("Tool X is already
180
+ * registered") and offers no unregister of its own, so a naive replay leaves a
181
+ * changed schema at its old definition and can never take a withdrawn tool back
182
+ * out. The model then calls a name the server does not have, and CodeBuddy
183
+ * answers it with `Tool "…" does not exist in the current tool set.` instead of
184
+ * a host result — the "tool went missing mid-conversation" symptom.
185
+ *
186
+ * This wrapper therefore reconciles by name: register what is new, `update()`
187
+ * what changed, and `remove()` what the host withdrew. The call handler is built
188
+ * per registered tool and answers through the session's tool-result pairing, so
189
+ * a tool re-registered after a mode change still collects its own result.
190
+ */
191
+ export class HostToolRegistry {
192
+ /** What this registry has actually installed, by tool name, with its schema hash. */
193
+ private readonly installed = new Map<string, { hash: string, handle: RegisteredToolHandle }>()
194
+
195
+ constructor(
196
+ /** The MCP server the tools are installed into. */
197
+ private readonly host: ToolRegistryHost,
198
+ /**
199
+ * The call handler handed to the SDK for one tool.
200
+ *
201
+ * Built per registered tool and given the tool's name; the session's pairing
202
+ * answers on the tool-use id it announced, not on the name.
203
+ */
204
+ private readonly handlerFor: (name: string) => ((args: unknown) => Promise<{ content: McpContent[], isError?: boolean }>),
205
+ /** Receives anything the SDK refuses, so a silent gap never reaches the model. */
206
+ private readonly onProblem: (message: string) => void = () => {},
207
+ ) {}
208
+
209
+ /**
210
+ * Declare the tools capability before the transport connects.
211
+ *
212
+ * Must run before `connect()`, because the SDK refuses a capability change
213
+ * afterwards. Without it a session whose first turn published no host tools
214
+ * connects with no tools capability, and every tool the host offers later can
215
+ * only throw — see {@link ToolRegistryHost.setToolRequestHandlers}.
216
+ */
217
+ prepare(): void {
218
+ try {
219
+ this.host.setToolRequestHandlers?.()
220
+ } catch (error) {
221
+ // A host whose SDK has no such hook (or that is already connected) still
222
+ // works for a fixed tool set; only the mid-session add/remove is lost.
223
+ this.onProblem(`MCP tools 能力未能在连接前声明:${errorText(error)}`)
224
+ }
225
+ }
226
+
227
+ /**
228
+ * Make the installed tool set match `tools` exactly.
229
+ *
230
+ * @param tools - the host's live tool schemas, in the order the host published them.
231
+ * @returns whether anything was added, changed or removed.
232
+ */
233
+ reconcile(tools: readonly { name: string, description: string, parameters?: unknown }[]): boolean {
234
+ const wanted = new Map<string, { hash: string, schema: { name: string, description: string, parameters?: unknown } }>()
235
+ for (const schema of tools) {
236
+ // Last write wins: the host never publishes a duplicate name, but a
237
+ // duplicate must not leave the earlier definition installed. The
238
+ // description is part of the signature: it is what tells the model *when*
239
+ // to call the tool, so a reworded one is a definition change, not a no-op.
240
+ const hash = JSON.stringify([schema.description, schema.parameters ?? {}])
241
+ wanted.set(schema.name, { hash, schema })
242
+ }
243
+
244
+ let changed = false
245
+ // Withdraw first: a name that changed incompatibly is safer to re-add than
246
+ // to leave in place, and the host's own set is the contract.
247
+ for (const [name, entry] of [...this.installed.entries()]) {
248
+ if (wanted.has(name)) continue
249
+ try {
250
+ entry.handle.remove()
251
+ } catch (error) {
252
+ this.onProblem(`工具 ${name} 无法从 MCP 注销:${errorText(error)}`)
253
+ }
254
+ this.installed.delete(name)
255
+ changed = true
256
+ }
257
+
258
+ for (const [name, { hash, schema }] of wanted) {
259
+ const existing = this.installed.get(name)
260
+ if (existing !== undefined && existing.hash === hash) continue
261
+ const description = schema.description.length > 0 ? schema.description : name
262
+ const inputSchema = jsonSchemaToShape((schema.parameters ?? {}) as Record<string, unknown>)
263
+ if (existing !== undefined) {
264
+ // The schema changed while the session stayed alive. Updating in place
265
+ // keeps the tool listed with no gap for the model to notice.
266
+ try {
267
+ existing.handle.update({ description, paramsSchema: inputSchema })
268
+ this.installed.set(name, { hash, handle: existing.handle })
269
+ changed = true
270
+ continue
271
+ } catch (error) {
272
+ this.onProblem(`工具 ${name} 的 schema 更新失败,改为重新注册:${errorText(error)}`)
273
+ try {
274
+ existing.handle.remove()
275
+ } catch {
276
+ // A handle that cannot update or remove is reported once, below,
277
+ // when the fresh registration reports the same reason.
278
+ }
279
+ this.installed.delete(name)
280
+ }
281
+ }
282
+ try {
283
+ const handle = this.host.registerTool(name, { description, inputSchema }, this.handlerFor(name))
284
+ this.installed.set(name, { hash, handle })
285
+ changed = true
286
+ } catch (error) {
287
+ // Loud, and never silent: this is the one failure that removes a tool
288
+ // from the model's world while the host still believes it is offered.
289
+ this.onProblem(`宿主工具 ${name} 未能注册进 MCP server:${errorText(error)}`)
290
+ }
291
+ }
292
+
293
+ if (changed) {
294
+ try {
295
+ this.host.sendToolListChanged?.()
296
+ } catch {
297
+ // Not connected yet, so no client is listening; the connect-time
298
+ // `tools/list` still reports the reconciled set.
299
+ }
300
+ }
301
+ return changed
302
+ }
303
+
304
+ /** Names currently installed, for diagnostics and tests. */
305
+ names(): string[] {
306
+ return [...this.installed.keys()]
307
+ }
308
+ }
309
+
310
+ /** One error's message, for the diagnostics above. */
311
+ function errorText(error: unknown): string {
312
+ return error instanceof Error ? error.message : String(error)
313
+ }
314
+
126
315
  interface ChannelMessage {
127
316
  type: 'user'
128
317
  message: { role: 'user', content: ChannelContent[] }
@@ -338,10 +527,11 @@ export function meteredUsage(
338
527
 
339
528
  /**
340
529
  * The host tool runtime dispatches by the bare host name; the inner model
341
- * only ever sees the namespaced MCP form, so strip the prefix on the way out.
530
+ * only ever sees the namespaced MCP form, so strip every prefix layer on the
531
+ * way out. See {@link stripMcpNamespace} for why one layer is not enough.
342
532
  */
343
533
  export function hostToolName(name: string): string {
344
- return name.startsWith(MCP_TOOL_PREFIX) ? name.slice(MCP_TOOL_PREFIX.length) : name
534
+ return stripMcpNamespace(name, [MCP_TOOL_PREFIX]) ?? name
345
535
  }
346
536
 
347
537
  /** Deny native tools, allow this adapter's MCP tools. */
@@ -726,7 +916,29 @@ export class QoderSession {
726
916
  */
727
917
  private readonly pairing = new ToolResultPairing()
728
918
  private readonly mcp = createSdkMcpServer({ name: MCP_SERVER_NAME, tools: [] })
729
- private readonly registered = new Map<string, string>()
919
+ /**
920
+ * Reconciles the live host tool list into {@link mcp}.
921
+ *
922
+ * The session outlives the host's tool list: `dsh-ops` publishes a different
923
+ * set per mode and `ops_discover_tools` adds capabilities mid-conversation.
924
+ * Installing only what is new left the server unable to ever replace a
925
+ * changed schema (the MCP SDK refuses a duplicate name), so this owns the
926
+ * add/update/remove bookkeeping instead of a name→hash map.
927
+ */
928
+ private readonly registry = new HostToolRegistry(
929
+ this.mcp.instance as unknown as ToolRegistryHost,
930
+ () => async (_args: unknown): Promise<{ content: McpContent[], isError?: boolean }> => {
931
+ const result = await this.pairing.claim(this.toolResultTimeoutMs)
932
+ return {
933
+ content: result.content,
934
+ ...result.isError ? { isError: true } : {},
935
+ }
936
+ },
937
+ // A tool the SDK refused is invisible to the model, and the model then calls
938
+ // it, gets `Tool "…" does not exist in the current tool set.` from the CLI,
939
+ // and never reaches this pairing. Log it rather than let it pass silently.
940
+ message => console.warn(`[dsh-agent-sdk-bridge] ${message}`),
941
+ )
730
942
  private queue: TurnQueue | null = null
731
943
  private model: string
732
944
  private reasoningEffort: string | undefined
@@ -847,6 +1059,11 @@ export class QoderSession {
847
1059
  // The SDK is brand-specific: the CN module speaks to qoderclicn and the
848
1060
  // international one to qodercli, each against its own credentials.
849
1061
  const sdk = await loadSdk(this.brand)
1062
+ // Declare the tools capability before this server connects. `query()` below
1063
+ // connects it, and the SDK refuses a capability change afterwards — so a
1064
+ // session whose first turn published no host tools would connect without a
1065
+ // tools capability, and every tool the host offered later could only throw.
1066
+ this.registry.prepare()
850
1067
  const q = sdk.query({
851
1068
  prompt: this.channel,
852
1069
  options: {
@@ -930,31 +1147,19 @@ export class QoderSession {
930
1147
  })
931
1148
  }
932
1149
 
933
- /** Register any host tools whose schema this session's MCP server lacks. */
1150
+ /**
1151
+ * Make this session's MCP tool set match the host's live tool list.
1152
+ *
1153
+ * The host adds and withdraws tools during a conversation (`dsh-ops` mode
1154
+ * switches, `ops_discover_tools`), so this reconciles rather than only adds:
1155
+ * a tool that appears mid-session is registered, a changed schema is updated
1156
+ * in place, and a withdrawn tool is removed. See {@link HostToolRegistry} for
1157
+ * the failure this prevents — the model calling a name the MCP server no
1158
+ * longer had, which the CLI answers with `Tool "…" does not exist in the
1159
+ * current tool set.` instead of a host result.
1160
+ */
934
1161
  ensureTools(tools: readonly ToolSchema[]): void {
935
- for (const schema of tools) {
936
- const hash = JSON.stringify(schema.parameters ?? {})
937
- if (this.registered.get(schema.name) === hash) continue
938
- const shape = jsonSchemaToShape(schema.parameters ?? {})
939
- try {
940
- this.mcp.instance.registerTool(schema.name, {
941
- description: schema.description.length > 0 ? schema.description : schema.name,
942
- inputSchema: shape,
943
- }, async (args: unknown): Promise<{ content: McpContent[], isError?: boolean }> => {
944
- void args
945
- const result = await this.pairing.claim(this.toolResultTimeoutMs)
946
- return {
947
- content: result.content,
948
- ...result.isError ? { isError: true } : {},
949
- }
950
- })
951
- } catch {
952
- // Re-registration of a changed schema failed: keep the old tool rather
953
- // than dropping it; nothing else can recover here.
954
- continue
955
- }
956
- this.registered.set(schema.name, hash)
957
- }
1162
+ this.registry.reconcile(tools)
958
1163
  }
959
1164
 
960
1165
  /**
package/src/usage.ts CHANGED
@@ -60,7 +60,13 @@ async function* inertInput(): AsyncGenerator<never> {
60
60
  /** Cached quota reader for one brand. */
61
61
  export class QoderUsage {
62
62
  private cached: UsageSnapshot | undefined
63
- private inflight: Promise<UsageSnapshot> | undefined
63
+ private inflight: { epoch: number, promise: Promise<UsageSnapshot> } | undefined
64
+ /**
65
+ * Bumped by {@link invalidate}. A fetch that started before a sign-in may
66
+ * still resolve with the previous account's numbers, so it must neither be
67
+ * shared with later readers nor written back to the cache.
68
+ */
69
+ private epoch = 0
64
70
 
65
71
  /**
66
72
  * @param brand - which edition's CLI answers.
@@ -89,16 +95,29 @@ export class QoderUsage {
89
95
  return this.missingCli()
90
96
  }
91
97
  const ttlMs = readLive(this.ttlMs, DEFAULT_USAGE_CACHE_TTL_MS)
98
+ const epoch = this.epoch
92
99
  if (!fresh && this.cached !== undefined && Date.now() - this.cached.at < ttlMs) return this.cached
93
- this.inflight ??= this.fetch().finally(() => { this.inflight = undefined })
94
- const snapshot = await this.inflight
95
- this.cached = snapshot
100
+ let entry = this.inflight
101
+ if (entry === undefined || entry.epoch !== epoch) {
102
+ const promise = this.fetch()
103
+ entry = { epoch, promise }
104
+ this.inflight = entry
105
+ const settled = entry
106
+ const clear = (): void => {
107
+ if (this.inflight === settled) this.inflight = undefined
108
+ }
109
+ void promise.then(clear, clear)
110
+ }
111
+ const snapshot = await entry.promise
112
+ if (epoch === this.epoch) this.cached = snapshot
96
113
  return snapshot
97
114
  }
98
115
 
99
- /** Drop the cached reading. */
116
+ /** Drop the cached reading, including any fetch that started before now. */
100
117
  invalidate(): void {
101
118
  this.cached = undefined
119
+ this.epoch += 1
120
+ this.inflight = undefined
102
121
  }
103
122
 
104
123
  /** The reading for a machine whose CLI is not installed. */