@1agents/acp-service 0.8.1 → 0.8.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 (103) hide show
  1. package/README.md +37 -2
  2. package/dist/bin/a2a.js +3 -2
  3. package/dist/src/a2a/executor.d.ts +2 -0
  4. package/dist/src/a2a/executor.js +63 -10
  5. package/dist/src/a2a/gateway.d.ts +407 -14
  6. package/dist/src/a2a/gateway.js +719 -37
  7. package/dist/src/a2a/index.d.ts +8 -1
  8. package/dist/src/a2a/index.js +4 -0
  9. package/dist/src/a2a/notices.d.ts +24 -0
  10. package/dist/src/a2a/notices.js +56 -0
  11. package/dist/src/a2a/preflight.d.ts +52 -0
  12. package/dist/src/a2a/preflight.js +153 -0
  13. package/dist/src/a2a/result-metadata.d.ts +59 -0
  14. package/dist/src/a2a/result-metadata.js +156 -0
  15. package/dist/src/a2a/server.js +30 -0
  16. package/dist/src/a2a/session-delivery.d.ts +69 -0
  17. package/dist/src/a2a/session-delivery.js +260 -0
  18. package/dist/src/a2a/session-hosts.d.ts +34 -0
  19. package/dist/src/a2a/session-hosts.js +211 -0
  20. package/dist/src/a2a/store.js +3 -1
  21. package/dist/src/a2a/types.d.ts +33 -0
  22. package/dist/src/execution/delivery-progress.d.ts +108 -0
  23. package/dist/src/execution/delivery-progress.js +57 -0
  24. package/dist/src/execution/ledger.d.ts +235 -0
  25. package/dist/src/execution/ledger.js +396 -0
  26. package/dist/src/execution/ppt-delivery.d.ts +231 -0
  27. package/dist/src/execution/ppt-delivery.js +625 -0
  28. package/dist/src/execution/targets.d.ts +349 -0
  29. package/dist/src/execution/targets.js +428 -0
  30. package/package.json +11 -12
  31. package/skills/acp-service/SKILL.md +9 -2
  32. package/skills/acp-service/references/a2a.md +72 -4
  33. package/vendor/dsh/a2a-executor.d.ts +2 -1
  34. package/vendor/dsh/a2a-executor.js +28 -1
  35. package/vendor/dsh/a2a.js +1 -0
  36. package/vendor/dsh/client.js +11 -3
  37. package/vendor/runtime/dist/{agent-registry-CMg8LHKY.js → agent-registry-R7A3MSpr.js} +9 -1
  38. package/vendor/runtime/dist/agent-registry-R7A3MSpr.js.map +1 -0
  39. package/vendor/runtime/dist/agent-registry.d.ts +1 -0
  40. package/vendor/runtime/dist/agent-registry.d.ts.map +1 -1
  41. package/vendor/runtime/dist/agent-registry.js +1 -2
  42. package/vendor/runtime/dist/{cli-Bdzplbpj.js → cli-DeOpE2Xz.js} +4 -4
  43. package/vendor/runtime/dist/{cli-Bdzplbpj.js.map → cli-DeOpE2Xz.js.map} +1 -1
  44. package/vendor/runtime/dist/cli.d.ts +2 -1
  45. package/vendor/runtime/dist/cli.js +10 -10
  46. package/vendor/runtime/dist/cli.js.map +1 -1
  47. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts → client-VQsqcIOJ.d.ts} +2 -2
  48. package/vendor/runtime/dist/{client-BXOiB0ND.d.ts.map → client-VQsqcIOJ.d.ts.map} +1 -1
  49. package/vendor/runtime/dist/docs-site/.nojekyll +0 -0
  50. package/vendor/runtime/dist/docs-site/CLI.html +833 -0
  51. package/vendor/runtime/dist/docs-site/VISION.html +415 -0
  52. package/vendor/runtime/dist/docs-site/agents.html +391 -0
  53. package/vendor/runtime/dist/docs-site/compare.html +359 -0
  54. package/vendor/runtime/dist/docs-site/config.html +450 -0
  55. package/vendor/runtime/dist/docs-site/custom-agents.html +408 -0
  56. package/vendor/runtime/dist/docs-site/exit-codes.html +347 -0
  57. package/vendor/runtime/dist/docs-site/favicon.svg +21 -0
  58. package/vendor/runtime/dist/docs-site/flows.html +498 -0
  59. package/vendor/runtime/dist/docs-site/index.html +367 -0
  60. package/vendor/runtime/dist/docs-site/install.html +386 -0
  61. package/vendor/runtime/dist/docs-site/llms.txt +36 -0
  62. package/vendor/runtime/dist/docs-site/output-formats.html +407 -0
  63. package/vendor/runtime/dist/docs-site/permissions.html +422 -0
  64. package/vendor/runtime/dist/docs-site/prompting.html +460 -0
  65. package/vendor/runtime/dist/docs-site/quickstart.html +382 -0
  66. package/vendor/runtime/dist/docs-site/releasing.html +341 -0
  67. package/vendor/runtime/dist/docs-site/runtime-environment.html +329 -0
  68. package/vendor/runtime/dist/docs-site/runtime-process-lifecycle.html +335 -0
  69. package/vendor/runtime/dist/docs-site/safe-errors.html +323 -0
  70. package/vendor/runtime/dist/docs-site/session-control.html +408 -0
  71. package/vendor/runtime/dist/docs-site/session-watch.html +354 -0
  72. package/vendor/runtime/dist/docs-site/sessions.html +488 -0
  73. package/vendor/runtime/dist/docs-site/shared-sessions.html +377 -0
  74. package/vendor/runtime/dist/{flows-BKlAuzM8.js → flows-oaBGn31w.js} +5 -5
  75. package/vendor/runtime/dist/{flows-BKlAuzM8.js.map → flows-oaBGn31w.js.map} +1 -1
  76. package/vendor/runtime/dist/flows.d.ts +2 -2
  77. package/vendor/runtime/dist/flows.d.ts.map +1 -1
  78. package/vendor/runtime/dist/flows.js +1 -2
  79. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js → invocation-options-CUDEE8vW.js} +5 -5
  80. package/vendor/runtime/dist/{invocation-options-DMy77sEU.js.map → invocation-options-CUDEE8vW.js.map} +1 -1
  81. package/vendor/runtime/dist/{ipc-CLv2iL89.js → ipc-BQQpcEdP.js} +98 -20
  82. package/vendor/runtime/dist/ipc-BQQpcEdP.js.map +1 -0
  83. package/vendor/runtime/dist/{output-I-t-v55D.js → output-CFv3jcOQ.js} +86 -22
  84. package/vendor/runtime/dist/output-CFv3jcOQ.js.map +1 -0
  85. package/vendor/runtime/dist/{queue-owner-runtime-RN3uSid0.js → queue-owner-runtime-DvMJiGbP.js} +86 -27
  86. package/vendor/runtime/dist/queue-owner-runtime-DvMJiGbP.js.map +1 -0
  87. package/vendor/runtime/dist/runtime.d.ts +5 -2
  88. package/vendor/runtime/dist/runtime.d.ts.map +1 -1
  89. package/vendor/runtime/dist/runtime.js +77 -29
  90. package/vendor/runtime/dist/runtime.js.map +1 -1
  91. package/vendor/runtime/dist/{session-options-DNnDfiUt.d.ts → session-options-NjpFwf-c.d.ts} +5 -1
  92. package/vendor/runtime/dist/session-options-NjpFwf-c.d.ts.map +1 -0
  93. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js → session-watch-Di-wIdCH.js} +4 -4
  94. package/vendor/runtime/dist/{session-watch-CmHbH0jS.js.map → session-watch-Di-wIdCH.js.map} +1 -1
  95. package/vendor/runtime/dist/{watch-BE-kKa7o.js → watch-CIpoMaWD.js} +2 -2
  96. package/vendor/runtime/dist/{watch-BE-kKa7o.js.map → watch-CIpoMaWD.js.map} +1 -1
  97. package/vendor/runtime/package.json +1 -1
  98. package/vendor/runtime/skills/acpx/SKILL.md +7 -2
  99. package/vendor/runtime/dist/agent-registry-CMg8LHKY.js.map +0 -1
  100. package/vendor/runtime/dist/ipc-CLv2iL89.js.map +0 -1
  101. package/vendor/runtime/dist/output-I-t-v55D.js.map +0 -1
  102. package/vendor/runtime/dist/queue-owner-runtime-RN3uSid0.js.map +0 -1
  103. package/vendor/runtime/dist/session-options-DNnDfiUt.d.ts.map +0 -1
