@getpaseo/plugin 0.17.0-beta.1 → 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();
@@ -140,10 +143,14 @@ async function dispatch(input, state) {
140
143
  await mutateSession(session, () => session.runtime.prompt(input));
141
144
  return;
142
145
  }
143
- case "session.interrupt":
144
- await requireSession(state, input.sessionId).runtime.interrupt();
146
+ case "session.interrupt": {
147
+ const session = requireSession(state, input.sessionId);
148
+ const retired = await session.runtime.interrupt();
145
149
  state.emit({ type: "request.completed", requestId: input.requestId });
150
+ if (retired)
151
+ retireSession(state, input.sessionId);
146
152
  return;
153
+ }
147
154
  case "session.permission":
148
155
  requireSession(state, input.sessionId).runtime.respondToPermission(input.permissionId, input.response);
149
156
  return;
@@ -182,10 +189,10 @@ async function discover(input, state) {
182
189
  });
183
190
  try {
184
191
  let catalog = await runtime.discover(input.cwd);
185
- const config = runtime.configAccess();
192
+ const context = runtime.configContext();
186
193
  for (const transformer of state.options.transformers ?? []) {
187
194
  if (transformer.discover) {
188
- catalog = await transformer.discover(catalog, { sessionId: "catalog", config });
195
+ catalog = await transformer.discover(catalog, context);
189
196
  }
190
197
  }
191
198
  state.emit({ type: "catalog", requestId: input.requestId, catalog });
@@ -220,6 +227,11 @@ async function listSessions(input, state) {
220
227
  await runtime.close();
221
228
  }
222
229
  }
230
+ function retireSession(state, sessionId) {
231
+ if (state.sessions.delete(sessionId)) {
232
+ state.emit({ type: "session.closed", sessionId });
233
+ }
234
+ }
223
235
  async function openSession(input, state) {
224
236
  if (state.sessions.has(input.sessionId))
225
237
  throw new Error(`Session already exists: ${input.sessionId}`);
@@ -230,6 +242,7 @@ async function openSession(input, state) {
230
242
  cwd: input.config.cwd,
231
243
  env: input.config.env,
232
244
  emit: state.emit,
245
+ onRetired: () => retireSession(state, input.sessionId),
233
246
  });
