@getpaseo/plugin 0.16.2 → 0.17.0

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.
@@ -30,6 +30,9 @@ export async function createAcpProviderConnection(options, request) {
30
30
  if (probe.agentCapabilities.loadSession) {
31
31
  supportedCapabilities.push("session.persistence");
32
32
  }
33
+ if (options.acpOptions?.deferTurnOnRunningTools) {
34
+ supportedCapabilities.push("prompt.steer");
35
+ }
33
36
  await probe.close();
34
37
  const capabilities = negotiateProviderCapabilities(request.capabilities, supportedCapabilities);
35
38
  const listeners = new Set();
@@ -135,13 +138,19 @@ async function dispatch(input, state) {
135
138
  case "session.open":
136
139
  await openSession(input, state);
137
140
  return;
138
- case "session.prompt":
139
- await requireSession(state, input.sessionId).runtime.prompt(input);
141
+ case "session.prompt": {
142
+ const session = requireSession(state, input.sessionId);
143
+ await mutateSession(session, () => session.runtime.prompt(input));
140
144
  return;
141
- case "session.interrupt":
142
- await requireSession(state, input.sessionId).runtime.interrupt();
145
+ }
146
+ case "session.interrupt": {
147
+ const session = requireSession(state, input.sessionId);
148
+ const retired = await session.runtime.interrupt();
143
149
  state.emit({ type: "request.completed", requestId: input.requestId });
150
+ if (retired)
151
+ retireSession(state, input.sessionId);
144
152
  return;
153
+ }
145
154
  case "session.permission":
146
155
  requireSession(state, input.sessionId).runtime.respondToPermission(input.permissionId, input.response);
147
156
  return;
@@ -174,15 +183,16 @@ async function discover(input, state) {
174
183
  options: state.options,
175
184
  launch: state.launch,
176
185
  boundarySessionId: "catalog",
186
+ cwd: input.cwd,
177
187
  env: {},
178
188
  emit: state.emit,
179
189
  });
180
190
  try {
181
191
  let catalog = await runtime.discover(input.cwd);
182
- const config = runtime.configAccess();
192
+ const context = runtime.configContext();
183
193
  for (const transformer of state.options.transformers ?? []) {
184
194
  if (transformer.discover) {
185
- catalog = await transformer.discover(catalog, { sessionId: "catalog", config });
195
+ catalog = await transformer.discover(catalog, context);
186
196
  }
187
197
  }
188
198
  state.emit({ type: "catalog", requestId: input.requestId, catalog });
@@ -217,6 +227,11 @@ async function listSessions(input, state) {
217
227
  await runtime.close();
218
228
  }
219
229
  }
230
+ function retireSession(state, sessionId) {
231
+ if (state.sessions.delete(sessionId)) {
232
+ state.emit({ type: "session.closed", sessionId });
233
+ }
234
+ }
220
235
  async function openSession(input, state) {
221
236
  if (state.sessions.has(input.sessionId))
222
237
  throw new Error(`Session already exists: ${input.sessionId}`);
@@ -224,8 +239,10 @@ async function openSession(input, state) {
224
239
  options: state.options,
225
240
  launch: state.launch,
226
241
  boundarySessionId: input.sessionId,
242
+ cwd: input.config.cwd,
227
243
  env: input.config.env,
228
244
  emit: state.emit,
245
+ onRetired: () => retireSession(state, input.sessionId),
229
246
  });
230
247
  try {
231
248
  const capabilities = await runtime.open(input, state.capabilities);
@@ -238,6 +255,7 @@ async function openSession(input, state) {
238
255
  capabilities,
239
256
  mutationLane: Promise.resolve(),
240
257
  });
258
+ state.emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
241
259
  }