@@ -1,5 +1,5 @@
1
- import { $ as resetPerfMetrics, $t as UnsupportedPromptContentError, Bt as AgentStartupError, C as textPrompt, Ct as normalizeOutputError, Dt as isAcpResourceNotFoundError, Et as extractAcpError, F as normalizeName, G as SESSION_JOURNAL_SCHEMA, Gt as PermissionDeniedError, Ht as ClaudeAcpSessionCreateTimeoutError, Jt as SessionConfigOptionReplayError, K as SessionJournalReader, Kt as PermissionPromptUnavailableError, L as readSessionRecord, Lt as AcpxOperationalError, M as isoNow$1, O as absolutePath, Q as measurePerf, Qt as SessionResumeRequiredError, R as resolveSessionRecord, Rt as AgentDisconnectedError, S as promptToDisplayText, St as isRetryablePromptError, T as lockOwnerPid, U as extractAgentSessionId, Ut as CopilotAcpUnsupportedError, Vt as AuthPolicyError, W as normalizeAgentSessionId, Wt as GeminiAcpStartupTimeoutError, X as getPerfMetricsSnapshot, Xt as SessionModelReplayError, Y as formatPerfMetric, Yt as SessionModeReplayError, Z as incrementPerfCounter, _ as ProcessDescendants, a as trySetModelOnRunningOwner, at as isSessionUpdateNotification, bt as formatErrorMessage, d as releaseQueueOwnerLease, dt as sessionBaseDir, et as setPerfGauge, f as terminateProcess, ft as sessionEventActivePath, g as QueueLeaseGuardSettlementError, h as waitMs$1, i as trySetModeOnRunningOwner, it as isAcpMessageObject, j as findSessionByDirectoryWalk, k as findGitRepositoryRoot, m as tryAcquireQueueOwnerLease, mt as sessionEventSegmentPath, n as tryCloseSessionOnRunningOwner, o as trySubmitToRunningOwner, p as terminateQueueOwnerForSession, pt as sessionEventLockPath, qt as QueueConnectionError, r as trySetConfigOptionOnRunningOwner, rt as isAcpJsonRpcMessage, s as SessionQueueOwner, t as tryCancelOnRunningOwner, tt as startPerfTimer, u as refreshQueueOwnerLease, ut as defaultSessionEventLog, vt as isProcessAlive, w as createLockOwner, xt as isAcpQueryClosedBeforeResponseError, y as getUnsupportedPromptContentMessage, z as writeSessionRecord, zt as AgentSpawnError } from "./ipc-CLv2iL89.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-CMg8LHKY.js";
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-BQQpcEdP.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-R7A3MSpr.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";
@@ -139,8 +139,8 @@ async function pathExists(filePath) {
139
139
  }
