stitchkit 0.132.0 → 0.132.2

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 (29) hide show
  1. package/CHANGELOG.md +18 -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/codex/event-routing.d.ts +8 -1
  13. package/dist/agent-executor/codex/event-routing.d.ts.map +1 -1
  14. package/dist/agent-executor/codex/handlers.d.ts +1 -0
  15. package/dist/agent-executor/codex/handlers.d.ts.map +1 -1
  16. package/dist/agent-executor/codex/limits.d.ts.map +1 -1
  17. package/dist/agent-executor/codex/session.d.ts.map +1 -1
  18. package/dist/agent-executor/codex/shared-server.d.ts.map +1 -1
  19. package/dist/agent-executor/codex/shared-thread.d.ts +1 -0
  20. package/dist/agent-executor/codex/shared-thread.d.ts.map +1 -1
  21. package/dist/agent-executor/codex/thread-open.d.ts.map +1 -1
  22. package/dist/agent-runtime/branch-observations.d.ts +5 -5
  23. package/dist/agent-runtime/sql-rows.d.ts +10 -10
  24. package/dist/agent-runtime/store-conformance-lifecycle.d.ts +20 -20
  25. package/dist/agent-runtime/store-conformance-support.d.ts +10 -10
  26. package/dist/agent-runtime/terminal-commit.d.ts +10 -10
  27. package/dist/entrypoints/agent-executor/acp.js +306 -162
  28. package/dist/entrypoints/agent-executor/codex.js +197 -54
  29. package/package.json +1 -1
@@ -51,6 +51,9 @@ import {
51
51
  assertTimerMs,
52
52
  withSignalDeadline
53
53
  } from "../../index-agy5fqgf.js";
54
+ import {
55
+ abortReason
56
+ } from "../../index-rptj3qnc.js";
54
57
 
55
58
  // src/agent-executor/acp/scenarios.ts
56
59
  var session = "fake-session";
@@ -716,6 +719,12 @@ var ACP_CANCELLED = { outcome: { outcome: "cancelled" } };
716
719
  var AcpOptionSelectionInputSchema = z4.strictObject({
717
720
  optionId: z4.string().min(1)
718
721
  });
722
+ function drainExternalAcpPending(externalPending) {
723
+ for (const [interactionId, pending] of [...externalPending]) {
724
+ externalPending.delete(interactionId);
725
+ pending.resolve(ACP_CANCELLED);
726
+ }
727
+ }
719
728
  function isPlainJsonRecord(value) {
720
729
  return typeof value === "object" && value !== null && !Array.isArray(value);
721
730
  }
