@1agents/acp-service 0.10.12 → 0.11.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.
Files changed (115) hide show
  1. package/dist/src/acp-connection.js +33 -0
  2. package/dist/src/bridge.js +44 -1
  3. package/dist/src/capacity-queue.d.ts +3 -1
  4. package/dist/src/capacity-queue.js +4 -0
  5. package/dist/src/catalog.js +13 -3
  6. package/package.json +4 -4
  7. package/skills/acp-service/SKILL.md +1 -1
  8. package/vendor/dsh/adapter.d.ts +6 -0
  9. package/vendor/dsh/adapter.js +23 -0
  10. package/vendor/dsh/index.js +19 -0
  11. package/vendor/runtime/README.md +36 -11
  12. package/vendor/runtime/dist/{agent-registry-DxcyXXqb.js → agent-registry-CsdsVpJb.js} +209 -177
  13. package/vendor/runtime/dist/agent-registry-CsdsVpJb.js.map +1 -0
  14. package/vendor/runtime/dist/agent-registry.d.ts +0 -2
  15. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  16. package/vendor/runtime/dist/agent-registry.js +1 -1
  17. package/vendor/runtime/dist/{cli-BKmMxgix.js → cli-B5gQOSDl.js} +33 -14
  18. package/vendor/runtime/dist/cli-B5gQOSDl.js.map +1 -0
  19. package/vendor/runtime/dist/cli.d.ts +2 -6
  20. package/vendor/runtime/dist/cli.d.ts.map +1 -1
  21. package/vendor/runtime/dist/cli.js +189 -164
  22. package/vendor/runtime/dist/cli.js.map +1 -1
  23. package/vendor/runtime/dist/{client-C5zneoBs.d.ts → client-D5y4RXME.d.ts} +4 -12
  24. package/vendor/runtime/dist/client-D5y4RXME.d.ts.map +1 -0
  25. package/vendor/runtime/dist/docs-site/CLI.html +19 -21
  26. package/vendor/runtime/dist/docs-site/VISION.html +3 -2
  27. package/vendor/runtime/dist/docs-site/agents.html +10 -15
  28. package/vendor/runtime/dist/docs-site/assets/agents/Apache-2.0.txt +202 -0
  29. package/vendor/runtime/dist/docs-site/assets/agents/LobeHub-MIT.txt +21 -0
  30. package/vendor/runtime/dist/docs-site/assets/agents/Mux-AGPL-3.0.txt +661 -0
  31. package/vendor/runtime/dist/docs-site/assets/agents/README.md +41 -0
  32. package/vendor/runtime/dist/docs-site/assets/agents/ante.png +0 -0
  33. package/vendor/runtime/dist/docs-site/assets/agents/antigravity.png +0 -0
  34. package/vendor/runtime/dist/docs-site/assets/agents/claude.png +0 -0
  35. package/vendor/runtime/dist/docs-site/assets/agents/codex.png +0 -0
  36. package/vendor/runtime/dist/docs-site/assets/agents/copilot.png +0 -0
  37. package/vendor/runtime/dist/docs-site/assets/agents/cursor.png +0 -0
  38. package/vendor/runtime/dist/docs-site/assets/agents/deepseek-harness.png +0 -0
  39. package/vendor/runtime/dist/docs-site/assets/agents/devin.png +0 -0
  40. package/vendor/runtime/dist/docs-site/assets/agents/droid.png +0 -0
  41. package/vendor/runtime/dist/docs-site/assets/agents/fast-agent.png +0 -0
  42. package/vendor/runtime/dist/docs-site/assets/agents/fx.png +0 -0
  43. package/vendor/runtime/dist/docs-site/assets/agents/gemini.png +0 -0
  44. package/vendor/runtime/dist/docs-site/assets/agents/goose.png +0 -0
  45. package/vendor/runtime/dist/docs-site/assets/agents/grok-build.png +0 -0
  46. package/vendor/runtime/dist/docs-site/assets/agents/iflow.png +0 -0
  47. package/vendor/runtime/dist/docs-site/assets/agents/junie.png +0 -0
  48. package/vendor/runtime/dist/docs-site/assets/agents/kilocode.png +0 -0
  49. package/vendor/runtime/dist/docs-site/assets/agents/kimi.png +0 -0
  50. package/vendor/runtime/dist/docs-site/assets/agents/kiro.png +0 -0
  51. package/vendor/runtime/dist/docs-site/assets/agents/mcode.png +0 -0
  52. package/vendor/runtime/dist/docs-site/assets/agents/mux.png +0 -0
  53. package/vendor/runtime/dist/docs-site/assets/agents/octomind.png +0 -0
  54. package/vendor/runtime/dist/docs-site/assets/agents/openclaw.png +0 -0
  55. package/vendor/runtime/dist/docs-site/assets/agents/opencode.png +0 -0
  56. package/vendor/runtime/dist/docs-site/assets/agents/pi.png +0 -0
  57. package/vendor/runtime/dist/docs-site/assets/agents/pool.png +0 -0
  58. package/vendor/runtime/dist/docs-site/assets/agents/qoder.png +0 -0
  59. package/vendor/runtime/dist/docs-site/assets/agents/qwen.png +0 -0
  60. package/vendor/runtime/dist/docs-site/assets/agents/trae.png +0 -0
  61. package/vendor/runtime/dist/docs-site/assets/agents/zeroclaw.png +0 -0
  62. package/vendor/runtime/dist/docs-site/compare.html +8 -7
  63. package/vendor/runtime/dist/docs-site/config.html +5 -4
  64. package/vendor/runtime/dist/docs-site/custom-agents.html +13 -13
  65. package/vendor/runtime/dist/docs-site/exit-codes.html +4 -3
  66. package/vendor/runtime/dist/docs-site/flows.html +21 -8
  67. package/vendor/runtime/dist/docs-site/index.html +7 -6
  68. package/vendor/runtime/dist/docs-site/install.html +7 -6
  69. package/vendor/runtime/dist/docs-site/llms.txt +6 -6
  70. package/vendor/runtime/dist/docs-site/output-formats.html +9 -8
  71. package/vendor/runtime/dist/docs-site/permissions.html +5 -4
  72. package/vendor/runtime/dist/docs-site/prompting.html +9 -7
  73. package/vendor/runtime/dist/docs-site/quickstart.html +5 -4
  74. package/vendor/runtime/dist/docs-site/releasing.html +9 -8
  75. package/vendor/runtime/dist/docs-site/runtime-environment.html +28 -5
  76. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +13 -7
  77. package/vendor/runtime/dist/docs-site/safe-errors.html +3 -2
  78. package/vendor/runtime/dist/docs-site/session-control.html +7 -6
  79. package/vendor/runtime/dist/docs-site/session-watch.html +6 -5
  80. package/vendor/runtime/dist/docs-site/sessions.html +13 -10
  81. package/vendor/runtime/dist/docs-site/shared-sessions.html +7 -4
  82. package/vendor/runtime/dist/{flows-VrII9VKZ.js → flows-CDj5YcTh.js} +136 -68
  83. package/vendor/runtime/dist/flows-CDj5YcTh.js.map +1 -0
  84. package/vendor/runtime/dist/flows.d.ts +28 -19
  85. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  86. package/vendor/runtime/dist/flows.js +1 -1
  87. package/vendor/runtime/dist/{invocation-options-DHMZ5Rrb.js → input-file-BsfVGZgn.js} +30 -15
  88. package/vendor/runtime/dist/input-file-BsfVGZgn.js.map +1 -0
  89. package/vendor/runtime/dist/{ipc-CNNM5DP_.js → ipc-DfqJsbk6.js} +114 -146
  90. package/vendor/runtime/dist/ipc-DfqJsbk6.js.map +1 -0
  91. package/vendor/runtime/dist/{output-DtzXtiBc.js → output-DOIF4iFc.js} +20 -47
  92. package/vendor/runtime/dist/output-DOIF4iFc.js.map +1 -0
  93. package/vendor/runtime/dist/{queue-owner-runtime-ehuh3SQU.js → queue-owner-runtime-DHBQbjXo.js} +394 -258
  94. package/vendor/runtime/dist/queue-owner-runtime-DHBQbjXo.js.map +1 -0
  95. package/vendor/runtime/dist/runtime.d.ts +37 -36
  96. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  97. package/vendor/runtime/dist/runtime.js +117 -172
  98. package/vendor/runtime/dist/runtime.js.map +1 -1
  99. package/vendor/runtime/dist/{session-options-NjpFwf-c.d.ts → session-options-Ci4aw1oD.d.ts} +13 -16
  100. package/vendor/runtime/dist/session-options-Ci4aw1oD.d.ts.map +1 -0
  101. package/vendor/runtime/dist/{session-watch-CbKfGRkZ.js → session-watch-DRwFHcWw.js} +5 -6
  102. package/vendor/runtime/dist/{session-watch-CbKfGRkZ.js.map → session-watch-DRwFHcWw.js.map} +1 -1
  103. package/vendor/runtime/dist/{watch-BGt4kcE6.js → watch-CUDGkljG.js} +3 -4
  104. package/vendor/runtime/dist/{watch-BGt4kcE6.js.map → watch-CUDGkljG.js.map} +1 -1
  105. package/vendor/runtime/package.json +3 -3
  106. package/vendor/runtime/skills/acpx/SKILL.md +42 -11
  107. package/vendor/runtime/dist/agent-registry-DxcyXXqb.js.map +0 -1
  108. package/vendor/runtime/dist/cli-BKmMxgix.js.map +0 -1
  109. package/vendor/runtime/dist/client-C5zneoBs.d.ts.map +0 -1
  110. package/vendor/runtime/dist/flows-VrII9VKZ.js.map +0 -1
  111. package/vendor/runtime/dist/invocation-options-DHMZ5Rrb.js.map +0 -1
  112. package/vendor/runtime/dist/ipc-CNNM5DP_.js.map +0 -1
  113. package/vendor/runtime/dist/output-DtzXtiBc.js.map +0 -1
  114. package/vendor/runtime/dist/queue-owner-runtime-ehuh3SQU.js.map +0 -1
  115. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +0 -1
