zapagent 1.14.19 → 1.14.21

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.
@@ -182,6 +182,21 @@ export class ReactiveCompact {
182
182
  // caused by the tail message itself, so preserve its head/tail and retry.
183
183
  this.compactOversizedMessages(result, protectedMessages);
184
184
 
185
+ // Multimodal providers send text blocks instead of `content`. Keep mirrored
186
+ // text in sync after both reducers; independent blocks are not disposable.
187
+ messages.forEach((original, index) => {
188
+ const candidate = result[index]!;
189
+ if (original.role !== "user" || !original.contentBlocks?.length
190
+ || original.content === candidate.content) return;
191
+ const textBlocks = original.contentBlocks.filter(block => block.type === "text");
192
+ if (textBlocks.length !== 1 || textBlocks[0]!.text !== original.content) {
193
+ result[index] = original;
194
+ return;
195
+ }
196
+ result[index] = { ...candidate, contentBlocks: original.contentBlocks.map(block =>
197
+ block.type === "text" ? { ...block, text: candidate.content } : block) };
198
+ });
199
+
185
200
  // Step 3: If still overflowing, drop middle messages.
186
201
  // Keep: leading system messages, last 6 messages, drop the middle. Trigger whenever
187
202
  // at least one old non-system message can be replaced; context overflows can
@@ -611,10 +611,18 @@ export class AgentCoordinator {
611
611
  }
612
612
 
613
613
  private async waitForMessage(runId: string): Promise<AgentMailboxMessage> {
614
- const available = await this.drainMailbox(runId);
615
- if (available[0]) return available[0];
616
614
  const control = this.controls.get(runId);
617
615
  if (!control) throw new Error(`Unknown Agent run: ${runId}`);
616
+ control.controller.signal.throwIfAborted();
617
+ // Claim only the returned message, before yielding to another receiver.
618
+ const available = this.current().messages.find((message) =>
619
+ message.toRunId === runId && message.consumedAt === undefined
620
+ );
621
+ if (available) {
622
+ available.consumedAt = this.clock();
623
+ await this.persist();
624
+ return structuredClone(available);
625
+ }
618
626
  return new Promise((resolve, reject) => {
619
627
  const deliver = (message: AgentMailboxMessage) => {
620
628
  control.controller.signal.removeEventListener("abort", abort);
@@ -625,13 +633,14 @@ export class AgentCoordinator {
625
633
  if (index >= 0) control.messageWaiters.splice(index, 1);
626
634
  reject(control.controller.signal.reason ?? new Error("Agent cancelled"));
627
635
  };
628
- if (control.controller.signal.aborted) abort();
629
- else control.controller.signal.addEventListener("abort", abort, { once: true });
636
+ control.controller.signal.addEventListener("abort", abort, { once: true });
630
637
  control.messageWaiters.push(deliver);
631
638
  });
632
639
  }
633
640
 
634
641
  private deliverMessage(message: AgentMailboxMessage): void {
642
+ // A receiver may have claimed this message while send() persisted it.
643
+ if (message.consumedAt !== undefined) return;
635
644
  const control = this.controls.get(message.toRunId);
636
645
  const waiter = control?.messageWaiters.shift();
637
646
  if (!waiter) return;
@@ -356,6 +356,7 @@ export class OpenAICompatibleProvider implements LLMProvider {
356
356
  type: "tool_call_start",
357
357
  toolCallId,
358
358
  toolName: tc.function.name,
359
+ toolCallIndex: tc.index,
359
360
  };
360
361
  emittedAnything = true;
361
362
  }
@@ -1,14 +1,22 @@
1
1
  import OpenAI from "openai";
2
2
  import type { Response as APIResponse, ResponseInputItem, ResponseCreateParams } from "openai/resources/responses/responses";
3
3
  import type { LLMProvider, LLMCallOptions } from "../llm.js";
4
- import type { LLMChunk, LLMResponse, Message, ToolCallRequest } from "../types.js";
4
+ import type { LLMChunk, LLMResponse, Message, ToolCallRequest, TokenUsage } from "../types.js";
5
5
  import type { ToolDefinition } from "../../tools/types.js";
6
6
  import { canonicalizeJsonSchema, zodToJsonSchema } from "../../tools/schema.js";
7
7
  import { ProviderRequest } from "../provider-request.js";
8
8
  import { getStreamIdleMs, withStreamIdleTimeout } from "../stream-idle.js";
9
9
  import { OpenAICompatibleProvider, type OpenAICompatibleProviderOptions } from "./openai-compatible.js";
10
+ import { stripBoundary } from "../prompt-boundary.js";
10
11
 
11
- export type OpenAIResponsesProviderOptions = OpenAICompatibleProviderOptions;
12
+ export const CODEX_RESPONSES_BASE_URL = "https://chatgpt.com/backend-api/codex";
13
+ export interface OpenAIResponsesProviderOptions extends OpenAICompatibleProviderOptions {
14
+ /** Host-owned ChatGPT credentials, resolved on each call to allow rotation/logout. */
15
+ codex?: {
16
+ getCredentials: (signal?: AbortSignal) => Promise<{ accessToken: string; accountId?: string }>;
17
+ fetch?: typeof globalThis.fetch;
18
+ };
19
+ }
12
20
  type LayoutItem =
13
21
  | { type: "reasoning"; [key: string]: unknown }
14
22
  | { type: "message"; length: number; phase?: "commentary" | "final_answer" | null }
@@ -21,7 +29,8 @@ export class OpenAIResponsesProvider implements LLMProvider {
21
29
  private formatter: OpenAICompatibleProvider;
22
30
 
23
31
  constructor(private options: OpenAIResponsesProviderOptions) {
24
- this.client = options.client ?? new OpenAI({ apiKey: options.apiKey ?? process.env.OPENAI_API_KEY,
32
+ this.client = options.codex ? new OpenAI({ apiKey: "oauth-pending", baseURL: CODEX_RESPONSES_BASE_URL, maxRetries: 0 })
33
+ : options.client ?? new OpenAI({ apiKey: options.apiKey ?? process.env.OPENAI_API_KEY,
25
34
  baseURL: options.baseURL, defaultHeaders: options.defaultHeaders, maxRetries: 0 });
26
35
  this.formatter = new OpenAICompatibleProvider({ ...options, client: this.client });
27
36
  }
@@ -29,6 +38,17 @@ export class OpenAIResponsesProvider implements LLMProvider {
29
38
  setVisionSupported(supported: boolean): void { this.formatter.setVisionSupported(supported); }
30
39
  getImageTokenContext(options?: LLMCallOptions) { return this.formatter.getImageTokenContext(options); }
31
40
 
41
+ private async requestClient(request: ProviderRequest): Promise<OpenAI> {
42
+ const codex = this.options.codex;
43
+ if (!codex) return this.client;
44
+ const credentials = await request.wait(codex.getCredentials(request.signal));
45
+ request.signal.throwIfAborted();
46
+ // OAuth tokens are never sent to a user-configurable endpoint/client.
47
+ return new OpenAI({ baseURL: CODEX_RESPONSES_BASE_URL, apiKey: credentials.accessToken, maxRetries: 0,
48
+ fetch: codex.fetch, defaultHeaders: { originator: "zap",
49
+ ...(credentials.accountId ? { "ChatGPT-Account-ID": credentials.accountId } : {}) } });
50
+ }
51
+
32
52
  serializeMessages(messages: Message[]): ResponseInputItem[] {
33
53
  // Reuse image degradation, tool-image grouping, text sanitization and late
34
54
  // system-message normalization; never pass Chat sidecars into Responses.
@@ -94,7 +114,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
94
114
  delete extra.conversation;
95
115
  delete extra.background;
96
116
  const include = Array.isArray(extra.include) ? extra.include.filter(value => typeof value === "string") : [];
97
- return {
117
+ const body = {
98
118
  model: opts?.model ?? this.options.model,
99
119
  max_output_tokens: opts?.maxOutputTokens ?? this.options.maxTokens ?? 4096,
100
120
  ...extra,
@@ -107,6 +127,18 @@ export class OpenAIResponsesProvider implements LLMProvider {
107
127
  store: false,
108
128
  stream,
109
129
  } as ResponseCreateParams;
130
+ if (this.options.codex) {
131
+ let leadingSystemEnd = 0;
132
+ while (messages[leadingSystemEnd]?.role === "system") leadingSystemEnd++;
133
+ body.instructions = messages.slice(0, leadingSystemEnd).map(message => stripBoundary(message.content)).join("\n\n");
134
+ body.input = this.serializeMessages(messages.slice(leadingSystemEnd));
135
+ // Codex requires SSE and rejects generation controls accepted by the API.
136
+ delete body.max_output_tokens;
137
+ delete body.temperature;
138
+ delete body.top_p;
139
+ body.stream = true;
140
+ }
141
+ return body;
110
142
  }
111
143
 
112
144
  private parse(response: APIResponse): LLMResponse {
@@ -150,6 +182,7 @@ export class OpenAIResponsesProvider implements LLMProvider {
150
182
  }
151
183
 
152
184
  async call(messages: Message[], tools?: ToolDefinition[], opts?: LLMCallOptions): Promise<LLMResponse> {
185
+ if (this.options.codex) return this.collectCodexStream(messages, tools, opts);
153
186
  const request = new ProviderRequest(opts);
154
187
  try {
155
188
  const body = this.body(messages, tools, opts, false);
@@ -161,6 +194,30 @@ export class OpenAIResponsesProvider implements LLMProvider {
161
194
  } finally { request.close(); }
162
195
  }
163
196
 
197
+ private async collectCodexStream(messages: Message[], tools?: ToolDefinition[], opts?: LLMCallOptions): Promise<LLMResponse> {
198
+ let text = "";
199
+ let usage: TokenUsage = { inputTokens: 0, outputTokens: 0, providerUsageReported: false };
200
+ let finishReason: string | undefined;
201
+ let raw: Record<string, unknown> | undefined;
202
+ const pending = new Map<string, { name: string; json: string }>();
203
+ for await (const chunk of this.stream(messages, tools, opts)) {
204
+ if (chunk.type === "text_delta") text += chunk.text;
205
+ if (chunk.type === "tool_call_start") pending.set(chunk.toolCallId, { name: chunk.toolName, json: "" });
206
+ if (chunk.type === "tool_call_delta") { const call = pending.get(chunk.toolCallId); if (call) call.json += chunk.partialJson; }
207
+ if (chunk.type === "done") { usage = chunk.usage; finishReason = chunk.finishReason; raw = chunk.raw; }
208
+ }
209
+ opts?.signal?.throwIfAborted();
210
+ const toolCalls: ToolCallRequest[] = [...pending].map(([id, call]) => {
211
+ try {
212
+ const args = JSON.parse(call.json);
213
+ if (!args || typeof args !== "object" || Array.isArray(args)) throw new Error();
214
+ return { id, name: call.name, arguments: args };
215
+ } catch { return { id, name: call.name, arguments: {}, argumentParseError: "Malformed tool arguments JSON from provider: expected an object." }; }
216
+ });
217
+ return { type: toolCalls.length ? "tool_call" : "text", text,
218
+ toolCalls: toolCalls.length ? toolCalls : undefined, usage, finishReason, raw };
219
+ }
220
+
164
221
  async *stream(messages: Message[], tools?: ToolDefinition[], opts?: LLMCallOptions): AsyncIterable<LLMChunk> {
165
222
  const request = new ProviderRequest(opts);
166
223
  yield* request.watch(this.streamResponse(messages, tools, opts, request));
@@ -168,8 +225,9 @@ export class OpenAIResponsesProvider implements LLMProvider {
168
225
 
169
226
  private async *streamResponse(messages: Message[], tools: ToolDefinition[] | undefined, opts: LLMCallOptions | undefined, request: ProviderRequest): AsyncIterable<LLMChunk> {
170
227
  const body = this.body(messages, tools, opts, true);
171
- request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
172
- const stream = await this.client.responses.create({ ...body, stream: true }, { signal: request.signal, maxRetries: 0 });
228
+ request.measureBody(body, this.options.maxRequestBytes, `responses:${this.options.codex ? CODEX_RESPONSES_BASE_URL : this.options.baseURL ?? this.options.client?.baseURL ?? "default"}`);
229
+ const client = await this.requestClient(request);
230
+ const stream = await request.wait(client.responses.create({ ...body, stream: true }, { signal: request.signal, maxRetries: 0 }));
173
231
  request.responseReceived();
174
232
  let emittedText = "";
175
233
  try {
@@ -164,7 +164,7 @@ export class AgentLogger {
164
164
 
165
165
  type UsageLogInput = Pick<
166
166
  TokenUsage,
167
- "inputTokens" | "providerUsageReported" | "cacheReadInputTokens" | "cacheCreationInputTokens"
167
+ "inputTokens" | "providerUsageReported" | "usageIncomplete" | "cacheReadInputTokens" | "cacheCreationInputTokens"
168
168
  >;
169
169
 
170
170
  export function formatUsageLogFields(usage: UsageLogInput): Record<string, unknown> {
@@ -173,6 +173,9 @@ export function formatUsageLogFields(usage: UsageLogInput): Record<string, unkno
173
173
  const cacheCreationReported = typeof usage.cacheCreationInputTokens === "number";
174
174
  return {
175
175
  inputTokens: usage.inputTokens,
176
+ ...(typeof usage.usageIncomplete === "boolean"
177
+ ? { usageIncomplete: usage.usageIncomplete }
178
+ : {}),
176
179
  ...(typeof usage.providerUsageReported === "boolean"
177
180
  ? { providerUsageReported: usage.providerUsageReported }
178
181
  : {}),
@@ -330,7 +330,7 @@ export class MCPManager {
330
330
  clearTimeout(s.reconnectTimer);
331
331
  s.reconnectTimer = undefined;
332
332
  }
333
- await this.disposeClient(s);
333
+ // connect() owns invalidation and disposal, including overlapping reconnects.
334
334
  // Clear terminal-error so scheduleReconnect's attempt counter starts
335
335
  // fresh — the user explicitly asked to retry.
336
336
  s.reconnectAttempts = 0;
@@ -380,10 +380,9 @@ export class MCPManager {
380
380
  if (!s) return;
381
381
  if (s.reconnectTimer) clearTimeout(s.reconnectTimer);
382
382
  this.servers.delete(name);
383
- if (s.client) {
384
- try { await s.client.close(); } catch { /* ignore */ }
385
- }
383
+ const disposed = this.disposeClient(s); // invalidate pending startup before yielding
386
384
  this.setStatus(s, "disconnected");
385
+ await disposed;
387
386
  }
388
387
 
389
388
  /** Tear down everything. Best-effort, parallel; safe to call at unmount. */
@@ -436,26 +435,27 @@ export class MCPManager {
436
435
  }
437
436
 
438
437
  private async connect(s: ManagedServer): Promise<void> {
439
- // If a previous transport/client is still attached (e.g. reached here
440
- // from the auto-reconnect path after a transport drop, where the close
441
- // notification fired but close() was never explicitly called on the
442
- // client), tear it down before standing up a fresh pair. disposeClient
443
- // also bumps s.generation so any stale callbacks bound to the old pair
444
- // identify themselves and bail.
445
- if (s.client || s.transport) {
446
- await this.disposeClient(s);
447
- }
448
-
449
- const generation = ++s.generation;
438
+ if (this.servers.get(s.config.name) !== s) return;
439
+ // Invalidate first, even when transport creation has not yet returned.
440
+ // Each continuation owns only this generation, never a newer reconnect.
441
+ const disposed = this.disposeClient(s);
442
+ const generation = s.generation;
443
+ const current = () => this.isCurrent(s, generation);
444
+ await disposed;
445
+ if (!current()) return;
450
446
  this.setStatus(s, "connecting");
451
447
 
452
448
  let transport: Transport;
453
449
  try {
454
450
  const built = await createTransport(s.config);
455
451
  transport = built.transport;
452
+ if (!current()) {
453
+ try { await transport.close(); } catch { /* never attached to a client */ }
454
+ return;
455
+ }
456
456
  s.authProvider = built.authProvider;
457
457
  } catch (err) {
458
- this.markError(s, err);
458
+ if (current()) this.markError(s, err);
459
459
  return;
460
460
  }
461
461
 
@@ -465,15 +465,15 @@ export class MCPManager {
465
465
  advertiseSampling,
466
466
  advertiseRoots,
467
467
  onToolsChanged: () => {
468
- if (generation !== s.generation) return;
468
+ if (!current()) return;
469
469
  void this.refreshTools(s).catch(() => { /* ignore */ });
470
470
  },
471
471
  onResourcesChanged: () => {
472
- if (generation !== s.generation) return;
472
+ if (!current()) return;
473
473
  void this.refreshResources(s).catch(() => { /* ignore */ });
474
474
  },
475
475
  onPromptsChanged: () => {
476
- if (generation !== s.generation) return;
476
+ if (!current()) return;
477
477
  void this.refreshPrompts(s).catch(() => { /* ignore */ });
478
478
  },
479
479
  });
@@ -501,7 +501,7 @@ export class MCPManager {
501
501
  }
502
502
  // notifications/message → log event
503
503
  client.setNotificationHandler(LoggingMessageNotificationSchema, async (notif) => {
504
- if (generation !== s.generation) return;
504
+ if (!current()) return;
505
505
  const p = notif.params;
506
506
  this.emit({
507
507
  type: "log",
@@ -515,7 +515,7 @@ export class MCPManager {
515
515
  // useMCPSubsystem hook). UI integration can be deepened later but the
516
516
  // shape is stable enough for status-line widgets to consume.
517
517
  client.setNotificationHandler(ProgressNotificationSchema, async (notif) => {
518
- if (generation !== s.generation) return;
518
+ if (!current()) return;
519
519
  const p = notif.params;
520
520
  this.emit({
521
521
  type: "log",
@@ -530,17 +530,25 @@ export class MCPManager {
530
530
  // from previous generations so a stale onclose can't trigger a reconnect
531
531
  // while a fresh connect is already in progress.
532
532
  transport.onclose = () => {
533
- if (generation !== s.generation) return;
533
+ if (!current()) return;
534
534
  if (s.status === "disconnected") return; // intentional stop
535
535
  s.lastError = "transport closed";
536
536
  this.setStatus(s, "degraded");
537
537
  this.scheduleReconnect(s);
538
538
  };
539
539
  transport.onerror = (err) => {
540
- if (generation !== s.generation) return;
540
+ if (!current()) return;
541
541
  s.lastError = err instanceof Error ? err.message : String(err);
542
542
  };
543
543
 
544
+ const retire = async () => {
545
+ if (!current()) return undefined;
546
+ const disposal = this.disposeClient(s);
547
+ const retiredGeneration = s.generation;
548
+ await disposal;
549
+ return retiredGeneration;
550
+ };
551
+
544
552
  const connectTimeout = s.config.connectTimeoutMs ?? DEFAULTS.connectTimeoutMs;
545
553
  try {
546
554
  await withTimeout(
@@ -553,17 +561,21 @@ export class MCPManager {
553
561
  // We do NOT auto-trigger the browser flow on every connect — that
554
562
  // would race on app startup and pop a window without user intent.
555
563
  if (err instanceof UnauthorizedError) {
556
- await this.disposeClient(s); // close the half-initialized client
564
+ const retiredGeneration = await retire();
565
+ if (retiredGeneration === undefined || !this.isCurrent(s, retiredGeneration)) return;
557
566
  s.lastError = "authorization required";
558
567
  this.setStatus(s, "needs_auth");
559
568
  return;
560
569
  }
561
- await this.disposeClient(s); // prevent stdio child / socket from lingering across retries
570
+ const retiredGeneration = await retire();
571
+ if (retiredGeneration === undefined || !this.isCurrent(s, retiredGeneration)) return;
562
572
  this.markError(s, err);
563
573
  this.scheduleReconnect(s);
564
574
  return;
565
575
  }
566
576
 
577
+ if (!current()) return;
578
+
567
579
  // Capture server capabilities for UI display + feature gating.
568
580
  const caps = (client.getServerCapabilities?.() ?? {}) as MCPServerCapabilities;
569
581
  s.capabilities = caps;
@@ -576,28 +588,33 @@ export class MCPManager {
576
588
  try {
577
589
  if (caps.tools) await this.refreshTools(s);
578
590
  } catch (err) {
579
- await this.disposeClient(s); // close before retry — see disposeClient docs
591
+ const retiredGeneration = await retire();
592
+ if (retiredGeneration === undefined || !this.isCurrent(s, retiredGeneration)) return;
580
593
  this.markError(s, err);
581
594
  this.scheduleReconnect(s);
582
595
  return;
583
596
  }
597
+ if (!current()) return;
584
598
  await Promise.allSettled([
585
599
  caps.resources ? this.refreshResources(s) : Promise.resolve(),
586
600
  caps.prompts ? this.refreshPrompts(s) : Promise.resolve(),
587
601
  ]);
588
602
 
603
+ if (!current()) return;
604
+
589
605
  // Re-subscribe to anything that was subscribed before the reconnect,
590
606
  // and route resources/updated notifications back to event-bus consumers.
591
607
  if (caps.resources?.subscribe) {
592
608
  client.setNotificationHandler(
593
609
  ResourceUpdatedNotificationSchema,
594
610
  async (notif) => {
595
- if (generation !== s.generation) return;
611
+ if (!current()) return;
596
612
  this.emit({ type: "resource_updated", server: s.config.name, uri: notif.params.uri });
597
613
  },
598
614
  );
599
615
  for (const uri of s.subscriptions) {
600
616
  try { await client.subscribeResource({ uri }); } catch { /* ignore */ }
617
+ if (!current()) return;
601
618
  }
602
619
  }
603
620
 
@@ -607,13 +624,16 @@ export class MCPManager {
607
624
  try { await client.setLoggingLevel(s.config.loggingLevel); } catch { /* ignore */ }
608
625
  }
609
626
 
627
+ if (!current()) return;
610
628
  s.reconnectAttempts = 0;
611
629
  s.connectedAt = new Date().toISOString();
612
630
  this.setStatus(s, "ready");
613
631
  }
614
632
 
615
633
  private async refreshTools(s: ManagedServer): Promise<void> {
616
- if (!s.client) return;
634
+ const client = s.client;
635
+ const generation = s.generation;
636
+ if (!client || !this.isCurrent(s, generation)) return;
617
637
  const collected: MCPListedTool[] = [];
618
638
  let cursor: string | undefined;
619
639
  // Pagination loop. Most servers return everything in one shot; we still
@@ -624,10 +644,11 @@ export class MCPManager {
624
644
  // behaviour of fetchResources / fetchPrompts so the connect path stays
625
645
  // symmetric across primitives.
626
646
  for (let i = 0; i < 32; i++) {
627
- let res: Awaited<ReturnType<typeof s.client.listTools>>;
647
+ let res: Awaited<ReturnType<typeof client.listTools>>;
628
648
  try {
629
- res = await s.client.listTools(cursor ? { cursor } : undefined);
649
+ res = await client.listTools(cursor ? { cursor } : undefined);
630
650
  } catch (err) {
651
+ if (!this.isCurrent(s, generation)) return;
631
652
  const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
632
653
  if (msg.includes("-32601") || msg.includes("not found") || msg.includes("not supported")) {
633
654
  s.tools = [];
@@ -636,6 +657,7 @@ export class MCPManager {
636
657
  }
637
658
  throw err;
638
659
  }
660
+ if (!this.isCurrent(s, generation)) return;
639
661
  for (const t of res.tools ?? []) collected.push(t as MCPListedTool);
640
662
  cursor = res.nextCursor;
641
663
  if (!cursor) break;
@@ -645,7 +667,7 @@ export class MCPManager {
645
667
  for (const t of collected) {
646
668
  try {
647
669
  bridged.push(bridgeMCPTool(
648
- s.client!,
670
+ client,
649
671
  s.config,
650
672
  t,
651
673
  { projectCwd: this.projectCwd },
@@ -673,23 +695,34 @@ export class MCPManager {
673
695
  }
674
696
 
675
697
  private async refreshResources(s: ManagedServer): Promise<void> {
676
- if (!s.client) return;
677
- const { resources, templates } = await fetchResources(s.client, s.config);
698
+ const client = s.client;
699
+ const generation = s.generation;
700
+ if (!client || !this.isCurrent(s, generation)) return;
701
+ const { resources, templates } = await fetchResources(client, s.config);
702
+ if (!this.isCurrent(s, generation)) return;
678
703
  s.resources = resources;
679
704
  s.resourceTemplates = templates;
680
705
  this.emit({ type: "resources_changed", server: s.config.name });
681
706
  }
682
707
 
683
708
  private async refreshPrompts(s: ManagedServer): Promise<void> {
684
- if (!s.client) return;
685
- s.prompts = await fetchPrompts(s.client, s.config);
709
+ const client = s.client;
710
+ const generation = s.generation;
711
+ if (!client || !this.isCurrent(s, generation)) return;
712
+ const prompts = await fetchPrompts(client, s.config);
713
+ if (!this.isCurrent(s, generation)) return;
714
+ s.prompts = prompts;
686
715
  this.emit({ type: "prompts_changed", server: s.config.name });
687
716
  }
688
717
 
689
718
  // ── Reconnect / error helpers ──────────────────────────────────────────
690
719
 
720
+ private isCurrent(s: ManagedServer, generation: number): boolean {
721
+ return this.servers.get(s.config.name) === s && s.generation === generation;
722
+ }
723
+
691
724
  private scheduleReconnect(s: ManagedServer): void {
692
- if (s.status === "disconnected") return;
725
+ if (this.servers.get(s.config.name) !== s || s.status === "disconnected") return;
693
726
  if (s.reconnectAttempts >= DEFAULTS.maxReconnectAttempts) {
694
727
  this.setStatus(s, "error");
695
728
  return;
@@ -698,8 +731,9 @@ export class MCPManager {
698
731
  const delay = delays[Math.min(s.reconnectAttempts, delays.length - 1)]!;
699
732
  s.reconnectAttempts++;
700
733
  if (s.reconnectTimer) clearTimeout(s.reconnectTimer);
734
+ const generation = s.generation;
701
735
  s.reconnectTimer = setTimeout(() => {
702
- if (!this.servers.has(s.config.name)) return; // stopped while waiting
736
+ if (!this.isCurrent(s, generation)) return; // stopped or replaced while waiting
703
737
  void this.connect(s);
704
738
  }, delay);
705
739
  }
@@ -729,14 +763,12 @@ export class MCPManager {
729
763
  const transport = s.transport;
730
764
  s.client = null;
731
765
  s.transport = null;
732
- if (transport) {
733
- // Detach handlers FIRST so the close fired by client.close() doesn't
734
- // trip the reconnect loop.
735
- transport.onclose = undefined;
736
- transport.onerror = undefined;
737
- }
766
+ // Keep the SDK's transport callbacks intact so close rejects pending
767
+ // requests. Our callbacks already ignore this invalidated generation.
738
768
  if (client) {
739
769
  try { await client.close(); } catch { /* swallow — server may already be gone */ }
770
+ } else if (transport) {
771
+ try { await transport.close(); } catch { /* half-initialized transport */ }
740
772
  }
741
773
  }
742
774
 
@@ -22,13 +22,15 @@ export function applySkillTemplate(
22
22
  let body = skill.systemPrompt;
23
23
  const provided = new Set(Object.keys(params));
24
24
 
25
+ // Callback replacements keep literal dollar tokens out of replacement-string syntax.
25
26
  for (const [k, v] of Object.entries(params)) {
26
- body = body.replaceAll(`{{${k}}}`, v);
27
+ body = body.replaceAll(`{{${k}}}`, () => v);
27
28
  }
28
29
 
29
30
  for (const p of skill.parameters ?? []) {
30
- if (!provided.has(p.name) && p.default !== undefined) {
31
- body = body.replaceAll(`{{${p.name}}}`, p.default);
31
+ const defaultValue = p.default;
32
+ if (!provided.has(p.name) && defaultValue !== undefined) {
33
+ body = body.replaceAll(`{{${p.name}}}`, () => defaultValue);
32
34
  }
33
35
  }
34
36