@@ -807,6 +816,14 @@ function answerAcpSessionRequest(input) {
807
816
  // src/agent-executor/acp/v1-handlers.ts
808
817
  var JSON_RPC_INTERNAL_ERROR = -32603;
809
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
+ }
810
827
  function normalizeTransformedUpdates(raw, transform) {
811
828
  if (transform === undefined)
812
829
  return [raw];
@@ -853,6 +870,8 @@ function handleAcpNotification(state, externalState, method, params) {
853
870
  try {
854
871
  updates = normalizeTransformedUpdates(parsed.data.update, state.transformUpdate);
855
872
  } catch (error) {
873
+ if (!isHandlersAlive(state))
874
+ return;
856
875
  if (turn !== undefined) {
857
876
  turn.chunk += 1;
858
877
  offerTurnDelta(turn.channel, {
@@ -868,6 +887,8 @@ function handleAcpNotification(state, externalState, method, params) {
868
887
  }
869
888
  const opened = state.isOpened();
870
889
  for (const update of updates) {
890
+ if (!isHandlersAlive(state))
891
+ return;
871
892
  state.onSessionMeta({
872
893
  ...update.configOptions !== undefined && { configOptions: update.configOptions },
873
894
  ...update.sessionUpdate === "session_info_update" && typeof update.title === "string" && { title: update.title },
@@ -933,7 +954,7 @@ function handleAcpRequest(state, method, params, id) {
933
954
  resolve
934
955
  });
935
956
  });
936
- 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)) {
937
958
  const observer = state.onPermissionRequest;
938
959
  invokeSafely(() => observer({
939
960
  interactionId,
@@ -942,6 +963,7 @@ function handleAcpRequest(state, method, params, id) {
942
963
  duringActiveTurn: true,
943
964
  delta,
944
965
  async respond(reply) {
966
+ state.ensureAlive();
945
967
  answerActiveAcpTurnRequest(turn, interactionId, reply);
946
968
  }
947
969
  }));
@@ -975,6 +997,8 @@ function handleAcpRequest(state, method, params, id) {
975
997
  if (state.externalPending.get(interactionId) !== entry)
976
998
  return;
977
999
  state.externalPending.delete(interactionId);
1000
+ if (!isHandlersAlive(state))
1001
+ return;
978
1002
  if (error instanceof JsonRpcError2)
979
1003
  reject(error);
980
1004
  else
@@ -988,6 +1012,7 @@ function handleAcpRequest(state, method, params, id) {
988
1012
  duringActiveTurn: false,
989
1013
  delta,
990
1014
  async respond(reply) {
1015
+ state.ensureAlive();
991
1016
  answerAcpSessionRequest({
992
1017
  turn: undefined,
993
1018
  externalPending: state.externalPending,
@@ -997,8 +1022,23 @@ function handleAcpRequest(state, method, params, id) {
997
1022
  });
998
1023
  }
999
1024
  });
1000
- if (typeof outcome === "object" && outcome !== null && "then" in outcome && typeof outcome.then === "function") {
1001
- 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);
1002
1042
  }
1003
1043
  } catch (error) {
1004
1044
  onObserverError(error);
@@ -1010,13 +1050,70 @@ function createAcpHandlers(state) {
1010
1050
  chunk: 0,
1011
1051
  track: { segment: 0, toolNames: new Map }
1012
1052
  };
1053
+ const dropClosedRequest = () => new Promise(() => {
1054
+ return;
1055
+ });
1013
1056
  return {
1014
- onNotification: (method, params) => handleAcpNotification(state, externalState, method, params),
1015
- 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
+ },
1016
1067
  onEnd: state.onEnd
1017
1068
  };
1018
1069
  }
1019
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
+
1020
1117
  // src/agent-executor/acp/v1-probe.ts
1021
1118
  var DEFAULT_PROBE_TIMEOUT_MS = 30000;
1022
1119
  var ProbeSessionId = AcpNewSessionResultSchema.pick({ sessionId: true });
@@ -1027,29 +1124,40 @@ async function readProbeSession(config, connection, cwd, signal) {
1027
1124
  mcpServers: [],
1028
1125
  ...meta !== undefined && { _meta: meta }
1029
1126
  }, { signal });
1127
+ if (signal?.aborted)
1128
+ throw abortReason(signal);
1030
1129
  const { sessionId } = ProbeSessionId.parse(reply);
1031
1130
  const parsed = AcpNewSessionResultSchema.safeParse(reply);
1032
1131
  const failures = parsed.success ? [] : [parsed.error];
1033
1132
  const timeoutMs = closeRequestTimeoutMs(config);
1133
+ const cleanupOptions = { timeoutMs, ...signal !== undefined && { signal } };
1034
1134
  const recordFailure = (method, cause) => failures.push(new Error(`${method} failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
1035
1135
  cause
1036
1136
  }));
1037
1137
  if (acpCan(connection, "close")) {
1038
1138
  try {
1039
- await connection.peer.request("session/close", { sessionId }, { timeoutMs });
1139
+ await connection.peer.request("session/close", { sessionId }, cleanupOptions);
1040
1140
  } catch (cause) {
1141
+ if (signal?.aborted)
1142
+ throw abortReason(signal);
1041
1143
  const canFallBack = cause instanceof JsonRpcError2 && cause.code === JSON_RPC_METHOD_NOT_FOUND2 && acpCan(connection, "delete");
1042
1144
  if (!canFallBack)
1043
1145
  recordFailure("session/close", cause);
1044
1146
  }
1045
1147
  }
1148
+ if (signal?.aborted)
1149
+ throw abortReason(signal);
1046
1150
  if (acpCan(connection, "delete")) {
1047
1151
  try {
1048
- await connection.peer.request("session/delete", { sessionId }, { timeoutMs });
1152
+ await connection.peer.request("session/delete", { sessionId }, cleanupOptions);
1049
1153
  } catch (cause) {
1154
+ if (signal?.aborted)
1155
+ throw abortReason(signal);
1050
1156
  recordFailure("session/delete", cause);
1051
1157
  }
1052
1158
  }
1159
+ if (signal?.aborted)
1160
+ throw abortReason(signal);
1053
1161
  if (failures.length > 1) {
1054
1162
  throw new AggregateError(failures, failures.map((error) => error.message).join("; "), {
1055
1163
  cause: failures[0]
@@ -1120,9 +1228,7 @@ async function probeAcpCapabilities(config, input) {
1120
1228
  let result;
1121
1229
  try {
1122
1230
  const session = await readProbeSession(config, connection, input.cwd, deadlineSignal);
1123
- if (session.configOptions != null && (!sawConfigOptionUpdate || configOptions.length === 0 && session.configOptions.length > 0)) {
1124
- configOptions = session.configOptions;
1125
- }
1231
+ configOptions = mergeInitialAcpConfigOptions(configOptions, session.configOptions, sawConfigOptionUpdate);
1126
1232
  deadlineSignal.throwIfAborted();
1127
1233
  const models = extractProbeModels(configOptions, session.models?.availableModels);
1128
1234
  result = {
@@ -1161,11 +1267,23 @@ function newAcpTurn(turnId) {
1161
1267
  settled: false
1162
1268
  };
1163
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
+ }
1164
1281
  function runAcpPrompt(input) {
1165
- const { peer, sessionId, prompt, turn, generation, checkOutcome, done } = input;
1282
+ const { peer, sessionId, prompt, turn, generation, ensureAlive, checkOutcome, done } = input;
1166
1283
  peer.request("session/prompt", { sessionId, prompt: [...prompt] }, { timeoutMs: null }).then(async (result) => {
1167
1284
  if (turn.settled)
1168
1285
  return;
1286
+ ensureAlive();
1169
1287
  const parsed = AcpPromptResultSchema.parse(result);
1170
1288
  if (parsed.usage !== undefined && parsed.usage !== null) {
1171
1289
  turn.accumulatedUsage = addAcpTokenUsage(turn.accumulatedUsage, normalizeAcpUsage(parsed.usage, {
@@ -1179,6 +1297,7 @@ function runAcpPrompt(input) {
1179
1297
  const rawOverride = !turn.state.interruptRequested && checkOutcome !== undefined ? await checkOutcome(parsed) : undefined;
1180
1298
  if (turn.settled || generation !== turn.promptGeneration)
1181
1299
  return;
1300
+ ensureAlive();
1182
1301
  const override = rawOverride !== undefined ? AcpPromptOutcomeOverrideSchema.parse(rawOverride) : undefined;
1183
1302
  const outcome = override !== undefined ? "failed" : acpOutcome(parsed.stopReason, turn.state.interruptRequested);
1184
1303
  const raw = { source: "acp", type: `session/prompt/${parsed.stopReason}` };
@@ -1228,8 +1347,21 @@ function runAcpPrompt(input) {
1228
1347
  if (turn.settled || generation !== turn.promptGeneration)
1229
1348
  return;
1230
1349
  turn.settled = true;
1231
- const kind = classifyAcpRpcRefusal(error);
1232
- 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) {
1233
1365
  const raw = { source: "acp", type: "session/prompt" };
1234
1366
  endEngineTurn(turn, () => ACP_CANCELLED, [
1235
1367
  {
@@ -1238,7 +1370,7 @@ function runAcpPrompt(input) {
1238
1370
  itemId: "failure",
1239
1371
  raw,
1240
1372
  kind,
1241
- message: error.message
1373
+ message: failure.message
1242
1374
  },
1243
1375
  {
1244
1376
  type: "turn-end",
@@ -1249,20 +1381,28 @@ function runAcpPrompt(input) {
1249
1381
  }
1250
1382
  ]);
1251
1383
  } else {
1252
- loseEngineTurn(turn, () => ACP_CANCELLED, error);
1384
+ loseEngineTurn(turn, () => ACP_CANCELLED, failure);
1253
1385
  }
1254
1386
  done();
1255
1387
  });
1256
1388
  }
1257
- function acpTurnHandle(peer, sessionId, turn) {
1389
+ function acpTurnHandle(peer, sessionId, turn, ensureAlive) {
1258
1390
  return {
1259
1391
  deltas: turn.channel,
1260
1392
  async interrupt() {
1393
+ if (turn.settled)
1394
+ return;
1395
+ try {
1396
+ ensureAlive();
1397
+ } catch {
1398
+ return;
1399
+ }
1261
1400
  turn.state.interruptRequested = true;
1262
1401
  peer.notify("session/cancel", { sessionId });
1263
1402
  drainEngineRequests(turn, () => ACP_CANCELLED);
1264
1403
  },
1265
1404
  async respond(interactionId, rawReply) {
1405
+ ensureAlive();
1266
1406
  answerActiveAcpTurnRequest(turn, interactionId, rawReply);
1267
1407
  }
1268
1408
  };
@@ -1285,6 +1425,7 @@ function createAcpTurnControls(input) {
1285
1425
  let checkOutcome;
1286
1426
  try {
1287
1427
  prompt = await acpPromptBlocks(turnInput.input, input.limits);
1428
+ input.ensureAlive();
1288
1429
  if (input.config.watchPromptOutcome !== undefined) {
1289
1430
  checkOutcome = await input.config.watchPromptOutcome({
1290
1431
  sessionId: input.sessionId,
@@ -1304,13 +1445,14 @@ function createAcpTurnControls(input) {
1304
1445
  prompt,
1305
1446
  turn,
1306
1447
  generation: 1,
1448
+ ensureAlive: input.ensureAlive,
1307
1449
  ...input.config.usageInputIncludesCachedRead !== undefined && {
1308
1450
  usageInputIncludesCachedRead: input.config.usageInputIncludesCachedRead
1309
1451
  },
1310
1452
  ...checkOutcome !== undefined && { checkOutcome },
1311
1453
  done: () => releaseTurn(turn)
1312
1454
  });
1313
- return acpTurnHandle(input.peer, input.sessionId, turn);
1455
+ return acpTurnHandle(input.peer, input.sessionId, turn, input.ensureAlive);
1314
1456
  },
1315
1457
  async steerTurn(steerInput) {
1316
1458
  if ((input.config.steerMode ?? "none") !== "prompt") {
@@ -1359,6 +1501,7 @@ function createAcpTurnControls(input) {
1359
1501
  prompt,
1360
1502
  turn,
1361
1503
  generation: nextGeneration,
1504
+ ensureAlive: input.ensureAlive,
1362
1505
  ...input.config.usageInputIncludesCachedRead !== undefined && {
1363
1506
  usageInputIncludesCachedRead: input.config.usageInputIncludesCachedRead
1364
1507
  },
@@ -1371,68 +1514,41 @@ function createAcpTurnControls(input) {
1371
1514
  }
1372
1515
 
1373
1516
  // src/agent-executor/acp/v1-session.ts
1374
- function optionOf(options, category) {
1375
- return options.find((option) => option.category === category) ?? options.find((option) => option.id === category);
1376
- }
1377
- async function setOption(peer, sessionId, options, category, value) {
1378
- const option = optionOf(options, category);
1379
- if (option === undefined)
1380
- throw new Error(`The ACP agent offers no ${category} option`);
1381
- const values = acpOptionValues(option);
1382
- if (values.length > 0 && !values.includes(value)) {
1383
- throw new Error(`The ACP agent's ${category} option has no value ${value} (offered: ${values.join(", ")})`);
1384
- }
1385
- const answer = AcpSetConfigOptionResultSchema.parse(await peer.request("session/set_config_option", { sessionId, configId: option.id, value }));
1386
- return answer.configOptions ?? options;
1387
- }
1388
- async function applySessionSelections(input) {
1389
- let options = input.configOptions;
1390
- if (input.model !== undefined) {
1391
- if (optionOf(options, "model") !== undefined) {
1392
- options = await setOption(input.peer, input.sessionId, options, "model", input.model);
1393
- } else if (input.models !== undefined && input.models !== null) {
1394
- const available = input.models.availableModels?.map((entry) => entry.modelId) ?? [];
1395
- if (available.length > 0 && !available.includes(input.model)) {
1396
- throw new Error(`The ACP agent's model option has no value ${input.model} (offered: ${available.join(", ")})`);
1517
+ function createAcpSessionClose(input) {
1518
+ const { state, linked, externalPending } = input;
1519
+ let closePromise;
1520
+ return () => {
1521
+ if (closePromise !== undefined)
1522
+ return closePromise;
1523
+ closePromise = (async () => {
1524
+ const alreadyTerminated = state.dead !== undefined || linked.signal.aborted;
1525
+ const closeReason = state.dead ?? (linked.signal.aborted ? abortReason(linked.signal) : new Error("The ACP session is closing"));
1526
+ state.closing = true;
1527
+ const turn = state.current;
1528
+ state.current = undefined;
1529
+ settleAcpTurn(turn, closeReason, !alreadyTerminated);
1530
+ if (alreadyTerminated)
1531
+ externalPending.clear();
1532
+ else
1533
+ drainExternalAcpPending(externalPending);
1534
+ if (!alreadyTerminated && acpCan(input.connected, "close")) {
1535
+ await input.connected.peer.request("session/close", { sessionId: input.sessionId }, { timeoutMs: closeRequestTimeoutMs(input.config), signal: linked.signal }).catch(() => {
1536
+ return;
1537
+ });
1397
1538
  }
1398
- await input.peer.request("session/set_model", {
1399
- sessionId: input.sessionId,
1400
- modelId: input.model
1401
- });
1402
- } else {
1403
- throw new Error("The ACP agent offers no model option");
1404
- }
1405
- }
1406
- if (input.thoughtLevel !== undefined) {
1407
- options = await setOption(input.peer, input.sessionId, options, "thought_level", input.thoughtLevel);
1408
- }
1409
- if (input.mode !== undefined) {
1410
- options = await setOption(input.peer, input.sessionId, options, "mode", input.mode);
1411
- }
1412
- return options;
1413
- }
1414
- function drainExternalPending(externalPending) {
1415
- for (const [interactionId, pending] of [...externalPending]) {
1416
- externalPending.delete(interactionId);
1417
- pending.resolve(ACP_CANCELLED);
1418
- }
1419
- }
1420
- function mergeInitialConfigOptions(current, incoming, sawConfigOptionUpdate) {
1421
- if (incoming == null)
1422
- return current;
1423
- if (!sawConfigOptionUpdate || current.length === 0 && incoming.length > 0) {
1424
- return incoming;
1425
- }
1426
- return current;
1539
+ await input.stop();
1540
+ })();
1541
+ return closePromise;
1542
+ };
1427
1543
  }
1428
1544
  async function openOrReopenAcpSession(input) {
1429
- const { connected, cwd, nativeThreadId, mcpServers, meta } = input;
1545
+ const { connected, cwd, nativeThreadId, mcpServers, meta, signal } = input;
1430
1546
  if (nativeThreadId === undefined) {
1431
1547
  const created = AcpNewSessionResultSchema.parse(await connected.peer.request("session/new", {
1432
1548
  cwd,
1433
1549
  mcpServers,
1434
1550
  ...meta !== undefined && { _meta: meta }
1435
- }));
1551
+ }, { signal }));
1436
1552
  return {
1437
1553
  sessionId: created.sessionId,
1438
1554
  configOptions: created.configOptions,
@@ -1445,35 +1561,104 @@ async function openOrReopenAcpSession(input) {
1445
1561
  cwd,
1446
1562
  mcpServers,
1447
1563
  ...meta !== undefined && { _meta: meta }
1448
- }) ?? {});
1564
+ }, { signal }) ?? {});
1449
1565
  return {
1450
1566
  sessionId: nativeThreadId,
1451
1567
  configOptions: reopened.configOptions,
1452
1568
  models: reopened.models
1453
1569
  };