@@ -1,5 +1,5 @@
1
- import { $ as measurePerf, $t as SessionModeReplayError, At as extractAcpError, C as textPrompt, Dt as normalizeOutputError, Et as isRetryablePromptError, F as normalizeName, G as normalizeAgentSessionId, Gt as AuthPolicyError, H as canonicalAgentCommand, Ht as AgentDisconnectedError, Jt as GeminiAcpStartupTimeoutError, K as SESSION_JOURNAL_SCHEMA, Kt as ClaudeAcpSessionCreateTimeoutError, L as readSessionRecord, M as isoNow$1, O as absolutePath, Q as incrementPerfCounter, Qt as SessionConfigOptionReplayError, R as resolveSessionRecord, S as promptToDisplayText, St as isProcessAlive, T as lockOwnerPid, Tt as isAcpQueryClosedBeforeResponseError, Ut as AgentSpawnError, Vt as AcpxOperationalError, W as extractAgentSessionId, Wt as AgentStartupError, X as formatPerfMetric, Xt as PermissionPromptUnavailableError, Yt as PermissionDeniedError, Z as getPerfMetricsSnapshot, Zt as QueueConnectionError, _ as ProcessDescendants, _t as sessionEventLockPath, a as trySetModelOnRunningOwner, at as isAcpMessageObject, d as releaseQueueOwnerLease, en as SessionModelReplayError, et as resetPerfMetrics, f as terminateProcess, ft as defaultSessionEventLog, g as QueueLeaseGuardSettlementError, gt as sessionEventActivePath, h as waitMs$1, ht as sessionBaseDir, i as trySetModeOnRunningOwner, it as isAcpJsonRpcMessage, j as findSessionByDirectoryWalk, jt as isAcpResourceNotFoundError, k as findGitRepositoryRoot, m as tryAcquireQueueOwnerLease, mt as retainedEventMaxSegments, n as tryCloseSessionOnRunningOwner, nn as SessionResumeRequiredError, nt as startPerfTimer, o as trySubmitToRunningOwner, ot as isSessionUpdateNotification, p as terminateQueueOwnerForSession, pt as existingEventSegmentIndices, q as SessionJournalReader, qt as CopilotAcpUnsupportedError, r as trySetConfigOptionOnRunningOwner, rn as UnsupportedPromptContentError, s as SessionQueueOwner, t as tryCancelOnRunningOwner, tt as setPerfGauge, u as refreshQueueOwnerLease, vt as sessionEventSegmentPath, w as createLockOwner, wt as formatErrorMessage, y as getUnsupportedPromptContentMessage, z as writeSessionRecord } from "./ipc-CNNM5DP_.js";
2
- import { D as isChildProcessRunning, E as basenameToken$1, F as splitCommandLine, I as waitForChildExit, L as waitForSpawn, M as resolveAgentCommandParts, N as resolveAgentSessionCwd, O as isoNow$2, P as runTimedExecFile, S as resolveWindowsExecutablePath, T as asAbsoluteCwd, _ as buildSpawnCommandOptions, b as readWindowsEnvValue, f as resolveBuiltInAgentLaunch, g as buildAgentSpawnCommand, j as requireAgentStdio, v as buildTerminalShellSpawnCommand, w as PROCESS_HELPER_TIMEOUT_MS, x as resolveWindowsCommand, y as buildTerminalSpawnCommand } from "./agent-registry-DxcyXXqb.js";
1
+ import { $ as incrementPerfCounter, $t as SessionModeReplayError, A as findGitRepositoryRoot, At as extractAcpError, B as writeSessionRecord, C as promptToDisplayText, Ct as isProcessAlive, Dt as normalizeOutputError, E as lockOwnerPid, Et as isRetryablePromptError, G as extractAgentSessionId, Gt as AuthPolicyError, Ht as AgentDisconnectedError, I as normalizeName, J as SessionJournalReader, Jt as GeminiAcpStartupTimeoutError, K as normalizeAgentSessionId, Kt as ClaudeAcpSessionCreateTimeoutError, M as findSessionByDirectoryWalk, N as isoNow$1, Q as getPerfMetricsSnapshot, Qt as SessionConfigOptionReplayError, R as readSessionRecord, T as createLockOwner, Tt as formatErrorMessage, U as canonicalAgentCommand, Ut as AgentSpawnError, Vt as AcpxOperationalError, Wt as AgentStartupError, Xt as PermissionPromptUnavailableError, Yt as PermissionDeniedError, Z as formatPerfMetric, Zt as QueueConnectionError, _ as QueueLeaseGuardSettlementError, _t as sessionEventActivePath, a as trySetModeOnRunningOwner, at as isAcpJsonRpcMessage, b as getUnsupportedPromptContentMessage, c as SessionQueueOwner, d as refreshQueueOwnerLease, en as SessionModelReplayError, et as measurePerf, f as releaseQueueOwnerLease, g as waitMs$1, gt as sessionBaseDir, h as tryAcquireQueueOwnerLease, ht as retainedEventMaxSegments, i as trySetConfigOptionOnRunningOwner, in as describeSpawnEnoent, jt as isAcpResourceNotFoundError, k as absolutePath, m as terminateQueueOwnerForSession, mt as existingEventSegmentIndices, n as tryCancelOnRunningOwner, nn as SessionResumeRequiredError, nt as setPerfGauge, o as trySetModelOnRunningOwner, ot as isAcpMessageObject, p as terminateProcess, pt as defaultSessionEventLog, q as SESSION_JOURNAL_SCHEMA, qt as CopilotAcpUnsupportedError, r as tryCloseSessionOnRunningOwner, rn as UnsupportedPromptContentError, rt as startPerfTimer, s as trySubmitToRunningOwner, st as isSessionUpdateNotification, tt as resetPerfMetrics, v as ProcessDescendants, vt as sessionEventLockPath, w as textPrompt, yt as sessionEventSegmentPath, z as resolveSessionRecord } from "./ipc-DfqJsbk6.js";
2
+ import { A as waitForSpawn, D as runTimedExecFile, E as resolveAgentSessionCwd, F as readWindowsEnvValue, L as resolveWindowsCommand, M as buildSpawnCommandOptions, N as buildTerminalShellSpawnCommand, O as splitCommandLine, P as buildTerminalSpawnCommand, R as resolveWindowsExecutablePath, T as resolveAgentCommandParts, _ as PROCESS_HELPER_TIMEOUT_MS, b as isChildProcessRunning, f as resolveBuiltInAgentLaunch, j as buildAgentSpawnCommand, k as waitForChildExit, v as asAbsoluteCwd, w as requireAgentStdio, x as isoNow$2, y as basenameToken$1 } from "./agent-registry-CsdsVpJb.js";
3
3
  import fs, { readFileSync, realpathSync } from "node:fs";
4
4
  import { fileURLToPath, pathToFileURL } from "node:url";
5
5
  import path from "node:path";
@@ -16,7 +16,7 @@ import { PROTOCOL_VERSION, RequestError, client, methods } from "@1agents/acp-ru
16
16
  import { FsSafeError } from "@openclaw/fs-safe/errors";
17
17
  import { root } from "@openclaw/fs-safe/root";
18
18
  import readline from "node:readline/promises";
