@letta-ai/letta-code 0.34.38 → 0.34.39

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/mcp-client.js +2 -2
  2. package/dist/mcp-client.js.map +1 -1
  3. package/dist/mcp-oauth.js +2 -2
  4. package/dist/mcp-oauth.js.map +1 -1
  5. package/dist/types/backend/api/agent-message.d.ts +18 -3
  6. package/dist/types/backend/api/agent-message.d.ts.map +1 -1
  7. package/dist/types/backend/api/conversation-enqueue.d.ts +5 -2
  8. package/dist/types/backend/api/conversation-enqueue.d.ts.map +1 -1
  9. package/dist/types/tools/impl/send-agent-message.d.ts.map +1 -1
  10. package/dist/types/types/protocol_v2.d.ts +1 -0
  11. package/dist/types/types/protocol_v2.d.ts.map +1 -1
  12. package/dist/types/types/teleport-protocol.d.ts +12 -1
  13. package/dist/types/types/teleport-protocol.d.ts.map +1 -1
  14. package/dist/types/websocket/listener/input-disposition-retention.d.ts +1 -0
  15. package/dist/types/websocket/listener/input-disposition-retention.d.ts.map +1 -1
  16. package/dist/types/websocket/listener/input-disposition.d.ts +0 -2
  17. package/dist/types/websocket/listener/input-disposition.d.ts.map +1 -1
  18. package/dist/types/websocket/listener/input-terminal-journal.d.ts +7 -6
  19. package/dist/types/websocket/listener/input-terminal-journal.d.ts.map +1 -1
  20. package/dist/types/websocket/listener/interrupted-turn-record.d.ts +14 -0
  21. package/dist/types/websocket/listener/interrupted-turn-record.d.ts.map +1 -1
  22. package/dist/types/websocket/listener/interrupted-turn-revision.d.ts +3 -0
  23. package/dist/types/websocket/listener/interrupted-turn-revision.d.ts.map +1 -0
  24. package/dist/types/websocket/listener/interrupted-turn-schema.d.ts.map +1 -1
  25. package/dist/types/websocket/listener/interrupted-turn-types.d.ts +5 -1
  26. package/dist/types/websocket/listener/interrupted-turn-types.d.ts.map +1 -1
  27. package/dist/types/websocket/listener/teleport-protocol-inbound.d.ts.map +1 -1
  28. package/dist/types/websocket/listener/turn-finished-replay.d.ts +2 -1
  29. package/dist/types/websocket/listener/turn-finished-replay.d.ts.map +1 -1
  30. package/dist/types/websocket/listener/types.d.ts +5 -0
  31. package/dist/types/websocket/listener/types.d.ts.map +1 -1
  32. package/letta.js +950 -406
  33. package/npm-shrinkwrap.json +11 -11
  34. package/package.json +2 -2