234
247
  try {
235
248
  const capabilities = await runtime.open(input, state.capabilities);
@@ -260,12 +273,15 @@ function requireSession(state, sessionId) {
260
273
  throw new Error(`Unknown session: ${sessionId}`);
261
274
  return session;
262
275
  }
276
+ const DEFAULT_DEFERRED_SETTLE_DELAY_MS = 500;
277
+ const DEFAULT_DEFERRED_QUIET_LIMIT_MS = 120000;
263
278
  class AcpRuntime {
264
279
  static async start(options) {
265
280
  let child = null;
266
281
  let spawnFailure = null;
267
282
  let stream;
268
283
  let closeConnector = async () => { };
284
+ let whenConnectorClosed = () => null;
269
285
  if (options.options.command) {
270
286
  // COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
271
287
  // Standalone callers and older hosts do not send a daemon-resolved launch.
@@ -289,8 +305,9 @@ class AcpRuntime {
289
305
  const owned = ownConnectorStream(await options.options.connector());
290
306
  stream = owned.stream;
291
307
  closeConnector = owned.close;
308
+ whenConnectorClosed = owned.whenClosed;
292
309
  }
293
- const runtime = new AcpRuntime(stream, child, closeConnector, options);
310
+ const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
294
311
  try {
295
312
  const initialize = withTimeout(runtime.call(runtime.connection.initialize({
296
313
  protocolVersion: PROTOCOL_VERSION,
@@ -308,12 +325,15 @@ class AcpRuntime {
308
325
  throw error;
309
326
  }
310
327
  }
311
- constructor(stream, child, closeConnector, options) {
328
+ constructor(stream, child, closeConnector, whenConnectorClosed, options) {
312
329
  this.options = options;
313
330
  this.agentCapabilities = {};
314
331
  this.nativeSessionId = "";
315
332
  this.messages = new Map();
316
333
  this.toolCalls = new Map();
334
+ this.mcpServerNames = [];
335
+ this.liveOpenToolIds = new Set();
336
+ this.canceledToolCallIds = new Set();
317
337
  // Running tool rows published by transformers; the turn's terminal closes any left open.
318
338
  this.vendorToolCalls = new Map();
319
339
  this.pendingCompactions = new Set();
@@ -337,49 +357,62 @@ class AcpRuntime {
337
357
  this.replayWindow = null;
338
358
  this.lastLoadUpdateAt = 0;
339
359
  this.closing = false;
360
+ this.closePromise = null;
361
+ this.deferredRetirement = null;
362
+ this.deferredFinalized = false;
340
363
  this.processFailed = false;
341
364
  this.configTransaction = false;
342
365
  this.stagedTransformerConfig = null;
343
366
  this.notificationLane = Promise.resolve();
367
+ this.incomingWireSeq = 0;
368
+ this.sessionUpdateWireSeqs = [];
344
369
  this.autoAccept = false;
345
370
  this.activePrompt = null;
346
371
  this.lastUsage = {};
372
+ this.request = async (method, params) => jsonValue(await this.call(this.connection.extMethod(method, params)));
347
373
  this.child = child;
348
374
  this.closeConnector = closeConnector;
375
+ this.whenConnectorClosed = whenConnectorClosed;
349
376
  this.emit = options.emit;
350
377
  this.transformers = options.options.transformers ?? [];
351
378
  const client = {
352
379
  requestPermission: (request) => this.requestPermission(request),
353
- 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
+ },
354
384
  };
355
- 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)));
356
386
  if (!child)
357
387
  void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
358
388
  child?.on("error", (error) => {
389
+ const message = describeError(error);
359
390
  this.processFailed = true;
360
- this.settlePendingWork();
391
+ this.settlePendingWork(message);
361
392
  if (this.closing || !this.nativeSessionId)
362
393
  return;
363
394
  this.emit({
364
395
  type: "session.runtime_failed",
365
396
  sessionId: this.options.boundarySessionId,
366
- error: { message: describeError(error) },
397
+ error: { message },
367
398
  });
368
399
  });
369
400
  child?.once("close", (code, signal) => {
370
401
  if (this.closing || this.processFailed || !this.nativeSessionId)
371
402
  return;
403
+ const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
372
404
  this.processFailed = true;
373
- this.settlePendingWork();
405
+ this.settlePendingWork(message);
374
406
  this.emit({
375
407
  type: "session.runtime_failed",
376
408
  sessionId: this.options.boundarySessionId,
377
- error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
409
+ error: { message },
378
410
  });
379
411
  });
380
412
  }
381
413
  async open(input, connectionCapabilities) {
382
414
  const mcpServers = toAcpMcpServers(input.config);
415
+ this.mcpServerNames = mcpServers.map((server) => server.name);
383
416
  let nativeSessionId = readNativeSessionId(input.persistence);
384
417
  const metadata = {
385
418
  _paseo: {
@@ -471,10 +504,32 @@ class AcpRuntime {
471
504
  };
472
505
  }
473
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
+ }
474
514
  const active = this.activePrompt;
475
515
  if (active) {
476
- 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
+ }
477
529
  await active.settled;
530
+ if (this.closing || this.processFailed || this.deferredRetirement) {
531
+ throw new Error("ACP session is closed");
532
+ }
478
533
  }
479
534
  const prompt = toAcpPrompt(input.prompt);
480
535
  this.replayWindow = null;
@@ -505,10 +560,22 @@ class AcpRuntime {
505
560
  turnId,
506
561
  state: "started",
507
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
+ };
508
574
  // The SDK dispatches notifications without awaiting them, so the prompt response can resolve
509
575
  // while earlier session updates are still queued. Apply them before the turn ends.
510
576
  const settled = this.call(this.connection.prompt({ sessionId: this.nativeSessionId, prompt })).then(async (response) => {
511
577
  await this.drainNotifications();
578
+ activePrompt.wirePromptsInFlight -= 1;
512
579
  if (response.usage) {
513
580
  this.lastUsage = {
514
581
  ...this.lastUsage,
@@ -524,38 +591,39 @@ class AcpRuntime {
524
591
  });
525
592
  }
526
593
  const state = response.stopReason === "cancelled" ? "canceled" : "completed";
527
- this.fallbackChunkIds.clear();
528
- this.terminalizeTransientItems(state);
529
- this.finishTurnPermissions(turnId);
530
- this.emit({
531
- type: "session.turn",
532
- sessionId: this.options.boundarySessionId,
533
- turnId,
534
- state,
535
- });
594
+ if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
595
+ await this.settleDeferredPrompt(activePrompt);
596
+ return undefined;
597
+ }
598
+ this.finishPromptTurn(turnId, state);
536
599
  return undefined;
537
600
  }, async (error) => {
538
601
  await this.drainNotifications();
539
- this.fallbackChunkIds.clear();
540
- this.terminalizeTransientItems("failed");
541
- this.finishTurnPermissions(turnId);
542
- this.emit({
543
- type: "session.turn",
544
- sessionId: this.options.boundarySessionId,
545
- turnId,
546
- state: "failed",
547
- error: { message: describeError(error) },
548
- });
602
+ activePrompt.wirePromptsInFlight -= 1;
603
+ this.finishPromptTurn(turnId, "failed", { message: describeError(error) });
549
604
  return undefined;
550
605
  });
551
- this.activePrompt = { turnId, settled, cancelling: false };
606
+ activePrompt.settled = settled;
607
+ this.activePrompt = activePrompt;
552
608
  void settled.finally(() => {
553
609
  if (this.activePrompt?.turnId === turnId)
554
610
  this.activePrompt = null;
555
611
  });
556
612
  }
557
613
  async interrupt() {
614
+ if (this.deferredRetirement)
615
+ return this.deferredRetirement;
558
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
+ }
559
627
  if (active)
560
628
  active.cancelling = true;
561
629
  try {
@@ -563,9 +631,54 @@ class AcpRuntime {
563
631
  }
564
632
  finally {
565
633
  // An agent may wait for its outstanding permission replies before ending the prompt.
566
- if (active)
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.
567
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;
568
679
  }
680
+ this.finalizeDeferredTurn(deferredTurnId, false);
681
+ return true;
569
682
  }
570
683
  listSessions(cwd) {
571
684
  return this.call(this.connection.listSessions({ cwd }));
@@ -606,6 +719,8 @@ class AcpRuntime {
606
719
  sessionId: this.options.boundarySessionId,
607
720
  permissionId,
608
721
  });
722
+ if (this.activePrompt?.deferred)
723
+ this.scheduleDeferredSettle();
609
724
  }
610
725
  async configure(changes) {
611
726
  const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
@@ -671,12 +786,21 @@ class AcpRuntime {
671
786
  }
672
787
  await this.close();
673
788
  }
674
- async close() {
675
- if (this.closing)
676
- return;
789
+ close(options) {
790
+ if (this.closePromise)
791
+ return this.closePromise;
677
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) {
678
802
  this.settlePendingWork();
679
- await this.closeConnector();
803
+ await this.closeConnector(options);
680
804
  const child = this.child;
681
805
  if (!child || this.processFailed)
682
806
  return;
@@ -745,14 +869,13 @@ class AcpRuntime {
745
869
  this.autoAccept = enableAutoAccept;
746
870
  return;
747
871
  }
748
- const access = this.configAccess();
872
+ const context = {
873
+ ...this.configContext(),
874
+ catalog: () => toProviderCatalog(this.modes, this.configOptions),
875
+ apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
876
+ };
749
877
  for (const transformer of this.transformers) {
750
- if ((await transformer.configure?.(change, {
751
- sessionId: this.options.boundarySessionId,
752
- config: access,
753
- catalog: () => toProviderCatalog(this.modes, this.configOptions),
754
- apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
755
- })) === "handled") {
878
+ if ((await transformer.configure?.(change, context)) === "handled") {
756
879
  return;
757
880
  }
758
881
  }
@@ -786,6 +909,13 @@ class AcpRuntime {
786
909
  }));
787
910
  this.configOptions = response.configOptions;
788
911
  }
912
+ configContext() {
913
+ return {
914
+ sessionId: this.options.boundarySessionId,
915
+ config: this.configAccess(),
916
+ request: this.request,
917
+ };
918
+ }
789
919
  configAccess() {
790
920
  return {
791
921
  read: async () => configValues(this.configOptions),
@@ -821,6 +951,10 @@ class AcpRuntime {
821
951
  modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }],
822
952
  };
823
953
  }
954
+ const context = { sessionId: this.options.boundarySessionId };
955
+ for (const transformer of this.transformers) {
956
+ config = transformer.config?.(config, context) ?? config;
957
+ }
824
958
  this.emit({
825
959
  type: "session.config",
826
960
  sessionId: this.options.boundarySessionId,
@@ -866,6 +1000,8 @@ class AcpRuntime {
866
1000
  const permissionId = `permission:${request.toolCall.toolCallId}`;
867
1001
  return new Promise((resolve) => {
868
1002
  this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
1003
+ if (this.activePrompt?.deferred)
1004
+ this.scheduleDeferredSettle();
869
1005
  this.emit({
870
1006
  type: "session.permission",
871
1007
  sessionId: this.options.boundarySessionId,
@@ -884,7 +1020,28 @@ class AcpRuntime {
884
1020
  });
885
1021
  });
886
1022
  }
887
- 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) {
888
1045
  if (notification.sessionId !== this.nativeSessionId)
889
1046
  return;
890
1047
  if (this.replayWindow)
@@ -895,7 +1052,7 @@ class AcpRuntime {
895
1052
  update.sessionUpdate === "config_option_update" ||
896
1053
  update.sessionUpdate === "current_mode_update" ||
897
1054
  update.sessionUpdate === "usage_update") {
898
- this.reduceStateUpdate(update);
1055
+ this.reduceStateUpdate(update, wireSeq);
899
1056
  }
900
1057
  return;
901
1058
  }
@@ -904,9 +1061,9 @@ class AcpRuntime {
904
1061
  this.reduceUserMessageChunk(notification.update);
905
1062
  return;
906
1063
  }
907
- this.reduceUpdate(notification.update);
1064
+ this.reduceUpdate(notification.update, wireSeq);
908
1065
  }
909
- reduceUpdate(update) {
1066
+ reduceUpdate(update, wireSeq) {
910
1067
  if (update.sessionUpdate === "agent_message_chunk" ||
911
1068
  update.sessionUpdate === "agent_thought_chunk" ||
912
1069
  update.sessionUpdate === "user_message_chunk") {
@@ -937,17 +1094,18 @@ class AcpRuntime {
937
1094
  : {}),
938
1095
  },
939
1096
  });
1097
+ this.noteDeferredChunk(update.sessionUpdate, wireSeq);
940
1098
  return;
941
1099
  }
942
1100
  if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
943
1101
  if (update.sessionUpdate === "tool_call")
944
1102
  this.fallbackChunkIds.clear();
945
- this.reduceToolCall(update);
1103
+ this.reduceToolCall(update, wireSeq);
946
1104
  return;
947
1105
  }
948
1106
  if (update.sessionUpdate === "plan")
949
1107
  this.fallbackChunkIds.clear();
950
- this.reduceStateUpdate(update);
1108
+ this.reduceStateUpdate(update, wireSeq);
951
1109
  }