19
- //#region src/async-control.ts
19
+ // src/async-control.ts
20
20
  var TimeoutError = class extends Error {
21
21
  constructor(timeoutMs) {
22
22
  super(`Timed out after ${timeoutMs}ms`);
@@ -50,6 +50,7 @@ async function withTimeout(promise, timeoutMs) {
50
50
  async function withInterrupt(run, onInterrupt) {
51
51
  return await new Promise((resolve, reject) => {
52
52
  let settled = false;
53
+ let interrupting = false;
53
54
  const finish = (cb) => {
54
55
  if (settled) return;
55
56
  settled = true;
@@ -59,6 +60,8 @@ async function withInterrupt(run, onInterrupt) {
59
60
  cb();
60
61
  };
61
62
  const rejectInterrupted = (signal) => {
63
+ if (settled || interrupting) return;
64
+ interrupting = true;
62
65
  onInterrupt(signal).then(() => finish(() => reject(new InterruptedError())), (error) => finish(() => reject(error)));
63
66
  };
64
67
  const onSigint = () => {
@@ -73,11 +76,14 @@ async function withInterrupt(run, onInterrupt) {
73
76
  process.once("SIGINT", onSigint);
74
77
  process.once("SIGTERM", onSigterm);
75
78
  process.once("SIGHUP", onSighup);
76
- run().then((result) => finish(() => resolve(result)), (error) => finish(() => reject(error)));
79
+ run().then((result) => {
80
+ if (!interrupting) finish(() => resolve(result));
81
+ }, (error) => {
82
+ if (!interrupting) finish(() => reject(error));
83
+ });
77
84
  });
78
85
  }
79
- //#endregion
80
- //#region src/acp/codex-compat.ts
86
+ // src/acp/codex-compat.ts
81
87
  function basenameToken(value) {
82
88
  return path.basename(value).toLowerCase().replace(/\.(cmd|exe|bat)$/u, "");
83
89
  }
@@ -122,8 +128,7 @@ function codexPermissionNotice(request, response, agentName) {
122
128
  const selectedId = response.outcome.optionId;
123
129
  return request.options.find((option) => option.optionId === selectedId)?.kind === "reject_once" && selectedId === "cancel" ? "Permission refused using Codex's cancellation option; this can end the current turn. The operation was not approved." : void 0;
124
130
  }
125
- //#endregion
126
- //#region src/session/events.ts
131
+ // src/session/events.ts
127
132
  async function ensureSessionDir() {
128
133
  await fs$1.mkdir(sessionBaseDir(), {
129
134
  recursive: true,
@@ -386,8 +391,7 @@ async function listSessionEvents(sessionId, maxSegments) {
386
391
  eventLog: { max_segments: maxSegments }
387
392
  }).readAcpMessages();
388
393
  }
389
- //#endregion
390
- //#region src/session/turn-ownership.ts
394
+ // src/session/turn-ownership.ts
391
395
  const LOCK_RETRY_MS = 15;
392
396
  const INCOMPLETE_RESERVATION_GRACE_MS = 15e3;
393
397
  let lastCreatedAt = 0;
@@ -417,7 +421,7 @@ async function tryAcquireGuard(filePath, owner, signal) {
417
421
  return await acquireFileLock(filePath, {
418
422
  managerKey: "acpx.session-turn",
419
423
  lockPath: `${filePath}.guard`,
420
- staleMs: Infinity,
424
+ staleMs: 1e400,
421
425
  timeoutMs: LOCK_RETRY_MS,
422
426
  retry: {
423
427
  retries: 8,
@@ -626,16 +630,14 @@ async function acquireSessionOwnership(requestedPath, signal) {
626
630
  await setTimeout$1(LOCK_RETRY_MS, void 0, { signal });
627
631
  }
628
632
  }
629
- //#endregion
630
- //#region src/session/execution/contracts.ts
633
+ // src/session/execution/contracts.ts
631
634
  const DEFAULT_QUEUE_OWNER_TTL_MS = 3e5;
632
635
  function normalizeQueueOwnerTtlMs(ttlMs) {
633
636
  if (ttlMs == null) return DEFAULT_QUEUE_OWNER_TTL_MS;
634
637
  if (!Number.isFinite(ttlMs) || ttlMs < 0) return DEFAULT_QUEUE_OWNER_TTL_MS;
635
638
  return Math.round(ttlMs);
636
639
  }
637
- //#endregion
638
- //#region src/file-read-window.ts
640
+ // src/file-read-window.ts
639
641
  function sliceReadWindow(content, line, limit) {
640
642
  if (line == null && limit == null) return content;
641
643
  const lines = content.split("\n");
@@ -645,8 +647,7 @@ function sliceReadWindow(content, line, limit) {
645
647
  const endIndex = maxLines == null ? lines.length : Math.min(lines.length, startIndex + maxLines);
646
648
  return lines.slice(startIndex, endIndex).join("\n");
647
649
  }
648
- //#endregion
649
- //#region src/permission-prompt.ts
650
+ // src/permission-prompt.ts
650
651
  function visiblePromptText(value) {
651
652
  let rendered = "";
652
653
  for (const character of value) {
@@ -714,8 +715,7 @@ function writePromptDetails(options) {
714
715
  if (options.header) process.stderr.write(`\n${visiblePromptText(options.header)}\n`);
715
716
  if (options.details && options.details.trim().length > 0) process.stderr.write(`${options.details.split("\n").map(visiblePromptText).join("\n")}\n`);
716
717
  }
717
- //#endregion
718
- //#region src/filesystem.ts
718
+ // src/filesystem.ts
719
719
  const WRITE_PREVIEW_MAX_LINES = 16;
720
720
  const WRITE_PREVIEW_MAX_CHARS = 1200;
721
721
  function nowIso$1() {
@@ -907,7 +907,7 @@ var FileSystemHandlers = class {
907
907
  return this.workspace ??= root(this.rootDir, {
908
908
  symlinks: "follow-within-root",
909
909
  hardlinks: "allow",
910
- maxBytes: Infinity
910
+ maxBytes: 1e400
911
911
  });
912
912
  }
913
913
  readWindowDetails(line, limit) {
@@ -918,8 +918,7 @@ var FileSystemHandlers = class {
918
918
  this.onOperation?.(operation);
919
919
  }
920
920
  };
921
- //#endregion
922
- //#region src/permissions.ts
921
+ // src/permissions.ts
923
922
  const PERMISSION_MODE_RANK = {
924
923
  "deny-all": 0,
925
924
  "approve-reads": 1,
@@ -1147,7 +1146,7 @@ async function resolveReadOrPromptPermission(params, nonInteractivePolicy, allow
1147
1146
  function permissionModeSatisfies(actual, required) {
1148
1147
  return PERMISSION_MODE_RANK[actual] >= PERMISSION_MODE_RANK[required];
1149
1148
  }
1150
- async function resolvePermissionRequestWithDetails(params, mode, nonInteractivePolicy = "deny", policy, signal) {
1149
+ async function resolvePermissionRequest(params, mode, nonInteractivePolicy = "deny", policy, signal) {
1151
1150
  try {
1152
1151
  signal?.throwIfAborted();
1153
1152
  const result = await resolvePermissionByPolicy(params, mode, nonInteractivePolicy, policy, signal);
@@ -1189,8 +1188,7 @@ function classifyPermissionDecision(params, response) {
1189
1188
  if (selectedOption.kind === "allow_once" || selectedOption.kind === "allow_always") return "approved";
1190
1189
  return "denied";
1191
1190
  }
1192
- //#endregion
1193
- //#region src/acp/agent-command.ts
1191
+ // src/acp/agent-command.ts
1194
1192
  const DEFAULT_AGENT_CLOSE_AFTER_STDIN_END_MS = 100;
1195
1193
  const QODER_AGENT_CLOSE_AFTER_STDIN_END_MS = 750;
1196
1194
  const GEMINI_ACP_STARTUP_TIMEOUT_MS = 15e3;
@@ -1204,13 +1202,17 @@ const GEMINI_ACP_FLAG_VERSION = [
1204
1202
  const COPILOT_HELP_TIMEOUT_MS = 2e3;
1205
1203
  const CLAUDE_CODE_DEFAULT_SETTING_SOURCES = ["project", "local"];
1206
1204
  const QODER_BENIGN_STDOUT_LINES = /* @__PURE__ */ new Set(["Received interrupt signal. Cleaning up resources...", "Cleanup completed. Exiting..."]);
1205
+ function isQoderCommand(command) {
1206
+ const name = basenameToken$1(command);
1207
+ return name === "qoder" || name === "qodercli";
1208
+ }
1207
1209
  function resolveAgentCloseAfterStdinEndMs(agentCommand) {
1208
1210
  const { command } = splitCommandLine(agentCommand);
1209
- return basenameToken$1(command) === "qodercli" ? QODER_AGENT_CLOSE_AFTER_STDIN_END_MS : DEFAULT_AGENT_CLOSE_AFTER_STDIN_END_MS;
1211
+ return isQoderCommand(command) ? QODER_AGENT_CLOSE_AFTER_STDIN_END_MS : DEFAULT_AGENT_CLOSE_AFTER_STDIN_END_MS;
1210
1212
  }
1211
1213
  function shouldIgnoreNonJsonAgentOutputLine(agentCommand, trimmedLine) {
1212
1214
  const { command } = splitCommandLine(agentCommand);
1213
- return basenameToken$1(command) === "qodercli" && QODER_BENIGN_STDOUT_LINES.has(trimmedLine);
1215
+ return isQoderCommand(command) && QODER_BENIGN_STDOUT_LINES.has(trimmedLine);
1214
1216
  }
1215
1217
  function isGeminiAcpCommand(command, args) {
1216
1218
  return basenameToken$1(command) === "gemini" && (args.includes("--acp") || args.includes("--experimental-acp"));
@@ -1223,7 +1225,7 @@ function isCopilotAcpCommand(command, args) {
1223
1225
  return basenameToken$1(command) === "copilot" && args.includes("--acp");
1224
1226
  }
1225
1227
  function isQoderAcpCommand(command, args) {
1226
- return basenameToken$1(command) === "qodercli" && args.includes("--acp");
1228
+ return isQoderCommand(command) && args.includes("--acp");
1227
1229
  }
1228
1230
  function isCursorAcpCommand(command, args) {
1229
1231
  const commandToken = basenameToken$1(command);
@@ -1366,8 +1368,91 @@ function resolveClaudeCodeExecutable(platform = process.platform, env = process.
1366
1368
  if (readWindowsEnvValue(env, "CLAUDE_CODE_EXECUTABLE")) return;
1367
1369
  return resolveWindowsExecutablePath("claude", env, cwd);
1368
1370
  }
1369
- //#endregion
1370
- //#region src/acp/auth-env.ts
1371
+ // src/acp/inherited-env.ts
1372
+ const AUTH_GRANT_PREFIX = "ACPX_AUTH_";
1373
+ const POSIX_ESSENTIAL_NAMES = [
1374
+ "PATH",
1375
+ "HOME",
1376
+ "USER",
1377
+ "LOGNAME",
1378
+ "SHELL",
1379
+ "LANG",
1380
+ "LANGUAGE",
1381
+ "TZ",
1382
+ "TMPDIR",
1383
+ "TMP",
1384
+ "TEMP"
1385
+ ];
1386
+ const WINDOWS_ESSENTIAL_NAMES = [
1387
+ "SYSTEMROOT",
1388
+ "WINDIR",
1389
+ "SYSTEMDRIVE",
1390
+ "COMSPEC",
1391
+ "PATHEXT",
1392
+ "USERPROFILE",
1393
+ "HOMEDRIVE",
1394
+ "HOMEPATH",
1395
+ "USERNAME",
1396
+ "USERDOMAIN",
1397
+ "APPDATA",
1398
+ "LOCALAPPDATA",
1399
+ "PROGRAMDATA",
1400
+ "ALLUSERSPROFILE",
1401
+ "PROGRAMFILES",
1402
+ "PROGRAMFILES(X86)",
1403
+ "PROGRAMW6432",
1404
+ "COMMONPROGRAMFILES",
1405
+ "COMMONPROGRAMFILES(X86)",
1406
+ "COMMONPROGRAMW6432"
1407
+ ];
1408
+ const ESSENTIAL_PREFIXES = ["LC_", "XDG_"];
1409
+ /** Environment name as compared on this platform: Windows names are case-insensitive. */
1410
+ function envNameKey(name) {
1411
+ return process.platform === "win32" ? name.toUpperCase() : name;
1412
+ }
1413
+ function essentialNames() {
1414
+ return process.platform === "win32" ? [...POSIX_ESSENTIAL_NAMES, ...WINDOWS_ESSENTIAL_NAMES] : POSIX_ESSENTIAL_NAMES;
1415
+ }
1416
+ function isEnvName(name) {
1417
+ return typeof name === "string" && name.length > 0 && !name.includes("=") && !name.includes("\0");
1418
+ }
1419
+ function validateEnvNames(option, names) {
1420
+ if (!Array.isArray(names) || !names.every(isEnvName)) throw new Error(`Invalid ${option}: expected an array of non-empty names without NUL or '='`);
1421
+ return names;
1422
+ }
1423
+ /** Validate and copy an embedder's name list once, when a client or runtime is constructed. */
1424
+ function snapshotEnvNames(option, names) {
1425
+ return names === void 0 ? void 0 : [...validateEnvNames(option, names)];
1426
+ }
1427
+ function inheritedNameFilter(policy) {
1428
+ const blocked = new Set((policy?.block ?? []).map(envNameKey));
1429
+ const allowed = policy?.allow ? new Set([...essentialNames(), ...policy.allow].map(envNameKey)) : void 0;
1430
+ return (name) => {
1431
+ const key = envNameKey(name);
1432
+ if (key.startsWith(AUTH_GRANT_PREFIX)) return true;
1433
+ if (blocked.has(key)) return false;
1434
+ return !allowed || allowed.has(key) || ESSENTIAL_PREFIXES.some((p) => key.startsWith(p));
1435
+ };
1436
+ }
1437
+ /** Whether a parent environment name reaches agent children under this policy. */
1438
+ function isInheritedEnvName(policy, name) {
1439
+ return inheritedNameFilter(policy)(name);
1440
+ }
1441
+ /** Whether the policy changes inheritance at all; with neither list set it does not. */
1442
+ function hasInheritedEnvPolicy(policy) {
1443
+ return policy?.allow !== void 0 || (policy?.block?.length ?? 0) > 0;
1444
+ }
1445
+ /** Copy the parent environment, keeping only the names this policy lets children inherit. */
1446
+ function inheritParentEnvironment(policy) {
1447
+ const env = { ...process.env };
1448
+ if (!hasInheritedEnvPolicy(policy)) return env;
1449
+ validateEnvNames("agentProcessEnvAllow", policy?.allow ?? []);
1450
+ validateEnvNames("agentProcessEnvBlock", policy?.block ?? []);
1451
+ const inherits = inheritedNameFilter(policy);
1452
+ for (const name of Object.keys(env)) if (!inherits(name)) delete env[name];
1453
+ return env;
1454
+ }
1455
+ // src/acp/auth-env.ts
1371
1456
  const AUTH_ENV_PREFIX = "ACPX_AUTH_";
1372
1457
  const CLAUDE_SETTINGS_ENV_KEYS = [
1373
1458
  "ANTHROPIC_AUTH_TOKEN",
@@ -1444,15 +1529,12 @@ function promotePrefixedAuthEnvironment(env) {
1444
1529
  }
1445
1530
  return protectedKeys;
1446
1531
  }
1447
- function baseAgentEnvironment() {
1448
- return { ...process.env };
1449
- }
1450
1532
  function validateAgentProcessEnv(agentProcessEnv) {
1451
1533
  for (const [key, value] of Object.entries(agentProcessEnv ?? {})) if (typeof value !== "string" || key.includes("=") || key.includes("\0") || value.includes("\0")) throw new Error("Invalid agentProcessEnv: environment entries cannot contain NUL or names with '='");
1452
1534
  }
1453
- function buildAgentEnvironment(authCredentials, sessionEnv, agentProcessEnv, includeClaudeSettings = false) {
1535
+ function buildAgentEnvironment(authCredentials, sessionEnv, agentProcessEnv, includeClaudeSettings = false, inheritedEnv) {
1454
1536
  validateAgentProcessEnv(agentProcessEnv);
1455
- const env = baseAgentEnvironment();
1537
+ const env = inheritParentEnvironment(inheritedEnv);
1456
1538
  if (includeClaudeSettings) applyClaudeSettingsEnvironment(env);
1457
1539
  const protectedAuthEnvKeys = promotePrefixedAuthEnvironment(env);
1458
1540
  if (authCredentials) for (const [methodId, credential] of Object.entries(authCredentials)) {
@@ -1506,14 +1588,17 @@ function resolveConfiguredAuthCredential(methodId, authCredentials) {
1506
1588
  const configCredentials = authCredentials ?? {};
1507
1589
  return configCredentials[methodId] ?? configCredentials[toEnvToken(methodId)];
1508
1590
  }
1509
- function buildAgentSpawnOptions(cwd, authCredentials, sessionEnv, agentProcessEnvOrClaudeSettings, includeClaudeSettings = false) {
1591
+ function buildAgentSpawnOptions(cwd, authCredentials, sessionEnv, agentProcessEnvOrClaudeSettings, includeClaudeSettingsOrInheritedEnv, inheritedEnv) {
1510
1592
  let agentProcessEnv;
1511
- let claudeSettings = includeClaudeSettings;
1593
+ let claudeSettings = false;
1594
+ let inheritedEnvPolicy = inheritedEnv;
1512
1595
  if (typeof agentProcessEnvOrClaudeSettings === "boolean") claudeSettings = agentProcessEnvOrClaudeSettings;
1513
1596
  else if (agentProcessEnvOrClaudeSettings && typeof agentProcessEnvOrClaudeSettings === "object") agentProcessEnv = agentProcessEnvOrClaudeSettings;
1597
+ if (typeof includeClaudeSettingsOrInheritedEnv === "boolean") claudeSettings = includeClaudeSettingsOrInheritedEnv;
1598
+ else if (includeClaudeSettingsOrInheritedEnv && inheritedEnv === void 0) inheritedEnvPolicy = includeClaudeSettingsOrInheritedEnv;
1514
1599
  return {
1515
1600
  cwd,
1516
- env: buildAgentEnvironment(authCredentials, sessionEnv, agentProcessEnv, claudeSettings),
1601
+ env: buildAgentEnvironment(authCredentials, sessionEnv, agentProcessEnv, claudeSettings, inheritedEnvPolicy),
1517
1602
  stdio: [
1518
1603
  "pipe",
1519
1604
  "pipe",
@@ -1522,8 +1607,7 @@ function buildAgentSpawnOptions(cwd, authCredentials, sessionEnv, agentProcessEn
1522
1607
  windowsHide: true
1523
1608
  };
1524
1609
  }
1525
- //#endregion
1526
- //#region src/version.ts
1610
+ // src/version.ts
1527
1611
  const UNKNOWN_VERSION = "0.0.0-unknown";
1528
1612
  const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
1529
1613
  let cachedVersion = null;
@@ -1565,8 +1649,7 @@ function getAcpxVersion() {
1565
1649
  cachedVersion = resolveAcpxVersion();
1566
1650
  return cachedVersion;
1567
1651
  }
1568
- //#endregion
1569
- //#region src/acp/client-protocol.ts
1652
+ // src/acp/client-protocol.ts
1570
1653
  const DEVIN_COMPATIBILITY_CLIENT_CAPABILITIES_META = Object.freeze({ "cognition.ai/requestDiagnostics": true });
1571
1654
  const DEVIN_COMPATIBILITY_CLIENT_NAME = "windsurf";
1572
1655
  const DEFAULT_DEVIN_COMPATIBILITY_CLIENT_VERSION = "1.110.1";
@@ -1598,8 +1681,7 @@ function resolveClientCapabilities(params) {
1598
1681
  _meta: DEVIN_COMPATIBILITY_CLIENT_CAPABILITIES_META
1599
1682
  };
1600
1683
  }
1601
- //#endregion
1602
- //#region src/acp/command-probe.ts
1684
+ // src/acp/command-probe.ts
1603
1685
  var CommandProbeAdmissionError = class extends Error {
1604
1686
  reason;
1605
1687
  constructor(reason) {
@@ -1665,8 +1747,7 @@ function captureCommandProbeOutput(child, timeoutMs, retire) {
1665
1747
  }
1666
1748
  };
1667
1749
  }
1668
- //#endregion
1669
- //#region src/acp/grok-ask-user.ts
1750
+ // src/acp/grok-ask-user.ts
1670
1751
  /**
1671
1752
  * Grok Build ACP client extension: `_x.ai/ask_user_question`.
1672
1753
  *
@@ -1836,8 +1917,7 @@ function normalizeHostAskUserResponse(value) {
1836
1917
  }
1837
1918
  if (isRecord$1(value)) return acceptedAskUserResponse(value);
1838
1919
  }
1839
- //#endregion
1840
- //#region src/acp/grok-exit-plan.ts
1920
+ // src/acp/grok-exit-plan.ts
1841
1921
  /**
1842
1922
  * Grok Build ACP client extension: `_x.ai/exit_plan_mode`.
1843
1923
  *
@@ -1931,8 +2011,7 @@ async function promptGrokExitPlanMode(request) {
1931
2011
  rl.close();
1932
2012
  }
1933
2013
  }
1934
- //#endregion
1935
- //#region src/acp/model-config-state.ts
2014
+ // src/acp/model-config-state.ts
1936
2015
  function asRecord$2(value) {
1937
2016
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
1938
2017
  return value;
@@ -1991,8 +2070,7 @@ function modelStateFromConfigOptions(configOptions) {
1991
2070
  }
1992
2071
  return selected;
1993
2072
  }
1994
- //#endregion
1995
- //#region src/acp/model-support.ts
2073
+ // src/acp/model-support.ts
1996
2074
  const REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE = "ACP_MODEL_UNSUPPORTED";
1997
2075
  const REQUESTED_MODEL_UNSUPPORTED_REASONS = ["missing-capability", "unadvertised-model"];
1998
2076
  var RequestedModelUnsupportedError = class extends Error {
@@ -2078,8 +2156,7 @@ function assertRequestedModelSupported(params) {
2078
2156
  throw new RequestedModelUnsupportedError(`Cannot ${params.context === "replay" ? "replay saved model" : "apply --model"} "${params.requestedModel}": the ACP agent did not advertise that model. Available models: ${formatAvailableModelIds(params.models)}.`, "unadvertised-model");
2079
2157
  }
2080
2158
  }
2081
- //#endregion
2082
- //#region src/acp/ndjson-stream.ts
2159
+ // src/acp/ndjson-stream.ts
2083
2160
  const DEFAULT_MAX_ACP_MESSAGE_BYTES = 67108864;
2084
2161
  var AcpMessageLimitError = class extends AcpxOperationalError {
2085
2162
  constructor(limit) {
@@ -2115,27 +2192,27 @@ function parseAcpJsonMessageLine(line) {
2115
2192
  const message = JSON.parse(line);
2116
2193
  return isAcpMessageObject(message) ? message : void 0;
2117
2194
  }
2118
- function enqueueNdJsonLine(agentCommand, line, controller) {
2195
+ function enqueueNdJsonLine(agentCommand, line, controller, quietInvalidLines) {
2119
2196
  const trimmedLine = line.trim();
2120
2197
  if (!trimmedLine || shouldIgnoreNonJsonAgentOutputLine(agentCommand, trimmedLine)) return;
2121
2198
  try {
2122
2199
  const message = parseAcpJsonMessageLine(trimmedLine);
2123
2200
  if (message) controller.enqueue(message);
2124
2201
  } catch (err) {
2125
- console.error("Failed to parse JSON message:", trimmedLine, err);
2202
+ if (!quietInvalidLines?.()) console.error("Failed to parse JSON message:", trimmedLine, err);
2126
2203
  }
2127
2204
  }
2128
- function enqueueNdJsonChunk(agentCommand, chunk, fragments, controller) {
2205
+ function enqueueNdJsonChunk(agentCommand, chunk, fragments, controller, quietInvalidLines) {
2129
2206
  const lines = chunk.split("\n");
2130
2207
  const suffix = lines.pop() || "";
2131
2208
  if (lines.length > 0 && fragments.length > 0) {
2132
2209
  lines[0] = fragments.join("") + lines[0];
2133
2210
  fragments.length = 0;
2134
2211
  }
2135
- for (const line of lines) enqueueNdJsonLine(agentCommand, line, controller);
2212
+ for (const line of lines) enqueueNdJsonLine(agentCommand, line, controller, quietInvalidLines);
2136
2213
  if (suffix) fragments.push(suffix);
2137
2214
  }
2138
- function createNdJsonMessageStream(agentCommand, output, input, maxMessageBytes, onReadError) {
2215
+ function createNdJsonMessageStream(agentCommand, output, input, maxMessageBytes, onReadError, quietInvalidLines) {
2139
2216
  const textEncoder = new TextEncoder();
2140
2217
  const textDecoder = new TextDecoder();
2141
2218
  return {
@@ -2148,7 +2225,7 @@ function createNdJsonMessageStream(agentCommand, output, input, maxMessageBytes,
2148
2225
  const { value, done } = await reader.read();
2149
2226
  if (done) break;
2150
2227
  if (maxMessageBytes !== void 0) retainedBytes = countLineBytes(value, retainedBytes, maxMessageBytes);
2151
- enqueueNdJsonChunk(agentCommand, textDecoder.decode(value, { stream: true }), fragments, controller);
2228
+ enqueueNdJsonChunk(agentCommand, textDecoder.decode(value, { stream: true }), fragments, controller, quietInvalidLines);
2152
2229
  }
2153
2230
  controller.close();
2154
2231
  } catch (err) {
@@ -2170,8 +2247,7 @@ function createNdJsonMessageStream(agentCommand, output, input, maxMessageBytes,
2170
2247
  } })
2171
2248
  };
2172
2249
  }
2173
- //#endregion
2174
- //#region src/acp/observed-stream.ts
2250
+ // src/acp/observed-stream.ts
2175
2251
  function observeAcpStream(base, options) {
2176
2252
  const elicitationRequestIds = /* @__PURE__ */ new Set();
2177
2253
  const shouldSuppressInboundReplaySessionUpdate = (message) => {
@@ -2238,8 +2314,7 @@ function promptRequestOwner(message) {
2238
2314
  sessionId
2239
2315
  } : void 0;
2240
2316
  }
2241
- //#endregion
2242
- //#region src/acp/session-control-errors.ts
2317
+ // src/acp/session-control-errors.ts
2243
2318
  const SESSION_CONTROL_UNSUPPORTED_ACP_CODES = /* @__PURE__ */ new Set([-32601, -32602]);
2244
2319
  function asRecord$1(value) {
2245
2320
  if (!value || typeof value !== "object" || Array.isArray(value)) return;
@@ -2252,8 +2327,8 @@ function isLikelySessionControlUnsupportedError(acp) {
2252
2327
  return typeof details === "string" && details.toLowerCase().includes("invalid params");
2253
2328
  }
2254
2329
  function formatSessionControlAcpSummary(acp) {
2255
- const details = asRecord$1(acp.data)?.details;
2256
- if (typeof details === "string" && details.trim().length > 0) return `${details.trim()} (ACP ${acp.code}, adapter reported "${acp.message}")`;
2330
+ const data = asRecord$1(acp.data);
2331
+ for (const value of [data?.details, data?.message]) if (typeof value === "string" && value.trim().length > 0) return `${value.trim()} (ACP ${acp.code}, adapter reported "${acp.message}")`;
2257
2332
  return `${acp.message} (ACP ${acp.code})`;
2258
2333
  }
2259
2334
  function maybeWrapSessionControlError(method, error, context) {
@@ -2265,8 +2340,7 @@ function maybeWrapSessionControlError(method, error, context) {
2265
2340
  wrapped.acp = acp;
2266
2341
  return wrapped;
2267
2342
  }
2268
- //#endregion
2269
- //#region src/acp/terminal-manager.ts
2343
+ // src/acp/terminal-manager.ts
2270
2344
  const DEFAULT_TERMINAL_OUTPUT_LIMIT_BYTES = 65536;
2271
2345
  const DEFAULT_KILL_GRACE_MS = 1500;
2272
2346
  function nowIso() {
@@ -2276,14 +2350,14 @@ function toCommandLine(command, args) {
2276
2350
  const renderedArgs = (args ?? []).map((arg) => JSON.stringify(arg)).join(" ");
2277
2351
  return renderedArgs.length > 0 ? `${command} ${renderedArgs}` : command;
2278
2352
  }
2279
- function toEnvObject(env) {
2280
- if (!env || env.length === 0) return;
2281
- const merged = { ...process.env };
2282
- for (const entry of env) merged[entry.name] = entry.value;
2353
+ function toEnvObject(env, inheritedEnv) {
2354
+ if (!env?.length && !hasInheritedEnvPolicy(inheritedEnv)) return;
2355
+ const merged = inheritParentEnvironment(inheritedEnv);
2356
+ for (const entry of env ?? []) merged[entry.name] = entry.value;
2283
2357
  return merged;
2284
2358
  }
2285
- function buildTerminalSpawnOptions(command, cwd, env, platform = process.platform) {
2286
- const resolvedEnv = toEnvObject(env);
2359
+ function buildTerminalSpawnOptions(command, cwd, env, platform = process.platform, inheritedEnv) {
2360
+ const resolvedEnv = toEnvObject(env, inheritedEnv);
2287
2361
  return buildSpawnCommandOptions(command, {
2288
2362
  cwd,
2289
2363
  env: resolvedEnv,
@@ -2305,9 +2379,6 @@ function readTerminalOutputCeiling() {
2305
2379
  function resolveTerminalOutputLimit(requested, ceiling) {
2306
2380
  return Math.min(Math.max(0, Math.round(requested ?? DEFAULT_TERMINAL_OUTPUT_LIMIT_BYTES)), ceiling ?? Number.POSITIVE_INFINITY);
2307
2381
  }
2308
- function tracksTerminalDescendants(terminal) {
2309
- return terminal.killProcessGroup || terminal.descendants !== void 0;
2310
- }
2311
2382
  function createTerminalDescendants(proc, killProcessGroup) {
2312
2383
  return process.platform === "win32" && killProcessGroup ? void 0 : new ProcessDescendants(proc, { ownProcessGroup: true });
2313
2384
  }
@@ -2335,6 +2406,7 @@ function waitMs(ms) {
2335
2406
  function onStreamError() {}
2336
2407
  var TerminalManager = class {
2337
2408
  cwd;
2409
+ inheritedEnv;
2338
2410
  permissionMode;
2339
2411
  nonInteractivePermissions;
2340
2412
  onOperation;
@@ -2348,6 +2420,7 @@ var TerminalManager = class {
2348
2420
  constructor(options) {
2349
2421
  this.outputCeilingBytes = readTerminalOutputCeiling();
2350
2422
  this.cwd = options.cwd;
2423
+ this.inheritedEnv = options.inheritedEnv;
2351
2424
  this.permissionMode = options.permissionMode;
2352
2425
  this.nonInteractivePermissions = options.nonInteractivePermissions ?? "deny";
2353
2426
  this.onOperation = options.onOperation;
@@ -2384,7 +2457,10 @@ var TerminalManager = class {
2384
2457
  assertControlAuthority(authority);
2385
2458
  if (!approved) throw new PermissionDeniedError("Permission denied for terminal/create");
2386
2459
  const outputByteLimit = resolveTerminalOutputLimit(params.outputByteLimit, this.outputCeilingBytes);
2387
- const { proc, spawnCommand } = await spawnTerminalProcess(params, this.cwd, authority);
2460
+ const { proc, spawnCommand } = await spawnTerminalProcess(params, {
2461
+ cwd: this.cwd,
2462
+ inheritedEnv: this.inheritedEnv
2463
+ }, authority);
2388
2464
  let resolveExit = () => {};
2389
2465
  const exitPromise = new Promise((resolve) => {
2390
2466
  resolveExit = resolve;
@@ -2603,7 +2679,6 @@ var TerminalManager = class {
2603
2679
  return terminal.exitCode === void 0 && terminal.signal === void 0;
2604
2680
  }
2605
2681
  async killProcess(terminal) {
2606
- if (!this.isRunning(terminal) && !tracksTerminalDescendants(terminal)) return;
2607
2682
  try {
2608
2683
  await this.signalProcess(terminal, "SIGTERM");
2609
2684
  } catch {
@@ -2655,28 +2730,36 @@ var TerminalManager = class {
2655
2730
  return true;
2656
2731
  }
2657
2732
  };
2658
- async function spawnTerminalProcess(params, defaultCwd, authority) {
2733
+ async function spawnTerminalProcess(params, context, authority) {
2659
2734
  const directCommand = buildTerminalSpawnCommand(params.command, params.args);
2660
2735
  try {
2661
2736
  return {
2662
- proc: await spawnAndWait(directCommand, params, defaultCwd, authority),
2737
+ proc: await spawnAndWait(directCommand, params, context, authority),
2663
2738
  spawnCommand: directCommand
2664
2739
  };
2665
2740
  } catch (error) {
2666
- const fallbackCommand = params.args === void 0 && isCommandLineSpawnError(error) ? buildTerminalFallbackSpawnCommand(params.command, params.cwd ?? defaultCwd) : void 0;
2741
+ const fallbackCommand = params.args === void 0 && isCommandLineSpawnError(error) ? buildTerminalFallbackSpawnCommand(params.command, params.cwd ?? context.cwd) : void 0;
2667
2742
  if (!fallbackCommand) throw error;
2668
2743
  return {
2669
- proc: await spawnAndWait(fallbackCommand, params, defaultCwd, authority),
2744
+ proc: await spawnAndWait(fallbackCommand, params, context, authority),
2670
2745
  spawnCommand: fallbackCommand
2671
2746
  };
2672
2747
  }
2673
2748
  }
2674
- async function spawnAndWait(spawnCommand, params, defaultCwd, authority) {
2675
- const spawnOptions = buildTerminalSpawnOptions(spawnCommand.command, params.cwd ?? defaultCwd, params.env);
2749
+ async function spawnAndWait(spawnCommand, params, context, authority) {
2750
+ const spawnOptions = buildTerminalSpawnOptions(spawnCommand.command, params.cwd ?? context.cwd, params.env, process.platform, context.inheritedEnv);
2676
2751
  if (process.platform !== "win32") spawnOptions.detached = true;
2677
2752
  assertControlAuthority(authority);
2678
2753
  const proc = spawn(spawnCommand.command, spawnCommand.args, spawnOptions);
2679
- await waitForSpawn(proc);
2754
+ try {
2755
+ await waitForSpawn(proc);
2756
+ } catch (error) {
2757
+ throw describeSpawnEnoent(error, "", {
2758
+ command: spawnCommand.command,
2759
+ cwd: spawnOptions.cwd,
2760
+ env: spawnOptions.env ?? process.env
2761
+ });
2762
+ }
2680
2763
  return proc;
2681
2764
  }
2682
2765
  function isCommandLineSpawnError(error) {
@@ -2782,8 +2865,7 @@ function hasLivePid(pids) {
2782
2865
  }
2783
2866
  return false;
2784
2867
  }
2785
- //#endregion
2786
- //#region src/acp/client.ts
2868
+ // src/acp/client.ts
2787
2869
  const REPLAY_IDLE_MS = 80;
2788
2870
  const REPLAY_DRAIN_TIMEOUT_MS = 5e3;
2789
2871
  const DRAIN_POLL_INTERVAL_MS = 20;
@@ -2989,7 +3071,6 @@ var AcpClient = class AcpClient {
2989
3071
  suppressSessionUpdates = false;
2990
3072
  bufferedSessionUpdates = [];
2991
3073
  static MAX_BUFFERED_SESSION_UPDATES = 64;
2992
- suppressReplaySessionUpdateMessages = false;
2993
3074
  activePrompt;
2994
3075
  pendingPromptOwners = [];
2995
3076
  cancellingSessionIds = /* @__PURE__ */ new Set();
@@ -3011,6 +3092,8 @@ var AcpClient = class AcpClient {
3011
3092
  ...options,
3012
3093
  cwd: asAbsoluteCwd(options.cwd),
3013
3094
  agentProcessEnv: options.agentProcessEnv ? { ...options.agentProcessEnv } : void 0,
3095
+ agentProcessEnvAllow: snapshotEnvNames("agentProcessEnvAllow", options.agentProcessEnvAllow),
3096
+ agentProcessEnvBlock: snapshotEnvNames("agentProcessEnvBlock", options.agentProcessEnvBlock),
3014
3097
  authPolicy: options.authPolicy ?? "skip",
3015
3098
  permissionPolicy: snapshotPermissionPolicy(options.permissionPolicy),
3016
3099
  elicitationModes: normalizeElicitationModes(options.elicitationModes)
@@ -3037,6 +3120,7 @@ var AcpClient = class AcpClient {
3037
3120
  });
3038
3121
  this.terminalManager = new TerminalManager({
3039
3122
  cwd: this.options.cwd,
3123
+ inheritedEnv: this.inheritedEnvPolicy(),
3040
3124
  permissionMode: this.options.permissionMode,
3041
3125
  nonInteractivePermissions: this.options.nonInteractivePermissions,
3042
3126
  ...grokBuildAcp ? { confirmExecute: async (commandLine, ctx) => await this.confirmGrokClientOperation(ctx.sessionId ?? "", "execute", `Run ${commandLine}`, { command: commandLine }) } : {},
@@ -3189,7 +3273,7 @@ var AcpClient = class AcpClient {
3189
3273
  const stream = this.createTappedStream(createNdJsonMessageStream(this.options.agentCommand, input, output, maxMessageBytes, (error) => {
3190
3274
  this.rejectPendingConnectionRequests(error);
3191
3275
  connection?.close(error);
3192
- }));
3276
+ }, () => this.options.suppressSdkConsoleErrors === true));
3193
3277
  const capabilities = resolveClientCapabilities({
3194
3278
  devinAcp: launch.devinAcp,
3195
3279
  fs: this.options.fs !== false,
@@ -3225,7 +3309,7 @@ var AcpClient = class AcpClient {
3225
3309
  let args = resolvedBuiltInLaunch?.args ?? configuredCommand.args;
3226
3310
  const claudeAcp = isClaudeAcpCommand(spawnCommand, args);
3227
3311
  const codexAcp = isCodexAcpCommand(spawnCommand, args);
3228
- const spawnOptions = buildAgentSpawnOptions(this.options.cwd, this.options.authCredentials, this.options.sessionOptions?.env, this.options.agentProcessEnv, claudeAcp);
3312
+ const spawnOptions = buildAgentSpawnOptions(this.options.cwd, this.options.authCredentials, this.options.sessionOptions?.env, this.options.agentProcessEnv, claudeAcp, this.inheritedEnvPolicy());
3229
3313
  const commandContext = {
3230
3314
  env: spawnOptions.env,
3231
3315
  readOutput: async (command, args, timeoutMs, diagnostic = false) => {
@@ -3324,7 +3408,11 @@ var AcpClient = class AcpClient {
3324
3408
  });
3325
3409
  await waitForSpawn(spawnedChild);
3326
3410
  } catch (error) {
3327
- const spawnError = new AgentSpawnError(this.options.agentCommand, error);
3411
+ const spawnError = new AgentSpawnError(this.options.agentCommand, error, {
3412
+ command: launch.command,
3413
+ cwd: launch.cwd,
3414
+ env: plan.spawnOptions.env
3415
+ });
3328
3416
  this.notifyProcessSpawnFailure(launch, spawnError);
3329
3417
  throw spawnError;
3330
3418
  }
@@ -3375,7 +3463,11 @@ var AcpClient = class AcpClient {
3375
3463
  detached: process.platform !== "win32"
3376
3464
  });
3377
3465
  } catch (error) {
3378
- this.notifyProcessSpawnFailure(launch, new AgentSpawnError(command, error));
3466
+ this.notifyProcessSpawnFailure(launch, new AgentSpawnError(command, error, {
3467
+ command: launch.command,
3468
+ cwd: launch.cwd,
3469
+ env: options.env
3470
+ }));
3379
3471
  return;
3380
3472
  }
3381
3473
  this.commandProbes.add(child);
@@ -3385,7 +3477,11 @@ var AcpClient = class AcpClient {
3385
3477
  try {
3386
3478
  await waitForSpawn(child);
3387
3479
  } catch (error) {
3388
- this.notifyProcessSpawnFailure(launch, new AgentSpawnError(command, error));
3480
+ this.notifyProcessSpawnFailure(launch, new AgentSpawnError(command, error, {
3481
+ command: launch.command,
3482
+ cwd: launch.cwd,
3483
+ env: options.env
3484
+ }));
3389
3485
  return;
3390
3486
  }
3391
3487
  if (child.pid === void 0) {
@@ -3513,7 +3609,7 @@ var AcpClient = class AcpClient {
3513
3609
  this.eventHandlers.onAcpOutputMessage?.(direction, message);
3514
3610
  this.eventHandlers.onAcpMessage?.(direction, message);
3515
3611
  },
3516
- suppressReplaySessionUpdates: () => this.suppressReplaySessionUpdateMessages,
3612
+ suppressReplaySessionUpdates: () => this.suppressSessionUpdates,
3517
3613
  bindPromptOwner: (owner) => this.bindPromptOwner(owner),
3518
3614
  assertPromptActive: (active) => this.assertPromptActive(active),
3519
3615
  onPromptRequestWritten: (active, owner) => this.onPromptRequestWritten(active, owner)
@@ -3568,7 +3664,8 @@ var AcpClient = class AcpClient {
3568
3664
  const connection = this.getConnection();
3569
3665
  const sessionCwd = await resolveAgentSessionCwd(cwd, this.options.agentCommand);
3570
3666
  assertControlAuthority(options.authority);
3571
- const previousSuppression = this.applySessionUpdateSuppression(Boolean(options.suppressReplayUpdates));
3667
+ const previousSuppression = this.suppressSessionUpdates;
3668
+ this.suppressSessionUpdates = previousSuppression || Boolean(options.suppressReplayUpdates);
3572
3669
  let response;
3573
3670
  try {
3574
3671
  response = await this.runConnectionRequest(() => connection.agent.request(methods.agent.session.load, {
@@ -3579,7 +3676,7 @@ var AcpClient = class AcpClient {
3579
3676
  }), options.authority);
3580
3677
  await this.waitForSessionUpdateDrain(options.replayIdleMs ?? REPLAY_IDLE_MS, options.replayDrainTimeoutMs ?? REPLAY_DRAIN_TIMEOUT_MS);
3581
3678
  } finally {
3582
- this.restoreSessionUpdateSuppression(previousSuppression);
3679
+ this.suppressSessionUpdates = previousSuppression;
3583
3680
  }
3584
3681
  this.loadedSessionId = sessionId;
3585
3682
  const result = toReconnectedSessionResult(response);
@@ -3607,19 +3704,6 @@ var AcpClient = class AcpClient {
3607
3704
  await this.captureAgentDescendants(this.agent);
3608
3705
  return result;
3609
3706
  }
3610
- applySessionUpdateSuppression(enabled) {
3611
- const previous = {
3612
- suppressSessionUpdates: this.suppressSessionUpdates,
3613
- suppressReplaySessionUpdateMessages: this.suppressReplaySessionUpdateMessages
3614
- };
3615
- this.suppressSessionUpdates = previous.suppressSessionUpdates || enabled;
3616
- this.suppressReplaySessionUpdateMessages = previous.suppressReplaySessionUpdateMessages || enabled;
3617
- return previous;
3618
- }
3619
- restoreSessionUpdateSuppression(previous) {
3620
- this.suppressSessionUpdates = previous.suppressSessionUpdates;
3621
- this.suppressReplaySessionUpdateMessages = previous.suppressReplaySessionUpdateMessages;
3622
- }
3623
3707
  async prompt(sessionId, prompt, onRequestWritten, onElicitation, onPermissionRequest, authority) {
3624
3708
  const connection = this.getConnection();
3625
3709
  const normalizedPrompt = this.normalizePromptForAgent(prompt);
@@ -3929,7 +4013,6 @@ var AcpClient = class AcpClient {
3929
4013
  this.observedSessionUpdates = 0;
3930
4014
  this.processedSessionUpdates = 0;
3931
4015
  this.suppressSessionUpdates = false;
3932
- this.suppressReplaySessionUpdateMessages = false;
3933
4016
  this.activePrompt = void 0;
3934
4017
  this.pendingPromptOwners.length = 0;
3935
4018
  this.cancellingSessionIds.clear();
@@ -4151,8 +4234,14 @@ var AcpClient = class AcpClient {
4151
4234
  if (agentManagedSelection) return agentManagedSelection;
4152
4235
  }
4153
4236
  }
4237
+ inheritedEnvPolicy() {
4238
+ return {
4239
+ allow: this.options.agentProcessEnvAllow,
4240
+ block: this.options.agentProcessEnvBlock
4241
+ };
4242
+ }
4154
4243
  readAgentSpecificEnvCredential(methodId) {
4155
- if (!this.isGrokBuildAcpCommand() || methodId !== "xai.api_key") return;
4244
+ if (!this.isGrokBuildAcpCommand() || methodId !== "xai.api_key" || !isInheritedEnvName(this.inheritedEnvPolicy(), "XAI_API_KEY")) return;
4156
4245
  return nonEmptyEnvironmentValue(process.env.XAI_API_KEY);
4157
4246
  }
4158
4247
  selectAgentManagedAuthMethod(methodId) {
@@ -4421,7 +4510,7 @@ var AcpClient = class AcpClient {
4421
4510
  async resolvePermissionRequestFromMode(params, owner) {
4422
4511
  try {
4423
4512
  assertControlAuthority(owner);
4424
- const result = await resolvePermissionRequestWithDetails(preferCodexPermissionRefusal(params, this.initResult?.agentInfo?.name), this.options.permissionMode, this.options.nonInteractivePermissions ?? "deny", this.options.permissionPolicy, owner.signal);
4513
+ const result = await resolvePermissionRequest(preferCodexPermissionRefusal(params, this.initResult?.agentInfo?.name), this.options.permissionMode, this.options.nonInteractivePermissions ?? "deny", this.options.permissionPolicy, owner.signal);
4425
4514
  assertControlAuthority(owner);
4426
4515
  this.emitPermissionEscalation(result.escalation);
4427
4516
  return this.explainPermissionRefusal(params, result.response);
@@ -4520,7 +4609,16 @@ var AcpClient = class AcpClient {
4520
4609
  this.log(`process lifecycle ${hook} hook failed: ${message}`);
4521
4610
  }
4522
4611
  recordAgentExit(child, reason, exitCode, signal) {
4523
- if (this.agent !== child || this.lastAgentExit) return;
4612
+ if (this.agent !== child) return;
4613
+ const recorded = this.lastAgentExit;
4614
+ if (recorded) {
4615
+ if (recorded.unexpectedDuringPrompt && recorded.exitCode === null && recorded.signal === null) this.lastAgentExit = {
4616
+ ...recorded,
4617
+ exitCode,
4618
+ signal
4619
+ };
4620
+ return;
4621
+ }
4524
4622
  this.lastAgentExit = {
4525
4623
  exitCode,
4526
4624
  signal,
@@ -4704,8 +4802,7 @@ var AcpClient = class AcpClient {
4704
4802
  await this.waitForSessionUpdateDrain(options?.idleMs ?? 0, options?.timeoutMs ?? 0);
4705
4803
  }
4706
4804
  };
4707
- //#endregion
4708
- //#region src/session/model-state.ts
4805
+ // src/session/model-state.ts
4709
4806
  function configOptionsAreAuthoritative(state) {
4710
4807
  return state.model_control === "config_option";
4711
4808
  }
@@ -4752,8 +4849,7 @@ function applyConfigOptionsModelState(state, configOptions) {
4752
4849
  else if (preservesLegacyControl) state.model_control = "legacy_set_model";
4753
4850
  else clearAdvertisedModelState(state);
4754
4851
  }
4755
- //#endregion
4756
- //#region src/session/conversation-reducer.ts
4852
+ // src/session/conversation-reducer.ts
4757
4853
  function resolveUserMessageId(value) {
4758
4854
  return typeof value === "string" ? value : value();
4759
4855
  }
@@ -5011,17 +5107,27 @@ function applyToolStatusUpdate(tool, update) {
5011
5107
  function applyToolResultUpdate(agent, tool, update) {
5012
5108
  if (!hasToolResultPatch(update)) return;
5013
5109
  const status = update.status;
5014
- const output = hasOwn(update, "rawOutput") ? deepClone(update.rawOutput) : void 0;
5110
+ const output = hasOwn(update, "rawOutput") ? deepClone(update.rawOutput) ?? void 0 : void 0;
5015
5111
  upsertToolResult(agent, update.toolCallId, {
5016
5112
  tool_name: tool.name,
5017
5113
  is_error: status === void 0 ? void 0 : statusIndicatesError(status),
5018
- content: output === void 0 ? void 0 : toToolResultContent(output),
5114
+ content: output === void 0 ? toolContentText(agent, update) : toToolResultContent(output),
5019
5115
  output
5020
5116
  });
5021
5117
  }
5118
+ function toolContentText(agent, update) {
5119
+ const content = update.content;
5120
+ if (!Array.isArray(content) || agent.tool_results[update.toolCallId]?.output != null) return;
5121
+ return { Text: content.flatMap((item) => {
5122
+ const block = item;
5123
+ const text = block?.type === "content" && block.content?.type === "text" && block.content.text;
5124
+ return typeof text === "string" ? [text] : [];
5125
+ }).join("\n") };
5126
+ }
5022
5127
  function hasToolResultPatch(update) {
5023
5128
  return [
5024
5129
  "rawOutput",
5130
+ "content",
5025
5131
  "status",
5026
5132
  "title",
5027
5133
  "kind"
@@ -5245,8 +5351,7 @@ function applySessionInfoUpdate(conversation, update) {
5245
5351
  if (hasOwn(update, "title")) conversation.title = update.title ?? null;
5246
5352
  if (hasOwn(update, "updatedAt")) conversation.updated_at = update.updatedAt ?? conversation.updated_at;
5247
5353
  }
5248
- //#endregion
5249
- //#region src/session/conversation-retention.ts
5354
+ // src/session/conversation-retention.ts
5250
5355
  const MAX_RUNTIME_MESSAGES = 200;
5251
5356
  const MAX_RUNTIME_AGENT_TEXT_CHARS = 8e3;
5252
5357
  const MAX_RUNTIME_THINKING_CHARS = 4e3;
@@ -5291,8 +5396,7 @@ function trimRuntimeToolResult(result) {
5291
5396
  if ("Text" in result.content) result.content.Text = trimRuntimeText(result.content.Text, MAX_RUNTIME_TOOL_IO_CHARS);
5292
5397
  if (typeof result.output === "string") result.output = trimRuntimeText(result.output, MAX_RUNTIME_TOOL_IO_CHARS);
5293
5398
  }
5294
- //#endregion
5295
- //#region src/session/conversation-model.ts
5399
+ // src/session/conversation-model.ts
5296
5400
  function isoNow() {
5297
5401
  return (/* @__PURE__ */ new Date()).toISOString();
5298
5402
  }
@@ -5324,8 +5428,7 @@ function recordClientOperation(conversation, state, _operation, timestamp = isoN
5324
5428
  trimConversationForRuntime(conversation);
5325
5429
  return acpx;
5326
5430
  }
5327
- //#endregion
5328
- //#region src/runtime/engine/lifecycle.ts
5431
+ // src/runtime/engine/lifecycle.ts
5329
5432
  function createInitialSessionRecord(params) {
5330
5433
  const now = (/* @__PURE__ */ new Date()).toISOString();
5331
5434
  return {
@@ -5390,8 +5493,7 @@ function applyConversation(record, conversation) {
5390
5493
  record.cumulative_cost = conversation.cumulative_cost;
5391
5494
  record.request_token_usage = conversation.request_token_usage;
5392
5495
  }
5393
- //#endregion
5394
- //#region src/runtime/engine/session-options.ts
5496
+ // src/runtime/engine/session-options.ts
5395
5497
  function mergeSessionOptions(preferred, fallback) {
5396
5498
  const merged = { ...fallback };
5397
5499
  if (preferred) {
@@ -5493,8 +5595,7 @@ function storedMaxTurns(value) {
5493
5595
  function nonEmptyString(value) {
5494
5596
  return typeof value === "string" && value.trim().length > 0 ? value : void 0;
5495
5597
  }
5496
- //#endregion
5497
- //#region src/session/mode-preference.ts
5598
+ // src/session/mode-preference.ts
5498
5599
  function ensureAcpxState(state) {
5499
5600
  return state ?? {};
5500
5601
  }
@@ -5539,8 +5640,7 @@ function syncAdvertisedModelState(record, models) {
5539
5640
  applyAdvertisedModelState(acpx, models);
5540
5641
  record.acpx = acpx;
5541
5642
  }
5542
- //#endregion
5543
- //#region src/session/model-application.ts
5643
+ // src/session/model-application.ts
5544
5644
  function currentModelIdFromSetModelResponse(response, fallbackModelId) {
5545
5645
  return modelStateFromConfigOptions(response?.configOptions)?.currentModelId ?? fallbackModelId;
5546
5646
  }
@@ -5571,8 +5671,7 @@ async function applyRequestedModelIfAdvertised(params) {
5571
5671
  response: await withTimeout(params.client.setSessionModel(params.sessionId, requestedModel, params.models, params.authority), params.timeoutMs)
5572
5672
  };
5573
5673
  }
5574
- //#endregion
5575
- //#region src/session/config-options.ts
5674
+ // src/session/config-options.ts
5576
5675
  function applyConfigOptionsToState(state, configOptions) {
5577
5676
  const acpxState = cloneSessionAcpxState(state) ?? {};
5578
5677
  applyConfigOptionsModelState(acpxState, configOptions);
@@ -5636,8 +5735,45 @@ function applyConfigOptionSelection(state, configId, value, response, modelConfi
5636
5735
  value
5637
5736
  });
5638
5737
  }
5639
- //#endregion
5640
- //#region src/session/execution/direct-lifetime.ts
5738
+ // src/session/configuration.ts
5739
+ async function applySessionConfigOptions(params) {
5740
+ let state = params.getState();
5741
+ const selections = [];
5742
+ for (const selection of params.configOptions ?? []) {
5743
+ assertControlAuthority(params.authority);
5744
+ const models = advertisedModelState(params.getState());
5745
+ const { modelConfigId, resolvedValue } = resolveRequestedConfigOption({
5746
+ ...selection,
5747
+ models,
5748
+ agentCommand: params.agentCommand
5749
+ });
5750
+ const response = await withTimeout(params.client.setSessionConfigOption(params.sessionId, selection.configId, selection.value, models, params.authority), params.timeoutMs);
5751
+ assertControlAuthority(params.authority);
5752
+ state = applyConfigOptionSelection(params.getState(), selection.configId, selection.value, response, modelConfigId, resolvedValue);
5753
+ params.setState(state);
5754
+ const acceptedValue = Array.isArray(response?.configOptions) ? response.configOptions.find((option) => option.id === selection.configId)?.currentValue : void 0;
5755
+ selections.push({
5756
+ ...selection,
5757
+ acceptedValue: typeof acceptedValue === "string" ? acceptedValue : resolvedValue,
5758
+ reported: typeof acceptedValue === "string"
5759
+ });
5760
+ }
5761
+ return {
5762
+ state,
5763
+ selections
5764
+ };
5765
+ }
5766
+ function describeSessionConfiguration(params) {
5767
+ return {
5768
+ ...params.requestedModel === void 0 ? {} : { model: {
5769
+ requested: params.requestedModel,
5770
+ applied: params.modelApplied,
5771
+ ...params.state?.current_model_id === void 0 ? {} : { accepted: params.state.current_model_id }
5772
+ } },
5773
+ configOptions: params.selections
5774
+ };
5775
+ }
5776
+ // src/session/execution/direct-lifetime.ts
5641
5777
  function ownDirectClient(client, signal) {
5642
5778
  let closing;
5643
5779
  const cancel = async () => {
@@ -5660,8 +5796,7 @@ function ownDirectClient(client, signal) {
5660
5796
  function directExecutionError(error, signal) {
5661
5797
  return signal?.aborted && error instanceof AgentDisconnectedError ? signal.reason : error;
5662
5798
  }
5663
- //#endregion
5664
- //#region src/runtime/engine/reconnect.ts
5799
+ // src/runtime/engine/reconnect.ts
5665
5800
  const SESSION_LOAD_UNSUPPORTED_CODES = /* @__PURE__ */ new Set([-32601, -32602]);
5666
5801
  function createReplayState(authority) {
5667
5802
  let failure;
@@ -5685,7 +5820,7 @@ function shouldFallbackToNewSession(error, record) {
5685
5820
  if (isHardReconnectFailure(error)) return false;
5686
5821
  const acp = extractAcpError(error);
5687
5822
  if (isAcpResourceNotFoundError(error) || isUnsupportedSessionLoadAcpError(acp)) return true;
5688
- return !sessionHasAgentMessages(record) && isFallbackSafeEmptySessionError(error, acp);
5823
+ return !sessionHasAgentMessages(record) && acp?.code === -32603;
5689
5824
  }
5690
5825
  function isHardReconnectFailure(error) {
5691
5826
  return error instanceof TimeoutError || error instanceof InterruptedError;
@@ -5693,11 +5828,8 @@ function isHardReconnectFailure(error) {
5693
5828
  function isUnsupportedSessionLoadAcpError(acp) {
5694
5829
  return !!acp && SESSION_LOAD_UNSUPPORTED_CODES.has(acp.code);
5695
5830
  }
5696
- function isFallbackSafeEmptySessionError(error, acp) {
5697
- return isAcpQueryClosedBeforeResponseError(error) || acp?.code === -32603;
5698
- }
5699
- function requiresSameSession(resumePolicy) {
5700
- return resumePolicy === "same-session-only";
5831
+ function requiresSameSession(options) {
5832
+ return options.resumePolicy === "same-session-only" || Boolean(options.record.importedFrom) || options.strictResume === true;
5701
5833
  }
5702
5834
  function makeSessionResumeRequiredError(params) {
5703
5835
  return new SessionResumeRequiredError(`Persistent ACP session ${params.record.acpSessionId} could not be resumed: ${params.reason}`, { cause: params.cause instanceof Error ? params.cause : void 0 });
@@ -5800,7 +5932,7 @@ async function connectAndLoadSession(options) {
5800
5932
  const record = options.record;
5801
5933
  const client = options.client;
5802
5934
  assertControlAuthority(options.authority);
5803
- const sameSessionOnly = requiresSameSession(options.resumePolicy) || Boolean(record.importedFrom);
5935
+ const sameSessionOnly = requiresSameSession(options);
5804
5936
  const originalSessionId = record.acpSessionId;
5805
5937
  const originalAgentSessionId = record.agentSessionId;
5806
5938
  const originalAcpx = cloneSessionAcpxState(record.acpx);
@@ -5825,7 +5957,8 @@ async function connectAndLoadSession(options) {
5825
5957
  sameSessionOnly,
5826
5958
  timeoutMs: options.timeoutMs,
5827
5959
  authority: options.authority,
5828
- promptRecorded: options.promptRecorded
5960
+ promptRecorded: options.promptRecorded,
5961
+ strictResume: options.strictResume
5829
5962
  });
5830
5963
  const { resumed, loadError, sessionId, createdFreshSession, pendingAgentSessionId, sessionModels } = loadState;
5831
5964
  applyReconnectedModelState(record, sessionModels, loadState.configOptionsPresent, loadState.legacyModelMetadataPresent, createdFreshSession);
@@ -5852,6 +5985,7 @@ async function connectAndLoadSession(options) {
5852
5985
  applyReconnectedModelState(record, resolveModelsAfterReplay(preferenceReplay, sessionModels), resolveConfigOptionsPresenceAfterReplay(preferenceReplay, loadState.configOptionsPresent), loadState.legacyModelMetadataPresent, createdFreshSession);
5853
5986
  options.onSessionIdResolved?.(sessionId);
5854
5987
  return {
5988
+ reusingLoadedSession,
5855
5989
  sessionId,
5856
5990
  agentSessionId: record.agentSessionId,
5857
5991
  resumed,
@@ -6038,6 +6172,7 @@ async function recoverRuntimeSessionLoadFailure(params, error) {
6038
6172
  };
6039
6173
  }
6040
6174
  function canRecoverLoadWithFreshSession(params, error) {
6175
+ if (params.strictResume) return false;
6041
6176
  if (!params.sameSessionOnly) return shouldFallbackToNewSession(error, params.record);
6042
6177
  return isUnpromptedNewSession(params.record, params.promptRecorded) && extractAcpError(error)?.code === -32603;
6043
6178
  }
@@ -6061,8 +6196,7 @@ async function createFreshRuntimeSession(client, record, timeoutMs, authority) {
6061
6196
  createdFreshSession: true
6062
6197
  };
6063
6198
  }
6064
- //#endregion
6065
- //#region src/runtime/engine/connected-session.ts
6199
+ // src/runtime/engine/connected-session.ts
6066
6200
  function createActiveSessionController(params) {
6067
6201
  const getActiveSessionId = () => params.getActiveSessionId();
6068
6202
  return {
@@ -6118,6 +6252,7 @@ async function withConnectedSession(options) {
6118
6252
  client,
6119
6253
  record,
6120
6254
  resumePolicy: options.resumePolicy,
6255
+ strictResume: options.strictResume,
6121
6256
  replacingMode: options.replacingMode,
6122
6257
  replacingConfigOption: options.replacingConfigOption,
6123
6258
  authority: options.authority,
@@ -6174,8 +6309,7 @@ async function withConnectedSession(options) {
6174
6309
  await options.saveRecord(record).catch(() => {});
6175
6310
  }
6176
6311
  }
6177
- //#endregion
6178
- //#region src/session/execution/prompt-runner.ts
6312
+ // src/session/execution/prompt-runner.ts
6179
6313
  function buildDirectConnectedSessionOptions(options, run) {
6180
6314
  return {
6181
6315
  sessionRecordId: options.sessionRecordId,
@@ -6191,9 +6325,7 @@ function buildDirectConnectedSessionOptions(options, run) {
6191
6325
  terminal: options.terminal,
6192
6326
  timeoutMs: options.timeoutMs,
6193
6327
  verbose: options.verbose,
6194
- onClientAvailable: (controller) => {
6195
- options.onClientAvailable?.(controller);
6196
- },
6328
+ onClientAvailable: options.onClientAvailable,
6197
6329
  onClientClosed: options.onClientClosed,
6198
6330
  run
6199
6331
  };
@@ -6281,8 +6413,7 @@ async function runSessionSetConfigOptionDirect(options) {
6281
6413
  loadError: result.loadError
6282
6414
  };
6283
6415
  }
6284
- //#endregion
6285
- //#region src/session/execution/windows-process-command.ts
6416
+ // src/session/execution/windows-process-command.ts
6286
6417
  function skipSeparators(value) {
6287
6418
  return value.replace(/^[ \t]+/u, "");
6288
6419
  }
@@ -6364,8 +6495,7 @@ function splitWindowsProcessCommandLine(commandLine) {
6364
6495
  }
6365
6496
  return argv;
6366
6497
  }
6367
- //#endregion
6368
- //#region src/session/execution/session-control.ts
6498
+ // src/session/execution/session-control.ts
6369
6499
  async function cancelSessionPrompt(options) {
6370
6500
  const cancelled = await tryCancelOnRunningOwner(options);
6371
6501
  return {
@@ -6399,16 +6529,8 @@ async function setSessionMode(options) {
6399
6529
  const onOwner = await setSessionModeOnOwner(options);
6400
6530
  if (onOwner) return onOwner;
6401
6531
  return await runSessionSetModeDirect({
6402
- sessionRecordId: options.sessionId,
6403
- modeId: options.modeId,
6404
- mcpServers: options.mcpServers,
6405
- nonInteractivePermissions: options.nonInteractivePermissions,
6406
- authCredentials: options.authCredentials,
6407
- authPolicy: options.authPolicy,
6408
- fs: options.fs,
6409
- terminal: options.terminal,
6410
- timeoutMs: options.timeoutMs,
6411
- verbose: options.verbose
6532
+ ...options,
6533
+ sessionRecordId: options.sessionId
6412
6534
  });
6413
6535
  }
6414
6536
  /** Owner-only counterpart of {@link setSessionMode} for the model control. */
@@ -6434,16 +6556,8 @@ async function setSessionModel(options) {
6434
6556
  const onOwner = await setSessionModelOnOwner(options);
6435
6557
  if (onOwner) return onOwner;
6436
6558
  return await runSessionSetModelDirect({
6437
- sessionRecordId: options.sessionId,
6438
- modelId: options.modelId,
6439
- mcpServers: options.mcpServers,
6440
- nonInteractivePermissions: options.nonInteractivePermissions,
6441
- authCredentials: options.authCredentials,
6442
- authPolicy: options.authPolicy,
6443
- fs: options.fs,
6444
- terminal: options.terminal,
6445
- timeoutMs: options.timeoutMs,
6446
- verbose: options.verbose
6559
+ ...options,
6560
+ sessionRecordId: options.sessionId
6447
6561
  });
6448
6562
  }
6449
6563
  /** Owner-only counterpart of {@link setSessionMode} for the config option control. */
@@ -6472,17 +6586,8 @@ async function setSessionConfigOption(options) {
6472
6586
  const onOwner = await setSessionConfigOptionOnOwner(options);
6473
6587
  if (onOwner) return onOwner;
6474
6588
  return await runSessionSetConfigOptionDirect({
6475
- sessionRecordId: options.sessionId,
6476
- configId: options.configId,
6477
- value: options.value,
6478
- mcpServers: options.mcpServers,
6479
- nonInteractivePermissions: options.nonInteractivePermissions,
6480
- authCredentials: options.authCredentials,
6481
- authPolicy: options.authPolicy,
6482
- fs: options.fs,
6483
- terminal: options.terminal,
6484
- timeoutMs: options.timeoutMs,
6485
- verbose: options.verbose
6589
+ ...options,
6590
+ sessionRecordId: options.sessionId
6486
6591
  });
6487
6592
  }
6488
6593
  function firstAgentCommandToken(command, argv) {
@@ -6575,8 +6680,7 @@ async function closeSession(sessionId) {
6575
6680
  await ownership[Symbol.asyncDispose]();
6576
6681
  }
6577
6682
  }
6578
- //#endregion
6579
- //#region src/session/execution/session-management.ts
6683
+ // src/session/execution/session-management.ts
6580
6684
  async function createSessionRecordWithClient(client, options, resumedRecordId) {
6581
6685
  const cwd = absolutePath(options.cwd);
6582
6686
  await withTimeout(client.start({ signal: options.signal }), options.timeoutMs);
@@ -6605,10 +6709,33 @@ async function createSessionRecordWithClient(client, options, resumedRecordId) {
6605
6709
  persistSessionOptions(record, options.sessionOptions);
6606
6710
  applyConfigOptionsToRecord(record, createdState.sessionResult);
6607
6711
  applyInitialModelSelection(record, createdState.sessionResult.models, createdState.modelApplication);
6712
+ await configureCreatedSession(client, options, record, createdState.modelApplication.applied);
6713
+ assertControlAuthority({ signal: options.signal });
6608
6714
  await writeSessionRecord(record);
6609
6715
  assertControlAuthority({ signal: options.signal });
6610
6716
  return record;
6611
6717
  }
6718
+ async function configureCreatedSession(client, options, record, modelApplied) {
6719
+ const configured = await applySessionConfigOptions({
6720
+ client,
6721
+ sessionId: record.acpSessionId,
6722
+ agentCommand: options.agentCommand,
6723
+ getState: () => record.acpx,
6724
+ setState: (state) => {
6725
+ record.acpx = state;
6726
+ },
6727
+ configOptions: options.configOptions,
6728
+ timeoutMs: options.timeoutMs,
6729
+ authority: { signal: options.signal }
6730
+ });
6731
+ record.acpx = configured.state;
6732
+ options.onSessionConfigured?.(describeSessionConfiguration({
6733
+ requestedModel: options.sessionOptions?.model,
6734
+ modelApplied,
6735
+ state: record.acpx,
6736
+ selections: configured.selections
6737
+ }));
6738
+ }
6612
6739
  async function createFreshSessionState(client, options, cwd) {
6613
6740
  const createdSession = await withTimeout(client.createSession(cwd, { signal: options.signal }), options.timeoutMs);
6614
6741
  assertControlAuthority({ signal: options.signal });
@@ -6783,7 +6910,7 @@ async function ensureSessionWithOwnership(options, cwd) {
6783
6910
  });
6784
6911
  if (existing) {
6785
6912
  const requestedModel = options.sessionOptions?.model;
6786
- if (requestedModel) return {
6913
+ if (requestedModel && options.applyModelOnReuse !== false) return {
6787
6914
  record: (await setSessionModel({
6788
6915
  sessionId: existing.acpxRecordId,
6789
6916
  modelId: requestedModel,
@@ -6827,8 +6954,7 @@ async function ensureSessionWithOwnership(options, cwd) {
6827
6954
  created: true
6828
6955
  };
6829
6956
  }
6830
- //#endregion
6831
- //#region src/perf-metrics-capture.ts
6957
+ // src/perf-metrics-capture.ts
6832
6958
  const PERF_METRICS_FILE_ENV = "ACPX_PERF_METRICS_FILE";
6833
6959
  let installed = false;
6834
6960
  let flushed = false;
@@ -6912,8 +7038,7 @@ function installPerfMetricsCapture(options = {}) {
6912
7038
  process.once(signal, handler);
6913
7039
  }
6914
7040
  }
6915
- //#endregion
6916
- //#region src/session/queue/control-admission.ts
7041
+ // src/session/queue/control-admission.ts
6917
7042
  var QueueControlDeadline = class {
6918
7043
  controller = new AbortController();
6919
7044
  admissionSignal;
@@ -7082,36 +7207,22 @@ var QueueOwnerControlAdmission = class {
7082
7207
  return operation;
7083
7208
  }
7084
7209
  };
7085
- //#endregion
7086
- //#region src/session/queue/owner-turn-controller.ts
7210
+ // src/session/queue/owner-turn-controller.ts
7087
7211
  var QueueOwnerTurnController = class {
7088
- state = "idle";
7089
7212
  pendingCancel = false;
7090
7213
  activeController;
7091
7214
  waitingTurn;
7092
- get lifecycleState() {
7093
- return this.state;
7094
- }
7095
- get hasPendingCancel() {
7096
- return this.pendingCancel;
7097
- }
7098
7215
  beginTurn() {
7099
- this.state = "starting";
7100
7216
  this.pendingCancel = false;
7101
7217
  this.waitingTurn = new AbortController();
7102
7218
  return this.waitingTurn.signal;
7103
7219
  }
7104
- markPromptActive() {
7105
- if (this.state === "starting" || this.state === "active") this.state = "active";
7106
- }
7107
7220
  endTurn() {
7108
- this.state = "idle";
7109
7221
  this.pendingCancel = false;
7110
7222
  this.waitingTurn = void 0;
7111
7223
  }
7112
7224
  beginClosing() {
7113
- this.state = "closing";
7114
- this.pendingCancel = false;
7225
+ this.endTurn();
7115
7226
  this.activeController = void 0;
7116
7227
  }
7117
7228
  setActiveController(controller) {
@@ -7123,9 +7234,9 @@ var QueueOwnerTurnController = class {
7123
7234
  async requestCancel() {
7124
7235
  const activeController = this.activeController;
7125
7236
  if (activeController?.hasActivePrompt()) return await this.cancelActivePrompt(activeController);
7126
- if (this.state === "starting" || this.state === "active") {
7237
+ if (this.waitingTurn) {
7127
7238
  this.pendingCancel = true;
7128
- this.waitingTurn?.abort();
7239
+ this.waitingTurn.abort();
7129
7240
  return true;
7130
7241
  }
7131
7242
  return false;
@@ -7144,8 +7255,7 @@ var QueueOwnerTurnController = class {
7144
7255
  return cancelled;
7145
7256
  }
7146
7257
  };
7147
- //#endregion
7148
- //#region src/session/execution/owned-controls.ts
7258
+ // src/session/execution/owned-controls.ts
7149
7259
  async function acceptControl(options, invoke, apply, deadline = new QueueControlDeadline()) {
7150
7260
  deadline.assertActive();
7151
7261
  const raw = invoke(deadline.authority).then(async (response) => {
@@ -7276,8 +7386,7 @@ async function runIdleOwnerControl(options, invoke) {
7276
7386
  await ownership[Symbol.asyncDispose]();
7277
7387
  }
7278
7388
  }
7279
- //#endregion
7280
- //#region src/session/execution/queue-owner-process.ts
7389
+ // src/session/execution/queue-owner-process.ts
7281
7390
  function isNonEmptyStringArray(value) {
7282
7391
  return Array.isArray(value) && value.length > 0 && value.every((entry) => typeof entry === "string" && entry.length > 0);
7283
7392
  }
@@ -7449,8 +7558,7 @@ function spawnQueueOwnerProcess(options, queueOwnerArgs) {
7449
7558
  stopStartupCapture
7450
7559
  };
7451
7560
  }
7452
- //#endregion
7453
- //#region src/runtime/engine/prompt-turn.ts
7561
+ // src/runtime/engine/prompt-turn.ts
7454
7562
  const SESSION_REPLY_IDLE_MS = 1e3;
7455
7563
  const SESSION_REPLY_DRAIN_TIMEOUT_MS = 5e3;
7456
7564
  function responseMetaField(meta) {
@@ -7506,8 +7614,7 @@ async function runPromptTurn(params) {
7506
7614
  lifetime.abort();
7507
7615
  }
7508
7616
  }
7509
- //#endregion
7510
- //#region src/session/live-checkpoint.ts
7617
+ // src/session/live-checkpoint.ts
7511
7618
  const DEFAULT_LIVE_CHECKPOINT_INTERVAL_MS = 500;
7512
7619
  var LiveSessionCheckpoint = class {
7513
7620
  save;
@@ -7567,8 +7674,7 @@ var LiveSessionCheckpoint = class {
7567
7674
  }
7568
7675
  }
7569
7676
  };
7570
- //#endregion
7571
- //#region src/session/execution/discard-output.ts
7677
+ // src/session/execution/discard-output.ts
7572
7678
  const DISCARD_OUTPUT_FORMATTER = {
7573
7679
  setContext() {},
7574
7680
  onAcpMessage() {},
@@ -7576,8 +7682,7 @@ const DISCARD_OUTPUT_FORMATTER = {
7576
7682
  onPermissionEscalation() {},
7577
7683
  flush() {}
7578
7684
  };
7579
- //#endregion
7580
- //#region src/session/execution/runtime.ts
7685
+ // src/session/execution/runtime.ts
7581
7686
  const INTERRUPT_CANCEL_WAIT_MS = 2500;
7582
7687
  var QueueTaskOutputFormatter = class {
7583
7688
  requestId;
@@ -7680,7 +7785,7 @@ function requestedModelId(value) {
7680
7785
  }
7681
7786
  async function applyPromptModelIfAdvertised(params) {
7682
7787
  const requestedModel = requestedModelId(params.requestedModel);
7683
- if (!requestedModel) return;
7788
+ if (!requestedModel) return false;
7684
7789
  const result = await applyRequestedModelIfAdvertised({
7685
7790
  client: params.client,
7686
7791
  sessionId: params.sessionId,
@@ -7692,6 +7797,37 @@ async function applyPromptModelIfAdvertised(params) {
7692
7797
  onWarning: params.suppressWarnings ? void 0 : (message) => process.stderr.write(`[acpx] warning: ${message}\n`)
7693
7798
  });
7694
7799
  if (result.applied) params.record.acpx = applyModelSelection(params.record.acpx, requestedModel, result.response, result.resolvedModelId);
7800
+ return result.applied;
7801
+ }
7802
+ async function applyPromptConfiguration(client, activeSessionId, record, options) {
7803
+ const modelApplied = await applyPromptModelIfAdvertised({
7804
+ client,
7805
+ sessionId: activeSessionId,
7806
+ requestedModel: options.sessionOptions?.model,
7807
+ record,
7808
+ timeoutMs: options.timeoutMs,
7809
+ suppressWarnings: options.suppressSdkConsoleErrors,
7810
+ signal: options.ownedSignal
7811
+ });
7812
+ const configured = await applySessionConfigOptions({
7813
+ client,
7814
+ sessionId: activeSessionId,
7815
+ agentCommand: record.agentCommand,
7816
+ getState: () => record.acpx,
7817
+ setState: (state) => {
7818
+ record.acpx = state;
7819
+ },
7820
+ configOptions: options.configOptions,
7821
+ timeoutMs: options.timeoutMs,
7822
+ authority: { signal: options.ownedSignal }
7823
+ });
7824
+ record.acpx = configured.state;
7825
+ options.onSessionConfigured?.(describeSessionConfiguration({
7826
+ requestedModel: options.sessionOptions?.model,
7827
+ modelApplied,
7828
+ state: record.acpx,
7829
+ selections: configured.selections
7830
+ }));
7695
7831
  }
7696
7832
  function jsonRpcIdKey(message) {
7697
7833
  if (!("id" in message)) return;
@@ -8088,14 +8224,12 @@ async function runOwnedSessionPrompt(options) {
8088
8224
  onSessionUpdate: (notification) => {
8089
8225
  if (promptTurnActive) promptTurnHadSideEffects = true;
8090
8226
  record.acpx = recordSessionUpdate(conversation, record.acpx, notification);
8091
- trimConversationForRuntime(conversation);
8092
8227
  liveCheckpoint.request();
8093
8228
  options.onSessionUpdate?.(notification);
8094
8229
  },
8095
8230
  onClientOperation: (operation) => {
8096
8231
  if (promptTurnActive) promptTurnHadSideEffects = true;
8097
8232
  record.acpx = recordClientOperation(conversation, record.acpx, operation);
8098
- trimConversationForRuntime(conversation);
8099
8233
  liveCheckpoint.request();
8100
8234
  options.onClientOperation?.(operation);
8101
8235
  },
@@ -8255,18 +8389,10 @@ async function runOwnedSessionPrompt(options) {
8255
8389
  };
8256
8390
  const runPrompt = async () => {
8257
8391
  options.ownedSignal?.throwIfAborted();
8258
- const { sessionId: activeSessionId, resumed, loadError } = await connectForPrompt();
8392
+ const { sessionId: activeSessionId, resumed, loadError, reusingLoadedSession } = await connectForPrompt();
8259
8393
  options.ownedSignal?.throwIfAborted();
8260
8394
  try {
8261
- await applyPromptModelIfAdvertised({
8262
- client,
8263
- sessionId: activeSessionId,
8264
- requestedModel: options.sessionOptions?.model,
8265
- record,
8266
- timeoutMs: options.timeoutMs,
8267
- suppressWarnings: options.suppressSdkConsoleErrors,
8268
- signal: options.ownedSignal
8269
- });
8395
+ if (!options.skipConfigurationForLoadedSession || !reusingLoadedSession) await applyPromptConfiguration(client, activeSessionId, record, options);
8270
8396
  } catch (error) {
8271
8397
  if (error instanceof TimeoutError) closeClientOnExit = true;
8272
8398
  throw error;
@@ -8452,17 +8578,25 @@ async function runOnce(options, control) {
8452
8578
  onWarning: options.suppressSdkConsoleErrors ? void 0 : (message) => process.stderr.write(`[acpx] warning: ${message}\n`)
8453
8579
  });
8454
8580
  if (modelApplication.applied) controlState = applyModelSelection(controlState, modelApplication.modelId, modelApplication.response, modelApplication.resolvedModelId);
8455
- for (const configOption of options.configOptions ?? []) {
8456
- assertControlAuthority(authority);
8457
- const models = advertisedModelState(controlState);
8458
- const { modelConfigId, resolvedValue } = resolveRequestedConfigOption({
8459
- ...configOption,
8460
- models,
8461
- agentCommand: options.agentCommand
8462
- });
8463
- const response = await withTimeout(client.setSessionConfigOption(sessionId, configOption.configId, configOption.value, models, authority), options.timeoutMs);
8464
- controlState = applyConfigOptionSelection(controlState, configOption.configId, configOption.value, response, modelConfigId, resolvedValue);
8465
- }
8581
+ const configured = await applySessionConfigOptions({
8582
+ client,
8583
+ sessionId,
8584
+ agentCommand: options.agentCommand,
8585
+ getState: () => controlState,
8586
+ setState: (state) => {
8587
+ controlState = state ?? {};
8588
+ },
8589
+ configOptions: options.configOptions,
8590
+ timeoutMs: options.timeoutMs,
8591
+ authority
8592
+ });
8593
+ controlState = configured.state ?? {};
8594
+ options.onSessionConfigured?.(describeSessionConfiguration({
8595
+ requestedModel: options.sessionOptions?.model,
8596
+ modelApplied: modelApplication.applied,
8597
+ state: controlState,
8598
+ selections: configured.selections
8599
+ }));
8466
8600
  assertControlAuthority(authority);
8467
8601
  output.setContext({ sessionId });
8468
8602
  const response = await runExecPromptWithRetries(sessionId);
@@ -8520,15 +8654,18 @@ async function sendSessionDirect(options, control) {
8520
8654
  timeoutMs: options.timeoutMs,
8521
8655
  suppressSdkConsoleErrors: options.suppressSdkConsoleErrors,
8522
8656
  verbose: options.verbose,
8523
- client: options.client
8657
+ client: options.client,
8658
+ skipConfigurationForLoadedSession: options.skipConfigurationForLoadedSession,
8659
+ sessionOptions: options.sessionOptions,
8660
+ configOptions: options.configOptions,
8661
+ onSessionConfigured: options.onSessionConfigured
8524
8662
  });
8525
8663
  } finally {
8526
8664
  await closeProvidedClient?.();
8527
8665
  }
8528
8666
  }
8529
- //#endregion
8530
- //#region src/session/execution/queue-owner-runtime.ts
8531
- const QUEUE_OWNER_STARTUP_MAX_ATTEMPTS = 120;
8667
+ // src/session/execution/queue-owner-runtime.ts
8668
+ const QUEUE_OWNER_STARTUP_TIMEOUT_MS = 6e4;
8532
8669
  const QUEUE_OWNER_HEARTBEAT_INTERVAL_MS = 5e3;
8533
8670
  const QUEUE_OWNER_ACTIVE_TURN_CANCEL_GRACE_MS = 750;
8534
8671
  async function submitToRunningOwner(options, waitForCompletion, extras) {
@@ -8875,7 +9012,6 @@ async function runQueueOwnerRuntime(options, lease, bindStopRequest) {
8875
9012
  onPromptFinalizing: () => controls.seal(ticket),
8876
9013
  onPromptActive: async () => {
8877
9014
  if (activeControls) controls.publish(ticket, activeControls);
8878
- turnController.markPromptActive();
8879
9015
  await applyPendingCancel();
8880
9016
  },
8881
9017
  handleProcessInterrupts: false,
@@ -8910,7 +9046,8 @@ async function sendSession(options) {
8910
9046
  owner.stopStartupCapture();
8911
9047
  };
8912
9048
  try {
8913
- for (let attempt = 0; attempt < QUEUE_OWNER_STARTUP_MAX_ATTEMPTS; attempt += 1) {
9049
+ const startupDeadline = Date.now() + QUEUE_OWNER_STARTUP_TIMEOUT_MS;
9050
+ while (Date.now() < startupDeadline) {
8914
9051
  options.signal?.throwIfAborted();
8915
9052
  const queued = await submitToRunningOwner(options, waitForCompletion, { onQueueAccepted });
8916
9053
  if (queued) return queued;
@@ -8936,7 +9073,6 @@ async function sendSession(options) {
8936
9073
  }
8937
9074
  }
8938
9075
  const queueOwnerRuntimeTestInternals = { queueOwnerExitIsFatal };
8939
- //#endregion
8940
- export { isRequestedModelUnsupportedError as $, applyInitialModelSelection as A, reconcileAgentSessionId as B, setSessionModeOnOwner as C, connectAndLoadSession as D, withConnectedSession as E, persistSessionOptions as F, recordSessionUpdate as G, createSessionConversation as H, sessionOptionsFromRecord as I, advertisedModelState as J, trimConversationForRuntime as K, applyConversation as L, applyRequestedModelIfAdvertised as M, setDesiredModeId as N, applyConfigOptionSelection as O, normalizeSessionOptionShape as P, RequestedModelUnsupportedError as Q, applyLifecycleSnapshotToRecord as R, setSessionMode as S, setSessionModelOnOwner as T, recordClientOperation as U, cloneSessionConversation as V, recordPromptSubmission as W, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as X, AcpClient as Y, REQUESTED_MODEL_UNSUPPORTED_REASONS as Z, cancelSessionPrompt as _, runQueuedTask as a, normalizeQueueOwnerTtlMs as at, setSessionConfigOption as b, LiveSessionCheckpoint as c, listSessionEvents as ct, flushPerfMetricsCapture as d, TimeoutError as dt, resolveRequestedConfigOption as et, installPerfMetricsCapture as f, assertControlAuthority as ft, listAgentSessions as g, ensureSession as h, runOnce as i, DEFAULT_QUEUE_OWNER_TTL_MS as it, applyModelSelection as j, applyConfigOptionsToRecord as k, runPromptTurn as l, isLegacyZedCodexAcpInvocation as lt, createSessionWithClient as m, withTimeout as mt, runSessionQueueOwner as n, getAcpxVersion as nt, sendSessionDirect as o, acquireSessionImport as ot, createSession as p, withInterrupt as pt, cloneSessionAcpxState as q, sendSession as r, permissionModeSatisfies as rt, DISCARD_OUTPUT_FORMATTER as s, acquireSessionScope as st, queueOwnerRuntimeTestInternals as t, resolveRequestedModelId as tt, buildQueueOwnerArgOverride as u, InterruptedError as ut, closeSession as v, setSessionModel as w, setSessionConfigOptionOnOwner as x, sessionControlTestInternals as y, createInitialSessionRecord as z };
9076
+ export { resolveRequestedConfigOption as $, applyInitialModelSelection as A, reconcileAgentSessionId as B, setSessionModeOnOwner as C, connectAndLoadSession as D, withConnectedSession as E, persistSessionOptions as F, recordSessionUpdate as G, createSessionConversation as H, sessionOptionsFromRecord as I, AcpClient as J, cloneSessionAcpxState as K, applyConversation as L, applyRequestedModelIfAdvertised as M, setDesiredModeId as N, applyConfigOptionSelection as O, normalizeSessionOptionShape as P, isRequestedModelUnsupportedError as Q, applyLifecycleSnapshotToRecord as R, setSessionMode as S, setSessionModelOnOwner as T, recordClientOperation as U, cloneSessionConversation as V, recordPromptSubmission as W, REQUESTED_MODEL_UNSUPPORTED_REASONS as X, REQUESTED_MODEL_UNSUPPORTED_ERROR_CODE as Y, RequestedModelUnsupportedError as Z, cancelSessionPrompt as _, runQueuedTask as a, normalizeQueueOwnerTtlMs as at, setSessionConfigOption as b, LiveSessionCheckpoint as c, listSessionEvents as ct, flushPerfMetricsCapture as d, TimeoutError as dt, resolveRequestedModelId as et, installPerfMetricsCapture as f, assertControlAuthority as ft, listAgentSessions as g, ensureSession as h, runOnce as i, DEFAULT_QUEUE_OWNER_TTL_MS as it, applyModelSelection as j, applyConfigOptionsToRecord as k, runPromptTurn as l, isLegacyZedCodexAcpInvocation as lt, createSessionWithClient as m, withTimeout as mt, runSessionQueueOwner as n, snapshotEnvNames as nt, sendSessionDirect as o, acquireSessionImport as ot, createSession as p, withInterrupt as pt, advertisedModelState as q, sendSession as r, permissionModeSatisfies as rt, DISCARD_OUTPUT_FORMATTER as s, acquireSessionScope as st, queueOwnerRuntimeTestInternals as t, getAcpxVersion as tt, buildQueueOwnerArgOverride as u, InterruptedError as ut, closeSession as v, setSessionModel as w, setSessionConfigOptionOnOwner as x, sessionControlTestInternals as y, createInitialSessionRecord as z };
8941
9077
 
8942
- //# sourceMappingURL=queue-owner-runtime-ehuh3SQU.js.map
9078
+ //# sourceMappingURL=queue-owner-runtime-DHBQbjXo.js.map