@getpaseo/plugin 0.17.0-beta.1 → 0.17.1

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,9 +242,10 @@ 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
- const capabilities = await runtime.open(input, state.capabilities);
248
+ const capabilities = await runtime.open(input, state.capabilities, state.isClosed);
236
249
  if (state.isClosed()) {
237
250
  await runtime.closeSession();
238
251
  return;
@@ -260,12 +273,16 @@ 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;
285
+ let onPartialWireRead = null;
269
286
  if (options.options.command) {
270
287
  // COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
271
288
  // Standalone callers and older hosts do not send a daemon-resolved launch.
@@ -282,15 +299,18 @@ class AcpRuntime {
282
299
  spawnFailure = new Promise((_resolve, reject) => child.once("error", reject));
283
300
  child.stderr.on("data", () => undefined);
284
301
  const output = Writable.toWeb(child.stdin);
285
- const input = Readable.toWeb(child.stdout);
302
+ const rawInput = Readable.toWeb(child.stdout);
303
+ const input = observePartialWireReads(rawInput, () => onPartialWireRead?.());
286
304
  stream = ndJsonStream(output, input);
287
305
  }
288
306
  else {
289
307
  const owned = ownConnectorStream(await options.options.connector());
290
308
  stream = owned.stream;
291
309
  closeConnector = owned.close;
310
+ whenConnectorClosed = owned.whenClosed;
292
311
  }
293
- const runtime = new AcpRuntime(stream, child, closeConnector, options);
312
+ const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
313
+ onPartialWireRead = () => runtime.notePartialWireRead();
294
314
  try {
295
315
  const initialize = withTimeout(runtime.call(runtime.connection.initialize({
296
316
  protocolVersion: PROTOCOL_VERSION,
@@ -308,12 +328,15 @@ class AcpRuntime {
308
328
  throw error;
309
329
  }
310
330
  }
311
- constructor(stream, child, closeConnector, options) {
331
+ constructor(stream, child, closeConnector, whenConnectorClosed, options) {
312
332
  this.options = options;
313
333
  this.agentCapabilities = {};
314
334
  this.nativeSessionId = "";
315
335
  this.messages = new Map();
316
336
  this.toolCalls = new Map();
337
+ this.mcpServerNames = [];
338
+ this.liveOpenToolIds = new Set();
339
+ this.canceledToolCallIds = new Set();
317
340
  // Running tool rows published by transformers; the turn's terminal closes any left open.
318
341
  this.vendorToolCalls = new Map();
319
342
  this.pendingCompactions = new Set();
@@ -335,51 +358,68 @@ class AcpRuntime {
335
358
  * Once ready, suppress late replay rows until the first prompt.
336
359
  */
337
360
  this.replayWindow = null;
338
- this.lastLoadUpdateAt = 0;
361
+ this.lastLoadHistoryAt = 0;
362
+ this.lastPartialWireAt = 0;
339
363
  this.closing = false;
364
+ this.closePromise = null;
365
+ this.deferredRetirement = null;
366
+ this.deferredFinalized = false;
340
367
  this.processFailed = false;
368
+ this.processFailureMessage = null;
341
369
  this.configTransaction = false;
342
370
  this.stagedTransformerConfig = null;
343
371
  this.notificationLane = Promise.resolve();
372
+ this.incomingWireSeq = 0;
373
+ this.sessionUpdateWireSeqs = [];
344
374
  this.autoAccept = false;
345
375
  this.activePrompt = null;
346
376
  this.lastUsage = {};
377
+ this.request = async (method, params) => jsonValue(await this.call(this.connection.extMethod(method, params)));
347
378
  this.child = child;
348
379
  this.closeConnector = closeConnector;
380
+ this.whenConnectorClosed = whenConnectorClosed;
349
381
  this.emit = options.emit;
350
382
  this.transformers = options.options.transformers ?? [];
351
383
  const client = {
352
384
  requestPermission: (request) => this.requestPermission(request),
353
- sessionUpdate: (notification) => this.enqueueNotification(() => this.sessionUpdate(notification)),
385
+ sessionUpdate: (notification) => {
386
+ const wireSeq = this.sessionUpdateWireSeqs.shift() ?? ++this.incomingWireSeq;
387
+ return this.enqueueNotification(() => this.sessionUpdate(notification, wireSeq));
388
+ },
354
389
  };
355
- this.connection = new ClientSideConnection(() => client, routeVendorNotifications(stream, (method, params) => this.vendorNotification(method, params)));
390
+ this.connection = new ClientSideConnection(() => client, routeIncomingMessages(stream, (method, params) => this.vendorNotification(method, params), (message) => this.observeWireMessage(message)));
356
391
  if (!child)
357
392
  void this.connection.closed.then(() => this.handleUnexpectedTransportClose());
358
393
  child?.on("error", (error) => {
394
+ const message = describeError(error);
359
395
  this.processFailed = true;
360
- this.settlePendingWork();
396
+ this.processFailureMessage = message;
397
+ this.settlePendingWork(message);
361
398
  if (this.closing || !this.nativeSessionId)
362
399
  return;
363
400
  this.emit({
364
401
  type: "session.runtime_failed",
365
402
  sessionId: this.options.boundarySessionId,
366
- error: { message: describeError(error) },
403
+ error: { message },
367
404
  });
368
405
  });
369
406
  child?.once("close", (code, signal) => {
370
407
  if (this.closing || this.processFailed || !this.nativeSessionId)
371
408
  return;
409
+ const message = `ACP process exited (${signal ?? code ?? "unknown"})`;
372
410
  this.processFailed = true;
373
- this.settlePendingWork();
411
+ this.processFailureMessage = message;
412
+ this.settlePendingWork(message);
374
413
  this.emit({
375
414
  type: "session.runtime_failed",
376
415
  sessionId: this.options.boundarySessionId,
377
- error: { message: `ACP process exited (${signal ?? code ?? "unknown"})` },
416
+ error: { message },
378
417
  });
379
418
  });
380
419
  }
381
- async open(input, connectionCapabilities) {
420
+ async open(input, connectionCapabilities, isConnectionClosed) {
382
421
  const mcpServers = toAcpMcpServers(input.config);
422
+ this.mcpServerNames = mcpServers.map((server) => server.name);
383
423
  let nativeSessionId = readNativeSessionId(input.persistence);
384
424
  const metadata = {
385
425
  _paseo: {
@@ -442,15 +482,21 @@ class AcpRuntime {
442
482
  cwd: input.config.cwd,
443
483
  });
444
484
  this.emitConfig();
485
+ await this.finishSessionOpen(isConnectionClosed);
486
+ return sessionCapabilities;
487
+ }
488
+ async finishSessionOpen(isConnectionClosed) {
445
489
  if (this.options.options.acpOptions?.waitForInitialCommands) {
446
490
  await this.waitForInitialCommands();
447
491
  }
448
492
  const quietPeriod = this.options.options.acpOptions?.loadReplayQuietPeriodMs;
449
493
  if (this.replayWindow && quietPeriod && quietPeriod > 0) {
450
- await this.waitForLoadReplay(quietPeriod);
494
+ await this.waitForLoadReplay(quietPeriod, isConnectionClosed);
451
495
  this.replayWindow = "skip";
452
496
  }
453
- return sessionCapabilities;
497
+ if (this.processFailed && !isConnectionClosed()) {
498
+ throw new Error(this.processFailureMessage ?? "ACP process exited during session open");
499
+ }
454
500
  }
455
501
  async discover(cwd) {
456
502
  if (cwd === undefined && this.options.options.acpOptions?.workspaceOnlyCatalog) {
@@ -471,10 +517,32 @@ class AcpRuntime {
471
517
  };
472
518
  }
473
519
  async prompt(input) {
520
+ if (this.closing || this.processFailed || this.deferredRetirement) {
521
+ throw new Error("ACP session is closed");
522
+ }
523
+ if (input.prompt.delivery === "steer") {
524
+ this.steerDeferredPrompt(input);
525
+ return;
526
+ }
474
527
  const active = this.activePrompt;
475
528
  if (active) {
476
- await this.interrupt();
529
+ if (active.deferred && active.wirePromptsInFlight === 0) {
530
+ // Wire session/prompt already resolved; finish the deferred turn without sending
531
+ // session/cancel so running background tools stay alive into the follow-up turn.
532
+ this.finishDeferredTurn(active, { type: "complete", terminalizeTools: false });
533
+ }
534
+ else {
535
+ const retired = await this.interrupt();
536
+ if (retired) {
537
+ // Notify caller that the session closed before failing the replacement prompt.
538
+ this.options.onRetired?.();
539
+ throw new Error("ACP session retired after stopping deferred background work");
540
+ }
541
+ }
477
542
  await active.settled;
543
+ if (this.closing || this.processFailed || this.deferredRetirement) {
544
+ throw new Error("ACP session is closed");
545
+ }
478
546
  }
479
547
  const prompt = toAcpPrompt(input.prompt);
480
548
  this.replayWindow = null;
@@ -505,10 +573,22 @@ class AcpRuntime {
505
573
  turnId,
506
574
  state: "started",
507
575
  });
576
+ const activePrompt = {
577
+ turnId,
578
+ settled: Promise.resolve(),
579
+ cancelling: false,
580
+ wirePromptsInFlight: 1,
581
+ wirePromptLane: Promise.resolve(),
582
+ lastPromptResponseWireSeq: null,
583
+ crossedEndTurn: false,
584
+ replyState: "idle",
585
+ deferred: null,
586
+ };
508
587
  // The SDK dispatches notifications without awaiting them, so the prompt response can resolve
509
588
  // while earlier session updates are still queued. Apply them before the turn ends.
510
589
  const settled = this.call(this.connection.prompt({ sessionId: this.nativeSessionId, prompt })).then(async (response) => {
511
590
  await this.drainNotifications();
591
+ activePrompt.wirePromptsInFlight -= 1;
512
592
  if (response.usage) {
513
593
  this.lastUsage = {
514
594
  ...this.lastUsage,
@@ -524,38 +604,39 @@ class AcpRuntime {
524
604
  });
525
605
  }
526
606
  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
- });
607
+ if (response.stopReason === "end_turn" && this.shouldDeferTurn(activePrompt)) {
608
+ await this.settleDeferredPrompt(activePrompt);
609
+ return undefined;
610
+ }
611
+ this.finishPromptTurn(turnId, state);
536
612
  return undefined;
537
613
  }, async (error) => {
538
614
  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
- });
615
+ activePrompt.wirePromptsInFlight -= 1;
616
+ this.finishPromptTurn(turnId, "failed", { message: describeError(error) });
549
617
  return undefined;
550
618
  });
551
- this.activePrompt = { turnId, settled, cancelling: false };
619
+ activePrompt.settled = settled;
620
+ this.activePrompt = activePrompt;
552
621
  void settled.finally(() => {
553
622
  if (this.activePrompt?.turnId === turnId)
554
623
  this.activePrompt = null;
555
624
  });
556
625
  }
557
626
  async interrupt() {
627
+ if (this.deferredRetirement)
628
+ return this.deferredRetirement;
558
629
  const active = this.activePrompt;
630
+ const deferredTurnId = active?.deferred ? active.turnId : null;
631
+ if (active && deferredTurnId) {
632
+ const retirement = this.retireDeferredTurn(active, deferredTurnId).catch((error) => {
633
+ if (this.deferredRetirement === retirement)
634
+ this.deferredRetirement = null;
635
+ throw error;
636
+ });
637
+ this.deferredRetirement = retirement;
638
+ return retirement;
639
+ }
559
640
  if (active)
560
641
  active.cancelling = true;
561
642
  try {
@@ -563,9 +644,54 @@ class AcpRuntime {
563
644
  }
564
645
  finally {
565
646
  // An agent may wait for its outstanding permission replies before ending the prompt.
566
- if (active)
647
+ if (active) {
648
+ this.finishTurnPermissions(active.turnId);
649
+ }
650
+ }
651
+ return false;
652
+ }
653
+ finalizeDeferredTurn(deferredTurnId, emitRetired) {
654
+ if (this.deferredFinalized)
655
+ return;
656
+ this.deferredFinalized = true;
657
+ this.finishPromptTurn(deferredTurnId, "canceled", undefined, {
658
+ suppressTrailingToolEcho: true,
659
+ });
660
+ if (emitRetired)
661
+ this.options.onRetired?.();
662
+ }
663
+ async retireDeferredTurn(active, deferredTurnId) {
664
+ active.cancelling = true;
665
+ // Record open tools owned by Stop before writing session/cancel so any failure
666
+ // update arriving during cancel preserves their canceled state.
667
+ for (const id of this.liveOpenToolIds)
668
+ this.canceledToolCallIds.add(id);
669
+ let cancelTimedOut = false;
670
+ if (!this.closing) {
671
+ try {
672
+ await withTimeout(this.call(this.connection.cancel({ sessionId: this.nativeSessionId })), 1000, `ACP session ${this.nativeSessionId} did not accept cancel`);
673
+ }
674
+ catch {
675
+ cancelTimedOut = true;
676
+ }
677
+ finally {
678
+ // An agent may wait for its outstanding permission replies before ending the prompt.
567
679
  this.finishTurnPermissions(active.turnId);
680
+ }
568
681
  }
682
+ // ACP v1 has no response or end boundary for session/cancel once session/prompt
683
+ // already returned. Close the process first while the turn still appears running,
684
+ // then emit the canceled turn synchronously before request.completed and session.closed
685
+ // so queued work and config changes immediately observe the retired session.
686
+ try {
687
+ await this.close({ force: cancelTimedOut, timeoutMs: 1000 });
688
+ }
689
+ catch (error) {
690
+ void this.whenConnectorClosed()?.then(() => this.finalizeDeferredTurn(deferredTurnId, true), () => undefined);
691
+ throw error;
692
+ }
693
+ this.finalizeDeferredTurn(deferredTurnId, false);
694
+ return true;
569
695
  }
570
696
  listSessions(cwd) {
571
697
  return this.call(this.connection.listSessions({ cwd }));
@@ -606,6 +732,8 @@ class AcpRuntime {
606
732
  sessionId: this.options.boundarySessionId,
607
733
  permissionId,
608
734
  });
735
+ if (this.activePrompt?.deferred)
736
+ this.scheduleDeferredSettle();
609
737
  }
610
738
  async configure(changes) {
611
739
  const autoAcceptMode = this.options.options.acpOptions?.autoAcceptMode;
@@ -671,12 +799,21 @@ class AcpRuntime {
671
799
  }
672
800
  await this.close();
673
801
  }
674
- async close() {
675
- if (this.closing)
676
- return;
802
+ close(options) {
803
+ if (this.closePromise)
804
+ return this.closePromise;
677
805
  this.closing = true;
806
+ const promise = this.closeInternal(options).catch((error) => {
807
+ if (this.closePromise === promise)
808
+ this.closePromise = null;
809
+ throw error;
810
+ });
811
+ this.closePromise = promise;
812
+ return promise;
813
+ }
814
+ async closeInternal(options) {
678
815
  this.settlePendingWork();
679
- await this.closeConnector();
816
+ await this.closeConnector(options);
680
817
  const child = this.child;
681
818
  if (!child || this.processFailed)
682
819
  return;
@@ -745,14 +882,13 @@ class AcpRuntime {
745
882
  this.autoAccept = enableAutoAccept;
746
883
  return;
747
884
  }
748
- const access = this.configAccess();
885
+ const context = {
886
+ ...this.configContext(),
887
+ catalog: () => toProviderCatalog(this.modes, this.configOptions),
888
+ apply: (nativeChange) => this.applyNativeConfigChange(nativeChange),
889
+ };
749
890
  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") {
891
+ if ((await transformer.configure?.(change, context)) === "handled") {
756
892
  return;
757
893
  }
758
894
  }
@@ -786,6 +922,13 @@ class AcpRuntime {
786
922
  }));
787
923
  this.configOptions = response.configOptions;
788
924
  }
925
+ configContext() {
926
+ return {
927
+ sessionId: this.options.boundarySessionId,
928
+ config: this.configAccess(),
929
+ request: this.request,
930
+ };
931
+ }
789
932
  configAccess() {
790
933
  return {
791
934
  read: async () => configValues(this.configOptions),
@@ -821,6 +964,10 @@ class AcpRuntime {
821
964
  modes: [...config.modes, { ...autoAcceptMode.mode, isUnattended: true }],
822
965
  };
823
966
  }
967
+ const context = { sessionId: this.options.boundarySessionId };
968
+ for (const transformer of this.transformers) {
969
+ config = transformer.config?.(config, context) ?? config;
970
+ }
824
971
  this.emit({
825
972
  type: "session.config",
826
973
  sessionId: this.options.boundarySessionId,
@@ -866,6 +1013,8 @@ class AcpRuntime {
866
1013
  const permissionId = `permission:${request.toolCall.toolCallId}`;
867
1014
  return new Promise((resolve) => {
868
1015
  this.permissions.set(permissionId, { request, resolve, turnId: this.activePrompt?.turnId });
1016
+ if (this.activePrompt?.deferred)
1017
+ this.scheduleDeferredSettle();
869
1018
  this.emit({
870
1019
  type: "session.permission",
871
1020
  sessionId: this.options.boundarySessionId,
@@ -884,18 +1033,36 @@ class AcpRuntime {
884
1033
  });
885
1034
  });
886
1035
  }
887
- sessionUpdate(notification) {
1036
+ observeWireMessage(message) {
1037
+ if (typeof message !== "object" || message === null)
1038
+ return;
1039
+ const record = message;
1040
+ if (record.method === "session/update") {
1041
+ this.sessionUpdateWireSeqs.push(++this.incomingWireSeq);
1042
+ return;
1043
+ }
1044
+ if (!("method" in record) &&
1045
+ "id" in record &&
1046
+ typeof record.result === "object" &&
1047
+ record.result !== null &&
1048
+ typeof record.result.stopReason === "string" &&
1049
+ this.activePrompt &&
1050
+ this.activePrompt.lastPromptResponseWireSeq === null) {
1051
+ this.activePrompt.lastPromptResponseWireSeq = ++this.incomingWireSeq;
1052
+ }
1053
+ }
1054
+ isPostWirePrompt(active, wireSeq) {
1055
+ return active.lastPromptResponseWireSeq !== null && wireSeq > active.lastPromptResponseWireSeq;
1056
+ }
1057
+ sessionUpdate(notification, wireSeq) {
888
1058
  if (notification.sessionId !== this.nativeSessionId)
889
1059
  return;
890
- if (this.replayWindow)
891
- this.lastLoadUpdateAt = performance.now();
1060
+ if (this.replayWindow && isReplayHistoryUpdate(notification.update)) {
1061
+ this.lastLoadHistoryAt = performance.now();
1062
+ }
892
1063
  if (this.replayWindow === "skip") {
893
- const update = notification.update;
894
- if (update.sessionUpdate === "available_commands_update" ||
895
- update.sessionUpdate === "config_option_update" ||
896
- update.sessionUpdate === "current_mode_update" ||
897
- update.sessionUpdate === "usage_update") {
898
- this.reduceStateUpdate(update);
1064
+ if (isSessionStateUpdate(notification.update)) {
1065
+ this.reduceStateUpdate(notification.update, wireSeq);
899
1066
  }
900
1067
  return;
901
1068
  }
@@ -904,9 +1071,9 @@ class AcpRuntime {
904
1071
  this.reduceUserMessageChunk(notification.update);
905
1072
  return;
906
1073
  }
907
- this.reduceUpdate(notification.update);
1074
+ this.reduceUpdate(notification.update, wireSeq);
908
1075
  }
909
- reduceUpdate(update) {
1076
+ reduceUpdate(update, wireSeq) {
910
1077
  if (update.sessionUpdate === "agent_message_chunk" ||
911
1078
  update.sessionUpdate === "agent_thought_chunk" ||
912
1079
  update.sessionUpdate === "user_message_chunk") {
@@ -937,17 +1104,18 @@ class AcpRuntime {
937
1104
  : {}),
938
1105
  },
939
1106
  });
1107
+ this.noteDeferredChunk(update.sessionUpdate, wireSeq);
940
1108
  return;
941
1109
  }
942
1110
  if (update.sessionUpdate === "tool_call" || update.sessionUpdate === "tool_call_update") {
943
1111
  if (update.sessionUpdate === "tool_call")
944
1112
  this.fallbackChunkIds.clear();
945
- this.reduceToolCall(update);
1113
+ this.reduceToolCall(update, wireSeq);
946
1114
  return;
947
1115
  }
948
1116
  if (update.sessionUpdate === "plan")
949
1117
  this.fallbackChunkIds.clear();
950
- this.reduceStateUpdate(update);
1118
+ this.reduceStateUpdate(update, wireSeq);
951
1119
  }
952
1120
  // Historical user messages arrive only as replayed chunks; a live prompt
953
1121
  // already echoes its own user message when it is admitted.
@@ -984,7 +1152,7 @@ class AcpRuntime {
984
1152
  }
985
1153
  return id;
986
1154
  }
987
- reduceStateUpdate(update) {
1155
+ reduceStateUpdate(update, wireSeq) {
988
1156
  if (update.sessionUpdate === "plan") {
989
1157
  this.emit({
990
1158
  type: "timeline.item",
@@ -1003,11 +1171,18 @@ class AcpRuntime {
1003
1171
  return;
1004
1172
  }
1005
1173
  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
- }));
1174
+ const context = { sessionId: this.options.boundarySessionId };
1175
+ const commands = update.availableCommands.map((command) => {
1176
+ let entry = {
1177
+ name: command.name,
1178
+ description: command.description,
1179
+ argumentHint: command.input?.hint,
1180
+ };
1181
+ for (const transformer of this.transformers) {
1182
+ entry = transformer.command?.(entry, context) ?? entry;
1183
+ }
1184
+ return entry;
1185
+ });
1011
1186
  this.emit({ type: "session.commands", sessionId: this.options.boundarySessionId, commands });
1012
1187
  this.receivedInitialCommands = true;
1013
1188
  this.commandWaiter?.();
@@ -1040,6 +1215,7 @@ class AcpRuntime {
1040
1215
  sessionId: this.options.boundarySessionId,
1041
1216
  usage: this.lastUsage,
1042
1217
  });
1218
+ this.noteDeferredUsageUpdate(wireSeq);
1043
1219
  return;
1044
1220
  }
1045
1221
  if (update.sessionUpdate === "compaction_update") {
@@ -1056,17 +1232,29 @@ class AcpRuntime {
1056
1232
  status: update.status === "completed" ? "completed" : "loading",
1057
1233
  },
1058
1234
  });
1235
+ if (this.activePrompt?.deferred)
1236
+ this.scheduleDeferredSettle();
1059
1237
  }
1060
1238
  }
1061
- terminalizeTransientItems(state) {
1062
- for (const [id, snapshot] of this.toolCalls) {
1239
+ terminalizeTransientItems(state, options) {
1240
+ const preserve = options?.preserveQualifyingOpenTools === true;
1241
+ for (const [id, tool] of this.toolCalls) {
1242
+ const snapshot = tool.presentation;
1063
1243
  if (snapshot.status !== "pending" && snapshot.status !== "in_progress")
1064
1244
  continue;
1245
+ if (preserve && this.liveOpenToolIds.has(id) && this.toolKeepsTurnOpen(snapshot))
1246
+ continue;
1247
+ this.liveOpenToolIds.delete(id);
1248
+ if (options?.suppressTrailingToolEcho)
1249
+ this.canceledToolCallIds.add(id);
1065
1250
  const completed = {
1066
1251
  ...snapshot,
1067
1252
  status: state === "completed" ? "completed" : "failed",
1068
1253
  };
1069
- this.toolCalls.set(id, completed);
1254
+ this.toolCalls.set(id, {
1255
+ source: { ...tool.source, status: completed.status },
1256
+ presentation: completed,
1257
+ });
1070
1258
  this.emit({
1071
1259
  type: "timeline.item",
1072
1260
  sessionId: this.options.boundarySessionId,
@@ -1090,18 +1278,53 @@ class AcpRuntime {
1090
1278
  }
1091
1279
  this.pendingCompactions.clear();
1092
1280
  }
1093
- reduceToolCall(update) {
1094
- const current = this.toolCalls.get(update.toolCallId);
1095
- let snapshot = mergeToolCallSnapshot(update, current);
1096
- const context = { sessionId: this.options.boundarySessionId };
1281
+ reduceToolCall(update, wireSeq) {
1282
+ if (update.sessionUpdate === "tool_call_update" &&
1283
+ this.canceledToolCallIds.has(update.toolCallId)) {
1284
+ return;
1285
+ }
1286
+ if (update.sessionUpdate === "tool_call") {
1287
+ this.canceledToolCallIds.delete(update.toolCallId);
1288
+ }
1289
+ const tool = this.toolCalls.get(update.toolCallId);
1290
+ const current = tool?.presentation;
1291
+ const wasOpenQualifying = current !== undefined &&
1292
+ this.liveOpenToolIds.has(current.id) &&
1293
+ this.toolKeepsTurnOpen(current);
1294
+ const source = mergeToolCallSnapshot(update, tool?.source);
1295
+ let snapshot = source;
1296
+ const context = {
1297
+ sessionId: this.options.boundarySessionId,
1298
+ mcpServerNames: this.mcpServerNames,
1299
+ };
1097
1300
  for (const transformer of this.transformers)
1098
1301
  snapshot = transformer.toolCall?.(snapshot, context) ?? snapshot;
1099
- this.toolCalls.set(snapshot.id, snapshot);
1302
+ if (!snapshot.detail && source.diff && snapshot.kind === "edit") {
1303
+ snapshot = {
1304
+ ...snapshot,
1305
+ detail: {
1306
+ type: "edit",
1307
+ filePath: source.diff.path,
1308
+ oldString: source.diff.oldText ?? undefined,
1309
+ newString: source.diff.newText,
1310
+ },
1311
+ };
1312
+ }
1313
+ this.toolCalls.set(snapshot.id, { source, presentation: snapshot });
1314
+ const isOpen = snapshot.status === "pending" || snapshot.status === "in_progress";
1315
+ if (this.replayWindow === null) {
1316
+ if (isOpen)
1317
+ this.liveOpenToolIds.add(snapshot.id);
1318
+ else
1319
+ this.liveOpenToolIds.delete(snapshot.id);
1320
+ }
1100
1321
  this.emit({
1101
1322
  type: "timeline.item",
1102
1323
  sessionId: this.options.boundarySessionId,
1103
1324
  item: toolTimelineItem(snapshot),
1104
1325
  });
1326
+ const isOpenQualifying = this.liveOpenToolIds.has(snapshot.id) && this.toolKeepsTurnOpen(snapshot);
1327
+ this.noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq);
1105
1328
  }
1106
1329
  vendorNotification(method, params) {
1107
1330
  const notification = { method, params: jsonValue(params) };
@@ -1169,24 +1392,284 @@ class AcpRuntime {
1169
1392
  handleUnexpectedTransportClose() {
1170
1393
  if (this.closing || this.processFailed)
1171
1394
  return;
1395
+ const message = "ACP transport closed unexpectedly";
1172
1396
  this.processFailed = true;
1173
- this.settlePendingWork();
1397
+ this.processFailureMessage = message;
1398
+ this.settlePendingWork(message);
1174
1399
  if (!this.nativeSessionId)
1175
1400
  return;
1176
1401
  this.emit({
1177
1402
  type: "session.runtime_failed",
1178
1403
  sessionId: this.options.boundarySessionId,
1179
- error: { message: "ACP transport closed unexpectedly" },
1404
+ error: { message },
1180
1405
  });
1181
1406
  }
1182
- settlePendingWork() {
1407
+ settlePendingWork(failureMessage) {
1183
1408
  for (const permission of this.permissions.values()) {
1184
1409
  permission.resolve({ outcome: { outcome: "cancelled" } });
1185
1410
  }
1186
1411
  this.permissions.clear();
1412
+ if (this.activePrompt?.deferred) {
1413
+ this.finishDeferredTurn(this.activePrompt, failureMessage ? { type: "fail", error: { message: failureMessage } } : { type: "cancel" });
1414
+ }
1187
1415
  this.commandWaiter?.();
1188
1416
  this.commandWaiter = null;
1189
1417
  }
1418
+ finishPromptTurn(turnId, state, error, options) {
1419
+ this.fallbackChunkIds.clear();
1420
+ this.terminalizeTransientItems(state, options);
1421
+ this.finishTurnPermissions(turnId);
1422
+ if (state === "failed") {
1423
+ this.emit({
1424
+ type: "session.turn",
1425
+ sessionId: this.options.boundarySessionId,
1426
+ turnId,
1427
+ state,
1428
+ error: error ?? { message: "ACP turn failed" },
1429
+ });
1430
+ return;
1431
+ }
1432
+ this.emit({
1433
+ type: "session.turn",
1434
+ sessionId: this.options.boundarySessionId,
1435
+ turnId,
1436
+ state,
1437
+ });
1438
+ }
1439
+ steerDeferredPrompt(input) {
1440
+ const active = this.activePrompt;
1441
+ const deferred = active?.deferred;
1442
+ if (!active || !deferred || active.cancelling || this.closing || this.processFailed) {
1443
+ this.emit({
1444
+ type: "session.prompt_result",
1445
+ sessionId: this.options.boundarySessionId,
1446
+ clientMessageId: input.prompt.clientMessageId,
1447
+ result: {
1448
+ type: "failed",
1449
+ error: {
1450
+ message: "ACP session can only steer while waiting on deferred background tools",
1451
+ },
1452
+ },
1453
+ });
1454
+ return;
1455
+ }
1456
+ if (input.prompt.clearPendingPermissions) {
1457
+ this.finishTurnPermissions(active.turnId);
1458
+ }
1459
+ const prompt = toAcpPrompt(input.prompt);
1460
+ active.wirePromptsInFlight += 1;
1461
+ this.scheduleDeferredSettle();
1462
+ this.replayWindow = null;
1463
+ this.fallbackChunkIds.clear();
1464
+ this.emit({
1465
+ type: "timeline.item",
1466
+ sessionId: this.options.boundarySessionId,
1467
+ item: {
1468
+ type: "user_message",
1469
+ id: input.prompt.clientMessageId,
1470
+ text: prompt
1471
+ .filter((part) => part.type === "text")
1472
+ .map((part) => part.text)
1473
+ .join("\n"),
1474
+ clientMessageId: input.prompt.clientMessageId,
1475
+ },
1476
+ });
1477
+ this.emit({
1478
+ type: "session.prompt_result",
1479
+ sessionId: this.options.boundarySessionId,
1480
+ clientMessageId: input.prompt.clientMessageId,
1481
+ result: { type: "steer", turnId: active.turnId },
1482
+ });
1483
+ const runSteer = async () => {
1484
+ try {
1485
+ if (this.closing ||
1486
+ this.processFailed ||
1487
+ active.cancelling ||
1488
+ active.deferred !== deferred) {
1489
+ return;
1490
+ }
1491
+ this.fallbackChunkIds.clear();
1492
+ active.lastPromptResponseWireSeq = null;
1493
+ if (active.replyState === "settled_with_open_tools")
1494
+ active.replyState = "idle";
1495
+ const response = await this.call(this.connection.prompt({ sessionId: this.nativeSessionId, prompt }));
1496
+ await this.drainNotifications();
1497
+ if (this.closing || this.deferredRetirement || active.deferred !== deferred)
1498
+ return;
1499
+ if (response.usage) {
1500
+ this.lastUsage = {
1501
+ ...this.lastUsage,
1502
+ inputTokens: response.usage.inputTokens,
1503
+ outputTokens: response.usage.outputTokens,
1504
+ cachedInputTokens: response.usage.cachedReadTokens ?? undefined,
1505
+ };
1506
+ this.emit({
1507
+ type: "session.usage",
1508
+ sessionId: this.options.boundarySessionId,
1509
+ turnId: active.turnId,
1510
+ usage: this.lastUsage,
1511
+ });
1512
+ }
1513
+ if (response.stopReason === "cancelled") {
1514
+ this.finishDeferredTurn(active, { type: "cancel" });
1515
+ return;
1516
+ }
1517
+ if (response.stopReason !== "end_turn" && active.wirePromptsInFlight === 1) {
1518
+ this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
1519
+ }
1520
+ }
1521
+ catch (error) {
1522
+ await this.drainNotifications();
1523
+ if (this.closing || this.deferredRetirement || active.deferred !== deferred)
1524
+ return;
1525
+ if (this.processFailed) {
1526
+ this.finishDeferredTurn(active, {
1527
+ type: "fail",
1528
+ error: { message: describeError(error) },
1529
+ });
1530
+ }
1531
+ else {
1532
+ this.emit({
1533
+ type: "session.notice",
1534
+ sessionId: this.options.boundarySessionId,
1535
+ notice: {
1536
+ id: `acp:steer-error:${input.prompt.clientMessageId}`,
1537
+ severity: "error",
1538
+ title: "Follow-up prompt failed",
1539
+ description: describeError(error),
1540
+ },
1541
+ });
1542
+ }
1543
+ }
1544
+ finally {
1545
+ if (active.lastPromptResponseWireSeq === null) {
1546
+ active.lastPromptResponseWireSeq = this.incomingWireSeq;
1547
+ }
1548
+ active.wirePromptsInFlight -= 1;
1549
+ this.scheduleDeferredSettle();
1550
+ }
1551
+ };
1552
+ active.wirePromptLane = active.wirePromptLane.then(runSteer);
1553
+ }
1554
+ async settleDeferredPrompt(active) {
1555
+ this.fallbackChunkIds.clear();
1556
+ const outcome = await new Promise((resolve) => {
1557
+ active.deferred = { timer: null, resolve };
1558
+ this.scheduleDeferredSettle();
1559
+ });
1560
+ if (this.closing || this.deferredRetirement)
1561
+ return;
1562
+ if (outcome.type === "fail") {
1563
+ this.finishPromptTurn(active.turnId, "failed", outcome.error);
1564
+ return;
1565
+ }
1566
+ this.finishPromptTurn(active.turnId, outcome.type === "cancel" ? "canceled" : "completed", undefined, {
1567
+ preserveQualifyingOpenTools: outcome.type === "complete" && !outcome.terminalizeTools,
1568
+ suppressTrailingToolEcho: outcome.type === "cancel",
1569
+ });
1570
+ }
1571
+ toolKeepsTurnOpen(snapshot) {
1572
+ const defer = this.options.options.acpOptions?.deferTurnOnRunningTools;
1573
+ if (!defer)
1574
+ return false;
1575
+ return defer.keepsTurnOpen ? defer.keepsTurnOpen(snapshot) : true;
1576
+ }
1577
+ hasQualifyingOpenTools() {
1578
+ for (const id of this.liveOpenToolIds) {
1579
+ const snapshot = this.toolCalls.get(id)?.presentation;
1580
+ if (snapshot && this.toolKeepsTurnOpen(snapshot))
1581
+ return true;
1582
+ }
1583
+ return false;
1584
+ }
1585
+ hasDeferredBlockers() {
1586
+ return ((this.activePrompt?.wirePromptsInFlight ?? 0) > 0 ||
1587
+ this.hasQualifyingOpenTools() ||
1588
+ this.permissions.size > 0 ||
1589
+ this.pendingCompactions.size > 0);
1590
+ }
1591
+ shouldDeferTurn(active) {
1592
+ if (!this.options.options.acpOptions?.deferTurnOnRunningTools)
1593
+ return false;
1594
+ if (active.cancelling || this.closing || this.processFailed)
1595
+ return false;
1596
+ return this.hasQualifyingOpenTools() || active.crossedEndTurn;
1597
+ }
1598
+ finishDeferredTurn(active, outcome) {
1599
+ const deferred = active.deferred;
1600
+ if (!deferred)
1601
+ return;
1602
+ if (deferred.timer)
1603
+ clearTimeout(deferred.timer);
1604
+ active.deferred = null;
1605
+ deferred.resolve(outcome);
1606
+ }
1607
+ noteDeferredToolTransition(wasOpenQualifying, isOpenQualifying, isOpen, snapshot, wireSeq) {
1608
+ const active = this.activePrompt;
1609
+ if (!active || wasOpenQualifying === isOpenQualifying)
1610
+ return;
1611
+ if (!active.deferred && !this.isPostWirePrompt(active, wireSeq))
1612
+ return;
1613
+ if (!active.deferred && wasOpenQualifying && !isOpen && this.toolKeepsTurnOpen(snapshot)) {
1614
+ active.crossedEndTurn = true;
1615
+ }
1616
+ if (isOpenQualifying)
1617
+ active.replyState = "idle";
1618
+ if (active.deferred)
1619
+ this.scheduleDeferredSettle();
1620
+ }
1621
+ noteDeferredChunk(kind, wireSeq) {
1622
+ const active = this.activePrompt;
1623
+ if (!active || !this.isPostWirePrompt(active, wireSeq))
1624
+ return;
1625
+ if (kind === "agent_message_chunk")
1626
+ active.replyState = "open";
1627
+ else if (active.replyState !== "open")
1628
+ active.replyState = "idle";
1629
+ if (active.deferred)
1630
+ this.scheduleDeferredSettle();
1631
+ }
1632
+ noteDeferredUsageUpdate(wireSeq) {
1633
+ const active = this.activePrompt;
1634
+ if (!active || !this.isPostWirePrompt(active, wireSeq) || active.replyState !== "open")
1635
+ return;
1636
+ active.replyState = this.hasQualifyingOpenTools() ? "settled_with_open_tools" : "settled";
1637
+ if (active.deferred)
1638
+ this.scheduleDeferredSettle();
1639
+ }
1640
+ scheduleDeferredSettle() {
1641
+ const active = this.activePrompt;
1642
+ const deferred = active?.deferred;
1643
+ const config = this.options.options.acpOptions?.deferTurnOnRunningTools;
1644
+ if (!active || !deferred || !config || active.cancelling)
1645
+ return;
1646
+ if (deferred.timer) {
1647
+ clearTimeout(deferred.timer);
1648
+ deferred.timer = null;
1649
+ }
1650
+ if (this.hasDeferredBlockers())
1651
+ return;
1652
+ const settled = active.replyState === "settled" || active.replyState === "settled_with_open_tools";
1653
+ const delayMs = settled
1654
+ ? (config.settleDelayMs ?? DEFAULT_DEFERRED_SETTLE_DELAY_MS)
1655
+ : (config.quietLimitMs ?? DEFAULT_DEFERRED_QUIET_LIMIT_MS);
1656
+ deferred.timer = setTimeout(() => {
1657
+ deferred.timer = null;
1658
+ void this.trySettleDeferredTurn(active, deferred);
1659
+ }, delayMs);
1660
+ }
1661
+ async trySettleDeferredTurn(active, deferred) {
1662
+ await this.drainNotifications();
1663
+ if (this.closing ||
1664
+ this.processFailed ||
1665
+ active.cancelling ||
1666
+ active.deferred !== deferred ||
1667
+ deferred.timer !== null ||
1668
+ this.hasDeferredBlockers()) {
1669
+ return;
1670
+ }
1671
+ this.finishDeferredTurn(active, { type: "complete", terminalizeTools: true });
1672
+ }
1190
1673
  waitForInitialCommands() {
1191
1674
  if (this.receivedInitialCommands)
1192
1675
  return Promise.resolve();
@@ -1200,20 +1683,73 @@ class AcpRuntime {
1200
1683
  this.commandWaiter = null;
1201
1684
  });
1202
1685
  }
1203
- async waitForLoadReplay(quietPeriod) {
1686
+ notePartialWireRead() {
1687
+ if (this.replayWindow)
1688
+ this.lastPartialWireAt = performance.now();
1689
+ }
1690
+ // An agent that streams history after its session/load response sends no end marker,
1691
+ // so the history ends once a quiet period passes without a history update.
1692
+ async waitForLoadReplay(quietPeriod, isConnectionClosed) {
1204
1693
  const start = performance.now();
1205
- const deadline = start + 5 * quietPeriod;
1206
- while (!this.closing && !this.processFailed) {
1207
- const idleAt = Math.max(start, this.lastLoadUpdateAt) + quietPeriod;
1208
- const remaining = Math.min(deadline, idleAt) - performance.now();
1209
- if (remaining <= 0)
1210
- return;
1211
- await new Promise((resolve) => setTimeout(resolve, remaining));
1694
+ while (!this.closing && !this.processFailed && !isConnectionClosed()) {
1695
+ const lastActivityAt = Math.max(start, this.lastLoadHistoryAt, this.lastPartialWireAt);
1696
+ const remaining = lastActivityAt + quietPeriod - performance.now();
1697
+ // A stalled event loop reaches the quiet period with history still unread in the pipe.
1698
+ // setImmediate lets the loop read pending input once before the silence is trusted.
1699
+ await new Promise((resolve) => {
1700
+ if (remaining > 0)
1701
+ setTimeout(resolve, remaining);
1702
+ else
1703
+ setImmediate(resolve);
1704
+ });
1212
1705
  await this.notificationLane;
1706
+ if (remaining <= 0 &&
1707
+ Math.max(start, this.lastLoadHistoryAt, this.lastPartialWireAt) === lastActivityAt) {
1708
+ return;
1709
+ }
1213
1710
  }
1214
1711
  }
1215
1712
  }
1216
- function routeVendorNotifications(stream, receive) {
1713
+ function observePartialWireReads(input, onPartialRead) {
1714
+ let incompleteLine = false;
1715
+ return input.pipeThrough(new TransformStream({
1716
+ transform(chunk, controller) {
1717
+ const wasIncomplete = incompleteLine;
1718
+ incompleteLine = hasTrailingIncompleteLine(chunk, incompleteLine);
1719
+ if (wasIncomplete || incompleteLine)
1720
+ onPartialRead();
1721
+ controller.enqueue(chunk);
1722
+ },
1723
+ }));
1724
+ }
1725
+ function hasTrailingIncompleteLine(chunk, incompleteLine) {
1726
+ const newline = chunk.lastIndexOf(0x0a);
1727
+ const start = newline === -1 ? 0 : newline + 1;
1728
+ if (newline !== -1)
1729
+ incompleteLine = false;
1730
+ for (let index = start; index < chunk.length; index += 1) {
1731
+ const byte = chunk[index];
1732
+ if (byte !== 0x20 && byte !== 0x09 && byte !== 0x0d)
1733
+ return true;
1734
+ }
1735
+ return incompleteLine;
1736
+ }
1737
+ function isReplayHistoryUpdate(update) {
1738
+ return (update.sessionUpdate === "user_message_chunk" ||
1739
+ update.sessionUpdate === "agent_message_chunk" ||
1740
+ update.sessionUpdate === "agent_thought_chunk" ||
1741
+ update.sessionUpdate === "tool_call" ||
1742
+ update.sessionUpdate === "tool_call_update" ||
1743
+ update.sessionUpdate === "plan" ||
1744
+ update.sessionUpdate === "compaction_update");
1745
+ }
1746
+ function isSessionStateUpdate(update) {
1747
+ return (update.sessionUpdate === "available_commands_update" ||
1748
+ update.sessionUpdate === "config_option_update" ||
1749
+ update.sessionUpdate === "current_mode_update" ||
1750
+ update.sessionUpdate === "usage_update");
1751
+ }
1752
+ function routeIncomingMessages(stream, receiveVendor, observeWire) {
1217
1753
  const clientMethods = new Set(Object.values(CLIENT_METHODS));
1218
1754
  return {
1219
1755
  writable: stream.writable,
@@ -1223,14 +1759,16 @@ function routeVendorNotifications(stream, receive) {
1223
1759
  // The SDK dispatches extensions asynchronously and can resolve a later response first.
1224
1760
  // Run synchronous vendor transforms in wire order, inside the configuration transaction.
1225
1761
  try {
1226
- receive(message.method, message.params);
1762
+ receiveVendor(message.method, message.params);
1227
1763
  }
1228
1764
  catch (error) {
1229
1765
  console.error("Error handling ACP vendor notification", error);
1230
1766
  }
1231
1767
  }
1232
- else
1768
+ else {
1769
+ observeWire(message);
1233
1770
  controller.enqueue(message);
1771
+ }
1234
1772
  },
1235
1773
  })),
1236
1774
  };
@@ -1248,7 +1786,7 @@ function permissionOptionBehavior(option) {
1248
1786
  function ownConnectorStream(source) {
1249
1787
  const reader = source.readable.getReader();
1250
1788
  const writer = source.writable.getWriter();
1251
- let closed = false;
1789
+ let closing = null;
1252
1790
  const stream = {
1253
1791
  readable: new ReadableStream({
1254
1792
  async pull(controller) {
@@ -1273,14 +1811,30 @@ function ownConnectorStream(source) {
1273
1811
  };
1274
1812
  return {
1275
1813
  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
- ]);
1814
+ whenClosed: () => closing,
1815
+ async close(options) {
1816
+ if (!closing) {
1817
+ const closeWrite = options?.force
1818
+ ? writer.abort(new Error("Paseo aborted the ACP connector"))
1819
+ : writer.close();
1820
+ closing = Promise.allSettled([
1821
+ reader.cancel(new Error("Paseo closed the ACP connector")),
1822
+ closeWrite,
1823
+ ]).then((results) => {
1824
+ if (options?.timeoutMs === undefined)
1825
+ return undefined;
1826
+ const rejected = results.find((result) => result.status === "rejected");
1827
+ if (rejected)
1828
+ throw rejected.reason;
1829
+ return undefined;
1830
+ });
1831
+ }
1832
+ if (options?.timeoutMs !== undefined) {
1833
+ await withTimeout(closing, options.timeoutMs, "ACP connector did not close");
1834
+ }
1835
+ else {
1836
+ await closing.catch(() => undefined);
1837
+ }
1284
1838
  },
1285
1839
  };
1286
1840
  }
@@ -1294,6 +1848,9 @@ function mergeToolCallSnapshot(update, current) {
1294
1848
  input: jsonValue(firstDefined(update.rawInput, current?.input, null)),
1295
1849
  output: jsonValue(firstDefined(update.rawOutput, current?.output, null)),
1296
1850
  locations: update.locations?.map((location) => location.path) ?? current?.locations ?? [],
1851
+ diff: update.content === undefined
1852
+ ? current?.diff
1853
+ : update.content?.find((item) => item.type === "diff"),
1297
1854
  };
1298
1855
  }
1299
1856
  function firstDefined(...values) {