952
1110
  // Historical user messages arrive only as replayed chunks; a live prompt
953
1111
  // already echoes its own user message when it is admitted.
@@ -984,7 +1142,7 @@ class AcpRuntime {
984
1142
  }
985
1143
  return id;
986
1144
  }
987
- reduceStateUpdate(update) {
1145
+ reduceStateUpdate(update, wireSeq) {
988
1146
  if (update.sessionUpdate === "plan") {
989
1147
  this.emit({
990
1148
  type: "timeline.item",
@@ -1003,11 +1161,18 @@ class AcpRuntime {
1003
1161
  return;
1004
1162
  }
1005
1163
  if (update.sessionUpdate === "available_commands_update") {
1006
- const commands = update.availableCommands.map((command) => ({
1007
- name: command.name,
1008
- description: command.description,
1009
- argumentHint: command.input?.hint,
1010
- }));
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
+ });
1011
1176
  this.emit({ type: "session.commands", sessionId: this.options.boundarySessionId, commands });
1012
1177
  this.receivedInitialCommands = true;
1013
1178
  this.commandWaiter?.();
@@ -1040,6 +1205,7 @@ class AcpRuntime {
1040
1205
  sessionId: this.options.boundarySessionId,
1041
1206
  usage: this.lastUsage,
1042
1207
  });
1208
+ this.noteDeferredUsageUpdate(wireSeq);
1043
1209
  return;
1044
1210
  }
1045
1211
  if (update.sessionUpdate === "compaction_update") {
@@ -1056,17 +1222,29 @@ class AcpRuntime {
1056
1222
  status: update.status === "completed" ? "completed" : "loading",
1057
1223
  },
1058
1224
  });
1225
+ if (this.activePrompt?.deferred)
1226
+ this.scheduleDeferredSettle();
1059
1227
  }