package/letta.js CHANGED
@@ -6077,7 +6077,7 @@ var package_default;
6077
6077
  var init_package = __esm(() => {
6078
6078
  package_default = {
6079
6079
  name: "@letta-ai/letta-code",
6080
- version: "0.34.38",
6080
+ version: "0.34.39",
6081
6081
  lettaStartupLogProtocol: 1,
6082
6082
  lettaConfigDirProtocol: 1,
6083
6083
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6355,7 +6355,7 @@ var init_package = __esm(() => {
6355
6355
  },
6356
6356
  lettaLifecycleProtocol: 1,
6357
6357
  lettaRuntimeGraphProtocol: 1,
6358
- lettaRuntimeGraphSha512: "sha512-A1kdX0tWknAIbqO7TviYhJ8DS12ycZiM8dB/8GuJPSW1AHCVvJ9QpqCQ/iVE1TOGYMRJpRz+FcpND+DAwTF7pg==",
6358
+ lettaRuntimeGraphSha512: "sha512-2T51CT9i+lr8cRce+/Vs++Xywnnut1NfZ62mMgIegeoXkikscyAvNQMjutx/TWqrsEH2TIk9QbYCuTeC4WhOVw==",
6359
6359
  patchedDependencies: {
6360
6360
  "@earendil-works/pi-ai@0.99.1": "patches/@earendil-works%2Fpi-ai@0.99.1.patch"
6361
6361
  }
@@ -211785,7 +211785,7 @@ var init_mcp_client = __esm(() => {
211785
211785
  init_streamableHttp();
211786
211786
  DEFAULT_CLIENT_INFO = {
211787
211787
  name: "letta-code",
211788
- version: "0.34.38"
211788
+ version: "0.34.39"
211789
211789
  };
211790
211790
  });
211791
211791
 
@@ -215553,6 +215553,31 @@ function collectInterruptedTurnInputOwnershipWithSidecars(records, readMainView,
215553
215553
  }
215554
215554
  var init_interrupted_turn_input_ownership = () => {};
215555
215555
 
215556
+ // src/websocket/listener/interrupted-turn-revision.ts
215557
+ import { randomUUID as randomUUID31 } from "node:crypto";
215558
+ function stampInterruptedTurnRevision(record6) {
215559
+ const revision = randomUUID31();
215560
+ return {
215561
+ ...record6,
215562
+ revision,
215563
+ ...record6.teleport ? {
215564
+ teleport: {
215565
+ ...record6.teleport,
215566
+ intentRevision: record6.teleport.intentRevision ?? revision,
215567
+ ...record6.teleport.terminalAuthority ? {
215568
+ terminalAuthority: {
215569
+ ...record6.teleport.terminalAuthority,
215570
+ interruptedRevision: record6.teleport.terminalAuthority.interruptedRevision || revision,
215571
+ authorityRevision: record6.teleport.terminalAuthority.authorityRevision || revision
215572
+ }
215573
+ } : {},
215574
+ readyRevision: record6.teleport.ready ? record6.teleport.readyRevision ?? revision : record6.teleport.readyRevision
215575
+ }
215576
+ } : {}
215577
+ };
215578
+ }
215579
+ var init_interrupted_turn_revision = () => {};
215580
+
215556
215581
  // src/types/turn-finished-protocol.ts
215557
215582
  function isTerminalConsumerId(value) {
215558
215583
  return typeof value === "string" && value.length > 0 && value.length <= MAX_TERMINAL_CONSUMER_ID_LENGTH && /^[A-Za-z0-9._~:%-]+$/.test(value);
@@ -221661,7 +221686,7 @@ __export(exports_overflow, {
221661
221686
  cleanupOldOverflowFiles: () => cleanupOldOverflowFiles,
221662
221687
  OVERFLOW_CONFIG: () => OVERFLOW_CONFIG
221663
221688
  });
221664
- import { randomUUID as randomUUID31 } from "node:crypto";
221689
+ import { randomUUID as randomUUID32 } from "node:crypto";
221665
221690
  import * as fs15 from "node:fs";
221666
221691
  import * as path16 from "node:path";
221667
221692
  function getOverflowDirectory(workingDirectory) {
@@ -221680,7 +221705,7 @@ function ensureOverflowDirectory(workingDirectory) {
221680
221705
  }
221681
221706
  function writeOverflowFile(content, workingDirectory, toolName2, secrets2 = {}) {
221682
221707
  const overflowDir = ensureOverflowDirectory(workingDirectory);
221683
- const uuid5 = randomUUID31();
221708
+ const uuid5 = randomUUID32();
221684
221709
  const filename = toolName2 ? `${toolName2.toLowerCase()}-${uuid5}.txt` : `${uuid5}.txt`;
221685
221710
  const filePath = path16.join(overflowDir, filename);
221686
221711
  fs15.writeFileSync(filePath, scrubSecretsFromString(content, secrets2), "utf-8");
@@ -230155,7 +230180,7 @@ var init_analyzer = __esm(() => {
230155
230180
  });
230156
230181
 
230157
230182
  // src/agent/mcp-originator-authority-file.ts
230158
- import { createHash as createHash9, randomUUID as randomUUID32 } from "node:crypto";
230183
+ import { createHash as createHash9, randomUUID as randomUUID33 } from "node:crypto";
230159
230184
  import {
230160
230185
  closeSync as closeSync7,
230161
230186
  existsSync as existsSync40,
@@ -230244,7 +230269,7 @@ function writeAuthorityRecords(path19, records) {
230244
230269
  version: 1,
230245
230270
  records: Object.fromEntries(records)
230246
230271
  };
230247
- const tmp = `${path19}.${process.pid}.${randomUUID32()}.tmp`;
230272
+ const tmp = `${path19}.${process.pid}.${randomUUID33()}.tmp`;
230248
230273
  try {
230249
230274
  writeFileSync27(tmp, JSON.stringify(file), { mode: 384, flag: "wx" });
230250
230275
  const fd = openSync7(tmp, "r+");
@@ -235130,7 +235155,7 @@ var init_mcp = __esm(() => {
235130
235155
  });
235131
235156
 
235132
235157
  // src/tools/script-tool-scope.ts
235133
- import { randomUUID as randomUUID33 } from "node:crypto";
235158
+ import { randomUUID as randomUUID34 } from "node:crypto";
235134
235159
  async function loadServerTools(agentId, builtins) {
235135
235160
  const tools = new Map;
235136
235161
  if (!agentId || !getBackend().capabilities.serverSideToolManagement) {
@@ -235250,7 +235275,7 @@ async function createScriptToolScope(parentAgentId, signal) {
235250
235275
  if (serverTool) {
235251
235276
  return callServerTool(parentAgentId, serverTool, toolArgs, signal);
235252
235277
  }
235253
- const toolCallId = `script-${randomUUID33()}`;
235278
+ const toolCallId = `script-${randomUUID34()}`;
235254
235279
  const { decision } = await manager.checkToolPermission(toolName2, toolArgs, permissionCwd, permissionModeState && { ...permissionModeState }, parentAgentId ?? undefined, toolContextId, toolCallId);
235255
235280
  if (decision !== "allow") {
235256
235281
  throw new Error(decision === "deny" ? `${toolName2} is denied by permission rules.` : `${toolName2} needs approval, which a script cannot request; call it directly or add an allow rule.`);
@@ -238699,7 +238724,7 @@ var init_worktree_git = __esm(async () => {
238699
238724
  });
238700
238725
 
238701
238726
  // src/tools/impl/enter-worktree.ts
238702
- import { randomUUID as randomUUID34 } from "node:crypto";
238727
+ import { randomUUID as randomUUID35 } from "node:crypto";
238703
238728
  import {
238704
238729
  copyFile,
238705
238730
  lstat,
@@ -238721,7 +238746,7 @@ function getStringArg(args, key2) {
238721
238746
  }
238722
238747
  function slugifyName(name) {
238723
238748
  const slug = name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^-+|-+$/g, "").replace(/-{2,}/g, "-").slice(0, MAX_SLUG_LENGTH).replace(/[-.]+$/g, "");
238724
- return slug || `worktree-${randomUUID34().slice(0, 8)}`;
238749
+ return slug || `worktree-${randomUUID35().slice(0, 8)}`;
238725
238750
  }
238726
238751
  async function localBranchExists(cwd2, branchName) {
238727
238752
  const result2 = await runGit3(["show-ref", "--verify", "--quiet", `refs/heads/${branchName}`], cwd2, { allowFailure: true });
@@ -238786,7 +238811,7 @@ async function chooseUniqueWorktreePath(worktreesDir, slug) {
238786
238811
  return candidate;
238787
238812
  }
238788
238813
  }
238789
- return path23.join(worktreesDir, `${slug}-${randomUUID34().slice(0, 8)}`);
238814
+ return path23.join(worktreesDir, `${slug}-${randomUUID35().slice(0, 8)}`);
238790
238815
  }
238791
238816
  async function chooseUniqueBranchName(repoRoot, slug, requestedBranchName) {
238792
238817
  if (requestedBranchName) {
@@ -238797,7 +238822,7 @@ async function chooseUniqueBranchName(repoRoot, slug, requestedBranchName) {
238797
238822
  return requestedBranchName;
238798
238823
  }
238799
238824
  for (let index = 0;index < 10; index += 1) {
238800
- const suffix = randomUUID34().slice(0, 8);
238825
+ const suffix = randomUUID35().slice(0, 8);
238801
238826
  const candidate = `letta/${slug}-${suffix}`;
238802
238827
  await assertValidBranchName(repoRoot, candidate);
238803
238828
  if (!await localBranchExists(repoRoot, candidate)) {
@@ -241752,7 +241777,7 @@ __export(exports_environments3, {
241752
241777
  describeEnvironment: () => describeEnvironment,
241753
241778
  createAgentSandbox: () => createAgentSandbox
241754
241779
  });
241755
- import { randomUUID as randomUUID35 } from "node:crypto";
241780
+ import { randomUUID as randomUUID36 } from "node:crypto";
241756
241781
  async function listEnvironments(options = {}) {
241757
241782
  return apiRequest("GET", "/v1/environments", undefined, {
241758
241783
  query: {
@@ -241857,7 +241882,7 @@ function getTeleportStatus(agentId, conversationId, teleportId, request = apiReq
241857
241882
  async function teleportToEnvironment(agentId, conversationId, targetConnectionId, request = apiRequest) {
241858
241883
  return request("POST", `/v1/environments/runtimes/${encodeURIComponent(agentId)}/${encodeURIComponent(conversationId)}/teleport`, {
241859
241884
  targetConnectionId,
241860
- idempotencyKey: randomUUID35()
241885
+ idempotencyKey: randomUUID36()
241861
241886
  });
241862
241887
  }
241863
241888
  var init_environments3 = __esm(() => {
@@ -244339,7 +244364,7 @@ function getEnqueueAgentId(receipt) {
244339
244364
  }
244340
244365
  async function enqueueConversationMessage(input, signal, request = apiRequest) {
244341
244366
  const body3 = {
244342
- agent_id: input.agentId,
244367
+ ...input.agentId !== undefined ? { agent_id: input.agentId } : {},
244343
244368
  client_message_id: input.clientMessageId,
244344
244369
  ...input.computer !== undefined ? { computer: input.computer } : {},
244345
244370
  messages: [
@@ -244370,7 +244395,7 @@ async function enqueueConversationMessage(input, signal, request = apiRequest) {
244370
244395
  return {
244371
244396
  ...accepted,
244372
244397
  status: "queued",
244373
- agent_id: input.agentId,
244398
+ agent_id: accepted.agent_id ?? input.agentId ?? null,
244374
244399
  conversation_id: input.conversationId,
244375
244400
  acting_user_id: input.actingUserId
244376
244401
  };
@@ -244632,30 +244657,38 @@ function validateAddress(value, kind) {
244632
244657
  }
244633
244658
  return value;
244634
244659
  }
244660
+ function buildAgentMessageRecoveryCommands(destination) {
244661
+ const target2 = `${destination.agentId ? `--agent ${destination.agentId} ` : ""}--conversation ${destination.conversationId}`;
244662
+ return {
244663
+ status_command: `letta messages status ${target2}`,
244664
+ messages_command: `letta messages list ${target2}`
244665
+ };
244666
+ }
244635
244667
  async function resolveAgentMessageDestination(input, backend3, signal) {
244636
- let agentId = validateAddress(input.agentId, "agent");
244668
+ const agentId = validateAddress(input.agentId, "agent");
244637
244669
  let conversationId = validateAddress(input.conversationId, "conversation");
244638
244670
  if (!agentId && !conversationId) {
244639
244671
  throw new Error("Choose a destination with agent_id or conversation_id.");
244640
244672
  }
244641
244673
  const options = { signal, ...actingUserRequestOptions(input.actingUserId) };
244642
- if (conversationId && conversationId !== "default") {
244643
- const conversation = await backend3.retrieveConversation(conversationId, options);
244644
- if (agentId && agentId !== conversation.agent_id) {
244645
- throw new Error("The conversation does not belong to the requested agent.");
244674
+ if (!conversationId || conversationId === "default") {
244675
+ if (!agentId) {
244676
+ throw new Error("The default conversation requires agent_id.");
244677
+ }
244678
+ if (!conversationId) {
244679
+ const conversation = await backend3.createConversation({
244680
+ agent_id: agentId,
244681
+ ...input.senderAgentId ? { hidden: true } : {}
244682
+ }, options);
244683
+ conversationId = conversation.id;
244646
244684
  }
244647
- agentId = conversation.agent_id ?? undefined;
244648
- }
244649
- if (!agentId)
244650
- throw new Error("The default conversation requires agent_id.");
244651
- if (!conversationId) {
244652
- const conversation = await backend3.createConversation({ agent_id: agentId, ...input.senderAgentId ? { hidden: true } : {} }, options);
244653
- conversationId = conversation.id;
244654
244685
  }
244655
- if (agentId === input.currentConversation?.agentId && conversationId === input.currentConversation?.conversationId) {
244686
+ const current = input.currentConversation;
244687
+ const isCurrent = conversationId === current?.conversationId && (conversationId !== "default" || agentId === current?.agentId);
244688
+ if (isCurrent) {
244656
244689
  throw new Error("Cannot message the current conversation. Use Monitor for external events or Wake for timed self-invocation.");
244657
244690
  }
244658
- return { agentId, conversationId };
244691
+ return agentId ? { agentId, conversationId } : { conversationId };
244659
244692
  }
244660
244693
  var init_agent_message = () => {};
244661
244694
 
@@ -244824,7 +244857,7 @@ function emitProgress(listener, value) {
244824
244857
  var MAX_TOOL_CALL_ARGS_LENGTH = 1000;
244825
244858
 
244826
244859
  // src/tools/impl/claude-stream-session.ts
244827
- import { randomUUID as randomUUID36 } from "node:crypto";
244860
+ import { randomUUID as randomUUID37 } from "node:crypto";
244828
244861
  import { createInterface as createInterface8 } from "node:readline";
244829
244862
  function errorMessage2(error5) {
244830
244863
  return error5 instanceof Error ? error5.message : String(error5);
@@ -244980,7 +245013,7 @@ function writeRaw(stdin, data) {
244980
245013
  });
244981
245014
  }
244982
245015
  function writeInput(session3, prompt) {
244983
- const uuid5 = randomUUID36();
245016
+ const uuid5 = randomUUID37();
244984
245017
  session3.latestInputUuid = uuid5;
244985
245018
  session3.latestInputStarted = false;
244986
245019
  return writeRaw(session3.transport.process.stdin, userInput(prompt, uuid5));
@@ -245151,7 +245184,7 @@ function handleResult(session3, value) {
245151
245184
  finishResult(session3, value);
245152
245185
  }
245153
245186
  async function launchSession(options, deps) {
245154
- const sessionId = options.resumeSessionId ?? options.sessionId ?? deps.createSessionId?.() ?? randomUUID36();
245187
+ const sessionId = options.resumeSessionId ?? options.sessionId ?? deps.createSessionId?.() ?? randomUUID37();
245155
245188
  const env6 = withNativeCliPath({
245156
245189
  ...deps.env ?? process.env,
245157
245190
  AGENT_ID: options.parentAgentId,
@@ -245345,7 +245378,7 @@ async function startSession(options, deps) {
245345
245378
  return launchSession(options, deps);
245346
245379
  }
245347
245380
  async function runClaudeTurn(options, deps = {}) {
245348
- const sessionId = options.resumeSessionId ?? options.sessionId ?? deps.createSessionId?.() ?? randomUUID36();
245381
+ const sessionId = options.resumeSessionId ?? options.sessionId ?? deps.createSessionId?.() ?? randomUUID37();
245349
245382
  options.onStarted?.(sessionId);
245350
245383
  try {
245351
245384
  const session3 = await startSession({ ...options, sessionId, onStarted: undefined }, deps);
@@ -245376,7 +245409,7 @@ async function steerSession(session3, prompt, signal) {
245376
245409
  if (session3.settled || sessions.get(session3.sessionId) !== session3) {
245377
245410
  throw new Error("Claude Code session is no longer active");
245378
245411
  }
245379
- const requestId = randomUUID36();
245412
+ const requestId = randomUUID37();
245380
245413
  const response = new Promise((resolve35, reject2) => {
245381
245414
  session3.pendingControls.set(requestId, { resolve: resolve35, reject: reject2 });
245382
245415
  });
@@ -245715,7 +245748,7 @@ class CodexAppServerClient {
245715
245748
  await this.request("initialize", {
245716
245749
  clientInfo: {
245717
245750
  name: "letta-code",
245718
- version: "0.34.38"
245751
+ version: "0.34.39"
245719
245752
  },
245720
245753
  capabilities: null
245721
245754
  });
@@ -246216,7 +246249,7 @@ var init_codex_app_server = __esm(() => {
246216
246249
  });
246217
246250
 
246218
246251
  // src/tools/impl/cursor-session.ts
246219
- import { randomUUID as randomUUID37 } from "node:crypto";
246252
+ import { randomUUID as randomUUID38 } from "node:crypto";
246220
246253
  import { existsSync as existsSync46 } from "node:fs";
246221
246254
  import { join as join63 } from "node:path";
246222
246255
  import { createInterface as createInterface10 } from "node:readline";
@@ -246236,7 +246269,7 @@ function resolveCursorWorkerPath() {
246236
246269
  return bundled;
246237
246270
  }
246238
246271
  async function runCursorTurn(options, env6 = process.env, secrets2 = {}) {
246239
- const id2 = options.resumeSessionId ?? randomUUID37();
246272
+ const id2 = options.resumeSessionId ?? randomUUID38();
246240
246273
  const startedAt = Date.now();
246241
246274
  const redact = (text2) => scrubSecretsFromString(text2, {
246242
246275
  ...secrets2,
@@ -247424,7 +247457,7 @@ var init_engine3 = __esm(() => {
247424
247457
  });
247425
247458
 
247426
247459
  // src/tools/impl/native-session-capture.ts
247427
- import { createHash as createHash10, randomUUID as randomUUID38 } from "node:crypto";
247460
+ import { createHash as createHash10, randomUUID as randomUUID39 } from "node:crypto";
247428
247461
  import { readdirSync as readdirSync17, rmSync as rmSync16 } from "node:fs";
247429
247462
  import {
247430
247463
  mkdtemp as mkdtemp4,
@@ -247983,7 +248016,7 @@ var init_native_session_capture = __esm(() => {
247983
248016
  states2 = new Map;
247984
248017
  admissions = new Map;
247985
248018
  spoolDirectories = new Set;
247986
- captureProcessInstanceId = randomUUID38();
248019
+ captureProcessInstanceId = randomUUID39();
247987
248020
  activeInstanceRegistryKey = Symbol.for("letta.native-session-capture.active-instances");
247988
248021
  activeCaptureInstances = (() => {
247989
248022
  const globalRegistry2 = globalThis;
@@ -248008,7 +248041,7 @@ var init_native_session_capture = __esm(() => {
248008
248041
  import {
248009
248042
  spawnSync as spawnSync6
248010
248043
  } from "node:child_process";
248011
- import { randomUUID as randomUUID39 } from "node:crypto";
248044
+ import { randomUUID as randomUUID40 } from "node:crypto";
248012
248045
  import { request } from "node:http";
248013
248046
  function trackProcess(child) {
248014
248047
  children.add(child);
@@ -248038,7 +248071,7 @@ function trackProcess(child) {
248038
248071
 
248039
248072
  class OpenCodeServer {
248040
248073
  lifetime = new AbortController;
248041
- password = randomUUID39();
248074
+ password = randomUUID40();
248042
248075
  url = "";
248043
248076
  directory;
248044
248077
  ready;
@@ -248436,7 +248469,7 @@ var init_opencode_session = __esm(() => {
248436
248469
  });
248437
248470
 
248438
248471
  // src/tools/impl/external-coding-agent.ts
248439
- import { randomUUID as randomUUID40 } from "node:crypto";
248472
+ import { randomUUID as randomUUID41 } from "node:crypto";
248440
248473
  import { once as once2 } from "node:events";
248441
248474
  function createExternalCodingAgentConfig(type3) {
248442
248475
  return {
@@ -248835,7 +248868,7 @@ async function runExternalCodingAgent(options, deps = {}) {
248835
248868
  const preflight = await (deps.runPreflight ?? defaultRunPreflight)(options.type === "claude-code" ? "claude" : "codex", preflightArgs(options.type), env6, options.signal);
248836
248869
  assertPreflightReady(options.type, preflight);
248837
248870
  if (options.type === "claude-code" && !deps.runProcess) {
248838
- const sessionId = options.resumeSessionId ?? randomUUID40();
248871
+ const sessionId = options.resumeSessionId ?? randomUUID41();
248839
248872
  if (scope && !options.resumeSessionId)
248840
248873
  rememberNativeSession("claude_code", sessionId, scope);
248841
248874
  if (scope)
@@ -250163,7 +250196,7 @@ var init_headless_environment_response = __esm(() => {
250163
250196
  });
250164
250197
 
250165
250198
  // src/headless-listener-launch.ts
250166
- import { randomUUID as randomUUID41 } from "node:crypto";
250199
+ import { randomUUID as randomUUID42 } from "node:crypto";
250167
250200
  import { setTimeout as delay4 } from "node:timers/promises";
250168
250201
  import WebSocket5 from "ws";
250169
250202
  function listenerControlUrl(baseUrl, connectionId, scope) {
@@ -250253,7 +250286,7 @@ async function launchListenerConversation(params, deps = {}) {
250253
250286
  if (!agentId)
250254
250287
  throw new Error("Listener delivery requires an agent or parent agent.");
250255
250288
  const client = deps.client ?? await createListenerClient(params.connectionId, params.scope);
250256
- const clientMessageId = params.clientMessageId ?? randomUUID41();
250289
+ const clientMessageId = params.clientMessageId ?? randomUUID42();
250257
250290
  const runIds = new Set;
250258
250291
  let loop;
250259
250292
  let cancelled = false;
@@ -251731,7 +251764,7 @@ var init_manager4 = __esm(async () => {
251731
251764
 
251732
251765
  // src/agent/memory-conflict-repair.ts
251733
251766
  import { execFile as execFile15 } from "node:child_process";
251734
- import { randomUUID as randomUUID42 } from "node:crypto";
251767
+ import { randomUUID as randomUUID43 } from "node:crypto";
251735
251768
  import { readFile as readFile18, rm as rm9, writeFile as writeFile13 } from "node:fs/promises";
251736
251769
  import { join as join68 } from "node:path";
251737
251770
  import { promisify as promisify15 } from "node:util";
@@ -251803,7 +251836,7 @@ async function transition(memoryDir, fn) {
251803
251836
  }
251804
251837
  }
251805
251838
  async function claimMemoryConflictRepair(memoryDir, kind = "conflict") {
251806
- const token2 = randomUUID42();
251839
+ const token2 = randomUUID43();
251807
251840
  let path30;
251808
251841
  let signature;
251809
251842
  try {
@@ -251868,7 +251901,7 @@ var init_memory_conflict_repair = __esm(() => {
251868
251901
  });
251869
251902
 
251870
251903
  // src/agent/subagents/memory-handoff.ts
251871
- import { randomUUID as randomUUID43 } from "node:crypto";
251904
+ import { randomUUID as randomUUID44 } from "node:crypto";
251872
251905
  import { mkdir as mkdir11, rm as rm10, writeFile as writeFile14 } from "node:fs/promises";
251873
251906
  import { join as join69 } from "node:path";
251874
251907
  async function withMemoryHandoff(params, run) {
@@ -251907,7 +251940,7 @@ async function prepareMemoryHandoff(params) {
251907
251940
  }
251908
251941
  const directory = join69(getTranscriptRoot(), params.agentId, "memory-handoffs");
251909
251942
  await mkdir11(directory, { recursive: true, mode: 448 });
251910
- transcriptPath = join69(directory, `${randomUUID43()}.json`);
251943
+ transcriptPath = join69(directory, `${randomUUID44()}.json`);
251911
251944
  await writeFile14(transcriptPath, JSON.stringify(messages, null, 2), {
251912
251945
  mode: 292,
251913
251946
  flag: "wx"
@@ -252244,7 +252277,7 @@ var init_remote_subagent_events = __esm(() => {
252244
252277
  });
252245
252278
 
252246
252279
  // src/tools/impl/remote-external-coding-agent.ts
252247
- import { randomUUID as randomUUID44 } from "node:crypto";
252280
+ import { randomUUID as randomUUID45 } from "node:crypto";
252248
252281
  import WebSocket6 from "ws";
252249
252282
  function formatRemoteStartupError(type3, computer, code2) {
252250
252283
  const name = DISPLAY_NAMES[type3];
@@ -252468,7 +252501,7 @@ async function launchRemoteExternalCodingAgent(params, deps) {
252468
252501
  }
252469
252502
  params.signal?.throwIfAborted();
252470
252503
  const connect = () => (deps.connect ?? defaultConnect)(connectionId, parentScope);
252471
- const toolCallId = params.toolCallId ?? `remote-${randomUUID44()}`;
252504
+ const toolCallId = params.toolCallId ?? `remote-${randomUUID45()}`;
252472
252505
  let client;
252473
252506
  try {
252474
252507
  client = await connect();
@@ -252483,7 +252516,7 @@ async function launchRemoteExternalCodingAgent(params, deps) {
252483
252516
  let launched;
252484
252517
  try {
252485
252518
  launched = await client.launchSubagent({
252486
- request_id: `launch-subagent-${randomUUID44()}`,
252519
+ request_id: `launch-subagent-${randomUUID45()}`,
252487
252520
  runtime: {
252488
252521
  agent_id: parentScope.agentId,
252489
252522
  conversation_id: parentScope.conversationId,
@@ -252591,7 +252624,7 @@ async function connectQualifiedTarget(agentId, parentScope, deps) {
252591
252624
  };
252592
252625
  }
252593
252626
  async function stopRemoteExternalCodingAgent(params, deps = {}) {
252594
- const requestId = `subagent-stop-${randomUUID44()}`;
252627
+ const requestId = `subagent-stop-${randomUUID45()}`;
252595
252628
  const { target: target2, client } = await connectQualifiedTarget(params.agentId, params.parentScope, deps);
252596
252629
  try {
252597
252630
  const response = await client.stopSubagent({
@@ -252611,9 +252644,9 @@ async function stopRemoteExternalCodingAgent(params, deps = {}) {
252611
252644
  }
252612
252645
  }
252613
252646
  async function sendRemoteExternalCodingAgentMessage(params, deps = {}) {
252614
- const requestId = `subagent-message-${randomUUID44()}`;
252647
+ const requestId = `subagent-message-${randomUUID45()}`;
252615
252648
  const { target: target2, client } = await connectQualifiedTarget(params.agentId, params.parentScope, deps);
252616
- const toolCallId = params.toolCallId ?? `remote-followup-${randomUUID44()}`;
252649
+ const toolCallId = params.toolCallId ?? `remote-followup-${randomUUID45()}`;
252617
252650
  const connect = async () => {
252618
252651
  const resolved2 = await (deps.resolveComputer ?? resolveQualifiedComputer)(target2.computer);
252619
252652
  return (deps.connect ?? defaultConnect)(resolved2.connectionId, params.parentScope);
@@ -253578,7 +253611,7 @@ var init_external_coding_agent_task = __esm(async () => {
253578
253611
  });
253579
253612
 
253580
253613
  // src/tools/impl/send-agent-message.ts
253581
- import { randomUUID as randomUUID45 } from "node:crypto";
253614
+ import { randomUUID as randomUUID46 } from "node:crypto";
253582
253615
  function finishUntrackedNativeCapture(completion, reservation, source, sessionId) {
253583
253616
  if (!reservation)
253584
253617
  return;
@@ -253613,7 +253646,7 @@ function resolveParentAddress(settings3) {
253613
253646
  return { agentId, conversationId };
253614
253647
  }
253615
253648
  async function send_agent_message(args, deps = {}) {
253616
- const clientMessageId = randomUUID45();
253649
+ const clientMessageId = randomUUID46();
253617
253650
  let submissionAttempted = false;
253618
253651
  let destination;
253619
253652
  try {
@@ -253880,8 +253913,6 @@ async function send_agent_message(args, deps = {}) {
253880
253913
  currentConversation: sender
253881
253914
  }, backend3, signal);
253882
253915
  signal.throwIfAborted();
253883
- const child = await resolveChildSubagent(backend3, destination.agentId, sender.agentId);
253884
- signal.throwIfAborted();
253885
253916
  submissionAttempted = true;
253886
253917
  const receipt = await (deps.enqueue ?? enqueueConversationMessage)({
253887
253918
  ...destination,
@@ -253890,6 +253921,7 @@ async function send_agent_message(args, deps = {}) {
253890
253921
  computer,
253891
253922
  actingUserId
253892
253923
  }, signal);
253924
+ const child = receipt.agent_id ? await resolveChildSubagent(backend3, receipt.agent_id, sender.agentId) : null;
253893
253925
  if (child) {
253894
253926
  (deps.trackChildSend ?? trackChildSend)({
253895
253927
  receipt,
@@ -253904,8 +253936,10 @@ async function send_agent_message(args, deps = {}) {
253904
253936
  return {
253905
253937
  content: JSON.stringify({
253906
253938
  ...receipt,
253907
- status_command: `letta messages status --agent ${receipt.agent_id} --conversation ${receipt.conversation_id}`,
253908
- messages_command: `letta messages list --agent ${receipt.agent_id} --conversation ${receipt.conversation_id}`
253939
+ ...buildAgentMessageRecoveryCommands({
253940
+ agentId: receipt.agent_id,
253941
+ conversationId: receipt.conversation_id
253942
+ })
253909
253943
  }),
253910
253944
  status: "success"
253911
253945
  };
@@ -253917,7 +253951,7 @@ async function send_agent_message(args, deps = {}) {
253917
253951
  error: error5 instanceof Error ? error5.message : String(error5),
253918
253952
  client_message_id: clientMessageId,
253919
253953
  ...destination ? {
253920
- agent_id: destination.agentId,
253954
+ ...destination.agentId ? { agent_id: destination.agentId } : {},
253921
253955
  conversation_id: destination.conversationId
253922
253956
  } : {},
253923
253957
  ...error5 instanceof ApiRequestError ? { http_status: error5.status } : {},
@@ -258115,6 +258149,9 @@ function isToolReturnContent2(value) {
258115
258149
  function isTeleportContinuation(value) {
258116
258150
  if (!isObjectRecord(value) || !Array.isArray(value.approvals))
258117
258151
  return false;
258152
+ if (value.terminal_consumer_ids !== undefined && (!Array.isArray(value.terminal_consumer_ids) || !value.terminal_consumer_ids.every(isTerminalConsumerId))) {
258153
+ return false;
258154
+ }
258118
258155
  return value.approvals.every((approval) => {
258119
258156
  if (!isObjectRecord(approval) || typeof approval.tool_call_id !== "string" || approval.tool_call_id.length === 0) {
258120
258157
  return false;
@@ -258139,7 +258176,7 @@ function parseTeleportCommand(value) {
258139
258176
  if (value.type === "teleport_request" && typeof value.request_id === "string" && typeof value.teleport_id === "string" && isObjectRecord(value.target) && typeof value.target.connection_id === "string" && typeof value.target.device_id === "string" && typeof value.target.connection_name === "string") {
258140
258177
  return value;
258141
258178
  }
258142
- if (value.type === "teleport_failed" && typeof value.teleport_id === "string" && typeof value.error === "string") {
258179
+ if (value.type === "teleport_failed" && (value.request_id === undefined || typeof value.request_id === "string") && typeof value.teleport_id === "string" && typeof value.error === "string") {
258143
258180
  return value;
258144
258181
  }
258145
258182
  return null;
@@ -258159,7 +258196,7 @@ function isTeleportIntent(value) {
258159
258196
  if (!value || typeof value !== "object")
258160
258197
  return false;
258161
258198
  const teleport = value;
258162
- return typeof teleport.teleportId === "string" && typeof teleport.connectionId === "string" && (teleport.connectionGeneration === undefined || typeof teleport.connectionGeneration === "string") && typeof teleport.activeTurn === "boolean" && typeof teleport.ready === "boolean" && (teleport.intentRevision === undefined || typeof teleport.intentRevision === "string") && (teleport.committedRevision === undefined || typeof teleport.committedRevision === "string") && (teleport.readyRevision === undefined || typeof teleport.readyRevision === "string") && (teleport.continuation === undefined || isTeleportContinuation(teleport.continuation));
258199
+ return typeof teleport.teleportId === "string" && typeof teleport.connectionId === "string" && (teleport.connectionGeneration === undefined || typeof teleport.connectionGeneration === "string") && typeof teleport.activeTurn === "boolean" && typeof teleport.ready === "boolean" && (teleport.intentRevision === undefined || typeof teleport.intentRevision === "string") && (teleport.committedRevision === undefined || typeof teleport.committedRevision === "string") && (teleport.terminalAuthority === undefined || typeof teleport.terminalAuthority.interruptedRevision === "string" && typeof teleport.terminalAuthority.authorityRevision === "string" && (teleport.terminalAuthority.recoveryAuthorityBaseRevision === undefined || typeof teleport.terminalAuthority.recoveryAuthorityBaseRevision === "string") && (teleport.terminalAuthority.recoveryLineageId === undefined || typeof teleport.terminalAuthority.recoveryLineageId === "string") && (teleport.terminalAuthority.terminalIdentity === undefined || typeof teleport.terminalAuthority.terminalIdentity === "string") && (teleport.terminalAuthority.preparationSequence === undefined || typeof teleport.terminalAuthority.preparationSequence === "number")) && (teleport.preserveSuccessorWork === undefined || typeof teleport.preserveSuccessorWork === "boolean") && (teleport.readyRevision === undefined || typeof teleport.readyRevision === "string") && (teleport.continuation === undefined || isTeleportContinuation(teleport.continuation));
258163
258200
  }
258164
258201
  function isInterruptedTurnRecord(value, file, path33) {
258165
258202
  if (!value || typeof value !== "object")
@@ -258289,7 +258326,7 @@ function createRecoveryAuthorityGuard(dependencies4) {
258289
258326
  }
258290
258327
 
258291
258328
  // src/websocket/listener/recovery-lineage-sidecar.ts
258292
- import { createHash as createHash12, randomUUID as randomUUID46 } from "node:crypto";
258329
+ import { createHash as createHash12, randomUUID as randomUUID47 } from "node:crypto";
258293
258330
  import {
258294
258331
  existsSync as existsSync49,
258295
258332
  mkdirSync as mkdirSync36,
@@ -258329,7 +258366,7 @@ function createRecoveryLineageSidecarAccess(params) {
258329
258366
  const write2 = (sidecar) => {
258330
258367
  mkdirSync36(params.directory, { recursive: true, mode: 448 });
258331
258368
  const destination = path33(sidecar.agentId, sidecar.conversationId, sidecar.lineageId);
258332
- const temporary = `${destination}.${process.pid}.${sidecarWriterInstanceId}.${randomUUID46()}.tmp`;
258369
+ const temporary = `${destination}.${process.pid}.${sidecarWriterInstanceId}.${randomUUID47()}.tmp`;
258333
258370
  try {
258334
258371
  writeFileSync32(temporary, JSON.stringify(sidecar), {
258335
258372
  mode: 384,
@@ -258365,7 +258402,7 @@ function createRecoveryLineageSidecarAccess(params) {
258365
258402
  });
258366
258403
  const retired = {
258367
258404
  ...previous,
258368
- revision: randomUUID46(),
258405
+ revision: randomUUID47(),
258369
258406
  state: "retired",
258370
258407
  retiredInterruptedRevision: previous.sourceMainRevision,
258371
258408
  retiredAuthorityRevision: previous.pendingAuthorityRevision ?? previous.revision,
@@ -258379,7 +258416,7 @@ function createRecoveryLineageSidecarAccess(params) {
258379
258416
  if (current?.state !== "retired" || current.revision !== retired.revision)
258380
258417
  return current ?? retired;
258381
258418
  const compact2 = {
258382
- revision: randomUUID46(),
258419
+ revision: randomUUID47(),
258383
258420
  agentId: current.agentId,
258384
258421
  conversationId: current.conversationId,
258385
258422
  lineageId: current.lineageId,
@@ -258405,7 +258442,7 @@ function createRecoveryLineageSidecarAccess(params) {
258405
258442
  return current;
258406
258443
  }
258407
258444
  const compact2 = {
258408
- revision: randomUUID46(),
258445
+ revision: randomUUID47(),
258409
258446
  agentId: current.agentId,
258410
258447
  conversationId: current.conversationId,
258411
258448
  lineageId: current.lineageId,
@@ -258453,7 +258490,7 @@ function createRecoveryLineageSidecarAccess(params) {
258453
258490
  exactResults.push(effect.result);
258454
258491
  }
258455
258492
  return {
258456
- revision: randomUUID46(),
258493
+ revision: randomUUID47(),
258457
258494
  agentId: current.agentId,
258458
258495
  conversationId: current.conversationId,
258459
258496
  lineageId: marker2.lineageId,
@@ -258670,11 +258707,11 @@ var init_recovery_lineage_sidecar = __esm(async () => {
258670
258707
  init_rename_sync_with_retry();
258671
258708
  init_durable_file_lock();
258672
258709
  await init_interrupted_turn_schema();
258673
- sidecarWriterInstanceId = randomUUID46();
258710
+ sidecarWriterInstanceId = randomUUID47();
258674
258711
  });
258675
258712
 
258676
258713
  // src/websocket/listener/interrupted-turn-record.ts
258677
- import { randomUUID as randomUUID47 } from "node:crypto";
258714
+ import { randomUUID as randomUUID48 } from "node:crypto";
258678
258715
  import {
258679
258716
  existsSync as existsSync50,
258680
258717
  mkdirSync as mkdirSync37,
@@ -258687,7 +258724,7 @@ import { join as join75 } from "node:path";
258687
258724
  function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(), dependencies4 = {}) {
258688
258725
  const sync = dependencies4.fsyncDirectory ?? fsyncInterruptedTurnDirectory;
258689
258726
  function persist(destination, record6) {
258690
- const temporary = `${destination}.${randomUUID47()}.tmp`;
258727
+ const temporary = `${destination}.${randomUUID48()}.tmp`;
258691
258728
  try {
258692
258729
  writeInterruptedTurnRecordFile(temporary, destination, directory, record6, sync);
258693
258730
  } finally {
@@ -258697,7 +258734,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
258697
258734
  function path33(agentId, conversationId) {
258698
258735
  return join75(directory, `${encodeURIComponent(agentId)}_${encodeURIComponent(conversationId)}.json`);
258699
258736
  }
258700
- function readRecord2(file) {
258737
+ function readRecordOrThrow(file) {
258701
258738
  try {
258702
258739
  const value = JSON.parse(readFileSync41(file, "utf8"));
258703
258740
  if (!isInterruptedTurnRecord(value, file, path33)) {
@@ -258705,9 +258742,16 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
258705
258742
  }
258706
258743
  return value;
258707
258744
  } catch (error5) {
258708
- if (error5.code !== "ENOENT") {
258709
- debugWarn("recovery", "Ignoring unreadable interrupted-turn record", file, error5);
258710
- }
258745
+ if (error5.code === "ENOENT")
258746
+ return null;
258747
+ throw error5;
258748
+ }
258749
+ }
258750
+ function readRecord2(file) {
258751
+ try {
258752
+ return readRecordOrThrow(file);
258753
+ } catch (error5) {
258754
+ debugWarn("recovery", "Ignoring unreadable interrupted-turn record", file, error5);
258711
258755
  return null;
258712
258756
  }
258713
258757
  }
@@ -258798,6 +258842,10 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
258798
258842
  const current = readRecord2(path33(agentId, conversationId));
258799
258843
  return current ? readMainView(current) : null;
258800
258844
  },
258845
+ readOrThrow(agentId, conversationId) {
258846
+ const current = readRecordOrThrow(path33(agentId, conversationId));
258847
+ return current ? readMainView(current) : null;
258848
+ },
258801
258849
  readRecoveryView(agentId, conversationId, lineageId) {
258802
258850
  const current = readRecord2(path33(agentId, conversationId));
258803
258851
  if (current?.recoveryClaimCompletion?.lineageId !== lineageId)
@@ -258851,24 +258899,32 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
258851
258899
  if (expectedRevision !== undefined && (current?.revision ?? null) !== expectedRevision) {
258852
258900
  throw new Error("Interrupted-turn revision changed");
258853
258901
  }
258854
- const revision = randomUUID47();
258855
- const written = {
258856
- ...record6,
258857
- revision,
258858
- ...record6.teleport ? {
258859
- teleport: {
258860
- ...record6.teleport,
258861
- intentRevision: record6.teleport.intentRevision ?? revision,
258862
- readyRevision: record6.teleport.ready ? record6.teleport.readyRevision ?? revision : record6.teleport.readyRevision
258863
- }
258864
- } : {}
258865
- };
258902
+ const written = stampInterruptedTurnRevision(record6);
258866
258903
  persist(destination, written);
258867
258904
  return written;
258868
258905
  } finally {
258869
258906
  release();
258870
258907
  }
258871
258908
  },
258909
+ writeWithRecoveryAuthority(params) {
258910
+ let written = null;
258911
+ const guarded = recoveryAuthority.withAuthority({
258912
+ agentId: params.record.agentId,
258913
+ conversationId: params.record.conversationId,
258914
+ lineageId: params.lineageId,
258915
+ expectedRevision: params.expectedAuthorityRevision,
258916
+ action: () => {
258917
+ const destination = path33(params.record.agentId, params.record.conversationId);
258918
+ const current = readRecord2(destination);
258919
+ if (current?.revision !== params.expectedRevision)
258920
+ return false;
258921
+ written = stampInterruptedTurnRevision(params.record);
258922
+ persist(destination, written);
258923
+ return true;
258924
+ }
258925
+ });
258926
+ return guarded ? written : null;
258927
+ },
258872
258928
  writeRecoveryLineageSnapshot(params) {
258873
258929
  const destination = path33(params.agentId, params.conversationId);
258874
258930
  const release = acquireDurableFileLock(destination, {
@@ -258897,7 +258953,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
258897
258953
  const exactResultIds = new Set((previous.exactResults ?? []).map((result3) => result3.tool_call_id));
258898
258954
  const written = {
258899
258955
  ...previous,
258900
- revision: randomUUID47(),
258956
+ revision: randomUUID48(),
258901
258957
  toolCallIds,
258902
258958
  results,
258903
258959
  ...params.update.runId !== undefined ? { runId: params.update.runId } : {},
@@ -258953,13 +259009,13 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
258953
259009
  exactResults.push(params.result);
258954
259010
  writeSidecar({
258955
259011
  ...previous,
258956
- revision: randomUUID47(),
259012
+ revision: randomUUID48(),
258957
259013
  exactResults,
258958
259014
  unstartedToolCallIds: previous.unstartedToolCallIds?.filter((toolCallId) => toolCallId !== params.result.tool_call_id)
258959
259015
  });
258960
259016
  return { revision: current.revision, independentSuccessor: true };
258961
259017
  }
258962
- const revision = randomUUID47();
259018
+ const revision = randomUUID48();
258963
259019
  const written = {
258964
259020
  ...current,
258965
259021
  revision,
@@ -259000,7 +259056,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
259000
259056
  const pending2 = previous.state === "pending" ? previous : {
259001
259057
  ...previous,
259002
259058
  pendingAuthorityRevision: previous.revision,
259003
- revision: randomUUID47(),
259059
+ revision: randomUUID48(),
259004
259060
  state: "pending"
259005
259061
  };
259006
259062
  if (pending2 !== previous)
@@ -259014,7 +259070,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
259014
259070
  return current;
259015
259071
  const written = {
259016
259072
  ...current,
259017
- revision: randomUUID47(),
259073
+ revision: randomUUID48(),
259018
259074
  recoveryClaimCompletion: {
259019
259075
  ...marker2,
259020
259076
  state: "pending",
@@ -259079,7 +259135,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
259079
259135
  ]);
259080
259136
  const preserved = {
259081
259137
  ...current,
259082
- revision: randomUUID47(),
259138
+ revision: randomUUID48(),
259083
259139
  recoveryClaimCompletion: undefined,
259084
259140
  toolCallIds: current.toolCallIds.filter((toolCallId) => !retiredToolCallIds.has(toolCallId)),
259085
259141
  results: current.results.filter((result3) => !retiredToolCallIds.has(result3.tool_call_id)),
@@ -259175,7 +259231,7 @@ function recordListenerWork(runtime, update3, phase, expectedRevision, recoveryL
259175
259231
  unstartedToolCallIds: previous?.unstartedToolCallIds,
259176
259232
  results: previous?.results ?? [],
259177
259233
  settledRecoveryEffects: previous?.settledRecoveryEffects,
259178
- requestOtid: previous?.requestOtid ?? randomUUID47(),
259234
+ requestOtid: previous?.requestOtid ?? randomUUID48(),
259179
259235
  actingUserId: previous?.actingUserId,
259180
259236
  recoveryClaimCompletion: inheritedCompletion,
259181
259237
  durableInputIdentities: previous?.durableInputIdentities,
@@ -259266,6 +259322,7 @@ var init_interrupted_turn_record = __esm(async () => {
259266
259322
  init_debug();
259267
259323
  init_durable_file_lock();
259268
259324
  init_interrupted_turn_input_ownership();
259325
+ init_interrupted_turn_revision();
259269
259326
  init_interrupted_turn_storage();
259270
259327
  init_recorded_tool_results();
259271
259328
  init_recorded_tool_results();
@@ -260890,6 +260947,9 @@ var init_queue_runtime = __esm(() => {
260890
260947
  });
260891
260948
 
260892
260949
  // src/websocket/listener/input-disposition-retention.ts
260950
+ function buildPreparedTerminalAliasIndex(entries2) {
260951
+ return new Set([...entries2].flatMap((entry) => entry.preparedTerminal?.inputDispositionKeys ?? []));
260952
+ }
260893
260953
  function legacyAuthorityReferenceKey(runtimeKey, recoveryLineageId, interruptedRevision) {
260894
260954
  return JSON.stringify([
260895
260955
  runtimeKey,
@@ -261122,7 +261182,7 @@ var init_input_disposition_validation = __esm(async () => {
261122
261182
  });
261123
261183
 
261124
261184
  // src/websocket/listener/input-disposition.ts
261125
- import { randomUUID as randomUUID48 } from "node:crypto";
261185
+ import { randomUUID as randomUUID49 } from "node:crypto";
261126
261186
  import {
261127
261187
  chmodSync as chmodSync10,
261128
261188
  closeSync as closeSync9,
@@ -261244,7 +261304,7 @@ function validateDurableStore(value) {
261244
261304
  }
261245
261305
  if (rawEntry.preparedTerminal !== undefined) {
261246
261306
  const prepared = rawEntry.preparedTerminal;
261247
- if (!isRecord12(prepared) || prepared.preparedAt !== undefined && (typeof prepared.preparedAt !== "number" || !Number.isFinite(prepared.preparedAt)) || prepared.preparationSequence !== undefined && (!Number.isSafeInteger(prepared.preparationSequence) || prepared.preparationSequence < 0) || prepared.publicationClaimed !== undefined && prepared.publicationClaimed !== true || prepared.persistWithoutConsumers !== undefined && prepared.persistWithoutConsumers !== true || !isRecord12(prepared.scope) || prepared.scope.agentId !== null && typeof prepared.scope.agentId !== "string" || typeof prepared.scope.conversationId !== "string" || getConversationRuntimeKey(prepared.scope.agentId, prepared.scope.conversationId) !== runtimeKey || !isRecord12(prepared.message) || prepared.message.type !== "turn_finished" || typeof prepared.message.turn_id !== "string" || typeof prepared.message.stop_reason !== "string" || prepared.message.terminal_consumer_ids !== undefined && (!Array.isArray(prepared.message.terminal_consumer_ids) || !prepared.message.terminal_consumer_ids.every((id2) => typeof id2 === "string")) || prepared.message.run_id !== undefined && typeof prepared.message.run_id !== "string" || prepared.message.error !== undefined && typeof prepared.message.error !== "string" || !isRecord12(prepared.owner) || prepared.owner.connectionId !== null && typeof prepared.owner.connectionId !== "string" || typeof prepared.owner.canRotate !== "boolean" || prepared.owner.lineageId !== null && typeof prepared.owner.lineageId !== "string" || prepared.owner.terminalIdentity !== undefined && typeof prepared.owner.terminalIdentity !== "string" || prepared.owner.interruptedRevision !== undefined && typeof prepared.owner.interruptedRevision !== "string" || prepared.owner.recoveryLineageId !== undefined && typeof prepared.owner.recoveryLineageId !== "string" || prepared.owner.interruptedAuthorityRevision !== undefined && typeof prepared.owner.interruptedAuthorityRevision !== "string" || prepared.owner.preparationSequence !== undefined && (!Number.isSafeInteger(prepared.owner.preparationSequence) || prepared.owner.preparationSequence < 0) || rawEntry.queuedInput !== undefined || rawEntry.replayCompleted !== true) {
261307
+ if (!isRecord12(prepared) || prepared.preparedAt !== undefined && (typeof prepared.preparedAt !== "number" || !Number.isFinite(prepared.preparedAt)) || prepared.preparationSequence !== undefined && (!Number.isSafeInteger(prepared.preparationSequence) || prepared.preparationSequence < 0) || prepared.inputDispositionKeys !== undefined && (!Array.isArray(prepared.inputDispositionKeys) || prepared.inputDispositionKeys.length > MAX_ACCEPTED_INPUT_DISPOSITIONS_PER_SCOPE || !prepared.inputDispositionKeys.every((key5) => typeof key5 === "string")) || prepared.publicationClaimed !== undefined && prepared.publicationClaimed !== true || prepared.persistWithoutConsumers !== undefined && prepared.persistWithoutConsumers !== true || prepared.suppressConsumerPublication !== undefined && prepared.suppressConsumerPublication !== true || !isRecord12(prepared.scope) || prepared.scope.agentId !== null && typeof prepared.scope.agentId !== "string" || typeof prepared.scope.conversationId !== "string" || getConversationRuntimeKey(prepared.scope.agentId, prepared.scope.conversationId) !== runtimeKey || !isRecord12(prepared.message) || prepared.message.type !== "turn_finished" || typeof prepared.message.turn_id !== "string" || typeof prepared.message.stop_reason !== "string" || prepared.message.terminal_consumer_ids !== undefined && (!Array.isArray(prepared.message.terminal_consumer_ids) || !prepared.message.terminal_consumer_ids.every((id2) => typeof id2 === "string")) || prepared.message.run_id !== undefined && typeof prepared.message.run_id !== "string" || prepared.message.error !== undefined && typeof prepared.message.error !== "string" || !isRecord12(prepared.owner) || prepared.owner.connectionId !== null && typeof prepared.owner.connectionId !== "string" || typeof prepared.owner.canRotate !== "boolean" || prepared.owner.lineageId !== null && typeof prepared.owner.lineageId !== "string" || prepared.owner.terminalIdentity !== undefined && typeof prepared.owner.terminalIdentity !== "string" || prepared.owner.interruptedRevision !== undefined && typeof prepared.owner.interruptedRevision !== "string" || prepared.owner.recoveryLineageId !== undefined && typeof prepared.owner.recoveryLineageId !== "string" || prepared.owner.interruptedAuthorityRevision !== undefined && typeof prepared.owner.interruptedAuthorityRevision !== "string" || prepared.owner.preparationSequence !== undefined && (!Number.isSafeInteger(prepared.owner.preparationSequence) || prepared.owner.preparationSequence < 0) || rawEntry.queuedInput !== undefined || rawEntry.replayCompleted !== true) {
261248
261308
  throw new Error("Prepared input terminal is invalid");
261249
261309
  }
261250
261310
  }
@@ -261288,7 +261348,7 @@ function writeDurableStore(path33, store3) {
261288
261348
  if (Buffer.byteLength(serialized) > MAX_INPUT_DISPOSITION_STORE_BYTES) {
261289
261349
  throw new Error("Accepted-input disposition store exceeds its size limit");
261290
261350
  }
261291
- const temporaryPath = `${path33}.${process.pid}.${randomUUID48()}.tmp`;
261351
+ const temporaryPath = `${path33}.${process.pid}.${randomUUID49()}.tmp`;
261292
261352
  try {
261293
261353
  writeFileSync34(temporaryPath, serialized, { mode: 384, flag: "wx" });
261294
261354
  const fd = openSync9(temporaryPath, "r+");
@@ -261321,9 +261381,10 @@ function pruneDurableStore(store3, now2) {
261321
261381
  let changed = false;
261322
261382
  changed = settleExpiredQuarantineJournals(Object.entries(store3.entries), now2, (key4) => delete store3.entries[key4]) || changed;
261323
261383
  const references = buildLegacyAuthorityReferenceIndex(Object.values(store3.entries));
261384
+ const preparedAliasKeys = buildPreparedTerminalAliasIndex(Object.values(store3.entries));
261324
261385
  for (const [key4, entry] of Object.entries(store3.entries)) {
261325
261386
  if (entry.expiresAt <= now2) {
261326
- if (shouldRetainDisposition(entry, () => references)) {
261387
+ if (preparedAliasKeys.has(key4) || shouldRetainDisposition(entry, () => references)) {
261327
261388
  entry.expiresAt = now2 + ACCEPTED_INPUT_DISPOSITION_TTL_MS;
261328
261389
  } else {
261329
261390
  delete store3.entries[key4];
@@ -261716,7 +261777,7 @@ var init_input_disposition = __esm(async () => {
261716
261777
  });
261717
261778
 
261718
261779
  // src/websocket/listener/turn-finished-replay.ts
261719
- import { randomUUID as randomUUID49 } from "node:crypto";
261780
+ import { randomUUID as randomUUID50 } from "node:crypto";
261720
261781
  import {
261721
261782
  closeSync as closeSync10,
261722
261783
  fsyncSync as fsyncSync6,
@@ -261760,6 +261821,23 @@ function terminalAuthorityStatus(runtime, terminal, terminals, interruptedStore
261760
261821
  return "unknown";
261761
261822
  }
261762
261823
  }
261824
+ function isInterruptedTerminalAuthorityCurrent(runtime, authority) {
261825
+ if (!authority.recoveryLineageId)
261826
+ return "current";
261827
+ if (!runtime.agentId)
261828
+ return "unknown";
261829
+ try {
261830
+ const store3 = createInterruptedTurnStore();
261831
+ const snapshot2 = store3.readRecoverySnapshot(runtime.agentId, runtime.conversationId, authority.recoveryLineageId);
261832
+ if (snapshot2) {
261833
+ return snapshot2.record.revision === (authority.recoveryAuthorityBaseRevision ?? authority.interruptedRevision) && snapshot2.revisionToken === authority.authorityRevision ? "current" : snapshot2.record.recoveryClaimCompletion?.state === "pending" ? "unknown" : "stale";
261834
+ }
261835
+ const retired = store3.readRetiredRecoveryAuthority(runtime.agentId, runtime.conversationId, authority.recoveryLineageId);
261836
+ return retired?.interruptedRevision === (authority.recoveryAuthorityBaseRevision ?? authority.interruptedRevision) && retired.authorityRevision === authority.authorityRevision ? "current" : retired ? "stale" : "unknown";
261837
+ } catch {
261838
+ return "unknown";
261839
+ }
261840
+ }
261763
261841
  function defaultTurnFinishedDirectory() {
261764
261842
  let serverUrl;
261765
261843
  try {
@@ -261794,7 +261872,7 @@ function fsyncDirectory2(directory) {
261794
261872
  }
261795
261873
  }
261796
261874
  function createTurnFinishedStore(directory = defaultTurnFinishedDirectory(), options = {}) {
261797
- const claimantToken = randomUUID49();
261875
+ const claimantToken = randomUUID50();
261798
261876
  const path33 = (agentId, conversationId) => join77(directory, `${encodeTurnFinishedScope(agentId, conversationId)}.json`);
261799
261877
  const readRecord2 = (agentId, conversationId) => {
261800
261878
  try {
@@ -261812,7 +261890,7 @@ function createTurnFinishedStore(directory = defaultTurnFinishedDirectory(), opt
261812
261890
  const write2 = (record6) => {
261813
261891
  mkdirSync39(directory, { recursive: true, mode: 448 });
261814
261892
  const destination = path33(record6.agentId, record6.conversationId);
261815
- const temporary = `${destination}.${randomUUID49()}.tmp`;
261893
+ const temporary = `${destination}.${randomUUID50()}.tmp`;
261816
261894
  try {
261817
261895
  writeFileSync35(temporary, JSON.stringify(record6), {
261818
261896
  mode: 384,
@@ -261928,7 +262006,7 @@ function createTurnFinishedStore(directory = defaultTurnFinishedDirectory(), opt
261928
262006
  }
261929
262007
  }
261930
262008
  const terminal = {
261931
- id: `turn_finished:${randomUUID49()}`,
262009
+ id: `turn_finished:${randomUUID50()}`,
261932
262010
  createdAt: Date.now(),
261933
262011
  message: message2,
261934
262012
  owner,
@@ -262020,7 +262098,7 @@ function getTurnFinishedOwner(runtime, interruptedRevision) {
262020
262098
  connectionId,
262021
262099
  canRotate: connection?.options.connectionIdCanResume === false,
262022
262100
  lineageId: connection?.startupOwner.lineageId ?? null,
262023
- terminalIdentity: randomUUID49(),
262101
+ terminalIdentity: randomUUID50(),
262024
262102
  ...interruptedRevision ? { interruptedRevision } : {}
262025
262103
  };
262026
262104
  }
@@ -262225,12 +262303,33 @@ function recordCompletedTerminalAuthority(entry, owner, publicationClaimed = fal
262225
262303
  function terminalAuthorityMatches(candidate, terminal) {
262226
262304
  return Boolean(terminal.owner.recoveryLineageId && terminal.owner.interruptedRevision && candidate.scope.agentId === terminal.scope.agentId && candidate.scope.conversationId === terminal.scope.conversationId && candidate.owner.recoveryLineageId === terminal.owner.recoveryLineageId && candidate.owner.interruptedRevision === terminal.owner.interruptedRevision);
262227
262305
  }
262228
- function prepareInputTerminal(runtime, identities, terminal) {
262229
- if (identities.length === 0)
262230
- return true;
262306
+ function terminalMessageWithoutConsumers(message2) {
262307
+ const { terminal_consumer_ids: _4, ...withoutConsumers } = message2;
262308
+ return withoutConsumers;
262309
+ }
262310
+ function prepareInputTerminal(runtime, identities, terminal, options) {
262311
+ if (identities.length === 0) {
262312
+ return options?.onPrepared?.(structuredClone(terminal)) !== false;
262313
+ }
262231
262314
  const ledger = getLedger(runtime.listener);
262232
262315
  const keys3 = identityKeys(runtime, identities);
262233
- const preparedBase = structuredClone(terminal);
262316
+ const mergeTerminalConsumers = (entries2) => {
262317
+ if (options?.mergeTerminalConsumerIds !== false) {
262318
+ const consumers = new Set(terminal.message.terminal_consumer_ids ?? []);
262319
+ for (const key4 of keys3) {
262320
+ for (const consumer of entries2[key4]?.queuedInput?.incoming.terminalConsumerIds ?? []) {
262321
+ consumers.add(consumer);
262322
+ }
262323
+ }
262324
+ if (consumers.size > 0) {
262325
+ terminal.message.terminal_consumer_ids = [...consumers];
262326
+ }
262327
+ }
262328
+ if (options?.onPrepared?.(terminal) === false) {
262329
+ throw new Error("Prepared terminal side effect was rejected");
262330
+ }
262331
+ return structuredClone(terminal);
262332
+ };
262234
262333
  if (ledger.persistentPath) {
262235
262334
  try {
262236
262335
  return durableTransaction(ledger.persistentPath, (store3) => {
@@ -262246,20 +262345,28 @@ function prepareInputTerminal(runtime, identities, terminal) {
262246
262345
  }
262247
262346
  }
262248
262347
  const preparationSequence2 = terminal.preparationSequence ?? ++store3.nextGeneration;
262348
+ const preparedBase2 = mergeTerminalConsumers(store3.entries);
262249
262349
  const prepared2 = {
262250
- ...preparedBase,
262350
+ ...preparedBase2,
262351
+ inputDispositionKeys: keys3,
262251
262352
  preparedAt: terminal.preparedAt ?? Date.now(),
262252
262353
  preparationSequence: preparationSequence2,
262253
- owner: { ...preparedBase.owner, preparationSequence: preparationSequence2 }
262354
+ owner: { ...preparedBase2.owner, preparationSequence: preparationSequence2 }
262254
262355
  };
262255
262356
  let changed = false;
262357
+ let storedCanonicalTerminal2 = false;
262256
262358
  for (const key4 of keys3) {
262257
262359
  const entry = store3.entries[key4];
262258
262360
  if (!entry)
262259
262361
  continue;
262260
262362
  delete entry.queuedInput;
262261
262363
  entry.replayCompleted = true;
262262
- entry.preparedTerminal = prepared2;
262364
+ if (!storedCanonicalTerminal2) {
262365
+ entry.preparedTerminal = prepared2;
262366
+ storedCanonicalTerminal2 = true;
262367
+ } else {
262368
+ delete entry.preparedTerminal;
262369
+ }
262263
262370
  changed = true;
262264
262371
  }
262265
262372
  syncMemoryFromDurable(ledger, store3);
@@ -262279,19 +262386,27 @@ function prepareInputTerminal(runtime, identities, terminal) {
262279
262386
  }
262280
262387
  }
262281
262388
  const preparationSequence = terminal.preparationSequence ?? ++ledger.nextGeneration;
262389
+ const preparedBase = mergeTerminalConsumers(Object.fromEntries(ledger.entries.entries()));
262282
262390
  const prepared = {
262283
262391
  ...preparedBase,
262392
+ inputDispositionKeys: keys3,
262284
262393
  preparedAt: terminal.preparedAt ?? Date.now(),
262285
262394
  preparationSequence,
262286
262395
  owner: { ...preparedBase.owner, preparationSequence }
262287
262396
  };
262397
+ let storedCanonicalTerminal = false;
262288
262398
  for (const key4 of keys3) {
262289
262399
  const entry = ledger.entries.get(key4);
262290
262400
  if (!entry)
262291
262401
  continue;
262292
262402
  delete entry.queuedInput;
262293
262403
  entry.replayCompleted = true;
262294
- entry.preparedTerminal = prepared;
262404
+ if (!storedCanonicalTerminal) {
262405
+ entry.preparedTerminal = prepared;
262406
+ storedCanonicalTerminal = true;
262407
+ } else {
262408
+ delete entry.preparedTerminal;
262409
+ }
262295
262410
  }
262296
262411
  return true;
262297
262412
  }
@@ -262303,11 +262418,14 @@ function completePreparedInputTerminal(runtime, identities, turnId) {
262303
262418
  if (ledger.persistentPath) {
262304
262419
  try {
262305
262420
  return durableTransaction(ledger.persistentPath, (store3) => {
262421
+ const prepared2 = keys3.map((key4) => store3.entries[key4]?.preparedTerminal).find((terminal) => terminal?.message.turn_id === turnId);
262306
262422
  let changed = false;
262307
- for (const key4 of keys3) {
262308
- const entry = store3.entries[key4];
262309
- if (entry?.preparedTerminal?.message.turn_id === turnId) {
262310
- recordCompletedTerminalAuthority(entry, entry.preparedTerminal.owner, entry.preparedTerminal.publicationClaimed);
262423
+ if (prepared2) {
262424
+ for (const key4 of keys3) {
262425
+ const entry = store3.entries[key4];
262426
+ if (!entry)
262427
+ continue;
262428
+ recordCompletedTerminalAuthority(entry, prepared2.owner, prepared2.publicationClaimed);
262311
262429
  delete entry.preparedTerminal;
262312
262430
  changed = true;
262313
262431
  }
@@ -262319,10 +262437,13 @@ function completePreparedInputTerminal(runtime, identities, turnId) {
262319
262437
  return false;
262320
262438
  }
262321
262439
  }
262322
- for (const key4 of keys3) {
262323
- const entry = ledger.entries.get(key4);
262324
- if (entry?.preparedTerminal?.message.turn_id === turnId) {
262325
- recordCompletedTerminalAuthority(entry, entry.preparedTerminal.owner, entry.preparedTerminal.publicationClaimed);
262440
+ const prepared = keys3.map((key4) => ledger.entries.get(key4)?.preparedTerminal).find((terminal) => terminal?.message.turn_id === turnId);
262441
+ if (prepared) {
262442
+ for (const key4 of keys3) {
262443
+ const entry = ledger.entries.get(key4);
262444
+ if (!entry)
262445
+ continue;
262446
+ recordCompletedTerminalAuthority(entry, prepared.owner, prepared.publicationClaimed);
262326
262447
  delete entry.preparedTerminal;
262327
262448
  }
262328
262449
  }
@@ -262360,6 +262481,7 @@ function loadPreparedInputTerminals(listener) {
262360
262481
  if (prepared) {
262361
262482
  const ordered = {
262362
262483
  ...prepared,
262484
+ message: prepared.suppressConsumerPublication ? terminalMessageWithoutConsumers(prepared.message) : prepared.message,
262363
262485
  preparationSequence: prepared.preparationSequence ?? entry.generation,
262364
262486
  owner: {
262365
262487
  ...prepared.owner,
@@ -262429,7 +262551,10 @@ function loadPreparedInputTerminals(listener) {
262429
262551
  }
262430
262552
  function preparedTerminalWithoutClaim(candidate) {
262431
262553
  const { publicationClaimed: _4, ...durable } = candidate;
262432
- return durable;
262554
+ return {
262555
+ ...durable,
262556
+ message: durable.suppressConsumerPublication ? terminalMessageWithoutConsumers(durable.message) : durable.message
262557
+ };
262433
262558
  }
262434
262559
  function completedAuthorityKey(authority) {
262435
262560
  return JSON.stringify([
@@ -262518,7 +262643,7 @@ function publishPreparedInputTerminalIfCurrent(listener, terminal, publish, vali
262518
262643
  const ledger = getLedger(listener);
262519
262644
  const expected = preparedTerminalWithoutClaim(terminal);
262520
262645
  const publishAndRetire = (entries2) => {
262521
- const values4 = [...entries2];
262646
+ const values4 = [...entries2.values()];
262522
262647
  const quarantines = buildLegacyAuthorityQuarantineIndex(values4);
262523
262648
  const matches3 = values4.filter((entry) => !preparedTerminalMatchesLegacyAuthorityIndex(entry, quarantines) && entry.preparedTerminal?.publicationClaimed === true && isDeepStrictEqual(preparedTerminalWithoutClaim(entry.preparedTerminal), expected));
262524
262649
  if (matches3.length === 0)
@@ -262531,20 +262656,23 @@ function publishPreparedInputTerminalIfCurrent(listener, terminal, publish, vali
262531
262656
  const prepared = entry.preparedTerminal;
262532
262657
  return prepared !== undefined && (matches3.includes(entry) || terminalAuthorityMatches(prepared, winner));
262533
262658
  });
262534
- for (const entry of resolvedEntries) {
262535
- const prepared = entry.preparedTerminal;
262536
- if (!prepared)
262537
- continue;
262659
+ const completedEntries = new Set(resolvedEntries);
262660
+ for (const key4 of winner.inputDispositionKeys ?? []) {
262661
+ const entry = entries2.get(key4);
262662
+ if (entry)
262663
+ completedEntries.add(entry);
262664
+ }
262665
+ for (const entry of completedEntries) {
262538
262666
  recordCompletedTerminalAuthority(entry, winner.owner, winner.publicationClaimed);
262539
262667
  delete entry.preparedTerminal;
262540
262668
  }
262541
262669
  return true;
262542
262670
  };
262543
262671
  if (!ledger.persistentPath) {
262544
- return publishAndRetire(ledger.entries.values());
262672
+ return publishAndRetire(ledger.entries);
262545
262673
  }
262546
262674
  return durableTransaction(ledger.persistentPath, (store3) => {
262547
- const result3 = publishAndRetire(Object.values(store3.entries));
262675
+ const result3 = publishAndRetire(new Map(Object.entries(store3.entries)));
262548
262676
  syncMemoryFromDurable(ledger, store3);
262549
262677
  return { result: result3, changed: result3 };
262550
262678
  });
@@ -262650,7 +262778,7 @@ function hasPreparedInputTerminalRevision(listener, scope, interruptedRevision)
262650
262778
  return loadPreparedInputTerminals(listener).some((prepared) => prepared.scope.agentId === scope.agentId && prepared.scope.conversationId === scope.conversationId && prepared.owner.interruptedRevision === interruptedRevision);
262651
262779
  }
262652
262780
  function hasPreparedInputTerminalAuthority(listener, scope, authority) {
262653
- return loadPreparedInputTerminals(listener).some((prepared) => prepared.scope.agentId === scope.agentId && prepared.scope.conversationId === scope.conversationId && prepared.owner.interruptedRevision === authority.interruptedRevision && (prepared.owner.interruptedAuthorityRevision ?? prepared.owner.interruptedRevision) === authority.authorityRevision && prepared.owner.recoveryLineageId === authority.recoveryLineageId);
262781
+ return loadPreparedInputTerminals(listener).some((prepared) => prepared.scope.agentId === scope.agentId && prepared.scope.conversationId === scope.conversationId && prepared.owner.interruptedRevision === authority.interruptedRevision && (prepared.owner.interruptedAuthorityRevision ?? prepared.owner.interruptedRevision) === authority.authorityRevision && prepared.owner.recoveryLineageId === authority.recoveryLineageId && (authority.terminalIdentity === undefined || prepared.owner.terminalIdentity === authority.terminalIdentity) && (authority.preparationSequence === undefined || prepared.owner.preparationSequence === authority.preparationSequence));
262654
262782
  }
262655
262783
  function clearPreparedInputTerminal(listener, scope, turnId, terminalIdentity) {
262656
262784
  const ledger = getLedger(listener);
@@ -268085,7 +268213,7 @@ var init_auth3 = __esm(() => {
268085
268213
  });
268086
268214
 
268087
268215
  // src/websocket/listener/manual-instance-lock.ts
268088
- import { createHash as createHash15, randomUUID as randomUUID50 } from "node:crypto";
268216
+ import { createHash as createHash15, randomUUID as randomUUID51 } from "node:crypto";
268089
268217
  import { link as link4, mkdir as mkdir12, readFile as readFile23, rm as rm11, unlink as unlink3, writeFile as writeFile15 } from "node:fs/promises";
268090
268218
  import { uptime as uptime2 } from "node:os";
268091
268219
  import path33 from "node:path";
@@ -268148,7 +268276,7 @@ function parseLockRecord(raw2, expectedScopeHash) {
268148
268276
  }
268149
268277
  }
268150
268278
  async function publishInitializedFile(targetPath, contents) {
268151
- const candidatePath = path33.join(path33.dirname(targetPath), `.manual-listener-lock-${randomUUID50()}.candidate`);
268279
+ const candidatePath = path33.join(path33.dirname(targetPath), `.manual-listener-lock-${randomUUID51()}.candidate`);
268152
268280
  let publicationError;
268153
268281
  try {
268154
268282
  await writeFile15(candidatePath, contents, { flag: "wx" });
@@ -268225,7 +268353,7 @@ async function acquireManualListenerLock(scope, overrides = {}) {
268225
268353
  const deps = {
268226
268354
  lockRoot: getManualListenerLockRoot(),
268227
268355
  processId: process.pid,
268228
- ownerToken: randomUUID50(),
268356
+ ownerToken: randomUUID51(),
268229
268357
  isProcessAlive: defaultIsProcessAlive2,
268230
268358
  bootTimeMs: getDefaultBootTimeMs(),
268231
268359
  getProcessCommand,
@@ -444343,40 +444471,6 @@ var init_input_disposition_rollback = __esm(async () => {
444343
444471
  await init_input_disposition();
444344
444472
  });
444345
444473
 
444346
- // src/websocket/listener/input-terminal-evidence.ts
444347
- function hasCompletedInputTerminalRevision(listener, runtimeKey, identities, revision) {
444348
- if (identities.length === 0)
444349
- return false;
444350
- const ledger = getLedger(listener);
444351
- const keys3 = identities.map((identity2) => dispositionKey(runtimeKey, identity2));
444352
- const matches3 = (entries2) => keys3.every((key4) => entries2.get(key4)?.completedTerminalRevision === revision);
444353
- if (!ledger.persistentPath)
444354
- return matches3(ledger.entries);
444355
- return durableTransaction(ledger.persistentPath, (store3) => {
444356
- syncMemoryFromDurable(ledger, store3);
444357
- return { result: matches3(ledger.entries), changed: false };
444358
- });
444359
- }
444360
- function hasCompletedInputTerminalAuthority(listener, runtimeKey, identities, authority) {
444361
- if (identities.length === 0)
444362
- return false;
444363
- const ledger = getLedger(listener);
444364
- const keys3 = identities.map((identity2) => dispositionKey(runtimeKey, identity2));
444365
- const matches3 = (entries2) => keys3.every((key4) => {
444366
- const completed = entries2.get(key4)?.completedTerminalAuthority;
444367
- return completed?.interruptedRevision === authority.interruptedRevision && completed.authorityRevision === authority.authorityRevision && completed.recoveryLineageId === authority.recoveryLineageId;
444368
- });
444369
- if (!ledger.persistentPath)
444370
- return matches3(ledger.entries);
444371
- return durableTransaction(ledger.persistentPath, (store3) => {
444372
- syncMemoryFromDurable(ledger, store3);
444373
- return { result: matches3(ledger.entries), changed: false };
444374
- });
444375
- }
444376
- var init_input_terminal_evidence = __esm(async () => {
444377
- await init_input_disposition();
444378
- });
444379
-
444380
444474
  // src/websocket/listener/recoverable-notices.ts
444381
444475
  function getRecoverableStatusNoticeVisibility(kind) {
444382
444476
  switch (kind) {
@@ -444573,6 +444667,269 @@ var init_recoverable_notices = __esm(async () => {
444573
444667
  await init_protocol_outbound();
444574
444668
  });
444575
444669
 
444670
+ // src/websocket/listener/teleport-failed-ack.ts
444671
+ function emitTeleportFailedAck(params) {
444672
+ if (!params.command.request_id)
444673
+ return;
444674
+ const message2 = {
444675
+ type: "teleport_failed_ack",
444676
+ request_id: params.command.request_id,
444677
+ teleport_id: params.command.teleport_id,
444678
+ runtime: params.command.runtime,
444679
+ accepted: true
444680
+ };
444681
+ emitProtocolV2Message(params.socket, params.listener, message2, message2.runtime, toListenerConnection(params.connectionId));
444682
+ }
444683
+ var init_teleport_failed_ack = __esm(async () => {
444684
+ await __promiseAll([
444685
+ init_connection(),
444686
+ init_protocol_outbound()
444687
+ ]);
444688
+ });
444689
+
444690
+ // src/websocket/listener/input-terminal-evidence.ts
444691
+ function hasCompletedInputTerminalRevision(listener, runtimeKey, identities, revision) {
444692
+ if (identities.length === 0)
444693
+ return false;
444694
+ const ledger = getLedger(listener);
444695
+ const keys3 = identities.map((identity2) => dispositionKey(runtimeKey, identity2));
444696
+ const matches3 = (entries2) => keys3.every((key4) => entries2.get(key4)?.completedTerminalRevision === revision);
444697
+ if (!ledger.persistentPath)
444698
+ return matches3(ledger.entries);
444699
+ return durableTransaction(ledger.persistentPath, (store3) => {
444700
+ syncMemoryFromDurable(ledger, store3);
444701
+ return { result: matches3(ledger.entries), changed: false };
444702
+ });
444703
+ }
444704
+ function hasCompletedInputTerminalAuthority(listener, runtimeKey, identities, authority) {
444705
+ if (identities.length === 0)
444706
+ return false;
444707
+ const ledger = getLedger(listener);
444708
+ const keys3 = identities.map((identity2) => dispositionKey(runtimeKey, identity2));
444709
+ const matches3 = (entries2) => keys3.every((key4) => {
444710
+ const completed = entries2.get(key4)?.completedTerminalAuthority;
444711
+ return completed?.interruptedRevision === authority.interruptedRevision && completed.authorityRevision === authority.authorityRevision && completed.recoveryLineageId === authority.recoveryLineageId && (authority.terminalIdentity === undefined || completed.terminalIdentity === authority.terminalIdentity) && (authority.preparationSequence === undefined || completed.preparationSequence === authority.preparationSequence);
444712
+ });
444713
+ if (!ledger.persistentPath)
444714
+ return matches3(ledger.entries);
444715
+ return durableTransaction(ledger.persistentPath, (store3) => {
444716
+ syncMemoryFromDurable(ledger, store3);
444717
+ return { result: matches3(ledger.entries), changed: false };
444718
+ });
444719
+ }
444720
+ var init_input_terminal_evidence = __esm(async () => {
444721
+ await init_input_disposition();
444722
+ });
444723
+
444724
+ // src/websocket/listener/teleport-terminal-transfer.ts
444725
+ function terminalConsumersMatch(terminal, expected) {
444726
+ const actual = terminal.message.terminal_consumer_ids ?? [];
444727
+ const expectedSet = new Set(expected);
444728
+ return actual.length === expectedSet.size && actual.every((consumerId) => expectedSet.has(consumerId));
444729
+ }
444730
+ function classifyTeleportTerminal(runtime, pending2, record6, revision) {
444731
+ if (!revision)
444732
+ return "absent";
444733
+ try {
444734
+ const scope = {
444735
+ agentId: pending2.agentId,
444736
+ conversationId: pending2.conversationId
444737
+ };
444738
+ const authority = record6.teleport?.terminalAuthority;
444739
+ if (authority) {
444740
+ const status = isInterruptedTerminalAuthorityCurrent(runtime, authority);
444741
+ if (status === "unknown")
444742
+ return "ambiguous";
444743
+ if (status === "stale")
444744
+ return "absent";
444745
+ }
444746
+ if (authority ? hasPreparedInputTerminalAuthority(runtime.listener, scope, authority) : hasPreparedInputTerminalRevision(runtime.listener, scope, revision)) {
444747
+ return "present";
444748
+ }
444749
+ const identities = record6.durableInputIdentities ?? [];
444750
+ if (authority ? hasCompletedInputTerminalAuthority(runtime.listener, runtime.key, identities, authority) : hasCompletedInputTerminalRevision(runtime.listener, runtime.key, identities, revision)) {
444751
+ return "present";
444752
+ }
444753
+ const terminals = createTurnFinishedStore().readOrThrow(pending2.agentId, pending2.conversationId);
444754
+ return terminals?.terminals.some((terminal) => authority ? terminal.owner.interruptedRevision === authority.interruptedRevision && (terminal.owner.interruptedAuthorityRevision ?? terminal.owner.interruptedRevision) === authority.authorityRevision && terminal.owner.recoveryLineageId === authority.recoveryLineageId && terminal.owner.terminalIdentity === authority.terminalIdentity : terminal.owner.interruptedRevision === revision) ? "present" : "absent";
444755
+ } catch {
444756
+ return "ambiguous";
444757
+ }
444758
+ }
444759
+ function hasDurableTeleportTerminal(runtime, pending2, revision) {
444760
+ try {
444761
+ const record6 = createInterruptedTurnStore().readOrThrow(pending2.agentId, pending2.conversationId);
444762
+ return record6 ? classifyTeleportTerminal(runtime, pending2, record6, revision) !== "absent" : false;
444763
+ } catch {
444764
+ return true;
444765
+ }
444766
+ }
444767
+ function retainDurableTeleportTerminal(runtime, pending2, revision, error5) {
444768
+ if (!(error5 instanceof TeleportTerminalPreparedError) && (!revision || !hasDurableTeleportTerminal(runtime, pending2, revision))) {
444769
+ return false;
444770
+ }
444771
+ runtime.listener.scheduleRecordedRecovery?.();
444772
+ return true;
444773
+ }
444774
+ function retireTeleportTerminalProof(record6, committedRevision) {
444775
+ if (!committedRevision)
444776
+ return;
444777
+ const store3 = createTurnFinishedStore();
444778
+ const proof = store3.read(record6.agentId, record6.conversationId)?.terminals.find((terminal) => terminal.requiredConsumerIds.length === 0 && terminal.owner.interruptedRevision === committedRevision);
444779
+ if (proof)
444780
+ store3.remove(record6.agentId, record6.conversationId, proof.id);
444781
+ }
444782
+ function classifyPersistedTeleportTerminal(runtime, record6) {
444783
+ const pending2 = {
444784
+ teleportId: record6.teleport?.teleportId ?? "",
444785
+ connectionId: record6.teleport?.connectionId ?? "",
444786
+ agentId: record6.agentId,
444787
+ conversationId: record6.conversationId,
444788
+ requestedAt: 0,
444789
+ drainAcceptedInputs: false,
444790
+ activeTurn: record6.teleport?.activeTurn ?? false
444791
+ };
444792
+ const proof = classifyTeleportTerminal(runtime, pending2, record6, record6.teleport?.committedRevision ?? record6.teleport?.intentRevision ?? record6.revision);
444793
+ if (proof === "ambiguous")
444794
+ runtime.listener.scheduleRecordedRecovery?.();
444795
+ return proof;
444796
+ }
444797
+ function persistSuccessorTeleportReady(runtime, pending2, record6, committedRevision) {
444798
+ if (record6.teleport?.teleportId !== pending2.teleportId || classifyTeleportTerminal(runtime, pending2, record6, committedRevision) !== "present") {
444799
+ runtime.listener.scheduleRecordedRecovery?.();
444800
+ return;
444801
+ }
444802
+ try {
444803
+ const store3 = createInterruptedTurnStore();
444804
+ const readyRecord = {
444805
+ ...record6,
444806
+ teleport: {
444807
+ ...record6.teleport,
444808
+ ready: true,
444809
+ committedRevision,
444810
+ preserveSuccessorWork: true
444811
+ }
444812
+ };
444813
+ const authority = record6.teleport.terminalAuthority;
444814
+ return authority?.recoveryLineageId ? store3.writeWithRecoveryAuthority({
444815
+ record: readyRecord,
444816
+ expectedRevision: record6.revision ?? "",
444817
+ lineageId: authority.recoveryLineageId,
444818
+ expectedAuthorityRevision: authority.authorityRevision
444819
+ }) ?? undefined : store3.write(readyRecord, record6.revision);
444820
+ } catch {
444821
+ runtime.listener.scheduleRecordedRecovery?.();
444822
+ return;
444823
+ }
444824
+ }
444825
+ function journalTeleportIntent(runtime, pending2, expectedRevision, terminal) {
444826
+ const sidecarAuthority = terminal?.owner.recoveryLineageId && terminal.owner.interruptedAuthorityRevision && terminal.owner.interruptedAuthorityRevision !== terminal.owner.interruptedRevision;
444827
+ return recordListenerWork(runtime, {
444828
+ teleport: {
444829
+ teleportId: pending2.teleportId,
444830
+ connectionId: pending2.connectionId,
444831
+ connectionGeneration: runtime.listener.connectionGeneration ?? undefined,
444832
+ activeTurn: pending2.activeTurn,
444833
+ continuation: pending2.continuation,
444834
+ ...terminal ? {
444835
+ terminalAuthority: {
444836
+ interruptedRevision: "",
444837
+ authorityRevision: sidecarAuthority ? terminal.owner.interruptedAuthorityRevision ?? "" : "",
444838
+ ...terminal.owner.recoveryLineageId ? {
444839
+ recoveryLineageId: terminal.owner.recoveryLineageId,
444840
+ ...sidecarAuthority ? {
444841
+ recoveryAuthorityBaseRevision: terminal.owner.interruptedRevision
444842
+ } : {}
444843
+ } : {},
444844
+ ...terminal.owner.terminalIdentity ? { terminalIdentity: terminal.owner.terminalIdentity } : {},
444845
+ ...terminal.owner.preparationSequence !== undefined ? {
444846
+ preparationSequence: terminal.owner.preparationSequence
444847
+ } : {}
444848
+ }
444849
+ } : {},
444850
+ ready: false
444851
+ }
444852
+ }, "after_tool_execution", expectedRevision);
444853
+ }
444854
+ function journalTeleportIntentWithTerminalConsumers(runtime, pending2, terminal, expectedRevision) {
444855
+ const consumers = terminal.message.terminal_consumer_ids;
444856
+ pending2.continuation = {
444857
+ approvals: pending2.continuation?.approvals ?? [],
444858
+ ...consumers?.length ? { terminal_consumer_ids: [...new Set(consumers)] } : {}
444859
+ };
444860
+ return journalTeleportIntent(runtime, pending2, expectedRevision, terminal);
444861
+ }
444862
+ function commitActiveTeleportTerminalTransfer(params) {
444863
+ const fallback = () => {
444864
+ const fallbackRevision = params.onUnavailable(revision) ?? params.expectedInterruptedRevision;
444865
+ return {
444866
+ fallback: true,
444867
+ transition: params.commit({
444868
+ stopReason: params.stopReason,
444869
+ agentId: params.pending.agentId,
444870
+ conversationId: params.pending.conversationId,
444871
+ expectedInterruptedRevision: fallbackRevision
444872
+ })
444873
+ };
444874
+ };
444875
+ let revision;
444876
+ for (let attempt2 = 0;attempt2 <= 64; attempt2 += 1) {
444877
+ try {
444878
+ const transition2 = params.commit({
444879
+ stopReason: params.stopReason,
444880
+ agentId: params.pending.agentId,
444881
+ conversationId: params.pending.conversationId,
444882
+ persistTerminalWithoutConsumers: true,
444883
+ expectedInterruptedRevision: revision ?? params.expectedInterruptedRevision,
444884
+ teleportHandoff: true,
444885
+ onBeforePrepareInputTerminal: (terminal) => {
444886
+ revision = journalTeleportIntentWithTerminalConsumers(params.runtime, params.pending, terminal, revision ?? params.expectedInterruptedRevision);
444887
+ return revision ?? false;
444888
+ },
444889
+ validatePreparedInputTerminal: (terminal) => terminalConsumersMatch(terminal, params.pending.continuation?.terminal_consumer_ids ?? [])
444890
+ });
444891
+ if (!revision)
444892
+ return fallback();
444893
+ return { transition: transition2, revision };
444894
+ } catch (error5) {
444895
+ if (error5 instanceof TeleportIntentUnavailableError) {
444896
+ return fallback();
444897
+ }
444898
+ if (error5 instanceof TeleportTerminalConsumerRaceError && attempt2 < 64) {
444899
+ continue;
444900
+ }
444901
+ if (error5 instanceof TeleportTerminalConsumerRaceError)
444902
+ return fallback();
444903
+ if (revision && hasDurableTeleportTerminal(params.runtime, params.pending, revision)) {
444904
+ throw new TeleportTerminalPreparedError(error5);
444905
+ }
444906
+ params.onUnavailable(revision);
444907
+ throw error5;
444908
+ }
444909
+ }
444910
+ return fallback();
444911
+ }
444912
+ var TeleportTerminalConsumerRaceError, TeleportIntentUnavailableError, TeleportTerminalPreparedError;
444913
+ var init_teleport_terminal_transfer = __esm(async () => {
444914
+ await __promiseAll([
444915
+ init_input_terminal_evidence(),
444916
+ init_input_terminal_journal(),
444917
+ init_interrupted_turn_record(),
444918
+ init_turn_finished_replay()
444919
+ ]);
444920
+ TeleportTerminalConsumerRaceError = class TeleportTerminalConsumerRaceError extends Error {
444921
+ };
444922
+ TeleportIntentUnavailableError = class TeleportIntentUnavailableError extends Error {
444923
+ };
444924
+ TeleportTerminalPreparedError = class TeleportTerminalPreparedError extends Error {
444925
+ terminalCause;
444926
+ constructor(terminalCause) {
444927
+ super("Teleport terminal is durable and awaiting recovery");
444928
+ this.terminalCause = terminalCause;
444929
+ }
444930
+ };
444931
+ });
444932
+
444576
444933
  // src/websocket/listener/teleport.ts
444577
444934
  function expectInboundTeleport(runtime, teleportId) {
444578
444935
  runtime.expectedTeleportId = teleportId;
@@ -444641,29 +444998,11 @@ function persistedTeleportRecord(agentId, conversationId, teleportId) {
444641
444998
  const record6 = createInterruptedTurnStore().read(agentId, conversationId);
444642
444999
  return record6?.teleport?.teleportId === teleportId ? record6 : null;
444643
445000
  }
444644
- function persistedTeleportTerminalIsDurable(listener, record6) {
444645
- const revision = record6.revision;
444646
- if (!revision)
444647
- return false;
444648
- const scope = {
444649
- agentId: record6.agentId,
444650
- conversationId: record6.conversationId
444651
- };
444652
- return hasPreparedInputTerminalRevision(listener, scope, revision) || hasCompletedInputTerminalRevision(listener, getConversationRuntimeKey(record6.agentId, record6.conversationId), record6.durableInputIdentities ?? [], revision) || createTurnFinishedStore().read(record6.agentId, record6.conversationId)?.terminals.some((terminal) => terminal.owner.interruptedRevision === revision) === true;
444653
- }
444654
- function retireTeleportTerminalProof(record6, committedRevision) {
444655
- if (!committedRevision)
444656
- return;
444657
- const store3 = createTurnFinishedStore();
444658
- const proof = store3.read(record6.agentId, record6.conversationId)?.terminals.find((terminal) => terminal.requiredConsumerIds.length === 0 && terminal.owner.interruptedRevision === committedRevision);
444659
- if (proof)
444660
- store3.remove(record6.agentId, record6.conversationId, proof.id);
444661
- }
444662
- function authorizePersistedTeleportReady(listener, pending2, record6) {
445001
+ function authorizePersistedTeleportReady(runtime, pending2, record6) {
444663
445002
  const intent = record6.teleport;
444664
445003
  if (!intent || !record6.revision)
444665
445004
  return false;
444666
- if (!intent.ready && !persistedTeleportTerminalIsDurable(listener, record6)) {
445005
+ if (!intent.ready && classifyPersistedTeleportTerminal(runtime, record6) !== "present") {
444667
445006
  return false;
444668
445007
  }
444669
445008
  pending2.activeTurn = intent.activeTurn;
@@ -444673,6 +445012,9 @@ function authorizePersistedTeleportReady(listener, pending2, record6) {
444673
445012
  return true;
444674
445013
  }
444675
445014
  const store3 = createInterruptedTurnStore();
445015
+ const committedRevision = intent.committedRevision ?? intent.intentRevision;
445016
+ if (!committedRevision)
445017
+ return false;
444676
445018
  try {
444677
445019
  const readyRecord = store3.write({
444678
445020
  ...record6,
@@ -444680,28 +445022,17 @@ function authorizePersistedTeleportReady(listener, pending2, record6) {
444680
445022
  ...intent,
444681
445023
  connectionId: pending2.connectionId,
444682
445024
  ready: true,
444683
- committedRevision: record6.revision
445025
+ committedRevision,
445026
+ ...record6.revision !== committedRevision ? { preserveSuccessorWork: true } : {}
444684
445027
  }
444685
445028
  }, record6.revision);
444686
445029
  pending2.interruptedRevision = readyRecord.revision;
444687
- retireTeleportTerminalProof(readyRecord, record6.revision);
445030
+ retireTeleportTerminalProof(readyRecord, committedRevision);
444688
445031
  return true;
444689
445032
  } catch {
444690
445033
  return false;
444691
445034
  }
444692
445035
  }
444693
- function journalTeleportIntent(runtime, pending2, expectedRevision) {
444694
- return recordListenerWork(runtime, {
444695
- teleport: {
444696
- teleportId: pending2.teleportId,
444697
- connectionId: pending2.connectionId,
444698
- connectionGeneration: runtime.listener.connectionGeneration ?? undefined,
444699
- activeTurn: pending2.activeTurn,
444700
- continuation: pending2.continuation,
444701
- ready: false
444702
- }
444703
- }, "after_tool_execution", expectedRevision);
444704
- }
444705
445036
  function persistIdleTeleportReady(pending2, intentRevision) {
444706
445037
  const store3 = createInterruptedTurnStore();
444707
445038
  const record6 = store3.read(pending2.agentId, pending2.conversationId);
@@ -444733,8 +445064,10 @@ function abandonTeleportIntent(listener, pending2, intentRevision) {
444733
445064
  return;
444734
445065
  }
444735
445066
  try {
444736
- store3.write({ ...record6, teleportId: undefined, teleport: undefined }, intentRevision);
444737
- } catch {}
445067
+ return store3.write({ ...record6, teleportId: undefined, teleport: undefined }, intentRevision).revision;
445068
+ } catch {
445069
+ return;
445070
+ }
444738
445071
  }
444739
445072
  function findPendingTeleportForRuntime(runtime, agentId, conversationId) {
444740
445073
  for (const pending2 of getPendingTeleports(runtime).values()) {
@@ -444804,12 +445137,14 @@ function handleTeleportProbe(command, socket, safeSocketSend) {
444804
445137
  runtime: command.runtime,
444805
445138
  supported: resolveBackendMode() === "api",
444806
445139
  drains_accepted_inputs: true,
444807
- idempotent_continuation: true
445140
+ idempotent_continuation: true,
445141
+ transfers_terminal_consumers: true
444808
445142
  }, "teleport_probe_response", "teleport_probe");
444809
445143
  }
444810
445144
  function handleTeleportRequest(params) {
444811
445145
  const { listener, command, connectionId } = params;
444812
445146
  const pendingTeleports = getPendingTeleports(listener);
445147
+ const scopedRuntime = getOrCreateScopedRuntime(listener, command.runtime.agent_id, command.runtime.conversation_id);
444813
445148
  const key4 = pendingTeleportKey(command.runtime.agent_id, command.runtime.conversation_id, command.teleport_id);
444814
445149
  const existing = pendingTeleports.get(key4);
444815
445150
  if (existing) {
@@ -444821,7 +445156,7 @@ function handleTeleportRequest(params) {
444821
445156
  });
444822
445157
  } else {
444823
445158
  const record6 = persistedTeleportRecord(command.runtime.agent_id, command.runtime.conversation_id, command.teleport_id);
444824
- if (record6 && authorizePersistedTeleportReady(listener, existing, record6)) {
445159
+ if (record6 && authorizePersistedTeleportReady(scopedRuntime, existing, record6)) {
444825
445160
  emitClaimedTeleportReady(listener, existing);
444826
445161
  }
444827
445162
  }
@@ -444842,7 +445177,7 @@ function handleTeleportRequest(params) {
444842
445177
  pending2.activeTurn = persisted.teleport.activeTurn;
444843
445178
  pending2.continuation = persisted.teleport.continuation;
444844
445179
  pendingTeleports.set(key4, pending2);
444845
- if (authorizePersistedTeleportReady(listener, pending2, persisted)) {
445180
+ if (authorizePersistedTeleportReady(scopedRuntime, pending2, persisted)) {
444846
445181
  emitClaimedTeleportReady(listener, pending2);
444847
445182
  }
444848
445183
  return;
@@ -444943,28 +445278,47 @@ function emitClaimedTeleportReady(listener, pending2) {
444943
445278
  }
444944
445279
  function finishClaimedTeleport(runtime, pending2, commit, options = {}) {
444945
445280
  let intentRevision;
444946
- try {
444947
- intentRevision = journalTeleportIntent(runtime, pending2, options.expectedInterruptedRevision);
444948
- } catch (error5) {
444949
- abandonTeleportIntent(runtime.listener, pending2, undefined);
444950
- throw error5;
445281
+ if (!pending2.activeTurn) {
445282
+ try {
445283
+ intentRevision = journalTeleportIntent(runtime, pending2, options.expectedInterruptedRevision);
445284
+ } catch (error5) {
445285
+ abandonTeleportIntent(runtime.listener, pending2, undefined);
445286
+ throw error5;
445287
+ }
444951
445288
  }
444952
445289
  let transition2;
444953
445290
  try {
444954
- transition2 = commit({
444955
- stopReason: options.stopReason ?? "cancelled",
444956
- agentId: pending2.agentId,
444957
- conversationId: pending2.conversationId,
444958
- persistTerminalWithoutConsumers: intentRevision !== undefined,
444959
- expectedInterruptedRevision: intentRevision,
444960
- teleportHandoff: pending2.activeTurn
444961
- });
445291
+ if (pending2.activeTurn) {
445292
+ const result3 = commitActiveTeleportTerminalTransfer({
445293
+ runtime,
445294
+ pending: pending2,
445295
+ commit,
445296
+ stopReason: options.stopReason ?? "cancelled",
445297
+ expectedInterruptedRevision: options.expectedInterruptedRevision,
445298
+ onUnavailable: (revision) => abandonTeleportIntent(runtime.listener, pending2, revision)
445299
+ });
445300
+ if (result3.fallback)
445301
+ return result3.transition;
445302
+ intentRevision = result3.revision;
445303
+ transition2 = result3.transition;
445304
+ } else {
445305
+ transition2 = commit({
445306
+ stopReason: options.stopReason ?? "cancelled",
445307
+ agentId: pending2.agentId,
445308
+ conversationId: pending2.conversationId,
445309
+ persistTerminalWithoutConsumers: intentRevision !== undefined,
445310
+ expectedInterruptedRevision: intentRevision
445311
+ });
445312
+ }
444962
445313
  } catch (error5) {
444963
- abandonTeleportIntent(runtime.listener, pending2, intentRevision);
445314
+ if (!retainDurableTeleportTerminal(runtime, pending2, intentRevision, error5)) {
445315
+ abandonTeleportIntent(runtime.listener, pending2, intentRevision);
445316
+ }
444964
445317
  throw error5;
444965
445318
  }
444966
445319
  if (!transition2.finished) {
444967
- abandonTeleportIntent(runtime.listener, pending2, intentRevision);
445320
+ if (!retainDurableTeleportTerminal(runtime, pending2, intentRevision))
445321
+ abandonTeleportIntent(runtime.listener, pending2, intentRevision);
444968
445322
  return transition2;
444969
445323
  }
444970
445324
  if (!intentRevision) {
@@ -444973,18 +445327,51 @@ function finishClaimedTeleport(runtime, pending2, commit, options = {}) {
444973
445327
  return transition2;
444974
445328
  }
444975
445329
  const store3 = createInterruptedTurnStore();
444976
- const record6 = store3.read(pending2.agentId, pending2.conversationId);
444977
- if (record6?.revision !== intentRevision || !record6.teleport)
445330
+ let record6;
445331
+ try {
445332
+ record6 = store3.readOrThrow(pending2.agentId, pending2.conversationId);
445333
+ } catch {
445334
+ runtime.listener.scheduleRecordedRecovery?.();
445335
+ return transition2;
445336
+ }
445337
+ if (!record6) {
445338
+ pending2.readyAt = Date.now();
445339
+ pending2.error = "Teleport intent disappeared after source terminal commit";
445340
+ sendTeleportReady(runtime.listener, pending2, {
445341
+ success: false,
445342
+ error: pending2.error
445343
+ });
445344
+ retainTeleportForRecovery(runtime.listener, pending2);
445345
+ return transition2;
445346
+ }
445347
+ if (record6.revision !== intentRevision) {
445348
+ if (options.canCommit?.() === false) {
445349
+ runtime.listener.scheduleRecordedRecovery?.();
445350
+ return transition2;
445351
+ }
445352
+ const readyRecord = persistSuccessorTeleportReady(runtime, pending2, record6, intentRevision);
445353
+ if (readyRecord) {
445354
+ pending2.interruptedRevision = readyRecord.revision;
445355
+ retireTeleportTerminalProof(readyRecord, intentRevision);
445356
+ emitClaimedTeleportReady(runtime.listener, pending2);
445357
+ }
444978
445358
  return transition2;
444979
- const terminalIsDurable = persistedTeleportTerminalIsDurable(runtime.listener, record6);
445359
+ }
445360
+ if (!record6.teleport)
445361
+ return transition2;
445362
+ const terminalProof = classifyPersistedTeleportTerminal(runtime, record6);
444980
445363
  if (options.canCommit?.() === false) {
444981
- if (!terminalIsDurable) {
445364
+ if (terminalProof === "absent") {
444982
445365
  abandonTeleportIntent(runtime.listener, pending2, intentRevision);
444983
445366
  } else {
444984
445367
  runtime.listener.scheduleRecordedRecovery?.();
444985
445368
  }
444986
445369
  return transition2;
444987
445370
  }
445371
+ if (terminalProof !== "present") {
445372
+ runtime.listener.scheduleRecordedRecovery?.();
445373
+ return transition2;
445374
+ }
444988
445375
  try {
444989
445376
  options.beforeReadyPersist?.();
444990
445377
  const readyRecord = store3.write({
@@ -445035,6 +445422,8 @@ function clearAcceptedFailedTeleport(listener, pending2, dependencies4 = {}) {
445035
445422
  clearAcceptedFailedTeleportBounded(listener, pending2, dependencies4);
445036
445423
  }
445037
445424
  function handleTeleportFailure(params) {
445425
+ const runtime = params.getOrCreateScopedRuntime(params.listener, params.command.runtime.agent_id, params.command.runtime.conversation_id);
445426
+ const identity2 = teleportInputIdentity(params.command.teleport_id);
445038
445427
  const pending2 = findFailedTeleport({
445039
445428
  listener: params.listener,
445040
445429
  teleportId: params.command.teleport_id,
@@ -445042,10 +445431,16 @@ function handleTeleportFailure(params) {
445042
445431
  conversationId: params.command.runtime.conversation_id,
445043
445432
  connectionId: params.connectionId
445044
445433
  });
445045
- if (!pending2 || pending2.error)
445434
+ if (!pending2) {
445435
+ const admission2 = reserveInputDisposition(runtime, identity2);
445436
+ if (admission2.kind === "duplicate")
445437
+ emitTeleportFailedAck(params);
445438
+ if (admission2.kind === "reserved")
445439
+ rollbackInputDisposition(runtime, admission2.reservation);
445440
+ return;
445441
+ }
445442
+ if (pending2.error)
445046
445443
  return;
445047
- const runtime = params.getOrCreateScopedRuntime(params.listener, pending2.agentId, pending2.conversationId);
445048
- const identity2 = teleportInputIdentity(params.command.teleport_id);
445049
445444
  const incoming = {
445050
445445
  type: "message",
445051
445446
  connectionId: params.connectionId,
@@ -445056,7 +445451,8 @@ function handleTeleportFailure(params) {
445056
445451
  error: params.command.error,
445057
445452
  approvals: pending2.continuation?.approvals
445058
445453
  }),
445059
- durableInputIdentities: [identity2]
445454
+ durableInputIdentities: [identity2],
445455
+ terminalConsumerIds: pending2.continuation?.terminal_consumer_ids
445060
445456
  };
445061
445457
  const admission = reserveInputDisposition(runtime, identity2);
445062
445458
  if (admission.kind === "full")
@@ -445064,6 +445460,7 @@ function handleTeleportFailure(params) {
445064
445460
  if (admission.kind === "duplicate") {
445065
445461
  clearAcceptedFailedTeleport(params.listener, pending2, params.failedTeleportCleanup);
445066
445462
  params.listener.pendingTeleports?.delete(pendingTeleportKey(pending2.agentId, pending2.conversationId, pending2.teleportId));
445463
+ emitTeleportFailedAck(params);
445067
445464
  return;
445068
445465
  }
445069
445466
  const reservation = admission.kind === "reserved" ? admission.reservation : undefined;
@@ -445077,6 +445474,7 @@ function handleTeleportFailure(params) {
445077
445474
  runtime.dequeuedInputIdentitiesByBatchId.set(directBatchId, [identity2]);
445078
445475
  clearAcceptedFailedTeleport(params.listener, pending2, params.failedTeleportCleanup);
445079
445476
  params.listener.pendingTeleports?.delete(pendingTeleportKey(pending2.agentId, pending2.conversationId, pending2.teleportId));
445477
+ emitTeleportFailedAck(params);
445080
445478
  emitLoopErrorNotice(params.socket, runtime, {
445081
445479
  message: `Teleport failed: ${params.command.error}`,
445082
445480
  stopReason: "error",
@@ -445105,13 +445503,12 @@ var init_teleport = __esm(async () => {
445105
445503
  init_failed_teleport_cleanup(),
445106
445504
  init_input_disposition(),
445107
445505
  init_input_disposition_rollback(),
445108
- init_input_terminal_evidence(),
445109
- init_input_terminal_journal(),
445110
445506
  init_interrupted_turn_record(),
445111
445507
  init_protocol_outbound(),
445112
445508
  init_recoverable_notices(),
445113
445509
  init_runtime6(),
445114
- init_turn_finished_replay()
445510
+ init_teleport_failed_ack(),
445511
+ init_teleport_terminal_transfer()
445115
445512
  ]);
445116
445513
  TELEPORT_RECOVERY_TTL_MS = 5 * 60000;
445117
445514
  });
@@ -450059,6 +450456,36 @@ var init_recovered_approval_retry = __esm(() => {
450059
450456
  retryStates = new WeakMap;
450060
450457
  });
450061
450458
 
450459
+ // src/websocket/listener/input-terminal-consumer-snapshot.ts
450460
+ function snapshotInputTerminalConsumers(runtime, identities, initial2) {
450461
+ const keys3 = [
450462
+ ...new Set(identities.map((identity2) => dispositionKey(runtime.key, identity2)))
450463
+ ];
450464
+ const ledger = getLedger(runtime.listener);
450465
+ const collect = (entries2) => {
450466
+ const consumers = new Set(initial2);
450467
+ for (const key4 of keys3) {
450468
+ const entry = entries2.get(key4);
450469
+ for (const consumerId of entry?.queuedInput?.incoming.terminalConsumerIds ?? []) {
450470
+ consumers.add(consumerId);
450471
+ }
450472
+ }
450473
+ return [...consumers];
450474
+ };
450475
+ if (!ledger.persistentPath)
450476
+ return collect(ledger.entries);
450477
+ return durableTransaction(ledger.persistentPath, (store3) => {
450478
+ syncMemoryFromDurable(ledger, store3);
450479
+ return {
450480
+ result: collect(new Map(Object.entries(store3.entries))),
450481
+ changed: false
450482
+ };
450483
+ });
450484
+ }
450485
+ var init_input_terminal_consumer_snapshot = __esm(async () => {
450486
+ await init_input_disposition();
450487
+ });
450488
+
450062
450489
  // src/websocket/listener/interrupted-turn-read.ts
450063
450490
  function readInterruptedTurn(runtime, recoveryLineageId) {
450064
450491
  if (!runtime.agentId || !runtime.listener.connectionId?.startsWith("conn-"))
@@ -450100,7 +450527,7 @@ function finishListenerTurn(runtime, lease, options) {
450100
450527
  type: "turn_finished",
450101
450528
  turn_id: options.turnId,
450102
450529
  stop_reason: options.stopReason,
450103
- ...options.terminalConsumerIds?.length && !options.teleportHandoff ? {
450530
+ ...options.terminalConsumerIds?.length ? {
450104
450531
  terminal_consumer_ids: [
450105
450532
  ...new Set(options.terminalConsumerIds)
450106
450533
  ]
@@ -450111,7 +450538,7 @@ function finishListenerTurn(runtime, lease, options) {
450111
450538
  } : null;
450112
450539
  const readRevision = options.readInterruptedRevision ?? (() => readInterruptedTurn(runtime)?.revision);
450113
450540
  const interruptedRevision = readRevision();
450114
- const expectedAuthorityRevision = options.expectedInterruptedAuthorityRevision ?? options.expectedInterruptedRevision;
450541
+ let expectedAuthorityRevision = options.expectedInterruptedAuthorityRevision ?? options.expectedInterruptedRevision;
450115
450542
  const readAuthorityRevision = options.readInterruptedAuthorityRevision ?? readRevision;
450116
450543
  if (expectedAuthorityRevision !== undefined && readAuthorityRevision() !== expectedAuthorityRevision) {
450117
450544
  return rejectedCommit();
@@ -450126,27 +450553,56 @@ function finishListenerTurn(runtime, lease, options) {
450126
450553
  terminalOwner.recoveryLineageId = options.recoveryLineageId;
450127
450554
  terminalOwner.interruptedAuthorityRevision = expectedAuthorityRevision;
450128
450555
  }
450556
+ if (turnFinishedMessage && options.onBeforePrepareInputTerminal) {
450557
+ const consumers = snapshotInputTerminalConsumers(runtime, options.durableInputIdentities ?? [], turnFinishedMessage.terminal_consumer_ids ?? []);
450558
+ if (consumers.length)
450559
+ turnFinishedMessage.terminal_consumer_ids = consumers;
450560
+ }
450129
450561
  const identitylessConsumerTerminal = !!turnFinishedMessage?.terminal_consumer_ids?.length && (options.durableInputIdentities?.length ?? 0) === 0;
450130
450562
  if (identitylessConsumerTerminal && terminalOwner.connectionId === null) {
450131
450563
  terminalOwner.canRotate = true;
450132
450564
  }
450133
450565
  let preparedTurnFinished = null;
450134
- if (turnFinishedMessage && !(options.prepareInputTerminal ?? prepareInputTerminal)(runtime, options.durableInputIdentities ?? [], {
450566
+ const inputTerminal = turnFinishedMessage ? {
450135
450567
  scope: {
450136
450568
  agentId: runtime.agentId,
450137
450569
  conversationId: runtime.conversationId
450138
450570
  },
450139
450571
  message: turnFinishedMessage,
450140
450572
  owner: terminalOwner,
450141
- ...options.persistTerminalWithoutConsumers ? { persistWithoutConsumers: true } : {}
450573
+ ...options.persistTerminalWithoutConsumers ? { persistWithoutConsumers: true } : {},
450574
+ ...options.teleportHandoff ? { suppressConsumerPublication: true } : {}
450575
+ } : undefined;
450576
+ if (inputTerminal && options.onBeforePrepareInputTerminal) {
450577
+ const nextRevision = options.onBeforePrepareInputTerminal(inputTerminal);
450578
+ if (nextRevision === false)
450579
+ throw new TeleportIntentUnavailableError;
450580
+ if (nextRevision) {
450581
+ terminalOwner.interruptedRevision = nextRevision;
450582
+ if (!options.readInterruptedAuthorityRevision || readAuthorityRevision() === nextRevision) {
450583
+ expectedAuthorityRevision = nextRevision;
450584
+ terminalOwner.interruptedAuthorityRevision = nextRevision;
450585
+ }
450586
+ }
450587
+ }
450588
+ let preparedValidationRejected = false;
450589
+ if (inputTerminal && !(options.prepareInputTerminal ?? prepareInputTerminal)(runtime, options.durableInputIdentities ?? [], inputTerminal, {
450590
+ onPrepared: options.validatePreparedInputTerminal ? (terminal) => {
450591
+ const valid2 = options.validatePreparedInputTerminal?.(terminal) === true;
450592
+ preparedValidationRejected = !valid2;
450593
+ return valid2;
450594
+ } : undefined
450142
450595
  })) {
450596
+ if (preparedValidationRejected) {
450597
+ throw new TeleportTerminalConsumerRaceError;
450598
+ }
450143
450599
  runtime.turnLifecycle.finish(lease, options.stopReason);
450144
450600
  throw new Error("Failed to atomically prepare accepted-input terminal");
450145
450601
  }
450146
450602
  if (!ownsInterruptedRevision()) {
450147
450603
  return rejectedCommit();
450148
450604
  }
450149
- const deferUntilReplayOwner = runtime.listener.connectionId?.startsWith("conn-") === true && !!turnFinishedMessage?.terminal_consumer_ids?.length && terminalOwner.connectionId === null && !identitylessConsumerTerminal && !options.turnFinishedStore;
450605
+ const deferUntilReplayOwner = !options.teleportHandoff && runtime.listener.connectionId?.startsWith("conn-") === true && !!turnFinishedMessage?.terminal_consumer_ids?.length && terminalOwner.connectionId === null && !identitylessConsumerTerminal && !options.turnFinishedStore;
450150
450606
  const authorityGuard = options.recoveryAuthorityGuard ?? (!options.readInterruptedRevision && !options.readInterruptedAuthorityRevision ? createInterruptedTurnStore() : undefined);
450151
450607
  let guardDirectPublication = false;
450152
450608
  try {
@@ -450165,7 +450621,12 @@ function finishListenerTurn(runtime, lease, options) {
450165
450621
  throw error5;
450166
450622
  }
450167
450623
  try {
450168
- const persistTerminal = () => turnFinishedMessage && !deferUntilReplayOwner ? prepareTurnFinished(runtime, turnFinishedMessage, options.turnFinishedStore, terminalOwner, options.persistTerminalWithoutConsumers || identitylessConsumerTerminal) : null;
450624
+ const persistTerminal = () => {
450625
+ if (!turnFinishedMessage || deferUntilReplayOwner)
450626
+ return null;
450627
+ const durableMessage = options.teleportHandoff ? terminalMessageWithoutConsumers(turnFinishedMessage) : turnFinishedMessage;
450628
+ return prepareTurnFinished(runtime, durableMessage, options.turnFinishedStore, terminalOwner, options.persistTerminalWithoutConsumers || identitylessConsumerTerminal);
450629
+ };
450169
450630
  if (guardDirectPublication && authorityGuard?.withRecoveryAuthority && options.recoveryLineageId && expectedAuthorityRevision) {
450170
450631
  const guarded = authorityGuard.withRecoveryAuthority({
450171
450632
  agentId: runtime.agentId ?? "",
@@ -450242,11 +450703,13 @@ var init_turn_terminal = __esm(async () => {
450242
450703
  init_debug();
450243
450704
  await __promiseAll([
450244
450705
  init_connection(),
450706
+ init_input_terminal_consumer_snapshot(),
450245
450707
  init_input_terminal_journal(),
450246
450708
  init_interrupted_turn_read(),
450247
450709
  init_interrupted_turn_record(),
450248
450710
  init_protocol_outbound(),
450249
450711
  init_recoverable_notices(),
450712
+ init_teleport_terminal_transfer(),
450250
450713
  init_turn_finished_replay()
450251
450714
  ]);
450252
450715
  });
@@ -450522,7 +450985,7 @@ var init_secrets_sync = __esm(() => {
450522
450985
  });
450523
450986
 
450524
450987
  // src/websocket/listener/turn-durability-ownership.ts
450525
- import { randomUUID as randomUUID51 } from "node:crypto";
450988
+ import { randomUUID as randomUUID52 } from "node:crypto";
450526
450989
  async function checkpointTurnInputOwnership(runtime, ownership, expectedRevision, actingUserId, recoveryLineageId, recoveryEvidenceWriter) {
450527
450990
  const update3 = {
450528
450991
  durableInputIdentities: [...ownership.durableInputIdentities],
@@ -450542,7 +451005,7 @@ function createTurnDurabilityOwnership() {
450542
451005
  const durableInputIdentities = new Map;
450543
451006
  const terminalConsumerIds = new Set;
450544
451007
  return {
450545
- terminalTurnId: `turn-${randomUUID51()}`,
451008
+ terminalTurnId: `turn-${randomUUID52()}`,
450546
451009
  recordInput(input) {
450547
451010
  for (const identity2 of input.durableInputIdentities ?? []) {
450548
451011
  durableInputIdentities.set(`${identity2.domain}\x00${identity2.id}`, identity2);
@@ -459312,7 +459775,7 @@ var init_post_turn_reflection = __esm(() => {
459312
459775
 
459313
459776
  // src/agent/memory-worktree.ts
459314
459777
  import { execFile as execFileCb3 } from "node:child_process";
459315
- import { randomUUID as randomUUID52 } from "node:crypto";
459778
+ import { randomUUID as randomUUID53 } from "node:crypto";
459316
459779
  import { existsSync as existsSync63 } from "node:fs";
459317
459780
  import { mkdir as mkdir14 } from "node:fs/promises";
459318
459781
  import { dirname as dirname36, isAbsolute as isAbsolute25, join as join95, resolve as resolve38 } from "node:path";
@@ -459356,7 +459819,7 @@ function normalizeGitPath(path43, cwd2) {
459356
459819
  }
459357
459820
  function buildReflectionWorktreeId(now2 = new Date) {
459358
459821
  const timestamp = now2.toISOString().replace(/[^0-9]/g, "").slice(0, 14);
459359
- return `${timestamp}-${randomUUID52().slice(0, 8)}`;
459822
+ return `${timestamp}-${randomUUID53().slice(0, 8)}`;
459360
459823
  }
459361
459824
  function summarizeReflectionCommitSubject(subject) {
459362
459825
  const summary = subject.trim().replace(/^[a-z]+(?:\([^)]+\))?!?:\s*/i, "").trim();
@@ -459965,7 +460428,7 @@ function isAutoReflectionEnabled() {
459965
460428
  }
459966
460429
 
459967
460430
  // src/telemetry/reflection-threshold-feedback.ts
459968
- import { randomUUID as randomUUID53 } from "node:crypto";
460431
+ import { randomUUID as randomUUID54 } from "node:crypto";
459969
460432
  async function resolveFeedbackApiKey() {
459970
460433
  const settings3 = await settingsManager.getSettingsWithSecureTokens();
459971
460434
  return process.env.LETTA_API_KEY || settings3.env?.LETTA_API_KEY;
@@ -459977,7 +460440,7 @@ function getFeedbackDeviceId() {
459977
460440
  return deviceId;
459978
460441
  }
459979
460442
  } catch {}
459980
- return randomUUID53();
460443
+ return randomUUID54();
459981
460444
  }
459982
460445
  function getAlertDeviceType() {
459983
460446
  switch (process.platform) {
@@ -466201,6 +466664,14 @@ var init_queue2 = __esm(async () => {
466201
466664
  });
466202
466665
 
466203
466666
  // src/websocket/listener/input-disposition-ownership.ts
466667
+ function entryHasLiveAcceptedInputOwner(entry) {
466668
+ if (!entry || entry.expiresAt <= Date.now())
466669
+ return false;
466670
+ if (entry.disposition !== "started" && entry.disposition !== "queued") {
466671
+ return false;
466672
+ }
466673
+ return !entry.replayCompleted && !entry.preparedTerminal && !entry.completedTerminalRevision && !entry.completedTerminalAuthority;
466674
+ }
466204
466675
  function readInputDispositionEntry(runtime, identity2) {
466205
466676
  if (!identity2)
466206
466677
  return;
@@ -466223,18 +466694,45 @@ function readInputDispositionEntry(runtime, identity2) {
466223
466694
  return ledger.entries.get(key4) ?? undefined;
466224
466695
  }
466225
466696
  function hasLiveAcceptedInputOwner(runtime, identity2) {
466226
- const entry = readInputDispositionEntry(runtime, identity2);
466227
- if (!entry)
466228
- return false;
466229
- if (entry.expiresAt <= Date.now())
466230
- return false;
466231
- if (entry.disposition !== "started" && entry.disposition !== "queued") {
466697
+ return entryHasLiveAcceptedInputOwner(readInputDispositionEntry(runtime, identity2));
466698
+ }
466699
+ function attachTerminalConsumerToLiveAcceptedInput(runtime, identity2, terminalConsumerId) {
466700
+ if (!identity2 || !terminalConsumerId)
466232
466701
  return false;
466702
+ const ledger = getLedger(runtime.listener);
466703
+ const key4 = dispositionKey(runtime.key, identity2);
466704
+ const attach = (entry) => {
466705
+ if (!entryHasLiveAcceptedInputOwner(entry) || !entry.queuedInput) {
466706
+ return false;
466707
+ }
466708
+ const incoming = entry.queuedInput.incoming;
466709
+ const previousConsumers = incoming.terminalConsumerIds;
466710
+ const nextConsumers = [
466711
+ ...new Set([...incoming.terminalConsumerIds ?? [], terminalConsumerId])
466712
+ ];
466713
+ if (nextConsumers.length > MAX_LATE_TERMINAL_CONSUMERS_PER_INPUT) {
466714
+ return false;
466715
+ }
466716
+ incoming.terminalConsumerIds = nextConsumers;
466717
+ if (Buffer.byteLength(JSON.stringify(entry.queuedInput)) > MAX_DURABLE_QUEUED_INPUT_BYTES) {
466718
+ incoming.terminalConsumerIds = previousConsumers;
466719
+ return false;
466720
+ }
466721
+ return true;
466722
+ };
466723
+ if (ledger.persistentPath) {
466724
+ try {
466725
+ return durableTransaction(ledger.persistentPath, (store3) => {
466726
+ const attached = attach(store3.entries[key4]);
466727
+ syncMemoryFromDurable(ledger, store3);
466728
+ return { result: attached, changed: attached };
466729
+ });
466730
+ } catch {
466731
+ return false;
466732
+ }
466233
466733
  }
466234
- return !entry.replayCompleted && !entry.preparedTerminal && !entry.completedTerminalRevision && !entry.completedTerminalAuthority;
466235
- }
466236
- function liveAcceptedInputOwnerProof(runtime, identity2) {
466237
- return identity2 ? () => hasLiveAcceptedInputOwner(runtime, identity2) : undefined;
466734
+ expireAcceptedInputDispositions(ledger, Date.now());
466735
+ return attach(ledger.entries.get(key4));
466238
466736
  }
466239
466737
  function hasLiveAcceptedInputOwnerWithOriginatorRetirement(runtime, identity2) {
466240
466738
  if (!hasLiveAcceptedInputOwner(runtime, identity2))
@@ -466243,6 +466741,7 @@ function hasLiveAcceptedInputOwnerWithOriginatorRetirement(runtime, identity2) {
466243
466741
  const owner = entry?.queuedInput?.incoming?.mcpOriginatorSuperRunId;
466244
466742
  return typeof owner === "string" && owner.length > 0;
466245
466743
  }
466744
+ var MAX_LATE_TERMINAL_CONSUMERS_PER_INPUT = 64;
466246
466745
  var init_input_disposition_ownership = __esm(async () => {
466247
466746
  await init_input_disposition();
466248
466747
  });
@@ -466314,11 +466813,12 @@ function dispatchInboundMessageWhenReady(params) {
466314
466813
  }
466315
466814
  const admission = reserveInputDisposition(runtime, identity2);
466316
466815
  if (admission.kind === "duplicate") {
466816
+ const terminalConsumerId = incoming.terminalConsumerIds?.[0];
466317
466817
  acknowledgeInput2({
466318
466818
  accepted: true,
466319
466819
  disposition: admission.disposition,
466320
466820
  duplicate: true,
466321
- mayRecreateOwner: liveAcceptedInputOwnerProof(runtime, identity2)
466821
+ mayRecreateOwner: () => terminalConsumerId ? attachTerminalConsumerToLiveAcceptedInput(runtime, identity2, terminalConsumerId) : hasLiveAcceptedInputOwner(runtime, identity2)
466322
466822
  });
466323
466823
  return;
466324
466824
  }
@@ -466432,17 +466932,25 @@ var init_inbound_dispatch = __esm(async () => {
466432
466932
 
466433
466933
  // src/websocket/listener/input-ack.ts
466434
466934
  function acknowledgeInputFrame(send, socket, frame, accepted, error5, disposition, deliveryHandling, mayRecreateOwner, extras) {
466935
+ let duplicateOwnerLive;
466936
+ const trackRecreateOwnerProof = mayRecreateOwner ? () => {
466937
+ const live = mayRecreateOwner();
466938
+ duplicateOwnerLive = duplicateOwnerLive === true || live;
466939
+ return live;
466940
+ } : undefined;
466941
+ if (accepted)
466942
+ trackRecreateOwnerProof?.();
466435
466943
  if (accepted) {
466436
466944
  const allowCreate = (deliveryHandling ?? (disposition ? "create" : "refresh")) === "create";
466437
466945
  if (extras?.preGated === null) {} else if (extras?.preGated !== undefined) {
466438
466946
  installPreGatedMcpOriginatorDelivery(extras.preGated, {
466439
466947
  allowCreate,
466440
- mayRecreateOwner
466948
+ mayRecreateOwner: trackRecreateOwnerProof
466441
466949
  });
466442
466950
  } else {
466443
466951
  const verdict = recordMcpOriginatorDelivery(frame, {
466444
466952
  allowCreate,
466445
- mayRecreateOwner
466953
+ mayRecreateOwner: trackRecreateOwnerProof
466446
466954
  });
466447
466955
  if (verdict === "denied_retryable") {
466448
466956
  console.error("[input-ack] originator admission is retryable-denied; suppressing the ack so Cloud redelivers");
@@ -466461,6 +466969,7 @@ function acknowledgeInputFrame(send, socket, frame, accepted, error5, dispositio
466461
466969
  runtime: frame.runtime,
466462
466970
  accepted,
466463
466971
  ...disposition ? { disposition } : {},
466972
+ ...duplicateOwnerLive === undefined ? {} : { duplicate_owner_live: duplicateOwnerLive },
466464
466973
  ...error5 ? { error: error5 } : {},
466465
466974
  ...extras?.abortReason !== undefined && !accepted ? { abortReason: extras.abortReason } : {}
466466
466975
  }, "input_accepted_response", "input");
@@ -466473,7 +466982,8 @@ function acknowledgeIfAlreadyAdmitted(transport3, runtime, identity2) {
466473
466982
  return true;
466474
466983
  }
466475
466984
  function acknowledgeAdmissionDuplicate(transport3, runtime, identity2, disposition) {
466476
- acknowledgeInputFrame(transport3.safeSocketSend, transport3.socket, transport3.frame, true, undefined, disposition, "refresh", liveAcceptedInputOwnerProof(runtime, identity2));
466985
+ const terminalConsumerId = typeof transport3.frame.terminal_consumer_id === "string" ? transport3.frame.terminal_consumer_id : undefined;
466986
+ acknowledgeInputFrame(transport3.safeSocketSend, transport3.socket, transport3.frame, true, undefined, disposition, "refresh", () => terminalConsumerId ? attachTerminalConsumerToLiveAcceptedInput(runtime, identity2, terminalConsumerId) : hasLiveAcceptedInputOwner(runtime, identity2));
466477
466987
  }
466478
466988
  var MCP_ORIGINATOR_DENIED_PERMANENT_ABORT_REASON = "mcp_originator_denied_permanent";
466479
466989
  var init_input_ack = __esm(async () => {
@@ -466731,7 +467241,12 @@ function admitTeleportContinueInput(params) {
466731
467241
  teleportId,
466732
467242
  approvals: payload.continuation?.approvals
466733
467243
  }),
466734
- durableInputIdentities: [identity2]
467244
+ durableInputIdentities: [identity2],
467245
+ ...payload.continuation?.terminal_consumer_ids?.length ? {
467246
+ terminalConsumerIds: [
467247
+ ...new Set(payload.continuation.terminal_consumer_ids)
467248
+ ]
467249
+ } : {}
466735
467250
  };
466736
467251
  if (!(params.commitDisposition ?? commitInputDisposition)(scopedRuntime, reservation, "started", {
466737
467252
  incoming: continuationInput
@@ -468378,21 +468893,23 @@ function prepareRecordedInputTerminal(listener, terminalStore, runtime, record6,
468378
468893
  agentId: record6.agentId,
468379
468894
  conversationId: record6.conversationId
468380
468895
  };
468381
- const terminalAuthority = authority ? {
468896
+ const terminalAuthority = record6.teleport?.terminalAuthority ?? (authority ? {
468382
468897
  interruptedRevision: record6.revision,
468383
468898
  authorityRevision: authority.revisionToken,
468384
468899
  recoveryLineageId: authority.lineageId
468385
- } : undefined;
468386
- const existingPrepared = loadPreparedInputTerminals(listener).find((prepared) => prepared.scope.agentId === scope.agentId && prepared.scope.conversationId === scope.conversationId && prepared.owner.interruptedRevision === record6.revision && (terminalAuthority ? prepared.owner.recoveryLineageId === terminalAuthority.recoveryLineageId && prepared.owner.interruptedAuthorityRevision === terminalAuthority.authorityRevision : prepared.owner.recoveryLineageId === undefined));
468900
+ } : undefined);
468901
+ const suppressTeleportConsumers = record6.teleport?.activeTurn === true && record6.teleport.ready === false;
468902
+ const proofRevision = terminalAuthority?.interruptedRevision || record6.revision;
468903
+ const existingPrepared = loadPreparedInputTerminals(listener).find((prepared) => prepared.scope.agentId === scope.agentId && prepared.scope.conversationId === scope.conversationId && prepared.owner.interruptedRevision === proofRevision && (terminalAuthority ? prepared.owner.recoveryLineageId === terminalAuthority.recoveryLineageId && prepared.owner.interruptedAuthorityRevision === terminalAuthority.authorityRevision : prepared.owner.recoveryLineageId === undefined));
468387
468904
  const terminalDigest = createHash18("sha256").update(JSON.stringify([
468388
468905
  "recorded-turn-terminal-v1",
468389
468906
  record6.agentId,
468390
468907
  record6.conversationId,
468391
- record6.revision,
468908
+ proofRevision,
468392
468909
  terminalAuthority?.recoveryLineageId ?? null,
468393
468910
  terminalAuthority?.authorityRevision ?? null
468394
468911
  ])).digest("hex");
468395
- const terminalIdentity = `recorded:${terminalDigest}`;
468912
+ const terminalIdentity = terminalAuthority?.terminalIdentity ?? `recorded:${terminalDigest}`;
468396
468913
  let existingPersisted;
468397
468914
  if (!identities.length) {
468398
468915
  try {
@@ -468401,14 +468918,14 @@ function prepareRecordedInputTerminal(listener, terminalStore, runtime, record6,
468401
468918
  return false;
468402
468919
  }
468403
468920
  }
468404
- if (terminalAuthority ? hasCompletedInputTerminalAuthority(listener, runtime.key, identities, terminalAuthority) : hasCompletedInputTerminalRevision(listener, runtime.key, identities, record6.revision)) {
468921
+ if (terminalAuthority ? hasCompletedInputTerminalAuthority(listener, runtime.key, identities, terminalAuthority) : hasCompletedInputTerminalRevision(listener, runtime.key, identities, proofRevision)) {
468405
468922
  return true;
468406
468923
  }
468407
468924
  const eligibleConnections = [...listener.connections.values()].filter((connection) => connection.initialized && connection.subscriptions.has(runtime.key)).sort((left, right) => left.id.localeCompare(right.id));
468408
468925
  const activeConnection = runtime.activeConnectionId ? listener.connections.get(runtime.activeConnectionId) : undefined;
468409
468926
  const ownerConnection = activeConnection?.initialized && activeConnection.subscriptions.has(runtime.key) ? activeConnection : eligibleConnections.find((connection) => connection.options.connectionIdCanResume !== false);
468410
468927
  const persistedEvidence = existingPrepared ?? existingPersisted;
468411
- const owner = persistedEvidence ? { ...persistedEvidence.owner } : getTurnFinishedOwner(runtime, record6.revision);
468928
+ const owner = persistedEvidence ? { ...persistedEvidence.owner } : getTurnFinishedOwner(runtime, proofRevision);
468412
468929
  if (!persistedEvidence) {
468413
468930
  if (terminalAuthority) {
468414
468931
  owner.recoveryLineageId = terminalAuthority.recoveryLineageId;
@@ -468423,11 +468940,11 @@ function prepareRecordedInputTerminal(listener, terminalStore, runtime, record6,
468423
468940
  type: "turn_finished",
468424
468941
  turn_id: `turn-recovered-complete-${owner.terminalIdentity?.replace(/^recorded:/, "")}`,
468425
468942
  stop_reason: stopReason,
468426
- ...record6.terminalConsumerIds?.length ? { terminal_consumer_ids: [...new Set(record6.terminalConsumerIds)] } : {},
468943
+ ...!suppressTeleportConsumers && record6.terminalConsumerIds?.length ? { terminal_consumer_ids: [...new Set(record6.terminalConsumerIds)] } : {},
468427
468944
  ...runId ? { run_id: runId } : {}
468428
468945
  };
468429
468946
  if (!identities.length) {
468430
- if (!message2.terminal_consumer_ids?.length)
468947
+ if (!message2.terminal_consumer_ids?.length && !suppressTeleportConsumers)
468431
468948
  return true;
468432
468949
  if (owner.connectionId === null)
468433
468950
  owner.canRotate = true;
@@ -468436,12 +468953,13 @@ function prepareRecordedInputTerminal(listener, terminalStore, runtime, record6,
468436
468953
  if (!prepareInputTerminal(runtime, identities, {
468437
468954
  scope,
468438
468955
  message: message2,
468439
- owner
468956
+ owner,
468957
+ ...suppressTeleportConsumers ? { suppressConsumerPublication: true } : {}
468440
468958
  })) {
468441
468959
  return false;
468442
468960
  }
468443
468961
  promotePreparedInputTerminals(listener, terminalStore, scope);
468444
- return terminalAuthority ? !hasPreparedInputTerminalAuthority(listener, scope, terminalAuthority) : !hasPreparedInputTerminalRevision(listener, scope, record6.revision);
468962
+ return terminalAuthority ? !hasPreparedInputTerminalAuthority(listener, scope, terminalAuthority) : !hasPreparedInputTerminalRevision(listener, scope, proofRevision);
468445
468963
  }
468446
468964
  var init_recorded_turn_terminal = __esm(async () => {
468447
468965
  await __promiseAll([
@@ -468453,8 +468971,20 @@ var init_recorded_turn_terminal = __esm(async () => {
468453
468971
  ]);
468454
468972
  });
468455
468973
 
468974
+ // src/websocket/listener/teleport-ready-cleanup.ts
468975
+ function retireReadyTeleportRecord(store3, record6) {
468976
+ try {
468977
+ if (record6.teleport?.preserveSuccessorWork) {
468978
+ return Boolean(store3.write({ ...record6, teleportId: undefined, teleport: undefined }, record6.revision));
468979
+ }
468980
+ return store3.remove(record6.agentId, record6.conversationId, record6.revision ?? null);
468981
+ } catch {
468982
+ return false;
468983
+ }
468984
+ }
468985
+
468456
468986
  // src/websocket/listener/recover-recorded-turn.ts
468457
- import { randomUUID as randomUUID54 } from "node:crypto";
468987
+ import { randomUUID as randomUUID55 } from "node:crypto";
468458
468988
  function scheduleRecordedTurnRecovery(listener, recover = recoverRecordedTurns, retryDelayMs = 5000) {
468459
468989
  if (scheduledRecoveries.has(listener))
468460
468990
  return;
@@ -468637,9 +469167,8 @@ async function recoverRecordedTurns(listener, deps = {}) {
468637
469167
  deferred2 = true;
468638
469168
  continue;
468639
469169
  }
468640
- if (!store3.remove(record6.agentId, record6.conversationId, record6.revision ?? null)) {
469170
+ if (!retireReadyTeleportRecord(store3, record6))
468641
469171
  deferred2 = true;
468642
- }
468643
469172
  } else if (teleport.status === "failed") {
468644
469173
  const failureWasAdmitted = loadDurableQueuedInputEntries(listener).some(({ disposition, payload }) => (disposition === "queued" || disposition === "started") && payload.scope.agentId === record6.agentId && payload.scope.conversationId === record6.conversationId && payload.identity.domain === "teleport" && payload.identity.id === teleportId) || hasCompletedTeleportInput(listener, getConversationRuntimeKey(record6.agentId, record6.conversationId), teleportId);
468645
469174
  if (failureWasAdmitted && runningCompletion?.independentSuccessor && record6.revision) {
@@ -468650,9 +469179,8 @@ async function recoverRecordedTurns(listener, deps = {}) {
468650
469179
  if (!failureWasAdmitted || !recoveryRecord.teleport || !record6.revision) {
468651
469180
  deferred2 = true;
468652
469181
  } else if (recoveryRecord.teleport.readyRevision === record6.revision) {
468653
- if (!store3.remove(record6.agentId, record6.conversationId, record6.revision)) {
469182
+ if (!retireReadyTeleportRecord(store3, record6))
468654
469183
  deferred2 = true;
468655
- }
468656
469184
  } else {
468657
469185
  try {
468658
469186
  store3.write({ ...record6, teleportId: undefined, teleport: undefined }, record6.revision);
@@ -468662,6 +469190,11 @@ async function recoverRecordedTurns(listener, deps = {}) {
468662
469190
  }
468663
469191
  } else if (recoveryRecord.teleport && !recoveryRecord.teleport.ready && record6.revision) {
468664
469192
  const teleportIntent = recoveryRecord.teleport;
469193
+ const intentAuthority = teleportIntent.terminalAuthority;
469194
+ if (intentAuthority?.recoveryLineageId && (terminalAuthority?.lineageId !== intentAuthority.recoveryLineageId || terminalAuthority.revisionToken !== intentAuthority.authorityRevision)) {
469195
+ deferred2 = true;
469196
+ continue;
469197
+ }
468665
469198
  const eligibility2 = await resolveRecoveryEligibility(runtime, deps.canRecover);
468666
469199
  if (eligibility2 !== "owned" || !unchanged()) {
468667
469200
  deferred2 = true;
@@ -468682,6 +469215,7 @@ async function recoverRecordedTurns(listener, deps = {}) {
468682
469215
  continue;
468683
469216
  }
468684
469217
  try {
469218
+ const committedRevision = teleportIntent.committedRevision ?? teleportIntent.intentRevision ?? runningCompletion?.effectRevision ?? record6.revision;
468685
469219
  if (runningCompletion?.independentSuccessor) {
468686
469220
  store3.writeRecoveryLineageSnapshot({
468687
469221
  agentId: record6.agentId,
@@ -468691,19 +469225,23 @@ async function recoverRecordedTurns(listener, deps = {}) {
468691
469225
  teleport: {
468692
469226
  ...teleportIntent,
468693
469227
  ready: true,
468694
- committedRevision: runningCompletion.effectRevision ?? record6.revision
469228
+ committedRevision,
469229
+ preserveSuccessorWork: true
468695
469230
  }
468696
469231
  }
468697
469232
  });
469233
+ retireTeleportTerminalProof(recoveryRecord, committedRevision);
468698
469234
  } else {
468699
- store3.write({
469235
+ const readyRecord = store3.write({
468700
469236
  ...record6,
468701
469237
  teleport: {
468702
469238
  ...teleportIntent,
468703
469239
  ready: true,
468704
- committedRevision: record6.revision
469240
+ committedRevision,
469241
+ ...record6.revision !== committedRevision ? { preserveSuccessorWork: true } : {}
468705
469242
  }
468706
469243
  }, record6.revision);
469244
+ retireTeleportTerminalProof(readyRecord, committedRevision);
468707
469245
  }
468708
469246
  } catch {
468709
469247
  deferred2 = true;
@@ -468882,9 +469420,9 @@ async function recoverRecordedTurns(listener, deps = {}) {
468882
469420
  ...recoveryRecord,
468883
469421
  toolCallIds: owned.map((approval) => approval.toolCallId),
468884
469422
  results: approvals,
468885
- requestOtid: randomUUID54()
469423
+ requestOtid: randomUUID55()
468886
469424
  };
468887
- const recoveryLineageId = runningCompletion?.lineageId ?? randomUUID54();
469425
+ const recoveryLineageId = runningCompletion?.lineageId ?? randomUUID55();
468888
469426
  const persistedContinuation = runningCompletion ? {
468889
469427
  ...continuation,
468890
469428
  revision: recoveryRecord.revision,
@@ -469022,6 +469560,7 @@ var init_recover_recorded_turn = __esm(async () => {
469022
469560
  init_recovery_evidence(),
469023
469561
  init_recovery_ownership(),
469024
469562
  init_runtime6(),
469563
+ init_teleport_terminal_transfer(),
469025
469564
  init_turn(),
469026
469565
  init_turn_finished_replay()
469027
469566
  ]);
@@ -471279,7 +471818,7 @@ function createToolLifecycleTracker(onEvent2) {
471279
471818
  }
471280
471819
 
471281
471820
  // src/websocket/app-server-openai-turn.ts
471282
- import { randomUUID as randomUUID55 } from "node:crypto";
471821
+ import { randomUUID as randomUUID56 } from "node:crypto";
471283
471822
  function runBridgeTurn(params) {
471284
471823
  return runTurnImpl(params);
471285
471824
  }
@@ -471298,7 +471837,7 @@ async function ensureListenerRuntime(onLog) {
471298
471837
  if (active && !active.intentionallyClosed)
471299
471838
  return active;
471300
471839
  bridgeRuntimeStart ??= startLocalChannelListener({
471301
- connectionId: `openai-api-${randomUUID55()}`,
471840
+ connectionId: `openai-api-${randomUUID56()}`,
471302
471841
  deviceId: settingsManager.getOrCreateDeviceId(),
471303
471842
  connectionName: "openai-api",
471304
471843
  onConnected: () => {},
@@ -471507,11 +472046,11 @@ var init_app_server_openai_turn = __esm(async () => {
471507
472046
  });
471508
472047
 
471509
472048
  // src/websocket/app-server-openai-responses.ts
471510
- import { randomUUID as randomUUID56 } from "node:crypto";
472049
+ import { randomUUID as randomUUID57 } from "node:crypto";
471511
472050
  function createStoredResponseId(state2) {
471512
472051
  const cursor = Buffer.from(JSON.stringify({
471513
472052
  version: 1,
471514
- nonce: randomUUID56(),
472053
+ nonce: randomUUID57(),
471515
472054
  agent_id: state2.agentId,
471516
472055
  conversation_id: state2.conversationId
471517
472056
  })).toString("base64url");
@@ -471556,7 +472095,7 @@ function toBridgeMessages(messages, stateful) {
471556
472095
  return { messages: [], correlationOtid: null };
471557
472096
  }
471558
472097
  if (stateful) {
471559
- const otid = randomUUID56();
472098
+ const otid = randomUUID57();
471560
472099
  return {
471561
472100
  messages: [{ role: "user", content: lastUserContent, otid }],
471562
472101
  correlationOtid: otid
@@ -471578,7 +472117,7 @@ function toBridgeMessages(messages, stateful) {
471578
472117
  bridgeMessages.push({
471579
472118
  role: message2.role,
471580
472119
  content,
471581
- otid: randomUUID56()
472120
+ otid: randomUUID57()
471582
472121
  });
471583
472122
  }
471584
472123
  return {
@@ -471710,7 +472249,7 @@ class ResponseOutputBuilder {
471710
472249
  this.finishText();
471711
472250
  const result3 = {
471712
472251
  type: "function_call_output",
471713
- id: `fco_${randomUUID56()}`,
472252
+ id: `fco_${randomUUID57()}`,
471714
472253
  call_id: event.tool_call_id,
471715
472254
  output: [{ type: "input_text", text: event.output }],
471716
472255
  status: event.success ? "completed" : "incomplete"
@@ -471795,7 +472334,7 @@ class ResponseOutputBuilder {
471795
472334
  return this.message;
471796
472335
  const item = {
471797
472336
  type: "message",
471798
- id: `msg_${randomUUID56()}`,
472337
+ id: `msg_${randomUUID57()}`,
471799
472338
  status: "in_progress",
471800
472339
  role: "assistant",
471801
472340
  content: [{ type: "output_text", text: "", annotations: [] }]
@@ -471822,7 +472361,7 @@ class ResponseOutputBuilder {
471822
472361
  return this.reasoning;
471823
472362
  const item = {
471824
472363
  type: "reasoning",
471825
- id: `rs_${randomUUID56()}`,
472364
+ id: `rs_${randomUUID57()}`,
471826
472365
  status: "in_progress",
471827
472366
  summary: [{ type: "summary_text", text: "" }]
471828
472367
  };
@@ -471853,7 +472392,7 @@ class ResponseOutputBuilder {
471853
472392
  }
471854
472393
  const item = {
471855
472394
  type: "function_call",
471856
- id: `fc_${randomUUID56()}`,
472395
+ id: `fc_${randomUUID57()}`,
471857
472396
  call_id: callId,
471858
472397
  name,
471859
472398
  arguments: "",
@@ -471958,7 +472497,7 @@ async function handleResponses(request2, response, options) {
471958
472497
  sendOpenAiError(response, 500, "failed to create a conversation for this response", "server_error");
471959
472498
  return;
471960
472499
  }
471961
- const responseId = body3.store === true ? createStoredResponseId({ agentId: agent.id, conversationId }) : `resp_${randomUUID56()}`;
472500
+ const responseId = body3.store === true ? createStoredResponseId({ agentId: agent.id, conversationId }) : `resp_${randomUUID57()}`;
471962
472501
  const createdAt = Math.floor(Date.now() / 1000);
471963
472502
  let sequenceNumber = 0;
471964
472503
  let clientClosed = false;
@@ -472048,7 +472587,7 @@ var init_app_server_openai_responses = __esm(async () => {
472048
472587
  });
472049
472588
 
472050
472589
  // src/websocket/app-server-openai.ts
472051
- import { randomUUID as randomUUID57 } from "node:crypto";
472590
+ import { randomUUID as randomUUID58 } from "node:crypto";
472052
472591
  function isOpenAiCompatPath(pathname) {
472053
472592
  return pathname === MODELS_PATH || pathname === CHAT_COMPLETIONS_PATH || pathname === RESPONSES_PATH;
472054
472593
  }
@@ -472117,7 +472656,7 @@ async function handleChatCompletions(request2, response, options) {
472117
472656
  turnMessages.push({
472118
472657
  role: "user",
472119
472658
  content: userContent,
472120
- otid: randomUUID57()
472659
+ otid: randomUUID58()
472121
472660
  });
472122
472661
  } else {
472123
472662
  for (const message2 of body3.messages) {
@@ -472134,7 +472673,7 @@ async function handleChatCompletions(request2, response, options) {
472134
472673
  }
472135
472674
  if (content.length === 0)
472136
472675
  continue;
472137
- turnMessages.push({ role: message2.role, content, otid: randomUUID57() });
472676
+ turnMessages.push({ role: message2.role, content, otid: randomUUID58() });
472138
472677
  }
472139
472678
  }
472140
472679
  correlationOtid = turnMessages.at(-1)?.otid ?? null;
@@ -472143,7 +472682,7 @@ async function handleChatCompletions(request2, response, options) {
472143
472682
  return;
472144
472683
  }
472145
472684
  }
472146
- const completionId = `chatcmpl-${randomUUID57()}`;
472685
+ const completionId = `chatcmpl-${randomUUID58()}`;
472147
472686
  const created = Math.floor(Date.now() / 1000);
472148
472687
  const streaming3 = body3.stream === true;
472149
472688
  let clientClosed = false;
@@ -473635,7 +474174,7 @@ var init_listen = __esm(async () => {
473635
474174
  });
473636
474175
 
473637
474176
  // src/backend/local/transcript-migration.ts
473638
- import { randomUUID as randomUUID58 } from "node:crypto";
474177
+ import { randomUUID as randomUUID59 } from "node:crypto";
473639
474178
  import {
473640
474179
  copyFileSync as copyFileSync3,
473641
474180
  existsSync as existsSync65,
@@ -473675,7 +474214,7 @@ function writeSessionEntryJsonl(path47, messages, input) {
473675
474214
  ...messages.map((message2) => {
473676
474215
  const entry = {
473677
474216
  type: "message",
473678
- id: randomUUID58().slice(0, 8),
474217
+ id: randomUUID59().slice(0, 8),
473679
474218
  parentId,
473680
474219
  timestamp: message2.metadata?.created_at ?? new Date(message2.timestamp).toISOString(),
473681
474220
  message: message2
@@ -487024,13 +487563,13 @@ var init_headless_message_sender = __esm(() => {
487024
487563
  });
487025
487564
 
487026
487565
  // src/headless-response-state.ts
487027
- import { randomUUID as randomUUID59 } from "node:crypto";
487566
+ import { randomUUID as randomUUID60 } from "node:crypto";
487028
487567
  function createHeadlessResponseState() {
487029
487568
  let reusableInput = null;
487030
487569
  return {
487031
487570
  prepare(approvals, fullyAutoHandled) {
487032
487571
  const input = [
487033
- { type: "approval", approvals, otid: randomUUID59() }
487572
+ { type: "approval", approvals, otid: randomUUID60() }
487034
487573
  ];
487035
487574
  reusableInput = fullyAutoHandled ? input : null;
487036
487575
  return input;
@@ -487098,7 +487637,7 @@ function resolveListMessagesRoute(listReq, sessionConvId, sessionAgentId) {
487098
487637
  }
487099
487638
 
487100
487639
  // src/agent/bootstrap-handler.ts
487101
- import { randomUUID as randomUUID60 } from "node:crypto";
487640
+ import { randomUUID as randomUUID61 } from "node:crypto";
487102
487641
  async function handleBootstrapSessionState(params) {
487103
487642
  const {
487104
487643
  bootstrapReq,
@@ -487147,7 +487686,7 @@ async function handleBootstrapSessionState(params) {
487147
487686
  response: payload
487148
487687
  },
487149
487688
  session_id: sessionContext.sessionId,
487150
- uuid: randomUUID60()
487689
+ uuid: randomUUID61()
487151
487690
  };
487152
487691
  } catch (err) {
487153
487692
  return {
@@ -487158,7 +487697,7 @@ async function handleBootstrapSessionState(params) {
487158
487697
  error: err instanceof Error ? err.message : "bootstrap_session_state failed"
487159
487698
  },
487160
487699
  session_id: sessionContext.sessionId,
487161
- uuid: randomUUID60()
487700
+ uuid: randomUUID61()
487162
487701
  };
487163
487702
  }
487164
487703
  }
@@ -487209,7 +487748,7 @@ var init_headless_model_startup = __esm(() => {
487209
487748
  });
487210
487749
 
487211
487750
  // src/agent/list-messages-handler.ts
487212
- import { randomUUID as randomUUID61 } from "node:crypto";
487751
+ import { randomUUID as randomUUID62 } from "node:crypto";
487213
487752
  async function handleListMessages(params) {
487214
487753
  const {
487215
487754
  listReq,
@@ -487249,7 +487788,7 @@ async function handleListMessages(params) {
487249
487788
  response: payload
487250
487789
  },
487251
487790
  session_id: sessionId,
487252
- uuid: randomUUID61()
487791
+ uuid: randomUUID62()
487253
487792
  };
487254
487793
  } catch (err) {
487255
487794
  return {
@@ -487260,7 +487799,7 @@ async function handleListMessages(params) {
487260
487799
  error: err instanceof Error ? err.message : "list_messages failed"
487261
487800
  },
487262
487801
  session_id: sessionId,
487263
- uuid: randomUUID61()
487802
+ uuid: randomUUID62()
487264
487803
  };
487265
487804
  }
487266
487805
  }
@@ -487537,7 +488076,7 @@ var init_headless_enqueue_wait = __esm(() => {
487537
488076
  });
487538
488077
 
487539
488078
  // src/headless-cloud-send.ts
487540
- import { randomUUID as randomUUID62 } from "node:crypto";
488079
+ import { randomUUID as randomUUID63 } from "node:crypto";
487541
488080
  function shouldEnqueueCloudSend(values4, cloud, isAgentLaunch) {
487542
488081
  if (!cloud || isAgentLaunch || values4["new-agent"] || values4.ephemeral)
487543
488082
  return false;
@@ -487587,7 +488126,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
487587
488126
  const format6 = values4["output-format"] ?? "text";
487588
488127
  const noWait = Boolean(values4["no-wait"]);
487589
488128
  const started = Date.now();
487590
- const clientMessageId = values4["client-message-id"] ?? randomUUID62();
488129
+ const clientMessageId = values4["client-message-id"] ?? randomUUID63();
487591
488130
  const controller = new AbortController;
487592
488131
  const submissionTimeout = setTimeout(() => controller.abort(new Error("Cloud submission timed out; inspect the conversation before resending.")), 30000);
487593
488132
  const timeout = setTimeout(() => controller.abort(new Error("Stopped waiting; remote execution was not cancelled.")), deps.timeoutMs ?? resolveEnvironmentMaxWaitMs());
@@ -487631,11 +488170,14 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
487631
488170
  conversationId: env6.CONVERSATION_ID || env6.LETTA_CONVERSATION_ID
487632
488171
  }
487633
488172
  }, backend3, controller.signal));
487634
- const recovery = {
487635
- status_command: `letta messages status --agent ${agentId} --conversation ${conversationId}`,
487636
- messages_command: `letta messages list --agent ${agentId} --conversation ${conversationId}`
487637
- };
487638
- const events = noWait ? undefined : (await (deps.openStatusStream ?? openConversationStatusStream)(agentId, controller))[Symbol.asyncIterator]();
488173
+ if (!agentId && !noWait) {
488174
+ agentId = (await backend3.retrieveConversation(conversationId, {
488175
+ signal: controller.signal
488176
+ })).agent_id ?? undefined;
488177
+ if (!agentId)
488178
+ throw new Error("Could not determine the conversation's agent to wait for a reply; pass --agent or use --no-wait.");
488179
+ }
488180
+ const events = noWait || !agentId ? undefined : (await (deps.openStatusStream ?? openConversationStatusStream)(agentId, controller))[Symbol.asyncIterator]();
487639
488181
  const initial2 = events ? await events.next() : undefined;
487640
488182
  if (initial2?.done)
487641
488183
  throw new Error("Conversation status stream closed before submission; nothing was sent.");
@@ -487648,11 +488190,16 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
487648
488190
  computer
487649
488191
  }, AbortSignal.any([controller.signal, AbortSignal.timeout(30000)]));
487650
488192
  clearTimeout(submissionTimeout);
488193
+ agentId = receipt.agent_id ?? agentId;
488194
+ const recovery = buildAgentMessageRecoveryCommands({
488195
+ agentId,
488196
+ conversationId
488197
+ });
487651
488198
  if (noWait) {
487652
488199
  await writeObject({ ...receipt, ...recovery });
487653
488200
  return 0;
487654
488201
  }
487655
- if (!events || !initial2 || initial2.done)
488202
+ if (!events || !initial2 || initial2.done || !agentId)
487656
488203
  throw new Error("Missing conversation status subscription.");
487657
488204
  if (format6 === "stream-json") {
487658
488205
  const init = {
@@ -487667,7 +488214,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
487667
488214
  mcp_servers: [],
487668
488215
  permission_mode: "",
487669
488216
  slash_commands: [],
487670
- uuid: randomUUID62()
488217
+ uuid: randomUUID63()
487671
488218
  };
487672
488219
  await writeObject(init);
487673
488220
  }
@@ -487710,7 +488257,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
487710
488257
  duration_api_ms: 0,
487711
488258
  num_turns: 1,
487712
488259
  usage: null,
487713
- uuid: randomUUID62(),
488260
+ uuid: randomUUID63(),
487714
488261
  ...recovery
487715
488262
  });
487716
488263
  return 0;
@@ -487729,16 +488276,13 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
487729
488276
  run_ids: error5 instanceof EnqueuedWaitError ? error5.runIds : [],
487730
488277
  usage: null,
487731
488278
  stop_reason: "error",
487732
- uuid: randomUUID62(),
488279
+ uuid: randomUUID63(),
487733
488280
  status: receipt ? "wait_failed" : submissionAttempted && !(error5 instanceof ApiRequestError && error5.status >= 400 && error5.status < 500) ? "acceptance_unknown" : "submission_failed",
487734
488281
  agent_id: agentId ?? null,
487735
488282
  conversation_id: conversationId ?? "",
487736
488283
  client_message_id: clientMessageId,
487737
488284
  ...receipt ? { receipt } : {},
487738
- ...agentId && conversationId ? {
487739
- status_command: `letta messages status --agent ${agentId} --conversation ${conversationId}`,
487740
- messages_command: `letta messages list --agent ${agentId} --conversation ${conversationId}`
487741
- } : {},
488285
+ ...conversationId ? buildAgentMessageRecoveryCommands({ agentId, conversationId }) : {},
487742
488286
  ...error5 instanceof ApiRequestError ? { http_status: error5.status } : {}
487743
488287
  };
487744
488288
  if (format6 === "text")
@@ -488238,7 +488782,7 @@ __export(exports_headless, {
488238
488782
  decideInterruptAction: () => decideInterruptAction,
488239
488783
  __headlessTestUtils: () => __headlessTestUtils
488240
488784
  });
488241
- import { randomUUID as randomUUID63 } from "node:crypto";
488785
+ import { randomUUID as randomUUID64 } from "node:crypto";
488242
488786
  function trackHeadlessBoundaryError(errorType, error5, context3) {
488243
488787
  trackBoundaryError({
488244
488788
  errorType,
@@ -488260,7 +488804,7 @@ async function reportStartupErrorAndExit(errorType, error5, context3, outputForm
488260
488804
  message: message2,
488261
488805
  stop_reason: "error",
488262
488806
  session_id: "startup",
488263
- uuid: `startup-error-${randomUUID63()}`
488807
+ uuid: `startup-error-${randomUUID64()}`
488264
488808
  };
488265
488809
  await writeWireMessageAsync(errorMsg);
488266
488810
  } else {
@@ -488358,7 +488902,7 @@ async function emitHeadlessTurnStartCancellationOutput(options) {
488358
488902
  message: options.reason,
488359
488903
  stop_reason: "cancelled",
488360
488904
  session_id: options.sessionId,
488361
- uuid: `error-turn-start-cancel-${randomUUID63()}`
488905
+ uuid: `error-turn-start-cancel-${randomUUID64()}`
488362
488906
  };
488363
488907
  await writeWireMessageAsync(errorMsg);
488364
488908
  const resultMsg = {
@@ -488373,7 +488917,7 @@ async function emitHeadlessTurnStartCancellationOutput(options) {
488373
488917
  conversation_id: options.conversationId,
488374
488918
  run_ids: [],
488375
488919
  usage: null,
488376
- uuid: `result-turn-start-cancel-${randomUUID63()}`,
488920
+ uuid: `result-turn-start-cancel-${randomUUID64()}`,
488377
488921
  stop_reason: "cancelled"
488378
488922
  };
488379
488923
  await writeWireMessageAsync(resultMsg);
@@ -488402,7 +488946,7 @@ function writeBidirectionalTurnStartCancellation(options) {
488402
488946
  message: options.reason,
488403
488947
  stop_reason: "cancelled",
488404
488948
  session_id: options.sessionId,
488405
- uuid: `error-turn-start-cancel-${randomUUID63()}`
488949
+ uuid: `error-turn-start-cancel-${randomUUID64()}`
488406
488950
  };
488407
488951
  writeWireMessage(errorMsg);
488408
488952
  const resultMsg = {
@@ -488417,7 +488961,7 @@ function writeBidirectionalTurnStartCancellation(options) {
488417
488961
  conversation_id: options.conversationId,
488418
488962
  run_ids: [],
488419
488963
  usage: null,
488420
- uuid: `result-turn-start-cancel-${randomUUID63()}`,
488964
+ uuid: `result-turn-start-cancel-${randomUUID64()}`,
488421
488965
  stop_reason: "cancelled"
488422
488966
  };
488423
488967
  writeWireMessage(resultMsg);
@@ -489220,7 +489764,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489220
489764
  const approvalInput = {
489221
489765
  type: "approval",
489222
489766
  approvals: denialResults,
489223
- otid: randomUUID63()
489767
+ otid: randomUUID64()
489224
489768
  };
489225
489769
  const approvalMessages = [approvalInput];
489226
489770
  {
@@ -489233,7 +489777,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489233
489777
  type: "text",
489234
489778
  text: sc.content
489235
489779
  })),
489236
- otid: randomUUID63()
489780
+ otid: randomUUID64()
489237
489781
  });
489238
489782
  }
489239
489783
  }
@@ -489266,7 +489810,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489266
489810
  message: `Failed to resolve pending approvals on resume: ${approvalError instanceof Error ? approvalError.message : String(approvalError)}`,
489267
489811
  stop_reason: "error",
489268
489812
  session_id: sessionId,
489269
- uuid: `error-pre-loop-approval-${randomUUID63()}`
489813
+ uuid: `error-pre-loop-approval-${randomUUID64()}`
489270
489814
  };
489271
489815
  writeWireMessage(errorMsg);
489272
489816
  } else {
@@ -489339,7 +489883,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489339
489883
  content: contentParts,
489340
489884
  backend: backend3,
489341
489885
  onMessage: outputFormat === "stream-json" ? (message2) => {
489342
- const uuid5 = Reflect.get(message2, "otid") ?? Reflect.get(message2, "id") ?? randomUUID63();
489886
+ const uuid5 = Reflect.get(message2, "otid") ?? Reflect.get(message2, "id") ?? randomUUID64();
489343
489887
  writeWireMessage(includePartialMessages ? {
489344
489888
  type: "stream_event",
489345
489889
  event: message2,
@@ -489402,7 +489946,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489402
489946
  {
489403
489947
  role: "user",
489404
489948
  content: contentParts,
489405
- otid: randomUUID63()
489949
+ otid: randomUUID64()
489406
489950
  }
489407
489951
  ];
489408
489952
  const recoveredApprovalResults = queuedRecoveredApprovalResults ?? [];
@@ -489411,7 +489955,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489411
489955
  {
489412
489956
  type: "approval",
489413
489957
  approvals: recoveredApprovalResults,
489414
- otid: randomUUID63()
489958
+ otid: randomUUID64()
489415
489959
  },
489416
489960
  ...currentInput
489417
489961
  ];
@@ -489458,7 +490002,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489458
490002
  message: `Maximum turns limit reached (${buffers.usage.stepCount}/${maxTurns} steps)`,
489459
490003
  stop_reason: "max_steps",
489460
490004
  session_id: sessionId,
489461
- uuid: `error-max-turns-${randomUUID63()}`
490005
+ uuid: `error-max-turns-${randomUUID64()}`
489462
490006
  };
489463
490007
  await writeWireMessageAsync(errorMsg);
489464
490008
  } else {
@@ -489475,7 +490019,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489475
490019
  message: "Interrupted by SIGINT",
489476
490020
  stop_reason: "cancelled",
489477
490021
  session_id: sessionId,
489478
- uuid: `error-interrupted-${randomUUID63()}`
490022
+ uuid: `error-interrupted-${randomUUID64()}`
489479
490023
  };
489480
490024
  await writeWireMessageAsync(errorMsg);
489481
490025
  } else {
@@ -489504,7 +490048,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489504
490048
  type: "text",
489505
490049
  text: sc.content
489506
490050
  })),
489507
- otid: randomUUID63()
490051
+ otid: randomUUID64()
489508
490052
  }
489509
490053
  ];
489510
490054
  }
@@ -489550,7 +490094,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489550
490094
  recovery_type: "approval_pending",
489551
490095
  message: "Detected pending approval conflict on send; resolving before retry",
489552
490096
  session_id: sessionId,
489553
- uuid: `recovery-pre-stream-${randomUUID63()}`
490097
+ uuid: `recovery-pre-stream-${randomUUID64()}`
489554
490098
  };
489555
490099
  writeWireMessage(recoveryMsg);
489556
490100
  } else {
@@ -489583,7 +490127,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489583
490127
  max_attempts: CONVERSATION_BUSY_MAX_RETRIES,
489584
490128
  delay_ms: retryDelayMs,
489585
490129
  session_id: sessionId,
489586
- uuid: `retry-conversation-busy-${randomUUID63()}`
490130
+ uuid: `retry-conversation-busy-${randomUUID64()}`
489587
490131
  };
489588
490132
  writeWireMessage(retryMsg);
489589
490133
  } else {
@@ -489611,7 +490155,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489611
490155
  max_attempts: LLM_API_ERROR_MAX_RETRIES2,
489612
490156
  delay_ms: delayMs,
489613
490157
  session_id: sessionId,
489614
- uuid: `retry-pre-stream-${randomUUID63()}`
490158
+ uuid: `retry-pre-stream-${randomUUID64()}`
489615
490159
  };
489616
490160
  writeWireMessage(retryMsg);
489617
490161
  } else {
@@ -489637,7 +490181,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489637
490181
  stop_reason: "error",
489638
490182
  run_id: errorInfo.run_id,
489639
490183
  session_id: sessionId,
489640
- uuid: randomUUID63(),
490184
+ uuid: randomUUID64(),
489641
490185
  ...errorInfo.error_type && errorInfo.run_id && {
489642
490186
  api_error: {
489643
490187
  message_type: "error_message",
@@ -489659,7 +490203,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489659
490203
  message: "Detected pending approval conflict; auto-denying stale approval and retrying",
489660
490204
  run_id: recoveryRunId ?? undefined,
489661
490205
  session_id: sessionId,
489662
- uuid: `recovery-${recoveryRunId || randomUUID63()}`
490206
+ uuid: `recovery-${recoveryRunId || randomUUID64()}`
489663
490207
  };
489664
490208
  writeWireMessage(recoveryMsg);
489665
490209
  approvalPendingRecovery = true;
@@ -489677,7 +490221,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489677
490221
  type: "stream_event",
489678
490222
  event: chunk2,
489679
490223
  session_id: sessionId,
489680
- uuid: uuid5 || randomUUID63()
490224
+ uuid: uuid5 || randomUUID64()
489681
490225
  };
489682
490226
  writeWireMessage(streamEvent);
489683
490227
  } else {
@@ -489685,7 +490229,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489685
490229
  type: "message",
489686
490230
  ...chunk2,
489687
490231
  session_id: sessionId,
489688
- uuid: uuid5 || randomUUID63()
490232
+ uuid: uuid5 || randomUUID64()
489689
490233
  };
489690
490234
  writeWireMessage(msg);
489691
490235
  }
@@ -489730,7 +490274,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489730
490274
  {
489731
490275
  role: "user",
489732
490276
  content: continueMessage,
489733
- otid: randomUUID63()
490277
+ otid: randomUUID64()
489734
490278
  }
489735
490279
  ];
489736
490280
  const continueTurnStartEmission = await emitHeadlessTurnStart({
@@ -489832,7 +490376,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489832
490376
  delay_ms: 0,
489833
490377
  run_id: lastRunId ?? undefined,
489834
490378
  session_id: sessionId,
489835
- uuid: `retry-${lastRunId || randomUUID63()}`
490379
+ uuid: `retry-${lastRunId || randomUUID64()}`
489836
490380
  };
489837
490381
  writeWireMessage(retryMsg);
489838
490382
  } else {
@@ -489860,7 +490404,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489860
490404
  delay_ms: delayMs,
489861
490405
  run_id: lastRunId ?? undefined,
489862
490406
  session_id: sessionId,
489863
- uuid: `retry-${lastRunId || randomUUID63()}`
490407
+ uuid: `retry-${lastRunId || randomUUID64()}`
489864
490408
  };
489865
490409
  writeWireMessage(retryMsg);
489866
490410
  } else {
@@ -489881,7 +490425,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489881
490425
  message: "Tool call ID mismatch; fetching actual pending approvals and resyncing",
489882
490426
  run_id: lastRunId ?? undefined,
489883
490427
  session_id: sessionId,
489884
- uuid: `recovery-${lastRunId || randomUUID63()}`
490428
+ uuid: `recovery-${lastRunId || randomUUID64()}`
489885
490429
  };
489886
490430
  writeWireMessage(recoveryMsg);
489887
490431
  } else {
@@ -489898,7 +490442,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489898
490442
  stop_reason: stopReason,
489899
490443
  run_id: lastRunId ?? undefined,
489900
490444
  session_id: sessionId,
489901
- uuid: `error-${lastRunId || randomUUID63()}`
490445
+ uuid: `error-${lastRunId || randomUUID64()}`
489902
490446
  };
489903
490447
  await writeWireMessageAsync(errorMsg);
489904
490448
  } else {
@@ -489940,7 +490484,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489940
490484
  const nudgeMessage = {
489941
490485
  role: "user",
489942
490486
  content: `<system-reminder>The previous response was empty. Please provide a response with either text content or a tool call.</system-reminder>`,
489943
- otid: randomUUID63()
490487
+ otid: randomUUID64()
489944
490488
  };
489945
490489
  currentInput = [...currentInput, nudgeMessage];
489946
490490
  }
@@ -489953,7 +490497,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489953
490497
  delay_ms: delayMs,
489954
490498
  run_id: lastRunId ?? undefined,
489955
490499
  session_id: sessionId,
489956
- uuid: `retry-empty-${lastRunId || randomUUID63()}`
490500
+ uuid: `retry-empty-${lastRunId || randomUUID64()}`
489957
490501
  };
489958
490502
  writeWireMessage(retryMsg);
489959
490503
  } else {
@@ -489980,7 +490524,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
489980
490524
  delay_ms: delayMs,
489981
490525
  run_id: lastRunId ?? undefined,
489982
490526
  session_id: sessionId,
489983
- uuid: `retry-${lastRunId || randomUUID63()}`
490527
+ uuid: `retry-${lastRunId || randomUUID64()}`
489984
490528
  };
489985
490529
  writeWireMessage(retryMsg);
489986
490530
  } else {
@@ -490010,7 +490554,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
490010
490554
  delay_ms: delayMs,
490011
490555
  run_id: lastRunId ?? undefined,
490012
490556
  session_id: sessionId,
490013
- uuid: `retry-${lastRunId || randomUUID63()}`
490557
+ uuid: `retry-${lastRunId || randomUUID64()}`
490014
490558
  };
490015
490559
  writeWireMessage(retryMsg);
490016
490560
  } else {
@@ -490059,7 +490603,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
490059
490603
  stop_reason: stopReason,
490060
490604
  run_id: lastRunId ?? undefined,
490061
490605
  session_id: sessionId,
490062
- uuid: `error-${lastRunId || randomUUID63()}`
490606
+ uuid: `error-${lastRunId || randomUUID64()}`
490063
490607
  };
490064
490608
  await writeWireMessageAsync(errorMsg);
490065
490609
  } else {
@@ -490081,7 +490625,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
490081
490625
  stop_reason: "error",
490082
490626
  run_id: lastKnownRunId ?? undefined,
490083
490627
  session_id: sessionId,
490084
- uuid: `error-${lastKnownRunId || randomUUID63()}`
490628
+ uuid: `error-${lastKnownRunId || randomUUID64()}`
490085
490629
  };
490086
490630
  await writeWireMessageAsync(errorMsg);
490087
490631
  } else {
@@ -490280,7 +490824,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490280
490824
  const approvalInput = {
490281
490825
  type: "approval",
490282
490826
  approvals: denialResults,
490283
- otid: randomUUID63()
490827
+ otid: randomUUID64()
490284
490828
  };
490285
490829
  const approvalMessages = [approvalInput];
490286
490830
  {
@@ -490293,7 +490837,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490293
490837
  type: "text",
490294
490838
  text: sc.content
490295
490839
  })),
490296
- otid: randomUUID63()
490840
+ otid: randomUUID64()
490297
490841
  });
490298
490842
  }
490299
490843
  }
@@ -490351,7 +490895,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490351
490895
  reason,
490352
490896
  cleared_count: clearedCount,
490353
490897
  session_id: sessionId,
490354
- uuid: `q-clr-${randomUUID63()}`
490898
+ uuid: `q-clr-${randomUUID64()}`
490355
490899
  })
490356
490900
  }
490357
490901
  });
@@ -490381,7 +490925,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490381
490925
  reason: "runtime_busy",
490382
490926
  queue_len: Math.max(1, queueLen),
490383
490927
  session_id: sessionId,
490384
- uuid: `q-blk-${randomUUID63()}`
490928
+ uuid: `q-blk-${randomUUID64()}`
490385
490929
  });
490386
490930
  }
490387
490931
  function enqueueForTracking(input) {
@@ -490453,7 +490997,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490453
490997
  request_id: interruptRequestId
490454
490998
  },
490455
490999
  session_id: sessionId,
490456
- uuid: randomUUID63()
491000
+ uuid: randomUUID64()
490457
491001
  };
490458
491002
  writeWireMessage(interruptResponse);
490459
491003
  return;
@@ -490580,7 +491124,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490580
491124
  const approvalInput = {
490581
491125
  type: "approval",
490582
491126
  approvals: denialResults,
490583
- otid: randomUUID63()
491127
+ otid: randomUUID64()
490584
491128
  };
490585
491129
  const approvalStream = await sendScopedApprovalMessages({
490586
491130
  agentId: agent.id,
@@ -490619,7 +491163,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490619
491163
  message: "Invalid JSON input",
490620
491164
  stop_reason: "error",
490621
491165
  session_id: sessionId,
490622
- uuid: randomUUID63()
491166
+ uuid: randomUUID64()
490623
491167
  };
490624
491168
  writeWireMessage(errorMsg2);
490625
491169
  continue;
@@ -490645,7 +491189,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490645
491189
  }
490646
491190
  },
490647
491191
  session_id: sessionId,
490648
- uuid: randomUUID63()
491192
+ uuid: randomUUID64()
490649
491193
  };
490650
491194
  writeWireMessage(initResponse);
490651
491195
  } else if (subtype === "interrupt") {
@@ -490662,7 +491206,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490662
491206
  request_id: requestId ?? ""
490663
491207
  },
490664
491208
  session_id: sessionId,
490665
- uuid: randomUUID63()
491209
+ uuid: randomUUID64()
490666
491210
  };
490667
491211
  writeWireMessage(interruptResponse);
490668
491212
  } else if (subtype === "register_external_tools") {
@@ -490740,7 +491284,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490740
491284
  response: { registered: tools.length }
490741
491285
  },
490742
491286
  session_id: sessionId,
490743
- uuid: randomUUID63()
491287
+ uuid: randomUUID64()
490744
491288
  };
490745
491289
  writeWireMessage(registerResponse);
490746
491290
  } else if (subtype === "bootstrap_session_state") {
@@ -490796,7 +491340,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490796
491340
  response: recovery
490797
491341
  },
490798
491342
  session_id: sessionId,
490799
- uuid: randomUUID63()
491343
+ uuid: randomUUID64()
490800
491344
  };
490801
491345
  writeWireMessage(recoveryResponse);
490802
491346
  } catch (error5) {
@@ -490808,7 +491352,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490808
491352
  error: error5 instanceof Error ? error5.message : String(error5)
490809
491353
  },
490810
491354
  session_id: sessionId,
490811
- uuid: randomUUID63()
491355
+ uuid: randomUUID64()
490812
491356
  };
490813
491357
  writeWireMessage(recoveryError);
490814
491358
  }
@@ -490821,7 +491365,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490821
491365
  error: `Unknown control request subtype: ${subtype}`
490822
491366
  },
490823
491367
  session_id: sessionId,
490824
- uuid: randomUUID63()
491368
+ uuid: randomUUID64()
490825
491369
  };
490826
491370
  writeWireMessage(errorResponse);
490827
491371
  }
@@ -490876,7 +491420,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490876
491420
  try {
490877
491421
  const buffers = createBuffers(agent.id);
490878
491422
  const startTime = performance.now();
490879
- const userOtid = randomUUID63();
491423
+ const userOtid = randomUUID64();
490880
491424
  const userTranscriptText = extractTelemetryInputText(userContent);
490881
491425
  if (userTranscriptText.length > 0) {
490882
491426
  const userLineId = `user-${userOtid}`;
@@ -490942,7 +491486,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
490942
491486
  currentInput.unshift({
490943
491487
  role: "user",
490944
491488
  content: INTERRUPT_RECOVERY_ALERT,
490945
- otid: randomUUID63()
491489
+ otid: randomUUID64()
490946
491490
  });
490947
491491
  try {
490948
491492
  await resolveAllPendingApprovals();
@@ -491005,7 +491549,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491005
491549
  recovery_type: "approval_pending",
491006
491550
  message: "Detected pending approval conflict on send; resolving before retry",
491007
491551
  session_id: sessionId,
491008
- uuid: `recovery-bidir-${randomUUID63()}`
491552
+ uuid: `recovery-bidir-${randomUUID64()}`
491009
491553
  };
491010
491554
  writeWireMessage(recoveryMsg);
491011
491555
  await resolveAllPendingApprovals();
@@ -491028,7 +491572,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491028
491572
  max_attempts: LLM_API_ERROR_MAX_RETRIES2,
491029
491573
  delay_ms: delayMs,
491030
491574
  session_id: sessionId,
491031
- uuid: `retry-bidir-${randomUUID63()}`
491575
+ uuid: `retry-bidir-${randomUUID64()}`
491032
491576
  };
491033
491577
  writeWireMessage(retryMsg);
491034
491578
  await new Promise((resolve42) => setTimeout(resolve42, delayMs));
@@ -491050,7 +491594,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491050
491594
  stop_reason: "error",
491051
491595
  run_id: errorInfo.run_id,
491052
491596
  session_id: sessionId,
491053
- uuid: randomUUID63(),
491597
+ uuid: randomUUID64(),
491054
491598
  ...errorInfo.error_type && errorInfo.run_id && {
491055
491599
  api_error: {
491056
491600
  message_type: "error_message",
@@ -491078,7 +491622,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491078
491622
  type: "stream_event",
491079
491623
  event: chunk2,
491080
491624
  session_id: sessionId,
491081
- uuid: uuid5 || randomUUID63()
491625
+ uuid: uuid5 || randomUUID64()
491082
491626
  };
491083
491627
  writeWireMessage(streamEvent);
491084
491628
  } else {
@@ -491086,7 +491630,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491086
491630
  type: "message",
491087
491631
  ...chunk2,
491088
491632
  session_id: sessionId,
491089
- uuid: uuid5 || randomUUID63()
491633
+ uuid: uuid5 || randomUUID64()
491090
491634
  };
491091
491635
  writeWireMessage(msg);
491092
491636
  }
@@ -491223,7 +491767,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491223
491767
  message: errorDetails,
491224
491768
  stop_reason: "error",
491225
491769
  session_id: sessionId,
491226
- uuid: randomUUID63()
491770
+ uuid: randomUUID64()
491227
491771
  };
491228
491772
  writeWireMessage(errorMsg2);
491229
491773
  const errorResultMsg = {
@@ -491261,7 +491805,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
491261
491805
  message: `Unknown message type: ${message2.type}`,
491262
491806
  stop_reason: "error",
491263
491807
  session_id: sessionId,
491264
- uuid: randomUUID63()
491808
+ uuid: randomUUID64()
491265
491809
  };
491266
491810
  writeWireMessage(errorMsg);
491267
491811
  }
@@ -492752,7 +493296,7 @@ var init_reflection_arena_hf_upload = __esm(() => {
492752
493296
 
492753
493297
  // src/cli/helpers/reflection-arena.ts
492754
493298
  import { execFile as execFileCb5 } from "node:child_process";
492755
- import { randomInt as randomInt2, randomUUID as randomUUID64 } from "node:crypto";
493299
+ import { randomInt as randomInt2, randomUUID as randomUUID65 } from "node:crypto";
492756
493300
  import { appendFile as appendFile4, mkdir as mkdir19, readFile as readFile34, writeFile as writeFile22 } from "node:fs/promises";
492757
493301
  import { join as join109 } from "node:path";
492758
493302
  import { promisify as promisify20 } from "node:util";
@@ -493094,7 +493638,7 @@ async function startReflectionArenaRun(options) {
493094
493638
  }
493095
493639
  let releaseReservation = true;
493096
493640
  try {
493097
- const runId = randomUUID64().slice(0, 8);
493641
+ const runId = randomUUID65().slice(0, 8);
493098
493642
  const labels = shuffledLabels();
493099
493643
  const prepared = await Promise.all([
493100
493644
  prepareReflectionMemoryWorktreeLaunch({
@@ -512592,7 +513136,7 @@ var init_provider_selector_helpers = __esm(() => {
512592
513136
  });
512593
513137
 
512594
513138
  // src/cli/hooks/use-chatgpt-rate-limit-state.ts
512595
- import { randomUUID as randomUUID65 } from "node:crypto";
513139
+ import { randomUUID as randomUUID66 } from "node:crypto";
512596
513140
  function errorMessage7(error5, fallback) {
512597
513141
  return error5 instanceof Error ? error5.message : fallback;
512598
513142
  }
@@ -512689,7 +513233,7 @@ function useChatGPTRateLimitState(target2) {
512689
513233
  target: target2,
512690
513234
  providerName,
512691
513235
  resetId,
512692
- idempotencyKey: randomUUID65()
513236
+ idempotencyKey: randomUUID66()
512693
513237
  });
512694
513238
  if (!result3.success) {
512695
513239
  return { notice: { tone: "warning", message: result3.error.message } };
@@ -518776,12 +519320,12 @@ var init_ExitStats = __esm(async () => {
518776
519320
  });
518777
519321
 
518778
519322
  // src/cli/app/ids.ts
518779
- import { randomUUID as randomUUID66 } from "node:crypto";
519323
+ import { randomUUID as randomUUID67 } from "node:crypto";
518780
519324
  function uid(prefix) {
518781
519325
  return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
518782
519326
  }
518783
519327
  function createClientOtid() {
518784
- return randomUUID66();
519328
+ return randomUUID67();
518785
519329
  }
518786
519330
  function appendOptimisticUserLine(buffers, text3, otid) {
518787
519331
  if (!text3) {
@@ -522257,7 +522801,7 @@ var init_turn_input = __esm(() => {
522257
522801
  });
522258
522802
 
522259
522803
  // src/cli/app/use-approval-flow.ts
522260
- import { randomUUID as randomUUID67 } from "node:crypto";
522804
+ import { randomUUID as randomUUID68 } from "node:crypto";
522261
522805
  function useApprovalFlow(ctx) {
522262
522806
  const {
522263
522807
  abortControllerRef,
@@ -522763,7 +523307,7 @@ function useApprovalFlow(ctx) {
522763
523307
  {
522764
523308
  type: "approval",
522765
523309
  approvals: allResults,
522766
- otid: randomUUID67()
523310
+ otid: randomUUID68()
522767
523311
  }
522768
523312
  ]);
522769
523313
  } catch (error5) {
@@ -524151,7 +524695,7 @@ var init_system_reminders2 = __esm(() => {
524151
524695
  });
524152
524696
 
524153
524697
  // src/cli/app/use-conversation-loop.ts
524154
- import { randomUUID as randomUUID68 } from "node:crypto";
524698
+ import { randomUUID as randomUUID69 } from "node:crypto";
524155
524699
  function sleep12(ms) {
524156
524700
  return new Promise((resolve44) => setTimeout(resolve44, ms));
524157
524701
  }
@@ -524463,16 +525007,16 @@ function useConversationLoop(ctx) {
524463
525007
  currentInput = [
524464
525008
  ...lastSentInputRef.current.map((m4) => ({
524465
525009
  ...m4,
524466
- otid: randomUUID68()
525010
+ otid: randomUUID69()
524467
525011
  })),
524468
525012
  ...currentInput.map((m4) => m4.type === "message" && m4.role === "user" ? {
524469
525013
  ...m4,
524470
- otid: randomUUID68(),
525014
+ otid: randomUUID69(),
524471
525015
  content: [
524472
525016
  { type: "text", text: INTERRUPT_RECOVERY_ALERT },
524473
525017
  ...typeof m4.content === "string" ? [{ type: "text", text: m4.content }] : Array.isArray(m4.content) ? m4.content : []
524474
525018
  ]
524475
- } : { ...m4, otid: randomUUID68() })
525019
+ } : { ...m4, otid: randomUUID69() })
524476
525020
  ];
524477
525021
  pendingInterruptRecoveryConversationIdRef.current = null;
524478
525022
  lastSentInputRef.current = [
@@ -524511,7 +525055,7 @@ function useConversationLoop(ctx) {
524511
525055
  type: "text",
524512
525056
  text: sc.content
524513
525057
  })),
524514
- otid: randomUUID68()
525058
+ otid: randomUUID69()
524515
525059
  }
524516
525060
  ];
524517
525061
  }
@@ -524865,7 +525409,7 @@ ${feedback}
524865
525409
  });
524866
525410
  buffersRef.current.order.push(statusId);
524867
525411
  refreshDerived();
524868
- const hookMessageOtid = randomUUID68();
525412
+ const hookMessageOtid = randomUUID69();
524869
525413
  setTimeout(() => {
524870
525414
  processConversation([
524871
525415
  {
@@ -524892,7 +525436,7 @@ ${feedback}
524892
525436
  turnEndContinue = undefined;
524893
525437
  }
524894
525438
  if (turnEndContinue) {
524895
- const continueOtid = randomUUID68();
525439
+ const continueOtid = randomUUID69();
524896
525440
  setTimeout(() => {
524897
525441
  processConversation([
524898
525442
  {
@@ -525222,7 +525766,7 @@ ${feedback}
525222
525766
  {
525223
525767
  type: "approval",
525224
525768
  approvals: allResults,
525225
- otid: randomUUID68()
525769
+ otid: randomUUID69()
525226
525770
  }
525227
525771
  ], {
525228
525772
  allowReentry: true,
@@ -525426,7 +525970,7 @@ ${feedback}
525426
525970
  type: "message",
525427
525971
  role: "user",
525428
525972
  content: `<system-reminder>The previous response was empty. Please provide a response with either text content or a tool call.</system-reminder>`,
525429
- otid: randomUUID68()
525973
+ otid: randomUUID69()
525430
525974
  }
525431
525975
  ];
525432
525976
  }
@@ -525711,7 +526255,7 @@ var init_use_conversation_loop = __esm(async () => {
525711
526255
  });
525712
526256
 
525713
526257
  // src/cli/app/use-conversation-switching.ts
525714
- import { randomUUID as randomUUID69 } from "node:crypto";
526258
+ import { randomUUID as randomUUID70 } from "node:crypto";
525715
526259
  function useConversationSwitching(ctx) {
525716
526260
  const {
525717
526261
  abortControllerRef,
@@ -525786,7 +526330,7 @@ function useConversationSwitching(ctx) {
525786
526330
  {
525787
526331
  role: "user",
525788
526332
  content: question,
525789
- otid: randomUUID69()
526333
+ otid: randomUUID70()
525790
526334
  }
525791
526335
  ];
525792
526336
  let approvalRecoveryRetries = 0;
@@ -531253,7 +531797,7 @@ var init_conversation_switch_alert = __esm(() => {
531253
531797
  });
531254
531798
 
531255
531799
  // src/cli/app/use-submit-handler.ts
531256
- import { randomUUID as randomUUID70 } from "node:crypto";
531800
+ import { randomUUID as randomUUID71 } from "node:crypto";
531257
531801
  import { existsSync as existsSync81, readFileSync as readFileSync57, renameSync as renameSync13 } from "node:fs";
531258
531802
  import { tmpdir as tmpdir17 } from "node:os";
531259
531803
  import { join as join119 } from "node:path";
@@ -531587,7 +532131,7 @@ ${SYSTEM_REMINDER_CLOSE}` : "";
531587
532131
  content: buildTextParts(`${SYSTEM_REMINDER_OPEN}
531588
532132
  ${prompt}
531589
532133
  ${SYSTEM_REMINDER_CLOSE}`),
531590
- otid: randomUUID70()
532134
+ otid: randomUUID71()
531591
532135
  }
531592
532136
  ]);
531593
532137
  } catch (error5) {
@@ -531651,7 +532195,7 @@ ${SYSTEM_REMINDER_CLOSE}`),
531651
532195
  type: "message",
531652
532196
  role: "user",
531653
532197
  content: buildTextParts(buildModCommandPrompt(result4)),
531654
- otid: randomUUID70()
532198
+ otid: randomUUID71()
531655
532199
  }
531656
532200
  ]);
531657
532201
  } else if (result4.type === "output") {
@@ -531696,7 +532240,7 @@ ${SYSTEM_REMINDER_CLOSE}`),
531696
532240
  ${SYSTEM_REMINDER_OPEN}
531697
532241
  ${request3}
531698
532242
  ${SYSTEM_REMINDER_CLOSE}`),
531699
- otid: randomUUID70()
532243
+ otid: randomUUID71()
531700
532244
  }
531701
532245
  ]);
531702
532246
  } catch (error5) {
@@ -531965,7 +532509,7 @@ ${SYSTEM_REMINDER_CLOSE}`),
531965
532509
  ${SYSTEM_REMINDER_OPEN}
531966
532510
  ${request3}
531967
532511
  ${SYSTEM_REMINDER_CLOSE}`),
531968
- otid: randomUUID70()
532512
+ otid: randomUUID71()
531969
532513
  }
531970
532514
  ]);
531971
532515
  } catch (error5) {
@@ -532774,7 +533318,7 @@ ${SYSTEM_REMINDER_CLOSE}`;
532774
533318
  type: "message",
532775
533319
  role: "user",
532776
533320
  content: buildTextParts(skillMessage),
532777
- otid: randomUUID70()
533321
+ otid: randomUUID71()
532778
533322
  }
532779
533323
  ]);
532780
533324
  } catch (error5) {
@@ -533196,7 +533740,7 @@ Resumed reflection arena choice prompt for run ${run2.runId}.`, true);
533196
533740
  type: "message",
533197
533741
  role: "user",
533198
533742
  content: buildTextParts(initMessage),
533199
- otid: randomUUID70()
533743
+ otid: randomUUID71()
533200
533744
  }
533201
533745
  ]);
533202
533746
  } catch (error5) {
@@ -533229,7 +533773,7 @@ Resumed reflection arena choice prompt for run ${run2.runId}.`, true);
533229
533773
  type: "message",
533230
533774
  role: "user",
533231
533775
  content: buildTextParts(doctorMessage),
533232
- otid: randomUUID70()
533776
+ otid: randomUUID71()
533233
533777
  }
533234
533778
  ]);
533235
533779
  } catch (error5) {
@@ -533361,7 +533905,7 @@ Resumed reflection arena choice prompt for run ${run2.runId}.`, true);
533361
533905
  type: "message",
533362
533906
  role: "user",
533363
533907
  content: buildTextParts(wrapSkillPrompt2(matchedSkill.id, skillContent, userRequest)),
533364
- otid: randomUUID70()
533908
+ otid: randomUUID71()
533365
533909
  }
533366
533910
  ]);
533367
533911
  } catch (error5) {
@@ -541087,4 +541631,4 @@ function registerBunOAuthFlows() {
541087
541631
  registerBunOAuthFlows();
541088
541632
  await init_src5().then(() => exports_src2);
541089
541633
 
541090
- //# debugId=27D2CAFC27386FDE64756E2164756E21
541634
+ //# debugId=5DDB2959A60CDFCA64756E2164756E21