stitchkit 0.132.1 → 0.132.3

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.
Files changed (34) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/agent-executor/acp/v1-handlers.d.ts +2 -1
  3. package/dist/agent-executor/acp/v1-handlers.d.ts.map +1 -1
  4. package/dist/agent-executor/acp/v1-permission.d.ts +2 -0
  5. package/dist/agent-executor/acp/v1-permission.d.ts.map +1 -1
  6. package/dist/agent-executor/acp/v1-probe.d.ts.map +1 -1
  7. package/dist/agent-executor/acp/v1-session-options.d.ts +19 -0
  8. package/dist/agent-executor/acp/v1-session-options.d.ts.map +1 -0
  9. package/dist/agent-executor/acp/v1-session.d.ts.map +1 -1
  10. package/dist/agent-executor/acp/v1-turn.d.ts +7 -1
  11. package/dist/agent-executor/acp/v1-turn.d.ts.map +1 -1
  12. package/dist/agent-executor/claude/session.d.ts.map +1 -1
  13. package/dist/agent-executor/claude-sdk/controls.d.ts +1 -0
  14. package/dist/agent-executor/claude-sdk/controls.d.ts.map +1 -1
  15. package/dist/agent-executor/claude-sdk/query-loop.d.ts +6 -1
  16. package/dist/agent-executor/claude-sdk/query-loop.d.ts.map +1 -1
  17. package/dist/agent-executor/claude-sdk/query-manager.d.ts +40 -0
  18. package/dist/agent-executor/claude-sdk/query-manager.d.ts.map +1 -0
  19. package/dist/agent-executor/claude-sdk/query-options.d.ts +3 -1
  20. package/dist/agent-executor/claude-sdk/query-options.d.ts.map +1 -1
  21. package/dist/agent-executor/claude-sdk/session.d.ts.map +1 -1
  22. package/dist/agent-executor/codex/handlers.d.ts +1 -1
  23. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  24. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  25. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  26. package/dist/agent-executor/codex/shared-thread.d.ts +4 -2
  27. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  28. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  29. package/dist/agent-runtime/branch-observations.d.ts +5 -5
  30. package/dist/entrypoints/agent-executor/acp.js +305 -160
  31. package/dist/entrypoints/agent-executor/claude-sdk.js +269 -171
  32. package/dist/entrypoints/agent-executor/claude.js +153 -70
  33. package/dist/entrypoints/agent-executor/codex.js +78 -28
  34. package/package.json +1 -1
@@ -719,6 +719,12 @@ var ACP_CANCELLED = { outcome: { outcome: "cancelled" } };
719
719
  var AcpOptionSelectionInputSchema = z4.strictObject({
720
720
  optionId: z4.string().min(1)
721
721
  });
722
+ function drainExternalAcpPending(externalPending) {
723
+ for (const [interactionId, pending] of [...externalPending]) {
724
+ externalPending.delete(interactionId);
725
+ pending.resolve(ACP_CANCELLED);
726
+ }
727
+ }
722
728
  function isPlainJsonRecord(value) {
723
729
  return typeof value === "object" && value !== null && !Array.isArray(value);
724
730
  }