1060
1228
  }
1061
- terminalizeTransientItems(state) {
1062
- 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;
1063
1233
  if (snapshot.status !== "pending" && snapshot.status !== "in_progress")
1064
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);
1065
1240
  const completed = {
1066
1241
  ...snapshot,
1067
1242
  status: state === "completed" ? "completed" : "failed",
1068
1243
  };
1069
- this.toolCalls.set(id, completed);
1244
+ this.toolCalls.set(id, {
1245
+ source: { ...tool.source, status: completed.status },
1246
+ presentation: completed,
1247
+ });
1070
1248
  this.emit({
1071
1249
  type: "timeline.item",
1072
1250
  sessionId: this.options.boundarySessionId,
@@ -1090,18 +1268,53 @@ class AcpRuntime {
1090
1268
  }
1091
1269
  this.pendingCompactions.clear();
1092
1270
  }
1093
- reduceToolCall(update) {
1094
- const current = this.toolCalls.get(update.toolCallId);
1095
- let snapshot = mergeToolCallSnapshot(update, current);
1096
- 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
+ };
1097
1290
  for (const transformer of this.transformers)
1098
1291
  snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
1099
- 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
+ }
1100
1311
  this.emit({
1101
1312
  type: "timeline.item",
1102
1313
  sessionId: this.options.boundarySessionId,
1103
1314
  item: toolTimelineItem(snapshot),
1104
1315
  });