1454
1570
  }
1571
+ function buildAcpSession(input) {
1572
+ const { config, connected, sessionId, linked, externalPending, state, ensureAlive, stop } = input;
1573
+ const { peer, initialized } = connected;
1574
+ const limits = {
1575
+ images: initialized.agentCapabilities?.promptCapabilities?.image === true,
1576
+ maxImageBytes: config.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES,
1577
+ ...config.resolveFile && { resolveFile: config.resolveFile }
1578
+ };
1579
+ const turnControls = createAcpTurnControls({
1580
+ config,
1581
+ peer,
1582
+ sessionId,
1583
+ limits,
1584
+ ensureAlive,
1585
+ getTurn: () => state.current,
1586
+ setTurn: (turn) => {
1587
+ state.current = turn;
1588
+ }
1589
+ });
1590
+ const close = createAcpSessionClose({
1591
+ config,
1592
+ connected,
1593
+ sessionId,
1594
+ linked,
1595
+ externalPending,
1596
+ state,
1597
+ stop
1598
+ });
1599
+ ensureAlive();
1600
+ state.opened = true;
1601
+ return {
1602
+ nativeThreadId: sessionId,
1603
+ get providerPid() {
1604
+ return state.closing || state.dead !== undefined || linked.signal.aborted ? undefined : state.livePid;
1605
+ },
1606
+ approvalEnforcement: "agent-initiated",
1607
+ get configOptions() {
1608
+ return state.configOptions;
1609
+ },
1610
+ get title() {
1611
+ return state.title;
1612
+ },
1613
+ get commands() {
1614
+ return state.commands;
1615
+ },
1616
+ async setConfigOption(configId, value) {
1617
+ ensureAlive();
1618
+ state.configOptions = await setAcpConfigOption(peer, sessionId, state.configOptions, configId, value, linked.signal);
1619
+ return state.configOptions;
1620
+ },
1621
+ async respond(interactionId, reply) {
1622
+ ensureAlive();
1623
+ answerAcpSessionRequest({ turn: state.current, externalPending, interactionId, reply });
1624
+ },
1625
+ ...turnControls,
1626
+ close
1627
+ };
1628
+ }
1455
1629
  async function openAcpSession(config, input) {
1456
1630
  assertAcpDriverOptions(config);
1457
1631
  const mcpServers = (config.mcpServers ?? []).map((server) => AcpMcpServerSchema.parse(server));
1458
1632
  const linked = sessionAbort(input.signal);
1459
1633
  const externalPending = new Map;
1460
- let current;
1461
- let opened = false;
1462
- let closing = false;
1463
- let dead;
1464
- let livePid;
1465
- let pidNotified = false;
1466
- let configOptions = [];
1467
- let sawConfigOptionUpdate = false;
1468
- let title;
1469
- let commands = [];
1634
+ const state = {
1635
+ current: undefined,
1636
+ opened: false,
1637
+ closing: false,
1638
+ dead: undefined,
1639
+ livePid: undefined,
1640
+ pidNotified: false,
1641
+ configOptions: [],
1642
+ sawConfigOptionUpdate: false,
1643
+ title: undefined,
1644
+ commands: []
1645
+ };
1470
1646
  let connected;
1647
+ const ensureAlive = () => {
1648
+ if (state.closing)
1649
+ throw new Error("The ACP session is closing");
1650
+ if (state.dead !== undefined)
1651
+ throw state.dead;
1652
+ if (linked.signal.aborted)
1653
+ throw abortReason(linked.signal);
1654
+ };
1471
1655
  const recordPid = (pid) => {
1472
- if (pid === undefined || closing || dead !== undefined)
1656
+ if (pid === undefined || state.closing || state.dead !== undefined || linked.signal.aborted) {
1473
1657
  return;
1474
- livePid = pid;
1475
- if (!pidNotified && config.onProviderPid !== undefined) {
1476
- pidNotified = true;
1658
+ }
1659
+ state.livePid = pid;
1660
+ if (!state.pidNotified && config.onProviderPid !== undefined) {
1661
+ state.pidNotified = true;
1477
1662
  invokeSafely(() => config.onProviderPid?.(pid));
1478
1663
  }
1479
1664
  };
@@ -1481,17 +1666,18 @@ async function openAcpSession(config, input) {
1481
1666
  connected = await connectAcp(config, input.profile, input.cwd, linked.signal, {
1482
1667
  ...createAcpHandlers({
1483
1668
  externalPending,
1484
- isOpened: () => opened,
1485
- getTurn: () => current,
1669
+ ensureAlive,
1670
+ isOpened: () => state.opened,
1671
+ getTurn: () => state.current,
1486
1672
  onSessionMeta(meta) {
1487
1673
  if (meta.configOptions !== undefined) {
1488
- configOptions = meta.configOptions;
1489
- sawConfigOptionUpdate = true;
1674
+ state.configOptions = meta.configOptions;
1675
+ state.sawConfigOptionUpdate = true;
1490
1676
  }
1491
1677
  if (meta.title !== undefined)
1492
- title = meta.title;
1678
+ state.title = meta.title;
1493
1679
  if (meta.commands !== undefined)
1494
- commands = meta.commands;
1680
+ state.commands = meta.commands;
1495
1681
  },
1496
1682
  ...config.transformUpdate !== undefined && {
1497
1683
  transformUpdate: config.transformUpdate
@@ -1504,15 +1690,15 @@ async function openAcpSession(config, input) {
1504
1690
  permissionRequestDelivery: config.permissionRequestDelivery
1505
1691
  },
1506
1692
  onEnd(error) {
1507
- const shouldNotify = opened && !closing && input.signal?.aborted !== true;
1508
- dead = error;
1509
- livePid = undefined;
1510
- const turn = current;
1511
- current = undefined;
1693
+ const abortedByCaller = input.signal?.aborted === true;
1694
+ const shouldNotify = state.opened && !state.closing && !abortedByCaller;
1695
+ if (!state.closing && !abortedByCaller)
1696
+ state.dead = error;
1697
+ state.livePid = undefined;
1698
+ const turn = state.current;
1699
+ state.current = undefined;
1512
1700
  externalPending.clear();
1513
- if (turn !== undefined)
1514
- turn.settled = true;
1515
- loseEngineTurn(turn, () => ACP_CANCELLED, error);
1701
+ settleAcpTurn(turn, abortedByCaller ? abortReason(linked.signal) : error, !abortedByCaller);
1516
1702
  linked.abort();
1517
1703
  if (shouldNotify)
1518
1704
  invokeSafely(() => config.onDisconnect?.(error));
@@ -1521,7 +1707,7 @@ async function openAcpSession(config, input) {
1521
1707
  onProviderPid: recordPid,
1522
1708
  ...input.onStartupPhase !== undefined && { onStartupPhase: input.onStartupPhase }
1523
1709
  });
1524
- if (livePid === undefined && !closing && dead === undefined) {
1710
+ if (state.livePid === undefined && !state.closing && state.dead === undefined && !linked.signal.aborted) {
1525
1711
  recordPid(await connected.engine.pidReady ?? connected.engine.pid);
1526
1712
  }
1527
1713
  } catch (error) {
@@ -1529,16 +1715,14 @@ async function openAcpSession(config, input) {
1529
1715
  throw error;
1530
1716
  }
1531
1717
  const { peer, initialized } = connected;
1532
- const ensureAlive = () => {
1533
- if (closing)
1534
- throw new Error("The ACP session is closing");
1535
- if (dead !== undefined)
1536
- throw dead;
1537
- };
1538
1718
  const stop = async (primary) => {
1539
- closing = true;
1540
- livePid = undefined;
1541
- drainExternalPending(externalPending);
1719
+ const terminated = state.dead !== undefined || linked.signal.aborted;
1720
+ state.closing = true;
1721
+ state.livePid = undefined;
1722
+ if (terminated)
1723
+ externalPending.clear();
1724
+ else
1725
+ drainExternalAcpPending(externalPending);
1542
1726
  linked.abort();
1543
1727
  try {
1544
1728
  await stopConnection(connected, primary);
@@ -1553,74 +1737,34 @@ async function openAcpSession(config, input) {
1553
1737
  cwd: input.cwd,
1554
1738
  nativeThreadId: input.nativeThreadId,
1555
1739
  mcpServers,
1556
- meta
1740
+ meta,
1741
+ signal: linked.signal
1557
1742
  });
1558
1743
  const sessionId = openedSession.sessionId;
1559
- configOptions = mergeInitialConfigOptions(configOptions, openedSession.configOptions, sawConfigOptionUpdate);
1744
+ state.configOptions = mergeInitialAcpConfigOptions(state.configOptions, openedSession.configOptions, state.sawConfigOptionUpdate);
1560
1745
  const desiredModel = input.model ?? config.model;
1561
1746
  const desiredThoughtLevel = input.thoughtLevel ?? config.thoughtLevel;
1562
1747
  const desiredMode = input.mode ?? config.mode;
1563
- configOptions = await applySessionSelections({
1748
+ state.configOptions = await applyAcpSessionSelections({
1564
1749
  peer,
1565
1750
  sessionId,
1566
- configOptions,
1751
+ configOptions: state.configOptions,
1567
1752
  models: openedSession.models,
1753
+ signal: linked.signal,
1568
1754
  ...desiredModel !== undefined && { model: desiredModel },
1569
1755
  ...desiredThoughtLevel !== undefined && { thoughtLevel: desiredThoughtLevel },
1570
1756
  ...desiredMode !== undefined && { mode: desiredMode }
1571
1757
  });
1572
- const limits = {
1573
- images: initialized.agentCapabilities?.promptCapabilities?.image === true,
1574
- maxImageBytes: config.maxImageBytes ?? DEFAULT_MAX_IMAGE_BYTES,
1575
- ...config.resolveFile && { resolveFile: config.resolveFile }
1576
- };
1577
- const turnControls = createAcpTurnControls({
1758
+ return buildAcpSession({
1578
1759
  config,
1579
- peer,
1760
+ connected,
1580
1761
  sessionId,
1581
- limits,
1762
+ linked,
1763
+ externalPending,
1764
+ state,
1582
1765
  ensureAlive,
1583
- getTurn: () => current,
1584
- setTurn: (turn) => {
1585
- current = turn;
1586
- }
1766
+ stop
1587
1767
  });
1588
- opened = true;
1589
- return {
1590
- nativeThreadId: sessionId,
1591
- get providerPid() {
1592
- return closing || dead !== undefined ? undefined : livePid;
1593
- },
1594
- approvalEnforcement: "agent-initiated",
1595
- get configOptions() {
1596
- return configOptions;
1597
- },
1598
- get title() {
1599
- return title;
1600
- },
1601
- get commands() {
1602
- return commands;
1603
- },
1604
- async setConfigOption(configId, value) {
1605
- ensureAlive();
1606
- configOptions = await setOption(peer, sessionId, configOptions, configId, value);
1607
- return configOptions;
1608
- },
1609
- async respond(interactionId, reply) {
1610
- ensureAlive();
1611
- answerAcpSessionRequest({ turn: current, externalPending, interactionId, reply });
1612
- },
1613
- ...turnControls,
1614
- async close() {
1615
- closing = true;
1616
- drainExternalPending(externalPending);
1617
- if (acpCan(connected, "close"))
1618
- await peer.request("session/close", { sessionId }, { timeoutMs: closeRequestTimeoutMs(config) }).catch(() => {
1619
- return;
1620
- });
1621
- await stop();
1622
- }
1623
- };
1624
1768
  } catch (error) {
1625
1769
  await stop({ error });
1626
1770
  throw error;