@letta-ai/letta-code 0.34.49 → 0.34.51

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 (74) hide show
  1. package/dist/app-server-client.cjs +32 -4
  2. package/dist/app-server-client.cjs.map +4 -4
  3. package/dist/app-server-client.js +32 -4
  4. package/dist/app-server-client.js.map +4 -4
  5. package/dist/mcp-client.js +2 -2
  6. package/dist/mcp-client.js.map +1 -1
  7. package/dist/mcp-oauth.js +2 -2
  8. package/dist/mcp-oauth.js.map +1 -1
  9. package/dist/types/agent/subagents/remote-turn-wait.d.ts.map +1 -1
  10. package/dist/types/app-server-client.d.ts.map +1 -1
  11. package/dist/types/headless-listener-launch.d.ts +2 -0
  12. package/dist/types/headless-listener-launch.d.ts.map +1 -1
  13. package/dist/types/runtime-context.d.ts +2 -0
  14. package/dist/types/runtime-context.d.ts.map +1 -1
  15. package/dist/types/tools/client-tool-background.d.ts +16 -0
  16. package/dist/types/tools/client-tool-background.d.ts.map +1 -0
  17. package/dist/types/tools/external-tool-background.d.ts +4 -1
  18. package/dist/types/tools/external-tool-background.d.ts.map +1 -1
  19. package/dist/types/tools/external-tool-execution.d.ts +9 -0
  20. package/dist/types/tools/external-tool-execution.d.ts.map +1 -0
  21. package/dist/types/tools/external-tool-types.d.ts +4 -0
  22. package/dist/types/tools/external-tool-types.d.ts.map +1 -1
  23. package/dist/types/tools/foreground-yield.d.ts +12 -0
  24. package/dist/types/tools/foreground-yield.d.ts.map +1 -0
  25. package/dist/types/tools/impl/bash.d.ts.map +1 -1
  26. package/dist/types/tools/impl/claude-stream-session.d.ts +1 -0
  27. package/dist/types/tools/impl/claude-stream-session.d.ts.map +1 -1
  28. package/dist/types/tools/impl/code-mode.d.ts.map +1 -1
  29. package/dist/types/tools/impl/codex-app-server.d.ts +1 -0
  30. package/dist/types/tools/impl/codex-app-server.d.ts.map +1 -1
  31. package/dist/types/tools/impl/exec-command.d.ts.map +1 -1
  32. package/dist/types/tools/impl/github-pull-request-cloud.d.ts +75 -0
  33. package/dist/types/tools/impl/github-pull-request-cloud.d.ts.map +1 -0
  34. package/dist/types/tools/impl/kill-bash.d.ts.map +1 -1
  35. package/dist/types/tools/impl/monitor.d.ts.map +1 -1
  36. package/dist/types/tools/impl/process_manager.d.ts +13 -1
  37. package/dist/types/tools/impl/process_manager.d.ts.map +1 -1
  38. package/dist/types/tools/impl/remote-external-coding-agent.d.ts.map +1 -1
  39. package/dist/types/tools/impl/send-agent-message.d.ts +6 -0
  40. package/dist/types/tools/impl/send-agent-message.d.ts.map +1 -1
  41. package/dist/types/tools/impl/stop-conversation-background.d.ts +4 -0
  42. package/dist/types/tools/impl/stop-conversation-background.d.ts.map +1 -0
  43. package/dist/types/tools/impl/subagent-stop-bridge.d.ts +7 -0
  44. package/dist/types/tools/impl/subagent-stop-bridge.d.ts.map +1 -0
  45. package/dist/types/tools/impl/task-abort-hook.d.ts.map +1 -1
  46. package/dist/types/tools/impl/task-stop.d.ts +2 -0
  47. package/dist/types/tools/impl/task-stop.d.ts.map +1 -1
  48. package/dist/types/tools/impl/wake.d.ts +6 -0
  49. package/dist/types/tools/impl/wake.d.ts.map +1 -1
  50. package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
  51. package/dist/types/tools/manager.d.ts +1 -0
  52. package/dist/types/tools/manager.d.ts.map +1 -1
  53. package/dist/types/tools/remote-external-tool-background.d.ts +15 -0
  54. package/dist/types/tools/remote-external-tool-background.d.ts.map +1 -0
  55. package/dist/types/tools/toolset-catalog.d.ts +1 -1
  56. package/dist/types/tools/toolset.d.ts +3 -0
  57. package/dist/types/tools/toolset.d.ts.map +1 -1
  58. package/dist/types/types/app-server-info.d.ts +2 -0
  59. package/dist/types/types/app-server-info.d.ts.map +1 -1
  60. package/dist/types/types/external-tool-protocol.d.ts +15 -0
  61. package/dist/types/types/external-tool-protocol.d.ts.map +1 -1
  62. package/dist/types/types/protocol_v2.d.ts +2 -2
  63. package/dist/types/types/protocol_v2.d.ts.map +1 -1
  64. package/dist/types/types/subagent-protocol.d.ts +6 -1
  65. package/dist/types/types/subagent-protocol.d.ts.map +1 -1
  66. package/dist/types/utils/confirm-process-exit.d.ts +3 -0
  67. package/dist/types/utils/confirm-process-exit.d.ts.map +1 -0
  68. package/dist/types/websocket/listener/durable-file-lock.d.ts.map +1 -1
  69. package/letta.js +1634 -778
  70. package/npm-shrinkwrap.json +137 -137
  71. package/package.json +2 -2
  72. package/scripts/source-file-size-baseline.json +1 -1
  73. package/skills/using-mcp-tools/SKILL.md +89 -1
  74. package/skills/using-mcp-tools/scripts/manage-managed-events.mjs +380 -0
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.49",
6080
+ version: "0.34.51",
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.",
@@ -6364,7 +6364,7 @@ var init_package = __esm(() => {
6364
6364
  },
6365
6365
  lettaLifecycleProtocol: 1,
6366
6366
  lettaRuntimeGraphProtocol: 1,
6367
- lettaRuntimeGraphSha512: "sha512-PelylmCwHLSQ4nNKA+M2dEtr1JsdzY5CQo8ewFdGCbwBGsYSkZRFrbSIHznoeAq3PLq98jM8R+FrPeKVr0mwsQ==",
6367
+ lettaRuntimeGraphSha512: "sha512-GmjJ/74vZNtDFKXmDwMpgzMjlFhHg/1Z6htsfHHXZr+/FV80SDbpEr4GPuCyAZc5FK8zl+SRkG4oIRQQQ1LalA==",
6368
6368
  patchedDependencies: {
6369
6369
  "@earendil-works/pi-ai@0.99.1": "patches/@earendil-works%2Fpi-ai@0.99.1.patch"
6370
6370
  }
@@ -212165,7 +212165,7 @@ var init_mcp_client = __esm(() => {
212165
212165
  init_streamableHttp();
212166
212166
  DEFAULT_CLIENT_INFO = {
212167
212167
  name: "letta-code",
212168
- version: "0.34.49"
212168
+ version: "0.34.51"
212169
212169
  };
212170
212170
  });
212171
212171
 
@@ -215644,7 +215644,7 @@ function prepareCandidate(lockPath, parent, owner) {
215644
215644
  function acquireDurableFileLock(path12, options = {}) {
215645
215645
  const waitMs = options.waitMs ?? 2000;
215646
215646
  const now2 = options.now ?? Date.now;
215647
- const owner = options.owner ?? currentDurableLockOwner(Math.max(1, Math.ceil(waitMs)));
215647
+ const owner = options.owner ?? currentDurableLockOwner();
215648
215648
  parseOwner(owner);
215649
215649
  const startedAt = now2();
215650
215650
  const remainingProbeTimeoutMs = () => {
@@ -216231,7 +216231,7 @@ This helps you catch type errors before making edits.
216231
216231
  var init_ReadLSP = () => {};
216232
216232
 
216233
216233
  // src/tools/descriptions/SendAgentMessage.md
216234
- var SendAgentMessage_default = 'Send a message without waiting for its answer. Use this to coordinate with an agent already working, including an Agent child, or to contact any conversation you are authorized to access. Letta-to-Letta messages require the Cloud backend and fail on the local backend (`agent-local-` IDs).\n\n- Supply `conversation_id` to message an existing thread, or `agent_id` alone to start a new hidden thread with that agent. To use an agent\'s default conversation, supply its `agent_id` and `conversation_id: "default"`. Pass the full conversation ID; truncated IDs are rejected.\n- Your agent and conversation IDs are attached automatically as the return address. To reply, the recipient must explicitly send to that address. Ordinary assistant output is not forwarded back to you.\n- A successful send means the message was accepted; the recipient may not have read it yet. Continue working rather than waiting for the answer.\n- External coding workers launched with Agent (including computer-qualified IDs from remote launches) can be messaged too. If the worker is mid-turn, the result says the message steered that turn; if it was idle, the result includes a `task_id` and you are notified when the new turn finishes.\n- Omit `computer` unless a particular computer is needed. If the conversation is active on A, selecting B is rejected rather than moving the conversation.\n- If delivery cannot be confirmed, check the recipient\'s messages before resending to avoid duplicates.\n- Keep sends sparse and useful: concise assignments, specific questions, or material updates. Skip status pings and repeated acknowledgments; repeat a point only when you have something new to add.\n- For work already underway, treat the agent doing it as its owner. Send what it needs, then let it decide. Do not take over or redo its work. If you think ownership should change, ask the human instead of declaring it in a message.\n\nIf you are a subagent, omitting both `agent_id` and `conversation_id` sends to your parent (the agent and conversation that launched you). Message your parent rarely: each message stays in both contexts, and your final report already reaches it. Send one only when a parent decision would otherwise force you to redo work, stating the default you will take, then keep working. Steering your own children is normal; message them as often as the work needs.\n\nOn the local backend, or from a script, use the CLI instead; it waits and prints the reply: `letta -p --from-agent $LETTA_AGENT_ID --conversation <conversation-id> --output-format json "message"` (add `--backend local` after `letta` for `agent-local-` IDs; `letta -p --help` lists options).\n';
216234
+ var SendAgentMessage_default = 'Send a message without waiting for its answer. Use this to coordinate with an agent already working, including an Agent child, or to contact any conversation you are authorized to access.\n\n- Supply `conversation_id` to message an existing thread, or `agent_id` alone to start a new hidden thread with that agent. To use an agent\'s default conversation, supply its `agent_id` and `conversation_id: "default"`. Pass the full conversation ID; truncated IDs are rejected.\n- Your agent and conversation IDs are attached automatically as the return address. To reply, the recipient must explicitly send to that address. Ordinary assistant output is not forwarded back to you.\n- A successful send means the message was accepted or delivery started; the recipient may not have read it yet. Continue working rather than waiting for the answer.\n- External coding workers launched with Agent (including computer-qualified IDs from remote launches) can be messaged too. If the worker is mid-turn, the result says the message steered that turn; if it was idle, the result includes a `task_id` and you are notified when the new turn finishes.\n- Omit `computer` unless a particular computer is needed. If the conversation is active on A, selecting B is rejected rather than moving the conversation.\n- If delivery cannot be confirmed, check the recipient\'s messages before resending to avoid duplicates.\n- Keep sends sparse and useful: concise assignments, specific questions, or material updates. Skip status pings and repeated acknowledgments; repeat a point only when you have something new to add.\n- For work already underway, treat the agent doing it as its owner. Send what it needs, then let it decide. Do not take over or redo its work. If you think ownership should change, ask the human instead of declaring it in a message.\n\nIf you are a subagent, omitting both `agent_id` and `conversation_id` sends to your parent (the agent and conversation that launched you). Message your parent rarely: each message stays in both contexts, and your final report already reaches it. Send one only when a parent decision would otherwise force you to redo work, stating the default you will take, then keep working. Steering your own children is normal; message them as often as the work needs.\n';
216235
216235
  var init_SendAgentMessage = () => {};
216236
216236
 
216237
216237
  // src/tools/descriptions/SetWorkingDirectory.md
@@ -217279,6 +217279,19 @@ async function ask_user_question_async(args) {
217279
217279
  }
217280
217280
  var init_ask_user_question = () => {};
217281
217281
 
217282
+ // src/tools/foreground-yield.ts
217283
+ function clampForegroundYieldMs(value) {
217284
+ return Math.max(MIN_FOREGROUND_YIELD_MS, Math.min(value, MAX_FOREGROUND_YIELD_MS));
217285
+ }
217286
+ function resolveForegroundYieldMs() {
217287
+ const value = getRuntimeContext()?.foregroundYieldMs;
217288
+ return typeof value === "number" && Number.isFinite(value) ? clampForegroundYieldMs(value) : DEFAULT_FOREGROUND_YIELD_MS;
217289
+ }
217290
+ var DEFAULT_FOREGROUND_YIELD_MS = 1e4, MIN_FOREGROUND_YIELD_MS = 1000, MAX_FOREGROUND_YIELD_MS = 30000;
217291
+ var init_foreground_yield = __esm(() => {
217292
+ init_runtime_context();
217293
+ });
217294
+
217282
217295
  // src/permissions/shell-analysis.ts
217283
217296
  function tryConsumeSafeRedirect(input, pos) {
217284
217297
  const isAppend = input.startsWith(">>", pos);
@@ -222174,7 +222187,7 @@ async function bash(args) {
222174
222187
  onOutput,
222175
222188
  secretEnv,
222176
222189
  parentScope,
222177
- foregroundYieldMs = DEFAULT_FOREGROUND_YIELD_MS
222190
+ foregroundYieldMs = resolveForegroundYieldMs()
222178
222191
  } = args;
222179
222192
  const userCwd = getCurrentWorkingDirectory();
222180
222193
  assertSafeWindowsCommand(command, {
@@ -222284,6 +222297,8 @@ async function bash(args) {
222284
222297
  });
222285
222298
  bgProcess = {
222286
222299
  process: runningProcess.process,
222300
+ completion: runningProcess.completion,
222301
+ terminate: runningProcess.terminate,
222287
222302
  command,
222288
222303
  stdout: [],
222289
222304
  stderr: [],
@@ -222422,10 +222437,11 @@ Output file: ${outputFile}`
222422
222437
  status: "success"
222423
222438
  };
222424
222439
  }
222425
- var cachedWorkingLauncher = null, DEFAULT_FOREGROUND_YIELD_MS = 1e4, shellProcessStarter, NOTIFICATION_TAIL_LINES = 50;
222440
+ var cachedWorkingLauncher = null, shellProcessStarter, NOTIFICATION_TAIL_LINES = 50;
222426
222441
  var init_bash = __esm(() => {
222427
222442
  init_constants2();
222428
222443
  init_runtime_context();
222444
+ init_foreground_yield();
222429
222445
  init_secret_substitution();
222430
222446
  init_message_queue_bridge();
222431
222447
  init_task_notifications();
@@ -224970,6 +224986,7 @@ function notificationText(toolReturn) {
224970
224986
  return scrubAmbientSecrets(String(toolReturn));
224971
224987
  }
224972
224988
  async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
224989
+ const label = options?.abortController ? "Tool" : "External tool";
224973
224990
  const signal = options?.signal;
224974
224991
  const runtime = options?.runtimeScope;
224975
224992
  const scope = options?.scope ?? (runtime?.agentId && runtime.conversationId ? {
@@ -224979,19 +224996,22 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
224979
224996
  } : undefined);
224980
224997
  const canBackground = () => typeof options?.canBackground === "function" ? options.canBackground() : options?.canBackground !== false;
224981
224998
  if (tool?.autoBackground !== true || !canBackground() || !scope || !options?.enqueue && !isQueueBridgeConnected())
224982
- return signal ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
224999
+ return signal && !options?.abortController ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
224983
225000
  const startedAt = Date.now();
224984
225001
  const settled = operation.then((result2) => ({ kind: "result", result: result2 }), (error5) => ({ kind: "error", error: error5 }));
224985
225002
  let timer;
224986
225003
  let onAbort;
224987
225004
  const abortSettled = signal ? new Promise((resolve21) => {
224988
225005
  onAbort = () => resolve21({ kind: "aborted" });
224989
- signal?.addEventListener("abort", onAbort);
225006
+ if (signal.aborted)
225007
+ onAbort();
225008
+ else
225009
+ signal.addEventListener("abort", onAbort);
224990
225010
  }) : undefined;
224991
225011
  const first = await Promise.race([
224992
225012
  settled,
224993
225013
  new Promise((resolve21) => {
224994
- timer = setTimeout(() => resolve21({ kind: "yield" }), options?.yieldMs ?? DEFAULT_EXTERNAL_TOOL_YIELD_MS);
225014
+ timer = setTimeout(() => resolve21({ kind: "yield" }), options?.yieldMs ?? resolveForegroundYieldMs());
224995
225015
  }),
224996
225016
  ...abortSettled ? [abortSettled] : []
224997
225017
  ]);
@@ -225001,33 +225021,79 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
225001
225021
  signal.removeEventListener("abort", onAbort);
225002
225022
  }
225003
225023
  if (first.kind === "aborted")
225004
- return interruptedExternalToolResult(toolName2);
225024
+ return options?.abortController ? operation : interruptedExternalToolResult(toolName2);
225005
225025
  if (first.kind === "result")
225006
225026
  return first.result;
225007
225027
  if (first.kind === "error")
225008
225028
  throw first.error;
225009
225029
  if (!canBackground()) {
225010
- return signal ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
225030
+ return signal && !options?.abortController ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
225011
225031
  }
225012
225032
  const taskId = `external_${crypto.randomUUID()}`;
225033
+ const outputFile = createBackgroundOutputFile(taskId);
225034
+ const entry = {
225035
+ process: { kill: () => options?.abortController?.abort() },
225036
+ command: toolName2,
225037
+ description: `${label} ${toolName2}`,
225038
+ kind: "tool",
225039
+ remote: !options?.abortController,
225040
+ status: "running",
225041
+ exitCode: null,
225042
+ startTime: new Date(startedAt),
225043
+ outputFile,
225044
+ runtimeScope: scope,
225045
+ actingUserId: scope.actingUserId,
225046
+ ...options?.remoteAbortController ? {
225047
+ cancel: async () => {
225048
+ options.remoteAbortController?.abort();
225049
+ const outcome = await settled;
225050
+ if (outcome.kind === "result" && outcome.result.cancellation === "cancelled") {
225051
+ return { killed: true, output: "Stopped" };
225052
+ }
225053
+ if (outcome.kind === "error" || outcome.result.cancellation === "timeout") {
225054
+ return {
225055
+ killed: false,
225056
+ output: "Cancellation was not confirmed; the remote tool may still finish."
225057
+ };
225058
+ }
225059
+ return {
225060
+ killed: false,
225061
+ output: `Already finished: ${notificationText(outcome.result.toolReturn)}`
225062
+ };
225063
+ }
225064
+ } : {}
225065
+ };
225066
+ backgroundProcesses.set(taskId, entry);
225067
+ options?.onBackground?.(outputFile);
225068
+ notifyBackgroundProcessStateChanged(scope);
225013
225069
  const enqueue = options?.enqueue ?? addToMessageQueue;
225014
225070
  settled.then(async (outcome) => {
225015
- if (await options?.shouldEnqueue?.() === false)
225016
- return;
225017
225071
  const result2 = outcome.kind === "result" ? outcome.result : undefined;
225018
225072
  const status = result2?.status === "success" ? "completed" : "failed";
225019
225073
  const richContent = Array.isArray(result2?.toolReturn) ? result2.toolReturn.map((part) => part.type === "text" ? { ...part, text: scrubAmbientSecrets(part.text) } : part) : undefined;
225020
225074
  let raw2 = result2 ? richContent ? "The tool result follows this notification as text and image parts." : notificationText(result2.toolReturn) : scrubAmbientSecrets(String(outcome.kind === "error" ? outcome.error : "Unknown error"));
225021
- if (status === "failed" && (!result2 || typeof result2.toolReturn === "string" && result2.toolReturn.startsWith("External tool execution error:")) && !raw2.includes("outcome is unknown")) {
225075
+ if (!options?.abortController && status === "failed" && (!result2 || typeof result2.toolReturn === "string" && result2.toolReturn.startsWith("External tool execution error:")) && !raw2.includes("outcome is unknown")) {
225022
225076
  raw2 += " The remote tool may still finish; its outcome is unknown. Check the destination before retrying a write.";
225023
225077
  }
225078
+ appendToOutputFile(outputFile, richContent ? `${richContent.map((part) => part.type === "text" ? part.text : "[Image result; see completion notification]").join(`
225079
+ `)}
225080
+ ` : `${raw2}
225081
+ `);
225082
+ if (!entry.completionNotificationSuppressed) {
225083
+ entry.status = status;
225084
+ entry.exitCode = status === "completed" ? 0 : 1;
225085
+ }
225086
+ scheduleBackgroundProcessCleanup(taskId);
225087
+ notifyBackgroundProcessStateChanged(scope);
225088
+ if (entry.completionNotificationSuppressed || await options?.shouldEnqueue?.() === false)
225089
+ return;
225024
225090
  const content = truncateByChars(raw2, LIMITS.TOOL_RETURN_MAX_CHARS + 1000, toolName2);
225025
225091
  enqueue({
225026
225092
  kind: "task_notification",
225027
225093
  text: formatTaskNotification({
225028
225094
  taskId,
225029
225095
  status,
225030
- summary: `External tool ${toolName2} ${status}`,
225096
+ summary: `${label} ${toolName2} ${status}`,
225031
225097
  result: content.content,
225032
225098
  usage: { durationMs: Date.now() - startedAt }
225033
225099
  }),
@@ -225037,17 +225103,70 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
225037
225103
  });
225038
225104
  return {
225039
225105
  status: "success",
225040
- toolReturn: `External tool ${toolName2} is still running. Task ID: ${taskId}. Its completion will arrive as a task notification. Do not retry an in-flight write or use this task ID as its result. A remote write cannot be cancelled by TaskStop.`
225106
+ toolReturn: `Tool ${toolName2} is still running with task ID: ${taskId}
225107
+ Output file: ${outputFile}
225108
+ You will be notified when it completes.`
225041
225109
  };
225042
225110
  }
225043
- var DEFAULT_EXTERNAL_TOOL_YIELD_MS = 1e4;
225044
225111
  var init_external_tool_background = __esm(() => {
225112
+ init_foreground_yield();
225113
+ init_process_manager();
225045
225114
  init_truncation();
225046
225115
  init_secret_substitution();
225047
225116
  init_message_queue_bridge();
225048
225117
  init_task_notifications();
225049
225118
  });
225050
225119
 
225120
+ // src/tools/client-tool-background.ts
225121
+ function autoBackgroundClientTool(name, operation, options, events) {
225122
+ const controller = new AbortController;
225123
+ const abort = () => controller.abort(options.signal?.reason);
225124
+ if (options.signal?.aborted)
225125
+ abort();
225126
+ else
225127
+ options.signal?.addEventListener("abort", abort, { once: true });
225128
+ let outputFile;
225129
+ const onOutput = (chunk2, stream11) => {
225130
+ options.onOutput?.(chunk2, stream11);
225131
+ if (outputFile)
225132
+ appendToOutputFile(outputFile, scrubAmbientSecrets(chunk2));
225133
+ };
225134
+ const pending2 = (typeof operation === "function" ? operation(controller.signal, onOutput) : operation).finally(() => options.signal?.removeEventListener("abort", abort));
225135
+ if (FOREGROUND_TOOLS.has(name) || SELF_BACKGROUNDING_TOOLS.has(name))
225136
+ return pending2;
225137
+ return runWithRuntimeContext(options.runtimeScope ?? {}, () => autoBackgroundExternalTool(name, { autoBackground: true }, pending2, {
225138
+ ...options,
225139
+ signal: controller.signal,
225140
+ abortController: controller,
225141
+ onBackground: (file) => {
225142
+ outputFile = file;
225143
+ },
225144
+ canBackground: () => !events || events.hasHandlers?.("tool_end") === false
225145
+ }));
225146
+ }
225147
+ var FOREGROUND_TOOLS, SELF_BACKGROUNDING_TOOLS;
225148
+ var init_client_tool_background = __esm(() => {
225149
+ init_runtime_context();
225150
+ init_external_tool_background();
225151
+ init_process_manager();
225152
+ init_secret_substitution();
225153
+ FOREGROUND_TOOLS = new Set([
225154
+ "Edit",
225155
+ "Memory",
225156
+ "Write",
225157
+ "ApplyPatch",
225158
+ "write_artifact_file",
225159
+ "SetWorkingDirectory",
225160
+ "EnterWorktree",
225161
+ "ExitWorktree",
225162
+ "UpdatePlan",
225163
+ "TaskCreate",
225164
+ "TaskUpdate",
225165
+ "AskUserQuestionAsync"
225166
+ ]);
225167
+ SELF_BACKGROUNDING_TOOLS = new Set(["Bash", "exec_command", "CodeMode"]);
225168
+ });
225169
+
225051
225170
  // src/tools/external-tool-background-eligibility.ts
225052
225171
  function enableListenerExternalToolBackground(tool, options) {
225053
225172
  listenerRegistrations.set(tool, options);
@@ -225074,34 +225193,6 @@ var init_external_tool_background_eligibility = __esm(() => {
225074
225193
  listenerRegistrations = new WeakMap;
225075
225194
  });
225076
225195
 
225077
- // src/tools/tool-context-retention.ts
225078
- function retainToolContext(contextId) {
225079
- holders.set(contextId, (holders.get(contextId) ?? 0) + 1);
225080
- }
225081
- function releaseRetainedToolContext(contextId) {
225082
- const count = (holders.get(contextId) ?? 0) - 1;
225083
- if (count > 0) {
225084
- holders.set(contextId, count);
225085
- return false;
225086
- }
225087
- holders.delete(contextId);
225088
- return deferredReleases.delete(contextId);
225089
- }
225090
- function isToolContextRetained(contextId) {
225091
- return holders.has(contextId);
225092
- }
225093
- function deferToolContextRelease(contextId) {
225094
- if (!holders.has(contextId))
225095
- return false;
225096
- deferredReleases.add(contextId);
225097
- return true;
225098
- }
225099
- var holders, deferredReleases;
225100
- var init_tool_context_retention = __esm(() => {
225101
- holders = new Map;
225102
- deferredReleases = new Set;
225103
- });
225104
-
225105
225196
  // src/tools/external-tool-content.ts
225106
225197
  function normalizeExternalToolResultContent(content) {
225107
225198
  const normalized = content.flatMap((part) => {
@@ -225130,6 +225221,128 @@ function normalizeExternalToolResultContent(content) {
225130
225221
  return text2 || JSON.stringify(content);
225131
225222
  }
225132
225223
 
225224
+ // src/tools/impl/tool-return-clamp.ts
225225
+ function clampToolReturnText(text2, toolName2) {
225226
+ if (text2.length <= LIMITS.TOOL_RETURN_MAX_CHARS) {
225227
+ return text2;
225228
+ }
225229
+ return truncateByChars(text2, LIMITS.TOOL_RETURN_MAX_CHARS, toolName2, {
225230
+ workingDirectory: getCurrentWorkingDirectory()
225231
+ }).content;
225232
+ }
225233
+ function clampRawToolReturn(rawResult, toolName2) {
225234
+ const text2 = typeof rawResult === "string" ? rawResult : rawResult != null ? JSON.stringify(rawResult) : "";
225235
+ if (text2.length <= LIMITS.TOOL_RETURN_MAX_CHARS + NOTICE_HEADROOM_CHARS) {
225236
+ return text2;
225237
+ }
225238
+ return clampToolReturnText(text2, toolName2 ?? "tool");
225239
+ }
225240
+ function clampToolReturnContent(content, toolName2) {
225241
+ if (typeof content === "string") {
225242
+ return clampToolReturnText(content, toolName2);
225243
+ }
225244
+ return content.map((block) => block.type === "text" ? { ...block, text: clampToolReturnText(block.text, toolName2) } : block);
225245
+ }
225246
+ var NOTICE_HEADROOM_CHARS = 1000;
225247
+ var init_tool_return_clamp = __esm(() => {
225248
+ init_runtime_context();
225249
+ init_truncation();
225250
+ });
225251
+
225252
+ // src/tools/external-tool-execution.ts
225253
+ async function executeExternalToolRequest(toolCallId, toolName2, input, executorOverride, toolDefinition, signal) {
225254
+ const executor = executorOverride;
225255
+ if (!executor) {
225256
+ return {
225257
+ toolReturn: `External tool executor not set for tool: ${toolName2}`,
225258
+ status: "error"
225259
+ };
225260
+ }
225261
+ const startedAt = Date.now();
225262
+ let success = false;
225263
+ try {
225264
+ const tool = toolDefinition;
225265
+ const result2 = await executor(toolCallId, toolName2, input, tool ? { tool, signal } : undefined);
225266
+ success = !result2.isError;
225267
+ return {
225268
+ toolReturn: clampToolReturnContent(normalizeExternalToolResultContent(result2.content), toolName2),
225269
+ status: result2.isError ? "error" : "success",
225270
+ ...result2.cancellation ? { cancellation: result2.cancellation } : {}
225271
+ };
225272
+ } catch (error5) {
225273
+ const errorMessage2 = error5 instanceof Error ? error5.message : String(error5);
225274
+ return {
225275
+ toolReturn: `External tool execution error: ${errorMessage2}`,
225276
+ status: "error"
225277
+ };
225278
+ } finally {
225279
+ if (toolName2 === "MessageChannel" || toolName2 === "message_channel") {
225280
+ telemetry.trackToolUsage(toolName2, success, Date.now() - startedAt, undefined, success ? undefined : "tool_error", undefined, messageChannelTelemetry(input));
225281
+ }
225282
+ }
225283
+ }
225284
+ var init_external_tool_execution = __esm(() => {
225285
+ init_telemetry();
225286
+ init_tool_return_clamp();
225287
+ });
225288
+
225289
+ // src/tools/external-tool-types.ts
225290
+ var EXTERNAL_TOOL_FOREGROUND_INTERRUPTED = "external_tool_foreground_interrupted";
225291
+
225292
+ // src/tools/remote-external-tool-background.ts
225293
+ async function autoBackgroundRemoteExternalTool(name, tool, execute, options) {
225294
+ if (!tool?.supportsCancellation) {
225295
+ return autoBackgroundExternalTool(name, tool, execute(options?.signal), options);
225296
+ }
225297
+ const controller = new AbortController;
225298
+ let backgrounded = false;
225299
+ const abort = () => controller.abort(backgrounded ? undefined : EXTERNAL_TOOL_FOREGROUND_INTERRUPTED);
225300
+ if (options?.signal?.aborted)
225301
+ abort();
225302
+ else
225303
+ options?.signal?.addEventListener("abort", abort, { once: true });
225304
+ const operation = execute(controller.signal).finally(() => options?.signal?.removeEventListener("abort", abort));
225305
+ return autoBackgroundExternalTool(name, tool, operation, {
225306
+ ...options,
225307
+ remoteAbortController: controller,
225308
+ onBackground: (outputFile) => {
225309
+ backgrounded = true;
225310
+ options?.onBackground?.(outputFile);
225311
+ }
225312
+ });
225313
+ }
225314
+ var init_remote_external_tool_background = __esm(() => {
225315
+ init_external_tool_background();
225316
+ });
225317
+
225318
+ // src/tools/tool-context-retention.ts
225319
+ function retainToolContext(contextId) {
225320
+ holders.set(contextId, (holders.get(contextId) ?? 0) + 1);
225321
+ }
225322
+ function releaseRetainedToolContext(contextId) {
225323
+ const count = (holders.get(contextId) ?? 0) - 1;
225324
+ if (count > 0) {
225325
+ holders.set(contextId, count);
225326
+ return false;
225327
+ }
225328
+ holders.delete(contextId);
225329
+ return deferredReleases.delete(contextId);
225330
+ }
225331
+ function isToolContextRetained(contextId) {
225332
+ return holders.has(contextId);
225333
+ }
225334
+ function deferToolContextRelease(contextId) {
225335
+ if (!holders.has(contextId))
225336
+ return false;
225337
+ deferredReleases.add(contextId);
225338
+ return true;
225339
+ }
225340
+ var holders, deferredReleases;
225341
+ var init_tool_context_retention = __esm(() => {
225342
+ holders = new Map;
225343
+ deferredReleases = new Set;
225344
+ });
225345
+
225133
225346
  // src/tools/filter.ts
225134
225347
  var exports_filter = {};
225135
225348
  __export(exports_filter, {
@@ -225214,34 +225427,6 @@ var init_hook_feedback = __esm(() => {
225214
225427
  init_debug();
225215
225428
  });
225216
225429
 
225217
- // src/tools/impl/tool-return-clamp.ts
225218
- function clampToolReturnText(text2, toolName2) {
225219
- if (text2.length <= LIMITS.TOOL_RETURN_MAX_CHARS) {
225220
- return text2;
225221
- }
225222
- return truncateByChars(text2, LIMITS.TOOL_RETURN_MAX_CHARS, toolName2, {
225223
- workingDirectory: getCurrentWorkingDirectory()
225224
- }).content;
225225
- }
225226
- function clampRawToolReturn(rawResult, toolName2) {
225227
- const text2 = typeof rawResult === "string" ? rawResult : rawResult != null ? JSON.stringify(rawResult) : "";
225228
- if (text2.length <= LIMITS.TOOL_RETURN_MAX_CHARS + NOTICE_HEADROOM_CHARS) {
225229
- return text2;
225230
- }
225231
- return clampToolReturnText(text2, toolName2 ?? "tool");
225232
- }
225233
- function clampToolReturnContent(content, toolName2) {
225234
- if (typeof content === "string") {
225235
- return clampToolReturnText(content, toolName2);
225236
- }
225237
- return content.map((block) => block.type === "text" ? { ...block, text: clampToolReturnText(block.text, toolName2) } : block);
225238
- }
225239
- var NOTICE_HEADROOM_CHARS = 1000;
225240
- var init_tool_return_clamp = __esm(() => {
225241
- init_runtime_context();
225242
- init_truncation();
225243
- });
225244
-
225245
225430
  // src/tools/permission-mode-state.ts
225246
225431
  function getEffectivePermissionModeState(permissionModeState) {
225247
225432
  return permissionModeState ?? {
@@ -232725,34 +232910,7 @@ function getExternalToolsAsClientTools() {
232725
232910
  }));
232726
232911
  }
232727
232912
  async function executeExternalTool(toolCallId, toolName2, input, executorOverride, toolDefinition, signal) {
232728
- const executor = executorOverride ?? getExternalToolExecutor();
232729
- if (!executor) {
232730
- return {
232731
- toolReturn: `External tool executor not set for tool: ${toolName2}`,
232732
- status: "error"
232733
- };
232734
- }
232735
- const startedAt = Date.now();
232736
- let success = false;
232737
- try {
232738
- const tool = toolDefinition ?? getExternalToolDefinition(toolName2);
232739
- const result2 = await executor(toolCallId, toolName2, input, tool ? { tool, signal } : undefined);
232740
- success = !result2.isError;
232741
- return {
232742
- toolReturn: clampToolReturnContent(normalizeExternalToolResultContent(result2.content), toolName2),
232743
- status: result2.isError ? "error" : "success"
232744
- };
232745
- } catch (error5) {
232746
- const errorMessage2 = error5 instanceof Error ? error5.message : String(error5);
232747
- return {
232748
- toolReturn: `External tool execution error: ${errorMessage2}`,
232749
- status: "error"
232750
- };
232751
- } finally {
232752
- if (toolName2 === "MessageChannel" || toolName2 === "message_channel") {
232753
- telemetry.trackToolUsage(toolName2, success, Date.now() - startedAt, undefined, success ? undefined : "tool_error", undefined, messageChannelTelemetry(input));
232754
- }
232755
- }
232913
+ return executeExternalToolRequest(toolCallId, toolName2, input, executorOverride ?? getExternalToolExecutor(), toolDefinition ?? getExternalToolDefinition(toolName2), signal);
232756
232914
  }
232757
232915
  function getClientToolsFromRegistry() {
232758
232916
  return buildClientToolsFromSnapshot(filterMemoryToolByMemoryFormat(toolRegistry, undefined), selectModelFacingExternalTools(filterExternalToolsByRuntimeContext(getExternalToolsRegistry(), {})), getAvailableModToolsRegistry());
@@ -233415,6 +233573,12 @@ async function executeToolInner(name, args, options) {
233415
233573
  workingDirectory: context3?.workingDirectory,
233416
233574
  permissionModeState: context3?.permissionModeState
233417
233575
  });
233576
+ const backgroundOptions = {
233577
+ shouldEnqueue: context3?.shouldEnqueueBackground,
233578
+ runtimeScope: executionScope,
233579
+ signal: options?.signal,
233580
+ onOutput: options?.onOutput
233581
+ };
233418
233582
  const workingDirectory = executionScope.workingDirectory ?? getCurrentWorkingDirectory();
233419
233583
  const scopedAgentId = executionScope.agentId ?? undefined;
233420
233584
  const modContext = context3?.modContext ?? toolExecutionModContext(executionScope, { workingDirectory });
@@ -233467,14 +233631,14 @@ async function executeToolInner(name, args, options) {
233467
233631
  return createModPermissionToolResult(permissionDecision2);
233468
233632
  }
233469
233633
  }
233470
- return executeModTool(name, modTool, eventArgs2, executionScope, {
233471
- signal: options?.signal,
233634
+ return autoBackgroundClientTool(name, (signal, onOutput) => executeModTool(name, modTool, eventArgs2, executionScope, {
233635
+ signal,
233472
233636
  toolCallId: options?.toolCallId,
233473
- onOutput: options?.onOutput,
233637
+ onOutput,
233474
233638
  workingDirectory,
233475
233639
  scopedAgentId,
233476
233640
  modContext
233477
- });
233641
+ }), backgroundOptions, modEvents);
233478
233642
  }
233479
233643
  if (activeExternalTools.has(name)) {
233480
233644
  const externalTool = activeExternalTools.get(name);
@@ -233504,7 +233668,10 @@ async function executeToolInner(name, args, options) {
233504
233668
  if (permissionDecision2?.decision !== undefined && permissionDecision2.decision !== "allow") {
233505
233669
  return createModPermissionToolResult(permissionDecision2);
233506
233670
  }
233507
- return runWithRuntimeContext(executionScope, () => autoBackgroundExternalTool(name, externalTool, executeExternalTool(options?.toolCallId ?? `ext-${Date.now()}`, name, eventArgs2, externalTool?.executor ?? activeExternalExecutor, externalTool, options?.signal), listenerExternalToolBackgroundOptions(externalTool, modEvents, executionScope, options?.signal)));
233671
+ if (externalTool?.executor && externalTool.autoBackground === undefined) {
233672
+ return runWithRuntimeContext(executionScope, () => autoBackgroundClientTool(name, (signal) => executeExternalTool(options?.toolCallId ?? `ext-${Date.now()}`, name, eventArgs2, externalTool.executor, externalTool, signal), backgroundOptions, modEvents));
233673
+ }
233674
+ return runWithRuntimeContext(executionScope, () => autoBackgroundRemoteExternalTool(name, externalTool, executeExternalTool.bind(null, options?.toolCallId ?? `ext-${Date.now()}`, name, eventArgs2, externalTool?.executor ?? activeExternalExecutor, externalTool), listenerExternalToolBackgroundOptions(externalTool, modEvents, executionScope, options?.signal)));
233508
233675
  }
233509
233676
  const internalName = resolveInternalToolName(name, activeRegistry);
233510
233677
  const tool = internalName ? activeRegistry.get(internalName) : undefined;
@@ -233552,7 +233719,7 @@ async function executeToolInner(name, args, options) {
233552
233719
  }
233553
233720
  }
233554
233721
  const startTime = Date.now();
233555
- const run = async () => {
233722
+ const run = async (signal, onOutput) => {
233556
233723
  const preHookResult = await runPreToolUseHooks(internalName, args, options?.toolCallId, workingDirectory, scopedAgentId);
233557
233724
  if (preHookResult.blocked) {
233558
233725
  const feedback = preHookResult.feedback.join(`
@@ -233575,15 +233742,13 @@ async function executeToolInner(name, args, options) {
233575
233742
  let outputStreamer = null;
233576
233743
  try {
233577
233744
  let enhancedArgs = expandPathArgs(internalName, args, workingDirectory);
233578
- if (options?.signal) {
233579
- enhancedArgs = { ...enhancedArgs, signal: options.signal };
233580
- }
233745
+ enhancedArgs = { ...enhancedArgs, signal };
233581
233746
  if (STREAMING_SHELL_TOOLS.has(internalName)) {
233582
233747
  const command = enhancedArgs.command ?? enhancedArgs.cmd;
233583
233748
  invocationSecrets = typeof command === "string" || Array.isArray(command) && command.every((part) => typeof part === "string") ? await resolveSecretEnvFromCommand(command, scopedAgentId) : {};
233584
233749
  invocationRedactions = captureSecretRedactions(scopedAgentId, invocationSecrets);
233585
- if (options?.onOutput) {
233586
- outputStreamer = createScrubbedOutputStreamer(invocationRedactions, options.onOutput, stripAnsi);
233750
+ if (onOutput) {
233751
+ outputStreamer = createScrubbedOutputStreamer(invocationRedactions, onOutput, stripAnsi);
233587
233752
  enhancedArgs = { ...enhancedArgs, onOutput: outputStreamer.onOutput };
233588
233753
  }
233589
233754
  if (Object.keys(invocationSecrets).length > 0) {
@@ -233683,7 +233848,7 @@ async function executeToolInner(name, args, options) {
233683
233848
  };
233684
233849
  }
233685
233850
  };
233686
- return runWithRuntimeContext(executionScope, run);
233851
+ return runWithRuntimeContext(executionScope, () => autoBackgroundClientTool(internalName, run, backgroundOptions, modEvents));
233687
233852
  }
233688
233853
  async function executeTool(...params) {
233689
233854
  const [name, args, options] = params;
@@ -233791,8 +233956,10 @@ var init_manager2 = __esm(() => {
233791
233956
  init_runtime_execution_settings();
233792
233957
  init_settings_manager();
233793
233958
  init_telemetry();
233794
- init_external_tool_background();
233959
+ init_client_tool_background();
233795
233960
  init_external_tool_background_eligibility();
233961
+ init_external_tool_execution();
233962
+ init_remote_external_tool_background();
233796
233963
  init_tool_context_retention();
233797
233964
  init_checkout_readiness();
233798
233965
  init_debug();
@@ -236067,7 +236234,7 @@ async function code_mode(args) {
236067
236234
  const {
236068
236235
  run_in_background = false,
236069
236236
  signal,
236070
- foregroundYieldMs = DEFAULT_FOREGROUND_YIELD_MS2
236237
+ foregroundYieldMs = resolveForegroundYieldMs()
236071
236238
  } = args;
236072
236239
  if (typeof args.code !== "string" || !args.code.trim()) {
236073
236240
  return {
@@ -236207,9 +236374,10 @@ Output file: ${outputFile}`,
236207
236374
  status: "success"
236208
236375
  };
236209
236376
  }
236210
- var DEFAULT_FOREGROUND_YIELD_MS2 = 1e4, MAX_NOTIFICATION_RESULT_CHARS = 30000;
236377
+ var MAX_NOTIFICATION_RESULT_CHARS = 30000;
236211
236378
  var init_code_mode = __esm(() => {
236212
236379
  init_constants2();
236380
+ init_foreground_yield();
236213
236381
  init_script_tool_scope();
236214
236382
  init_workflow_engine();
236215
236383
  init_message_queue_bridge();
@@ -239724,6 +239892,8 @@ async function startExecSession(args) {
239724
239892
  }
239725
239893
  backgroundProcesses.set(id2, {
239726
239894
  process: runningProcess.process,
239895
+ completion: runningProcess.completion,
239896
+ terminate: runningProcess.terminate,
239727
239897
  command: args.cmd,
239728
239898
  status: session3.status,
239729
239899
  exitCode: session3.exitCode,
@@ -239752,7 +239922,7 @@ async function exec_command(args) {
239752
239922
  throw new Error("cmd must be a non-empty string");
239753
239923
  }
239754
239924
  const session3 = await startExecSession(args);
239755
- const yieldTimeMs = clampYieldTime(args.yield_time_ms, DEFAULT_EXEC_YIELD_TIME_MS);
239925
+ const yieldTimeMs = clampYieldTime(args.yield_time_ms, resolveForegroundYieldMs());
239756
239926
  const { output, wallTimeMs } = await waitForSessionOutput({
239757
239927
  session: session3,
239758
239928
  startOffset: 0,
@@ -239848,10 +240018,11 @@ async function write_stdin(args) {
239848
240018
  output: scrubSecretsFromString(formattedOutput, session3.secrets)
239849
240019
  };
239850
240020
  }
239851
- var DEFAULT_EXEC_YIELD_TIME_MS = 1e4, DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250, MIN_YIELD_TIME_MS = 250, MIN_EMPTY_WRITE_STDIN_YIELD_TIME_MS = 5000, MAX_YIELD_TIME_MS = 30000, MAX_EMPTY_WRITE_STDIN_YIELD_TIME_MS = 300000, DEFAULT_MAX_OUTPUT_TOKENS = 1e4, MAX_INLINE_OUTPUT_CHARS, MAX_SESSION_OUTPUT_CHARS = 1e6, EXEC_SESSION_CLEANUP_MS, INTERRUPT = "\x03", execSessions;
240021
+ var DEFAULT_WRITE_STDIN_YIELD_TIME_MS = 250, MIN_YIELD_TIME_MS = 250, MIN_EMPTY_WRITE_STDIN_YIELD_TIME_MS = 5000, MAX_YIELD_TIME_MS = 30000, MAX_EMPTY_WRITE_STDIN_YIELD_TIME_MS = 300000, DEFAULT_MAX_OUTPUT_TOKENS = 1e4, MAX_INLINE_OUTPUT_CHARS, MAX_SESSION_OUTPUT_CHARS = 1e6, EXEC_SESSION_CLEANUP_MS, INTERRUPT = "\x03", execSessions;
239852
240022
  var init_exec_command = __esm(() => {
239853
240023
  init_usable_directory();
239854
240024
  init_runtime_context();
240025
+ init_foreground_yield();
239855
240026
  init_secret_substitution();
239856
240027
  init_message_queue_bridge();
239857
240028
  init_task_notifications();
@@ -242384,6 +242555,14 @@ async function wake(args, deps = {}) {
242384
242555
  });
242385
242556
  }
242386
242557
  }
242558
+ async function cancelConversationWakes(scope, deps = {}) {
242559
+ const current = await listCurrentWakes(scope, { action: "list" }, deps);
242560
+ if (current.warnings.length)
242561
+ throw new Error(current.warnings.join("; "));
242562
+ for (const record6 of current.wakes) {
242563
+ await cancelWake({ action: "cancel", id: record6.id }, scope, deps);
242564
+ }
242565
+ }
242387
242566
  var import_cron_parser2, MAX_ACTIVE_WAKES = 20, MIN_RECURRING_INTERVAL_MS, MAX_NAME_LENGTH = 80, MAX_PROMPT_LENGTH = 4000;
242388
242567
  var init_wake = __esm(() => {
242389
242568
  init_request();
@@ -243270,6 +243449,7 @@ function startCommandMonitor(args) {
243270
243449
  }
243271
243450
  });
243272
243451
  processState = {
243452
+ completion: runningProcess.completion,
243273
243453
  process: {
243274
243454
  kill(signal) {
243275
243455
  events.cancel();
@@ -244717,18 +244897,39 @@ function onceSocketEvent(socket, type3, listener) {
244717
244897
  });
244718
244898
  return detach;
244719
244899
  }
244720
- function waitForSocketOpen(socket) {
244900
+ function waitForSocketOpen(socket, timeoutMs) {
244721
244901
  if (socket.readyState === WEBSOCKET_OPEN_STATE) {
244722
244902
  return Promise.resolve();
244723
244903
  }
244724
- return new Promise((resolve35, reject2) => {
244904
+ return new Promise((resolvePromise, rejectPromise) => {
244905
+ let settled = false;
244906
+ const resolve35 = () => {
244907
+ if (settled)
244908
+ return;
244909
+ settled = true;
244910
+ resolvePromise();
244911
+ };
244912
+ const reject2 = (error5) => {
244913
+ if (settled)
244914
+ return;
244915
+ settled = true;
244916
+ rejectPromise(error5);
244917
+ };
244725
244918
  let detachOpen = () => {};
244726
244919
  let detachError = () => {};
244920
+ let detachClose = () => {};
244727
244921
  let detachResponse = () => {};
244728
244922
  let detachBody = () => {};
244923
+ let upgradeRejected = false;
244924
+ const timer = timeoutMs > 0 ? setTimeout(() => {
244925
+ cleanup();
244926
+ reject2(new Error(`App-server WebSocket failed to open: timed out after ${timeoutMs}ms`));
244927
+ }, timeoutMs) : undefined;
244729
244928
  const cleanup = () => {
244929
+ clearTimeout(timer);
244730
244930
  detachOpen();
244731
244931
  detachError();
244932
+ detachClose();
244732
244933
  detachResponse();
244733
244934
  detachBody();
244734
244935
  };
@@ -244740,6 +244941,7 @@ function waitForSocketOpen(socket) {
244740
244941
  const onResponse = (_request, response) => {
244741
244942
  if (!response)
244742
244943
  return;
244944
+ upgradeRejected = true;
244743
244945
  const request = _request;
244744
244946
  let body3 = Buffer.alloc(0);
244745
244947
  let finished2 = false;
@@ -244781,6 +244983,12 @@ function waitForSocketOpen(socket) {
244781
244983
  cleanup();
244782
244984
  reject2(new Error(`App-server WebSocket failed to open: ${String(event)}`));
244783
244985
  });
244986
+ detachClose = onceSocketEvent(socket, "close", () => {
244987
+ if (upgradeRejected)
244988
+ return;
244989
+ cleanup();
244990
+ reject2(new Error("App-server WebSocket failed to open: closed before opening"));
244991
+ });
244784
244992
  });
244785
244993
  }
244786
244994
  function rawEventData(event) {
@@ -244848,7 +245056,7 @@ class AppServerClient {
244848
245056
  });
244849
245057
  }
244850
245058
  async connect() {
244851
- await waitForSocketOpen(this.socket);
245059
+ await waitForSocketOpen(this.socket, this.requestTimeoutMs);
244852
245060
  return this;
244853
245061
  }
244854
245062
  close() {
@@ -245126,6 +245334,22 @@ function createAppServerClient(options) {
245126
245334
  var DEFAULT_REQUEST_TIMEOUT_MS = 30000, WEBSOCKET_OPEN_STATE = 1;
245127
245335
  var init_app_server_client = () => {};
245128
245336
 
245337
+ // src/tools/impl/subagent-stop-bridge.ts
245338
+ function registerLocalSubagentStop(connectionId, stop) {
245339
+ owners.set(connectionId, stop);
245340
+ return () => {
245341
+ if (owners.get(connectionId) === stop)
245342
+ owners.delete(connectionId);
245343
+ };
245344
+ }
245345
+ function stopLocalSubagent(connectionId, command) {
245346
+ return owners.get(connectionId)?.(command);
245347
+ }
245348
+ var owners;
245349
+ var init_subagent_stop_bridge = __esm(() => {
245350
+ owners = new Map;
245351
+ });
245352
+
245129
245353
  // src/headless-environment-response.ts
245130
245354
  function buildEnvironmentResponseMetadata(params) {
245131
245355
  return {
@@ -245297,6 +245521,50 @@ async function cancelAcceptedListenerInput(receipt) {
245297
245521
  client.close();
245298
245522
  }
245299
245523
  }
245524
+ async function stopAcceptedListenerConversation(receipt) {
245525
+ if (!receipt.connection_id)
245526
+ throw new Error("The owning listener is unknown");
245527
+ const scope = {
245528
+ agent_id: receipt.agent_id,
245529
+ conversation_id: receipt.conversation_id,
245530
+ acting_user_id: receipt.acting_user_id ?? undefined
245531
+ };
245532
+ try {
245533
+ await dequeueConversationMessage({
245534
+ agentId: getEnqueueAgentId(receipt),
245535
+ conversationId: receipt.conversation_id,
245536
+ clientMessageId: receipt.client_message_id,
245537
+ actingUserId: receipt.acting_user_id
245538
+ }, AbortSignal.timeout(1e4));
245539
+ } catch (error5) {
245540
+ if (!(error5 instanceof ApiRequestError && error5.status === 404))
245541
+ throw error5;
245542
+ }
245543
+ const command = {
245544
+ type: "subagent_stop",
245545
+ request_id: randomUUID37(),
245546
+ runtime: { ...scope, agent_id: getEnqueueAgentId(receipt) },
245547
+ agent_id: getEnqueueAgentId(receipt),
245548
+ conversation: scope,
245549
+ client_message_id: receipt.client_message_id
245550
+ };
245551
+ const requireStopped = (response) => {
245552
+ if (!response.success || !response.stopped || !response.cleanup_confirmed)
245553
+ throw new Error(response.error ?? "The listener did not confirm the stop");
245554
+ };
245555
+ const local = stopLocalSubagent(receipt.connection_id, command);
245556
+ if (local) {
245557
+ requireStopped(await local);
245558
+ return;
245559
+ }
245560
+ const client = await createListenerClient(receipt.connection_id, scope);
245561
+ try {
245562
+ await client.connect();
245563
+ requireStopped(await client.stopSubagent(command));
245564
+ } finally {
245565
+ client.close();
245566
+ }
245567
+ }
245300
245568
  async function launchListenerConversation(params, deps = {}) {
245301
245569
  const agentId = params.scope.agent_id ?? params.parentAgentId;
245302
245570
  if (!agentId)
@@ -245486,6 +245754,7 @@ var init_headless_listener_launch = __esm(() => {
245486
245754
  init_app_server_client();
245487
245755
  init_conversation_enqueue();
245488
245756
  init_request();
245757
+ init_subagent_stop_bridge();
245489
245758
  init_headless_environment_response();
245490
245759
  });
245491
245760
 
@@ -246041,6 +246310,15 @@ function recordRemoteRunProgress(messages, state2, subagentId) {
246041
246310
  }
246042
246311
  }
246043
246312
  async function collectRemoteTurnResult(receipt, state2, subagentId, signal = new AbortController().signal, deps = {}) {
246313
+ const task = [...backgroundTasks.values()].find((task2) => task2.subagentId === subagentId);
246314
+ let stopConfirmed = false;
246315
+ if (task) {
246316
+ task.remote = true;
246317
+ task.stop = async () => {
246318
+ await stopAcceptedListenerConversation(receipt);
246319
+ stopConfirmed = true;
246320
+ };
246321
+ }
246044
246322
  const startedAt = Date.now();
246045
246323
  updateSubagent(subagentId, {
246046
246324
  agentId: receipt.agent_id ?? undefined,
@@ -246087,7 +246365,7 @@ async function collectRemoteTurnResult(receipt, state2, subagentId, signal = new
246087
246365
  } catch (error5) {
246088
246366
  let detail = getErrorMessage2(error5);
246089
246367
  if (signal.aborted) {
246090
- const cancelled = await cancelAcceptedListenerInput(receipt).catch(() => false);
246368
+ const cancelled = stopConfirmed || await cancelAcceptedListenerInput(receipt).catch(() => false);
246091
246369
  detail = cancelled ? INTERRUPTED_BY_USER : `${INTERRUPTED_BY_USER} (could not confirm cancellation of remote Super Run ${receipt.super_run_id})`;
246092
246370
  }
246093
246371
  return {
@@ -246108,6 +246386,7 @@ var init_remote_turn_wait = __esm(() => {
246108
246386
  init_constants2();
246109
246387
  init_headless_listener_launch();
246110
246388
  init_headless_super_run_wait();
246389
+ init_process_manager();
246111
246390
  init_task_transcript();
246112
246391
  init_message_queue_bridge();
246113
246392
  init_task_notifications();
@@ -246178,6 +246457,284 @@ var init_child_send_tracking = __esm(() => {
246178
246457
  init_remote_turn_wait();
246179
246458
  });
246180
246459
 
246460
+ // src/mods/capabilities.ts
246461
+ function isModCapabilityId(value) {
246462
+ return MOD_CAPABILITY_ID_SET.has(value);
246463
+ }
246464
+ function resolveProcessModCapabilities(configuredCapabilities, env6 = process.env) {
246465
+ if (env6[LETTA_MOD_CAPABILITY_PROFILE_ENV] === PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE) {
246466
+ return cloneModCapabilities(PROVIDERS_ONLY_MOD_CAPABILITIES);
246467
+ }
246468
+ return resolveModCapabilities(configuredCapabilities);
246469
+ }
246470
+ function cloneModCapabilities(capabilities) {
246471
+ return {
246472
+ tools: capabilities.tools,
246473
+ commands: capabilities.commands,
246474
+ events: {
246475
+ lifecycle: capabilities.events.lifecycle,
246476
+ tools: capabilities.events.tools,
246477
+ turns: capabilities.events.turns,
246478
+ compact: capabilities.events.compact,
246479
+ llm: capabilities.events.llm
246480
+ },
246481
+ permissions: capabilities.permissions,
246482
+ providers: capabilities.providers,
246483
+ ui: {
246484
+ panels: capabilities.ui.panels
246485
+ }
246486
+ };
246487
+ }
246488
+ function resolveModCapabilities(capabilities) {
246489
+ return cloneModCapabilities(capabilities ?? DEFAULT_MOD_CAPABILITIES);
246490
+ }
246491
+ var MOD_CAPABILITY_IDS, MOD_CAPABILITY_ID_SET, DEFAULT_MOD_CAPABILITIES, DISABLED_MOD_CAPABILITIES, PROVIDERS_ONLY_MOD_CAPABILITIES, LETTA_MOD_CAPABILITY_PROFILE_ENV = "LETTA_MOD_CAPABILITY_PROFILE", PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE = "providers-only";
246492
+ var init_capabilities = __esm(() => {
246493
+ MOD_CAPABILITY_IDS = [
246494
+ "tools",
246495
+ "commands",
246496
+ "providers",
246497
+ "permissions",
246498
+ "events.lifecycle",
246499
+ "events.turns",
246500
+ "events.tools",
246501
+ "events.compact",
246502
+ "events.llm",
246503
+ "ui.panels"
246504
+ ];
246505
+ MOD_CAPABILITY_ID_SET = new Set(MOD_CAPABILITY_IDS);
246506
+ DEFAULT_MOD_CAPABILITIES = {
246507
+ tools: true,
246508
+ commands: true,
246509
+ events: {
246510
+ lifecycle: true,
246511
+ tools: true,
246512
+ turns: true,
246513
+ compact: true,
246514
+ llm: true
246515
+ },
246516
+ permissions: true,
246517
+ providers: true,
246518
+ ui: {
246519
+ panels: true
246520
+ }
246521
+ };
246522
+ DISABLED_MOD_CAPABILITIES = {
246523
+ tools: false,
246524
+ commands: false,
246525
+ events: {
246526
+ lifecycle: false,
246527
+ tools: false,
246528
+ turns: false,
246529
+ compact: false,
246530
+ llm: false
246531
+ },
246532
+ permissions: false,
246533
+ providers: false,
246534
+ ui: {
246535
+ panels: false
246536
+ }
246537
+ };
246538
+ PROVIDERS_ONLY_MOD_CAPABILITIES = {
246539
+ ...DISABLED_MOD_CAPABILITIES,
246540
+ events: { ...DISABLED_MOD_CAPABILITIES.events },
246541
+ providers: true,
246542
+ ui: { ...DISABLED_MOD_CAPABILITIES.ui }
246543
+ };
246544
+ });
246545
+
246546
+ // src/utils/transcript-paths.ts
246547
+ import { join as join62 } from "node:path";
246548
+ function getTranscriptRoot() {
246549
+ const envRoot = process.env[TRANSCRIPT_ROOT_ENV]?.trim();
246550
+ if (envRoot) {
246551
+ return envRoot;
246552
+ }
246553
+ return join62(resolveGlobalConfigDir(), "transcripts");
246554
+ }
246555
+ var TRANSCRIPT_ROOT_ENV = "LETTA_TRANSCRIPT_ROOT";
246556
+ var init_transcript_paths = __esm(() => {
246557
+ init_settings_path();
246558
+ });
246559
+
246560
+ // src/agent/subagents/memory-worker-session.ts
246561
+ function isMemoryWorkerSession(env6 = process.env) {
246562
+ return env6[MEMORY_WORKER_SESSION_ENV] === "1";
246563
+ }
246564
+ var MEMORY_WORKER_SESSION_ENV = "LETTA_MEMORY_WORKER_SESSION";
246565
+
246566
+ // src/agent/subagents/subagent-launcher.ts
246567
+ import { homedir as homedir18 } from "node:os";
246568
+ import { join as join63 } from "node:path";
246569
+ function resolveSubagentWorkingDirectory(env6 = process.env, fallbackCwd = getCurrentWorkingDirectory(), options = {}) {
246570
+ if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope) {
246571
+ return env6.USER_CWD || fallbackCwd;
246572
+ }
246573
+ if (options.subagentType !== "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope?.primaryRoot) {
246574
+ return options.memoryScope.primaryRoot;
246575
+ }
246576
+ const primaryRoot = options.memoryScope?.primaryRoot ?? options.inheritedPrimaryRoot;
246577
+ if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && primaryRoot) {
246578
+ return primaryRoot;
246579
+ }
246580
+ return env6.USER_CWD || fallbackCwd;
246581
+ }
246582
+ function resolveSubagentLauncher(cliArgs, options = {}) {
246583
+ const env6 = options.env ?? process.env;
246584
+ const argv = options.argv ?? process.argv;
246585
+ const execPath = options.execPath ?? process.execPath;
246586
+ const platform7 = options.platform ?? process.platform;
246587
+ const cwd2 = options.cwd ?? process.cwd();
246588
+ const invocation = resolveLettaInvocation(env6, argv, execPath, cwd2);
246589
+ if (invocation) {
246590
+ return {
246591
+ command: invocation.command,
246592
+ args: [...invocation.args, ...cliArgs]
246593
+ };
246594
+ }
246595
+ const currentScript = argv[1] || "";
246596
+ const resolvedCurrentScript = resolveEntryScriptPath(currentScript, cwd2);
246597
+ if (currentScript.endsWith(".ts")) {
246598
+ return {
246599
+ command: execPath,
246600
+ args: [resolvedCurrentScript, ...cliArgs]
246601
+ };
246602
+ }
246603
+ if (currentScript.endsWith(".js") && platform7 === "win32") {
246604
+ return {
246605
+ command: execPath,
246606
+ args: [resolvedCurrentScript, ...cliArgs]
246607
+ };
246608
+ }
246609
+ if (currentScript.endsWith(".js")) {
246610
+ return {
246611
+ command: resolvedCurrentScript,
246612
+ args: cliArgs
246613
+ };
246614
+ }
246615
+ return {
246616
+ command: "letta",
246617
+ args: cliArgs
246618
+ };
246619
+ }
246620
+ function resolveMemorySubagentScratchpad(parentProcessEnv, subagentId) {
246621
+ const configuredScratchpad = parentProcessEnv.LETTA_SCRATCHPAD;
246622
+ if (configuredScratchpad?.trim()) {
246623
+ return configuredScratchpad;
246624
+ }
246625
+ const configuredTranscriptRoot = parentProcessEnv[TRANSCRIPT_ROOT_ENV];
246626
+ const transcriptRoot = configuredTranscriptRoot?.trim() || join63(resolveGlobalConfigDir(parentProcessEnv, homedir18()), "transcripts");
246627
+ const scope = subagentId ? encodeURIComponent(subagentId) : crypto.randomUUID();
246628
+ return join63(transcriptRoot, "background", scope);
246629
+ }
246630
+ function composeSubagentChildEnv(options) {
246631
+ const {
246632
+ parentProcessEnv,
246633
+ listenerConnectionId,
246634
+ backendMode,
246635
+ localBackendStorageDir,
246636
+ parentAgentId,
246637
+ subagentType,
246638
+ launchProfile,
246639
+ inheritedPrimaryRoot,
246640
+ memoryScope,
246641
+ inheritedApiKey,
246642
+ inheritedBaseUrl,
246643
+ actingUserId,
246644
+ transcriptPath
246645
+ } = options;
246646
+ const childEnv = {
246647
+ ...parentProcessEnv,
246648
+ ...inheritedApiKey && { LETTA_API_KEY: inheritedApiKey },
246649
+ ...inheritedBaseUrl && { LETTA_BASE_URL: inheritedBaseUrl },
246650
+ DISABLE_AUTOUPDATER: "1",
246651
+ LETTA_CODE_AGENT_ROLE: "subagent",
246652
+ [MEMORY_WORKER_SESSION_ENV]: subagentType === "memory" ? "1" : undefined,
246653
+ [SUBAGENT_LAUNCH_ENV]: "1",
246654
+ [SUBAGENT_LAUNCH_PROFILE_ENV]: launchProfile ?? "default",
246655
+ ...(subagentType === "reflection" || subagentType === "memory") && {
246656
+ [LETTA_MOD_CAPABILITY_PROFILE_ENV]: PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE
246657
+ },
246658
+ LETTA_PARENT_AGENT_ID: parentAgentId,
246659
+ LETTA_PARENT_CONVERSATION_ID: options.parentConversationId,
246660
+ [SUBAGENT_DEPTH_ENV]: String(readSubagentDepth(parentProcessEnv) + 1),
246661
+ ...transcriptPath && { TRANSCRIPT_PATH: transcriptPath }
246662
+ };
246663
+ if (actingUserId)
246664
+ childEnv[ACTING_USER_ID_ENV] = actingUserId;
246665
+ else if (actingUserId === null)
246666
+ delete childEnv[ACTING_USER_ID_ENV];
246667
+ delete childEnv[SUBAGENT_NAME_ENV];
246668
+ if (options.subagentName)
246669
+ childEnv[SUBAGENT_NAME_ENV] = options.subagentName;
246670
+ if (backendMode === "local") {
246671
+ childEnv.LETTA_LOCAL_BACKEND_EXPERIMENTAL = "1";
246672
+ if (localBackendStorageDir) {
246673
+ childEnv.LETTA_LOCAL_BACKEND_DIR = localBackendStorageDir;
246674
+ }
246675
+ } else if (backendMode === "api") {
246676
+ childEnv.LETTA_LOCAL_BACKEND_EXPERIMENTAL = "0";
246677
+ }
246678
+ if (launchProfile === "memory-subagent") {
246679
+ delete childEnv[LISTENER_CONNECTION_ENV];
246680
+ childEnv.LETTA_SCRATCHPAD = resolveMemorySubagentScratchpad(parentProcessEnv, options.subagentId);
246681
+ const primaryRoot = memoryScope?.primaryRoot ?? inheritedPrimaryRoot;
246682
+ if (primaryRoot) {
246683
+ childEnv.MEMORY_DIR = primaryRoot;
246684
+ childEnv.LETTA_MEMORY_DIR = primaryRoot;
246685
+ } else {
246686
+ delete childEnv.MEMORY_DIR;
246687
+ delete childEnv.LETTA_MEMORY_DIR;
246688
+ }
246689
+ } else if (listenerConnectionId?.startsWith("conn-")) {
246690
+ childEnv[LISTENER_CONNECTION_ENV] = listenerConnectionId;
246691
+ } else if (isUnattachedListenerLaunch({
246692
+ listenerConnectionId,
246693
+ launchProfile,
246694
+ listenerConnectionCount: getActiveRuntime()?.connections.size ?? 0
246695
+ })) {
246696
+ trackBoundaryError({
246697
+ errorType: "subagent_launch_missing_listener_connection",
246698
+ error: new Error("Subagent launched in a listener without its connection"),
246699
+ context: "subagent_launch"
246700
+ });
246701
+ }
246702
+ return childEnv;
246703
+ }
246704
+ function isUnattachedListenerLaunch(options) {
246705
+ return !options.listenerConnectionId && options.launchProfile !== "memory-subagent" && options.listenerConnectionCount > 0;
246706
+ }
246707
+ function shouldLaunchThroughListener(options) {
246708
+ if (options.ephemeral) {
246709
+ if (options.computer)
246710
+ throw new Error("Ephemeral conversations cannot be routed to a Cloud computer");
246711
+ return false;
246712
+ }
246713
+ if (options.launchProfile === "memory-subagent") {
246714
+ if (options.computer)
246715
+ throw new Error("Memory subagents must run in their confined local process, not through a computer listener");
246716
+ return false;
246717
+ }
246718
+ return Boolean(options.computer) || options.cloudBackend && Boolean(options.connectionId);
246719
+ }
246720
+ function resolveSubagentInheritedPrimaryRoot(options) {
246721
+ if (options.backendMode === "local" && options.parentAgentId) {
246722
+ return getLocalBackendMemoryFilesystemRoot(options.parentAgentId, options.localBackendStorageDir ?? getLocalBackendStorageDir2());
246723
+ }
246724
+ return options.inheritedPrimaryRoot;
246725
+ }
246726
+ var init_subagent_launcher = __esm(() => {
246727
+ init_backend2();
246728
+ init_paths();
246729
+ init_capabilities();
246730
+ init_runtime_context();
246731
+ init_error_reporting();
246732
+ init_shell_env();
246733
+ init_settings_path();
246734
+ init_transcript_paths();
246735
+ init_runtime6();
246736
+ });
246737
+
246181
246738
  // src/backend/api/agent-message.ts
246182
246739
  function normalizeAgentMessageComputer(value) {
246183
246740
  if (value == null)
@@ -246217,7 +246774,7 @@ function validateAddress(value, kind) {
246217
246774
  return;
246218
246775
  if (kind === "conversation" && value === "default")
246219
246776
  return value;
246220
- const prefix = kind === "agent" ? "agent" : "conv";
246777
+ const prefix = kind === "agent" ? "agent" : "(local-)?conv";
246221
246778
  if (!new RegExp(`^${prefix}-[a-zA-Z0-9-]+$`).test(value)) {
246222
246779
  throw new Error(`Invalid ${kind} ID: ${JSON.stringify(value)}`);
246223
246780
  }
@@ -246373,13 +246930,28 @@ var init_subagent_process = __esm(() => {
246373
246930
  init_package_manager_spawn();
246374
246931
  });
246375
246932
 
246933
+ // src/utils/confirm-process-exit.ts
246934
+ async function confirmProcessExit(exit, name) {
246935
+ let timer;
246936
+ try {
246937
+ await Promise.race([
246938
+ exit,
246939
+ new Promise((_4, reject2) => {
246940
+ timer = setTimeout(() => reject2(new Error(`${name} process exit was not confirmed`)), 1e4);
246941
+ })
246942
+ ]);
246943
+ } finally {
246944
+ clearTimeout(timer);
246945
+ }
246946
+ }
246947
+
246376
246948
  // src/utils/native-cli-env.ts
246377
- import { homedir as homedir18 } from "node:os";
246378
- import { join as join62 } from "node:path";
246949
+ import { homedir as homedir19 } from "node:os";
246950
+ import { join as join64 } from "node:path";
246379
246951
  function withNativeCliPath(env6, platform7 = process.platform) {
246380
246952
  if (platform7 === "win32")
246381
246953
  return { ...env6 };
246382
- const nativeBin = join62(env6.HOME || homedir18(), ".local", "bin");
246954
+ const nativeBin = join64(env6.HOME || homedir19(), ".local", "bin");
246383
246955
  const paths = (env6.PATH ?? "/usr/bin:/bin").split(":");
246384
246956
  if (!paths.includes(nativeBin))
246385
246957
  paths.push(nativeBin);
@@ -246937,25 +247509,6 @@ import { createInterface as createInterface8 } from "node:readline";
246937
247509
  function errorMessage2(error5) {
246938
247510
  return error5 instanceof Error ? error5.message : String(error5);
246939
247511
  }
246940
- function userInput(prompt, uuid5) {
246941
- return `${JSON.stringify({
246942
- type: "user",
246943
- uuid: uuid5,
246944
- message: {
246945
- role: "user",
246946
- content: [{ type: "text", text: prompt }]
246947
- }
246948
- })}
246949
- `;
246950
- }
246951
- function interruptInput(requestId) {
246952
- return `${JSON.stringify({
246953
- type: "control_request",
246954
- request_id: requestId,
246955
- request: { subtype: "interrupt" }
246956
- })}
246957
- `;
246958
- }
246959
247512
  function buildClaudeStreamArgs(options) {
246960
247513
  const args = [
246961
247514
  "--print",
@@ -247091,7 +247644,8 @@ function writeInput(session3, prompt) {
247091
247644
  const uuid5 = randomUUID39();
247092
247645
  session3.latestInputUuid = uuid5;
247093
247646
  session3.latestInputStarted = false;
247094
- return writeRaw(session3.transport.process.stdin, userInput(prompt, uuid5));
247647
+ return writeRaw(session3.transport.process.stdin, `${JSON.stringify({ type: "user", uuid: uuid5, message: { role: "user", content: [{ type: "text", text: prompt }] } })}
247648
+ `);
247095
247649
  }
247096
247650
  function acknowledgeInput(session3, uuid5) {
247097
247651
  if (typeof uuid5 !== "string" || !session3.latestInputUuid)
@@ -247506,7 +248060,8 @@ async function steerSession(session3, prompt, signal) {
247506
248060
  }, CONTROL_RESPONSE_TIMEOUT_MS);
247507
248061
  timeout.unref?.();
247508
248062
  try {
247509
- await writeRaw(session3.transport.process.stdin, interruptInput(requestId));
248063
+ await writeRaw(session3.transport.process.stdin, `${JSON.stringify({ type: "control_request", request_id: requestId, request: { subtype: "interrupt" } })}
248064
+ `);
247510
248065
  await response;
247511
248066
  interruptAcknowledged = true;
247512
248067
  signal?.throwIfAborted();
@@ -247584,6 +248139,14 @@ async function sendClaudeMessage(options, deps = {}) {
247584
248139
  return { mode: "steered", sessionId: options.sessionId };
247585
248140
  return trackedReceipt(delivered.session);
247586
248141
  }
248142
+ async function stopClaudeSession(sessionId) {
248143
+ const session3 = sessions.get(sessionId);
248144
+ if (!session3)
248145
+ return false;
248146
+ session3.abortController.abort(new Error("Stopped by parent"));
248147
+ await confirmProcessExit(session3.exit, "Claude Code");
248148
+ return true;
248149
+ }
247587
248150
  var sessions, CONTROL_RESPONSE_TIMEOUT_MS = 30000, TURN_START_TIMEOUT_MS = 60000, BACKGROUND_TASK_WAIT_CAP_MS, SETTLED_EXIT_GRACE_MS = 1e4;
247588
248151
  var init_claude_stream_session = __esm(() => {
247589
248152
  init_subagent_process();
@@ -247761,21 +248324,20 @@ function textInput(text2) {
247761
248324
  return [{ type: "text", text: text2 }];
247762
248325
  }
247763
248326
  function spawnTransport(options) {
247764
- const [command = "codex", ...args] = wrapManagedWorkloadLauncher(["codex", ...options.configArgs ?? [], "app-server", "--stdio"], { env: options.env });
247765
- const child = getCommandProcessFactory()(command, args, {
247766
- cwd: options.cwd,
247767
- env: options.env,
247768
- stdio: ["pipe", "pipe", "pipe"],
247769
- windowsHide: true
248327
+ const controller = new AbortController;
248328
+ const { process: child, completion } = spawnManagedWorkloadProcess("codex", [...options.configArgs ?? [], "app-server", "--stdio"], {
248329
+ ...options,
248330
+ signal: controller.signal
247770
248331
  });
247771
248332
  return {
247772
248333
  stdin: child.stdin,
247773
248334
  stdout: child.stdout,
247774
248335
  stderr: child.stderr,
247775
- kill: () => process.platform === "win32" ? void killWindowsProcessTree(child) : child.kill(),
247776
- exited: new Promise((resolve35) => {
247777
- child.once("close", (code2, signal) => resolve35({ code: code2, signal }));
247778
- })
248336
+ kill: () => controller.abort(),
248337
+ exited: completion.then((exit) => ({
248338
+ code: exit.exitCode,
248339
+ signal: exit.exitSignal
248340
+ }))
247779
248341
  };
247780
248342
  }
247781
248343
 
@@ -247829,7 +248391,7 @@ class CodexAppServerClient {
247829
248391
  await this.request("initialize", {
247830
248392
  clientInfo: {
247831
248393
  name: "letta-code",
247832
- version: "0.34.49"
248394
+ version: "0.34.51"
247833
248395
  },
247834
248396
  capabilities: null
247835
248397
  });
@@ -247856,6 +248418,13 @@ class CodexAppServerClient {
247856
248418
  `);
247857
248419
  }
247858
248420
  }
248421
+ async stop() {
248422
+ if (!this.transport.exited)
248423
+ throw new Error("Codex process exit cannot be confirmed");
248424
+ this.transport.kill?.();
248425
+ await confirmProcessExit(this.transport.exited, "Codex");
248426
+ await this.close();
248427
+ }
247859
248428
  dispose() {
247860
248429
  this.transport.kill?.();
247861
248430
  this.close();
@@ -248341,11 +248910,19 @@ async function runCodexTurn(options, deps = {}) {
248341
248910
  };
248342
248911
  }
248343
248912
  }
248913
+ async function stopCodexSession(threadId) {
248914
+ const session3 = sessions2.get(threadId);
248915
+ if (!session3)
248916
+ return false;
248917
+ await session3.client.stop();
248918
+ if (sessions2.get(threadId) === session3)
248919
+ sessions2.delete(threadId);
248920
+ return true;
248921
+ }
248344
248922
  var sessions2, sessionCreations, DEFAULT_IDLE_TIMEOUT_MS, CODEX_NOT_SIGNED_IN_ERROR = "Codex is not signed in. Run `codex login` on this computer.";
248345
248923
  var init_codex_app_server = __esm(() => {
248346
248924
  init_subagent_process();
248347
248925
  init_native_cli_env();
248348
- init_package_manager_spawn();
248349
248926
  init_codex_app_server_payloads();
248350
248927
  init_external_llm_trace_launch();
248351
248928
  init_external_llm_trace_session();
@@ -248357,7 +248934,7 @@ var init_codex_app_server = __esm(() => {
248357
248934
  // src/tools/impl/cursor-session.ts
248358
248935
  import { randomUUID as randomUUID40 } from "node:crypto";
248359
248936
  import { existsSync as existsSync46 } from "node:fs";
248360
- import { join as join63 } from "node:path";
248937
+ import { join as join65 } from "node:path";
248361
248938
  import { createInterface as createInterface10 } from "node:readline";
248362
248939
  import { fileURLToPath as fileURLToPath7 } from "node:url";
248363
248940
  function key2(options, id2) {
@@ -248513,7 +249090,7 @@ async function runCursorTurn(options, env6 = process.env, secrets2 = {}) {
248513
249090
  type: "start",
248514
249091
  sessionId: id2,
248515
249092
  resume: !!options.resumeSessionId,
248516
- stateDir: join63(resolveGlobalConfigDir(), "cursor-sessions", sessionKey),
249093
+ stateDir: join65(resolveGlobalConfigDir(), "cursor-sessions", sessionKey),
248517
249094
  cwd: options.cwd,
248518
249095
  model: options.model,
248519
249096
  reminder: options.mcpReminder,
@@ -249572,8 +250149,8 @@ import {
249572
250149
  rm as rm8,
249573
250150
  stat as stat10
249574
250151
  } from "node:fs/promises";
249575
- import { homedir as homedir19, tmpdir as tmpdir13 } from "node:os";
249576
- import { join as join64 } from "node:path";
250152
+ import { homedir as homedir20, tmpdir as tmpdir13 } from "node:os";
250153
+ import { join as join66 } from "node:path";
249577
250154
  async function hashNativeSessionPrefix(input, size2) {
249578
250155
  const hash3 = createHash10("sha256");
249579
250156
  const buffer = Buffer.allocUnsafe(NATIVE_SESSION_CAPTURE_CHUNK_BYTES);
@@ -249658,7 +250235,7 @@ function scavengeStaleSpoolDirectories() {
249658
250235
  }
249659
250236
  }
249660
250237
  if (!ownerIsAlive)
249661
- cleanupSpoolDirectorySync(join64(tmpdir13(), entry.name));
250238
+ cleanupSpoolDirectorySync(join66(tmpdir13(), entry.name));
249662
250239
  }
249663
250240
  }
249664
250241
  function key3(source, sessionId) {
@@ -249809,11 +250386,11 @@ async function entries(path30, directories) {
249809
250386
  async function findNativeSessionPath(source, sessionId, env6 = process.env) {
249810
250387
  if (!UUID2.test(sessionId))
249811
250388
  return;
249812
- const home = env6.HOME || homedir19();
250389
+ const home = env6.HOME || homedir20();
249813
250390
  if (source === "claude_code") {
249814
- const projects = join64(env6.CLAUDE_CONFIG_DIR || join64(home, ".claude"), "projects");
250391
+ const projects = join66(env6.CLAUDE_CONFIG_DIR || join66(home, ".claude"), "projects");
249815
250392
  for (const project of await entries(projects, true)) {
249816
- const path30 = join64(projects, project, `${sessionId}.jsonl`);
250393
+ const path30 = join66(projects, project, `${sessionId}.jsonl`);
249817
250394
  try {
249818
250395
  if ((await stat10(path30)).isFile())
249819
250396
  return path30;
@@ -249824,14 +250401,14 @@ async function findNativeSessionPath(source, sessionId, env6 = process.env) {
249824
250401
  }
249825
250402
  return;
249826
250403
  }
249827
- const root2 = join64(env6.CODEX_HOME || join64(home, ".codex"), "sessions");
250404
+ const root2 = join66(env6.CODEX_HOME || join66(home, ".codex"), "sessions");
249828
250405
  for (const year of (await entries(root2, true)).filter((name) => /^\d{4}$/.test(name)))
249829
- for (const month of (await entries(join64(root2, year), true)).filter((name) => /^\d{2}$/.test(name)))
249830
- for (const day of (await entries(join64(root2, year, month), true)).filter((name) => /^\d{2}$/.test(name))) {
249831
- const directory = join64(root2, year, month, day);
250406
+ for (const month of (await entries(join66(root2, year), true)).filter((name) => /^\d{2}$/.test(name)))
250407
+ for (const day of (await entries(join66(root2, year, month), true)).filter((name) => /^\d{2}$/.test(name))) {
250408
+ const directory = join66(root2, year, month, day);
249832
250409
  for (const file of await entries(directory, false))
249833
250410
  if (file.startsWith("rollout-") && file.endsWith(`-${sessionId}.jsonl`))
249834
- return join64(directory, file);
250411
+ return join66(directory, file);
249835
250412
  }
249836
250413
  return;
249837
250414
  }
@@ -249848,9 +250425,9 @@ async function seal(state2, source, sessionId, scope, env6, requestOptions) {
249848
250425
  throw new Error("Native session file disappeared before EOF capture");
249849
250426
  throw error5;
249850
250427
  }
249851
- const directory = await mkdtemp4(join64(tmpdir13(), `letta-native-session-${process.pid}-${captureProcessInstanceId}-`));
250428
+ const directory = await mkdtemp4(join66(tmpdir13(), `letta-native-session-${process.pid}-${captureProcessInstanceId}-`));
249852
250429
  spoolDirectories.add(directory);
249853
- const spoolPath = join64(directory, "segment");
250430
+ const spoolPath = join66(directory, "segment");
249854
250431
  let output;
249855
250432
  let retained = false;
249856
250433
  try {
@@ -249967,7 +250544,7 @@ async function drain(state2, source, sessionId) {
249967
250544
  await spool.close();
249968
250545
  }
249969
250546
  state2.segments.shift();
249970
- const directory = join64(segment.path, "..");
250547
+ const directory = join66(segment.path, "..");
249971
250548
  await cleanupSpoolDirectory(directory);
249972
250549
  }
249973
250550
  }
@@ -249999,7 +250576,7 @@ async function discardRejectedSegment(state2) {
249999
250576
  const segment = state2.segments.shift();
250000
250577
  if (!segment)
250001
250578
  return;
250002
- const directory = join64(segment.path, "..");
250579
+ const directory = join66(segment.path, "..");
250003
250580
  await cleanupSpoolDirectory(directory);
250004
250581
  state2.ackedOffset = segment.end;
250005
250582
  state2.retryDelayMs = INITIAL_DRAIN_RETRY_MS;
@@ -250072,17 +250649,17 @@ function captureNativeSession(source, sessionId, scope, env6 = process.env, requ
250072
250649
  return sealing.then(() => startDrain(state2, source, sessionId));
250073
250650
  }
250074
250651
  function getNativeSessionOwner(source, sessionId) {
250075
- return owners.get(key3(source, sessionId));
250652
+ return owners2.get(key3(source, sessionId));
250076
250653
  }
250077
250654
  function rememberNativeSession(source, sessionId, scope, cloudUrl = getServerUrl()) {
250078
250655
  scavengeStaleSpoolDirectories();
250079
250656
  const id2 = key3(source, sessionId);
250080
- if (!owners.has(id2)) {
250081
- owners.set(id2, { ...scope });
250082
- if (owners.size > MAX_NATIVE_SESSION_OWNERS) {
250083
- const oldest = owners.keys().next().value;
250657
+ if (!owners2.has(id2)) {
250658
+ owners2.set(id2, { ...scope });
250659
+ if (owners2.size > MAX_NATIVE_SESSION_OWNERS) {
250660
+ const oldest = owners2.keys().next().value;
250084
250661
  if (oldest !== undefined)
250085
- owners.delete(oldest);
250662
+ owners2.delete(oldest);
250086
250663
  }
250087
250664
  }
250088
250665
  if (!states2.has(id2) && UUID2.test(sessionId) && isCloudServerUrl(cloudUrl))
@@ -250102,7 +250679,7 @@ function reportNativeSessionCaptureFailure(source, sessionId, error5) {
250102
250679
  const reason = error5 instanceof ApiRequestError ? `HTTP ${error5.status}` : error5 instanceof Error ? error5.name : "unknown error";
250103
250680
  debugWarn("native-session", `${source} ${sessionId}: upload failed (${reason})`);
250104
250681
  }
250105
- var NativeChunkAcknowledgmentError, NativeSessionSourceGrowthError, states2, admissions, spoolDirectories, captureProcessInstanceId, activeInstanceRegistryKey, activeCaptureInstances, spoolDirectoryName, staleSpoolsScavenged = false, sealHookForTests, prefixVerificationHookForTests, drainHookForTests, NATIVE_SESSION_CAPTURE_CHUNK_BYTES, INITIAL_DRAIN_RETRY_MS = 250, MAX_DRAIN_RETRY_MS = 30000, SEAL_RETRY_DELAYS_MS, UUID2, MAX_NATIVE_SESSION_OWNERS = 1024, owners;
250682
+ var NativeChunkAcknowledgmentError, NativeSessionSourceGrowthError, states2, admissions, spoolDirectories, captureProcessInstanceId, activeInstanceRegistryKey, activeCaptureInstances, spoolDirectoryName, staleSpoolsScavenged = false, sealHookForTests, prefixVerificationHookForTests, drainHookForTests, NATIVE_SESSION_CAPTURE_CHUNK_BYTES, INITIAL_DRAIN_RETRY_MS = 250, MAX_DRAIN_RETRY_MS = 30000, SEAL_RETRY_DELAYS_MS, UUID2, MAX_NATIVE_SESSION_OWNERS = 1024, owners2;
250106
250683
  var init_native_session_capture = __esm(() => {
250107
250684
  init_request();
250108
250685
  init_server_url();
@@ -250140,7 +250717,7 @@ var init_native_session_capture = __esm(() => {
250140
250717
  cleanupSpoolDirectorySync(directory);
250141
250718
  }
250142
250719
  });
250143
- owners = new Map;
250720
+ owners2 = new Map;
250144
250721
  });
250145
250722
 
250146
250723
  // src/tools/impl/opencode-server.ts
@@ -251375,23 +251952,9 @@ var init_fork_conversation = __esm(() => {
251375
251952
  init_subagent_model();
251376
251953
  });
251377
251954
 
251378
- // src/utils/transcript-paths.ts
251379
- import { join as join65 } from "node:path";
251380
- function getTranscriptRoot() {
251381
- const envRoot = process.env[TRANSCRIPT_ROOT_ENV]?.trim();
251382
- if (envRoot) {
251383
- return envRoot;
251384
- }
251385
- return join65(resolveGlobalConfigDir(), "transcripts");
251386
- }
251387
- var TRANSCRIPT_ROOT_ENV = "LETTA_TRANSCRIPT_ROOT";
251388
- var init_transcript_paths = __esm(() => {
251389
- init_settings_path();
251390
- });
251391
-
251392
251955
  // src/agent/subagents/sandbox.ts
251393
251956
  import { mkdirSync as mkdirSync35 } from "node:fs";
251394
- import { join as join66 } from "node:path";
251957
+ import { join as join67 } from "node:path";
251395
251958
  function wrapSubagentLauncher(input) {
251396
251959
  const env6 = input.env ?? process.env;
251397
251960
  if (!isFsSandboxEnabled(env6))
@@ -251434,7 +251997,7 @@ function wrapSubagentLauncher(input) {
251434
251997
  if (!wrapped || wrapped.length === 0)
251435
251998
  return null;
251436
251999
  const [command, ...args] = wrapped;
251437
- const scratchRoot = join66(getLettaHomeRoot(), "tmp");
252000
+ const scratchRoot = join67(getLettaHomeRoot(), "tmp");
251438
252001
  mkdirSync35(scratchRoot, { recursive: true });
251439
252002
  return {
251440
252003
  command,
@@ -251537,270 +252100,6 @@ var init_context_budget = __esm(() => {
251537
252100
  REFLECTION_STARTUP_CONTEXT_CHAR_LIMIT = REFLECTION_STARTUP_CONTEXT_TOKEN_LIMIT * STARTUP_CONTEXT_ESTIMATED_CHARS_PER_TOKEN;
251538
252101
  });
251539
252102
 
251540
- // src/mods/capabilities.ts
251541
- function isModCapabilityId(value) {
251542
- return MOD_CAPABILITY_ID_SET.has(value);
251543
- }
251544
- function resolveProcessModCapabilities(configuredCapabilities, env6 = process.env) {
251545
- if (env6[LETTA_MOD_CAPABILITY_PROFILE_ENV] === PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE) {
251546
- return cloneModCapabilities(PROVIDERS_ONLY_MOD_CAPABILITIES);
251547
- }
251548
- return resolveModCapabilities(configuredCapabilities);
251549
- }
251550
- function cloneModCapabilities(capabilities) {
251551
- return {
251552
- tools: capabilities.tools,
251553
- commands: capabilities.commands,
251554
- events: {
251555
- lifecycle: capabilities.events.lifecycle,
251556
- tools: capabilities.events.tools,
251557
- turns: capabilities.events.turns,
251558
- compact: capabilities.events.compact,
251559
- llm: capabilities.events.llm
251560
- },
251561
- permissions: capabilities.permissions,
251562
- providers: capabilities.providers,
251563
- ui: {
251564
- panels: capabilities.ui.panels
251565
- }
251566
- };
251567
- }
251568
- function resolveModCapabilities(capabilities) {
251569
- return cloneModCapabilities(capabilities ?? DEFAULT_MOD_CAPABILITIES);
251570
- }
251571
- var MOD_CAPABILITY_IDS, MOD_CAPABILITY_ID_SET, DEFAULT_MOD_CAPABILITIES, DISABLED_MOD_CAPABILITIES, PROVIDERS_ONLY_MOD_CAPABILITIES, LETTA_MOD_CAPABILITY_PROFILE_ENV = "LETTA_MOD_CAPABILITY_PROFILE", PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE = "providers-only";
251572
- var init_capabilities = __esm(() => {
251573
- MOD_CAPABILITY_IDS = [
251574
- "tools",
251575
- "commands",
251576
- "providers",
251577
- "permissions",
251578
- "events.lifecycle",
251579
- "events.turns",
251580
- "events.tools",
251581
- "events.compact",
251582
- "events.llm",
251583
- "ui.panels"
251584
- ];
251585
- MOD_CAPABILITY_ID_SET = new Set(MOD_CAPABILITY_IDS);
251586
- DEFAULT_MOD_CAPABILITIES = {
251587
- tools: true,
251588
- commands: true,
251589
- events: {
251590
- lifecycle: true,
251591
- tools: true,
251592
- turns: true,
251593
- compact: true,
251594
- llm: true
251595
- },
251596
- permissions: true,
251597
- providers: true,
251598
- ui: {
251599
- panels: true
251600
- }
251601
- };
251602
- DISABLED_MOD_CAPABILITIES = {
251603
- tools: false,
251604
- commands: false,
251605
- events: {
251606
- lifecycle: false,
251607
- tools: false,
251608
- turns: false,
251609
- compact: false,
251610
- llm: false
251611
- },
251612
- permissions: false,
251613
- providers: false,
251614
- ui: {
251615
- panels: false
251616
- }
251617
- };
251618
- PROVIDERS_ONLY_MOD_CAPABILITIES = {
251619
- ...DISABLED_MOD_CAPABILITIES,
251620
- events: { ...DISABLED_MOD_CAPABILITIES.events },
251621
- providers: true,
251622
- ui: { ...DISABLED_MOD_CAPABILITIES.ui }
251623
- };
251624
- });
251625
-
251626
- // src/agent/subagents/memory-worker-session.ts
251627
- function isMemoryWorkerSession(env6 = process.env) {
251628
- return env6[MEMORY_WORKER_SESSION_ENV] === "1";
251629
- }
251630
- var MEMORY_WORKER_SESSION_ENV = "LETTA_MEMORY_WORKER_SESSION";
251631
-
251632
- // src/agent/subagents/subagent-launcher.ts
251633
- import { homedir as homedir20 } from "node:os";
251634
- import { join as join67 } from "node:path";
251635
- function resolveSubagentWorkingDirectory(env6 = process.env, fallbackCwd = getCurrentWorkingDirectory(), options = {}) {
251636
- if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope) {
251637
- return env6.USER_CWD || fallbackCwd;
251638
- }
251639
- if (options.subagentType !== "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope?.primaryRoot) {
251640
- return options.memoryScope.primaryRoot;
251641
- }
251642
- const primaryRoot = options.memoryScope?.primaryRoot ?? options.inheritedPrimaryRoot;
251643
- if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && primaryRoot) {
251644
- return primaryRoot;
251645
- }
251646
- return env6.USER_CWD || fallbackCwd;
251647
- }
251648
- function resolveSubagentLauncher(cliArgs, options = {}) {
251649
- const env6 = options.env ?? process.env;
251650
- const argv = options.argv ?? process.argv;
251651
- const execPath = options.execPath ?? process.execPath;
251652
- const platform8 = options.platform ?? process.platform;
251653
- const cwd2 = options.cwd ?? process.cwd();
251654
- const invocation = resolveLettaInvocation(env6, argv, execPath, cwd2);
251655
- if (invocation) {
251656
- return {
251657
- command: invocation.command,
251658
- args: [...invocation.args, ...cliArgs]
251659
- };
251660
- }
251661
- const currentScript = argv[1] || "";
251662
- const resolvedCurrentScript = resolveEntryScriptPath(currentScript, cwd2);
251663
- if (currentScript.endsWith(".ts")) {
251664
- return {
251665
- command: execPath,
251666
- args: [resolvedCurrentScript, ...cliArgs]
251667
- };
251668
- }
251669
- if (currentScript.endsWith(".js") && platform8 === "win32") {
251670
- return {
251671
- command: execPath,
251672
- args: [resolvedCurrentScript, ...cliArgs]
251673
- };
251674
- }
251675
- if (currentScript.endsWith(".js")) {
251676
- return {
251677
- command: resolvedCurrentScript,
251678
- args: cliArgs
251679
- };
251680
- }
251681
- return {
251682
- command: "letta",
251683
- args: cliArgs
251684
- };
251685
- }
251686
- function resolveMemorySubagentScratchpad(parentProcessEnv, subagentId) {
251687
- const configuredScratchpad = parentProcessEnv.LETTA_SCRATCHPAD;
251688
- if (configuredScratchpad?.trim()) {
251689
- return configuredScratchpad;
251690
- }
251691
- const configuredTranscriptRoot = parentProcessEnv[TRANSCRIPT_ROOT_ENV];
251692
- const transcriptRoot = configuredTranscriptRoot?.trim() || join67(resolveGlobalConfigDir(parentProcessEnv, homedir20()), "transcripts");
251693
- const scope = subagentId ? encodeURIComponent(subagentId) : crypto.randomUUID();
251694
- return join67(transcriptRoot, "background", scope);
251695
- }
251696
- function composeSubagentChildEnv(options) {
251697
- const {
251698
- parentProcessEnv,
251699
- listenerConnectionId,
251700
- backendMode,
251701
- localBackendStorageDir,
251702
- parentAgentId,
251703
- subagentType,
251704
- launchProfile,
251705
- inheritedPrimaryRoot,
251706
- memoryScope,
251707
- inheritedApiKey,
251708
- inheritedBaseUrl,
251709
- actingUserId,
251710
- transcriptPath
251711
- } = options;
251712
- const childEnv = {
251713
- ...parentProcessEnv,
251714
- ...inheritedApiKey && { LETTA_API_KEY: inheritedApiKey },
251715
- ...inheritedBaseUrl && { LETTA_BASE_URL: inheritedBaseUrl },
251716
- DISABLE_AUTOUPDATER: "1",
251717
- LETTA_CODE_AGENT_ROLE: "subagent",
251718
- [MEMORY_WORKER_SESSION_ENV]: subagentType === "memory" ? "1" : undefined,
251719
- [SUBAGENT_LAUNCH_ENV]: "1",
251720
- [SUBAGENT_LAUNCH_PROFILE_ENV]: launchProfile ?? "default",
251721
- ...(subagentType === "reflection" || subagentType === "memory") && {
251722
- [LETTA_MOD_CAPABILITY_PROFILE_ENV]: PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE
251723
- },
251724
- LETTA_PARENT_AGENT_ID: parentAgentId,
251725
- LETTA_PARENT_CONVERSATION_ID: options.parentConversationId,
251726
- [SUBAGENT_DEPTH_ENV]: String(readSubagentDepth(parentProcessEnv) + 1),
251727
- ...transcriptPath && { TRANSCRIPT_PATH: transcriptPath }
251728
- };
251729
- if (actingUserId)
251730
- childEnv[ACTING_USER_ID_ENV] = actingUserId;
251731
- else if (actingUserId === null)
251732
- delete childEnv[ACTING_USER_ID_ENV];
251733
- delete childEnv[SUBAGENT_NAME_ENV];
251734
- if (options.subagentName)
251735
- childEnv[SUBAGENT_NAME_ENV] = options.subagentName;
251736
- if (backendMode === "local") {
251737
- childEnv.LETTA_LOCAL_BACKEND_EXPERIMENTAL = "1";
251738
- if (localBackendStorageDir) {
251739
- childEnv.LETTA_LOCAL_BACKEND_DIR = localBackendStorageDir;
251740
- }
251741
- } else if (backendMode === "api") {
251742
- childEnv.LETTA_LOCAL_BACKEND_EXPERIMENTAL = "0";
251743
- }
251744
- if (launchProfile === "memory-subagent") {
251745
- delete childEnv[LISTENER_CONNECTION_ENV];
251746
- childEnv.LETTA_SCRATCHPAD = resolveMemorySubagentScratchpad(parentProcessEnv, options.subagentId);
251747
- const primaryRoot = memoryScope?.primaryRoot ?? inheritedPrimaryRoot;
251748
- if (primaryRoot) {
251749
- childEnv.MEMORY_DIR = primaryRoot;
251750
- childEnv.LETTA_MEMORY_DIR = primaryRoot;
251751
- } else {
251752
- delete childEnv.MEMORY_DIR;
251753
- delete childEnv.LETTA_MEMORY_DIR;
251754
- }
251755
- } else if (listenerConnectionId?.startsWith("conn-")) {
251756
- childEnv[LISTENER_CONNECTION_ENV] = listenerConnectionId;
251757
- } else if (isUnattachedListenerLaunch({
251758
- listenerConnectionId,
251759
- launchProfile,
251760
- listenerConnectionCount: getActiveRuntime()?.connections.size ?? 0
251761
- })) {
251762
- trackBoundaryError({
251763
- errorType: "subagent_launch_missing_listener_connection",
251764
- error: new Error("Subagent launched in a listener without its connection"),
251765
- context: "subagent_launch"
251766
- });
251767
- }
251768
- return childEnv;
251769
- }
251770
- function isUnattachedListenerLaunch(options) {
251771
- return !options.listenerConnectionId && options.launchProfile !== "memory-subagent" && options.listenerConnectionCount > 0;
251772
- }
251773
- function shouldLaunchThroughListener(options) {
251774
- if (options.ephemeral) {
251775
- if (options.computer)
251776
- throw new Error("Ephemeral conversations cannot be routed to a Cloud computer");
251777
- return false;
251778
- }
251779
- if (options.launchProfile === "memory-subagent") {
251780
- if (options.computer)
251781
- throw new Error("Memory subagents must run in their confined local process, not through a computer listener");
251782
- return false;
251783
- }
251784
- return Boolean(options.computer) || options.cloudBackend && Boolean(options.connectionId);
251785
- }
251786
- function resolveSubagentInheritedPrimaryRoot(options) {
251787
- if (options.backendMode === "local" && options.parentAgentId) {
251788
- return getLocalBackendMemoryFilesystemRoot(options.parentAgentId, options.localBackendStorageDir ?? getLocalBackendStorageDir2());
251789
- }
251790
- return options.inheritedPrimaryRoot;
251791
- }
251792
- var init_subagent_launcher = __esm(() => {
251793
- init_backend2();
251794
- init_paths();
251795
- init_capabilities();
251796
- init_runtime_context();
251797
- init_error_reporting();
251798
- init_shell_env();
251799
- init_settings_path();
251800
- init_transcript_paths();
251801
- init_runtime6();
251802
- });
251803
-
251804
252103
  // src/agent/prompts/recall_subagent.md
251805
252104
  var recall_subagent_default = `Your task is to recall past experience based on a query. Use the CLI commands and search strategies below to search conversation history. Try to finish quickly with just 1-2 tool calls if possible (but use more if needed).
251806
252105
 
@@ -253345,6 +253644,7 @@ class RemoteSubagentFollower {
253345
253644
  detach;
253346
253645
  wake = Promise.withResolvers();
253347
253646
  closed = false;
253647
+ stopping = new AbortController;
253348
253648
  disconnected = false;
253349
253649
  lost = false;
253350
253650
  launched = false;
@@ -253423,6 +253723,19 @@ class RemoteSubagentFollower {
253423
253723
  this.detach?.();
253424
253724
  this.client?.close();
253425
253725
  this.wake.resolve();
253726
+ this.stopping.abort();
253727
+ }
253728
+ untilStopped(promise2, signal) {
253729
+ const stop = signal ? AbortSignal.any([signal, this.stopping.signal]) : this.stopping.signal;
253730
+ if (stop.aborted)
253731
+ return Promise.reject(stop.reason);
253732
+ return new Promise((resolve36, reject2) => {
253733
+ const onStop = () => reject2(stop.reason);
253734
+ stop.addEventListener("abort", onStop, { once: true });
253735
+ promise2.then(resolve36, reject2).finally(() => {
253736
+ stop.removeEventListener("abort", onStop);
253737
+ });
253738
+ });
253426
253739
  }
253427
253740
  async waitForTerminal(signal, onProgress) {
253428
253741
  const onAbort = () => this.wake.resolve();
@@ -253457,15 +253770,23 @@ class RemoteSubagentFollower {
253457
253770
  if (this.closed)
253458
253771
  throw new Error("Stopped following the subagent");
253459
253772
  try {
253460
- const client = await this.connect();
253773
+ const connecting = this.connect();
253774
+ const client = await this.untilStopped(connecting, signal).catch((error5) => {
253775
+ connecting.then((late) => late.close(), () => {});
253776
+ throw error5;
253777
+ });
253778
+ if (this.closed) {
253779
+ client.close();
253780
+ throw new Error("Stopped following the subagent");
253781
+ }
253461
253782
  this.attach(client);
253462
- await client.sync({
253783
+ await this.untilStopped(client.sync({
253463
253784
  runtime: {
253464
253785
  agent_id: this.scope.agentId,
253465
253786
  conversation_id: this.scope.conversationId
253466
253787
  },
253467
253788
  recover_approvals: false
253468
- });
253789
+ }), signal);
253469
253790
  failedReconnects = 0;
253470
253791
  disconnectedSince = undefined;
253471
253792
  } catch (error5) {
@@ -253645,6 +253966,8 @@ async function stopRemoteExternalCodingAgent(params, deps = {}) {
253645
253966
  });
253646
253967
  if (!response.success)
253647
253968
  throw new Error(response.error ?? "Stop failed");
253969
+ if (!response.cleanup_confirmed)
253970
+ throw new Error("The remote listener did not confirm process cleanup; update that listener and retry");
253648
253971
  return { stopped: response.stopped };
253649
253972
  } finally {
253650
253973
  client.close();
@@ -253818,7 +254141,7 @@ var init_subagent_computer = __esm(() => {
253818
254141
  // src/tools/impl/kill-bash.ts
253819
254142
  function killBackgroundProcess(shell_id) {
253820
254143
  const proc = backgroundProcesses.get(shell_id);
253821
- const retainsEntry = proc?.kind === "monitor" || proc?.kind === "workflow";
254144
+ const retainsEntry = proc?.kind === "monitor" || proc?.kind === "workflow" || proc?.kind === "tool";
253822
254145
  if (!proc || retainsEntry && proc.status !== "running") {
253823
254146
  return false;
253824
254147
  }
@@ -253851,12 +254174,44 @@ var init_kill_bash = __esm(() => {
253851
254174
  init_process_manager();
253852
254175
  });
253853
254176
 
254177
+ // src/tools/impl/stop-conversation-background.ts
254178
+ async function stopConversationBackground(scope) {
254179
+ const owned = [...backgroundProcesses].filter(([, process21]) => process21.runtimeScope?.conversationId === scope.conversationId && (scope.conversationId !== "default" || process21.runtimeScope.agentId === scope.agentId));
254180
+ for (const [, process21] of owned)
254181
+ process21.completionNotificationSuppressed = true;
254182
+ const failures = [];
254183
+ for (const [id2, process21] of owned) {
254184
+ await cancelMonitorBackup(id2);
254185
+ if (process21.status !== "running")
254186
+ continue;
254187
+ try {
254188
+ if (process21.terminate)
254189
+ process21.terminate();
254190
+ else if (!killBackgroundProcess(id2))
254191
+ throw new Error("Stop failed");
254192
+ if (process21.completion)
254193
+ await confirmProcessExit(process21.completion, id2);
254194
+ else if (!process21.kind)
254195
+ throw new Error("Process exit cannot be confirmed");
254196
+ } catch {
254197
+ failures.push(id2);
254198
+ }
254199
+ }
254200
+ if (failures.length)
254201
+ throw new Error(`Could not stop background tasks: ${failures.join(", ")}`);
254202
+ }
254203
+ var init_stop_conversation_background = __esm(() => {
254204
+ init_kill_bash();
254205
+ init_monitor_backup();
254206
+ init_process_manager();
254207
+ });
254208
+
253854
254209
  // src/tools/impl/task-stop.ts
253855
254210
  var exports_task_stop = {};
253856
254211
  __export(exports_task_stop, {
253857
254212
  task_stop: () => task_stop
253858
254213
  });
253859
- async function cancelRemoteRun(subagentId) {
254214
+ async function cancelRemoteRun(subagentId, allowIdle = false) {
253860
254215
  const child = getSubagents().find((agent) => agent.id === subagentId);
253861
254216
  const target2 = child?.conversationId === "default" ? child.agentId : child?.conversationId;
253862
254217
  try {
@@ -253864,32 +254219,76 @@ async function cancelRemoteRun(subagentId) {
253864
254219
  throw new Error("its conversation is not known yet");
253865
254220
  const results = await getBackend().cancelConversation(target2);
253866
254221
  const outcomes = Object.values(results);
253867
- if (outcomes.length === 0 || outcomes.some((status) => status !== "cancelled")) {
254222
+ if (!allowIdle && outcomes.length === 0 || outcomes.some((status) => status !== "cancelled")) {
253868
254223
  throw new Error("Cloud did not cancel every run");
253869
254224
  }
253870
- return { killed: true, output: "Cancelled the remote run" };
254225
+ return allowIdle ? { killed: true } : { killed: true, output: "Cancelled the remote run" };
253871
254226
  } catch (error5) {
254227
+ if (allowIdle && error5 instanceof ApiRequestError && error5.status === 409)
254228
+ return { killed: true };
253872
254229
  return {
253873
254230
  killed: false,
253874
254231
  output: `Couldn't cancel the remote run: ${getErrorMessage2(error5)}`
253875
254232
  };
253876
254233
  }
253877
254234
  }
254235
+ async function withTimeout3(promise2, timeoutMs) {
254236
+ let timer;
254237
+ try {
254238
+ return await Promise.race([
254239
+ promise2,
254240
+ new Promise((resolve36) => {
254241
+ timer = setTimeout(() => resolve36(TIMED_OUT), timeoutMs);
254242
+ })
254243
+ ]);
254244
+ } finally {
254245
+ clearTimeout(timer);
254246
+ }
254247
+ }
254248
+ async function finishPendingWakeCancellation(task) {
254249
+ for (let attempt2 = 0;attempt2 < 2; attempt2++) {
254250
+ try {
254251
+ await task.cancelPendingWakes?.();
254252
+ task.cancelPendingWakes = undefined;
254253
+ return { killed: true };
254254
+ } catch (error5) {
254255
+ if (attempt2 === 1)
254256
+ return {
254257
+ killed: false,
254258
+ output: `The process stopped, but its wakes could not be cancelled: ${getErrorMessage2(error5)}. Retry TaskStop to cancel the wakes.`
254259
+ };
254260
+ }
254261
+ }
254262
+ return { killed: false };
254263
+ }
253878
254264
  async function task_stop(args, deps = {}) {
253879
254265
  validateRequiredParams(args, ["task_id"], "TaskStop");
253880
254266
  const { task_id } = args;
253881
254267
  const task = backgroundTasks.get(task_id);
253882
254268
  if (task) {
254269
+ if (task.cancelPendingWakes)
254270
+ return finishPendingWakeCancellation(task);
253883
254271
  if (task.status === "running" && task.abortController) {
254272
+ const initialStop = task.stop;
253884
254273
  const child = getSubagents().find((agent) => agent.id === task.subagentId);
253885
254274
  const external3 = parseExternalCodingAgentId(child?.agentId ?? undefined);
253886
254275
  let remote;
253887
254276
  let remoteExternalStopped = false;
253888
- if (external3?.computer) {
254277
+ if (task.stop) {
254278
+ try {
254279
+ const result3 = await withTimeout3(task.stop(), deps.remoteStopTimeoutMs ?? REMOTE_STOP_TIMEOUT_MS);
254280
+ if (result3 === TIMED_OUT)
254281
+ throw new Error("The owning listener did not answer; the subagent may still be running");
254282
+ remote = { killed: true };
254283
+ } catch (error5) {
254284
+ remote = { killed: false, output: getErrorMessage2(error5) };
254285
+ }
254286
+ } else if (external3?.computer) {
253889
254287
  try {
253890
254288
  if (!task.runtimeScope)
253891
254289
  throw new Error("its parent conversation is not known");
253892
- const result3 = await (deps.stopRemoteExternal ?? stopRemoteExternalCodingAgent)({
254290
+ const timeoutMs = deps.remoteStopTimeoutMs ?? REMOTE_STOP_TIMEOUT_MS;
254291
+ const stopping = (deps.stopRemoteExternal ?? stopRemoteExternalCodingAgent)({
253893
254292
  agentId: child?.agentId,
253894
254293
  parentScope: {
253895
254294
  agentId: task.runtimeScope.agentId,
@@ -253897,6 +254296,10 @@ async function task_stop(args, deps = {}) {
253897
254296
  actingUserId: task.actingUserId
253898
254297
  }
253899
254298
  });
254299
+ stopping.catch(() => {});
254300
+ const result3 = await withTimeout3(stopping, timeoutMs);
254301
+ if (result3 === TIMED_OUT)
254302
+ throw new Error(`${external3.computer} did not answer within ${timeoutMs / 1000}s, so the worker may still be running`);
253900
254303
  remote = {
253901
254304
  killed: result3.stopped,
253902
254305
  output: result3.stopped ? "Stopped the remote external subagent" : "The remote external subagent was not running"
@@ -253908,44 +254311,122 @@ async function task_stop(args, deps = {}) {
253908
254311
  output: `Couldn't stop the remote external subagent: ${getErrorMessage2(error5)}`
253909
254312
  };
253910
254313
  }
253911
- } else if (task.remote) {
253912
- remote = await cancelRemoteRun(task.subagentId);
254314
+ } else if (task.remote || !external3 && child?.conversationId) {
254315
+ remote = await cancelRemoteRun(task.subagentId, !task.remote);
253913
254316
  }
253914
254317
  if (remote && !remote.killed)
253915
254318
  return remote;
254319
+ try {
254320
+ if (external3 && !external3.computer) {
254321
+ if (external3.type === "claude-code")
254322
+ await stopClaudeSession(external3.sessionId);
254323
+ if (external3.type === "codex")
254324
+ await stopCodexSession(external3.sessionId);
254325
+ }
254326
+ } catch (error5) {
254327
+ return { killed: false, output: getErrorMessage2(error5) };
254328
+ }
253916
254329
  task.abortController.abort(remoteExternalStopped ? REMOTE_EXTERNAL_WORKER_STOPPED : undefined);
253917
254330
  task.error = "Aborted by user";
253918
- await task.completion;
254331
+ try {
254332
+ if (!task.completion && (task.remote || external3 || initialStop))
254333
+ throw new Error("Subagent process exit cannot be confirmed");
254334
+ const completionTimeoutMs = deps.completionTimeoutMs ?? (external3?.computer ? COMPLETION_TIMEOUT_MS : 1e4);
254335
+ const settled = task.completion ? await withTimeout3(task.completion, completionTimeoutMs) : undefined;
254336
+ if (settled === TIMED_OUT) {
254337
+ if (!remoteExternalStopped)
254338
+ throw new Error("Subagent process exit was not confirmed");
254339
+ task.status = "failed";
254340
+ scheduleBackgroundTaskCleanup(task_id);
254341
+ return {
254342
+ killed: true,
254343
+ output: `${remote?.output ?? "Stopped the task"}, but stopped waiting for its result after ${completionTimeoutMs / 1000}s`
254344
+ };
254345
+ }
254346
+ } catch (error5) {
254347
+ return { killed: false, output: getErrorMessage2(error5) };
254348
+ }
254349
+ if (task.stop && task.stop !== initialStop) {
254350
+ try {
254351
+ const result3 = await withTimeout3(task.stop(), deps.remoteStopTimeoutMs ?? REMOTE_STOP_TIMEOUT_MS);
254352
+ if (result3 === TIMED_OUT)
254353
+ throw new Error("The owning listener did not confirm cancellation");
254354
+ } catch (error5) {
254355
+ return { killed: false, output: getErrorMessage2(error5) };
254356
+ }
254357
+ }
254358
+ if (!external3 && !initialStop && child?.conversationId) {
254359
+ const agentId = child.agentId ?? child.parentAgentId;
254360
+ if (agentId) {
254361
+ const scope = { agentId, conversationId: child.conversationId };
254362
+ try {
254363
+ await stopConversationBackground(scope);
254364
+ } catch (error5) {
254365
+ return { killed: false, output: getErrorMessage2(error5) };
254366
+ }
254367
+ task.status = "failed";
254368
+ scheduleBackgroundTaskCleanup(task_id);
254369
+ task.cancelPendingWakes = () => runWithRuntimeContext({
254370
+ ...scope,
254371
+ actingUserId: task.actingUserId ?? undefined,
254372
+ suppressActingUserFallback: task.actingUserId === null
254373
+ }, () => cancelConversationWakes(scope));
254374
+ const cleaned = await finishPendingWakeCancellation(task);
254375
+ if (!cleaned.killed)
254376
+ return cleaned;
254377
+ }
254378
+ }
253919
254379
  task.status = "failed";
253920
254380
  scheduleBackgroundTaskCleanup(task_id);
253921
254381
  return remote ?? { killed: true };
253922
254382
  }
253923
254383
  return { killed: false };
253924
254384
  }
253925
- return { killed: killBackgroundProcess(task_id) };
254385
+ const process21 = backgroundProcesses.get(task_id);
254386
+ if (process21?.cancel)
254387
+ return process21.cancel();
254388
+ if (process21?.remote && process21.status === "running") {
254389
+ return {
254390
+ killed: false,
254391
+ output: "The server for this tool doesn't support cancelling, so the call may still finish; its result will still arrive as a notification."
254392
+ };
254393
+ }
254394
+ const killed = killBackgroundProcess(task_id);
254395
+ return {
254396
+ killed,
254397
+ ...killed && process21?.kind === "tool" ? { output: "Stopped" } : {}
254398
+ };
253926
254399
  }
254400
+ var REMOTE_STOP_TIMEOUT_MS = 30000, COMPLETION_TIMEOUT_MS = 5000, TIMED_OUT;
253927
254401
  var init_task_stop = __esm(() => {
253928
254402
  init_subagent_state();
253929
254403
  init_backend2();
254404
+ init_request();
254405
+ init_runtime_context();
254406
+ init_claude_stream_session();
254407
+ init_codex_app_server();
253930
254408
  init_external_coding_agent();
253931
254409
  init_kill_bash();
253932
254410
  init_process_manager();
253933
254411
  init_remote_external_coding_agent();
254412
+ init_stop_conversation_background();
254413
+ init_wake();
254414
+ TIMED_OUT = Symbol("timed out");
253934
254415
  });
253935
254416
 
253936
254417
  // src/tools/impl/task-abort-hook.ts
253937
254418
  function buildBackgroundTaskAbortHook(taskId, abortController) {
253938
254419
  const bgTask = backgroundTasks.get(taskId);
253939
- const remote = bgTask?.remote ?? false;
253940
- const failSafeAbort = () => !remote && abortController.abort();
254420
+ const isRemote = () => Boolean(bgTask?.remote || bgTask?.stop);
254421
+ const failSafeAbort = () => !isRemote() && abortController.abort();
253941
254422
  const hook = () => {
253942
254423
  Promise.resolve().then(() => (init_task_stop(), exports_task_stop)).then((m4) => m4.task_stop({ task_id: taskId })).then((result3) => {
253943
254424
  if (!result3.killed)
253944
254425
  failSafeAbort();
253945
- settleInterruptedCancel(bgTask, remote, result3.killed, hook);
254426
+ settleInterruptedCancel(bgTask, isRemote(), result3.killed, hook);
253946
254427
  }).catch(() => {
253947
254428
  failSafeAbort();
253948
- settleInterruptedCancel(bgTask, remote, false, hook);
254429
+ settleInterruptedCancel(bgTask, isRemote(), false, hook);
253949
254430
  });
253950
254431
  };
253951
254432
  return hook;
@@ -254691,7 +255172,29 @@ var init_external_coding_agent_task = __esm(() => {
254691
255172
  });
254692
255173
 
254693
255174
  // src/tools/impl/send-agent-message.ts
255175
+ import { spawn as spawn11 } from "node:child_process";
254694
255176
  import { randomUUID as randomUUID48 } from "node:crypto";
255177
+ function buildLocalSendArgs(destination, message2) {
255178
+ return [
255179
+ "--backend",
255180
+ "local",
255181
+ "-p",
255182
+ ...destination.conversationId === "default" && destination.agentId ? ["--agent", destination.agentId] : [],
255183
+ "--conv",
255184
+ destination.conversationId,
255185
+ message2
255186
+ ];
255187
+ }
255188
+ function spawnDetached(command, args) {
255189
+ const child = spawn11(command, args, {
255190
+ cwd: getCurrentWorkingDirectory(),
255191
+ env: getRuntimeExecutionEnv(process.env, getRuntimeContext()?.executionSettings),
255192
+ detached: true,
255193
+ stdio: "ignore"
255194
+ });
255195
+ child.on("error", (error5) => debugLog("SendAgentMessage", "Local send failed to start", error5));
255196
+ child.unref();
255197
+ }
254695
255198
  function finishUntrackedNativeCapture(completion, reservation, source, sessionId) {
254696
255199
  if (!reservation)
254697
255200
  return;
@@ -254977,9 +255480,6 @@ async function send_agent_message(args, deps = {}) {
254977
255480
  }
254978
255481
  checkConversationId(args.conversation_id);
254979
255482
  const backend3 = deps.backend ?? getBackend();
254980
- if (!backend3.capabilities.environmentRouting) {
254981
- throw new Error("SendAgentMessage requires a Cloud backend.");
254982
- }
254983
255483
  const computer = normalizeAgentMessageComputer(args.computer);
254984
255484
  const actingUserId = getRuntimeActingUserAttribution();
254985
255485
  if (!actingUserId) {
@@ -255005,6 +255505,17 @@ async function send_agent_message(args, deps = {}) {
255005
255505
  }, backend3, signal);
255006
255506
  signal.throwIfAborted();
255007
255507
  submissionAttempted = true;
255508
+ if (!backend3.capabilities.environmentRouting) {
255509
+ const launcher = resolveSubagentLauncher(buildLocalSendArgs(destination, buildAgentSendReminder(sender, true) + args.message));
255510
+ (deps.spawnLocal ?? spawnDetached)(launcher.command, launcher.args);
255511
+ return {
255512
+ content: JSON.stringify({
255513
+ status: "spawned",
255514
+ conversation_id: destination.conversationId
255515
+ }),
255516
+ status: "success"
255517
+ };
255518
+ }
255008
255519
  const receipt = await (deps.enqueue ?? enqueueConversationMessage)({
255009
255520
  ...destination,
255010
255521
  clientMessageId,
@@ -255057,6 +255568,7 @@ async function send_agent_message(args, deps = {}) {
255057
255568
  var FULL_CONVERSATION_ID;
255058
255569
  var init_send_agent_message = __esm(() => {
255059
255570
  init_child_send_tracking();
255571
+ init_subagent_launcher();
255060
255572
  init_backend2();
255061
255573
  init_agent_message();
255062
255574
  init_conversation_enqueue();
@@ -255638,212 +256150,6 @@ var init_view_image = __esm(() => {
255638
256150
  ]);
255639
256151
  });
255640
256152
 
255641
- // src/tools/impl/github-pull-request-state.ts
255642
- function shortGitHubPullRequestSha(sha) {
255643
- return sha.slice(0, 12);
255644
- }
255645
- function pendingGitHubPullRequestChecks(snapshot2) {
255646
- return snapshot2.checks.filter((check5) => check5.phase === "pending");
255647
- }
255648
- function failedGitHubPullRequestChecks(snapshot2) {
255649
- return snapshot2.checks.filter((check5) => check5.phase === "failure");
255650
- }
255651
- function unresolvedGitHubPullRequestThreads(snapshot2) {
255652
- return snapshot2.reviewThreads.filter((thread) => !thread.isResolved);
255653
- }
255654
- function hasGitHubPullRequestReadyConditions(snapshot2) {
255655
- return snapshot2.state === "OPEN" && !snapshot2.isDraft && snapshot2.mergeable === "MERGEABLE" && snapshot2.mergeStateStatus === "CLEAN" && (snapshot2.reviewDecision === "NONE" || snapshot2.reviewDecision === "APPROVED") && pendingGitHubPullRequestChecks(snapshot2).length === 0 && failedGitHubPullRequestChecks(snapshot2).length === 0 && unresolvedGitHubPullRequestThreads(snapshot2).length === 0;
255656
- }
255657
- function isGitHubPullRequestReady(snapshot2) {
255658
- return snapshot2.readinessConfirmed && hasGitHubPullRequestReadyConditions(snapshot2);
255659
- }
255660
- function githubPullRequestCheckSummary(snapshot2) {
255661
- const pending2 = pendingGitHubPullRequestChecks(snapshot2).length;
255662
- const failed2 = failedGitHubPullRequestChecks(snapshot2).length;
255663
- const completed = snapshot2.checks.length - pending2;
255664
- if (snapshot2.checks.length === 0)
255665
- return "no checks reported";
255666
- return `${completed}/${snapshot2.checks.length} checks complete, ${failed2} failing, ${pending2} pending`;
255667
- }
255668
- function githubPullRequestBlockerSummary(snapshot2) {
255669
- const blockers = [];
255670
- if (snapshot2.isDraft)
255671
- blockers.push("draft");
255672
- if (snapshot2.mergeable === "CONFLICTING")
255673
- blockers.push("merge conflicts");
255674
- if (snapshot2.mergeable === "UNKNOWN") {
255675
- blockers.push("mergeability still unknown");
255676
- }
255677
- if (snapshot2.mergeStateStatus !== "CLEAN" && snapshot2.mergeStateStatus !== "UNKNOWN") {
255678
- blockers.push(`merge state ${snapshot2.mergeStateStatus}`);
255679
- }
255680
- if (snapshot2.mergeStateStatus === "UNKNOWN") {
255681
- blockers.push("merge state still unknown");
255682
- }
255683
- if (snapshot2.reviewDecision !== "NONE" && snapshot2.reviewDecision !== "APPROVED") {
255684
- blockers.push(`review decision ${snapshot2.reviewDecision}`);
255685
- }
255686
- if (hasGitHubPullRequestReadyConditions(snapshot2) && !snapshot2.readinessConfirmed) {
255687
- blockers.push("awaiting a second same-head readiness read");
255688
- }
255689
- const unresolved = unresolvedGitHubPullRequestThreads(snapshot2).length;
255690
- if (unresolved > 0) {
255691
- blockers.push(`${unresolved} unresolved review thread${unresolved === 1 ? "" : "s"}`);
255692
- }
255693
- return blockers.length > 0 ? blockers.join(", ") : "no known blockers";
255694
- }
255695
- function describeGitHubPullRequestSnapshot(snapshot2) {
255696
- const failing = failedGitHubPullRequestChecks(snapshot2);
255697
- const lines = [
255698
- `${snapshot2.ref.owner}/${snapshot2.ref.repo}#${snapshot2.ref.number} at ${shortGitHubPullRequestSha(snapshot2.headSha)}: ${snapshot2.state.toLowerCase()}${snapshot2.isDraft ? ", draft" : ""}; ${githubPullRequestCheckSummary(snapshot2)}; ${githubPullRequestBlockerSummary(snapshot2)}; ${isGitHubPullRequestReady(snapshot2) ? "merge-ready" : "not merge-ready"}.`
255699
- ];
255700
- if (failing.length > 0) {
255701
- lines.push(`Failing checks: ${failing.map((check5) => check5.name).join(", ")}.`);
255702
- }
255703
- const unresolved = unresolvedGitHubPullRequestThreads(snapshot2).slice(0, 5);
255704
- for (const thread of unresolved) {
255705
- const comment2 = thread.comments.at(-1);
255706
- if (!comment2)
255707
- continue;
255708
- lines.push(`Unresolved review thread${comment2.outdated ? " (outdated)" : ""}: ${comment2.url}`);
255709
- }
255710
- return lines.join(`
255711
- `);
255712
- }
255713
-
255714
- // src/tools/impl/github-pull-request-diff.ts
255715
- function normalizedBody(body3) {
255716
- const compact2 = body3.replace(/\s+/g, " ").trim();
255717
- if (compact2.length <= MAX_SUMMARY_BODY_CHARS)
255718
- return compact2;
255719
- return `${compact2.slice(0, MAX_SUMMARY_BODY_CHARS)}…`;
255720
- }
255721
- function commentEvent(label, comment2) {
255722
- const body3 = normalizedBody(comment2.body);
255723
- return `${label} from @${comment2.author}: ${body3 || "(no body)"} ${comment2.url}`;
255724
- }
255725
- function inlineCommentEvent(comment2, label = "New inline review comment") {
255726
- const location = comment2.path ? ` on ${comment2.path}${comment2.line ? `:${comment2.line}` : ""}` : "";
255727
- const outdated = comment2.outdated ? " (outdated)" : "";
255728
- return `${label} from @${comment2.author}${location}${outdated}: ${normalizedBody(comment2.body) || "(no body)"} ${comment2.url}`;
255729
- }
255730
- function checkUrl(check5) {
255731
- return check5.url ? ` ${check5.url}` : "";
255732
- }
255733
- function matchesCurrentFailure(attempt2, currentFailures) {
255734
- return currentFailures.some((check5) => attempt2.url && check5.url ? attempt2.url === check5.url : attempt2.name === check5.name && attempt2.result === check5.result);
255735
- }
255736
- function sameKnownValue(previous, current) {
255737
- return current === "UNKNOWN" || previous === current;
255738
- }
255739
- function diffGitHubPullRequestSnapshots(previous, current) {
255740
- const events = [];
255741
- const headChanged = previous.headSha !== current.headSha;
255742
- if (headChanged) {
255743
- events.push(`PR head changed from ${shortGitHubPullRequestSha(previous.headSha)} to ${shortGitHubPullRequestSha(current.headSha)}. ${githubPullRequestCheckSummary(current)}; ${githubPullRequestBlockerSummary(current)}.`);
255744
- const currentFailures = current.checks.filter((check5) => check5.phase === "failure");
255745
- for (const attempt2 of current.checkAttempts) {
255746
- if (attempt2.phase === "failure" && !matchesCurrentFailure(attempt2, currentFailures)) {
255747
- events.push(`Check attempt failed on new head before the next poll: ${attempt2.name} (${attempt2.result}).${checkUrl(attempt2)}`);
255748
- }
255749
- }
255750
- }
255751
- if (previous.state !== current.state) {
255752
- events.push(current.state === "MERGED" ? `PR merged at ${shortGitHubPullRequestSha(current.headSha)}: ${current.ref.url}` : current.state === "CLOSED" ? `PR closed without merge at ${shortGitHubPullRequestSha(current.headSha)}: ${current.ref.url}` : `PR reopened at ${shortGitHubPullRequestSha(current.headSha)}: ${current.ref.url}`);
255753
- }
255754
- if (previous.isDraft !== current.isDraft) {
255755
- events.push(current.isDraft ? "PR moved back to draft." : "PR marked ready for review.");
255756
- }
255757
- const previousComments = new Map(previous.comments.map((comment2) => [comment2.id, comment2]));
255758
- for (const comment2 of current.comments) {
255759
- const old = previousComments.get(comment2.id);
255760
- if (!old) {
255761
- events.push(commentEvent("New PR comment", comment2));
255762
- } else if (old.updatedAt !== comment2.updatedAt) {
255763
- events.push(commentEvent("PR comment edited", comment2));
255764
- }
255765
- }
255766
- const previousReviews = new Map(previous.reviews.map((review) => [review.id, review]));
255767
- for (const review of current.reviews) {
255768
- const old = previousReviews.get(review.id);
255769
- if (!old) {
255770
- events.push(commentEvent(`New ${review.state.toLowerCase()} review`, review));
255771
- } else if (old.state !== review.state || old.updatedAt !== review.updatedAt) {
255772
- events.push(commentEvent(`Review changed to ${review.state.toLowerCase()}`, review));
255773
- }
255774
- }
255775
- const previousThreads = new Map(previous.reviewThreads.map((thread) => [thread.id, thread]));
255776
- for (const thread of current.reviewThreads) {
255777
- const old = previousThreads.get(thread.id);
255778
- if (old && old.isResolved !== thread.isResolved) {
255779
- const url2 = thread.comments.at(-1)?.url ?? current.ref.url;
255780
- events.push(thread.isResolved ? `Review thread resolved: ${url2}` : `Review thread reopened: ${url2}`);
255781
- }
255782
- const oldComments = new Map(old?.comments.map((comment2) => [comment2.id, comment2]) ?? []);
255783
- for (const comment2 of thread.comments) {
255784
- const oldComment = oldComments.get(comment2.id);
255785
- if (!oldComment) {
255786
- events.push(inlineCommentEvent(comment2));
255787
- } else {
255788
- if (oldComment.updatedAt !== comment2.updatedAt) {
255789
- events.push(inlineCommentEvent(comment2, "Inline review comment edited"));
255790
- }
255791
- if (oldComment.outdated !== comment2.outdated) {
255792
- events.push(comment2.outdated ? `Review comment became outdated: ${comment2.url}` : `Review comment is current again: ${comment2.url}`);
255793
- }
255794
- }
255795
- }
255796
- }
255797
- if (!headChanged) {
255798
- const previousChecks = new Map(previous.checks.map((check5) => [check5.key, check5]));
255799
- const previousPending = pendingGitHubPullRequestChecks(previous).length;
255800
- const currentPending = pendingGitHubPullRequestChecks(current).length;
255801
- const currentFailures = current.checks.filter((check5) => check5.phase === "failure");
255802
- for (const check5 of current.checks) {
255803
- const old = previousChecks.get(check5.key);
255804
- if (check5.phase === "pending" && old && old.phase !== "pending") {
255805
- events.push(`Check rerun started: ${check5.name}.${checkUrl(check5)}`);
255806
- }
255807
- if ((!old || old.phase !== "failure") && check5.phase === "failure") {
255808
- events.push(`Check failed: ${check5.name} (${check5.result}).${checkUrl(check5)}`);
255809
- } else if (old?.phase === "failure" && (check5.phase === "success" || check5.phase === "neutral")) {
255810
- events.push(`Check recovered: ${check5.name} (${check5.result}).${checkUrl(check5)}`);
255811
- }
255812
- }
255813
- if (previousPending > 0 && currentPending === 0) {
255814
- events.push(`Current-head checks finished: ${githubPullRequestCheckSummary(current)}.`);
255815
- }
255816
- const previousAttempts = new Set(previous.checkAttempts.map((attempt2) => attempt2.key));
255817
- for (const attempt2 of current.checkAttempts) {
255818
- if (attempt2.phase === "failure" && !previousAttempts.has(attempt2.key) && !matchesCurrentFailure(attempt2, currentFailures)) {
255819
- events.push(`Check attempt failed before the next poll: ${attempt2.name} (${attempt2.result}).${checkUrl(attempt2)}`);
255820
- }
255821
- }
255822
- }
255823
- if (!sameKnownValue(previous.mergeable, current.mergeable)) {
255824
- events.push(current.mergeable === "CONFLICTING" ? "PR now has merge conflicts." : `PR mergeability changed to ${current.mergeable}.`);
255825
- }
255826
- if (!sameKnownValue(previous.mergeStateStatus, current.mergeStateStatus)) {
255827
- events.push(`GitHub merge state changed from ${previous.mergeStateStatus} to ${current.mergeStateStatus}.`);
255828
- }
255829
- if (previous.reviewDecision !== current.reviewDecision) {
255830
- events.push(`Review decision changed from ${previous.reviewDecision} to ${current.reviewDecision}.`);
255831
- }
255832
- const wasReady = isGitHubPullRequestReady(previous);
255833
- const isReady = isGitHubPullRequestReady(current);
255834
- if (!wasReady && isReady) {
255835
- events.push(`PR is merge-ready on head ${shortGitHubPullRequestSha(current.headSha)} after a fresh read: ${current.ref.url}`);
255836
- } else if (wasReady && !isReady) {
255837
- events.push(`PR is no longer merge-ready on head ${shortGitHubPullRequestSha(current.headSha)}: ${githubPullRequestBlockerSummary(current)}; ${githubPullRequestCheckSummary(current)}.`);
255838
- }
255839
- return {
255840
- events,
255841
- terminal: current.state === "MERGED" || current.state === "CLOSED"
255842
- };
255843
- }
255844
- var MAX_SUMMARY_BODY_CHARS = 240;
255845
- var init_github_pull_request_diff = () => {};
255846
-
255847
256153
  // src/tools/impl/github-pull-request-query.ts
255848
256154
  var GITHUB_PULL_REQUEST_QUERY = `
255849
256155
  query(
@@ -256008,6 +256314,79 @@ query($id: ID!, $before: String) {
256008
256314
  }
256009
256315
  }`;
256010
256316
 
256317
+ // src/tools/impl/github-pull-request-state.ts
256318
+ function shortGitHubPullRequestSha(sha) {
256319
+ return sha.slice(0, 12);
256320
+ }
256321
+ function pendingGitHubPullRequestChecks(snapshot2) {
256322
+ return snapshot2.checks.filter((check5) => check5.phase === "pending");
256323
+ }
256324
+ function failedGitHubPullRequestChecks(snapshot2) {
256325
+ return snapshot2.checks.filter((check5) => check5.phase === "failure");
256326
+ }
256327
+ function unresolvedGitHubPullRequestThreads(snapshot2) {
256328
+ return snapshot2.reviewThreads.filter((thread) => !thread.isResolved);
256329
+ }
256330
+ function hasGitHubPullRequestReadyConditions(snapshot2) {
256331
+ return snapshot2.state === "OPEN" && !snapshot2.isDraft && snapshot2.mergeable === "MERGEABLE" && snapshot2.mergeStateStatus === "CLEAN" && (snapshot2.reviewDecision === "NONE" || snapshot2.reviewDecision === "APPROVED") && pendingGitHubPullRequestChecks(snapshot2).length === 0 && failedGitHubPullRequestChecks(snapshot2).length === 0 && unresolvedGitHubPullRequestThreads(snapshot2).length === 0;
256332
+ }
256333
+ function isGitHubPullRequestReady(snapshot2) {
256334
+ return snapshot2.readinessConfirmed && hasGitHubPullRequestReadyConditions(snapshot2);
256335
+ }
256336
+ function githubPullRequestCheckSummary(snapshot2) {
256337
+ const pending2 = pendingGitHubPullRequestChecks(snapshot2).length;
256338
+ const failed2 = failedGitHubPullRequestChecks(snapshot2).length;
256339
+ const completed = snapshot2.checks.length - pending2;
256340
+ if (snapshot2.checks.length === 0)
256341
+ return "no checks reported";
256342
+ return `${completed}/${snapshot2.checks.length} checks complete, ${failed2} failing, ${pending2} pending`;
256343
+ }
256344
+ function githubPullRequestBlockerSummary(snapshot2) {
256345
+ const blockers = [];
256346
+ if (snapshot2.isDraft)
256347
+ blockers.push("draft");
256348
+ if (snapshot2.mergeable === "CONFLICTING")
256349
+ blockers.push("merge conflicts");
256350
+ if (snapshot2.mergeable === "UNKNOWN") {
256351
+ blockers.push("mergeability still unknown");
256352
+ }
256353
+ if (snapshot2.mergeStateStatus !== "CLEAN" && snapshot2.mergeStateStatus !== "UNKNOWN") {
256354
+ blockers.push(`merge state ${snapshot2.mergeStateStatus}`);
256355
+ }
256356
+ if (snapshot2.mergeStateStatus === "UNKNOWN") {
256357
+ blockers.push("merge state still unknown");
256358
+ }
256359
+ if (snapshot2.reviewDecision !== "NONE" && snapshot2.reviewDecision !== "APPROVED") {
256360
+ blockers.push(`review decision ${snapshot2.reviewDecision}`);
256361
+ }
256362
+ if (hasGitHubPullRequestReadyConditions(snapshot2) && !snapshot2.readinessConfirmed) {
256363
+ blockers.push("awaiting a second same-head readiness read");
256364
+ }
256365
+ const unresolved = unresolvedGitHubPullRequestThreads(snapshot2).length;
256366
+ if (unresolved > 0) {
256367
+ blockers.push(`${unresolved} unresolved review thread${unresolved === 1 ? "" : "s"}`);
256368
+ }
256369
+ return blockers.length > 0 ? blockers.join(", ") : "no known blockers";
256370
+ }
256371
+ function describeGitHubPullRequestSnapshot(snapshot2) {
256372
+ const failing = failedGitHubPullRequestChecks(snapshot2);
256373
+ const lines = [
256374
+ `${snapshot2.ref.owner}/${snapshot2.ref.repo}#${snapshot2.ref.number} at ${shortGitHubPullRequestSha(snapshot2.headSha)}: ${snapshot2.state.toLowerCase()}${snapshot2.isDraft ? ", draft" : ""}; ${githubPullRequestCheckSummary(snapshot2)}; ${githubPullRequestBlockerSummary(snapshot2)}; ${isGitHubPullRequestReady(snapshot2) ? "merge-ready" : "not merge-ready"}.`
256375
+ ];
256376
+ if (failing.length > 0) {
256377
+ lines.push(`Failing checks: ${failing.map((check5) => check5.name).join(", ")}.`);
256378
+ }
256379
+ const unresolved = unresolvedGitHubPullRequestThreads(snapshot2).slice(0, 5);
256380
+ for (const thread of unresolved) {
256381
+ const comment2 = thread.comments.at(-1);
256382
+ if (!comment2)
256383
+ continue;
256384
+ lines.push(`Unresolved review thread${comment2.outdated ? " (outdated)" : ""}: ${comment2.url}`);
256385
+ }
256386
+ return lines.join(`
256387
+ `);
256388
+ }
256389
+
256011
256390
  // src/tools/impl/github-pull-request-watch.ts
256012
256391
  import { execFile as execFile16 } from "node:child_process";
256013
256392
  import { promisify as promisify16 } from "node:util";
@@ -256544,6 +256923,263 @@ var init_github_pull_request_watch = __esm(() => {
256544
256923
  };
256545
256924
  });
256546
256925
 
256926
+ // src/tools/impl/github-pull-request-cloud.ts
256927
+ import { setTimeout as delay5 } from "node:timers/promises";
256928
+ async function requestSnapshot(ref5, signal) {
256929
+ const client = await getClient();
256930
+ try {
256931
+ const body3 = await client.post("/v1/integrations/github/pull-request-snapshots", {
256932
+ body: {
256933
+ pull_requests: [
256934
+ { owner: ref5.owner, repo: ref5.repo, number: ref5.number }
256935
+ ]
256936
+ },
256937
+ signal,
256938
+ maxRetries: 0,
256939
+ timeout: 30000
256940
+ });
256941
+ return { status: 200, body: body3 };
256942
+ } catch (error5) {
256943
+ if (error5 instanceof APIError && (error5.status === 404 || error5.status === 501 || error5.status === 429)) {
256944
+ return { status: error5.status };
256945
+ }
256946
+ throw error5;
256947
+ }
256948
+ }
256949
+ function sameRef(a2, b3) {
256950
+ return a2.owner.toLowerCase() === b3.owner.toLowerCase() && a2.repo.toLowerCase() === b3.repo.toLowerCase() && a2.number === b3.number;
256951
+ }
256952
+ function toComment(comment2) {
256953
+ return {
256954
+ id: comment2.id,
256955
+ author: comment2.author,
256956
+ body: comment2.body,
256957
+ url: comment2.url,
256958
+ updatedAt: comment2.updated_at
256959
+ };
256960
+ }
256961
+ function toClientSnapshot(ref5, snapshot2) {
256962
+ return {
256963
+ ref: { ...ref5, url: snapshot2.ref.url },
256964
+ headSha: snapshot2.head_sha,
256965
+ state: snapshot2.merged ? "MERGED" : snapshot2.state,
256966
+ isDraft: snapshot2.is_draft,
256967
+ mergeable: snapshot2.mergeable,
256968
+ mergeStateStatus: snapshot2.merge_state_status,
256969
+ reviewDecision: snapshot2.review_decision,
256970
+ readinessConfirmed: false,
256971
+ checks: snapshot2.checks,
256972
+ checkAttempts: snapshot2.check_attempts,
256973
+ comments: snapshot2.comments.map(toComment),
256974
+ reviews: snapshot2.reviews.map((review) => ({
256975
+ ...toComment(review),
256976
+ state: review.state,
256977
+ commitSha: review.commit_sha
256978
+ })),
256979
+ reviewThreads: snapshot2.review_threads.map((thread) => ({
256980
+ id: thread.id,
256981
+ isResolved: thread.is_resolved,
256982
+ comments: thread.comments.map((comment2) => ({
256983
+ ...toComment(comment2),
256984
+ path: comment2.path,
256985
+ line: comment2.line,
256986
+ outdated: comment2.outdated,
256987
+ commitSha: comment2.commit_sha
256988
+ }))
256989
+ }))
256990
+ };
256991
+ }
256992
+ function createGitHubPullRequestSnapshotFetcher(deps = {}) {
256993
+ const shouldFetchCloud = deps.isCloud ?? (() => resolveBackendMode() === "api" && isCloudServerUrl());
256994
+ const fetchGh = deps.fetchGh ?? fetchGitHubPullRequestSnapshot;
256995
+ const request2 = deps.request ?? requestSnapshot;
256996
+ const now2 = deps.now ?? Date.now;
256997
+ const wait = deps.wait ?? (async (ms, signal) => {
256998
+ await delay5(ms, undefined, { signal });
256999
+ });
257000
+ let unsupported = false;
257001
+ let reportedRateLimit = false;
257002
+ const pause = async (retryAt, signal) => {
257003
+ if (!reportedRateLimit) {
257004
+ reportedRateLimit = true;
257005
+ telemetry.trackError("github_rate_limit", "Cloud PR snapshot polling paused for GitHub quota cooldown", "watch_pr");
257006
+ }
257007
+ const remaining = Date.parse(retryAt ?? "") - now2();
257008
+ await wait(remaining > 0 ? remaining : DEFAULT_COOLDOWN_MS, signal);
257009
+ };
257010
+ return async (ref5, options) => {
257011
+ if (unsupported || !shouldFetchCloud())
257012
+ return fetchGh(ref5, options);
257013
+ while (true) {
257014
+ options.signal?.throwIfAborted();
257015
+ const result3 = await request2(ref5, options.signal);
257016
+ if (!("body" in result3)) {
257017
+ if (result3.status === 429) {
257018
+ await pause(undefined, options.signal);
257019
+ continue;
257020
+ }
257021
+ unsupported = true;
257022
+ return fetchGh(ref5, options);
257023
+ }
257024
+ const entry = result3.body.snapshots.find((item) => sameRef(item, ref5));
257025
+ const limit4 = result3.body.rate_limits?.find((item) => sameRef(item, ref5));
257026
+ if (limit4 || entry?.stale) {
257027
+ await pause(entry?.retry_at ?? limit4?.retry_at, options.signal);
257028
+ continue;
257029
+ }
257030
+ if (entry?.inaccessible) {
257031
+ throw new Error(`Cloud could not access ${ref5.url}`);
257032
+ }
257033
+ if (!entry?.snapshot) {
257034
+ throw new Error("Cloud returned no PR snapshot");
257035
+ }
257036
+ return toClientSnapshot(ref5, entry.snapshot);
257037
+ }
257038
+ };
257039
+ }
257040
+ var DEFAULT_COOLDOWN_MS = 30000;
257041
+ var init_github_pull_request_cloud = __esm(() => {
257042
+ init_letta_client();
257043
+ init_client4();
257044
+ init_server_url();
257045
+ init_backend_mode();
257046
+ init_telemetry();
257047
+ init_github_pull_request_watch();
257048
+ });
257049
+
257050
+ // src/tools/impl/github-pull-request-diff.ts
257051
+ function normalizedBody(body3) {
257052
+ const compact2 = body3.replace(/\s+/g, " ").trim();
257053
+ if (compact2.length <= MAX_SUMMARY_BODY_CHARS)
257054
+ return compact2;
257055
+ return `${compact2.slice(0, MAX_SUMMARY_BODY_CHARS)}…`;
257056
+ }
257057
+ function commentEvent(label, comment2) {
257058
+ const body3 = normalizedBody(comment2.body);
257059
+ return `${label} from @${comment2.author}: ${body3 || "(no body)"} ${comment2.url}`;
257060
+ }
257061
+ function inlineCommentEvent(comment2, label = "New inline review comment") {
257062
+ const location = comment2.path ? ` on ${comment2.path}${comment2.line ? `:${comment2.line}` : ""}` : "";
257063
+ const outdated = comment2.outdated ? " (outdated)" : "";
257064
+ return `${label} from @${comment2.author}${location}${outdated}: ${normalizedBody(comment2.body) || "(no body)"} ${comment2.url}`;
257065
+ }
257066
+ function checkUrl(check5) {
257067
+ return check5.url ? ` ${check5.url}` : "";
257068
+ }
257069
+ function matchesCurrentFailure(attempt2, currentFailures) {
257070
+ return currentFailures.some((check5) => attempt2.url && check5.url ? attempt2.url === check5.url : attempt2.name === check5.name && attempt2.result === check5.result);
257071
+ }
257072
+ function sameKnownValue(previous, current) {
257073
+ return current === "UNKNOWN" || previous === current;
257074
+ }
257075
+ function diffGitHubPullRequestSnapshots(previous, current) {
257076
+ const events = [];
257077
+ const headChanged = previous.headSha !== current.headSha;
257078
+ if (headChanged) {
257079
+ events.push(`PR head changed from ${shortGitHubPullRequestSha(previous.headSha)} to ${shortGitHubPullRequestSha(current.headSha)}. ${githubPullRequestCheckSummary(current)}; ${githubPullRequestBlockerSummary(current)}.`);
257080
+ const currentFailures = current.checks.filter((check5) => check5.phase === "failure");
257081
+ for (const attempt2 of current.checkAttempts) {
257082
+ if (attempt2.phase === "failure" && !matchesCurrentFailure(attempt2, currentFailures)) {
257083
+ events.push(`Check attempt failed on new head before the next poll: ${attempt2.name} (${attempt2.result}).${checkUrl(attempt2)}`);
257084
+ }
257085
+ }
257086
+ }
257087
+ if (previous.state !== current.state) {
257088
+ events.push(current.state === "MERGED" ? `PR merged at ${shortGitHubPullRequestSha(current.headSha)}: ${current.ref.url}` : current.state === "CLOSED" ? `PR closed without merge at ${shortGitHubPullRequestSha(current.headSha)}: ${current.ref.url}` : `PR reopened at ${shortGitHubPullRequestSha(current.headSha)}: ${current.ref.url}`);
257089
+ }
257090
+ if (previous.isDraft !== current.isDraft) {
257091
+ events.push(current.isDraft ? "PR moved back to draft." : "PR marked ready for review.");
257092
+ }
257093
+ const previousComments = new Map(previous.comments.map((comment2) => [comment2.id, comment2]));
257094
+ for (const comment2 of current.comments) {
257095
+ const old = previousComments.get(comment2.id);
257096
+ if (!old) {
257097
+ events.push(commentEvent("New PR comment", comment2));
257098
+ } else if (old.updatedAt !== comment2.updatedAt) {
257099
+ events.push(commentEvent("PR comment edited", comment2));
257100
+ }
257101
+ }
257102
+ const previousReviews = new Map(previous.reviews.map((review) => [review.id, review]));
257103
+ for (const review of current.reviews) {
257104
+ const old = previousReviews.get(review.id);
257105
+ if (!old) {
257106
+ events.push(commentEvent(`New ${review.state.toLowerCase()} review`, review));
257107
+ } else if (old.state !== review.state || old.updatedAt !== review.updatedAt) {
257108
+ events.push(commentEvent(`Review changed to ${review.state.toLowerCase()}`, review));
257109
+ }
257110
+ }
257111
+ const previousThreads = new Map(previous.reviewThreads.map((thread) => [thread.id, thread]));
257112
+ for (const thread of current.reviewThreads) {
257113
+ const old = previousThreads.get(thread.id);
257114
+ if (old && old.isResolved !== thread.isResolved) {
257115
+ const url2 = thread.comments.at(-1)?.url ?? current.ref.url;
257116
+ events.push(thread.isResolved ? `Review thread resolved: ${url2}` : `Review thread reopened: ${url2}`);
257117
+ }
257118
+ const oldComments = new Map(old?.comments.map((comment2) => [comment2.id, comment2]) ?? []);
257119
+ for (const comment2 of thread.comments) {
257120
+ const oldComment = oldComments.get(comment2.id);
257121
+ if (!oldComment) {
257122
+ events.push(inlineCommentEvent(comment2));
257123
+ } else {
257124
+ if (oldComment.updatedAt !== comment2.updatedAt) {
257125
+ events.push(inlineCommentEvent(comment2, "Inline review comment edited"));
257126
+ }
257127
+ if (oldComment.outdated !== comment2.outdated) {
257128
+ events.push(comment2.outdated ? `Review comment became outdated: ${comment2.url}` : `Review comment is current again: ${comment2.url}`);
257129
+ }
257130
+ }
257131
+ }
257132
+ }
257133
+ if (!headChanged) {
257134
+ const previousChecks = new Map(previous.checks.map((check5) => [check5.key, check5]));
257135
+ const previousPending = pendingGitHubPullRequestChecks(previous).length;
257136
+ const currentPending = pendingGitHubPullRequestChecks(current).length;
257137
+ const currentFailures = current.checks.filter((check5) => check5.phase === "failure");
257138
+ for (const check5 of current.checks) {
257139
+ const old = previousChecks.get(check5.key);
257140
+ if (check5.phase === "pending" && old && old.phase !== "pending") {
257141
+ events.push(`Check rerun started: ${check5.name}.${checkUrl(check5)}`);
257142
+ }
257143
+ if ((!old || old.phase !== "failure") && check5.phase === "failure") {
257144
+ events.push(`Check failed: ${check5.name} (${check5.result}).${checkUrl(check5)}`);
257145
+ } else if (old?.phase === "failure" && (check5.phase === "success" || check5.phase === "neutral")) {
257146
+ events.push(`Check recovered: ${check5.name} (${check5.result}).${checkUrl(check5)}`);
257147
+ }
257148
+ }
257149
+ if (previousPending > 0 && currentPending === 0) {
257150
+ events.push(`Current-head checks finished: ${githubPullRequestCheckSummary(current)}.`);
257151
+ }
257152
+ const previousAttempts = new Set(previous.checkAttempts.map((attempt2) => attempt2.key));
257153
+ for (const attempt2 of current.checkAttempts) {
257154
+ if (attempt2.phase === "failure" && !previousAttempts.has(attempt2.key) && !matchesCurrentFailure(attempt2, currentFailures)) {
257155
+ events.push(`Check attempt failed before the next poll: ${attempt2.name} (${attempt2.result}).${checkUrl(attempt2)}`);
257156
+ }
257157
+ }
257158
+ }
257159
+ if (!sameKnownValue(previous.mergeable, current.mergeable)) {
257160
+ events.push(current.mergeable === "CONFLICTING" ? "PR now has merge conflicts." : `PR mergeability changed to ${current.mergeable}.`);
257161
+ }
257162
+ if (!sameKnownValue(previous.mergeStateStatus, current.mergeStateStatus)) {
257163
+ events.push(`GitHub merge state changed from ${previous.mergeStateStatus} to ${current.mergeStateStatus}.`);
257164
+ }
257165
+ if (previous.reviewDecision !== current.reviewDecision) {
257166
+ events.push(`Review decision changed from ${previous.reviewDecision} to ${current.reviewDecision}.`);
257167
+ }
257168
+ const wasReady = isGitHubPullRequestReady(previous);
257169
+ const isReady = isGitHubPullRequestReady(current);
257170
+ if (!wasReady && isReady) {
257171
+ events.push(`PR is merge-ready on head ${shortGitHubPullRequestSha(current.headSha)} after a fresh read: ${current.ref.url}`);
257172
+ } else if (wasReady && !isReady) {
257173
+ events.push(`PR is no longer merge-ready on head ${shortGitHubPullRequestSha(current.headSha)}: ${githubPullRequestBlockerSummary(current)}; ${githubPullRequestCheckSummary(current)}.`);
257174
+ }
257175
+ return {
257176
+ events,
257177
+ terminal: current.state === "MERGED" || current.state === "CLOSED"
257178
+ };
257179
+ }
257180
+ var MAX_SUMMARY_BODY_CHARS = 240;
257181
+ var init_github_pull_request_diff = () => {};
257182
+
256547
257183
  // src/tools/impl/watch-pr.ts
256548
257184
  import { createHash as createHash11, randomUUID as randomUUID49 } from "node:crypto";
256549
257185
  import {
@@ -256554,7 +257190,7 @@ import {
256554
257190
  writeFileSync as writeFileSync31
256555
257191
  } from "node:fs";
256556
257192
  import { dirname as dirname31, join as join72 } from "node:path";
256557
- import { setTimeout as delay5 } from "node:timers/promises";
257193
+ import { setTimeout as delay6 } from "node:timers/promises";
256558
257194
  function errorText(error5) {
256559
257195
  const message2 = error5 instanceof Error ? error5.message : String(error5);
256560
257196
  return scrubSecretsFromString(message2, {}).replace(/\s+/g, " ").trim().slice(0, 500);
@@ -256563,7 +257199,7 @@ function pollDelayMs(failedPolls) {
256563
257199
  return Math.min(WATCH_POLL_MS * 2 ** failedPolls, WATCH_MAX_POLL_MS);
256564
257200
  }
256565
257201
  async function defaultWait(signal, milliseconds) {
256566
- await delay5(milliseconds, undefined, { signal });
257202
+ await delay6(milliseconds, undefined, { signal });
256567
257203
  }
256568
257204
  function saveSnapshot(path32, snapshot2) {
256569
257205
  if (!path32)
@@ -256639,7 +257275,7 @@ async function watch_pr(args, deps = {}) {
256639
257275
  }
256640
257276
  const ref5 = parseGitHubPullRequestUrl(args.url);
256641
257277
  const cwd2 = getCurrentWorkingDirectory();
256642
- const fetchSnapshot = deps.fetchSnapshot ?? ((pullRequestRef, options) => fetchGitHubPullRequestSnapshot(pullRequestRef, options));
257278
+ const fetchSnapshot = deps.fetchSnapshot ?? createGitHubPullRequestSnapshotFetcher();
256643
257279
  const runtimeContext = getRuntimeContext();
256644
257280
  const parentScope = args.parentScope ?? (runtimeContext?.agentId ? {
256645
257281
  agentId: runtimeContext.agentId,
@@ -256848,6 +257484,7 @@ var init_watch_pr = __esm(() => {
256848
257484
  init_secret_substitution();
256849
257485
  init_settings_path();
256850
257486
  init_task_notifications();
257487
+ init_github_pull_request_cloud();
256851
257488
  init_github_pull_request_diff();
256852
257489
  init_github_pull_request_watch();
256853
257490
  init_monitor();
@@ -264751,11 +265388,11 @@ function scheduleDurableQueueRestore(listener, capacityReleased = true) {
264751
265388
  clearDurableQueueRestoreRetry(listener);
264752
265389
  return;
264753
265390
  }
264754
- const delay6 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
265391
+ const delay7 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
264755
265392
  listener.durableQueueRestoreTimer = setTimeout(() => {
264756
265393
  listener.durableQueueRestoreTimer = undefined;
264757
265394
  scheduleDurableQueueRestore(listener, false);
264758
- }, delay6);
265395
+ }, delay7);
264759
265396
  listener.durableQueueRestoreTimer.unref?.();
264760
265397
  } finally {
264761
265398
  listener.durableQueueRestoreScheduled = false;
@@ -269947,6 +270584,9 @@ function captureExternalToolNotificationGuard(listener, runtimeScope) {
269947
270584
  }
269948
270585
  };
269949
270586
  }
270587
+ function captureNotificationWait(listener, runtimeScope) {
270588
+ return captureExternalToolNotificationGuard(listener, runtimeScope)?.waitUntilCurrent ?? (async () => false);
270589
+ }
269950
270590
  function toExternalToolDefinition(listener, tool, connectionId, runtimeScope) {
269951
270591
  const toolDefinition = {
269952
270592
  name: tool.name,
@@ -269966,7 +270606,7 @@ function toExternalToolDefinition(listener, tool, connectionId, runtimeScope) {
269966
270606
  createNotificationGuard: () => captureExternalToolNotificationGuard(listener, runtimeScope)
269967
270607
  });
269968
270608
  }
269969
- function installExternalToolBridge(runtime) {
270609
+ function installExternalToolBridge(runtime, options) {
269970
270610
  setExternalToolExecutor(async (toolCallId, toolName2, input, context3) => {
269971
270611
  const registrationKey = context3?.tool.registrationKey;
269972
270612
  const connectionId = registrationKey ? getConnectionIdsByRegistrationKey(runtime).get(registrationKey) : undefined;
@@ -269995,34 +270635,91 @@ function installExternalToolBridge(runtime) {
269995
270635
  };
269996
270636
  const requestFrame = JSON.stringify(request2);
269997
270637
  const timeoutMs = context3?.tool.timeoutMs ?? EXTERNAL_TOOL_CALL_TIMEOUT_MS;
269998
- const result3 = await new Promise((resolve38, reject2) => {
269999
- const timeout = setTimeout(() => {
270000
- getPendingExternalToolCalls(runtime).delete(requestKey);
270001
- reject2(new Error(`External tool call timed out after ${Math.ceil(timeoutMs / 1000)}s: ${toolName2}. The remote tool may still finish; its outcome is unknown. Check the destination before retrying a write.`));
270002
- }, timeoutMs);
270003
- getPendingExternalToolCalls(runtime).set(requestKey, {
270004
- connectionId: connection.id,
270005
- isOwningTurnCurrent,
270006
- requestFrame,
270007
- sentOn: writer,
270008
- resolve: (response) => {
270009
- resolve38({
270010
- content: [...response.content],
270011
- isError: response.is_error === true
270012
- });
270013
- },
270014
- reject: reject2,
270015
- timeout
270638
+ let cancellationRequested = false;
270639
+ let cancellationTimedOut = false;
270640
+ let onAbort;
270641
+ try {
270642
+ const result3 = await new Promise((resolve38, reject2) => {
270643
+ const timeout = setTimeout(() => {
270644
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270645
+ reject2(new Error(`External tool call timed out after ${Math.ceil(timeoutMs / 1000)}s: ${toolName2}. The remote tool may still finish; its outcome is unknown. Check the destination before retrying a write.`));
270646
+ }, timeoutMs);
270647
+ getPendingExternalToolCalls(runtime).set(requestKey, {
270648
+ connectionId: connection.id,
270649
+ isOwningTurnCurrent,
270650
+ requestFrame,
270651
+ sentOn: writer,
270652
+ resolve: (response) => {
270653
+ resolve38({
270654
+ content: [...response.content],
270655
+ isError: response.is_error === true
270656
+ });
270657
+ },
270658
+ reject: reject2,
270659
+ timeout
270660
+ });
270661
+ if (context3?.tool.supportsCancellation && context3.signal) {
270662
+ onAbort = () => {
270663
+ const pending2 = getPendingExternalToolCalls(runtime).get(requestKey);
270664
+ if (!pending2 || cancellationRequested)
270665
+ return;
270666
+ cancellationRequested = true;
270667
+ clearTimeout(pending2.timeout);
270668
+ pending2.requestFrame = JSON.stringify({
270669
+ type: "external_tool_call_cancel",
270670
+ request_id: requestId,
270671
+ reason: "aborted"
270672
+ });
270673
+ pending2.timeout = setTimeout(() => {
270674
+ cancellationTimedOut = true;
270675
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270676
+ reject2(new Error("External tool cancellation timed out"));
270677
+ }, options?.cancelTimeoutMs ?? 30000);
270678
+ try {
270679
+ connection.writer.send(pending2.requestFrame);
270680
+ pending2.sentOn = connection.writer;
270681
+ if (context3.signal?.reason === EXTERNAL_TOOL_FOREGROUND_INTERRUPTED) {
270682
+ clearTimeout(pending2.timeout);
270683
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270684
+ reject2(new Error("cancelled"));
270685
+ }
270686
+ } catch (error5) {
270687
+ clearTimeout(pending2.timeout);
270688
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270689
+ reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
270690
+ }
270691
+ };
270692
+ context3.signal.addEventListener("abort", onAbort, { once: true });
270693
+ }
270694
+ try {
270695
+ writer.send(requestFrame);
270696
+ if (context3?.signal?.aborted)
270697
+ onAbort?.();
270698
+ } catch (error5) {
270699
+ clearTimeout(timeout);
270700
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270701
+ reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
270702
+ }
270016
270703
  });
270017
- try {
270018
- writer.send(requestFrame);
270019
- } catch (error5) {
270020
- clearTimeout(timeout);
270021
- getPendingExternalToolCalls(runtime).delete(requestKey);
270022
- reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
270704
+ return result3;
270705
+ } catch (error5) {
270706
+ if (cancellationTimedOut || cancellationRequested && error5 instanceof Error && error5.message === "cancelled") {
270707
+ return {
270708
+ content: [
270709
+ {
270710
+ type: "text",
270711
+ text: cancellationTimedOut ? "Cancellation was not confirmed; the remote tool may still finish." : "cancelled"
270712
+ }
270713
+ ],
270714
+ isError: true,
270715
+ cancellation: cancellationTimedOut ? "timeout" : "cancelled"
270716
+ };
270023
270717
  }
270024
- });
270025
- return result3;
270718
+ throw error5;
270719
+ } finally {
270720
+ if (onAbort)
270721
+ context3?.signal?.removeEventListener("abort", onAbort);
270722
+ }
270026
270723
  });
270027
270724
  }
270028
270725
  function registerRuntimeExternalTools(runtime, connectionId, runtimeScope, groups, toolPolicy) {
@@ -270035,7 +270732,9 @@ function registerRuntimeExternalTools(runtime, connectionId, runtimeScope, group
270035
270732
  const registrationScope = createConnectionRequestKey(connectionId, runtimeKey);
270036
270733
  const previousTools = registeredTools.get(registrationScope)?.tools ?? [];
270037
270734
  unregisterExternalTools(previousTools);
270038
- const tools = resolvedGroups.flatMap((group) => group.tools.map((tool) => toExternalToolDefinition(runtime, tool, connectionId, runtimeScope)));
270735
+ const tools = resolvedGroups.flatMap((group) => group.tools.map((tool) => Object.assign(toExternalToolDefinition(runtime, tool, connectionId, runtimeScope), {
270736
+ supportsCancellation: group.capabilities?.external_tool_call_cancel === true
270737
+ })));
270039
270738
  const controllers = getConnectionIdsByRegistrationKey(runtime);
270040
270739
  for (const tool of previousTools) {
270041
270740
  if (tool.registrationKey) {
@@ -271516,7 +272215,7 @@ async function acquireRecoveryClaim(runtime, onLost = () => {}, dependencies4 =
271516
272215
  }
271517
272216
  return null;
271518
272217
  }
271519
- const claim = new RecoveryClaim(runtime, runtime.agentId, runtime.conversationId, connectionId, connectionGeneration, response.token, response.fence, request2, dependencies4.schedule ?? ((callback, delay6) => setTimeout(callback, delay6)), dependencies4.cancel ?? ((timer) => clearTimeout(timer)), onLost, now2, requestedAt + RECOVERY_CLAIM_TTL_MS - RECOVERY_CLAIM_EXPIRY_MARGIN_MS);
272218
+ const claim = new RecoveryClaim(runtime, runtime.agentId, runtime.conversationId, connectionId, connectionGeneration, response.token, response.fence, request2, dependencies4.schedule ?? ((callback, delay7) => setTimeout(callback, delay7)), dependencies4.cancel ?? ((timer) => clearTimeout(timer)), onLost, now2, requestedAt + RECOVERY_CLAIM_TTL_MS - RECOVERY_CLAIM_EXPIRY_MARGIN_MS);
271520
272219
  runtime.listener.activeRecoveryClaims ??= new Set;
271521
272220
  runtime.listener.activeRecoveryClaims.add(claim);
271522
272221
  refusalCounts.delete(runtime.listener);
@@ -274072,7 +274771,7 @@ function toRunsArray(listResponse) {
274072
274771
  }
274073
274772
  return [];
274074
274773
  }
274075
- function withTimeout3(promise2, timeoutMs, timeoutMessage) {
274774
+ function withTimeout4(promise2, timeoutMs, timeoutMessage) {
274076
274775
  return new Promise((resolve38, reject2) => {
274077
274776
  const timer = setTimeout(() => reject2(new Error(timeoutMessage)), timeoutMs);
274078
274777
  promise2.then((value) => {
@@ -274086,7 +274785,7 @@ function withTimeout3(promise2, timeoutMs, timeoutMessage) {
274086
274785
  }
274087
274786
  async function discoverFallbackRunIdWithTimeout(ctx) {
274088
274787
  const client = await getClient();
274089
- return withTimeout3(discoverFallbackRunIdForResume(client, ctx), FALLBACK_RUN_DISCOVERY_TIMEOUT_MS, `Fallback run discovery timed out after ${FALLBACK_RUN_DISCOVERY_TIMEOUT_MS}ms`);
274788
+ return withTimeout4(discoverFallbackRunIdForResume(client, ctx), FALLBACK_RUN_DISCOVERY_TIMEOUT_MS, `Fallback run discovery timed out after ${FALLBACK_RUN_DISCOVERY_TIMEOUT_MS}ms`);
274090
274789
  }
274091
274790
  async function discoverFallbackRunIdForResume(client, ctx) {
274092
274791
  const statuses = ["running"];
@@ -274975,6 +275674,7 @@ async function prepareToolExecutionContextForScope(params) {
274975
275674
  bundledSkills,
274976
275675
  workspaceSandbox,
274977
275676
  executionSettings,
275677
+ foregroundYieldMs,
274978
275678
  cachedAgent,
274979
275679
  modContext,
274980
275680
  modEvents,
@@ -275036,9 +275736,13 @@ async function prepareToolExecutionContextForScope(params) {
275036
275736
  ...skillSources !== undefined ? { skillSources } : {},
275037
275737
  ...bundledSkills !== undefined ? { bundledSkills } : {},
275038
275738
  ...workspaceSandbox !== undefined ? { workspaceSandbox } : {},
275039
- executionSettings
275739
+ executionSettings,
275740
+ foregroundYieldMs
275040
275741
  }
275041
275742
  });
275743
+ const context3 = getExecutionContextById(result3.preparedToolContext.contextId);
275744
+ if (context3)
275745
+ context3.shouldEnqueueBackground = params.shouldEnqueueBackground;
275042
275746
  return { ...result3, agent };
275043
275747
  }
275044
275748
  function shouldClearPersistedToolRules(agent) {
@@ -434357,12 +435061,12 @@ ${options.prefix}` : `
434357
435061
  this.pendingTimeouts = /* @__PURE__ */ new Map;
434358
435062
  this.logger = logger.hasLevel(3) ? logger : undefined;
434359
435063
  }
434360
- schedule(operationId, delay6, cb) {
435064
+ schedule(operationId, delay7, cb) {
434361
435065
  const pendingTimeout = this.pendingTimeouts.get(operationId);
434362
435066
  if (pendingTimeout) {
434363
435067
  this.host.clearTimeout(pendingTimeout);
434364
435068
  }
434365
- this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay6, operationId, this, cb));
435069
+ this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay7, operationId, this, cb));
434366
435070
  if (this.logger) {
434367
435071
  this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`);
434368
435072
  }
@@ -434383,9 +435087,9 @@ ${options.prefix}` : `
434383
435087
  }
434384
435088
  };
434385
435089
  var GcTimer = class _GcTimer {
434386
- constructor(host, delay6, logger) {
435090
+ constructor(host, delay7, logger) {
434387
435091
  this.host = host;
434388
- this.delay = delay6;
435092
+ this.delay = delay7;
434389
435093
  this.logger = logger;
434390
435094
  }
434391
435095
  scheduleCollect() {
@@ -442425,12 +443129,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
442425
443129
  const project = this.projectService.tryGetDefaultProjectForFile(fileName);
442426
443130
  return project && { fileName, project };
442427
443131
  }
442428
- getDiagnostics(next, delay6, fileArgs) {
443132
+ getDiagnostics(next, delay7, fileArgs) {
442429
443133
  if (this.suppressDiagnosticEvents) {
442430
443134
  return;
442431
443135
  }
442432
443136
  if (fileArgs.length > 0) {
442433
- this.updateErrorCheck(next, fileArgs, delay6);
443137
+ this.updateErrorCheck(next, fileArgs, delay7);
442434
443138
  }
442435
443139
  }
442436
443140
  change(args) {
@@ -442792,7 +443496,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
442792
443496
  const spans = languageService.getBraceMatchingAtPosition(file, position);
442793
443497
  return !spans ? undefined : simplifiedResult ? spans.map((span2) => toProtocolTextSpan(span2, scriptInfo)) : spans;
442794
443498
  }
442795
- getDiagnosticsForProject(next, delay6, fileName) {
443499
+ getDiagnosticsForProject(next, delay7, fileName) {
442796
443500
  if (this.suppressDiagnosticEvents) {
442797
443501
  return;
442798
443502
  }
@@ -442826,7 +443530,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
442826
443530
  }
442827
443531
  const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles];
442828
443532
  const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project }));
442829
- this.updateErrorCheck(next, checkList, delay6, false);
443533
+ this.updateErrorCheck(next, checkList, delay7, false);
442830
443534
  }
442831
443535
  configurePlugin(args) {
442832
443536
  this.projectService.configurePlugin(args);
@@ -447088,7 +447792,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
447088
447792
  retryStates.delete(runtime);
447089
447793
  return;
447090
447794
  }
447091
- const delay6 = retryDelay(state2.attempt);
447795
+ const delay7 = retryDelay(state2.attempt);
447092
447796
  state2.attempt += 1;
447093
447797
  state2.scheduled = true;
447094
447798
  state2.timer = setTimeout(() => {
@@ -447097,7 +447801,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
447097
447801
  state2.timer = undefined;
447098
447802
  state2.scheduled = false;
447099
447803
  scheduleRecoveredApprovalRetry(runtime, state2.retry);
447100
- }, delay6);
447804
+ }, delay7);
447101
447805
  state2.timer.unref?.();
447102
447806
  };
447103
447807
  state2.retry().then((handled) => {
@@ -448106,6 +448810,7 @@ async function executeRecoveredApprovalContinuation(params) {
448106
448810
  permissionModeState: getOrCreateConversationPermissionModeStateRef(runtime.listener, recovered.agentId, recovered.conversationId),
448107
448811
  modContext: createListenerAgentModContext(recovered.agentId),
448108
448812
  modAdapters,
448813
+ shouldEnqueueBackground: captureNotificationWait(runtime.listener, scope),
448109
448814
  modEvents: createListenerModEvents(modAdapters)
448110
448815
  });
448111
448816
  if (!hasRecoveryOwnership()) {
@@ -448363,6 +449068,7 @@ var init_recovery = __esm(() => {
448363
449068
  init_constants3();
448364
449069
  init_conversation_runtime();
448365
449070
  init_cwd();
449071
+ init_external_tools();
448366
449072
  init_interrupted_turn_record();
448367
449073
  init_interrupts();
448368
449074
  init_mod_adapter2();
@@ -448622,6 +449328,7 @@ async function resolveStaleApprovals(runtime, socket, turnLease, deps = {}) {
448622
449328
  permissionModeState: getOrCreateConversationPermissionModeStateRef(runtime.listener, runtime.agentId, runtime.conversationId),
448623
449329
  ...runtime.agentId ? { modContext: createListenerAgentModContext(runtime.agentId) } : {},
448624
449330
  modAdapters,
449331
+ shouldEnqueueBackground: captureNotificationWait(runtime.listener, scope),
448625
449332
  modEvents: createListenerModEvents(modAdapters)
448626
449333
  });
448627
449334
  assertCurrentTurnLease();
@@ -449035,6 +449742,7 @@ var init_send = __esm(() => {
449035
449742
  init_connection();
449036
449743
  init_constants3();
449037
449744
  init_cwd();
449745
+ init_external_tools();
449038
449746
  init_interrupted_turn_read();
449039
449747
  init_mod_adapter2();
449040
449748
  init_permission_mode();
@@ -454512,7 +455220,7 @@ var init_core5 = __esm(() => {
454512
455220
  });
454513
455221
 
454514
455222
  // node_modules/@letta-ai/trajectory/dist/adapters/deepagents/index.js
454515
- import { spawn as spawn11 } from "node:child_process";
455223
+ import { spawn as spawn12 } from "node:child_process";
454516
455224
  import { accessSync as accessSync2, constants as constants6 } from "node:fs";
454517
455225
  import { homedir as homedir23 } from "node:os";
454518
455226
  import { join as join84 } from "node:path";
@@ -454543,7 +455251,7 @@ async function loadDeepAgentsCheckpoint(checkpoint) {
454543
455251
  const python = checkpoint.pythonExecutable ?? process.env.PYTHON ?? "python3";
454544
455252
  const helper = resolveHelperPath();
454545
455253
  return await new Promise((resolve38, reject2) => {
454546
- const child = spawn11(python, [helper], {
455254
+ const child = spawn12(python, [helper], {
454547
455255
  stdio: ["pipe", "pipe", "pipe"],
454548
455256
  windowsHide: true
454549
455257
  });
@@ -458694,9 +459402,11 @@ async function prepareListenerTurn(params) {
458694
459402
  bundledSkills: runtime.bundledSkills,
458695
459403
  workspaceSandbox: runtime.workspaceSandbox,
458696
459404
  executionSettings: runtime.executionSettings,
459405
+ foregroundYieldMs: toolOwner.toolPolicy?.foreground_yield_ms,
458697
459406
  cachedAgent,
458698
459407
  ...agentId ? { modContext: createListenerAgentModContext(agentId) } : {},
458699
459408
  modAdapters,
459409
+ shouldEnqueueBackground: captureNotificationWait(runtime.listener, toolRuntimeScope),
458700
459410
  modEvents: createListenerModEvents(modAdapters)
458701
459411
  });
458702
459412
  if (isInterrupted()) {
@@ -460308,10 +461018,10 @@ async function registerWithCloudRetry(opts, callbacks) {
460308
461018
  }
460309
461019
  attempt2++;
460310
461020
  const backoffDelay = Math.min(REGISTER_INITIAL_DELAY_MS * 2 ** (attempt2 - 1), REGISTER_MAX_DELAY_MS);
460311
- const delay6 = error5 instanceof RegistrationError && error5.retryAfterMs !== undefined ? Math.max(error5.retryAfterMs, backoffDelay) : backoffDelay;
460312
- const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay6 * REGISTER_JITTER_RATIO));
461021
+ const delay7 = error5 instanceof RegistrationError && error5.retryAfterMs !== undefined ? Math.max(error5.retryAfterMs, backoffDelay) : backoffDelay;
461022
+ const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay7 * REGISTER_JITTER_RATIO));
460313
461023
  const jitter2 = jitterWindow > 0 ? Math.floor((callbacks?.random ?? Math.random)() * jitterWindow) : 0;
460314
- const retryDelay2 = delay6 + jitter2;
461024
+ const retryDelay2 = delay7 + jitter2;
460315
461025
  if (error5 instanceof Error) {
460316
461026
  callbacks?.onRetry?.(attempt2, retryDelay2, error5);
460317
461027
  }
@@ -460870,7 +461580,9 @@ async function handleAbortMessageInput(listener, params, deps = {}) {
460870
461580
  scheduleQueuePump,
460871
461581
  cancelConversation: async (agentId, conversationId) => {
460872
461582
  const cancelId = conversationId === "default" || !conversationId ? agentId : conversationId;
460873
- await getBackend().cancelConversation(cancelId);
461583
+ const results = await getBackend().cancelConversation(cancelId);
461584
+ if (!Object.values(results).length || Object.values(results).some((value) => value !== "cancelled"))
461585
+ throw new Error("Backend did not confirm cancellation of every run");
460874
461586
  },
460875
461587
  cancelRun: async (agentId, runId) => {
460876
461588
  const result3 = await getBackend().cancelRun(agentId, runId);
@@ -460974,16 +461686,32 @@ async function handleAbortMessageInput(listener, params, deps = {}) {
460974
461686
  const cancelAgentId = scopedRuntime.agentId;
460975
461687
  const cancelRunId = interruptedRunId ?? params.command.run_id ?? null;
460976
461688
  const backendCancellation = cancelAgentId && cancelRunId ? resolvedDeps.cancelRun(cancelAgentId, cancelRunId).catch(() => resolvedDeps.cancelConversation(cancelAgentId, cancelConversationId)) : cancelAgentId ? resolvedDeps.cancelConversation(cancelAgentId, cancelConversationId) : resolvedDeps.cancelConversationRun(cancelConversationId, cancelRunId);
460977
- backendCancellation.catch(() => {}).finally(() => {
461689
+ const pumpQueue = () => resolvedDeps.scheduleQueuePump(scopedRuntime, params.socket, params.opts, params.processQueuedTurn);
461690
+ const settlementPromise = backendCancellation.finally(() => {
460978
461691
  if (!cancellation.lease) {
460979
461692
  return;
460980
461693
  }
460981
461694
  const settlement = scopedRuntime.turnLifecycle.settleCancellation(cancellation.lease);
460982
- if (settlement.released) {
460983
- resolvedDeps.scheduleQueuePump(scopedRuntime, params.socket, params.opts, params.processQueuedTurn);
460984
- }
461695
+ if (settlement.released && !params.confirmBackendCancellation)
461696
+ pumpQueue();
460985
461697
  });
460986
- resolvedDeps.scheduleQueuePump(scopedRuntime, params.socket, params.opts, params.processQueuedTurn);
461698
+ try {
461699
+ if (params.confirmBackendCancellation) {
461700
+ await settlementPromise;
461701
+ const deadline = Date.now() + 1e4;
461702
+ while (cancellation.lease && scopedRuntime.turnLifecycle.isCurrent(cancellation.lease)) {
461703
+ if (Date.now() >= deadline)
461704
+ throw new Error("The listener turn did not stop");
461705
+ await new Promise((resolve39) => setTimeout(resolve39, 20));
461706
+ }
461707
+ } else {
461708
+ settlementPromise.catch(() => {
461709
+ return;
461710
+ });
461711
+ }
461712
+ } finally {
461713
+ pumpQueue();
461714
+ }
460987
461715
  return true;
460988
461716
  }
460989
461717
  async function handleCwdChange(msg, socket, runtime) {
@@ -461434,13 +462162,13 @@ function isStringList(value) {
461434
462162
  function isRuntimeStartExternalToolsGroup(value) {
461435
462163
  if (!isRecord18(value))
461436
462164
  return false;
461437
- return Array.isArray(value.tools) && value.tools.every(isExternalToolDefinitionPayload);
462165
+ return Array.isArray(value.tools) && value.tools.every(isExternalToolDefinitionPayload) && (value.capabilities === undefined || isRecord18(value.capabilities) && (value.capabilities.external_tool_call_cancel === undefined || typeof value.capabilities.external_tool_call_cancel === "boolean"));
461438
462166
  }
461439
462167
  function isRuntimeToolPolicy(value) {
461440
462168
  if (!isRecord18(value))
461441
462169
  return false;
461442
462170
  const toolset = value.toolset;
461443
- return (toolset === undefined || isRecord18(toolset) && (toolset.base === undefined || isToolsetPreference(toolset.base)) && (toolset.include === undefined || isStringList(toolset.include))) && (value.allowlist === undefined || isStringList(value.allowlist)) && (value.exclude_interactive === undefined || typeof value.exclude_interactive === "boolean");
462171
+ return (toolset === undefined || isRecord18(toolset) && (toolset.base === undefined || isToolsetPreference(toolset.base)) && (toolset.include === undefined || isStringList(toolset.include))) && (value.allowlist === undefined || isStringList(value.allowlist)) && (value.exclude_interactive === undefined || typeof value.exclude_interactive === "boolean") && (value.foreground_yield_ms === undefined || typeof value.foreground_yield_ms === "number" && Number.isFinite(value.foreground_yield_ms) && value.foreground_yield_ms > 0);
461444
462172
  }
461445
462173
  function isRuntimeExternalToolsUpdateCommand(value) {
461446
462174
  if (!isRecord18(value))
@@ -461602,7 +462330,14 @@ function isSubagentMessageCommand(value) {
461602
462330
  return typeof value.message === "string" && value.message.trim().length > 0 && (value.tool_call_id === undefined || typeof value.tool_call_id === "string" && value.tool_call_id.trim().length > 0);
461603
462331
  }
461604
462332
  function isSubagentStopCommand(value) {
461605
- return hasValidControlBase(value) && value.type === "subagent_stop";
462333
+ if (!hasValidControlBase(value) || value.type !== "subagent_stop")
462334
+ return false;
462335
+ if (value.client_message_id !== undefined && (typeof value.client_message_id !== "string" || !value.client_message_id.trim()))
462336
+ return false;
462337
+ if (value.conversation === undefined)
462338
+ return true;
462339
+ const scope = value.conversation;
462340
+ return Boolean(scope && typeof scope === "object" && typeof scope.conversation_id === "string" && (scope.agent_id === null || typeof scope.agent_id === "string"));
461606
462341
  }
461607
462342
  function isReadSubagentEventsCommand(value) {
461608
462343
  if (!value || typeof value !== "object")
@@ -464189,7 +464924,7 @@ var init_mod_commands = __esm(() => {
464189
464924
  });
464190
464925
 
464191
464926
  // src/websocket/listener/commands.ts
464192
- import { spawn as spawn12 } from "node:child_process";
464927
+ import { spawn as spawn13 } from "node:child_process";
464193
464928
  async function handleExecuteCommand(command, socket, conversationRuntime, opts) {
464194
464929
  const scope = {
464195
464930
  agent_id: conversationRuntime.agentId,
@@ -464426,7 +465161,7 @@ function scheduleRemoteRestart(connectionName, log3) {
464426
465161
  setTimeout(async () => {
464427
465162
  await flushRemoteSettingsWrites();
464428
465163
  log3(`spawning replacement listener: ${process.execPath} ${entrypoint} remote --computer-name ${connectionName}`);
464429
- const child = spawn12(process.execPath, [entrypoint, "remote", "--computer-name", connectionName], {
465164
+ const child = spawn13(process.execPath, [entrypoint, "remote", "--computer-name", connectionName], {
464430
465165
  cwd: process.cwd(),
464431
465166
  detached: true,
464432
465167
  env: process.env,
@@ -465040,6 +465775,7 @@ function buildAppServerInfoResponse(command, options) {
465040
465775
  runtime_workspace_sandbox: true,
465041
465776
  runtime_external_tools_update: true,
465042
465777
  runtime_tool_policy: true,
465778
+ runtime_tool_policy_foreground_yield: true,
465043
465779
  structured_outputs: options.backend === "api",
465044
465780
  write_file_base64: true,
465045
465781
  split_channels: false
@@ -468630,6 +469366,60 @@ var init_skills_agents = __esm(() => {
468630
469366
  init_protocol_inbound();
468631
469367
  });
468632
469368
 
469369
+ // src/websocket/listener/commands/stop-conversation.ts
469370
+ async function stopListenerConversation(command, abort, deps = {}) {
469371
+ const base2 = {
469372
+ type: "subagent_stop_response",
469373
+ request_id: command.request_id,
469374
+ runtime: command.runtime,
469375
+ agent_id: command.agent_id,
469376
+ success: false,
469377
+ stopped: false
469378
+ };
469379
+ const scope = command.conversation;
469380
+ if (!scope || scope.conversation_id !== command.runtime.conversation_id || scope.agent_id && scope.agent_id !== command.runtime.agent_id)
469381
+ return {
469382
+ ...base2,
469383
+ error: "Stop conversation does not match the control scope"
469384
+ };
469385
+ const backgroundScope = {
469386
+ agentId: scope.agent_id ?? command.runtime.agent_id,
469387
+ conversationId: scope.conversation_id
469388
+ };
469389
+ try {
469390
+ const results = await Promise.allSettled([
469391
+ stopConversationBackground(backgroundScope),
469392
+ abort(scope)
469393
+ ]);
469394
+ for (const result3 of results)
469395
+ if (result3.status === "rejected")
469396
+ throw result3.reason;
469397
+ const aborted2 = results[1]?.status === "fulfilled" && results[1].value;
469398
+ if (!aborted2) {
469399
+ try {
469400
+ const results2 = await getBackend().cancelConversation(scope.conversation_id);
469401
+ if (Object.values(results2).some((value) => value !== "cancelled"))
469402
+ throw new Error("Backend did not confirm cancellation of every run");
469403
+ } catch (error5) {
469404
+ if (!(error5 instanceof ApiRequestError && error5.status === 409))
469405
+ throw error5;
469406
+ }
469407
+ }
469408
+ await stopConversationBackground(backgroundScope);
469409
+ await runWithRuntimeContext({ ...backgroundScope, actingUserId: command.runtime.acting_user_id }, () => (deps.cancelWakes ?? cancelConversationWakes)(backgroundScope));
469410
+ return { ...base2, success: true, stopped: true, cleanup_confirmed: true };
469411
+ } catch (error5) {
469412
+ return { ...base2, error: getErrorMessage2(error5) };
469413
+ }
469414
+ }
469415
+ var init_stop_conversation = __esm(() => {
469416
+ init_backend2();
469417
+ init_request();
469418
+ init_runtime_context();
469419
+ init_stop_conversation_background();
469420
+ init_wake();
469421
+ });
469422
+
468633
469423
  // src/websocket/listener/input-ack.ts
468634
469424
  function acknowledgeInputFrame(send, socket, frame, accepted, error5, disposition, deliveryHandling, mayRecreateOwner, extras) {
468635
469425
  let duplicateOwnerLive;
@@ -469710,18 +470500,46 @@ async function handleSubagentStopCommand(command, parent) {
469710
470500
  if (parent.agentId !== command.runtime.agent_id || parent.conversationId !== command.runtime.conversation_id)
469711
470501
  return { ...base2, error: "Parent runtime does not match the stop request" };
469712
470502
  const owned = findOwnedTask(parent, command.agent_id);
470503
+ let nativeStopped = false;
470504
+ if (!owned && ownsNativeSession(parent, command.agent_id)) {
470505
+ const target2 = parseExternalCodingAgentId(command.agent_id);
470506
+ try {
470507
+ if (target2 && !target2.computer) {
470508
+ if (target2.type === "claude-code")
470509
+ nativeStopped = await stopClaudeSession(target2.sessionId);
470510
+ if (target2.type === "codex")
470511
+ nativeStopped = await stopCodexSession(target2.sessionId);
470512
+ }
470513
+ } catch (error5) {
470514
+ return {
470515
+ ...base2,
470516
+ error: error5 instanceof Error ? error5.message : String(error5)
470517
+ };
470518
+ }
470519
+ }
469713
470520
  if (!owned) {
469714
470521
  if (ownsNativeSession(parent, command.agent_id))
469715
- return { ...base2, success: true };
470522
+ return {
470523
+ ...base2,
470524
+ success: true,
470525
+ stopped: nativeStopped,
470526
+ cleanup_confirmed: true
470527
+ };
469716
470528
  return { ...base2, error: "Subagent does not belong to this conversation" };
469717
470529
  }
469718
- const [, task2] = owned;
470530
+ const [taskId, task2] = owned;
469719
470531
  if (task2.status !== "running")
469720
- return { ...base2, success: true };
470532
+ return { ...base2, success: true, stopped: true, cleanup_confirmed: true };
469721
470533
  if (!task2.abortController)
469722
470534
  return { ...base2, error: "Subagent could not be stopped" };
469723
- task2.abortController.abort(new Error("Stopped by remote parent"));
469724
- return { ...base2, success: true, stopped: true };
470535
+ const result3 = await task_stop({ task_id: taskId });
470536
+ return {
470537
+ ...base2,
470538
+ success: result3.killed,
470539
+ stopped: result3.killed,
470540
+ cleanup_confirmed: result3.killed,
470541
+ error: result3.output
470542
+ };
469725
470543
  }
469726
470544
  var DEDUPE_TTL_MS = 30000, responses;
469727
470545
  var init_subagent_control = __esm(() => {
@@ -469734,6 +470552,7 @@ var init_subagent_control = __esm(() => {
469734
470552
  init_external_coding_agent_task();
469735
470553
  init_native_session_capture();
469736
470554
  init_process_manager();
470555
+ init_task_stop();
469737
470556
  init_cwd();
469738
470557
  responses = new Map;
469739
470558
  });
@@ -469851,6 +470670,13 @@ async function handleTaskControlCommand(command, context3) {
469851
470670
  safeSocketSend
469852
470671
  } = context3;
469853
470672
  const execute = async () => {
470673
+ if (command.type === "subagent_stop" && command.conversation) {
470674
+ const response2 = await stopListenerConversation(command, context3.abortConversation ?? (async () => {
470675
+ throw new Error("Listener cancellation is unavailable");
470676
+ }));
470677
+ safeSocketSend(socket, response2, response2.type, command.type);
470678
+ return;
470679
+ }
469854
470680
  if (command.type === "monitor_stop") {
469855
470681
  const response2 = await handleMonitorStopCommand(command, runtime);
469856
470682
  safeSocketSend(socket, response2, response2.type, command.type);
@@ -469873,6 +470699,7 @@ async function handleTaskControlCommand(command, context3) {
469873
470699
  }
469874
470700
  var init_task_control = __esm(() => {
469875
470701
  init_monitors();
470702
+ init_stop_conversation();
469876
470703
  init_subagent_control();
469877
470704
  init_subagent_events2();
469878
470705
  init_subagents3();
@@ -469902,6 +470729,32 @@ function createListenerMessageHandler(params) {
469902
470729
  } = params;
469903
470730
  const connectionId = explicitConnectionId ?? opts.connectionId;
469904
470731
  const lineageId = explicitLineageId ?? runtime.connections.get(connectionId)?.startupOwner.lineageId ?? connectionId ?? runtime.sessionId;
470732
+ const abortStoppedConversation = async (scope, command) => {
470733
+ const child = getOrCreateScopedRuntime2(runtime, scope.agent_id, scope.conversation_id);
470734
+ child.queueRuntime.pause();
470735
+ for (const item of [...child.queueRuntime.items]) {
470736
+ if (item.source === "task_notification" || item.source === "cron" || command.client_message_id !== undefined && item.clientMessageId === command.client_message_id)
470737
+ child.queueRuntime.removeItem(item.id);
470738
+ }
470739
+ return handleAbortMessageInput2(runtime, {
470740
+ command: {
470741
+ type: "abort_message",
470742
+ request_id: command.request_id,
470743
+ runtime: scope
470744
+ },
470745
+ socket,
470746
+ connectionId,
470747
+ opts,
470748
+ processQueuedTurn,
470749
+ confirmBackendCancellation: true
470750
+ });
470751
+ };
470752
+ const removeLocalStop = registerLocalSubagentStop(connectionId, (command) => {
470753
+ if (runtime !== getActiveRuntime() || runtime.intentionallyClosed)
470754
+ return;
470755
+ return stopListenerConversation(command, (scope) => abortStoppedConversation(scope, command));
470756
+ });
470757
+ socket.once?.("close", removeLocalStop);
469905
470758
  return async (data) => {
469906
470759
  if (!await waitForListenerConnectionStartup(runtime, connectionId, socket))
469907
470760
  return;
@@ -469955,7 +470808,8 @@ function createListenerMessageHandler(params) {
469955
470808
  connectionId,
469956
470809
  getOrCreateScopedRuntime: getOrCreateScopedRuntime2,
469957
470810
  runDetachedListenerTask: runDetachedListenerTask2,
469958
- safeSocketSend
470811
+ safeSocketSend,
470812
+ abortConversation: parsed.type === "subagent_stop" ? (scope) => abortStoppedConversation(scope, parsed) : undefined
469959
470813
  });
469960
470814
  return;
469961
470815
  }
@@ -470340,6 +471194,7 @@ function createListenerMessageHandler(params) {
470340
471194
  var init_message_router = __esm(() => {
470341
471195
  init_system_prompt_warning();
470342
471196
  init_settings_manager();
471197
+ init_subagent_stop_bridge();
470343
471198
  init_debug();
470344
471199
  init_startup_log_boundary();
470345
471200
  init_terminal_handler();
@@ -470360,6 +471215,7 @@ var init_message_router = __esm(() => {
470360
471215
  init_secrets2();
470361
471216
  init_settings3();
470362
471217
  init_skills_agents();
471218
+ init_stop_conversation();
470363
471219
  init_connection();
470364
471220
  init_cwd();
470365
471221
  init_external_tools();
@@ -471937,10 +472793,10 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
471937
472793
  opts.onError(new Error("Failed to connect after 5 minutes of retrying"));
471938
472794
  return;
471939
472795
  }
471940
- const delay6 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
471941
- opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay6, opts.connectionId);
472796
+ const delay7 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
472797
+ opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay7, opts.connectionId);
471942
472798
  await new Promise((resolve39) => {
471943
- runtime.reconnectTimeout = setTimeout(resolve39, delay6);
472799
+ runtime.reconnectTimeout = setTimeout(resolve39, delay7);
471944
472800
  });
471945
472801
  runtime.reconnectTimeout = null;
471946
472802
  if (runtime !== getActiveRuntime() || runtime.intentionallyClosed) {
@@ -474779,7 +475635,7 @@ __export(exports_gateway_supervisor, {
474779
475635
  startChannelGatewaySupervisor: () => startChannelGatewaySupervisor,
474780
475636
  CHANNEL_GATEWAY_READY_SIGNAL: () => CHANNEL_GATEWAY_READY_SIGNAL
474781
475637
  });
474782
- import { spawn as spawn13 } from "node:child_process";
475638
+ import { spawn as spawn14 } from "node:child_process";
474783
475639
  function resolveLauncher(cwd2) {
474784
475640
  const invocation = resolveLettaInvocation(process.env, process.argv, process.execPath, cwd2);
474785
475641
  if (invocation)
@@ -474880,7 +475736,7 @@ async function startChannelGatewaySupervisor(options) {
474880
475736
  function launch() {
474881
475737
  if (stopping)
474882
475738
  return;
474883
- child = (options.spawnProcess ?? spawn13)(launcher.command, childArgs, {
475739
+ child = (options.spawnProcess ?? spawn14)(launcher.command, childArgs, {
474884
475740
  cwd: cwd2,
474885
475741
  env: options.env ?? process.env,
474886
475742
  stdio: ["pipe", "pipe", "pipe"],
@@ -478006,7 +478862,7 @@ var init_model2 = __esm(() => {
478006
478862
  });
478007
478863
 
478008
478864
  // src/mods/package-installer.ts
478009
- import { spawn as spawn14 } from "node:child_process";
478865
+ import { spawn as spawn15 } from "node:child_process";
478010
478866
  import {
478011
478867
  copyFileSync as copyFileSync4,
478012
478868
  existsSync as existsSync68,
@@ -478864,7 +479720,7 @@ var init_package_installer = __esm(() => {
478864
479720
  init_package_registry();
478865
479721
  init_package_manager_spawn();
478866
479722
  SKIPPED_PACKAGE_COPY_NAMES = new Set([".git", "node_modules"]);
478867
- spawnGitInstallProcess = spawn14;
479723
+ spawnGitInstallProcess = spawn15;
478868
479724
  });
478869
479725
 
478870
479726
  // src/mods/package-scaffolder.ts
@@ -508878,7 +509734,7 @@ var init_LettaLoginOverlay = __esm(async () => {
508878
509734
  });
508879
509735
 
508880
509736
  // src/backend/api/mcp-servers.ts
508881
- function withTimeout4(promise2, timeoutMs, label) {
509737
+ function withTimeout5(promise2, timeoutMs, label) {
508882
509738
  let timer;
508883
509739
  const timeout = new Promise((_4, reject2) => {
508884
509740
  timer = setTimeout(() => reject2(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
@@ -508889,10 +509745,10 @@ function withTimeout4(promise2, timeoutMs, label) {
508889
509745
  });
508890
509746
  }
508891
509747
  function listServerMcpServers(client, timeoutMs = 1e4) {
508892
- return withTimeout4(client.mcpServers.list(), timeoutMs, "Listing server-side MCP servers");
509748
+ return withTimeout5(client.mcpServers.list(), timeoutMs, "Listing server-side MCP servers");
508893
509749
  }
508894
509750
  async function listLiveServerMcpTools(client, serverName2, timeoutMs = 15000) {
508895
- const result3 = await withTimeout4(client.get(`/v1/tools/mcp/servers/${encodeURIComponent(serverName2)}/tools`), timeoutMs, `Listing tools for MCP server "${serverName2}"`);
509751
+ const result3 = await withTimeout5(client.get(`/v1/tools/mcp/servers/${encodeURIComponent(serverName2)}/tools`), timeoutMs, `Listing tools for MCP server "${serverName2}"`);
508896
509752
  if (!Array.isArray(result3))
508897
509753
  return [];
508898
509754
  return result3.filter((tool) => typeof tool === "object" && tool !== null && typeof tool.name === "string");
@@ -529383,7 +530239,7 @@ The deployment target for this project is CITATION-DOGFOOD-OK.
529383
530239
  });
529384
530240
 
529385
530241
  // src/mods/learning-harness.ts
529386
- import { spawn as spawn15 } from "node:child_process";
530242
+ import { spawn as spawn16 } from "node:child_process";
529387
530243
  import { access as access2, copyFile as copyFile2, mkdir as mkdir21, readFile as readFile36, writeFile as writeFile24 } from "node:fs/promises";
529388
530244
  import path50 from "node:path";
529389
530245
  function slugify2(value) {
@@ -530323,7 +531179,7 @@ async function writeHistoryArtifacts(params) {
530323
531179
  async function defaultCommandRunner(command, args, options) {
530324
531180
  const startedAt = Date.now();
530325
531181
  return new Promise((resolve44) => {
530326
- const child = spawn15(command, args, {
531182
+ const child = spawn16(command, args, {
530327
531183
  cwd: options.cwd,
530328
531184
  env: options.env,
530329
531185
  stdio: ["ignore", "pipe", "pipe"]
@@ -536753,9 +537609,9 @@ function App2({
536753
537609
  }
536754
537610
  const elapsedSinceClear = Date.now() - lastClearAtRef.current;
536755
537611
  const rateLimitDelay = elapsedSinceClear >= MIN_CLEAR_INTERVAL_MS ? 0 : MIN_CLEAR_INTERVAL_MS - elapsedSinceClear;
536756
- const delay6 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
537612
+ const delay7 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
536757
537613
  if (debugFlicker) {
536758
- console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay6}ms elapsedSinceClear=${elapsedSinceClear}ms`);
537614
+ console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay7}ms elapsedSinceClear=${elapsedSinceClear}ms`);
536759
537615
  }
536760
537616
  resizeClearTimeout.current = setTimeout(() => {
536761
537617
  resizeClearTimeout.current = null;
@@ -536775,7 +537631,7 @@ function App2({
536775
537631
  console.error(`[debug:flicker:resize-fire] clear target=${targetColumns}`);
536776
537632
  }
536777
537633
  clearAndRemount(targetColumns);
536778
- }, delay6);
537634
+ }, delay7);
536779
537635
  }, [clearAndRemount, debugFlicker]);
536780
537636
  import_react124.useEffect(() => {
536781
537637
  const prev = prevColumnsRef.current;
@@ -537281,11 +538137,11 @@ function App2({
537281
538137
  import_react124.useEffect(() => {
537282
538138
  if (deferredCommitAt === null)
537283
538139
  return;
537284
- const delay6 = Math.max(0, deferredCommitAt - Date.now());
538140
+ const delay7 = Math.max(0, deferredCommitAt - Date.now());
537285
538141
  const timer = setTimeout(() => {
537286
538142
  setDeferredCommitAt(null);
537287
538143
  refreshDerived();
537288
- }, delay6);
538144
+ }, delay7);
537289
538145
  return () => clearTimeout(timer);
537290
538146
  }, [deferredCommitAt, refreshDerived]);
537291
538147
  const streamingRefreshTimeoutRef = import_react124.useRef(null);
@@ -543196,4 +544052,4 @@ function registerBunOAuthFlows() {
543196
544052
  registerBunOAuthFlows();
543197
544053
  await init_src5().then(() => exports_src2);
543198
544054
 
543199
- //# debugId=BCE8FF592C80D3DE64756E2164756E21
544055
+ //# debugId=CDC0C27D3A902ABD64756E2164756E21