140
140
  }
141
141
  async function countExistingSegments(sessionId, maxSegments) {
142
- let count = 0;
143
- for (let segment = 1; segment <= maxSegments; segment += 1) if (await pathExists(sessionEventSegmentPath(sessionId, segment))) count += 1;
142
+ const limit = retainedEventMaxSegments(maxSegments);
143
+ let count = (await existingEventSegmentIndices(sessionId)).filter((index) => index <= limit).length;
144
144
  if (await pathExists(sessionEventActivePath(sessionId))) count += 1;
145
145
  return count;
146
146
  }
@@ -151,22 +151,36 @@ async function resolveInitialSegmentCount(record, maxSegments) {
151
151
  async function resolveSessionMaxSegments(sessionId) {
152
152
  try {
153
153
  const configured = (await resolveSessionRecord(sessionId)).eventLog.max_segments;
154
- if (Number.isInteger(configured) && configured > 0) return configured;
154
+ const retained = retainedEventMaxSegments(configured);
155
+ if (retained > 0) return retained;
155
156
  } catch {}
156
157
  return 5;
157
158
  }
158
159
  async function rotateSegments(sessionId, maxSegments) {
159
- const active = sessionEventActivePath(sessionId);
160
- const overflow = sessionEventSegmentPath(sessionId, maxSegments);
161
- await fs$1.unlink(overflow).catch((error) => {
160
+ const limit = retainedEventMaxSegments(maxSegments);
161
+ if (limit < 1) return;
162
+ await discardOverflowSegment(sessionId, limit);
163
+ await shiftRetainedSegments(sessionId, limit);
164
+ await promoteActiveSegment(sessionId);
165
+ }
166
+ async function discardOverflowSegment(sessionId, limit) {
167
+ if (!(await existingEventSegmentIndices(sessionId)).includes(limit)) return;
168
+ await fs$1.unlink(sessionEventSegmentPath(sessionId, limit)).catch((error) => {
162
169
  if (error.code !== "ENOENT") throw error;
163
170
  });
164
- for (let segment = maxSegments - 1; segment >= 1; segment -= 1) {
171
+ }
172
+ async function shiftRetainedSegments(sessionId, limit) {
173
+ const movable = (await existingEventSegmentIndices(sessionId)).filter((index) => index < limit).toSorted((left, right) => right - left);
174
+ for (const segment of movable) {
165
175
  const from = sessionEventSegmentPath(sessionId, segment);
166
- const to = sessionEventSegmentPath(sessionId, segment + 1);
167
176
  if (!await pathExists(from)) continue;
168
- await fs$1.rename(from, to);
177
+ const next = segment + 1;
178
+ if (!Number.isSafeInteger(next)) throw new Error("Session journal segment index exceeds its supported range");
179
+ await fs$1.rename(from, sessionEventSegmentPath(sessionId, next));
169
180
  }
181
+ }
182
+ async function promoteActiveSegment(sessionId) {
183
+ const active = sessionEventActivePath(sessionId);
170
184
  if (await pathExists(active)) await fs$1.rename(active, sessionEventSegmentPath(sessionId, 1));
171
185
  }
172
186
  var SessionEventWriter = class SessionEventWriter {
@@ -201,7 +215,7 @@ var SessionEventWriter = class SessionEventWriter {
201
215
  }
202
216
  static async open(record, options = {}) {
203
217
  const maxSegmentBytes = options.maxSegmentBytes ?? record.eventLog.max_segment_bytes ?? 67108864;
204
- const maxSegments = options.maxSegments ?? record.eventLog.max_segments ?? 5;
218
+ const maxSegments = retainedEventMaxSegments(options.maxSegments ?? record.eventLog.max_segments ?? 5);
205
219
  const activePath = sessionEventActivePath(record.acpxRecordId);
206
220
  const tail = await new SessionJournalReader({
207
221
  ...record,
@@ -366,7 +380,7 @@ var SessionEventWriter = class SessionEventWriter {
366
380
  }
367
381
  };
368
382
  async function listSessionEvents(sessionId, maxSegments) {
369
- maxSegments ??= await resolveSessionMaxSegments(sessionId);
383
+ maxSegments = retainedEventMaxSegments(maxSegments ?? await resolveSessionMaxSegments(sessionId));
370
384
  return await new SessionJournalReader({
371
385
  acpxRecordId: sessionId,
372
386
  eventLog: { max_segments: maxSegments }
@@ -585,7 +599,7 @@ async function acquireSessionTurn(recordId, signal) {
585
599
  }
586
600
  async function acquireSessionScope(scope, signal) {
587
601
  return await acquireSessionTurn(`ensure:${createHash("sha256").update(JSON.stringify([
588
- scope.agentCommand,
602
+ canonicalAgentCommand(scope.agentCommand),
589
603
  scope.cwd,
590
604
  scope.name
591
605
  ])).digest("hex")}`, signal);
@@ -633,6 +647,18 @@ function sliceReadWindow(content, line, limit) {
633
647
  }
634
648
  //#endregion
635
649
  //#region src/permission-prompt.ts
650
+ function visiblePromptText(value) {
651
+ let rendered = "";
652
+ for (const character of value) {
653
+ const codePoint = character.codePointAt(0);
654
+ if (codePoint !== void 0 && (codePoint <= 31 || codePoint >= 127 && codePoint <= 159)) {
655
+ rendered += `\\x${codePoint.toString(16).padStart(2, "0")}`;
656
+ continue;
657
+ }
658
+ rendered += character;
659
+ }
660
+ return rendered;
661
+ }
636
662
  let promptQueue = Promise.resolve();
637
663
  async function promptForPermission(options) {
638
664
  options.signal?.throwIfAborted();
@@ -651,6 +677,10 @@ async function promptForPermission(options) {
651
677
  signal.removeEventListener("abort", onAbort);
652
678
  }
653
679
  }
680
+ function promptForDisplay(prompt) {
681
+ if (prompt.startsWith("\n")) return `\n${visiblePromptText(prompt.slice(1))}`;
682
+ return visiblePromptText(prompt);
683
+ }
654
684
  async function askPermission(options) {
655
685
  options.signal?.throwIfAborted();
656
686
  if (!canPrompt()) return false;
@@ -667,7 +697,7 @@ async function askPermission(options) {
667
697
  rl.once("close", onClose);
668
698
  });
669
699
  try {
670
- const answer = await Promise.race([rl.question(options.prompt, { signal }), closed]);
700
+ const answer = await Promise.race([rl.question(promptForDisplay(options.prompt), { signal }), closed]);
671
701
  options.signal?.throwIfAborted();
672
702
  const normalized = answer?.trim().toLowerCase();
673
703
  return normalized === "y" || normalized === "yes";
@@ -681,8 +711,8 @@ function canPrompt() {
681
711
  return process.stdin.isTTY && process.stderr.isTTY && !process.stdin.readableEnded && !process.stdin.destroyed;
682
712
  }
683
713
  function writePromptDetails(options) {
684
- if (options.header) process.stderr.write(`\n${options.header}\n`);
685
- if (options.details && options.details.trim().length > 0) process.stderr.write(`${options.details}\n`);
714
+ if (options.header) process.stderr.write(`\n${visiblePromptText(options.header)}\n`);
715
+ if (options.details && options.details.trim().length > 0) process.stderr.write(`${options.details.split("\n").map(visiblePromptText).join("\n")}\n`);
686
716
  }
687
717
  //#endregion
688
718
  //#region src/filesystem.ts
@@ -1147,6 +1177,7 @@ const DECISION_FALLBACK_ORDER = {
1147
1177
  };
1148
1178
  function decisionToResponse(params, decision) {
1149
1179
  if (decision.outcome === "cancel") return cancelled();
1180
+ if (decision.outcome === "selected") return params.options.some((option) => option.optionId === decision.optionId) ? selected(decision.optionId) : cancelled();
1150
1181
  const matched = pickOption(params.options ?? [], DECISION_FALLBACK_ORDER[decision.outcome]);
1151
1182
  return matched ? selected(matched.optionId) : cancelled();
1152
1183
  }
@@ -5072,6 +5103,7 @@ function cloneUsageCost(cost) {
5072
5103
  function cloneSessionAcpxState(state) {
5073
5104
  if (!state) return;
5074
5105
  return {
5106
+ ...state.session_origin ? { session_origin: state.session_origin } : {},
5075
5107
  current_mode_id: state.current_mode_id,
5076
5108
  desired_mode_id: state.desired_mode_id,
5077
5109
  desired_config_options: state.desired_config_options ? { ...state.desired_config_options } : void 0,
@@ -5082,7 +5114,7 @@ function cloneSessionAcpxState(state) {
5082
5114
  available_commands: state.available_commands ? state.available_commands.map((command) => ({ ...command })) : void 0,
5083
5115
  config_options: state.config_options ? deepClone(state.config_options) : void 0,
5084
5116
  session_options: cloneSessionOptions(state.session_options),
5085
- turn_results: state.turn_results ? deepClone(state.turn_results) : void 0
5117
+ turn_results: deepClone(state.turn_results)
5086
5118
  };
5087
5119
  }
5088
5120
  function cloneSessionOptions(options) {
@@ -5296,7 +5328,7 @@ function createInitialSessionRecord(params) {
5296
5328
  closed: false,
5297
5329
  closedAt: void 0,
5298
5330
  ...createSessionConversation(now),
5299
- acpx: {}
5331
+ acpx: params.sessionOrigin ? { session_origin: params.sessionOrigin } : {}
5300
5332
  };
5301
5333
  }
5302
5334
  function applyLifecycleSnapshotToRecord(record, snapshot) {
@@ -5323,6 +5355,17 @@ function reconcileAgentSessionId(record, agentSessionId) {
5323
5355
  function sessionHasAgentMessages(recordOrConversation) {
5324
5356
  return recordOrConversation.messages.some((message) => typeof message === "object" && message !== null && "Agent" in message);
5325
5357
  }
5358
+ function sessionHasAtMostOneUserMessage(recordOrConversation) {
5359
+ let userMessageCount = 0;
5360
+ for (const message of recordOrConversation.messages) if (typeof message === "object" && message !== null && "User" in message) {
5361
+ userMessageCount += 1;
5362
+ if (userMessageCount > 1) return false;
5363
+ }
5364
+ return true;
5365
+ }
5366
+ function sessionHasUserMessages(recordOrConversation) {
5367
+ return recordOrConversation.messages.some((message) => typeof message === "object" && message !== null && "User" in message);
5368
+ }
5326
5369
  function applyConversation(record, conversation) {
5327
5370
  record.title = conversation.title;
5328
5371
  record.updated_at = conversation.updated_at;
@@ -5765,7 +5808,8 @@ async function connectAndLoadSession(options) {
5765
5808
  reusingLoadedSession,
5766
5809
  sameSessionOnly,
5767
5810
  timeoutMs: options.timeoutMs,
5768
- authority: options.authority
5811
+ authority: options.authority,
5812
+ promptRecorded: options.promptRecorded
5769
5813
  });
5770
5814
  const { resumed, loadError, sessionId, createdFreshSession, pendingAgentSessionId, sessionModels } = loadState;
5771
5815
  applyReconnectedModelState(record, sessionModels, loadState.configOptionsPresent, loadState.legacyModelMetadataPresent, createdFreshSession);
@@ -5964,19 +6008,32 @@ function rethrowCancelledLoad(error, authority) {
5964
6008
  }
5965
6009
  async function recoverRuntimeSessionLoadFailure(params, error) {
5966
6010
  const loadError = formatErrorMessage(error);
5967
- if (params.sameSessionOnly) throw makeSessionResumeRequiredError({
5968
- record: params.record,
5969
- reason: loadError,
5970
- cause: error
5971
- });
5972
- if (!shouldFallbackToNewSession(error, params.record)) throw error;
6011
+ if (!canRecoverLoadWithFreshSession(params, error)) {
6012
+ if (params.sameSessionOnly) throw makeSessionResumeRequiredError({
6013
+ record: params.record,
6014
+ reason: loadError,
6015
+ cause: error
6016
+ });
6017
+ throw error;
6018
+ }
5973
6019
  return {
5974
6020
  ...await createFreshRuntimeSession(params.client, params.record, params.timeoutMs, params.authority),
5975
6021
  loadError
5976
6022
  };
5977
6023
  }
6024
+ function canRecoverLoadWithFreshSession(params, error) {
6025
+ if (!params.sameSessionOnly) return shouldFallbackToNewSession(error, params.record);
6026
+ return isUnpromptedNewSession(params.record, params.promptRecorded) && extractAcpError(error)?.code === -32603;
6027
+ }
6028
+ function isUnpromptedNewSession(record, promptRecorded = false) {
6029
+ return record.acpx?.session_origin === "new" && !record.importedFrom && !sessionHasAgentMessages(record) && !record.messages.includes("Resume") && (promptRecorded ? sessionHasAtMostOneUserMessage(record) : !sessionHasUserMessages(record));
6030
+ }
5978
6031
  async function createFreshRuntimeSession(client, record, timeoutMs, authority) {
5979
6032
  const createdSession = await withTimeout(client.createSession(record.cwd, authority), timeoutMs);
6033
+ record.acpx = {
6034
+ ...record.acpx,
6035
+ session_origin: "new"
6036
+ };
5980
6037
  applyConfigOptionsToRecord(record, createdSession);
5981
6038
  return {
5982
6039
  sessionId: createdSession.sessionId,
@@ -6517,6 +6574,7 @@ async function createSessionRecordWithClient(client, options, resumedRecordId) {
6517
6574
  recordId: resumedRecordId ?? randomUUID(),
6518
6575
  sessionId,
6519
6576
  agentSessionId,
6577
+ sessionOrigin: options.resumeSessionId ? "resume" : "new",
6520
6578
  agentCommand: options.agentCommand,
6521
6579
  agentArgv: options.agentArgv,
6522
6580
  cwd,
@@ -8069,6 +8127,7 @@ async function runOwnedSessionPrompt(options) {
8069
8127
  timeoutMs: options.timeoutMs,
8070
8128
  verbose: options.verbose,
8071
8129
  suppressWarnings: options.suppressSdkConsoleErrors,
8130
+ promptRecorded: true,
8072
8131
  activeController,
8073
8132
  authority: { signal: options.ownedSignal },
8074
8133
  onClientAvailable: (controller) => {
@@ -8864,4 +8923,4 @@ const queueOwnerRuntimeTestInternals = { queueOwnerExitIsFatal };
8864
8923
  //#endregion
8865
8924
  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 };
8866
8925
 
8867
- //# sourceMappingURL=queue-owner-runtime-RN3uSid0.js.map
8926
+ //# sourceMappingURL=queue-owner-runtime-DvMJiGbP.js.map