@@ -810,6 +816,14 @@ function answerAcpSessionRequest(input) {
810
816
  // src/agent-executor/acp/v1-handlers.ts
811
817
  var JSON_RPC_INTERNAL_ERROR = -32603;
812
818
  var MAX_EXTERNAL_PENDING_REQUESTS = 256;
819
+ function isHandlersAlive(state) {
820
+ try {
821
+ state.ensureAlive();
822
+ return true;
823
+ } catch {
824
+ return false;
825
+ }
826
+ }
813
827
  function normalizeTransformedUpdates(raw, transform) {
814
828
  if (transform === undefined)
815
829
  return [raw];
@@ -856,6 +870,8 @@ function handleAcpNotification(state, externalState, method, params) {
856
870
  try {
857
871
  updates = normalizeTransformedUpdates(parsed.data.update, state.transformUpdate);
858
872
  } catch (error) {
873
+ if (!isHandlersAlive(state))
874
+ return;
859
875
  if (turn !== undefined) {
860
876
  turn.chunk += 1;
861
877
  offerTurnDelta(turn.channel, {
@@ -871,6 +887,8 @@ function handleAcpNotification(state, externalState, method, params) {
871
887
  }
872
888
  const opened = state.isOpened();
873
889
  for (const update of updates) {
890
+ if (!isHandlersAlive(state))
891
+ return;
874
892
  state.onSessionMeta({
875
893
  ...update.configOptions !== undefined && { configOptions: update.configOptions },
876
894
  ...update.sessionUpdate === "session_info_update" && typeof update.title === "string" && { title: update.title },
@@ -936,7 +954,7 @@ function handleAcpRequest(state, method, params, id) {
936
954
  resolve
937
955
  });
938
956
  });
939
- if (state.permissionRequestDelivery === "all" && state.onPermissionRequest !== undefined && turn.pending.has(interactionId)) {
957
+ if (state.permissionRequestDelivery === "all" && state.onPermissionRequest !== undefined && turn.pending.has(interactionId) && isHandlersAlive(state)) {
940
958
  const observer = state.onPermissionRequest;
941
959
  invokeSafely(() => observer({
942
960
  interactionId,
@@ -945,6 +963,7 @@ function handleAcpRequest(state, method, params, id) {
945
963
  duringActiveTurn: true,
946
964
  delta,
947
965
  async respond(reply) {
966
+ state.ensureAlive();
948
967
  answerActiveAcpTurnRequest(turn, interactionId, reply);
949
968
  }
950
969
  }));
@@ -978,6 +997,8 @@ function handleAcpRequest(state, method, params, id) {
978
997
  if (state.externalPending.get(interactionId) !== entry)
979
998
  return;
980
999
  state.externalPending.delete(interactionId);
1000
+ if (!isHandlersAlive(state))
1001
+ return;
981
1002
  if (error instanceof JsonRpcError2)
982
1003
  reject(error);
983
1004
  else
@@ -991,6 +1012,7 @@ function handleAcpRequest(state, method, params, id) {
991
1012
  duringActiveTurn: false,
992
1013
  delta,
993
1014
  async respond(reply) {
1015
+ state.ensureAlive();
994
1016
  answerAcpSessionRequest({
995
1017
  turn: undefined,
996
1018
  externalPending: state.externalPending,
@@ -1000,8 +1022,23 @@ function handleAcpRequest(state, method, params, id) {
1000
1022
  });
1001
1023
  }
1002
1024
  });
1003
- if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
1004
- Promise.resolve(outcome).catch(onObserverError);
1025
+ const thenable = typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function";
1026
+ if (!isHandlersAlive(state)) {
1027
+ if (state.externalPending.get(interactionId) === entry) {
1028
+ state.externalPending.delete(interactionId);
1029
+ }
1030
+ if (thenable)
1031
+ Promise.resolve(outcome).catch(() => {
1032
+ return;
1033
+ });
1034
+ return;
1035
+ }
1036
+ if (thenable) {
1037
+ Promise.resolve(outcome).then(() => {
1038
+ if (!isHandlersAlive(state) && state.externalPending.get(interactionId) === entry) {
1039
+ state.externalPending.delete(interactionId);
1040
+ }
1041
+ }, onObserverError);
1005
1042
  }
1006
1043
  } catch (error) {
1007
1044
  onObserverError(error);
@@ -1013,13 +1050,70 @@ function createAcpHandlers(state) {
1013
1050
  chunk: 0,
1014
1051
  track: { segment: 0, toolNames: new Map }
1015
1052
  };
1053
+ const dropClosedRequest = () => new Promise(() => {
1054
+ return;
1055
+ });
1016
1056
  return {
1017
- onNotification: (method, params) => handleAcpNotification(state, externalState, method, params),
1018
- onRequest: (method, params, id) => handleAcpRequest(state, method, params, id),
1057
+ onNotification: (method, params) => {
1058
+ if (!isHandlersAlive(state))
1059
+ return;
1060
+ handleAcpNotification(state, externalState, method, params);
1061
+ },
1062
+ onRequest: (method, params, id) => {
1063
+ if (!isHandlersAlive(state))
1064
+ return dropClosedRequest();
1065
+ return handleAcpRequest(state, method, params, id);
1066
+ },
1019
1067
  onEnd: state.onEnd
1020
1068
  };
1021
1069
  }
1022
1070
 
1071
+ // src/agent-executor/acp/v1-session-options.ts
1072
+ function optionOf(options, category) {
1073
+ return options.find((option) => option.category === category) ?? options.find((option) => option.id === category);
1074
+ }
1075
+ function mergeInitialAcpConfigOptions(current, incoming, sawConfigOptionUpdate) {
1076
+ if (incoming == null)
1077
+ return current;
1078
+ if (!sawConfigOptionUpdate || current.length === 0 && incoming.length > 0) {
1079
+ return incoming;
1080
+ }
1081
+ return current;
1082
+ }
1083
+ async function setAcpConfigOption(peer, sessionId, options, category, value, signal) {
1084
+ const option = optionOf(options, category);
1085
+ if (option === undefined)
1086
+ throw new Error(`The ACP agent offers no ${category} option`);
1087
+ const values = acpOptionValues(option);
1088
+ if (values.length > 0 && !values.includes(value)) {
1089
+ throw new Error(`The ACP agent's ${category} option has no value ${value} (offered: ${values.join(", ")})`);
1090
+ }
1091
+ const answer = AcpSetConfigOptionResultSchema.parse(await peer.request("session/set_config_option", { sessionId, configId: option.id, value }, signal !== undefined ? { signal } : undefined));
1092
+ return answer.configOptions ?? options;
1093
+ }
1094
+ async function applyAcpSessionSelections(input) {
1095
+ let options = input.configOptions;
1096
+ const setCat = (category, value) => setAcpConfigOption(input.peer, input.sessionId, options, category, value, input.signal);
1097
+ if (input.model !== undefined) {
1098
+ if (optionOf(options, "model") !== undefined) {
1099
+ options = await setCat("model", input.model);
1100
+ } else if (input.models !== undefined && input.models !== null) {
1101
+ const available = input.models.availableModels?.map((entry) => entry.modelId) ?? [];
1102
+ if (available.length > 0 && !available.includes(input.model)) {
1103
+ throw new Error(`The ACP agent's model option has no value ${input.model} (offered: ${available.join(", ")})`);
1104
+ }
1105
+ await input.peer.request("session/set_model", { sessionId: input.sessionId, modelId: input.model }, { signal: input.signal });
1106
+ } else {
1107
+ throw new Error("The ACP agent offers no model option");
1108
+ }
1109
+ }
1110
+ if (input.thoughtLevel !== undefined)
1111
+ options = await setCat("thought_level", input.thoughtLevel);
1112
+ if (input.mode !== undefined)
1113
+ options = await setCat("mode", input.mode);
1114
+ return options;
1115
+ }
1116
+
1023
1117
  // src/agent-executor/acp/v1-probe.ts
1024
1118
  var DEFAULT_PROBE_TIMEOUT_MS = 30000;
1025
1119
  var ProbeSessionId = AcpNewSessionResultSchema.pick({ sessionId: true });
@@ -1134,9 +1228,7 @@ async function probeAcpCapabilities(config, input) {
1134
1228
  let result;
1135
1229
  try {
1136
1230
  const session = await readProbeSession(config, connection, input.cwd, deadlineSignal);
1137
- if (session.configOptions != null && (!sawConfigOptionUpdate || configOptions.length === 0 && session.configOptions.length > 0)) {
1138
- configOptions = session.configOptions;
1139
- }
1231
+ configOptions = mergeInitialAcpConfigOptions(configOptions, session.configOptions, sawConfigOptionUpdate);
1140
1232
  deadlineSignal.throwIfAborted();
1141
1233
  const models = extractProbeModels(configOptions, session.models?.availableModels);
1142
1234
  result = {
@@ -1175,11 +1267,23 @@ function newAcpTurn(turnId) {
1175
1267
  settled: false
1176
1268
  };
1177
1269
  }
1270
+ function settleAcpTurn(turn, reason, sendCancelled) {
1271
+ if (turn === undefined)
1272
+ return;
1273
+ turn.settled = true;
1274
+ if (sendCancelled) {
1275
+ loseEngineTurn(turn, () => ACP_CANCELLED, reason);
1276
+ return;
1277
+ }
1278
+ turn.pending.clear();
1279
+ turn.channel.fail(reason);
1280
+ }
1178
1281
  function runAcpPrompt(input) {
1179
- const { peer, sessionId, prompt, turn, generation, checkOutcome, done } = input;
1282
+ const { peer, sessionId, prompt, turn, generation, ensureAlive, checkOutcome, done } = input;
1180
1283
  peer.request("session/prompt", { sessionId, prompt: [...prompt] }, { timeoutMs: null }).then(async (result) => {
1181
1284
  if (turn.settled)
1182
1285
  return;
1286
+ ensureAlive();
1183
1287
  const parsed = AcpPromptResultSchema.parse(result);
1184
1288
  if (parsed.usage !== undefined && parsed.usage !== null) {
1185
1289
  turn.accumulatedUsage = addAcpTokenUsage(turn.accumulatedUsage, normalizeAcpUsage(parsed.usage, {
@@ -1193,6 +1297,7 @@ function runAcpPrompt(input) {
1193
1297
  const rawOverride = !turn.state.interruptRequested && checkOutcome !== undefined ? await checkOutcome(parsed) : undefined;
1194
1298
  if (turn.settled || generation !== turn.promptGeneration)
1195
1299
  return;
1300
+ ensureAlive();
1196
1301
  const override = rawOverride !== undefined ? AcpPromptOutcomeOverrideSchema.parse(rawOverride) : undefined;
1197
1302
  const outcome = override !== undefined ? "failed" : acpOutcome(parsed.stopReason, turn.state.interruptRequested);
1198
1303
  const raw = { source: "acp", type: `session/prompt/${parsed.stopReason}` };
@@ -1242,8 +1347,21 @@ function runAcpPrompt(input) {
1242
1347
  if (turn.settled || generation !== turn.promptGeneration)
1243
1348
  return;
1244
1349
  turn.settled = true;
1245
- const kind = classifyAcpRpcRefusal(error);
1246
- if (kind !== undefined && error instanceof Error) {
1350
+ let failure = error;
1351
+ let alive = true;
1352
+ try {
1353
+ ensureAlive();
1354
+ } catch (aliveError) {
1355
+ alive = false;
1356
+ failure = aliveError;
1357
+ }
1358
+ if (!alive) {
1359
+ settleAcpTurn(turn, failure, false);
1360
+ done();
1361
+ return;
1362
+ }
1363
+ const kind = classifyAcpRpcRefusal(failure);
1364
+ if (kind !== undefined && failure instanceof Error) {
1247
1365
  const raw = { source: "acp", type: "session/prompt" };
1248
1366
  endEngineTurn(turn, () => ACP_CANCELLED, [
1249
1367
  {
@@ -1252,7 +1370,7 @@ function runAcpPrompt(input) {
1252
1370
  itemId: "failure",
1253
1371
  raw,
1254
1372
  kind,
1255
- message: error.message
1373
+ message: failure.message
1256
1374
  },
1257
1375
  {
1258
1376
  type: "turn-end",
@@ -1263,20 +1381,28 @@ function runAcpPrompt(input) {
1263
1381
  }
1264
1382
  ]);
1265
1383
  } else {
1266
- loseEngineTurn(turn, () => ACP_CANCELLED, error);
1384
+ loseEngineTurn(turn, () => ACP_CANCELLED, failure);
1267
1385
  }
1268
1386
  done();
1269
1387
  });
1270
1388
  }
1271
- function acpTurnHandle(peer, sessionId, turn) {
1389
+ function acpTurnHandle(peer, sessionId, turn, ensureAlive) {
1272
1390
  return {
1273
1391
  deltas: turn.channel,
1274
1392
  async interrupt() {
1393
+ if (turn.settled)
1394
+ return;
1395
+ try {
1396
+ ensureAlive();
1397
+ } catch {
1398
+ return;
1399
+ }
1275
1400
  turn.state.interruptRequested = true;
1276
1401
  peer.notify("session/cancel", { sessionId });
1277
1402
  drainEngineRequests(turn, () => ACP_CANCELLED);
1278
1403
  },
1279
1404
  async respond(interactionId, rawReply) {
1405
+ ensureAlive();
1280
1406
  answerActiveAcpTurnRequest(turn, interactionId, rawReply);
1281
1407
  }
1282
1408
  };
@@ -1299,6 +1425,7 @@ function createAcpTurnControls(input) {
1299
1425
  let checkOutcome;
1300
1426
  try {
1301
1427
  prompt = await acpPromptBlocks(turnInput.input, input.limits);
1428
+ input.ensureAlive();
1302
1429
  if (input.config.watchPromptOutcome !== undefined) {
1303
1430
  checkOutcome = await input.config.watchPromptOutcome({
1304
1431
  sessionId: input.sessionId,
@@ -1318,13 +1445,14 @@ function createAcpTurnControls(input) {
1318
1445
  prompt,
1319
1446
  turn,
1320
1447
  generation: 1,
1448
+ ensureAlive: input.ensureAlive,
1321
1449
  ...input.config.usageInputIncludesCachedRead !== undefined && {
1322
1450
  usageInputIncludesCachedRead: input.config.usageInputIncludesCachedRead
1323
1451
  },
1324
1452
  ...checkOutcome !== undefined && { checkOutcome },
1325
1453
  done: () => releaseTurn(turn)
1326
1454
  });
1327
- return acpTurnHandle(input.peer, input.sessionId, turn);
1455
+ return acpTurnHandle(input.peer, input.sessionId, turn, input.ensureAlive);
1328
1456
  },
1329
1457
  async steerTurn(steerInput) {
1330
1458
  if ((input.config.steerMode ?? "none") !== "prompt") {
@@ -1373,6 +1501,7 @@ function createAcpTurnControls(input) {
1373
1501
  prompt,
1374
1502
  turn,
1375
1503
  generation: nextGeneration,
1504
+ ensureAlive: input.ensureAlive,
1376
1505
  ...input.config.usageInputIncludesCachedRead !== undefined && {
1377
1506
  usageInputIncludesCachedRead: input.config.usageInputIncludesCachedRead
1378
1507
  },
@@ -1385,68 +1514,42 @@ function createAcpTurnControls(input) {
1385
1514
  }
1386
1515
 
1387
1516
  // src/agent-executor/acp/v1-session.ts
1388
- function optionOf(options, category) {
1389
- return options.find((option) => option.category === category) ?? options.find((option) => option.id === category);
1390
- }
1391
- async function setOption(peer, sessionId, options, category, value) {
1392
- const option = optionOf(options, category);
1393
- if (option === undefined)
1394
- throw new Error(`The ACP agent offers no ${category} option`);
1395
- const values = acpOptionValues(option);
1396
- if (values.length > 0 && !values.includes(value)) {
1397
- throw new Error(`The ACP agent's ${category} option has no value ${value} (offered: ${values.join(", ")})`);
1398
- }
1399
- const answer = AcpSetConfigOptionResultSchema.parse(await peer.request("session/set_config_option", { sessionId, configId: option.id, value }));
1400
- return answer.configOptions ?? options;
1401
- }
1402
- async function applySessionSelections(input) {
1403
- let options = input.configOptions;
1404
- if (input.model !== undefined) {
1405
- if (optionOf(options, "model") !== undefined) {
1406
- options = await setOption(input.peer, input.sessionId, options, "model", input.model);
1407
- } else if (input.models !== undefined && input.models !== null) {
1408
- const available = input.models.availableModels?.map((entry) => entry.modelId) ?? [];
1409
- if (available.length > 0 && !available.includes(input.model)) {
1410
- throw new Error(`The ACP agent's model option has no value ${input.model} (offered: ${available.join(", ")})`);
1517
+ function createAcpSessionClose(input) {
1518
+ const { state, callerSignal, linked, externalPending } = input;
1519
+ let closePromise;
1520
+ return () => {
1521
+ if (closePromise !== undefined)
1522
+ return closePromise;
1523
+ closePromise = (async () => {
1524
+ const aborted = callerSignal?.aborted === true || linked.signal.aborted;
1525
+ const alreadyTerminated = state.dead !== undefined || aborted;
1526
+ const closeReason = state.dead ?? (callerSignal?.aborted ? abortReason(callerSignal) : linked.signal.aborted ? abortReason(linked.signal) : new Error("The ACP session is closing"));
1527
+ state.closing = true;
1528
+ const turn = state.current;
1529
+ state.current = undefined;
1530
+ settleAcpTurn(turn, closeReason, !alreadyTerminated);
1531
+ if (alreadyTerminated)
1532
+ externalPending.clear();
1533
+ else
1534
+ drainExternalAcpPending(externalPending);
1535
+ if (!alreadyTerminated && acpCan(input.connected, "close")) {
1536
+ await input.connected.peer.request("session/close", { sessionId: input.sessionId }, { timeoutMs: closeRequestTimeoutMs(input.config), signal: linked.signal }).catch(() => {
1537
+ return;
1538
+ });
1411
1539
  }
1412
- await input.peer.request("session/set_model", {
1413
- sessionId: input.sessionId,
1414
- modelId: input.model
1415
- });
1416
- } else {
1417
- throw new Error("The ACP agent offers no model option");
1418
- }
1419
- }
1420
- if (input.thoughtLevel !== undefined) {
1421
- options = await setOption(input.peer, input.sessionId, options, "thought_level", input.thoughtLevel);
1422
- }
1423
- if (input.mode !== undefined) {
1424
- options = await setOption(input.peer, input.sessionId, options, "mode", input.mode);
1425
- }
1426
- return options;
1427
- }
1428
- function drainExternalPending(externalPending) {
1429
- for (const [interactionId, pending] of [...externalPending]) {
1430
- externalPending.delete(interactionId);
1431
- pending.resolve(ACP_CANCELLED);
1432
- }
1433
- }
1434
- function mergeInitialConfigOptions(current, incoming, sawConfigOptionUpdate) {
1435
- if (incoming == null)
1436
- return current;
1437
- if (!sawConfigOptionUpdate || current.length === 0 && incoming.length > 0) {
1438
- return incoming;
1439
- }
1440
- return current;
1540
+ await input.stop();
1541
+ })();
1542
+ return closePromise;
1543
+ };
1441
1544
  }
1442
1545
  async function openOrReopenAcpSession(input) {
1443
- const { connected, cwd, nativeThreadId, mcpServers, meta } = input;
1546
+ const { connected, cwd, nativeThreadId, mcpServers, meta, signal } = input;
1444
1547
  if (nativeThreadId === undefined) {
1445
1548
  const created = AcpNewSessionResultSchema.parse(await connected.peer.request("session/new", {
1446
1549
  cwd,
1447
1550
  mcpServers,
1448
1551
  ...meta !== undefined && { _meta: meta }
1449
- }));
1552
+ }, { signal }));
1450
1553
  return {
1451
1554
  sessionId: created.sessionId,
1452
1555
  configOptions: created.configOptions,
@@ -1459,35 +1562,117 @@ async function openOrReopenAcpSession(input) {
1459
1562
  cwd,
1460
1563
  mcpServers,
1461
1564
  ...meta !== undefined && { _meta: meta }
1462
- }) ?? {});
1565
+ }, { signal }) ?? {});
1463
1566
  return {
1464
1567
  sessionId: nativeThreadId,
1465
1568
  configOptions: reopened.configOptions,
1466
1569
  models: reopened.models
1467
1570
  };
1468
1571
  }
1572
+ function buildAcpSession(input) {
1573
+ const {
1574
+ config,
1575
+ connected,
1576
+ sessionId,
1577
+ callerSignal,
1578
+ linked,
1579
+ externalPending,
1580
+ state,
1581
+ ensureAlive,
1582
+ stop
1583
+ } = input;
1584
+ const { peer, initialized } = connected;
1585
+ const limits = {
1586
+ images: initialized.agentCapabilities?.promptCapabilities?.image === true,
1587
+ maxImageBytes: config.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES,
1588
+ ...config.resolveFile && { resolveFile: config.resolveFile }
1589
+ };
1590
+ const turnControls = createAcpTurnControls({
1591
+ config,
1592
+ peer,
1593
+ sessionId,
1594
+ limits,
1595
+ ensureAlive,
1596
+ getTurn: () => state.current,
1597
+ setTurn: (turn) => {
1598
+ state.current = turn;
1599
+ }
1600
+ });
1601
+ const close = createAcpSessionClose({
1602
+ config,
1603
+ connected,
1604
+ sessionId,
1605
+ callerSignal,
1606
+ linked,
1607
+ externalPending,
1608
+ state,
1609
+ stop
1610
+ });
1611
+ ensureAlive();
1612
+ state.opened = true;
1613
+ return {
1614
+ nativeThreadId: sessionId,
1615
+ get providerPid() {
1616
+ return state.closing || state.dead !== undefined || callerSignal?.aborted === true || linked.signal.aborted ? undefined : state.livePid;
1617
+ },
1618
+ approvalEnforcement: "agent-initiated",
1619
+ get configOptions() {
1620
+ return state.configOptions;
1621
+ },
1622
+ get title() {
1623
+ return state.title;
1624
+ },
1625
+ get commands() {
1626
+ return state.commands;
1627
+ },
1628
+ async setConfigOption(configId, value) {
1629
+ ensureAlive();
1630
+ state.configOptions = await setAcpConfigOption(peer, sessionId, state.configOptions, configId, value, linked.signal);
1631
+ return state.configOptions;
1632
+ },
1633
+ async respond(interactionId, reply) {
1634
+ ensureAlive();
1635
+ answerAcpSessionRequest({ turn: state.current, externalPending, interactionId, reply });
1636
+ },
1637
+ ...turnControls,
1638
+ close
1639
+ };
1640
+ }
1469
1641
  async function openAcpSession(config, input) {
1470
1642
  assertAcpDriverOptions(config);
1471
1643
  const mcpServers = (config.mcpServers ?? []).map((server) => AcpMcpServerSchema.parse(server));
1472
1644
  const linked = sessionAbort(input.signal);
1473
1645
  const externalPending = new Map;
1474
- let current;
1475
- let opened = false;
1476
- let closing = false;
1477
- let dead;
1478
- let livePid;
1479
- let pidNotified = false;
1480
- let configOptions = [];
1481
- let sawConfigOptionUpdate = false;
1482
- let title;
1483
- let commands = [];
1646
+ const state = {
1647
+ current: undefined,
1648
+ opened: false,
1649
+ closing: false,
1650
+ dead: undefined,
1651
+ livePid: undefined,
1652
+ pidNotified: false,
1653
+ configOptions: [],
1654
+ sawConfigOptionUpdate: false,
1655
+ title: undefined,
1656
+ commands: []
1657
+ };
1484
1658
  let connected;
1659
+ const ensureAlive = () => {
1660
+ if (state.closing)
1661
+ throw new Error("The ACP session is closing");
1662
+ if (state.dead !== undefined)
1663
+ throw state.dead;
1664
+ if (input.signal?.aborted)
1665
+ throw abortReason(input.signal);
1666
+ if (linked.signal.aborted)
1667
+ throw abortReason(linked.signal);
1668
+ };
1485
1669
  const recordPid = (pid) => {
1486
- if (pid === undefined || closing || dead !== undefined)
1670
+ if (pid === undefined || state.closing || state.dead !== undefined || input.signal?.aborted === true || linked.signal.aborted) {
1487
1671
  return;
1488
- livePid = pid;
1489
- if (!pidNotified && config.onProviderPid !== undefined) {
1490
- pidNotified = true;
1672
+ }
1673
+ state.livePid = pid;
1674
+ if (!state.pidNotified && config.onProviderPid !== undefined) {
1675
+ state.pidNotified = true;
1491
1676
  invokeSafely(() => config.onProviderPid?.(pid));
1492
1677
  }
1493
1678
  };
@@ -1495,17 +1680,18 @@ async function openAcpSession(config, input) {
1495
1680
  connected = await connectAcp(config, input.profile, input.cwd, linked.signal, {
1496
1681
  ...createAcpHandlers({
1497
1682
  externalPending,
1498
- isOpened: () => opened,
1499
- getTurn: () => current,
1683
+ ensureAlive,
1684
+ isOpened: () => state.opened,
1685
+ getTurn: () => state.current,
1500
1686
  onSessionMeta(meta) {
1501
1687
  if (meta.configOptions !== undefined) {
1502
- configOptions = meta.configOptions;
1503
- sawConfigOptionUpdate = true;
1688
+ state.configOptions = meta.configOptions;
1689
+ state.sawConfigOptionUpdate = true;
1504
1690
  }
1505
1691
  if (meta.title !== undefined)
1506
- title = meta.title;
1692
+ state.title = meta.title;
1507
1693
  if (meta.commands !== undefined)
1508
- commands = meta.commands;
1694
+ state.commands = meta.commands;
1509
1695
  },
1510
1696
  ...config.transformUpdate !== undefined && {
1511
1697
  transformUpdate: config.transformUpdate
@@ -1518,15 +1704,15 @@ async function openAcpSession(config, input) {
1518
1704
  permissionRequestDelivery: config.permissionRequestDelivery
1519
1705
  },
1520
1706
  onEnd(error) {
1521
- const shouldNotify = opened && !closing && input.signal?.aborted !== true;
1522
- dead = error;
1523
- livePid = undefined;
1524
- const turn = current;
1525
- current = undefined;
1707
+ const abortedByCaller = input.signal?.aborted === true;
1708
+ const shouldNotify = state.opened && !state.closing && !abortedByCaller;
1709
+ if (!state.closing && !abortedByCaller)
1710
+ state.dead = error;
1711
+ state.livePid = undefined;
1712
+ const turn = state.current;
1713
+ state.current = undefined;
1526
1714
  externalPending.clear();
1527
- if (turn !== undefined)
1528
- turn.settled = true;
1529
- loseEngineTurn(turn, () => ACP_CANCELLED, error);
1715
+ settleAcpTurn(turn, abortedByCaller && input.signal !== undefined ? abortReason(input.signal) : error, !abortedByCaller);
1530
1716
  linked.abort();
1531
1717
  if (shouldNotify)
1532
1718
  invokeSafely(() => config.onDisconnect?.(error));
@@ -1535,7 +1721,7 @@ async function openAcpSession(config, input) {
1535
1721
  onProviderPid: recordPid,
1536
1722
  ...input.onStartupPhase !== undefined && { onStartupPhase: input.onStartupPhase }
1537
1723
  });
1538
- if (livePid === undefined && !closing && dead === undefined) {
1724
+ if (state.livePid === undefined && !state.closing && state.dead === undefined && input.signal?.aborted !== true && !linked.signal.aborted) {
1539
1725
  recordPid(await connected.engine.pidReady ?? connected.engine.pid);
1540
1726
  }
1541
1727
  } catch (error) {
@@ -1543,16 +1729,14 @@ async function openAcpSession(config, input) {
1543
1729
  throw error;
1544
1730
  }
1545
1731
  const { peer, initialized } = connected;
1546
- const ensureAlive = () => {
1547
- if (closing)
1548
- throw new Error("The ACP session is closing");
1549
- if (dead !== undefined)
1550
- throw dead;
1551
- };
1552
1732
  const stop = async (primary) => {
1553
- closing = true;
1554
- livePid = undefined;
1555
- drainExternalPending(externalPending);
1733
+ const terminated = state.dead !== undefined || input.signal?.aborted === true || linked.signal.aborted;
1734
+ state.closing = true;
1735
+ state.livePid = undefined;
1736
+ if (terminated)
1737
+ externalPending.clear();
1738
+ else
1739
+ drainExternalAcpPending(externalPending);
1556
1740
  linked.abort();
1557
1741
  try {
1558
1742
  await stopConnection(connected, primary);
@@ -1567,74 +1751,35 @@ async function openAcpSession(config, input) {
1567
1751
  cwd: input.cwd,
1568
1752
  nativeThreadId: input.nativeThreadId,
1569
1753
  mcpServers,
1570
- meta
1754
+ meta,
1755
+ signal: linked.signal
1571
1756
  });
1572
1757
  const sessionId = openedSession.sessionId;
1573
- configOptions = mergeInitialConfigOptions(configOptions, openedSession.configOptions, sawConfigOptionUpdate);
1758
+ state.configOptions = mergeInitialAcpConfigOptions(state.configOptions, openedSession.configOptions, state.sawConfigOptionUpdate);
1574
1759
  const desiredModel = input.model ?? config.model;
1575
1760
  const desiredThoughtLevel = input.thoughtLevel ?? config.thoughtLevel;
1576
1761
  const desiredMode = input.mode ?? config.mode;
1577
- configOptions = await applySessionSelections({
1762
+ state.configOptions = await applyAcpSessionSelections({
1578
1763
  peer,
1579
1764
  sessionId,
1580
- configOptions,
1765
+ configOptions: state.configOptions,
1581
1766
  models: openedSession.models,
1767
+ signal: linked.signal,
1582
1768
  ...desiredModel !== undefined && { model: desiredModel },
1583
1769
  ...desiredThoughtLevel !== undefined && { thoughtLevel: desiredThoughtLevel },
1584
1770
  ...desiredMode !== undefined && { mode: desiredMode }
1585
1771
  });
1586
- const limits = {
1587
- images: initialized.agentCapabilities?.promptCapabilities?.image === true,
1588
- maxImageBytes: config.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES,
1589
- ...config.resolveFile && { resolveFile: config.resolveFile }
1590
- };
1591
- const turnControls = createAcpTurnControls({
1772
+ return buildAcpSession({
1592
1773
  config,
1593
- peer,
1774
+ connected,
1594
1775
  sessionId,
1595
- limits,
1776
+ callerSignal: input.signal,
1777
+ linked,
1778
+ externalPending,
1779
+ state,
1596
1780
  ensureAlive,
1597
- getTurn: () => current,
1598
- setTurn: (turn) => {
1599
- current = turn;
1600
- }
1781
+ stop
1601
1782
  });
1602
- opened = true;
1603
- return {
1604
- nativeThreadId: sessionId,
1605
- get providerPid() {
1606
- return closing || dead !== undefined ? undefined : livePid;
1607
- },
1608
- approvalEnforcement: "agent-initiated",
1609
- get configOptions() {
1610
- return configOptions;
1611
- },
1612
- get title() {
1613
- return title;
1614
- },
1615
- get commands() {
1616
- return commands;
1617
- },
1618
- async setConfigOption(configId, value) {
1619
- ensureAlive();
1620
- configOptions = await setOption(peer, sessionId, configOptions, configId, value);
1621
- return configOptions;
1622
- },
1623
- async respond(interactionId, reply) {
1624
- ensureAlive();
1625
- answerAcpSessionRequest({ turn: current, externalPending, interactionId, reply });
1626
- },
1627
- ...turnControls,
1628
- async close() {
1629
- closing = true;
1630
- drainExternalPending(externalPending);
1631
- if (acpCan(connected, "close"))
1632
- await peer.request("session/close", { sessionId }, { timeoutMs: closeRequestTimeoutMs(config) }).catch(() => {
1633
- return;
1634
- });
1635
- await stop();
1636
- }
1637
- };
1638
1783
  } catch (error) {
1639
1784
  await stop({ error });
1640
1785
  throw error;