242
260
  catch (error) {
243
261
  await runtime.close();
@@ -255,12 +273,15 @@ function requireSession(state, sessionId) {
255
273
  throw new Error(`Unknown session: ${sessionId}`);
256
274
  return session;
257
275
  }
276
+ const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
277
+ const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120000;
258
278
  class AcpRuntime {
259
279
  static async start(options) {
260
280
  let child = null;
261
281
  let spawnFailure = null;
262
282
  let stream;
263
283
  let closeConnector = async () => { };
284
+ let whenConnectorClosed = () => null;
264
285
  if (options.options.command) {
265
286
  // COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
266
287
  // Standalone callers and older hosts do not send a daemon-resolved launch.
@@ -270,6 +291,7 @@ class AcpRuntime {
270
291
  env: process.env,
271
292
  };
272
293
  child = spawnProcess(launch.command, launch.args, {
294
+ cwd: options.cwd,
273
295
  env: { ...launch.env, ...options.env },
274
296
  stdio: "pipe",
275
297
  });
@@ -283,8 +305,9 @@ class AcpRuntime {
283
305
  const owned = ownConnectorStream(await options.options.connector());
284
306
  stream = owned.stream;
285
307
  closeConnector = owned.close;
308
+ whenConnectorClosed = owned.whenClosed;
286
309
  }
287
- const runtime = new AcpRuntime(stream, child, closeConnector, options);
310
+ const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
288
311
  try {
289
312
  const initialize = withTimeout(runtime.call(runtime.connection.initialize({
290
313
  protocolVersion: PROTOCOL_VERSION,
@@ -302,12 +325,15 @@ class AcpRuntime {
302
325
  throw error;
303
326
  }
304
327
  }
305
- constructor(stream, child, closeConnector, options) {
328
+ constructor(stream, child, closeConnector, whenConnectorClosed, options) {
306
329
  this.options = options;
307
330
  this.agentCapabilities = {};
308
331
  this.nativeSessionId = "";
309
332
  this.messages = new Map();
310
333
  this.toolCalls = new Map();
334
+ this.mcpServerNames = [];
335
+ this.liveOpenToolIds = new Set();
336
+ this.canceledToolCallIds = new Set();
311
337
  // Running tool rows published by transformers; the turn's terminal closes any left open.
312
338
  this.vendorToolCalls = new Map();
313
339
  this.pendingCompactions = new Set();
@@ -315,6 +341,7 @@ class AcpRuntime {
315
341
  this.configOptions = [];
316
342
  this.modes = null;
317
343
  this.commandWaiter = null;
344
+ this.receivedInitialCommands = false;
318
345
  this.messageSequence = 0;
319
346
  /**
320
347
  * Fallback ids for streamed chunks that carry no `messageId`, one per
@@ -324,56 +351,69 @@ class AcpRuntime {
324
351
  */
325
352
  this.fallbackChunkIds = new Map();
326
353
  /**
327
- * Active while a persisted session loads. ACP agents replay the loaded
328
- * session's updates before session/load resolves; the value follows the
329
- * open request's history contract.
354
+ * Replay updates count as history until the session reports ready.
355
+ * Once ready, suppress late replay rows until the first prompt.
330
356
  */
331
357
  this.replayWindow = null;
358
+ this.lastLoadUpdateAt = 0;
332
359
  this.closing = false;
360
+ this.closePromise = null;
361
+ this.deferredRetirement = null;
362
+ this.deferredFinalized = false;
333
363
  this.processFailed = false;
334
364
  this.configTransaction = false;
335
365
  this.stagedTransformerConfig = null;
336
366
  this.notificationLane = Promise.resolve();
337
- this.promptLane = Promise.resolve();
367
+ this.incomingWireSeq = 0;
368
+ this.sessionUpdateWireSeqs = [];
369
+ this.autoAccept = false;
338
370
  this.activePrompt = null;
339
371
  this.lastUsage = {};
372
+ this.request = async (method, params) => jsonValue(await this.call(this.connection.extMethod(method, params)));
340
373
  this.child = child;
341
374
  this.closeConnector = closeConnector;
375
+ this.whenConnectorClosed = whenConnectorClosed;
342
376
  this.emit = options.emit;
343
377
  this.transformers = options.options.transformers ?? [];
344
378
  const client = {
345
379
  requestPermission: (request) => this.requestPermission(request),
346
- sessionUpdate: (notification) => this.enqueueNotification(() => this.sessionUpdate(notification)),
380
+ sessionUpdate: (notification) => {
381
+ const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq;
382
+ return this.enqueueNotification(() => this.sessionUpdate(notification, wireSeq));
383
+ },
347
384
  };
348
- this.connection = new ClientSideConnection(() => client, routeVendorNotifications(stream, (method, params) => this.vendorNotification(method, params)));
385
+ this.connection = new ClientSideConnection(() => client, routeIncomingMessages(stream, (method, params) => this.vendorNotification(method, params), (message) => this.observeWireMessage(message)));
349
386
  if (!child)
350
387
  void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
351
388
  child?.on("error", (error) => {
389
+ const message = describeError(error);
352
390
  this.processFailed = true;
353
- this.settlePendingWork();
391
+ this.settlePendingWork(message);
354
392
  if (this.closing || !this.nativeSessionId)
355
393
  return;
356
394
  this.emit({
357
395
  type: "session.runtime_failed",
358
396
  sessionId: this.options.boundarySessionId,
359
- error: { message: describeError(error) },
397
+ error: { message },
360
398
  });
361
399
  });
362
400
  child?.once("close", (code, signal) => {
363
401
  if (this.closing || this.processFailed || !this.nativeSessionId)
364
402
  return;
403
+ const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
365
404
  this.processFailed = true;
366
- this.settlePendingWork();
405
+ this.settlePendingWork(message);
367
406
  this.emit({
368
407
  type: "session.runtime_failed",
369
408
  sessionId: this.options.boundarySessionId,
370
- error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
409
+ error: { message },
371
410
  });
372
411
  });
373
412
  }
374
413
  async open(input, connectionCapabilities) {
375
414
  const mcpServers = toAcpMcpServers(input.config);
376
- const nativeSessionId = readNativeSessionId(input.persistence);
415
+ this.mcpServerNames = mcpServers.map((server) => server.name);
416
+ let nativeSessionId = readNativeSessionId(input.persistence);
377
417
  const metadata = {
378
418
  _paseo: {
379
419
  systemPrompt: input.config.systemPrompt,
@@ -382,24 +422,30 @@ class AcpRuntime {
382
422
  persist: input.config.persist,
383
423
  },
384
424
  };
425
+ for (const transformer of this.transformers) {
426
+ const prepared = transformer.sessionOpen?.({
427
+ persistence: input.persistence,
428
+ systemPrompt: input.config.systemPrompt,
429
+ agentMetadata: jsonValue(this.agentCapabilities._meta ?? null),
430
+ });
431
+ nativeSessionId ?? (nativeSessionId = prepared?.sessionId ?? null);
432
+ Object.assign(metadata, prepared?.metadata);
433
+ }
385
434
  let response;
386
435
  if (nativeSessionId) {
387
436
  // ACP agents replay the loaded session's updates before session/load resolves,
388
437
  // so the native id must be registered first for them to pass the session filter.
389
438
  this.nativeSessionId = nativeSessionId;
390
439
  this.replayWindow = input.history === "replay" ? "replay" : "skip";
391
- try {
392
- response = await this.call(this.connection.loadSession({
393
- sessionId: nativeSessionId,
394
- cwd: input.config.cwd,
395
- mcpServers,
396
- _meta: metadata,
397
- }));
398
- await this.drainNotifications();
399
- }
400
- finally {
440
+ response = await this.call(this.connection.loadSession({
441
+ sessionId: nativeSessionId,
442
+ cwd: input.config.cwd,
443
+ mcpServers,
444
+ _meta: metadata,
445
+ }));
446
+ await this.drainNotifications();
447
+ if (!this.options.options.acpOptions?.loadReplayQuietPeriodMs)
401
448
  this.replayWindow = null;
402
- }
403
449
  }
404
450
  else {
405
451
  const newSession = await this.call(this.connection.newSession({
@@ -410,10 +456,11 @@ class AcpRuntime {
410
456
  response = newSession;
411
457
  this.nativeSessionId = newSession.sessionId;
412
458
  }
413
- this.modes = response.modes;
459
+ this.modes = response.modes ?? null;
414
460
  this.configOptions = response.configOptions ?? [];
415
461
  await this.applyInitialConfig(input.config);
416
462
  const sessionCapabilities = connectionCapabilities.filter((capability) => capability !== "session.configure" ||
463
+ this.options.options.acpOptions?.autoAcceptMode !== undefined ||
417
464
  this.modes !== null ||
418
465
  this.configOptions.length > 0 ||
419
466
  this.transformers.some((transformer) => transformer.configure !== undefined));
@@ -431,7 +478,11 @@ class AcpRuntime {
431
478
  if (this.options.options.acpOptions?.waitForInitialCommands) {
432
479
  await this.waitForInitialCommands();
433
480
  }
434
- this.emit({ type: "session.ready", requestId: input.requestId, sessionId: input.sessionId });
481
+ const quietPeriod = this.options.options.acpOptions?.loadReplayQuietPeriodMs;
482
+ if (this.replayWindow && quietPeriod && quietPeriod > 0) {
483
+ await this.waitForLoadReplay(quietPeriod);
484
+ this.replayWindow = "skip";
485
+ }
435
486
  return sessionCapabilities;
436
487
  }
437
488
  async discover(cwd) {
@@ -440,22 +491,48 @@ class AcpRuntime {
440
491
  }
441
492
  const response = await this.call(this.connection.newSession({ cwd: cwd ?? process.cwd(), mcpServers: [] }));
442
493
  this.nativeSessionId = response.sessionId;
443
- this.modes = response.modes;
494
+ this.modes = response.modes ?? null;
444
495
  this.configOptions = response.configOptions ?? [];
445
- return toProviderCatalog(response.modes, response.configOptions ?? []);
446
- }
447
- prompt(input) {
448
- const admission = this.promptLane.then(() => this.admitPrompt(input));
449
- this.promptLane = admission.catch(() => undefined);
450
- return admission;
496
+ const catalog = toProviderCatalog(this.modes, this.configOptions);
497
+ const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
498
+ if (!autoAcceptMode)
499
+ return catalog;
500
+ return {
501
+ ...catalog,
502
+ modes: [...catalog.modes, { ...autoAcceptMode.mode, isUnattended: true }],
503
+ defaultMode: autoAcceptMode.default ? autoAcceptMode.mode.id : catalog.defaultMode,
504
+ };
451
505
  }
452
- async admitPrompt(input) {
506
+ async prompt(input) {
507
+ if (this.closing || this.processFailed || this.deferredRetirement) {
508
+ throw new Error("ACP session is closed");
509
+ }
510
+ if (input.prompt.delivery === "steer") {
511
+ this.steerDeferredPrompt(input);
512
+ return;
513
+ }
453
514
  const active = this.activePrompt;
454
515
  if (active) {
455
- await this.interrupt();
516
+ if (active.deferred && active.wirePromptsInFlight === 0) {
517
+ // Wire session/prompt already resolved; finish the deferred turn without sending
518
+ // session/cancel so running background tools stay alive into the follow-up turn.
519
+ this.finishDeferredTurn(active, { type: "complete", terminalizeTools: false });
520
+ }
521
+ else {
522
+ const retired = await this.interrupt();
523
+ if (retired) {
524
+ // Notify caller that the session closed before failing the replacement prompt.
525
+ this.options.onRetired?.();
526
+ throw new Error("ACP session retired after stopping deferred background work");
527
+ }
528
+ }
456
529
  await active.settled;
530
+ if (this.closing || this.processFailed || this.deferredRetirement) {
531
+ throw new Error("ACP session is closed");
532
+ }
457
533
  }
458
534
  const prompt = toAcpPrompt(input.prompt);
535
+ this.replayWindow = null;
459
536
  const turnId = `acp:${input.prompt.clientMessageId}`;
460
537
  this.fallbackChunkIds.clear();
461
538
  this.emit({
@@ -483,10 +560,22 @@ class AcpRuntime {
483
560
  turnId,
484
561
  state: "started",
485
562
  });
563
+ const activePrompt = {
564
+ turnId,
565
+ settled: Promise.resolve(),
566
+ cancelling: false,
567
+ wirePromptsInFlight: 1,
568
+ wirePromptLane: Promise.resolve(),
569
+ lastPromptResponseWireSeq: null,
570
+ crossedEndTurn: false,
571
+ replyState: "idle",
572
+ deferred: null,
573
+ };
486
574
  // The SDK dispatches notifications without awaiting them, so the prompt response can resolve
487
575
  // while earlier session updates are still queued. Apply them before the turn ends.
488
576
  const settled = this.call(this.connection.prompt({ sessionId: this.nativeSessionId, prompt })).then(async (response) => {
489
577
  await this.drainNotifications();
578
+ activePrompt.wirePromptsInFlight -= 1;
490
579
  if (response.usage) {
491
580
  this.lastUsage = {
492
581
  ...this.lastUsage,
@@ -502,36 +591,94 @@ class AcpRuntime {
502
591
  });
503
592
  }
504
593
  const state = response.stopReason === "cancelled" ? "canceled" : "completed";
505
- this.fallbackChunkIds.clear();
506
- this.terminalizeTransientItems(state);
507
- this.emit({
508
- type: "session.turn",
509
- sessionId: this.options.boundarySessionId,
510
- turnId,
511
- state,
512
- });
594
+ if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
595
+ await this.settleDeferredPrompt(activePrompt);
596
+ return undefined;
597
+ }
598
+ this.finishPromptTurn(turnId, state);
513
599
  return undefined;
514
600
  }, async (error) => {
515
601
  await this.drainNotifications();
516
- this.fallbackChunkIds.clear();
517
- this.terminalizeTransientItems("failed");
518
- this.emit({
519
- type: "session.turn",
520
- sessionId: this.options.boundarySessionId,
521
- turnId,
522
- state: "failed",
523
- error: { message: describeError(error) },
524
- });
602
+ activePrompt.wirePromptsInFlight -= 1;
603
+ this.finishPromptTurn(turnId, "failed", { message: describeError(error) });
525
604
  return undefined;
526
605
  });
527
- this.activePrompt = { turnId, settled };
606
+ activePrompt.settled = settled;
607
+ this.activePrompt = activePrompt;
528
608
  void settled.finally(() => {
529
609
  if (this.activePrompt?.turnId === turnId)
530
610
  this.activePrompt = null;
531
611
  });
532
612
  }
533
- interrupt() {
534
- return this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
613
+ async interrupt() {
614
+ if (this.deferredRetirement)
615
+ return this.deferredRetirement;
616
+ const active = this.activePrompt;
617
+ const deferredTurnId = active?.deferred ? active.turnId : null;
618
+ if (active && deferredTurnId) {
619
+ const retirement = this.retireDeferredTurn(active, deferredTurnId).catch((error) => {
620
+ if (this.deferredRetirement === retirement)
621
+ this.deferredRetirement = null;
622
+ throw error;
623
+ });
624
+ this.deferredRetirement = retirement;
625
+ return retirement;
626
+ }
627
+ if (active)
628
+ active.cancelling = true;
629
+ try {
630
+ await this.call(this.connection.cancel({ sessionId: this.nativeSessionId }));
631
+ }
632
+ finally {
633
+ // An agent may wait for its outstanding permission replies before ending the prompt.
634
+ if (active) {
635
+ this.finishTurnPermissions(active.turnId);
636
+ }
637
+ }
638
+ return false;
639
+ }
640
+ finalizeDeferredTurn(deferredTurnId, emitRetired) {
641
+ if (this.deferredFinalized)
642
+ return;
643
+ this.deferredFinalized = true;
644
+ this.finishPromptTurn(deferredTurnId, "canceled", undefined, {
645
+ suppressTrailingToolEcho: true,
646
+ });
647
+ if (emitRetired)
648
+ this.options.onRetired?.();
649
+ }
650
+ async retireDeferredTurn(active, deferredTurnId) {
651
+ active.cancelling = true;
652
+ // Record open tools owned by Stop before writing session/cancel so any failure
653
+ // update arriving during cancel preserves their canceled state.
654
+ for (const id of this.liveOpenToolIds)
655
+ this.canceledToolCallIds.add(id);
656
+ let cancelTimedOut = false;
657
+ if (!this.closing) {
658
+ try {
659
+ await withTimeout(this.call(this.connection.cancel({ sessionId: this.nativeSessionId })), 1000, `ACP session ${this.nativeSessionId} did not accept cancel`);
660
+ }
661
+ catch {
662
+ cancelTimedOut = true;
663
+ }
664
+ finally {
665
+ // An agent may wait for its outstanding permission replies before ending the prompt.
666
+ this.finishTurnPermissions(active.turnId);
667
+ }
668
+ }
669
+ // ACP v1 has no response or end boundary for session/cancel once session/prompt
670
+ // already returned. Close the process first while the turn still appears running,
671
+ // then emit the canceled turn synchronously before request.completed and session.closed
672
+ // so queued work and config changes immediately observe the retired session.
673
+ try {
674
+ await this.close({ force: cancelTimedOut, timeoutMs: 1000 });
675
+ }
676
+ catch (error) {
677
+ void this.whenConnectorClosed()?.then(() => this.finalizeDeferredTurn(deferredTurnId, true), () => undefined);
678
+ throw error;
679
+ }
680
+ this.finalizeDeferredTurn(deferredTurnId, false);
681
+ return true;
535
682
  }
536
683
  listSessions(cwd) {
537
684
  return this.call(this.connection.listSessions({ cwd }));
@@ -543,24 +690,46 @@ class AcpRuntime {
543
690
  respondToPermission(permissionId, response) {
544
691
  const pending = this.permissions.get(permissionId);
545
692
  if (!pending)
546
- throw new Error(`Unknown ACP permission: ${permissionId}`);
693
+ return;
694
+ const active = this.activePrompt;
695
+ if (active?.cancelling && pending.turnId === active.turnId)
696
+ return;
547
697
  const selected = selectPermissionOption(pending.request.options, response);
548
698
  if (response.selectedActionId !== undefined && !selected) {
549
699
  throw new Error(`ACP permission action '${response.selectedActionId}' does not exist or does not match '${response.behavior}' behavior`);
550
700
  }
551
- this.permissions.delete(permissionId);
552
- pending.resolve({
701
+ this.resolvePermission(permissionId, pending, {
553
702
  outcome: selected
554
703
  ? { outcome: "selected", optionId: selected.optionId }
555
704
  : { outcome: "cancelled" },
556
705
  });
706
+ }
707
+ finishTurnPermissions(turnId) {
708
+ for (const [permissionId, pending] of this.permissions) {
709
+ if (pending.turnId === turnId) {
710
+ this.resolvePermission(permissionId, pending, { outcome: { outcome: "cancelled" } });
711
+ }
712
+ }
713
+ }
714
+ resolvePermission(permissionId, pending, response) {
715
+ this.permissions.delete(permissionId);
716
+ pending.resolve(response);
557
717
  this.emit({
558
718
  type: "session.permission_resolved",
559
719
  sessionId: this.options.boundarySessionId,
560
720
  permissionId,
561
721
  });
722
+ if (this.activePrompt?.deferred)
723
+ this.scheduleDeferredSettle();
562
724
  }
563
725
  async configure(changes) {
726
+ const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
727
+ if (autoAcceptMode &&
728
+ changes.mode !== undefined &&
729
+ (changes.mode === autoAcceptMode.mode.id) !== this.autoAccept &&
730
+ (this.activePrompt || this.permissions.size > 0)) {
731
+ throw new Error(`Finish or stop the current turn before switching to or from ${autoAcceptMode.mode.label}.`);
732
+ }
564
733
  const requested = [];
565
734
  if (changes.model !== undefined)
566
735
  requested.push({ target: "model", value: changes.model });
@@ -573,6 +742,7 @@ class AcpRuntime {
573
742
  requested.push({ target: "setting", id, value });
574
743
  }
575
744
  const ordered = this.inAgentOrder(requested);
745
+ const previousAutoAccept = this.autoAccept;
576
746
  const previousModes = this.modes ? structuredClone(this.modes) : null;
577
747
  const previousOptions = structuredClone(this.configOptions);
578
748
  this.configTransaction = true;
@@ -598,6 +768,7 @@ class AcpRuntime {
598
768
  await this.close();
599
769
  throw failure;
600
770
  }
771
+ this.autoAccept = previousAutoAccept;
601
772
  this.modes = previousModes;
602
773
  this.configOptions = previousOptions;
603
774
  this.stagedTransformerConfig = null;
@@ -615,12 +786,21 @@ class AcpRuntime {
615
786
  }
616
787
  await this.close();
617
788
  }
618
- async close() {
619
- if (this.closing)
620
- return;
789
+ close(options) {
790
+ if (this.closePromise)
791
+ return this.closePromise;
621
792
  this.closing = true;
793
+ const promise = this.closeInternal(options).catch((error) => {
794
+ if (this.closePromise === promise)
795
+ this.closePromise = null;
796
+ throw error;
797
+ });
798
+ this.closePromise = promise;
799
+ return promise;
800
+ }
801
+ async closeInternal(options) {
622
802
  this.settlePendingWork();
623
- await this.closeConnector();
803
+ await this.closeConnector(options);
624
804
  const child = this.child;
625
805
  if (!child || this.processFailed)
626
806
  return;
@@ -639,8 +819,10 @@ class AcpRuntime {
639
819
  const requested = [];
640
820
  if (config.model)
641
821
  requested.push({ target: "model", value: config.model });
642
- if (config.mode)
643
- requested.push({ target: "mode", value: config.mode });
822
+ const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
823
+ const mode = config.mode ?? (autoAcceptMode?.default ? autoAcceptMode.mode.id : undefined);
824
+ if (mode)
825
+ requested.push({ target: "mode", value: mode });
644
826
  if (config.thinkingOption) {
645
827
  requested.push({ target: "thinking", value: config.thinkingOption });
646
828
  }
@@ -668,20 +850,40 @@ class AcpRuntime {
668
850
  if (change.target === "thinking") {
669
851
  return this.configOptions.find((option) => option.category === "thought_level")?.id;
670
852
  }
671
- return this.configOptions.find((option) => option.category === "mode")?.id;
853
+ return modeOption(this.configOptions)?.id;
672
854
  }
673
855
  async applyConfigChange(change) {
674
- const access = this.configAccess();
856
+ const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
857
+ if (change.target === "mode" &&
858
+ autoAcceptMode &&
859
+ (this.autoAccept || change.value === autoAcceptMode.mode.id)) {
860
+ const enableAutoAccept = change.value === autoAcceptMode.mode.id;
861
+ const nativeMode = enableAutoAccept ? autoAcceptMode.nativeMode : change.value;
862
+ this.autoAccept = false;
863
+ if (nativeMode !== this.nativeModeId()) {
864
+ await this.applyNativeConfigChange({ target: "mode", value: nativeMode });
865
+ }
866
+ if (nativeMode !== this.nativeModeId()) {
867
+ throw new Error(`ACP agent did not switch to mode '${nativeMode}'`);
868
+ }
869
+ this.autoAccept = enableAutoAccept;
870
+ return;
871
+ }
872
+ const context = {
873
+ ...this.configContext(),
874
+ catalog: () => toProviderCatalog(this.modes, this.configOptions),
875
+ apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
876
+ };
675
877
  for (const transformer of this.transformers) {
676
- if ((await transformer.configure?.(change, {
677
- sessionId: this.options.boundarySessionId,
678
- config: access,
679
- })) === "handled") {
878
+ if ((await transformer.configure?.(change, context)) === "handled") {
680
879
  return;
681
880
  }
682
881
  }
683
- if (change.target === "mode") {
684
- if (!change.value || !this.modes) {
882
+ await this.applyNativeConfigChange(change);
883
+ }
884
+ async applyNativeConfigChange(change) {
885
+ if (change.target === "mode" && this.modes && !modeOption(this.configOptions)) {
886
+ if (!change.value) {
685
887
  throw new Error("ACP session does not expose mode configuration");
686
888
  }
687
889
  await this.call(this.connection.setSessionMode({
@@ -707,6 +909,13 @@ class AcpRuntime {
707
909
  }));
708
910
  this.configOptions = response.configOptions;
709
911
  }
912
+ configContext() {
913
+ return {
914
+ sessionId: this.options.boundarySessionId,
915
+ config: this.configAccess(),
916
+ request: this.request,
917
+ };
918
+ }
710
919
  configAccess() {
711
920
  return {
712
921
  read: async () => configValues(this.configOptions),
@@ -728,7 +937,24 @@ class AcpRuntime {
728
937
  return;
729
938
  this.emitConfigSnapshot(toProviderConfigState(this.modes, this.configOptions));
730
939
  }
940
+ nativeModeId() {
941
+ return selectedValue(modeOption(this.configOptions)) ?? this.modes?.currentModeId;
942
+ }
731
943
  emitConfigSnapshot(config) {
944
+ const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
945
+ if (autoAcceptMode) {
946
+ if (this.nativeModeId() !== autoAcceptMode.nativeMode)
947
+ this.autoAccept = false;
948
+ config = {
949
+ ...config,
950
+ mode: this.autoAccept ? autoAcceptMode.mode.id : config.mode,
951
+ modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }],
952
+ };
953
+ }
954
+ const context = { sessionId: this.options.boundarySessionId };
955
+ for (const transformer of this.transformers) {
956
+ config = transformer.config?.(config, context) ?? config;
957
+ }
732
958
  this.emit({
733
959
  type: "session.config",
734
960
  sessionId: this.options.boundarySessionId,
@@ -736,7 +962,9 @@ class AcpRuntime {
736
962
  });
737
963
  }
738
964
  async restoreConfig(modes, options) {
739
- if (modes?.currentModeId && this.modes?.currentModeId !== modes.currentModeId) {
965
+ if (!modeOption(options) &&
966
+ modes?.currentModeId &&
967
+ this.modes?.currentModeId !== modes.currentModeId) {
740
968
  await this.call(this.connection.setSessionMode({
741
969
  sessionId: this.nativeSessionId,
742
970
  modeId: modes.currentModeId,
@@ -754,10 +982,26 @@ class AcpRuntime {
754
982
  }));
755
983
  }
756
984
  }
757
- requestPermission(request) {
985
+ async requestPermission(request) {
986
+ await this.notificationLane;
987
+ if (this.closing || this.processFailed || this.activePrompt?.cancelling) {
988
+ return { outcome: { outcome: "cancelled" } };
989
+ }
990
+ if (this.autoAccept &&
991
+ request.sessionId === this.nativeSessionId &&
992
+ this.nativeModeId() === this.options.options.acpOptions?.autoAcceptMode?.nativeMode) {
993
+ const allowOptions = request.options.filter((option) => option.kind.startsWith("allow"));
994
+ const allowOnce = allowOptions.find((option) => option.kind === "allow_once");
995
+ if (allowOnce &&
996
+ new Set(allowOptions.map((option) => option.kind)).size === allowOptions.length) {
997
+ return { outcome: { outcome: "selected", optionId: allowOnce.optionId } };
998
+ }
999
+ }
758
1000
  const permissionId = `permission:${request.toolCall.toolCallId}`;
759
1001
  return new Promise((resolve) => {
760
- this.permissions.set(permissionId, { request, resolve });
1002
+ this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
1003
+ if (this.activePrompt?.deferred)
1004
+ this.scheduleDeferredSettle();
761
1005
  this.emit({
762
1006
  type: "session.permission",
763
1007
  sessionId: this.options.boundarySessionId,
@@ -776,19 +1020,50 @@ class AcpRuntime {
776
1020
  });
777
1021
  });
778
1022
  }
779
- sessionUpdate(notification) {
1023
+ observeWireMessage(message) {
1024
+ if (typeof message !== "object" || message === null)
1025
+ return;
1026
+ const record = message;
1027
+ if (record.method === "session/update") {
1028
+ this.sessionUpdateWireSeqs.push(++this.incomingWireSeq);
1029
+ return;
1030
+ }
1031
+ if (!("method" in record) &&
1032
+ "id" in record &&
1033
+ typeof record.result === "object" &&
1034
+ record.result !== null &&
1035
+ typeof record.result.stopReason === "string" &&
1036
+ this.activePrompt &&
1037
+ this.activePrompt.lastPromptResponseWireSeq === null) {
1038
+ this.activePrompt.lastPromptResponseWireSeq = ++this.incomingWireSeq;
1039
+ }
1040
+ }
1041
+ isPostWirePrompt(active, wireSeq) {
1042
+ return active.lastPromptResponseWireSeq !== null && wireSeq > active.lastPromptResponseWireSeq;
1043
+ }
1044
+ sessionUpdate(notification, wireSeq) {
780
1045
  if (notification.sessionId !== this.nativeSessionId)
781
1046
  return;
782
- if (this.replayWindow === "skip")
1047
+ if (this.replayWindow)
1048
+ this.lastLoadUpdateAt = performance.now();
1049
+ if (this.replayWindow === "skip") {
1050
+ const update = notification.update;
1051
+ if (update.sessionUpdate === "available_commands_update" ||
1052
+ update.sessionUpdate === "config_option_update" ||
1053
+ update.sessionUpdate === "current_mode_update" ||
1054
+ update.sessionUpdate === "usage_update") {
1055
+ this.reduceStateUpdate(update, wireSeq);
1056
+ }
783
1057
  return;
1058
+ }
784
1059
  if (this.replayWindow === "replay" &&
785
1060
  notification.update.sessionUpdate === "user_message_chunk") {
786
1061
  this.reduceUserMessageChunk(notification.update);
787
1062
  return;
788
1063
  }
789
- this.reduceUpdate(notification.update);
1064
+ this.reduceUpdate(notification.update, wireSeq);
790
1065
  }
791
- reduceUpdate(update) {
1066
+ reduceUpdate(update, wireSeq) {
792
1067
  if (update.sessionUpdate === "agent_message_chunk" ||
793
1068
  update.sessionUpdate === "agent_thought_chunk" ||
794
1069
  update.sessionUpdate === "user_message_chunk") {
@@ -819,17 +1094,18 @@ class AcpRuntime {
819
1094
  : {}),
820
1095
  },
821
1096
  });
1097
+ this.noteDeferredChunk(update.sessionUpdate, wireSeq);
822
1098
  return;
823
1099
  }
824
1100
  if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
825
1101
  if (update.sessionUpdate === "tool_call")
826
1102
  this.fallbackChunkIds.clear();
827
- this.reduceToolCall(update);
1103
+ this.reduceToolCall(update, wireSeq);
828
1104
  return;
829
1105
  }
830
1106
  if (update.sessionUpdate === "plan")
831
1107
  this.fallbackChunkIds.clear();
832
- this.reduceStateUpdate(update);
1108
+ this.reduceStateUpdate(update, wireSeq);
833
1109
  }
834
1110
  // Historical user messages arrive only as replayed chunks; a live prompt
835
1111
  // already echoes its own user message when it is admitted.
@@ -866,7 +1142,7 @@ class AcpRuntime {
866
1142
  }
867
1143
  return id;
868
1144
  }
869
- reduceStateUpdate(update) {
1145
+ reduceStateUpdate(update, wireSeq) {
870
1146
  if (update.sessionUpdate === "plan") {
871
1147
  this.emit({
872
1148
  type: "timeline.item",
@@ -885,17 +1161,28 @@ class AcpRuntime {
885
1161
  return;
886
1162
  }
887
1163
  if (update.sessionUpdate === "available_commands_update") {
888
- const commands = update.availableCommands.map((command) => ({
889
- name: command.name,
890
- description: command.description,
891
- argumentHint: command.input?.hint,
892
- }));
1164
+ const context = { sessionId: this.options.boundarySessionId };
1165
+ const commands = update.availableCommands.map((command) => {
1166
+ let entry = {
1167
+ name: command.name,
1168
+ description: command.description,
1169
+ argumentHint: command.input?.hint,
1170
+ };
1171
+ for (const transformer of this.transformers) {
1172
+ entry = transformer.command?.(entry, context) ?? entry;
1173
+ }
1174
+ return entry;
1175
+ });
893
1176
  this.emit({ type: "session.commands", sessionId: this.options.boundarySessionId, commands });
1177
+ this.receivedInitialCommands = true;
894
1178
  this.commandWaiter?.();
895
- this.commandWaiter = null;
896
1179
  return;
897
1180
  }
898
1181
  if (update.sessionUpdate === "current_mode_update") {
1182
+ const option = modeOption(this.configOptions);
1183
+ if (option?.type === "select") {
1184
+ this.configOptions = this.configOptions.map((candidate) => candidate === option ? { ...option, currentValue: update.currentModeId } : candidate);
1185
+ }
899
1186
  if (this.modes)
900
1187
  this.modes = { ...this.modes, currentModeId: update.currentModeId };
901
1188
  this.emitConfig();
@@ -918,6 +1205,7 @@ class AcpRuntime {
918
1205
  sessionId: this.options.boundarySessionId,
919
1206
  usage: this.lastUsage,
920
1207
  });
1208
+ this.noteDeferredUsageUpdate(wireSeq);
921
1209
  return;
922
1210
  }
923
1211
  if (update.sessionUpdate === "compaction_update") {
@@ -934,17 +1222,29 @@ class AcpRuntime {
934
1222
  status: update.status === "completed" ? "completed" : "loading",
935
1223
  },
936
1224
  });
1225
+ if (this.activePrompt?.deferred)
1226
+ this.scheduleDeferredSettle();
937
1227
  }
938
1228
  }
939
- terminalizeTransientItems(state) {
940
- for (const [id, snapshot] of this.toolCalls) {
1229
+ terminalizeTransientItems(state, options) {
1230
+ const preserve = options?.preserveQualifyingOpenTools === true;
1231
+ for (const [id, tool] of this.toolCalls) {
1232
+ const snapshot = tool.presentation;
941
1233
  if (snapshot.status !== "pending" && snapshot.status !== "in_progress")
942
1234
  continue;
1235
+ if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot))
1236
+ continue;
1237
+ this.liveOpenToolIds.delete(id);
1238
+ if (options?.suppressTrailingToolEcho)
1239
+ this.canceledToolCallIds.add(id);
943
1240
  const completed = {
944
1241
  ...snapshot,
945
1242
  status: state === "completed" ? "completed" : "failed",
946
1243
  };
947
- this.toolCalls.set(id, completed);
1244
+ this.toolCalls.set(id, {
1245
+ source: { ...tool.source, status: completed.status },
1246
+ presentation: completed,
1247
+ });
948
1248
  this.emit({
949
1249
  type: "timeline.item",
950
1250
  sessionId: this.options.boundarySessionId,
@@ -968,18 +1268,53 @@ class AcpRuntime {
968
1268
  }
969
1269
  this.pendingCompactions.clear();
970
1270
  }
971
- reduceToolCall(update) {
972
- const current = this.toolCalls.get(update.toolCallId);
973
- let snapshot = mergeToolCallSnapshot(update, current);
974
- const context = { sessionId: this.options.boundarySessionId };
1271
+ reduceToolCall(update, wireSeq) {
1272
+ if (update.sessionUpdate === "tool_call_update" &&
1273
+ this.canceledToolCallIds.has(update.toolCallId)) {
1274
+ return;
1275
+ }
1276
+ if (update.sessionUpdate === "tool_call") {
1277
+ this.canceledToolCallIds.delete(update.toolCallId);
1278
+ }
1279
+ const tool = this.toolCalls.get(update.toolCallId);
1280
+ const current = tool?.presentation;
1281
+ const wasOpenQualifying = current !== undefined &&
1282
+ this.liveOpenToolIds.has(current.id) &&
1283
+ this.toolKeepsTurnOpen(current);
1284
+ const source = mergeToolCallSnapshot(update, tool?.source);
1285
+ let snapshot = source;
1286
+ const context = {
1287
+ sessionId: this.options.boundarySessionId,
1288
+ mcpServerNames: this.mcpServerNames,
1289
+ };
975
1290
  for (const transformer of this.transformers)
976
1291
  snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
977
- this.toolCalls.set(snapshot.id, snapshot);
1292
+ if (!snapshot.detail && source.diff && snapshot.kind === "edit") {
1293
+ snapshot = {
1294
+ ...snapshot,
1295
+ detail: {
1296
+ type: "edit",
1297
+ filePath: source.diff.path,
1298
+ oldString: source.diff.oldText ?? undefined,
1299
+ newString: source.diff.newText,
1300
+ },
1301
+ };
1302
+ }
1303
+ this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
1304
+ const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
1305
+ if (this.replayWindow === null) {
1306
+ if (isOpen)
1307
+ this.liveOpenToolIds.add(snapshot.id);
1308
+ else
1309
+ this.liveOpenToolIds.delete(snapshot.id);
1310
+ }
978
1311
  this.emit({
979
1312
  type: "timeline.item",
980
1313
  sessionId: this.options.boundarySessionId,
981
1314
  item: toolTimelineItem(snapshot),
982
1315
  });
1316
+ const isOpenQualifying = this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot);
1317
+ this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq);
983
1318
  }
984
1319
  vendorNotification(method, params) {
985
1320
  const notification = { method, params: jsonValue(params) };
@@ -1047,38 +1382,310 @@ class AcpRuntime {
1047
1382
  handleUnexpectedTransportClose() {
1048
1383
  if (this.closing || this.processFailed)
1049
1384
  return;
1385
+ const message = "ACP transport closed unexpectedly";
1050
1386
  this.processFailed = true;
1051
- this.settlePendingWork();
1387
+ this.settlePendingWork(message);
1052
1388
  if (!this.nativeSessionId)
1053
1389
  return;
1054
1390
  this.emit({
1055
1391
  type: "session.runtime_failed",
1056
1392
  sessionId: this.options.boundarySessionId,
1057
- error: { message: "ACP transport closed unexpectedly" },
1393
+ error: { message },
1058
1394
  });
1059
1395
  }
1060
- settlePendingWork() {
1396
+ settlePendingWork(failureMessage) {
1061
1397
  for (const permission of this.permissions.values()) {
1062
1398
  permission.resolve({ outcome: { outcome: "cancelled" } });
1063
1399
  }
1064
1400
  this.permissions.clear();
1401
+ if (this.activePrompt?.deferred) {
1402
+ this.finishDeferredTurn(this.activePrompt, failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" });
1403
+ }
1065
1404
  this.commandWaiter?.();
1066
1405
  this.commandWaiter = null;
1067
1406
  }
1407
+ finishPromptTurn(turnId, state, error, options) {
1408
+ this.fallbackChunkIds.clear();
1409
+ this.terminalizeTransientItems(state, options);
1410
+ this.finishTurnPermissions(turnId);
1411
+ if (state === "failed") {
1412
+ this.emit({
1413
+ type: "session.turn",
1414
+ sessionId: this.options.boundarySessionId,
1415
+ turnId,
1416
+ state,
1417
+ error: error ?? { message: "ACP turn failed" },
1418
+ });
1419
+ return;
1420
+ }
1421
+ this.emit({
1422
+ type: "session.turn",
1423
+ sessionId: this.options.boundarySessionId,
1424
+ turnId,
1425
+ state,
1426
+ });
1427
+ }
1428
+ steerDeferredPrompt(input) {
1429
+ const active = this.activePrompt;
1430
+ const deferred = active?.deferred;
1431
+ if (!active || !deferred || active.cancelling || this.closing || this.processFailed) {
1432
+ this.emit({
1433
+ type: "session.prompt_result",
1434
+ sessionId: this.options.boundarySessionId,
1435
+ clientMessageId: input.prompt.clientMessageId,
1436
+ result: {
1437
+ type: "failed",
1438
+ error: {
1439
+ message: "ACP session can only steer while waiting on deferred background tools",
1440
+ },
1441
+ },
1442
+ });
1443
+ return;
1444
+ }
1445
+ if (input.prompt.clearPendingPermissions) {
1446
+ this.finishTurnPermissions(active.turnId);
1447
+ }
1448
+ const prompt = toAcpPrompt(input.prompt);
1449
+ active.wirePromptsInFlight += 1;
1450
+ this.scheduleDeferredSettle();
1451
+ this.replayWindow = null;
1452
+ this.fallbackChunkIds.clear();
1453
+ this.emit({
1454
+ type: "timeline.item",
1455
+ sessionId: this.options.boundarySessionId,
1456
+ item: {
1457
+ type: "user_message",
1458
+ id: input.prompt.clientMessageId,
1459
+ text: prompt
1460
+ .filter((part) => part.type === "text")
1461
+ .map((part) => part.text)
1462
+ .join("\n"),
1463
+ clientMessageId: input.prompt.clientMessageId,
1464
+ },
1465
+ });
1466
+ this.emit({
1467
+ type: "session.prompt_result",
1468
+ sessionId: this.options.boundarySessionId,
1469
+ clientMessageId: input.prompt.clientMessageId,
1470
+ result: { type: "steer", turnId: active.turnId },
1471
+ });
1472
+ const runSteer = async () => {
1473
+ try {
1474
+ if (this.closing ||
1475
+ this.processFailed ||
1476
+ active.cancelling ||
1477
+ active.deferred !== deferred) {
1478
+ return;
1479
+ }
1480
+ this.fallbackChunkIds.clear();
1481
+ active.lastPromptResponseWireSeq = null;
1482
+ if (active.replyState === "settled_with_open_tools")
1483
+ active.replyState = "idle";
1484
+ const response = await this.call(this.connection.prompt({ sessionId: this.nativeSessionId, prompt }));
1485
+ await this.drainNotifications();
1486
+ if (this.closing || this.deferredRetirement || active.deferred !== deferred)
1487
+ return;
1488
+ if (response.usage) {
1489
+ this.lastUsage = {
1490
+ ...this.lastUsage,
1491
+ inputTokens: response.usage.inputTokens,
1492
+ outputTokens: response.usage.outputTokens,
1493
+ cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
1494
+ };
1495
+ this.emit({
1496
+ type: "session.usage",
1497
+ sessionId: this.options.boundarySessionId,
1498
+ turnId: active.turnId,
1499
+ usage: this.lastUsage,
1500
+ });
1501
+ }
1502
+ if (response.stopReason === "cancelled") {
1503
+ this.finishDeferredTurn(active, { type: "cancel" });
1504
+ return;
1505
+ }
1506
+ if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
1507
+ this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
1508
+ }
1509
+ }
1510
+ catch (error) {
1511
+ await this.drainNotifications();
1512
+ if (this.closing || this.deferredRetirement || active.deferred !== deferred)
1513
+ return;
1514
+ if (this.processFailed) {
1515
+ this.finishDeferredTurn(active, {
1516
+ type: "fail",
1517
+ error: { message: describeError(error) },
1518
+ });
1519
+ }
1520
+ else {
1521
+ this.emit({
1522
+ type: "session.notice",
1523
+ sessionId: this.options.boundarySessionId,
1524
+ notice: {
1525
+ id: `acp:steer-error:${input.prompt.clientMessageId}`,
1526
+ severity: "error",
1527
+ title: "Follow-up prompt failed",
1528
+ description: describeError(error),
1529
+ },
1530
+ });
1531
+ }
1532
+ }
1533
+ finally {
1534
+ if (active.lastPromptResponseWireSeq === null) {
1535
+ active.lastPromptResponseWireSeq = this.incomingWireSeq;
1536
+ }
1537
+ active.wirePromptsInFlight -= 1;
1538
+ this.scheduleDeferredSettle();
1539
+ }
1540
+ };
1541
+ active.wirePromptLane = active.wirePromptLane.then(runSteer);
1542
+ }
1543
+ async settleDeferredPrompt(active) {
1544
+ this.fallbackChunkIds.clear();
1545
+ const outcome = await new Promise((resolve) => {
1546
+ active.deferred = { timer: null, resolve };
1547
+ this.scheduleDeferredSettle();
1548
+ });
1549
+ if (this.closing || this.deferredRetirement)
1550
+ return;
1551
+ if (outcome.type === "fail") {
1552
+ this.finishPromptTurn(active.turnId, "failed", outcome.error);
1553
+ return;
1554
+ }
1555
+ this.finishPromptTurn(active.turnId, outcome.type === "cancel" ? "canceled" : "completed", undefined, {
1556
+ preserveQualifyingOpenTools: outcome.type === "complete" && !outcome.terminalizeTools,
1557
+ suppressTrailingToolEcho: outcome.type === "cancel",
1558
+ });
1559
+ }
1560
+ toolKeepsTurnOpen(snapshot) {
1561
+ const defer = this.options.options.acpOptions?.deferTurnOnRunningTools;
1562
+ if (!defer)
1563
+ return false;
1564
+ return defer.keepsTurnOpen ? defer.keepsTurnOpen(snapshot) : true;
1565
+ }
1566
+ hasQualifyingOpenTools() {
1567
+ for (const id of this.liveOpenToolIds) {
1568
+ const snapshot = this.toolCalls.get(id)?.presentation;
1569
+ if (snapshot && this.toolKeepsTurnOpen(snapshot))
1570
+ return true;
1571
+ }
1572
+ return false;
1573
+ }
1574
+ hasDeferredBlockers() {
1575
+ return ((this.activePrompt?.wirePromptsInFlight ?? 0) > 0 ||
1576
+ this.hasQualifyingOpenTools() ||
1577
+ this.permissions.size > 0 ||
1578
+ this.pendingCompactions.size > 0);
1579
+ }
1580
+ shouldDeferTurn(active) {
1581
+ if (!this.options.options.acpOptions?.deferTurnOnRunningTools)
1582
+ return false;
1583
+ if (active.cancelling || this.closing || this.processFailed)
1584
+ return false;
1585
+ return this.hasQualifyingOpenTools() || active.crossedEndTurn;
1586
+ }
1587
+ finishDeferredTurn(active, outcome) {
1588
+ const deferred = active.deferred;
1589
+ if (!deferred)
1590
+ return;
1591
+ if (deferred.timer)
1592
+ clearTimeout(deferred.timer);
1593
+ active.deferred = null;
1594
+ deferred.resolve(outcome);
1595
+ }
1596
+ noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq) {
1597
+ const active = this.activePrompt;
1598
+ if (!active || wasOpenQualifying === isOpenQualifying)
1599
+ return;
1600
+ if (!active.deferred && !this.isPostWirePrompt(active, wireSeq))
1601
+ return;
1602
+ if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
1603
+ active.crossedEndTurn = true;
1604
+ }
1605
+ if (isOpenQualifying)
1606
+ active.replyState = "idle";
1607
+ if (active.deferred)
1608
+ this.scheduleDeferredSettle();
1609
+ }
1610
+ noteDeferredChunk(kind, wireSeq) {
1611
+ const active = this.activePrompt;
1612
+ if (!active || !this.isPostWirePrompt(active, wireSeq))
1613
+ return;
1614
+ if (kind === "agent_message_chunk")
1615
+ active.replyState = "open";
1616
+ else if (active.replyState !== "open")
1617
+ active.replyState = "idle";
1618
+ if (active.deferred)
1619
+ this.scheduleDeferredSettle();
1620
+ }
1621
+ noteDeferredUsageUpdate(wireSeq) {
1622
+ const active = this.activePrompt;
1623
+ if (!active || !this.isPostWirePrompt(active, wireSeq) || active.replyState !== "open")
1624
+ return;
1625
+ active.replyState = this.hasQualifyingOpenTools() ? "settled_with_open_tools" : "settled";
1626
+ if (active.deferred)
1627
+ this.scheduleDeferredSettle();
1628
+ }
1629
+ scheduleDeferredSettle() {
1630
+ const active = this.activePrompt;
1631
+ const deferred = active?.deferred;
1632
+ const config = this.options.options.acpOptions?.deferTurnOnRunningTools;
1633
+ if (!active || !deferred || !config || active.cancelling)
1634
+ return;
1635
+ if (deferred.timer) {
1636
+ clearTimeout(deferred.timer);
1637
+ deferred.timer = null;
1638
+ }
1639
+ if (this.hasDeferredBlockers())
1640
+ return;
1641
+ const settled = active.replyState === "settled" || active.replyState === "settled_with_open_tools";
1642
+ const delayMs = settled
1643
+ ? (config.settleDelayMs ?? DEFAULT_DEFERRED_SETTLE_DELAY_MS)
1644
+ : (config.quietLimitMs ?? DEFAULT_DEFERRED_QUIET_LIMIT_MS);
1645
+ deferred.timer = setTimeout(() => {
1646
+ deferred.timer = null;
1647
+ void this.trySettleDeferredTurn(active, deferred);
1648
+ }, delayMs);
1649
+ }
1650
+ async trySettleDeferredTurn(active, deferred) {
1651
+ await this.drainNotifications();
1652
+ if (this.closing ||
1653
+ this.processFailed ||
1654
+ active.cancelling ||
1655
+ active.deferred !== deferred ||
1656
+ deferred.timer !== null ||
1657
+ this.hasDeferredBlockers()) {
1658
+ return;
1659
+ }
1660
+ this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
1661
+ }
1068
1662
  waitForInitialCommands() {
1663
+ if (this.receivedInitialCommands)
1664
+ return Promise.resolve();
1069
1665
  const timeoutMs = this.options.options.acpOptions?.initialCommandsTimeoutMs ?? 1000;
1070
1666
  const commands = new Promise((resolve) => {
1071
1667
  this.commandWaiter = resolve;
1072
1668
  });
1073
- const timeout = new Promise((resolve) => {
1074
- setTimeout(resolve, timeoutMs);
1075
- });
1076
- return Promise.race([commands, timeout]).finally(() => {
1669
+ return withTimeout(commands, timeoutMs, "ACP agent did not publish initial commands")
1670
+ .catch(() => undefined)
1671
+ .finally(() => {
1077
1672
  this.commandWaiter = null;
1078
1673
  });
1079
1674
  }
1675
+ async waitForLoadReplay(quietPeriod) {
1676
+ const start = performance.now();
1677
+ const deadline = start + 5 * quietPeriod;
1678
+ while (!this.closing && !this.processFailed) {
1679
+ const idleAt = Math.max(start, this.lastLoadUpdateAt) + quietPeriod;
1680
+ const remaining = Math.min(deadline, idleAt) - performance.now();
1681
+ if (remaining <= 0)
1682
+ return;
1683
+ await new Promise((resolve) => setTimeout(resolve, remaining));
1684
+ await this.notificationLane;
1685
+ }
1686
+ }
1080
1687
  }
1081
- function routeVendorNotifications(stream, receive) {
1688
+ function routeIncomingMessages(stream, receiveVendor, observeWire) {
1082
1689
  const clientMethods = new Set(Object.values(CLIENT_METHODS));
1083
1690
  return {
1084
1691
  writable: stream.writable,
@@ -1088,14 +1695,16 @@ function routeVendorNotifications(stream, receive) {
1088
1695
  // The SDK dispatches extensions asynchronously and can resolve a later response first.
1089
1696
  // Run synchronous vendor transforms in wire order, inside the configuration transaction.
1090
1697
  try {
1091
- receive(message.method, message.params);
1698
+ receiveVendor(message.method, message.params);
1092
1699
  }
1093
1700
  catch (error) {
1094
1701
  console.error("Error handling ACP vendor notification", error);
1095
1702
  }
1096
1703
  }
1097
- else
1704
+ else {
1705
+ observeWire(message);
1098
1706
  controller.enqueue(message);
1707
+ }
1099
1708
  },
1100
1709
  })),
1101
1710
  };
@@ -1113,7 +1722,7 @@ function permissionOptionBehavior(option) {
1113
1722
  function ownConnectorStream(source) {
1114
1723
  const reader = source.readable.getReader();
1115
1724
  const writer = source.writable.getWriter();
1116
- let closed = false;
1725
+ let closing = null;
1117
1726
  const stream = {
1118
1727
  readable: new ReadableStream({
1119
1728
  async pull(controller) {
@@ -1138,14 +1747,30 @@ function ownConnectorStream(source) {
1138
1747
  };
1139
1748
  return {
1140
1749
  stream,
1141
- async close() {
1142
- if (closed)
1143
- return;
1144
- closed = true;
1145
- await Promise.allSettled([
1146
- reader.cancel(new Error("Paseo closed the ACP connector")),
1147
- writer.close(),
1148
- ]);
1750
+ whenClosed: () => closing,
1751
+ async close(options) {
1752
+ if (!closing) {
1753
+ const closeWrite = options?.force
1754
+ ? writer.abort(new Error("Paseo aborted the ACP connector"))
1755
+ : writer.close();
1756
+ closing = Promise.allSettled([
1757
+ reader.cancel(new Error("Paseo closed the ACP connector")),
1758
+ closeWrite,
1759
+ ]).then((results) => {
1760
+ if (options?.timeoutMs === undefined)
1761
+ return undefined;
1762
+ const rejected = results.find((result) => result.status === "rejected");
1763
+ if (rejected)
1764
+ throw rejected.reason;
1765
+ return undefined;
1766
+ });
1767
+ }
1768
+ if (options?.timeoutMs !== undefined) {
1769
+ await withTimeout(closing, options.timeoutMs, "ACP connector did not close");
1770
+ }
1771
+ else {
1772
+ await closing.catch(() => undefined);
1773
+ }
1149
1774
  },
1150
1775
  };
1151
1776
  }
@@ -1159,6 +1784,9 @@ function mergeToolCallSnapshot(update, current) {
1159
1784
  input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
1160
1785
  output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
1161
1786
  locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [],
1787
+ diff: update.content === undefined
1788
+ ? current?.diff
1789
+ : update.content?.find((item) => item.type === "diff"),
1162
1790
  };
1163
1791
  }
1164
1792
  function firstDefined(...values) {
@@ -1210,24 +1838,29 @@ function readNativeSessionId(persistence) {
1210
1838
  function toProviderConfigState(modes, options) {
1211
1839
  const model = modelOption(options);
1212
1840
  const thinking = options.find((option) => option.category === "thought_level");
1841
+ const modeConfig = modeOption(options);
1213
1842
  return {
1214
1843
  model: selectedValue(model),
1215
- mode: modes?.currentModeId,
1844
+ mode: selectedValue(modeConfig) ?? modes?.currentModeId,
1216
1845
  thinkingOption: selectedValue(thinking),
1217
1846
  models: selectOptions(model).map((option) => ({ id: option.value, label: option.label })),
1218
- modes: modes?.availableModes.map((mode) => ({
1219
- id: mode.id,
1220
- label: mode.name,
1221
- description: mode.description ?? undefined,
1222
- })) ?? [],
1847
+ modes: modeConfig
1848
+ ? selectOptions(modeConfig).map((option) => ({
1849
+ id: option.value,
1850
+ label: option.label,
1851
+ description: option.description,
1852
+ }))
1853
+ : (modes?.availableModes.map((mode) => ({
1854
+ id: mode.id,
1855
+ label: mode.name,
1856
+ description: mode.description ?? undefined,
1857
+ })) ?? []),
1223
1858
  thinkingOptions: selectOptions(thinking).map((option) => ({
1224
1859
  id: option.value,
1225
1860
  label: option.label,
1226
1861
  })),
1227
1862
  settings: options
1228
- .filter((option) => option !== model &&
1229
- option.category !== "thought_level" &&
1230
- !(modes && option.category === "mode"))
1863
+ .filter((option) => option !== model && option.category !== "thought_level" && option !== modeConfig)
1231
1864
  .map(toProviderSetting),
1232
1865
  };
1233
1866
  }
@@ -1237,6 +1870,9 @@ function modelOption(options) {
1237
1870
  const candidates = options.filter((option) => option.category === "model");
1238
1871
  return candidates.find((option) => option.id === "model") ?? candidates[0];
1239
1872
  }
1873
+ function modeOption(options) {
1874
+ return options.find((option) => option.category === "mode" && option.type === "select");
1875
+ }
1240
1876
  function toProviderCatalog(modes, options) {
1241
1877
  const state = toProviderConfigState(modes, options);
1242
1878
  return {
@@ -1264,15 +1900,25 @@ function toProviderSetting(option) {
1264
1900
  label: option.name,
1265
1901
  description: option.description ?? undefined,
1266
1902
  value: option.currentValue,
1267
- options: selectOptions(option),
1903
+ options: selectOptions(option).map(({ label, value }) => ({ label, value })),
1268
1904
  };
1269
1905
  }
1270
1906
  function selectOptions(option) {
1271
1907
  if (!option || option.type === "boolean")
1272
1908
  return [];
1273
1909
  return option.options.flatMap((candidate) => "group" in candidate
1274
- ? candidate.options.map((nested) => ({ label: nested.name, value: nested.value }))
1275
- : [{ label: candidate.name, value: candidate.value }]);
1910
+ ? candidate.options.map((nested) => ({
1911
+ label: nested.name,
1912
+ value: nested.value,
1913
+ description: nested.description ?? undefined,
1914
+ }))
1915
+ : [
1916
+ {
1917
+ label: candidate.name,
1918
+ value: candidate.value,
1919
+ description: candidate.description ?? undefined,
1920
+ },
1921
+ ]);
1276
1922
  }
1277
1923
  function selectedValue(option) {
1278
1924
  return option && option.type !== "boolean" ? option.currentValue : undefined;
@@ -1283,15 +1929,16 @@ function configValues(options) {
1283
1929
  function toolTimelineItem(snapshot) {
1284
1930
  const input = jsonRecord(snapshot.input);
1285
1931
  const isEdit = snapshot.kind === "edit" || snapshot.name?.toLowerCase().includes("edit") === true;
1286
- const detail = isEdit
1287
- ? {
1288
- type: "edit",
1289
- filePath: typeof input.filePath === "string" ? input.filePath : (snapshot.locations[0] ?? ""),
1290
- oldString: typeof input.oldString === "string" ? input.oldString : undefined,
1291
- newString: typeof input.newString === "string" ? input.newString : undefined,
1292
- unifiedDiff: typeof input.unifiedDiff === "string" ? input.unifiedDiff : undefined,
1293
- }
1294
- : { type: "unknown", input: snapshot.input, output: snapshot.output };
1932
+ const detail = snapshot.detail ??
1933
+ (isEdit
1934
+ ? {
1935
+ type: "edit",
1936
+ filePath: typeof input.filePath === "string" ? input.filePath : (snapshot.locations[0] ?? ""),
1937
+ oldString: typeof input.oldString === "string" ? input.oldString : undefined,
1938
+ newString: typeof input.newString === "string" ? input.newString : undefined,
1939
+ unifiedDiff: typeof input.unifiedDiff === "string" ? input.unifiedDiff : undefined,
1940
+ }
1941
+ : { type: "unknown", input: snapshot.input, output: snapshot.output });
1295
1942
  const status = snapshot.status === "in_progress" || snapshot.status === "pending"
1296
1943
  ? "running"
1297
1944
  : snapshot.status;