1316
+ const isOpenQualifying = this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot);
1317
+ this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq);
1105
1318
  }
1106
1319
  vendorNotification(method, params) {
1107
1320
  const notification = { method, params: jsonValue(params) };
@@ -1169,24 +1382,283 @@ class AcpRuntime {
1169
1382
  handleUnexpectedTransportClose() {
1170
1383
  if (this.closing || this.processFailed)
1171
1384
  return;
1385
+ const message = "ACP transport closed unexpectedly";
1172
1386
  this.processFailed = true;
1173
- this.settlePendingWork();
1387
+ this.settlePendingWork(message);
1174
1388
  if (!this.nativeSessionId)
1175
1389
  return;
1176
1390
  this.emit({
1177
1391
  type: "session.runtime_failed",
1178
1392
  sessionId: this.options.boundarySessionId,
1179
- error: { message: "ACP transport closed unexpectedly" },
1393
+ error: { message },
1180
1394
  });
1181
1395
  }
1182
- settlePendingWork() {
1396
+ settlePendingWork(failureMessage) {
1183
1397
  for (const permission of this.permissions.values()) {
1184
1398
  permission.resolve({ outcome: { outcome: "cancelled" } });
1185
1399
  }
1186
1400
  this.permissions.clear();
1401
+ if (this.activePrompt?.deferred) {
1402
+ this.finishDeferredTurn(this.activePrompt, failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" });
1403
+ }
1187
1404
  this.commandWaiter?.();
1188
1405
  this.commandWaiter = null;
1189
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
+ }
1190
1662
  waitForInitialCommands() {
1191
1663
  if (this.receivedInitialCommands)
1192
1664
  return Promise.resolve();
@@ -1213,7 +1685,7 @@ class AcpRuntime {
1213
1685
  }
1214
1686
  }
1215
1687
  }
1216
- function routeVendorNotifications(stream, receive) {
1688
+ function routeIncomingMessages(stream, receiveVendor, observeWire) {
1217
1689
  const clientMethods = new Set(Object.values(CLIENT_METHODS));
1218
1690
  return {
1219
1691
  writable: stream.writable,
@@ -1223,14 +1695,16 @@ function routeVendorNotifications(stream, receive) {
1223
1695
  // The SDK dispatches extensions asynchronously and can resolve a later response first.
1224
1696
  // Run synchronous vendor transforms in wire order, inside the configuration transaction.
1225
1697
  try {
1226
- receive(message.method, message.params);
1698
+ receiveVendor(message.method, message.params);
1227
1699
  }
1228
1700
  catch (error) {
1229
1701
  console.error("Error handling ACP vendor notification", error);
1230
1702
  }
1231
1703
  }
1232
- else
1704
+ else {
1705
+ observeWire(message);
1233
1706
  controller.enqueue(message);
1707
+ }
1234
1708
  },
1235
1709
  })),
1236
1710
  };
@@ -1248,7 +1722,7 @@ function permissionOptionBehavior(option) {
1248
1722
  function ownConnectorStream(source) {
1249
1723
  const reader = source.readable.getReader();
1250
1724
  const writer = source.writable.getWriter();
1251
- let closed = false;
1725
+ let closing = null;
1252
1726
  const stream = {
1253
1727
  readable: new ReadableStream({
1254
1728
  async pull(controller) {
@@ -1273,14 +1747,30 @@ function ownConnectorStream(source) {
1273
1747
  };
1274
1748
  return {
1275
1749
  stream,
1276
- async close() {
1277
- if (closed)
1278
- return;
1279
- closed = true;
1280
- await Promise.allSettled([
1281
- reader.cancel(new Error("Paseo closed the ACP connector")),
1282
- writer.close(),
1283
- ]);
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
+ }
1284
1774
  },
1285
1775
  };
1286
1776
  }
@@ -1294,6 +1784,9 @@ function mergeToolCallSnapshot(update, current) {
1294
1784
  input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
1295
1785
  output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
1296
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"),
1297
1790
  };
1298
1791
  }
1299
1792
  function firstDefined(...values) {