@letta-ai/letta-code 0.34.49 → 0.34.50

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 (55) 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/app-server-client.d.ts.map +1 -1
  10. package/dist/types/runtime-context.d.ts +2 -0
  11. package/dist/types/runtime-context.d.ts.map +1 -1
  12. package/dist/types/tools/client-tool-background.d.ts +16 -0
  13. package/dist/types/tools/client-tool-background.d.ts.map +1 -0
  14. package/dist/types/tools/external-tool-background.d.ts +4 -1
  15. package/dist/types/tools/external-tool-background.d.ts.map +1 -1
  16. package/dist/types/tools/external-tool-execution.d.ts +9 -0
  17. package/dist/types/tools/external-tool-execution.d.ts.map +1 -0
  18. package/dist/types/tools/external-tool-types.d.ts +4 -0
  19. package/dist/types/tools/external-tool-types.d.ts.map +1 -1
  20. package/dist/types/tools/foreground-yield.d.ts +12 -0
  21. package/dist/types/tools/foreground-yield.d.ts.map +1 -0
  22. package/dist/types/tools/impl/bash.d.ts.map +1 -1
  23. package/dist/types/tools/impl/code-mode.d.ts.map +1 -1
  24. package/dist/types/tools/impl/exec-command.d.ts.map +1 -1
  25. package/dist/types/tools/impl/github-pull-request-cloud.d.ts +75 -0
  26. package/dist/types/tools/impl/github-pull-request-cloud.d.ts.map +1 -0
  27. package/dist/types/tools/impl/kill-bash.d.ts.map +1 -1
  28. package/dist/types/tools/impl/process_manager.d.ts +7 -1
  29. package/dist/types/tools/impl/process_manager.d.ts.map +1 -1
  30. package/dist/types/tools/impl/remote-external-coding-agent.d.ts.map +1 -1
  31. package/dist/types/tools/impl/send-agent-message.d.ts +6 -0
  32. package/dist/types/tools/impl/send-agent-message.d.ts.map +1 -1
  33. package/dist/types/tools/impl/task-stop.d.ts +2 -0
  34. package/dist/types/tools/impl/task-stop.d.ts.map +1 -1
  35. package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
  36. package/dist/types/tools/manager.d.ts +1 -0
  37. package/dist/types/tools/manager.d.ts.map +1 -1
  38. package/dist/types/tools/remote-external-tool-background.d.ts +15 -0
  39. package/dist/types/tools/remote-external-tool-background.d.ts.map +1 -0
  40. package/dist/types/tools/toolset-catalog.d.ts +1 -1
  41. package/dist/types/tools/toolset.d.ts +3 -0
  42. package/dist/types/tools/toolset.d.ts.map +1 -1
  43. package/dist/types/types/app-server-info.d.ts +2 -0
  44. package/dist/types/types/app-server-info.d.ts.map +1 -1
  45. package/dist/types/types/external-tool-protocol.d.ts +15 -0
  46. package/dist/types/types/external-tool-protocol.d.ts.map +1 -1
  47. package/dist/types/types/protocol_v2.d.ts +2 -2
  48. package/dist/types/types/protocol_v2.d.ts.map +1 -1
  49. package/dist/types/websocket/listener/durable-file-lock.d.ts.map +1 -1
  50. package/letta.js +1209 -723
  51. package/npm-shrinkwrap.json +137 -137
  52. package/package.json +2 -2
  53. package/scripts/source-file-size-baseline.json +1 -1
  54. package/skills/using-mcp-tools/SKILL.md +89 -1
  55. 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.50",
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.50"
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, {
@@ -222422,10 +222435,11 @@ Output file: ${outputFile}`
222422
222435
  status: "success"
222423
222436
  };
222424
222437
  }
222425
- var cachedWorkingLauncher = null, DEFAULT_FOREGROUND_YIELD_MS = 1e4, shellProcessStarter, NOTIFICATION_TAIL_LINES = 50;
222438
+ var cachedWorkingLauncher = null, shellProcessStarter, NOTIFICATION_TAIL_LINES = 50;
222426
222439
  var init_bash = __esm(() => {
222427
222440
  init_constants2();
222428
222441
  init_runtime_context();
222442
+ init_foreground_yield();
222429
222443
  init_secret_substitution();
222430
222444
  init_message_queue_bridge();
222431
222445
  init_task_notifications();
@@ -224970,6 +224984,7 @@ function notificationText(toolReturn) {
224970
224984
  return scrubAmbientSecrets(String(toolReturn));
224971
224985
  }
224972
224986
  async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
224987
+ const label = options?.abortController ? "Tool" : "External tool";
224973
224988
  const signal = options?.signal;
224974
224989
  const runtime = options?.runtimeScope;
224975
224990
  const scope = options?.scope ?? (runtime?.agentId && runtime.conversationId ? {
@@ -224979,19 +224994,22 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
224979
224994
  } : undefined);
224980
224995
  const canBackground = () => typeof options?.canBackground === "function" ? options.canBackground() : options?.canBackground !== false;
224981
224996
  if (tool?.autoBackground !== true || !canBackground() || !scope || !options?.enqueue && !isQueueBridgeConnected())
224982
- return signal ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
224997
+ return signal && !options?.abortController ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
224983
224998
  const startedAt = Date.now();
224984
224999
  const settled = operation.then((result2) => ({ kind: "result", result: result2 }), (error5) => ({ kind: "error", error: error5 }));
224985
225000
  let timer;
224986
225001
  let onAbort;
224987
225002
  const abortSettled = signal ? new Promise((resolve21) => {
224988
225003
  onAbort = () => resolve21({ kind: "aborted" });
224989
- signal?.addEventListener("abort", onAbort);
225004
+ if (signal.aborted)
225005
+ onAbort();
225006
+ else
225007
+ signal.addEventListener("abort", onAbort);
224990
225008
  }) : undefined;
224991
225009
  const first = await Promise.race([
224992
225010
  settled,
224993
225011
  new Promise((resolve21) => {
224994
- timer = setTimeout(() => resolve21({ kind: "yield" }), options?.yieldMs ?? DEFAULT_EXTERNAL_TOOL_YIELD_MS);
225012
+ timer = setTimeout(() => resolve21({ kind: "yield" }), options?.yieldMs ?? resolveForegroundYieldMs());
224995
225013
  }),
224996
225014
  ...abortSettled ? [abortSettled] : []
224997
225015
  ]);
@@ -225001,33 +225019,79 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
225001
225019
  signal.removeEventListener("abort", onAbort);
225002
225020
  }
225003
225021
  if (first.kind === "aborted")
225004
- return interruptedExternalToolResult(toolName2);
225022
+ return options?.abortController ? operation : interruptedExternalToolResult(toolName2);
225005
225023
  if (first.kind === "result")
225006
225024
  return first.result;
225007
225025
  if (first.kind === "error")
225008
225026
  throw first.error;
225009
225027
  if (!canBackground()) {
225010
- return signal ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
225028
+ return signal && !options?.abortController ? raceExternalOperationAbort(operation, signal, toolName2) : operation;
225011
225029
  }
225012
225030
  const taskId = `external_${crypto.randomUUID()}`;
225031
+ const outputFile = createBackgroundOutputFile(taskId);
225032
+ const entry = {
225033
+ process: { kill: () => options?.abortController?.abort() },
225034
+ command: toolName2,
225035
+ description: `${label} ${toolName2}`,
225036
+ kind: "tool",
225037
+ remote: !options?.abortController,
225038
+ status: "running",
225039
+ exitCode: null,
225040
+ startTime: new Date(startedAt),
225041
+ outputFile,
225042
+ runtimeScope: scope,
225043
+ actingUserId: scope.actingUserId,
225044
+ ...options?.remoteAbortController ? {
225045
+ cancel: async () => {
225046
+ options.remoteAbortController?.abort();
225047
+ const outcome = await settled;
225048
+ if (outcome.kind === "result" && outcome.result.cancellation === "cancelled") {
225049
+ return { killed: true, output: "Stopped" };
225050
+ }
225051
+ if (outcome.kind === "error" || outcome.result.cancellation === "timeout") {
225052
+ return {
225053
+ killed: false,
225054
+ output: "Cancellation was not confirmed; the remote tool may still finish."
225055
+ };
225056
+ }
225057
+ return {
225058
+ killed: false,
225059
+ output: `Already finished: ${notificationText(outcome.result.toolReturn)}`
225060
+ };
225061
+ }
225062
+ } : {}
225063
+ };
225064
+ backgroundProcesses.set(taskId, entry);
225065
+ options?.onBackground?.(outputFile);
225066
+ notifyBackgroundProcessStateChanged(scope);
225013
225067
  const enqueue = options?.enqueue ?? addToMessageQueue;
225014
225068
  settled.then(async (outcome) => {
225015
- if (await options?.shouldEnqueue?.() === false)
225016
- return;
225017
225069
  const result2 = outcome.kind === "result" ? outcome.result : undefined;
225018
225070
  const status = result2?.status === "success" ? "completed" : "failed";
225019
225071
  const richContent = Array.isArray(result2?.toolReturn) ? result2.toolReturn.map((part) => part.type === "text" ? { ...part, text: scrubAmbientSecrets(part.text) } : part) : undefined;
225020
225072
  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")) {
225073
+ if (!options?.abortController && status === "failed" && (!result2 || typeof result2.toolReturn === "string" && result2.toolReturn.startsWith("External tool execution error:")) && !raw2.includes("outcome is unknown")) {
225022
225074
  raw2 += " The remote tool may still finish; its outcome is unknown. Check the destination before retrying a write.";
225023
225075
  }
225076
+ appendToOutputFile(outputFile, richContent ? `${richContent.map((part) => part.type === "text" ? part.text : "[Image result; see completion notification]").join(`
225077
+ `)}
225078
+ ` : `${raw2}
225079
+ `);
225080
+ if (!entry.completionNotificationSuppressed) {
225081
+ entry.status = status;
225082
+ entry.exitCode = status === "completed" ? 0 : 1;
225083
+ }
225084
+ scheduleBackgroundProcessCleanup(taskId);
225085
+ notifyBackgroundProcessStateChanged(scope);
225086
+ if (entry.completionNotificationSuppressed || await options?.shouldEnqueue?.() === false)
225087
+ return;
225024
225088
  const content = truncateByChars(raw2, LIMITS.TOOL_RETURN_MAX_CHARS + 1000, toolName2);
225025
225089
  enqueue({
225026
225090
  kind: "task_notification",
225027
225091
  text: formatTaskNotification({
225028
225092
  taskId,
225029
225093
  status,
225030
- summary: `External tool ${toolName2} ${status}`,
225094
+ summary: `${label} ${toolName2} ${status}`,
225031
225095
  result: content.content,
225032
225096
  usage: { durationMs: Date.now() - startedAt }
225033
225097
  }),
@@ -225037,17 +225101,70 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
225037
225101
  });
225038
225102
  return {
225039
225103
  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.`
225104
+ toolReturn: `Tool ${toolName2} is still running with task ID: ${taskId}
225105
+ Output file: ${outputFile}
225106
+ You will be notified when it completes.`
225041
225107
  };
225042
225108
  }
225043
- var DEFAULT_EXTERNAL_TOOL_YIELD_MS = 1e4;
225044
225109
  var init_external_tool_background = __esm(() => {
225110
+ init_foreground_yield();
225111
+ init_process_manager();
225045
225112
  init_truncation();
225046
225113
  init_secret_substitution();
225047
225114
  init_message_queue_bridge();
225048
225115
  init_task_notifications();
225049
225116
  });
225050
225117
 
225118
+ // src/tools/client-tool-background.ts
225119
+ function autoBackgroundClientTool(name, operation, options, events) {
225120
+ const controller = new AbortController;
225121
+ const abort = () => controller.abort(options.signal?.reason);
225122
+ if (options.signal?.aborted)
225123
+ abort();
225124
+ else
225125
+ options.signal?.addEventListener("abort", abort, { once: true });
225126
+ let outputFile;
225127
+ const onOutput = (chunk2, stream11) => {
225128
+ options.onOutput?.(chunk2, stream11);
225129
+ if (outputFile)
225130
+ appendToOutputFile(outputFile, scrubAmbientSecrets(chunk2));
225131
+ };
225132
+ const pending2 = (typeof operation === "function" ? operation(controller.signal, onOutput) : operation).finally(() => options.signal?.removeEventListener("abort", abort));
225133
+ if (FOREGROUND_TOOLS.has(name) || SELF_BACKGROUNDING_TOOLS.has(name))
225134
+ return pending2;
225135
+ return runWithRuntimeContext(options.runtimeScope ?? {}, () => autoBackgroundExternalTool(name, { autoBackground: true }, pending2, {
225136
+ ...options,
225137
+ signal: controller.signal,
225138
+ abortController: controller,
225139
+ onBackground: (file) => {
225140
+ outputFile = file;
225141
+ },
225142
+ canBackground: () => !events || events.hasHandlers?.("tool_end") === false
225143
+ }));
225144
+ }
225145
+ var FOREGROUND_TOOLS, SELF_BACKGROUNDING_TOOLS;
225146
+ var init_client_tool_background = __esm(() => {
225147
+ init_runtime_context();
225148
+ init_external_tool_background();
225149
+ init_process_manager();
225150
+ init_secret_substitution();
225151
+ FOREGROUND_TOOLS = new Set([
225152
+ "Edit",
225153
+ "Memory",
225154
+ "Write",
225155
+ "ApplyPatch",
225156
+ "write_artifact_file",
225157
+ "SetWorkingDirectory",
225158
+ "EnterWorktree",
225159
+ "ExitWorktree",
225160
+ "UpdatePlan",
225161
+ "TaskCreate",
225162
+ "TaskUpdate",
225163
+ "AskUserQuestionAsync"
225164
+ ]);
225165
+ SELF_BACKGROUNDING_TOOLS = new Set(["Bash", "exec_command", "CodeMode"]);
225166
+ });
225167
+
225051
225168
  // src/tools/external-tool-background-eligibility.ts
225052
225169
  function enableListenerExternalToolBackground(tool, options) {
225053
225170
  listenerRegistrations.set(tool, options);
@@ -225074,34 +225191,6 @@ var init_external_tool_background_eligibility = __esm(() => {
225074
225191
  listenerRegistrations = new WeakMap;
225075
225192
  });
225076
225193
 
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
225194
  // src/tools/external-tool-content.ts
225106
225195
  function normalizeExternalToolResultContent(content) {
225107
225196
  const normalized = content.flatMap((part) => {
@@ -225130,6 +225219,128 @@ function normalizeExternalToolResultContent(content) {
225130
225219
  return text2 || JSON.stringify(content);
225131
225220
  }
225132
225221
 
225222
+ // src/tools/impl/tool-return-clamp.ts
225223
+ function clampToolReturnText(text2, toolName2) {
225224
+ if (text2.length <= LIMITS.TOOL_RETURN_MAX_CHARS) {
225225
+ return text2;
225226
+ }
225227
+ return truncateByChars(text2, LIMITS.TOOL_RETURN_MAX_CHARS, toolName2, {
225228
+ workingDirectory: getCurrentWorkingDirectory()
225229
+ }).content;
225230
+ }
225231
+ function clampRawToolReturn(rawResult, toolName2) {
225232
+ const text2 = typeof rawResult === "string" ? rawResult : rawResult != null ? JSON.stringify(rawResult) : "";
225233
+ if (text2.length <= LIMITS.TOOL_RETURN_MAX_CHARS + NOTICE_HEADROOM_CHARS) {
225234
+ return text2;
225235
+ }
225236
+ return clampToolReturnText(text2, toolName2 ?? "tool");
225237
+ }
225238
+ function clampToolReturnContent(content, toolName2) {
225239
+ if (typeof content === "string") {
225240
+ return clampToolReturnText(content, toolName2);
225241
+ }
225242
+ return content.map((block) => block.type === "text" ? { ...block, text: clampToolReturnText(block.text, toolName2) } : block);
225243
+ }
225244
+ var NOTICE_HEADROOM_CHARS = 1000;
225245
+ var init_tool_return_clamp = __esm(() => {
225246
+ init_runtime_context();
225247
+ init_truncation();
225248
+ });
225249
+
225250
+ // src/tools/external-tool-execution.ts
225251
+ async function executeExternalToolRequest(toolCallId, toolName2, input, executorOverride, toolDefinition, signal) {
225252
+ const executor = executorOverride;
225253
+ if (!executor) {
225254
+ return {
225255
+ toolReturn: `External tool executor not set for tool: ${toolName2}`,
225256
+ status: "error"
225257
+ };
225258
+ }
225259
+ const startedAt = Date.now();
225260
+ let success = false;
225261
+ try {
225262
+ const tool = toolDefinition;
225263
+ const result2 = await executor(toolCallId, toolName2, input, tool ? { tool, signal } : undefined);
225264
+ success = !result2.isError;
225265
+ return {
225266
+ toolReturn: clampToolReturnContent(normalizeExternalToolResultContent(result2.content), toolName2),
225267
+ status: result2.isError ? "error" : "success",
225268
+ ...result2.cancellation ? { cancellation: result2.cancellation } : {}
225269
+ };
225270
+ } catch (error5) {
225271
+ const errorMessage2 = error5 instanceof Error ? error5.message : String(error5);
225272
+ return {
225273
+ toolReturn: `External tool execution error: ${errorMessage2}`,
225274
+ status: "error"
225275
+ };
225276
+ } finally {
225277
+ if (toolName2 === "MessageChannel" || toolName2 === "message_channel") {
225278
+ telemetry.trackToolUsage(toolName2, success, Date.now() - startedAt, undefined, success ? undefined : "tool_error", undefined, messageChannelTelemetry(input));
225279
+ }
225280
+ }
225281
+ }
225282
+ var init_external_tool_execution = __esm(() => {
225283
+ init_telemetry();
225284
+ init_tool_return_clamp();
225285
+ });
225286
+
225287
+ // src/tools/external-tool-types.ts
225288
+ var EXTERNAL_TOOL_FOREGROUND_INTERRUPTED = "external_tool_foreground_interrupted";
225289
+
225290
+ // src/tools/remote-external-tool-background.ts
225291
+ async function autoBackgroundRemoteExternalTool(name, tool, execute, options) {
225292
+ if (!tool?.supportsCancellation) {
225293
+ return autoBackgroundExternalTool(name, tool, execute(options?.signal), options);
225294
+ }
225295
+ const controller = new AbortController;
225296
+ let backgrounded = false;
225297
+ const abort = () => controller.abort(backgrounded ? undefined : EXTERNAL_TOOL_FOREGROUND_INTERRUPTED);
225298
+ if (options?.signal?.aborted)
225299
+ abort();
225300
+ else
225301
+ options?.signal?.addEventListener("abort", abort, { once: true });
225302
+ const operation = execute(controller.signal).finally(() => options?.signal?.removeEventListener("abort", abort));
225303
+ return autoBackgroundExternalTool(name, tool, operation, {
225304
+ ...options,
225305
+ remoteAbortController: controller,
225306
+ onBackground: (outputFile) => {
225307
+ backgrounded = true;
225308
+ options?.onBackground?.(outputFile);
225309
+ }
225310
+ });
225311
+ }
225312
+ var init_remote_external_tool_background = __esm(() => {
225313
+ init_external_tool_background();
225314
+ });
225315
+
225316
+ // src/tools/tool-context-retention.ts
225317
+ function retainToolContext(contextId) {
225318
+ holders.set(contextId, (holders.get(contextId) ?? 0) + 1);
225319
+ }
225320
+ function releaseRetainedToolContext(contextId) {
225321
+ const count = (holders.get(contextId) ?? 0) - 1;
225322
+ if (count > 0) {
225323
+ holders.set(contextId, count);
225324
+ return false;
225325
+ }
225326
+ holders.delete(contextId);
225327
+ return deferredReleases.delete(contextId);
225328
+ }
225329
+ function isToolContextRetained(contextId) {
225330
+ return holders.has(contextId);
225331
+ }
225332
+ function deferToolContextRelease(contextId) {
225333
+ if (!holders.has(contextId))
225334
+ return false;
225335
+ deferredReleases.add(contextId);
225336
+ return true;
225337
+ }
225338
+ var holders, deferredReleases;
225339
+ var init_tool_context_retention = __esm(() => {
225340
+ holders = new Map;
225341
+ deferredReleases = new Set;
225342
+ });
225343
+
225133
225344
  // src/tools/filter.ts
225134
225345
  var exports_filter = {};
225135
225346
  __export(exports_filter, {
@@ -225214,34 +225425,6 @@ var init_hook_feedback = __esm(() => {
225214
225425
  init_debug();
225215
225426
  });
225216
225427
 
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
225428
  // src/tools/permission-mode-state.ts
225246
225429
  function getEffectivePermissionModeState(permissionModeState) {
225247
225430
  return permissionModeState ?? {
@@ -232725,34 +232908,7 @@ function getExternalToolsAsClientTools() {
232725
232908
  }));
232726
232909
  }
232727
232910
  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
- }
232911
+ return executeExternalToolRequest(toolCallId, toolName2, input, executorOverride ?? getExternalToolExecutor(), toolDefinition ?? getExternalToolDefinition(toolName2), signal);
232756
232912
  }
232757
232913
  function getClientToolsFromRegistry() {
232758
232914
  return buildClientToolsFromSnapshot(filterMemoryToolByMemoryFormat(toolRegistry, undefined), selectModelFacingExternalTools(filterExternalToolsByRuntimeContext(getExternalToolsRegistry(), {})), getAvailableModToolsRegistry());
@@ -233415,6 +233571,12 @@ async function executeToolInner(name, args, options) {
233415
233571
  workingDirectory: context3?.workingDirectory,
233416
233572
  permissionModeState: context3?.permissionModeState
233417
233573
  });
233574
+ const backgroundOptions = {
233575
+ shouldEnqueue: context3?.shouldEnqueueBackground,
233576
+ runtimeScope: executionScope,
233577
+ signal: options?.signal,
233578
+ onOutput: options?.onOutput
233579
+ };
233418
233580
  const workingDirectory = executionScope.workingDirectory ?? getCurrentWorkingDirectory();
233419
233581
  const scopedAgentId = executionScope.agentId ?? undefined;
233420
233582
  const modContext = context3?.modContext ?? toolExecutionModContext(executionScope, { workingDirectory });
@@ -233467,14 +233629,14 @@ async function executeToolInner(name, args, options) {
233467
233629
  return createModPermissionToolResult(permissionDecision2);
233468
233630
  }
233469
233631
  }
233470
- return executeModTool(name, modTool, eventArgs2, executionScope, {
233471
- signal: options?.signal,
233632
+ return autoBackgroundClientTool(name, (signal, onOutput) => executeModTool(name, modTool, eventArgs2, executionScope, {
233633
+ signal,
233472
233634
  toolCallId: options?.toolCallId,
233473
- onOutput: options?.onOutput,
233635
+ onOutput,
233474
233636
  workingDirectory,
233475
233637
  scopedAgentId,
233476
233638
  modContext
233477
- });
233639
+ }), backgroundOptions, modEvents);
233478
233640
  }
233479
233641
  if (activeExternalTools.has(name)) {
233480
233642
  const externalTool = activeExternalTools.get(name);
@@ -233504,7 +233666,10 @@ async function executeToolInner(name, args, options) {
233504
233666
  if (permissionDecision2?.decision !== undefined && permissionDecision2.decision !== "allow") {
233505
233667
  return createModPermissionToolResult(permissionDecision2);
233506
233668
  }
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)));
233669
+ if (externalTool?.executor && externalTool.autoBackground === undefined) {
233670
+ return runWithRuntimeContext(executionScope, () => autoBackgroundClientTool(name, (signal) => executeExternalTool(options?.toolCallId ?? `ext-${Date.now()}`, name, eventArgs2, externalTool.executor, externalTool, signal), backgroundOptions, modEvents));
233671
+ }
233672
+ 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
233673
  }
233509
233674
  const internalName = resolveInternalToolName(name, activeRegistry);
233510
233675
  const tool = internalName ? activeRegistry.get(internalName) : undefined;
@@ -233552,7 +233717,7 @@ async function executeToolInner(name, args, options) {
233552
233717
  }
233553
233718
  }
233554
233719
  const startTime = Date.now();
233555
- const run = async () => {
233720
+ const run = async (signal, onOutput) => {
233556
233721
  const preHookResult = await runPreToolUseHooks(internalName, args, options?.toolCallId, workingDirectory, scopedAgentId);
233557
233722
  if (preHookResult.blocked) {
233558
233723
  const feedback = preHookResult.feedback.join(`
@@ -233575,15 +233740,13 @@ async function executeToolInner(name, args, options) {
233575
233740
  let outputStreamer = null;
233576
233741
  try {
233577
233742
  let enhancedArgs = expandPathArgs(internalName, args, workingDirectory);
233578
- if (options?.signal) {
233579
- enhancedArgs = { ...enhancedArgs, signal: options.signal };
233580
- }
233743
+ enhancedArgs = { ...enhancedArgs, signal };
233581
233744
  if (STREAMING_SHELL_TOOLS.has(internalName)) {
233582
233745
  const command = enhancedArgs.command ?? enhancedArgs.cmd;
233583
233746
  invocationSecrets = typeof command === "string" || Array.isArray(command) && command.every((part) => typeof part === "string") ? await resolveSecretEnvFromCommand(command, scopedAgentId) : {};
233584
233747
  invocationRedactions = captureSecretRedactions(scopedAgentId, invocationSecrets);
233585
- if (options?.onOutput) {
233586
- outputStreamer = createScrubbedOutputStreamer(invocationRedactions, options.onOutput, stripAnsi);
233748
+ if (onOutput) {
233749
+ outputStreamer = createScrubbedOutputStreamer(invocationRedactions, onOutput, stripAnsi);
233587
233750
  enhancedArgs = { ...enhancedArgs, onOutput: outputStreamer.onOutput };
233588
233751
  }
233589
233752
  if (Object.keys(invocationSecrets).length > 0) {
@@ -233683,7 +233846,7 @@ async function executeToolInner(name, args, options) {
233683
233846
  };
233684
233847
  }
233685
233848
  };
233686
- return runWithRuntimeContext(executionScope, run);
233849
+ return runWithRuntimeContext(executionScope, () => autoBackgroundClientTool(internalName, run, backgroundOptions, modEvents));
233687
233850
  }
233688
233851
  async function executeTool(...params) {
233689
233852
  const [name, args, options] = params;
@@ -233791,8 +233954,10 @@ var init_manager2 = __esm(() => {
233791
233954
  init_runtime_execution_settings();
233792
233955
  init_settings_manager();
233793
233956
  init_telemetry();
233794
- init_external_tool_background();
233957
+ init_client_tool_background();
233795
233958
  init_external_tool_background_eligibility();
233959
+ init_external_tool_execution();
233960
+ init_remote_external_tool_background();
233796
233961
  init_tool_context_retention();
233797
233962
  init_checkout_readiness();
233798
233963
  init_debug();
@@ -236067,7 +236232,7 @@ async function code_mode(args) {
236067
236232
  const {
236068
236233
  run_in_background = false,
236069
236234
  signal,
236070
- foregroundYieldMs = DEFAULT_FOREGROUND_YIELD_MS2
236235
+ foregroundYieldMs = resolveForegroundYieldMs()
236071
236236
  } = args;
236072
236237
  if (typeof args.code !== "string" || !args.code.trim()) {
236073
236238
  return {
@@ -236207,9 +236372,10 @@ Output file: ${outputFile}`,
236207
236372
  status: "success"
236208
236373
  };
236209
236374
  }
236210
- var DEFAULT_FOREGROUND_YIELD_MS2 = 1e4, MAX_NOTIFICATION_RESULT_CHARS = 30000;
236375
+ var MAX_NOTIFICATION_RESULT_CHARS = 30000;
236211
236376
  var init_code_mode = __esm(() => {
236212
236377
  init_constants2();
236378
+ init_foreground_yield();
236213
236379
  init_script_tool_scope();
236214
236380
  init_workflow_engine();
236215
236381
  init_message_queue_bridge();
@@ -239752,7 +239918,7 @@ async function exec_command(args) {
239752
239918
  throw new Error("cmd must be a non-empty string");
239753
239919
  }
239754
239920
  const session3 = await startExecSession(args);
239755
- const yieldTimeMs = clampYieldTime(args.yield_time_ms, DEFAULT_EXEC_YIELD_TIME_MS);
239921
+ const yieldTimeMs = clampYieldTime(args.yield_time_ms, resolveForegroundYieldMs());
239756
239922
  const { output, wallTimeMs } = await waitForSessionOutput({
239757
239923
  session: session3,
239758
239924
  startOffset: 0,
@@ -239848,10 +240014,11 @@ async function write_stdin(args) {
239848
240014
  output: scrubSecretsFromString(formattedOutput, session3.secrets)
239849
240015
  };
239850
240016
  }
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;
240017
+ 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
240018
  var init_exec_command = __esm(() => {
239853
240019
  init_usable_directory();
239854
240020
  init_runtime_context();
240021
+ init_foreground_yield();
239855
240022
  init_secret_substitution();
239856
240023
  init_message_queue_bridge();
239857
240024
  init_task_notifications();
@@ -244717,18 +244884,39 @@ function onceSocketEvent(socket, type3, listener) {
244717
244884
  });
244718
244885
  return detach;
244719
244886
  }
244720
- function waitForSocketOpen(socket) {
244887
+ function waitForSocketOpen(socket, timeoutMs) {
244721
244888
  if (socket.readyState === WEBSOCKET_OPEN_STATE) {
244722
244889
  return Promise.resolve();
244723
244890
  }
244724
- return new Promise((resolve35, reject2) => {
244891
+ return new Promise((resolvePromise, rejectPromise) => {
244892
+ let settled = false;
244893
+ const resolve35 = () => {
244894
+ if (settled)
244895
+ return;
244896
+ settled = true;
244897
+ resolvePromise();
244898
+ };
244899
+ const reject2 = (error5) => {
244900
+ if (settled)
244901
+ return;
244902
+ settled = true;
244903
+ rejectPromise(error5);
244904
+ };
244725
244905
  let detachOpen = () => {};
244726
244906
  let detachError = () => {};
244907
+ let detachClose = () => {};
244727
244908
  let detachResponse = () => {};
244728
244909
  let detachBody = () => {};
244910
+ let upgradeRejected = false;
244911
+ const timer = timeoutMs > 0 ? setTimeout(() => {
244912
+ cleanup();
244913
+ reject2(new Error(`App-server WebSocket failed to open: timed out after ${timeoutMs}ms`));
244914
+ }, timeoutMs) : undefined;
244729
244915
  const cleanup = () => {
244916
+ clearTimeout(timer);
244730
244917
  detachOpen();
244731
244918
  detachError();
244919
+ detachClose();
244732
244920
  detachResponse();
244733
244921
  detachBody();
244734
244922
  };
@@ -244740,6 +244928,7 @@ function waitForSocketOpen(socket) {
244740
244928
  const onResponse = (_request, response) => {
244741
244929
  if (!response)
244742
244930
  return;
244931
+ upgradeRejected = true;
244743
244932
  const request = _request;
244744
244933
  let body3 = Buffer.alloc(0);
244745
244934
  let finished2 = false;
@@ -244781,6 +244970,12 @@ function waitForSocketOpen(socket) {
244781
244970
  cleanup();
244782
244971
  reject2(new Error(`App-server WebSocket failed to open: ${String(event)}`));
244783
244972
  });
244973
+ detachClose = onceSocketEvent(socket, "close", () => {
244974
+ if (upgradeRejected)
244975
+ return;
244976
+ cleanup();
244977
+ reject2(new Error("App-server WebSocket failed to open: closed before opening"));
244978
+ });
244784
244979
  });
244785
244980
  }
244786
244981
  function rawEventData(event) {
@@ -244848,7 +245043,7 @@ class AppServerClient {
244848
245043
  });
244849
245044
  }
244850
245045
  async connect() {
244851
- await waitForSocketOpen(this.socket);
245046
+ await waitForSocketOpen(this.socket, this.requestTimeoutMs);
244852
245047
  return this;
244853
245048
  }
244854
245049
  close() {
@@ -246178,6 +246373,284 @@ var init_child_send_tracking = __esm(() => {
246178
246373
  init_remote_turn_wait();
246179
246374
  });
246180
246375
 
246376
+ // src/mods/capabilities.ts
246377
+ function isModCapabilityId(value) {
246378
+ return MOD_CAPABILITY_ID_SET.has(value);
246379
+ }
246380
+ function resolveProcessModCapabilities(configuredCapabilities, env6 = process.env) {
246381
+ if (env6[LETTA_MOD_CAPABILITY_PROFILE_ENV] === PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE) {
246382
+ return cloneModCapabilities(PROVIDERS_ONLY_MOD_CAPABILITIES);
246383
+ }
246384
+ return resolveModCapabilities(configuredCapabilities);
246385
+ }
246386
+ function cloneModCapabilities(capabilities) {
246387
+ return {
246388
+ tools: capabilities.tools,
246389
+ commands: capabilities.commands,
246390
+ events: {
246391
+ lifecycle: capabilities.events.lifecycle,
246392
+ tools: capabilities.events.tools,
246393
+ turns: capabilities.events.turns,
246394
+ compact: capabilities.events.compact,
246395
+ llm: capabilities.events.llm
246396
+ },
246397
+ permissions: capabilities.permissions,
246398
+ providers: capabilities.providers,
246399
+ ui: {
246400
+ panels: capabilities.ui.panels
246401
+ }
246402
+ };
246403
+ }
246404
+ function resolveModCapabilities(capabilities) {
246405
+ return cloneModCapabilities(capabilities ?? DEFAULT_MOD_CAPABILITIES);
246406
+ }
246407
+ 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";
246408
+ var init_capabilities = __esm(() => {
246409
+ MOD_CAPABILITY_IDS = [
246410
+ "tools",
246411
+ "commands",
246412
+ "providers",
246413
+ "permissions",
246414
+ "events.lifecycle",
246415
+ "events.turns",
246416
+ "events.tools",
246417
+ "events.compact",
246418
+ "events.llm",
246419
+ "ui.panels"
246420
+ ];
246421
+ MOD_CAPABILITY_ID_SET = new Set(MOD_CAPABILITY_IDS);
246422
+ DEFAULT_MOD_CAPABILITIES = {
246423
+ tools: true,
246424
+ commands: true,
246425
+ events: {
246426
+ lifecycle: true,
246427
+ tools: true,
246428
+ turns: true,
246429
+ compact: true,
246430
+ llm: true
246431
+ },
246432
+ permissions: true,
246433
+ providers: true,
246434
+ ui: {
246435
+ panels: true
246436
+ }
246437
+ };
246438
+ DISABLED_MOD_CAPABILITIES = {
246439
+ tools: false,
246440
+ commands: false,
246441
+ events: {
246442
+ lifecycle: false,
246443
+ tools: false,
246444
+ turns: false,
246445
+ compact: false,
246446
+ llm: false
246447
+ },
246448
+ permissions: false,
246449
+ providers: false,
246450
+ ui: {
246451
+ panels: false
246452
+ }
246453
+ };
246454
+ PROVIDERS_ONLY_MOD_CAPABILITIES = {
246455
+ ...DISABLED_MOD_CAPABILITIES,
246456
+ events: { ...DISABLED_MOD_CAPABILITIES.events },
246457
+ providers: true,
246458
+ ui: { ...DISABLED_MOD_CAPABILITIES.ui }
246459
+ };
246460
+ });
246461
+
246462
+ // src/utils/transcript-paths.ts
246463
+ import { join as join62 } from "node:path";
246464
+ function getTranscriptRoot() {
246465
+ const envRoot = process.env[TRANSCRIPT_ROOT_ENV]?.trim();
246466
+ if (envRoot) {
246467
+ return envRoot;
246468
+ }
246469
+ return join62(resolveGlobalConfigDir(), "transcripts");
246470
+ }
246471
+ var TRANSCRIPT_ROOT_ENV = "LETTA_TRANSCRIPT_ROOT";
246472
+ var init_transcript_paths = __esm(() => {
246473
+ init_settings_path();
246474
+ });
246475
+
246476
+ // src/agent/subagents/memory-worker-session.ts
246477
+ function isMemoryWorkerSession(env6 = process.env) {
246478
+ return env6[MEMORY_WORKER_SESSION_ENV] === "1";
246479
+ }
246480
+ var MEMORY_WORKER_SESSION_ENV = "LETTA_MEMORY_WORKER_SESSION";
246481
+
246482
+ // src/agent/subagents/subagent-launcher.ts
246483
+ import { homedir as homedir18 } from "node:os";
246484
+ import { join as join63 } from "node:path";
246485
+ function resolveSubagentWorkingDirectory(env6 = process.env, fallbackCwd = getCurrentWorkingDirectory(), options = {}) {
246486
+ if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope) {
246487
+ return env6.USER_CWD || fallbackCwd;
246488
+ }
246489
+ if (options.subagentType !== "reflection" && options.launchProfile === "memory-subagent" && options.memoryScope?.primaryRoot) {
246490
+ return options.memoryScope.primaryRoot;
246491
+ }
246492
+ const primaryRoot = options.memoryScope?.primaryRoot ?? options.inheritedPrimaryRoot;
246493
+ if (options.subagentType === "reflection" && options.launchProfile === "memory-subagent" && primaryRoot) {
246494
+ return primaryRoot;
246495
+ }
246496
+ return env6.USER_CWD || fallbackCwd;
246497
+ }
246498
+ function resolveSubagentLauncher(cliArgs, options = {}) {
246499
+ const env6 = options.env ?? process.env;
246500
+ const argv = options.argv ?? process.argv;
246501
+ const execPath = options.execPath ?? process.execPath;
246502
+ const platform7 = options.platform ?? process.platform;
246503
+ const cwd2 = options.cwd ?? process.cwd();
246504
+ const invocation = resolveLettaInvocation(env6, argv, execPath, cwd2);
246505
+ if (invocation) {
246506
+ return {
246507
+ command: invocation.command,
246508
+ args: [...invocation.args, ...cliArgs]
246509
+ };
246510
+ }
246511
+ const currentScript = argv[1] || "";
246512
+ const resolvedCurrentScript = resolveEntryScriptPath(currentScript, cwd2);
246513
+ if (currentScript.endsWith(".ts")) {
246514
+ return {
246515
+ command: execPath,
246516
+ args: [resolvedCurrentScript, ...cliArgs]
246517
+ };
246518
+ }
246519
+ if (currentScript.endsWith(".js") && platform7 === "win32") {
246520
+ return {
246521
+ command: execPath,
246522
+ args: [resolvedCurrentScript, ...cliArgs]
246523
+ };
246524
+ }
246525
+ if (currentScript.endsWith(".js")) {
246526
+ return {
246527
+ command: resolvedCurrentScript,
246528
+ args: cliArgs
246529
+ };
246530
+ }
246531
+ return {
246532
+ command: "letta",
246533
+ args: cliArgs
246534
+ };
246535
+ }
246536
+ function resolveMemorySubagentScratchpad(parentProcessEnv, subagentId) {
246537
+ const configuredScratchpad = parentProcessEnv.LETTA_SCRATCHPAD;
246538
+ if (configuredScratchpad?.trim()) {
246539
+ return configuredScratchpad;
246540
+ }
246541
+ const configuredTranscriptRoot = parentProcessEnv[TRANSCRIPT_ROOT_ENV];
246542
+ const transcriptRoot = configuredTranscriptRoot?.trim() || join63(resolveGlobalConfigDir(parentProcessEnv, homedir18()), "transcripts");
246543
+ const scope = subagentId ? encodeURIComponent(subagentId) : crypto.randomUUID();
246544
+ return join63(transcriptRoot, "background", scope);
246545
+ }
246546
+ function composeSubagentChildEnv(options) {
246547
+ const {
246548
+ parentProcessEnv,
246549
+ listenerConnectionId,
246550
+ backendMode,
246551
+ localBackendStorageDir,
246552
+ parentAgentId,
246553
+ subagentType,
246554
+ launchProfile,
246555
+ inheritedPrimaryRoot,
246556
+ memoryScope,
246557
+ inheritedApiKey,
246558
+ inheritedBaseUrl,
246559
+ actingUserId,
246560
+ transcriptPath
246561
+ } = options;
246562
+ const childEnv = {
246563
+ ...parentProcessEnv,
246564
+ ...inheritedApiKey && { LETTA_API_KEY: inheritedApiKey },
246565
+ ...inheritedBaseUrl && { LETTA_BASE_URL: inheritedBaseUrl },
246566
+ DISABLE_AUTOUPDATER: "1",
246567
+ LETTA_CODE_AGENT_ROLE: "subagent",
246568
+ [MEMORY_WORKER_SESSION_ENV]: subagentType === "memory" ? "1" : undefined,
246569
+ [SUBAGENT_LAUNCH_ENV]: "1",
246570
+ [SUBAGENT_LAUNCH_PROFILE_ENV]: launchProfile ?? "default",
246571
+ ...(subagentType === "reflection" || subagentType === "memory") && {
246572
+ [LETTA_MOD_CAPABILITY_PROFILE_ENV]: PROVIDERS_ONLY_MOD_CAPABILITY_PROFILE
246573
+ },
246574
+ LETTA_PARENT_AGENT_ID: parentAgentId,
246575
+ LETTA_PARENT_CONVERSATION_ID: options.parentConversationId,
246576
+ [SUBAGENT_DEPTH_ENV]: String(readSubagentDepth(parentProcessEnv) + 1),
246577
+ ...transcriptPath && { TRANSCRIPT_PATH: transcriptPath }
246578
+ };
246579
+ if (actingUserId)
246580
+ childEnv[ACTING_USER_ID_ENV] = actingUserId;
246581
+ else if (actingUserId === null)
246582
+ delete childEnv[ACTING_USER_ID_ENV];
246583
+ delete childEnv[SUBAGENT_NAME_ENV];
246584
+ if (options.subagentName)
246585
+ childEnv[SUBAGENT_NAME_ENV] = options.subagentName;
246586
+ if (backendMode === "local") {
246587
+ childEnv.LETTA_LOCAL_BACKEND_EXPERIMENTAL = "1";
246588
+ if (localBackendStorageDir) {
246589
+ childEnv.LETTA_LOCAL_BACKEND_DIR = localBackendStorageDir;
246590
+ }
246591
+ } else if (backendMode === "api") {
246592
+ childEnv.LETTA_LOCAL_BACKEND_EXPERIMENTAL = "0";
246593
+ }
246594
+ if (launchProfile === "memory-subagent") {
246595
+ delete childEnv[LISTENER_CONNECTION_ENV];
246596
+ childEnv.LETTA_SCRATCHPAD = resolveMemorySubagentScratchpad(parentProcessEnv, options.subagentId);
246597
+ const primaryRoot = memoryScope?.primaryRoot ?? inheritedPrimaryRoot;
246598
+ if (primaryRoot) {
246599
+ childEnv.MEMORY_DIR = primaryRoot;
246600
+ childEnv.LETTA_MEMORY_DIR = primaryRoot;
246601
+ } else {
246602
+ delete childEnv.MEMORY_DIR;
246603
+ delete childEnv.LETTA_MEMORY_DIR;
246604
+ }
246605
+ } else if (listenerConnectionId?.startsWith("conn-")) {
246606
+ childEnv[LISTENER_CONNECTION_ENV] = listenerConnectionId;
246607
+ } else if (isUnattachedListenerLaunch({
246608
+ listenerConnectionId,
246609
+ launchProfile,
246610
+ listenerConnectionCount: getActiveRuntime()?.connections.size ?? 0
246611
+ })) {
246612
+ trackBoundaryError({
246613
+ errorType: "subagent_launch_missing_listener_connection",
246614
+ error: new Error("Subagent launched in a listener without its connection"),
246615
+ context: "subagent_launch"
246616
+ });
246617
+ }
246618
+ return childEnv;
246619
+ }
246620
+ function isUnattachedListenerLaunch(options) {
246621
+ return !options.listenerConnectionId && options.launchProfile !== "memory-subagent" && options.listenerConnectionCount > 0;
246622
+ }
246623
+ function shouldLaunchThroughListener(options) {
246624
+ if (options.ephemeral) {
246625
+ if (options.computer)
246626
+ throw new Error("Ephemeral conversations cannot be routed to a Cloud computer");
246627
+ return false;
246628
+ }
246629
+ if (options.launchProfile === "memory-subagent") {
246630
+ if (options.computer)
246631
+ throw new Error("Memory subagents must run in their confined local process, not through a computer listener");
246632
+ return false;
246633
+ }
246634
+ return Boolean(options.computer) || options.cloudBackend && Boolean(options.connectionId);
246635
+ }
246636
+ function resolveSubagentInheritedPrimaryRoot(options) {
246637
+ if (options.backendMode === "local" && options.parentAgentId) {
246638
+ return getLocalBackendMemoryFilesystemRoot(options.parentAgentId, options.localBackendStorageDir ?? getLocalBackendStorageDir2());
246639
+ }
246640
+ return options.inheritedPrimaryRoot;
246641
+ }
246642
+ var init_subagent_launcher = __esm(() => {
246643
+ init_backend2();
246644
+ init_paths();
246645
+ init_capabilities();
246646
+ init_runtime_context();
246647
+ init_error_reporting();
246648
+ init_shell_env();
246649
+ init_settings_path();
246650
+ init_transcript_paths();
246651
+ init_runtime6();
246652
+ });
246653
+
246181
246654
  // src/backend/api/agent-message.ts
246182
246655
  function normalizeAgentMessageComputer(value) {
246183
246656
  if (value == null)
@@ -246217,7 +246690,7 @@ function validateAddress(value, kind) {
246217
246690
  return;
246218
246691
  if (kind === "conversation" && value === "default")
246219
246692
  return value;
246220
- const prefix = kind === "agent" ? "agent" : "conv";
246693
+ const prefix = kind === "agent" ? "agent" : "(local-)?conv";
246221
246694
  if (!new RegExp(`^${prefix}-[a-zA-Z0-9-]+$`).test(value)) {
246222
246695
  throw new Error(`Invalid ${kind} ID: ${JSON.stringify(value)}`);
246223
246696
  }
@@ -246374,12 +246847,12 @@ var init_subagent_process = __esm(() => {
246374
246847
  });
246375
246848
 
246376
246849
  // src/utils/native-cli-env.ts
246377
- import { homedir as homedir18 } from "node:os";
246378
- import { join as join62 } from "node:path";
246850
+ import { homedir as homedir19 } from "node:os";
246851
+ import { join as join64 } from "node:path";
246379
246852
  function withNativeCliPath(env6, platform7 = process.platform) {
246380
246853
  if (platform7 === "win32")
246381
246854
  return { ...env6 };
246382
- const nativeBin = join62(env6.HOME || homedir18(), ".local", "bin");
246855
+ const nativeBin = join64(env6.HOME || homedir19(), ".local", "bin");
246383
246856
  const paths = (env6.PATH ?? "/usr/bin:/bin").split(":");
246384
246857
  if (!paths.includes(nativeBin))
246385
246858
  paths.push(nativeBin);
@@ -247829,7 +248302,7 @@ class CodexAppServerClient {
247829
248302
  await this.request("initialize", {
247830
248303
  clientInfo: {
247831
248304
  name: "letta-code",
247832
- version: "0.34.49"
248305
+ version: "0.34.50"
247833
248306
  },
247834
248307
  capabilities: null
247835
248308
  });
@@ -248357,7 +248830,7 @@ var init_codex_app_server = __esm(() => {
248357
248830
  // src/tools/impl/cursor-session.ts
248358
248831
  import { randomUUID as randomUUID40 } from "node:crypto";
248359
248832
  import { existsSync as existsSync46 } from "node:fs";
248360
- import { join as join63 } from "node:path";
248833
+ import { join as join65 } from "node:path";
248361
248834
  import { createInterface as createInterface10 } from "node:readline";
248362
248835
  import { fileURLToPath as fileURLToPath7 } from "node:url";
248363
248836
  function key2(options, id2) {
@@ -248513,7 +248986,7 @@ async function runCursorTurn(options, env6 = process.env, secrets2 = {}) {
248513
248986
  type: "start",
248514
248987
  sessionId: id2,
248515
248988
  resume: !!options.resumeSessionId,
248516
- stateDir: join63(resolveGlobalConfigDir(), "cursor-sessions", sessionKey),
248989
+ stateDir: join65(resolveGlobalConfigDir(), "cursor-sessions", sessionKey),
248517
248990
  cwd: options.cwd,
248518
248991
  model: options.model,
248519
248992
  reminder: options.mcpReminder,
@@ -249572,8 +250045,8 @@ import {
249572
250045
  rm as rm8,
249573
250046
  stat as stat10
249574
250047
  } from "node:fs/promises";
249575
- import { homedir as homedir19, tmpdir as tmpdir13 } from "node:os";
249576
- import { join as join64 } from "node:path";
250048
+ import { homedir as homedir20, tmpdir as tmpdir13 } from "node:os";
250049
+ import { join as join66 } from "node:path";
249577
250050
  async function hashNativeSessionPrefix(input, size2) {
249578
250051
  const hash3 = createHash10("sha256");
249579
250052
  const buffer = Buffer.allocUnsafe(NATIVE_SESSION_CAPTURE_CHUNK_BYTES);
@@ -249658,7 +250131,7 @@ function scavengeStaleSpoolDirectories() {
249658
250131
  }
249659
250132
  }
249660
250133
  if (!ownerIsAlive)
249661
- cleanupSpoolDirectorySync(join64(tmpdir13(), entry.name));
250134
+ cleanupSpoolDirectorySync(join66(tmpdir13(), entry.name));
249662
250135
  }
249663
250136
  }
249664
250137
  function key3(source, sessionId) {
@@ -249809,11 +250282,11 @@ async function entries(path30, directories) {
249809
250282
  async function findNativeSessionPath(source, sessionId, env6 = process.env) {
249810
250283
  if (!UUID2.test(sessionId))
249811
250284
  return;
249812
- const home = env6.HOME || homedir19();
250285
+ const home = env6.HOME || homedir20();
249813
250286
  if (source === "claude_code") {
249814
- const projects = join64(env6.CLAUDE_CONFIG_DIR || join64(home, ".claude"), "projects");
250287
+ const projects = join66(env6.CLAUDE_CONFIG_DIR || join66(home, ".claude"), "projects");
249815
250288
  for (const project of await entries(projects, true)) {
249816
- const path30 = join64(projects, project, `${sessionId}.jsonl`);
250289
+ const path30 = join66(projects, project, `${sessionId}.jsonl`);
249817
250290
  try {
249818
250291
  if ((await stat10(path30)).isFile())
249819
250292
  return path30;
@@ -249824,14 +250297,14 @@ async function findNativeSessionPath(source, sessionId, env6 = process.env) {
249824
250297
  }
249825
250298
  return;
249826
250299
  }
249827
- const root2 = join64(env6.CODEX_HOME || join64(home, ".codex"), "sessions");
250300
+ const root2 = join66(env6.CODEX_HOME || join66(home, ".codex"), "sessions");
249828
250301
  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);
250302
+ for (const month of (await entries(join66(root2, year), true)).filter((name) => /^\d{2}$/.test(name)))
250303
+ for (const day of (await entries(join66(root2, year, month), true)).filter((name) => /^\d{2}$/.test(name))) {
250304
+ const directory = join66(root2, year, month, day);
249832
250305
  for (const file of await entries(directory, false))
249833
250306
  if (file.startsWith("rollout-") && file.endsWith(`-${sessionId}.jsonl`))
249834
- return join64(directory, file);
250307
+ return join66(directory, file);
249835
250308
  }
249836
250309
  return;
249837
250310
  }
@@ -249848,9 +250321,9 @@ async function seal(state2, source, sessionId, scope, env6, requestOptions) {
249848
250321
  throw new Error("Native session file disappeared before EOF capture");
249849
250322
  throw error5;
249850
250323
  }
249851
- const directory = await mkdtemp4(join64(tmpdir13(), `letta-native-session-${process.pid}-${captureProcessInstanceId}-`));
250324
+ const directory = await mkdtemp4(join66(tmpdir13(), `letta-native-session-${process.pid}-${captureProcessInstanceId}-`));
249852
250325
  spoolDirectories.add(directory);
249853
- const spoolPath = join64(directory, "segment");
250326
+ const spoolPath = join66(directory, "segment");
249854
250327
  let output;
249855
250328
  let retained = false;
249856
250329
  try {
@@ -249967,7 +250440,7 @@ async function drain(state2, source, sessionId) {
249967
250440
  await spool.close();
249968
250441
  }
249969
250442
  state2.segments.shift();
249970
- const directory = join64(segment.path, "..");
250443
+ const directory = join66(segment.path, "..");
249971
250444
  await cleanupSpoolDirectory(directory);
249972
250445
  }
249973
250446
  }
@@ -249999,7 +250472,7 @@ async function discardRejectedSegment(state2) {
249999
250472
  const segment = state2.segments.shift();
250000
250473
  if (!segment)
250001
250474
  return;
250002
- const directory = join64(segment.path, "..");
250475
+ const directory = join66(segment.path, "..");
250003
250476
  await cleanupSpoolDirectory(directory);
250004
250477
  state2.ackedOffset = segment.end;
250005
250478
  state2.retryDelayMs = INITIAL_DRAIN_RETRY_MS;
@@ -251375,23 +251848,9 @@ var init_fork_conversation = __esm(() => {
251375
251848
  init_subagent_model();
251376
251849
  });
251377
251850
 
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
251851
  // src/agent/subagents/sandbox.ts
251393
251852
  import { mkdirSync as mkdirSync35 } from "node:fs";
251394
- import { join as join66 } from "node:path";
251853
+ import { join as join67 } from "node:path";
251395
251854
  function wrapSubagentLauncher(input) {
251396
251855
  const env6 = input.env ?? process.env;
251397
251856
  if (!isFsSandboxEnabled(env6))
@@ -251434,7 +251893,7 @@ function wrapSubagentLauncher(input) {
251434
251893
  if (!wrapped || wrapped.length === 0)
251435
251894
  return null;
251436
251895
  const [command, ...args] = wrapped;
251437
- const scratchRoot = join66(getLettaHomeRoot(), "tmp");
251896
+ const scratchRoot = join67(getLettaHomeRoot(), "tmp");
251438
251897
  mkdirSync35(scratchRoot, { recursive: true });
251439
251898
  return {
251440
251899
  command,
@@ -251537,270 +251996,6 @@ var init_context_budget = __esm(() => {
251537
251996
  REFLECTION_STARTUP_CONTEXT_CHAR_LIMIT = REFLECTION_STARTUP_CONTEXT_TOKEN_LIMIT * STARTUP_CONTEXT_ESTIMATED_CHARS_PER_TOKEN;
251538
251997
  });
251539
251998
 
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
251999
  // src/agent/prompts/recall_subagent.md
251805
252000
  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
252001
 
@@ -252509,7 +252704,7 @@ async function fetchParentConversationMessages(params) {
252509
252704
  }
252510
252705
  return messages;
252511
252706
  }
252512
- function contentText3(content) {
252707
+ function contentText2(content) {
252513
252708
  if (typeof content === "string")
252514
252709
  return content;
252515
252710
  if (!Array.isArray(content))
@@ -252535,7 +252730,7 @@ function renderToolCall(call2) {
252535
252730
  }
252536
252731
  function renderToolResult(result3) {
252537
252732
  const raw2 = result3.tool_return ?? result3.func_response;
252538
- const text2 = typeof raw2 === "string" ? raw2 : contentText3(raw2) || (raw2 == null ? "" : JSON.stringify(raw2));
252733
+ const text2 = typeof raw2 === "string" ? raw2 : contentText2(raw2) || (raw2 == null ? "" : JSON.stringify(raw2));
252539
252734
  return {
252540
252735
  type: "tool_result",
252541
252736
  call_id: result3.tool_call_id ?? undefined,
@@ -252571,11 +252766,11 @@ function userEvents(text2, speaker) {
252571
252766
  function renderMessage(message2) {
252572
252767
  switch (message2.message_type) {
252573
252768
  case "user_message": {
252574
- const text2 = contentText3(message2.content).replace(SYSTEM_REMINDER_PATTERN, "").trim();
252769
+ const text2 = contentText2(message2.content).replace(SYSTEM_REMINDER_PATTERN, "").trim();
252575
252770
  return userEvents(text2, message2.name ?? undefined);
252576
252771
  }
252577
252772
  case "assistant_message": {
252578
- const text2 = contentText3(message2.content).trim();
252773
+ const text2 = contentText2(message2.content).trim();
252579
252774
  return text2 ? [
252580
252775
  {
252581
252776
  type: "message",
@@ -253345,6 +253540,7 @@ class RemoteSubagentFollower {
253345
253540
  detach;
253346
253541
  wake = Promise.withResolvers();
253347
253542
  closed = false;
253543
+ stopping = new AbortController;
253348
253544
  disconnected = false;
253349
253545
  lost = false;
253350
253546
  launched = false;
@@ -253423,6 +253619,19 @@ class RemoteSubagentFollower {
253423
253619
  this.detach?.();
253424
253620
  this.client?.close();
253425
253621
  this.wake.resolve();
253622
+ this.stopping.abort();
253623
+ }
253624
+ untilStopped(promise2, signal) {
253625
+ const stop = signal ? AbortSignal.any([signal, this.stopping.signal]) : this.stopping.signal;
253626
+ if (stop.aborted)
253627
+ return Promise.reject(stop.reason);
253628
+ return new Promise((resolve36, reject2) => {
253629
+ const onStop = () => reject2(stop.reason);
253630
+ stop.addEventListener("abort", onStop, { once: true });
253631
+ promise2.then(resolve36, reject2).finally(() => {
253632
+ stop.removeEventListener("abort", onStop);
253633
+ });
253634
+ });
253426
253635
  }
253427
253636
  async waitForTerminal(signal, onProgress) {
253428
253637
  const onAbort = () => this.wake.resolve();
@@ -253457,15 +253666,23 @@ class RemoteSubagentFollower {
253457
253666
  if (this.closed)
253458
253667
  throw new Error("Stopped following the subagent");
253459
253668
  try {
253460
- const client = await this.connect();
253669
+ const connecting = this.connect();
253670
+ const client = await this.untilStopped(connecting, signal).catch((error5) => {
253671
+ connecting.then((late) => late.close(), () => {});
253672
+ throw error5;
253673
+ });
253674
+ if (this.closed) {
253675
+ client.close();
253676
+ throw new Error("Stopped following the subagent");
253677
+ }
253461
253678
  this.attach(client);
253462
- await client.sync({
253679
+ await this.untilStopped(client.sync({
253463
253680
  runtime: {
253464
253681
  agent_id: this.scope.agentId,
253465
253682
  conversation_id: this.scope.conversationId
253466
253683
  },
253467
253684
  recover_approvals: false
253468
- });
253685
+ }), signal);
253469
253686
  failedReconnects = 0;
253470
253687
  disconnectedSince = undefined;
253471
253688
  } catch (error5) {
@@ -253818,7 +254035,7 @@ var init_subagent_computer = __esm(() => {
253818
254035
  // src/tools/impl/kill-bash.ts
253819
254036
  function killBackgroundProcess(shell_id) {
253820
254037
  const proc = backgroundProcesses.get(shell_id);
253821
- const retainsEntry = proc?.kind === "monitor" || proc?.kind === "workflow";
254038
+ const retainsEntry = proc?.kind === "monitor" || proc?.kind === "workflow" || proc?.kind === "tool";
253822
254039
  if (!proc || retainsEntry && proc.status !== "running") {
253823
254040
  return false;
253824
254041
  }
@@ -253875,6 +254092,19 @@ async function cancelRemoteRun(subagentId) {
253875
254092
  };
253876
254093
  }
253877
254094
  }
254095
+ async function withTimeout3(promise2, timeoutMs) {
254096
+ let timer;
254097
+ try {
254098
+ return await Promise.race([
254099
+ promise2,
254100
+ new Promise((resolve36) => {
254101
+ timer = setTimeout(() => resolve36(TIMED_OUT), timeoutMs);
254102
+ })
254103
+ ]);
254104
+ } finally {
254105
+ clearTimeout(timer);
254106
+ }
254107
+ }
253878
254108
  async function task_stop(args, deps = {}) {
253879
254109
  validateRequiredParams(args, ["task_id"], "TaskStop");
253880
254110
  const { task_id } = args;
@@ -253889,7 +254119,8 @@ async function task_stop(args, deps = {}) {
253889
254119
  try {
253890
254120
  if (!task.runtimeScope)
253891
254121
  throw new Error("its parent conversation is not known");
253892
- const result3 = await (deps.stopRemoteExternal ?? stopRemoteExternalCodingAgent)({
254122
+ const timeoutMs = deps.remoteStopTimeoutMs ?? REMOTE_STOP_TIMEOUT_MS;
254123
+ const stopping = (deps.stopRemoteExternal ?? stopRemoteExternalCodingAgent)({
253893
254124
  agentId: child?.agentId,
253894
254125
  parentScope: {
253895
254126
  agentId: task.runtimeScope.agentId,
@@ -253897,6 +254128,10 @@ async function task_stop(args, deps = {}) {
253897
254128
  actingUserId: task.actingUserId
253898
254129
  }
253899
254130
  });
254131
+ stopping.catch(() => {});
254132
+ const result3 = await withTimeout3(stopping, timeoutMs);
254133
+ if (result3 === TIMED_OUT)
254134
+ throw new Error(`${external3.computer} did not answer within ${timeoutMs / 1000}s, so the worker may still be running`);
253900
254135
  remote = {
253901
254136
  killed: result3.stopped,
253902
254137
  output: result3.stopped ? "Stopped the remote external subagent" : "The remote external subagent was not running"
@@ -253915,15 +254150,35 @@ async function task_stop(args, deps = {}) {
253915
254150
  return remote;
253916
254151
  task.abortController.abort(remoteExternalStopped ? REMOTE_EXTERNAL_WORKER_STOPPED : undefined);
253917
254152
  task.error = "Aborted by user";
253918
- await task.completion;
254153
+ const completionTimeoutMs = deps.completionTimeoutMs ?? COMPLETION_TIMEOUT_MS;
254154
+ const settled = external3?.computer ? await withTimeout3(Promise.resolve(task.completion), completionTimeoutMs) : await task.completion;
253919
254155
  task.status = "failed";
253920
254156
  scheduleBackgroundTaskCleanup(task_id);
254157
+ if (settled === TIMED_OUT)
254158
+ return {
254159
+ killed: true,
254160
+ output: `${remote?.output ?? "Stopped the task"}, but stopped waiting for its result after ${completionTimeoutMs / 1000}s`
254161
+ };
253921
254162
  return remote ?? { killed: true };
253922
254163
  }
253923
254164
  return { killed: false };
253924
254165
  }
253925
- return { killed: killBackgroundProcess(task_id) };
254166
+ const process21 = backgroundProcesses.get(task_id);
254167
+ if (process21?.cancel)
254168
+ return process21.cancel();
254169
+ if (process21?.remote && process21.status === "running") {
254170
+ return {
254171
+ killed: false,
254172
+ output: "The server for this tool doesn't support cancelling, so the call may still finish; its result will still arrive as a notification."
254173
+ };
254174
+ }
254175
+ const killed = killBackgroundProcess(task_id);
254176
+ return {
254177
+ killed,
254178
+ ...killed && process21?.kind === "tool" ? { output: "Stopped" } : {}
254179
+ };
253926
254180
  }
254181
+ var REMOTE_STOP_TIMEOUT_MS = 30000, COMPLETION_TIMEOUT_MS = 5000, TIMED_OUT;
253927
254182
  var init_task_stop = __esm(() => {
253928
254183
  init_subagent_state();
253929
254184
  init_backend2();
@@ -253931,6 +254186,7 @@ var init_task_stop = __esm(() => {
253931
254186
  init_kill_bash();
253932
254187
  init_process_manager();
253933
254188
  init_remote_external_coding_agent();
254189
+ TIMED_OUT = Symbol("timed out");
253934
254190
  });
253935
254191
 
253936
254192
  // src/tools/impl/task-abort-hook.ts
@@ -254691,7 +254947,29 @@ var init_external_coding_agent_task = __esm(() => {
254691
254947
  });
254692
254948
 
254693
254949
  // src/tools/impl/send-agent-message.ts
254950
+ import { spawn as spawn11 } from "node:child_process";
254694
254951
  import { randomUUID as randomUUID48 } from "node:crypto";
254952
+ function buildLocalSendArgs(destination, message2) {
254953
+ return [
254954
+ "--backend",
254955
+ "local",
254956
+ "-p",
254957
+ ...destination.conversationId === "default" && destination.agentId ? ["--agent", destination.agentId] : [],
254958
+ "--conv",
254959
+ destination.conversationId,
254960
+ message2
254961
+ ];
254962
+ }
254963
+ function spawnDetached(command, args) {
254964
+ const child = spawn11(command, args, {
254965
+ cwd: getCurrentWorkingDirectory(),
254966
+ env: getRuntimeExecutionEnv(process.env, getRuntimeContext()?.executionSettings),
254967
+ detached: true,
254968
+ stdio: "ignore"
254969
+ });
254970
+ child.on("error", (error5) => debugLog("SendAgentMessage", "Local send failed to start", error5));
254971
+ child.unref();
254972
+ }
254695
254973
  function finishUntrackedNativeCapture(completion, reservation, source, sessionId) {
254696
254974
  if (!reservation)
254697
254975
  return;
@@ -254977,9 +255255,6 @@ async function send_agent_message(args, deps = {}) {
254977
255255
  }
254978
255256
  checkConversationId(args.conversation_id);
254979
255257
  const backend3 = deps.backend ?? getBackend();
254980
- if (!backend3.capabilities.environmentRouting) {
254981
- throw new Error("SendAgentMessage requires a Cloud backend.");
254982
- }
254983
255258
  const computer = normalizeAgentMessageComputer(args.computer);
254984
255259
  const actingUserId = getRuntimeActingUserAttribution();
254985
255260
  if (!actingUserId) {
@@ -255005,6 +255280,17 @@ async function send_agent_message(args, deps = {}) {
255005
255280
  }, backend3, signal);
255006
255281
  signal.throwIfAborted();
255007
255282
  submissionAttempted = true;
255283
+ if (!backend3.capabilities.environmentRouting) {
255284
+ const launcher = resolveSubagentLauncher(buildLocalSendArgs(destination, buildAgentSendReminder(sender, true) + args.message));
255285
+ (deps.spawnLocal ?? spawnDetached)(launcher.command, launcher.args);
255286
+ return {
255287
+ content: JSON.stringify({
255288
+ status: "spawned",
255289
+ conversation_id: destination.conversationId
255290
+ }),
255291
+ status: "success"
255292
+ };
255293
+ }
255008
255294
  const receipt = await (deps.enqueue ?? enqueueConversationMessage)({
255009
255295
  ...destination,
255010
255296
  clientMessageId,
@@ -255057,6 +255343,7 @@ async function send_agent_message(args, deps = {}) {
255057
255343
  var FULL_CONVERSATION_ID;
255058
255344
  var init_send_agent_message = __esm(() => {
255059
255345
  init_child_send_tracking();
255346
+ init_subagent_launcher();
255060
255347
  init_backend2();
255061
255348
  init_agent_message();
255062
255349
  init_conversation_enqueue();
@@ -255638,212 +255925,6 @@ var init_view_image = __esm(() => {
255638
255925
  ]);
255639
255926
  });
255640
255927
 
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
255928
  // src/tools/impl/github-pull-request-query.ts
255848
255929
  var GITHUB_PULL_REQUEST_QUERY = `
255849
255930
  query(
@@ -256008,6 +256089,79 @@ query($id: ID!, $before: String) {
256008
256089
  }
256009
256090
  }`;
256010
256091
 
256092
+ // src/tools/impl/github-pull-request-state.ts
256093
+ function shortGitHubPullRequestSha(sha) {
256094
+ return sha.slice(0, 12);
256095
+ }
256096
+ function pendingGitHubPullRequestChecks(snapshot2) {
256097
+ return snapshot2.checks.filter((check5) => check5.phase === "pending");
256098
+ }
256099
+ function failedGitHubPullRequestChecks(snapshot2) {
256100
+ return snapshot2.checks.filter((check5) => check5.phase === "failure");
256101
+ }
256102
+ function unresolvedGitHubPullRequestThreads(snapshot2) {
256103
+ return snapshot2.reviewThreads.filter((thread) => !thread.isResolved);
256104
+ }
256105
+ function hasGitHubPullRequestReadyConditions(snapshot2) {
256106
+ 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;
256107
+ }
256108
+ function isGitHubPullRequestReady(snapshot2) {
256109
+ return snapshot2.readinessConfirmed && hasGitHubPullRequestReadyConditions(snapshot2);
256110
+ }
256111
+ function githubPullRequestCheckSummary(snapshot2) {
256112
+ const pending2 = pendingGitHubPullRequestChecks(snapshot2).length;
256113
+ const failed2 = failedGitHubPullRequestChecks(snapshot2).length;
256114
+ const completed = snapshot2.checks.length - pending2;
256115
+ if (snapshot2.checks.length === 0)
256116
+ return "no checks reported";
256117
+ return `${completed}/${snapshot2.checks.length} checks complete, ${failed2} failing, ${pending2} pending`;
256118
+ }
256119
+ function githubPullRequestBlockerSummary(snapshot2) {
256120
+ const blockers = [];
256121
+ if (snapshot2.isDraft)
256122
+ blockers.push("draft");
256123
+ if (snapshot2.mergeable === "CONFLICTING")
256124
+ blockers.push("merge conflicts");
256125
+ if (snapshot2.mergeable === "UNKNOWN") {
256126
+ blockers.push("mergeability still unknown");
256127
+ }
256128
+ if (snapshot2.mergeStateStatus !== "CLEAN" && snapshot2.mergeStateStatus !== "UNKNOWN") {
256129
+ blockers.push(`merge state ${snapshot2.mergeStateStatus}`);
256130
+ }
256131
+ if (snapshot2.mergeStateStatus === "UNKNOWN") {
256132
+ blockers.push("merge state still unknown");
256133
+ }
256134
+ if (snapshot2.reviewDecision !== "NONE" && snapshot2.reviewDecision !== "APPROVED") {
256135
+ blockers.push(`review decision ${snapshot2.reviewDecision}`);
256136
+ }
256137
+ if (hasGitHubPullRequestReadyConditions(snapshot2) && !snapshot2.readinessConfirmed) {
256138
+ blockers.push("awaiting a second same-head readiness read");
256139
+ }
256140
+ const unresolved = unresolvedGitHubPullRequestThreads(snapshot2).length;
256141
+ if (unresolved > 0) {
256142
+ blockers.push(`${unresolved} unresolved review thread${unresolved === 1 ? "" : "s"}`);
256143
+ }
256144
+ return blockers.length > 0 ? blockers.join(", ") : "no known blockers";
256145
+ }
256146
+ function describeGitHubPullRequestSnapshot(snapshot2) {
256147
+ const failing = failedGitHubPullRequestChecks(snapshot2);
256148
+ const lines = [
256149
+ `${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"}.`
256150
+ ];
256151
+ if (failing.length > 0) {
256152
+ lines.push(`Failing checks: ${failing.map((check5) => check5.name).join(", ")}.`);
256153
+ }
256154
+ const unresolved = unresolvedGitHubPullRequestThreads(snapshot2).slice(0, 5);
256155
+ for (const thread of unresolved) {
256156
+ const comment2 = thread.comments.at(-1);
256157
+ if (!comment2)
256158
+ continue;
256159
+ lines.push(`Unresolved review thread${comment2.outdated ? " (outdated)" : ""}: ${comment2.url}`);
256160
+ }
256161
+ return lines.join(`
256162
+ `);
256163
+ }
256164
+
256011
256165
  // src/tools/impl/github-pull-request-watch.ts
256012
256166
  import { execFile as execFile16 } from "node:child_process";
256013
256167
  import { promisify as promisify16 } from "node:util";
@@ -256544,6 +256698,263 @@ var init_github_pull_request_watch = __esm(() => {
256544
256698
  };
256545
256699
  });
256546
256700
 
256701
+ // src/tools/impl/github-pull-request-cloud.ts
256702
+ import { setTimeout as delay5 } from "node:timers/promises";
256703
+ async function requestSnapshot(ref5, signal) {
256704
+ const client = await getClient();
256705
+ try {
256706
+ const body3 = await client.post("/v1/integrations/github/pull-request-snapshots", {
256707
+ body: {
256708
+ pull_requests: [
256709
+ { owner: ref5.owner, repo: ref5.repo, number: ref5.number }
256710
+ ]
256711
+ },
256712
+ signal,
256713
+ maxRetries: 0,
256714
+ timeout: 30000
256715
+ });
256716
+ return { status: 200, body: body3 };
256717
+ } catch (error5) {
256718
+ if (error5 instanceof APIError && (error5.status === 404 || error5.status === 501 || error5.status === 429)) {
256719
+ return { status: error5.status };
256720
+ }
256721
+ throw error5;
256722
+ }
256723
+ }
256724
+ function sameRef(a2, b3) {
256725
+ return a2.owner.toLowerCase() === b3.owner.toLowerCase() && a2.repo.toLowerCase() === b3.repo.toLowerCase() && a2.number === b3.number;
256726
+ }
256727
+ function toComment(comment2) {
256728
+ return {
256729
+ id: comment2.id,
256730
+ author: comment2.author,
256731
+ body: comment2.body,
256732
+ url: comment2.url,
256733
+ updatedAt: comment2.updated_at
256734
+ };
256735
+ }
256736
+ function toClientSnapshot(ref5, snapshot2) {
256737
+ return {
256738
+ ref: { ...ref5, url: snapshot2.ref.url },
256739
+ headSha: snapshot2.head_sha,
256740
+ state: snapshot2.merged ? "MERGED" : snapshot2.state,
256741
+ isDraft: snapshot2.is_draft,
256742
+ mergeable: snapshot2.mergeable,
256743
+ mergeStateStatus: snapshot2.merge_state_status,
256744
+ reviewDecision: snapshot2.review_decision,
256745
+ readinessConfirmed: false,
256746
+ checks: snapshot2.checks,
256747
+ checkAttempts: snapshot2.check_attempts,
256748
+ comments: snapshot2.comments.map(toComment),
256749
+ reviews: snapshot2.reviews.map((review) => ({
256750
+ ...toComment(review),
256751
+ state: review.state,
256752
+ commitSha: review.commit_sha
256753
+ })),
256754
+ reviewThreads: snapshot2.review_threads.map((thread) => ({
256755
+ id: thread.id,
256756
+ isResolved: thread.is_resolved,
256757
+ comments: thread.comments.map((comment2) => ({
256758
+ ...toComment(comment2),
256759
+ path: comment2.path,
256760
+ line: comment2.line,
256761
+ outdated: comment2.outdated,
256762
+ commitSha: comment2.commit_sha
256763
+ }))
256764
+ }))
256765
+ };
256766
+ }
256767
+ function createGitHubPullRequestSnapshotFetcher(deps = {}) {
256768
+ const shouldFetchCloud = deps.isCloud ?? (() => resolveBackendMode() === "api" && isCloudServerUrl());
256769
+ const fetchGh = deps.fetchGh ?? fetchGitHubPullRequestSnapshot;
256770
+ const request2 = deps.request ?? requestSnapshot;
256771
+ const now2 = deps.now ?? Date.now;
256772
+ const wait = deps.wait ?? (async (ms, signal) => {
256773
+ await delay5(ms, undefined, { signal });
256774
+ });
256775
+ let unsupported = false;
256776
+ let reportedRateLimit = false;
256777
+ const pause = async (retryAt, signal) => {
256778
+ if (!reportedRateLimit) {
256779
+ reportedRateLimit = true;
256780
+ telemetry.trackError("github_rate_limit", "Cloud PR snapshot polling paused for GitHub quota cooldown", "watch_pr");
256781
+ }
256782
+ const remaining = Date.parse(retryAt ?? "") - now2();
256783
+ await wait(remaining > 0 ? remaining : DEFAULT_COOLDOWN_MS, signal);
256784
+ };
256785
+ return async (ref5, options) => {
256786
+ if (unsupported || !shouldFetchCloud())
256787
+ return fetchGh(ref5, options);
256788
+ while (true) {
256789
+ options.signal?.throwIfAborted();
256790
+ const result3 = await request2(ref5, options.signal);
256791
+ if (!("body" in result3)) {
256792
+ if (result3.status === 429) {
256793
+ await pause(undefined, options.signal);
256794
+ continue;
256795
+ }
256796
+ unsupported = true;
256797
+ return fetchGh(ref5, options);
256798
+ }
256799
+ const entry = result3.body.snapshots.find((item) => sameRef(item, ref5));
256800
+ const limit4 = result3.body.rate_limits?.find((item) => sameRef(item, ref5));
256801
+ if (limit4 || entry?.stale) {
256802
+ await pause(entry?.retry_at ?? limit4?.retry_at, options.signal);
256803
+ continue;
256804
+ }
256805
+ if (entry?.inaccessible) {
256806
+ throw new Error(`Cloud could not access ${ref5.url}`);
256807
+ }
256808
+ if (!entry?.snapshot) {
256809
+ throw new Error("Cloud returned no PR snapshot");
256810
+ }
256811
+ return toClientSnapshot(ref5, entry.snapshot);
256812
+ }
256813
+ };
256814
+ }
256815
+ var DEFAULT_COOLDOWN_MS = 30000;
256816
+ var init_github_pull_request_cloud = __esm(() => {
256817
+ init_letta_client();
256818
+ init_client4();
256819
+ init_server_url();
256820
+ init_backend_mode();
256821
+ init_telemetry();
256822
+ init_github_pull_request_watch();
256823
+ });
256824
+
256825
+ // src/tools/impl/github-pull-request-diff.ts
256826
+ function normalizedBody(body3) {
256827
+ const compact2 = body3.replace(/\s+/g, " ").trim();
256828
+ if (compact2.length <= MAX_SUMMARY_BODY_CHARS)
256829
+ return compact2;
256830
+ return `${compact2.slice(0, MAX_SUMMARY_BODY_CHARS)}…`;
256831
+ }
256832
+ function commentEvent(label, comment2) {
256833
+ const body3 = normalizedBody(comment2.body);
256834
+ return `${label} from @${comment2.author}: ${body3 || "(no body)"} ${comment2.url}`;
256835
+ }
256836
+ function inlineCommentEvent(comment2, label = "New inline review comment") {
256837
+ const location = comment2.path ? ` on ${comment2.path}${comment2.line ? `:${comment2.line}` : ""}` : "";
256838
+ const outdated = comment2.outdated ? " (outdated)" : "";
256839
+ return `${label} from @${comment2.author}${location}${outdated}: ${normalizedBody(comment2.body) || "(no body)"} ${comment2.url}`;
256840
+ }
256841
+ function checkUrl(check5) {
256842
+ return check5.url ? ` ${check5.url}` : "";
256843
+ }
256844
+ function matchesCurrentFailure(attempt2, currentFailures) {
256845
+ return currentFailures.some((check5) => attempt2.url && check5.url ? attempt2.url === check5.url : attempt2.name === check5.name && attempt2.result === check5.result);
256846
+ }
256847
+ function sameKnownValue(previous, current) {
256848
+ return current === "UNKNOWN" || previous === current;
256849
+ }
256850
+ function diffGitHubPullRequestSnapshots(previous, current) {
256851
+ const events = [];
256852
+ const headChanged = previous.headSha !== current.headSha;
256853
+ if (headChanged) {
256854
+ events.push(`PR head changed from ${shortGitHubPullRequestSha(previous.headSha)} to ${shortGitHubPullRequestSha(current.headSha)}. ${githubPullRequestCheckSummary(current)}; ${githubPullRequestBlockerSummary(current)}.`);
256855
+ const currentFailures = current.checks.filter((check5) => check5.phase === "failure");
256856
+ for (const attempt2 of current.checkAttempts) {
256857
+ if (attempt2.phase === "failure" && !matchesCurrentFailure(attempt2, currentFailures)) {
256858
+ events.push(`Check attempt failed on new head before the next poll: ${attempt2.name} (${attempt2.result}).${checkUrl(attempt2)}`);
256859
+ }
256860
+ }
256861
+ }
256862
+ if (previous.state !== current.state) {
256863
+ 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}`);
256864
+ }
256865
+ if (previous.isDraft !== current.isDraft) {
256866
+ events.push(current.isDraft ? "PR moved back to draft." : "PR marked ready for review.");
256867
+ }
256868
+ const previousComments = new Map(previous.comments.map((comment2) => [comment2.id, comment2]));
256869
+ for (const comment2 of current.comments) {
256870
+ const old = previousComments.get(comment2.id);
256871
+ if (!old) {
256872
+ events.push(commentEvent("New PR comment", comment2));
256873
+ } else if (old.updatedAt !== comment2.updatedAt) {
256874
+ events.push(commentEvent("PR comment edited", comment2));
256875
+ }
256876
+ }
256877
+ const previousReviews = new Map(previous.reviews.map((review) => [review.id, review]));
256878
+ for (const review of current.reviews) {
256879
+ const old = previousReviews.get(review.id);
256880
+ if (!old) {
256881
+ events.push(commentEvent(`New ${review.state.toLowerCase()} review`, review));
256882
+ } else if (old.state !== review.state || old.updatedAt !== review.updatedAt) {
256883
+ events.push(commentEvent(`Review changed to ${review.state.toLowerCase()}`, review));
256884
+ }
256885
+ }
256886
+ const previousThreads = new Map(previous.reviewThreads.map((thread) => [thread.id, thread]));
256887
+ for (const thread of current.reviewThreads) {
256888
+ const old = previousThreads.get(thread.id);
256889
+ if (old && old.isResolved !== thread.isResolved) {
256890
+ const url2 = thread.comments.at(-1)?.url ?? current.ref.url;
256891
+ events.push(thread.isResolved ? `Review thread resolved: ${url2}` : `Review thread reopened: ${url2}`);
256892
+ }
256893
+ const oldComments = new Map(old?.comments.map((comment2) => [comment2.id, comment2]) ?? []);
256894
+ for (const comment2 of thread.comments) {
256895
+ const oldComment = oldComments.get(comment2.id);
256896
+ if (!oldComment) {
256897
+ events.push(inlineCommentEvent(comment2));
256898
+ } else {
256899
+ if (oldComment.updatedAt !== comment2.updatedAt) {
256900
+ events.push(inlineCommentEvent(comment2, "Inline review comment edited"));
256901
+ }
256902
+ if (oldComment.outdated !== comment2.outdated) {
256903
+ events.push(comment2.outdated ? `Review comment became outdated: ${comment2.url}` : `Review comment is current again: ${comment2.url}`);
256904
+ }
256905
+ }
256906
+ }
256907
+ }
256908
+ if (!headChanged) {
256909
+ const previousChecks = new Map(previous.checks.map((check5) => [check5.key, check5]));
256910
+ const previousPending = pendingGitHubPullRequestChecks(previous).length;
256911
+ const currentPending = pendingGitHubPullRequestChecks(current).length;
256912
+ const currentFailures = current.checks.filter((check5) => check5.phase === "failure");
256913
+ for (const check5 of current.checks) {
256914
+ const old = previousChecks.get(check5.key);
256915
+ if (check5.phase === "pending" && old && old.phase !== "pending") {
256916
+ events.push(`Check rerun started: ${check5.name}.${checkUrl(check5)}`);
256917
+ }
256918
+ if ((!old || old.phase !== "failure") && check5.phase === "failure") {
256919
+ events.push(`Check failed: ${check5.name} (${check5.result}).${checkUrl(check5)}`);
256920
+ } else if (old?.phase === "failure" && (check5.phase === "success" || check5.phase === "neutral")) {
256921
+ events.push(`Check recovered: ${check5.name} (${check5.result}).${checkUrl(check5)}`);
256922
+ }
256923
+ }
256924
+ if (previousPending > 0 && currentPending === 0) {
256925
+ events.push(`Current-head checks finished: ${githubPullRequestCheckSummary(current)}.`);
256926
+ }
256927
+ const previousAttempts = new Set(previous.checkAttempts.map((attempt2) => attempt2.key));
256928
+ for (const attempt2 of current.checkAttempts) {
256929
+ if (attempt2.phase === "failure" && !previousAttempts.has(attempt2.key) && !matchesCurrentFailure(attempt2, currentFailures)) {
256930
+ events.push(`Check attempt failed before the next poll: ${attempt2.name} (${attempt2.result}).${checkUrl(attempt2)}`);
256931
+ }
256932
+ }
256933
+ }
256934
+ if (!sameKnownValue(previous.mergeable, current.mergeable)) {
256935
+ events.push(current.mergeable === "CONFLICTING" ? "PR now has merge conflicts." : `PR mergeability changed to ${current.mergeable}.`);
256936
+ }
256937
+ if (!sameKnownValue(previous.mergeStateStatus, current.mergeStateStatus)) {
256938
+ events.push(`GitHub merge state changed from ${previous.mergeStateStatus} to ${current.mergeStateStatus}.`);
256939
+ }
256940
+ if (previous.reviewDecision !== current.reviewDecision) {
256941
+ events.push(`Review decision changed from ${previous.reviewDecision} to ${current.reviewDecision}.`);
256942
+ }
256943
+ const wasReady = isGitHubPullRequestReady(previous);
256944
+ const isReady = isGitHubPullRequestReady(current);
256945
+ if (!wasReady && isReady) {
256946
+ events.push(`PR is merge-ready on head ${shortGitHubPullRequestSha(current.headSha)} after a fresh read: ${current.ref.url}`);
256947
+ } else if (wasReady && !isReady) {
256948
+ events.push(`PR is no longer merge-ready on head ${shortGitHubPullRequestSha(current.headSha)}: ${githubPullRequestBlockerSummary(current)}; ${githubPullRequestCheckSummary(current)}.`);
256949
+ }
256950
+ return {
256951
+ events,
256952
+ terminal: current.state === "MERGED" || current.state === "CLOSED"
256953
+ };
256954
+ }
256955
+ var MAX_SUMMARY_BODY_CHARS = 240;
256956
+ var init_github_pull_request_diff = () => {};
256957
+
256547
256958
  // src/tools/impl/watch-pr.ts
256548
256959
  import { createHash as createHash11, randomUUID as randomUUID49 } from "node:crypto";
256549
256960
  import {
@@ -256554,7 +256965,7 @@ import {
256554
256965
  writeFileSync as writeFileSync31
256555
256966
  } from "node:fs";
256556
256967
  import { dirname as dirname31, join as join72 } from "node:path";
256557
- import { setTimeout as delay5 } from "node:timers/promises";
256968
+ import { setTimeout as delay6 } from "node:timers/promises";
256558
256969
  function errorText(error5) {
256559
256970
  const message2 = error5 instanceof Error ? error5.message : String(error5);
256560
256971
  return scrubSecretsFromString(message2, {}).replace(/\s+/g, " ").trim().slice(0, 500);
@@ -256563,7 +256974,7 @@ function pollDelayMs(failedPolls) {
256563
256974
  return Math.min(WATCH_POLL_MS * 2 ** failedPolls, WATCH_MAX_POLL_MS);
256564
256975
  }
256565
256976
  async function defaultWait(signal, milliseconds) {
256566
- await delay5(milliseconds, undefined, { signal });
256977
+ await delay6(milliseconds, undefined, { signal });
256567
256978
  }
256568
256979
  function saveSnapshot(path32, snapshot2) {
256569
256980
  if (!path32)
@@ -256639,7 +257050,7 @@ async function watch_pr(args, deps = {}) {
256639
257050
  }
256640
257051
  const ref5 = parseGitHubPullRequestUrl(args.url);
256641
257052
  const cwd2 = getCurrentWorkingDirectory();
256642
- const fetchSnapshot = deps.fetchSnapshot ?? ((pullRequestRef, options) => fetchGitHubPullRequestSnapshot(pullRequestRef, options));
257053
+ const fetchSnapshot = deps.fetchSnapshot ?? createGitHubPullRequestSnapshotFetcher();
256643
257054
  const runtimeContext = getRuntimeContext();
256644
257055
  const parentScope = args.parentScope ?? (runtimeContext?.agentId ? {
256645
257056
  agentId: runtimeContext.agentId,
@@ -256848,6 +257259,7 @@ var init_watch_pr = __esm(() => {
256848
257259
  init_secret_substitution();
256849
257260
  init_settings_path();
256850
257261
  init_task_notifications();
257262
+ init_github_pull_request_cloud();
256851
257263
  init_github_pull_request_diff();
256852
257264
  init_github_pull_request_watch();
256853
257265
  init_monitor();
@@ -264751,11 +265163,11 @@ function scheduleDurableQueueRestore(listener, capacityReleased = true) {
264751
265163
  clearDurableQueueRestoreRetry(listener);
264752
265164
  return;
264753
265165
  }
264754
- const delay6 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
265166
+ const delay7 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
264755
265167
  listener.durableQueueRestoreTimer = setTimeout(() => {
264756
265168
  listener.durableQueueRestoreTimer = undefined;
264757
265169
  scheduleDurableQueueRestore(listener, false);
264758
- }, delay6);
265170
+ }, delay7);
264759
265171
  listener.durableQueueRestoreTimer.unref?.();
264760
265172
  } finally {
264761
265173
  listener.durableQueueRestoreScheduled = false;
@@ -269947,6 +270359,9 @@ function captureExternalToolNotificationGuard(listener, runtimeScope) {
269947
270359
  }
269948
270360
  };
269949
270361
  }
270362
+ function captureNotificationWait(listener, runtimeScope) {
270363
+ return captureExternalToolNotificationGuard(listener, runtimeScope)?.waitUntilCurrent ?? (async () => false);
270364
+ }
269950
270365
  function toExternalToolDefinition(listener, tool, connectionId, runtimeScope) {
269951
270366
  const toolDefinition = {
269952
270367
  name: tool.name,
@@ -269966,7 +270381,7 @@ function toExternalToolDefinition(listener, tool, connectionId, runtimeScope) {
269966
270381
  createNotificationGuard: () => captureExternalToolNotificationGuard(listener, runtimeScope)
269967
270382
  });
269968
270383
  }
269969
- function installExternalToolBridge(runtime) {
270384
+ function installExternalToolBridge(runtime, options) {
269970
270385
  setExternalToolExecutor(async (toolCallId, toolName2, input, context3) => {
269971
270386
  const registrationKey = context3?.tool.registrationKey;
269972
270387
  const connectionId = registrationKey ? getConnectionIdsByRegistrationKey(runtime).get(registrationKey) : undefined;
@@ -269995,34 +270410,91 @@ function installExternalToolBridge(runtime) {
269995
270410
  };
269996
270411
  const requestFrame = JSON.stringify(request2);
269997
270412
  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
270413
+ let cancellationRequested = false;
270414
+ let cancellationTimedOut = false;
270415
+ let onAbort;
270416
+ try {
270417
+ const result3 = await new Promise((resolve38, reject2) => {
270418
+ const timeout = setTimeout(() => {
270419
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270420
+ 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.`));
270421
+ }, timeoutMs);
270422
+ getPendingExternalToolCalls(runtime).set(requestKey, {
270423
+ connectionId: connection.id,
270424
+ isOwningTurnCurrent,
270425
+ requestFrame,
270426
+ sentOn: writer,
270427
+ resolve: (response) => {
270428
+ resolve38({
270429
+ content: [...response.content],
270430
+ isError: response.is_error === true
270431
+ });
270432
+ },
270433
+ reject: reject2,
270434
+ timeout
270435
+ });
270436
+ if (context3?.tool.supportsCancellation && context3.signal) {
270437
+ onAbort = () => {
270438
+ const pending2 = getPendingExternalToolCalls(runtime).get(requestKey);
270439
+ if (!pending2 || cancellationRequested)
270440
+ return;
270441
+ cancellationRequested = true;
270442
+ clearTimeout(pending2.timeout);
270443
+ pending2.requestFrame = JSON.stringify({
270444
+ type: "external_tool_call_cancel",
270445
+ request_id: requestId,
270446
+ reason: "aborted"
270447
+ });
270448
+ pending2.timeout = setTimeout(() => {
270449
+ cancellationTimedOut = true;
270450
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270451
+ reject2(new Error("External tool cancellation timed out"));
270452
+ }, options?.cancelTimeoutMs ?? 30000);
270453
+ try {
270454
+ connection.writer.send(pending2.requestFrame);
270455
+ pending2.sentOn = connection.writer;
270456
+ if (context3.signal?.reason === EXTERNAL_TOOL_FOREGROUND_INTERRUPTED) {
270457
+ clearTimeout(pending2.timeout);
270458
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270459
+ reject2(new Error("cancelled"));
270460
+ }
270461
+ } catch (error5) {
270462
+ clearTimeout(pending2.timeout);
270463
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270464
+ reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
270465
+ }
270466
+ };
270467
+ context3.signal.addEventListener("abort", onAbort, { once: true });
270468
+ }
270469
+ try {
270470
+ writer.send(requestFrame);
270471
+ if (context3?.signal?.aborted)
270472
+ onAbort?.();
270473
+ } catch (error5) {
270474
+ clearTimeout(timeout);
270475
+ getPendingExternalToolCalls(runtime).delete(requestKey);
270476
+ reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
270477
+ }
270016
270478
  });
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)));
270479
+ return result3;
270480
+ } catch (error5) {
270481
+ if (cancellationTimedOut || cancellationRequested && error5 instanceof Error && error5.message === "cancelled") {
270482
+ return {
270483
+ content: [
270484
+ {
270485
+ type: "text",
270486
+ text: cancellationTimedOut ? "Cancellation was not confirmed; the remote tool may still finish." : "cancelled"
270487
+ }
270488
+ ],
270489
+ isError: true,
270490
+ cancellation: cancellationTimedOut ? "timeout" : "cancelled"
270491
+ };
270023
270492
  }
270024
- });
270025
- return result3;
270493
+ throw error5;
270494
+ } finally {
270495
+ if (onAbort)
270496
+ context3?.signal?.removeEventListener("abort", onAbort);
270497
+ }
270026
270498
  });
270027
270499
  }
270028
270500
  function registerRuntimeExternalTools(runtime, connectionId, runtimeScope, groups, toolPolicy) {
@@ -270035,7 +270507,9 @@ function registerRuntimeExternalTools(runtime, connectionId, runtimeScope, group
270035
270507
  const registrationScope = createConnectionRequestKey(connectionId, runtimeKey);
270036
270508
  const previousTools = registeredTools.get(registrationScope)?.tools ?? [];
270037
270509
  unregisterExternalTools(previousTools);
270038
- const tools = resolvedGroups.flatMap((group) => group.tools.map((tool) => toExternalToolDefinition(runtime, tool, connectionId, runtimeScope)));
270510
+ const tools = resolvedGroups.flatMap((group) => group.tools.map((tool) => Object.assign(toExternalToolDefinition(runtime, tool, connectionId, runtimeScope), {
270511
+ supportsCancellation: group.capabilities?.external_tool_call_cancel === true
270512
+ })));
270039
270513
  const controllers = getConnectionIdsByRegistrationKey(runtime);
270040
270514
  for (const tool of previousTools) {
270041
270515
  if (tool.registrationKey) {
@@ -271516,7 +271990,7 @@ async function acquireRecoveryClaim(runtime, onLost = () => {}, dependencies4 =
271516
271990
  }
271517
271991
  return null;
271518
271992
  }
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);
271993
+ 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
271994
  runtime.listener.activeRecoveryClaims ??= new Set;
271521
271995
  runtime.listener.activeRecoveryClaims.add(claim);
271522
271996
  refusalCounts.delete(runtime.listener);
@@ -274072,7 +274546,7 @@ function toRunsArray(listResponse) {
274072
274546
  }
274073
274547
  return [];
274074
274548
  }
274075
- function withTimeout3(promise2, timeoutMs, timeoutMessage) {
274549
+ function withTimeout4(promise2, timeoutMs, timeoutMessage) {
274076
274550
  return new Promise((resolve38, reject2) => {
274077
274551
  const timer = setTimeout(() => reject2(new Error(timeoutMessage)), timeoutMs);
274078
274552
  promise2.then((value) => {
@@ -274086,7 +274560,7 @@ function withTimeout3(promise2, timeoutMs, timeoutMessage) {
274086
274560
  }
274087
274561
  async function discoverFallbackRunIdWithTimeout(ctx) {
274088
274562
  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`);
274563
+ return withTimeout4(discoverFallbackRunIdForResume(client, ctx), FALLBACK_RUN_DISCOVERY_TIMEOUT_MS, `Fallback run discovery timed out after ${FALLBACK_RUN_DISCOVERY_TIMEOUT_MS}ms`);
274090
274564
  }
274091
274565
  async function discoverFallbackRunIdForResume(client, ctx) {
274092
274566
  const statuses = ["running"];
@@ -274975,6 +275449,7 @@ async function prepareToolExecutionContextForScope(params) {
274975
275449
  bundledSkills,
274976
275450
  workspaceSandbox,
274977
275451
  executionSettings,
275452
+ foregroundYieldMs,
274978
275453
  cachedAgent,
274979
275454
  modContext,
274980
275455
  modEvents,
@@ -275036,9 +275511,13 @@ async function prepareToolExecutionContextForScope(params) {
275036
275511
  ...skillSources !== undefined ? { skillSources } : {},
275037
275512
  ...bundledSkills !== undefined ? { bundledSkills } : {},
275038
275513
  ...workspaceSandbox !== undefined ? { workspaceSandbox } : {},
275039
- executionSettings
275514
+ executionSettings,
275515
+ foregroundYieldMs
275040
275516
  }
275041
275517
  });
275518
+ const context3 = getExecutionContextById(result3.preparedToolContext.contextId);
275519
+ if (context3)
275520
+ context3.shouldEnqueueBackground = params.shouldEnqueueBackground;
275042
275521
  return { ...result3, agent };
275043
275522
  }
275044
275523
  function shouldClearPersistedToolRules(agent) {
@@ -434357,12 +434836,12 @@ ${options.prefix}` : `
434357
434836
  this.pendingTimeouts = /* @__PURE__ */ new Map;
434358
434837
  this.logger = logger.hasLevel(3) ? logger : undefined;
434359
434838
  }
434360
- schedule(operationId, delay6, cb) {
434839
+ schedule(operationId, delay7, cb) {
434361
434840
  const pendingTimeout = this.pendingTimeouts.get(operationId);
434362
434841
  if (pendingTimeout) {
434363
434842
  this.host.clearTimeout(pendingTimeout);
434364
434843
  }
434365
- this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay6, operationId, this, cb));
434844
+ this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay7, operationId, this, cb));
434366
434845
  if (this.logger) {
434367
434846
  this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`);
434368
434847
  }
@@ -434383,9 +434862,9 @@ ${options.prefix}` : `
434383
434862
  }
434384
434863
  };
434385
434864
  var GcTimer = class _GcTimer {
434386
- constructor(host, delay6, logger) {
434865
+ constructor(host, delay7, logger) {
434387
434866
  this.host = host;
434388
- this.delay = delay6;
434867
+ this.delay = delay7;
434389
434868
  this.logger = logger;
434390
434869
  }
434391
434870
  scheduleCollect() {
@@ -442425,12 +442904,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
442425
442904
  const project = this.projectService.tryGetDefaultProjectForFile(fileName);
442426
442905
  return project && { fileName, project };
442427
442906
  }
442428
- getDiagnostics(next, delay6, fileArgs) {
442907
+ getDiagnostics(next, delay7, fileArgs) {
442429
442908
  if (this.suppressDiagnosticEvents) {
442430
442909
  return;
442431
442910
  }
442432
442911
  if (fileArgs.length > 0) {
442433
- this.updateErrorCheck(next, fileArgs, delay6);
442912
+ this.updateErrorCheck(next, fileArgs, delay7);
442434
442913
  }
442435
442914
  }
442436
442915
  change(args) {
@@ -442792,7 +443271,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
442792
443271
  const spans = languageService.getBraceMatchingAtPosition(file, position);
442793
443272
  return !spans ? undefined : simplifiedResult ? spans.map((span2) => toProtocolTextSpan(span2, scriptInfo)) : spans;
442794
443273
  }
442795
- getDiagnosticsForProject(next, delay6, fileName) {
443274
+ getDiagnosticsForProject(next, delay7, fileName) {
442796
443275
  if (this.suppressDiagnosticEvents) {
442797
443276
  return;
442798
443277
  }
@@ -442826,7 +443305,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
442826
443305
  }
442827
443306
  const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles];
442828
443307
  const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project }));
442829
- this.updateErrorCheck(next, checkList, delay6, false);
443308
+ this.updateErrorCheck(next, checkList, delay7, false);
442830
443309
  }
442831
443310
  configurePlugin(args) {
442832
443311
  this.projectService.configurePlugin(args);
@@ -447088,7 +447567,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
447088
447567
  retryStates.delete(runtime);
447089
447568
  return;
447090
447569
  }
447091
- const delay6 = retryDelay(state2.attempt);
447570
+ const delay7 = retryDelay(state2.attempt);
447092
447571
  state2.attempt += 1;
447093
447572
  state2.scheduled = true;
447094
447573
  state2.timer = setTimeout(() => {
@@ -447097,7 +447576,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
447097
447576
  state2.timer = undefined;
447098
447577
  state2.scheduled = false;
447099
447578
  scheduleRecoveredApprovalRetry(runtime, state2.retry);
447100
- }, delay6);
447579
+ }, delay7);
447101
447580
  state2.timer.unref?.();
447102
447581
  };
447103
447582
  state2.retry().then((handled) => {
@@ -448106,6 +448585,7 @@ async function executeRecoveredApprovalContinuation(params) {
448106
448585
  permissionModeState: getOrCreateConversationPermissionModeStateRef(runtime.listener, recovered.agentId, recovered.conversationId),
448107
448586
  modContext: createListenerAgentModContext(recovered.agentId),
448108
448587
  modAdapters,
448588
+ shouldEnqueueBackground: captureNotificationWait(runtime.listener, scope),
448109
448589
  modEvents: createListenerModEvents(modAdapters)
448110
448590
  });
448111
448591
  if (!hasRecoveryOwnership()) {
@@ -448363,6 +448843,7 @@ var init_recovery = __esm(() => {
448363
448843
  init_constants3();
448364
448844
  init_conversation_runtime();
448365
448845
  init_cwd();
448846
+ init_external_tools();
448366
448847
  init_interrupted_turn_record();
448367
448848
  init_interrupts();
448368
448849
  init_mod_adapter2();
@@ -448622,6 +449103,7 @@ async function resolveStaleApprovals(runtime, socket, turnLease, deps = {}) {
448622
449103
  permissionModeState: getOrCreateConversationPermissionModeStateRef(runtime.listener, runtime.agentId, runtime.conversationId),
448623
449104
  ...runtime.agentId ? { modContext: createListenerAgentModContext(runtime.agentId) } : {},
448624
449105
  modAdapters,
449106
+ shouldEnqueueBackground: captureNotificationWait(runtime.listener, scope),
448625
449107
  modEvents: createListenerModEvents(modAdapters)
448626
449108
  });
448627
449109
  assertCurrentTurnLease();
@@ -449035,6 +449517,7 @@ var init_send = __esm(() => {
449035
449517
  init_connection();
449036
449518
  init_constants3();
449037
449519
  init_cwd();
449520
+ init_external_tools();
449038
449521
  init_interrupted_turn_read();
449039
449522
  init_mod_adapter2();
449040
449523
  init_permission_mode();
@@ -453113,12 +453596,12 @@ function rowToolCalls(row, index, diagnostics2) {
453113
453596
  }
453114
453597
  return calls;
453115
453598
  }
453116
- function contentText4(content) {
453599
+ function contentText3(content) {
453117
453600
  if (typeof content === "string") {
453118
453601
  if (content.startsWith(CONTENT_JSON_PREFIX)) {
453119
453602
  const encoded = content.slice(CONTENT_JSON_PREFIX.length);
453120
453603
  try {
453121
- return contentText4(JSON.parse(encoded));
453604
+ return contentText3(JSON.parse(encoded));
453122
453605
  } catch {
453123
453606
  return encoded;
453124
453607
  }
@@ -453204,7 +453687,7 @@ var init_hermes = __esm(() => {
453204
453687
  });
453205
453688
  };
453206
453689
  if (row.role === "user") {
453207
- const content = contentText4(row.content);
453690
+ const content = contentText3(row.content);
453208
453691
  if (content) {
453209
453692
  emit({
453210
453693
  type: "message",
@@ -453224,7 +453707,7 @@ var init_hermes = __esm(() => {
453224
453707
  ...timestamp ? { timestamp } : {}
453225
453708
  });
453226
453709
  }
453227
- const content = contentText4(row.content);
453710
+ const content = contentText3(row.content);
453228
453711
  if (content) {
453229
453712
  emit({
453230
453713
  type: "message",
@@ -453247,7 +453730,7 @@ var init_hermes = __esm(() => {
453247
453730
  if (row.role === "tool") {
453248
453731
  emit({
453249
453732
  type: "tool_result",
453250
- content: contentText4(row.content),
453733
+ content: contentText3(row.content),
453251
453734
  ...typeof row.tool_call_id === "string" && row.tool_call_id ? { callId: row.tool_call_id } : {},
453252
453735
  ...timestamp ? { timestamp } : {}
453253
453736
  });
@@ -454512,7 +454995,7 @@ var init_core5 = __esm(() => {
454512
454995
  });
454513
454996
 
454514
454997
  // node_modules/@letta-ai/trajectory/dist/adapters/deepagents/index.js
454515
- import { spawn as spawn11 } from "node:child_process";
454998
+ import { spawn as spawn12 } from "node:child_process";
454516
454999
  import { accessSync as accessSync2, constants as constants6 } from "node:fs";
454517
455000
  import { homedir as homedir23 } from "node:os";
454518
455001
  import { join as join84 } from "node:path";
@@ -454543,7 +455026,7 @@ async function loadDeepAgentsCheckpoint(checkpoint) {
454543
455026
  const python = checkpoint.pythonExecutable ?? process.env.PYTHON ?? "python3";
454544
455027
  const helper = resolveHelperPath();
454545
455028
  return await new Promise((resolve38, reject2) => {
454546
- const child = spawn11(python, [helper], {
455029
+ const child = spawn12(python, [helper], {
454547
455030
  stdio: ["pipe", "pipe", "pipe"],
454548
455031
  windowsHide: true
454549
455032
  });
@@ -458694,9 +459177,11 @@ async function prepareListenerTurn(params) {
458694
459177
  bundledSkills: runtime.bundledSkills,
458695
459178
  workspaceSandbox: runtime.workspaceSandbox,
458696
459179
  executionSettings: runtime.executionSettings,
459180
+ foregroundYieldMs: toolOwner.toolPolicy?.foreground_yield_ms,
458697
459181
  cachedAgent,
458698
459182
  ...agentId ? { modContext: createListenerAgentModContext(agentId) } : {},
458699
459183
  modAdapters,
459184
+ shouldEnqueueBackground: captureNotificationWait(runtime.listener, toolRuntimeScope),
458700
459185
  modEvents: createListenerModEvents(modAdapters)
458701
459186
  });
458702
459187
  if (isInterrupted()) {
@@ -460308,10 +460793,10 @@ async function registerWithCloudRetry(opts, callbacks) {
460308
460793
  }
460309
460794
  attempt2++;
460310
460795
  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));
460796
+ const delay7 = error5 instanceof RegistrationError && error5.retryAfterMs !== undefined ? Math.max(error5.retryAfterMs, backoffDelay) : backoffDelay;
460797
+ const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay7 * REGISTER_JITTER_RATIO));
460313
460798
  const jitter2 = jitterWindow > 0 ? Math.floor((callbacks?.random ?? Math.random)() * jitterWindow) : 0;
460314
- const retryDelay2 = delay6 + jitter2;
460799
+ const retryDelay2 = delay7 + jitter2;
460315
460800
  if (error5 instanceof Error) {
460316
460801
  callbacks?.onRetry?.(attempt2, retryDelay2, error5);
460317
460802
  }
@@ -461434,13 +461919,13 @@ function isStringList(value) {
461434
461919
  function isRuntimeStartExternalToolsGroup(value) {
461435
461920
  if (!isRecord18(value))
461436
461921
  return false;
461437
- return Array.isArray(value.tools) && value.tools.every(isExternalToolDefinitionPayload);
461922
+ 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
461923
  }
461439
461924
  function isRuntimeToolPolicy(value) {
461440
461925
  if (!isRecord18(value))
461441
461926
  return false;
461442
461927
  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");
461928
+ 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
461929
  }
461445
461930
  function isRuntimeExternalToolsUpdateCommand(value) {
461446
461931
  if (!isRecord18(value))
@@ -464189,7 +464674,7 @@ var init_mod_commands = __esm(() => {
464189
464674
  });
464190
464675
 
464191
464676
  // src/websocket/listener/commands.ts
464192
- import { spawn as spawn12 } from "node:child_process";
464677
+ import { spawn as spawn13 } from "node:child_process";
464193
464678
  async function handleExecuteCommand(command, socket, conversationRuntime, opts) {
464194
464679
  const scope = {
464195
464680
  agent_id: conversationRuntime.agentId,
@@ -464426,7 +464911,7 @@ function scheduleRemoteRestart(connectionName, log3) {
464426
464911
  setTimeout(async () => {
464427
464912
  await flushRemoteSettingsWrites();
464428
464913
  log3(`spawning replacement listener: ${process.execPath} ${entrypoint} remote --computer-name ${connectionName}`);
464429
- const child = spawn12(process.execPath, [entrypoint, "remote", "--computer-name", connectionName], {
464914
+ const child = spawn13(process.execPath, [entrypoint, "remote", "--computer-name", connectionName], {
464430
464915
  cwd: process.cwd(),
464431
464916
  detached: true,
464432
464917
  env: process.env,
@@ -465040,6 +465525,7 @@ function buildAppServerInfoResponse(command, options) {
465040
465525
  runtime_workspace_sandbox: true,
465041
465526
  runtime_external_tools_update: true,
465042
465527
  runtime_tool_policy: true,
465528
+ runtime_tool_policy_foreground_yield: true,
465043
465529
  structured_outputs: options.backend === "api",
465044
465530
  write_file_base64: true,
465045
465531
  split_channels: false
@@ -471937,10 +472423,10 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
471937
472423
  opts.onError(new Error("Failed to connect after 5 minutes of retrying"));
471938
472424
  return;
471939
472425
  }
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);
472426
+ const delay7 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
472427
+ opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay7, opts.connectionId);
471942
472428
  await new Promise((resolve39) => {
471943
- runtime.reconnectTimeout = setTimeout(resolve39, delay6);
472429
+ runtime.reconnectTimeout = setTimeout(resolve39, delay7);
471944
472430
  });
471945
472431
  runtime.reconnectTimeout = null;
471946
472432
  if (runtime !== getActiveRuntime() || runtime.intentionallyClosed) {
@@ -474779,7 +475265,7 @@ __export(exports_gateway_supervisor, {
474779
475265
  startChannelGatewaySupervisor: () => startChannelGatewaySupervisor,
474780
475266
  CHANNEL_GATEWAY_READY_SIGNAL: () => CHANNEL_GATEWAY_READY_SIGNAL
474781
475267
  });
474782
- import { spawn as spawn13 } from "node:child_process";
475268
+ import { spawn as spawn14 } from "node:child_process";
474783
475269
  function resolveLauncher(cwd2) {
474784
475270
  const invocation = resolveLettaInvocation(process.env, process.argv, process.execPath, cwd2);
474785
475271
  if (invocation)
@@ -474880,7 +475366,7 @@ async function startChannelGatewaySupervisor(options) {
474880
475366
  function launch() {
474881
475367
  if (stopping)
474882
475368
  return;
474883
- child = (options.spawnProcess ?? spawn13)(launcher.command, childArgs, {
475369
+ child = (options.spawnProcess ?? spawn14)(launcher.command, childArgs, {
474884
475370
  cwd: cwd2,
474885
475371
  env: options.env ?? process.env,
474886
475372
  stdio: ["pipe", "pipe", "pipe"],
@@ -478006,7 +478492,7 @@ var init_model2 = __esm(() => {
478006
478492
  });
478007
478493
 
478008
478494
  // src/mods/package-installer.ts
478009
- import { spawn as spawn14 } from "node:child_process";
478495
+ import { spawn as spawn15 } from "node:child_process";
478010
478496
  import {
478011
478497
  copyFileSync as copyFileSync4,
478012
478498
  existsSync as existsSync68,
@@ -478864,7 +479350,7 @@ var init_package_installer = __esm(() => {
478864
479350
  init_package_registry();
478865
479351
  init_package_manager_spawn();
478866
479352
  SKIPPED_PACKAGE_COPY_NAMES = new Set([".git", "node_modules"]);
478867
- spawnGitInstallProcess = spawn14;
479353
+ spawnGitInstallProcess = spawn15;
478868
479354
  });
478869
479355
 
478870
479356
  // src/mods/package-scaffolder.ts
@@ -508878,7 +509364,7 @@ var init_LettaLoginOverlay = __esm(async () => {
508878
509364
  });
508879
509365
 
508880
509366
  // src/backend/api/mcp-servers.ts
508881
- function withTimeout4(promise2, timeoutMs, label) {
509367
+ function withTimeout5(promise2, timeoutMs, label) {
508882
509368
  let timer;
508883
509369
  const timeout = new Promise((_4, reject2) => {
508884
509370
  timer = setTimeout(() => reject2(new Error(`${label} timed out after ${timeoutMs}ms`)), timeoutMs);
@@ -508889,10 +509375,10 @@ function withTimeout4(promise2, timeoutMs, label) {
508889
509375
  });
508890
509376
  }
508891
509377
  function listServerMcpServers(client, timeoutMs = 1e4) {
508892
- return withTimeout4(client.mcpServers.list(), timeoutMs, "Listing server-side MCP servers");
509378
+ return withTimeout5(client.mcpServers.list(), timeoutMs, "Listing server-side MCP servers");
508893
509379
  }
508894
509380
  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}"`);
509381
+ const result3 = await withTimeout5(client.get(`/v1/tools/mcp/servers/${encodeURIComponent(serverName2)}/tools`), timeoutMs, `Listing tools for MCP server "${serverName2}"`);
508896
509382
  if (!Array.isArray(result3))
508897
509383
  return [];
508898
509384
  return result3.filter((tool) => typeof tool === "object" && tool !== null && typeof tool.name === "string");
@@ -529383,7 +529869,7 @@ The deployment target for this project is CITATION-DOGFOOD-OK.
529383
529869
  });
529384
529870
 
529385
529871
  // src/mods/learning-harness.ts
529386
- import { spawn as spawn15 } from "node:child_process";
529872
+ import { spawn as spawn16 } from "node:child_process";
529387
529873
  import { access as access2, copyFile as copyFile2, mkdir as mkdir21, readFile as readFile36, writeFile as writeFile24 } from "node:fs/promises";
529388
529874
  import path50 from "node:path";
529389
529875
  function slugify2(value) {
@@ -530323,7 +530809,7 @@ async function writeHistoryArtifacts(params) {
530323
530809
  async function defaultCommandRunner(command, args, options) {
530324
530810
  const startedAt = Date.now();
530325
530811
  return new Promise((resolve44) => {
530326
- const child = spawn15(command, args, {
530812
+ const child = spawn16(command, args, {
530327
530813
  cwd: options.cwd,
530328
530814
  env: options.env,
530329
530815
  stdio: ["ignore", "pipe", "pipe"]
@@ -536753,9 +537239,9 @@ function App2({
536753
537239
  }
536754
537240
  const elapsedSinceClear = Date.now() - lastClearAtRef.current;
536755
537241
  const rateLimitDelay = elapsedSinceClear >= MIN_CLEAR_INTERVAL_MS ? 0 : MIN_CLEAR_INTERVAL_MS - elapsedSinceClear;
536756
- const delay6 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
537242
+ const delay7 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
536757
537243
  if (debugFlicker) {
536758
- console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay6}ms elapsedSinceClear=${elapsedSinceClear}ms`);
537244
+ console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay7}ms elapsedSinceClear=${elapsedSinceClear}ms`);
536759
537245
  }
536760
537246
  resizeClearTimeout.current = setTimeout(() => {
536761
537247
  resizeClearTimeout.current = null;
@@ -536775,7 +537261,7 @@ function App2({
536775
537261
  console.error(`[debug:flicker:resize-fire] clear target=${targetColumns}`);
536776
537262
  }
536777
537263
  clearAndRemount(targetColumns);
536778
- }, delay6);
537264
+ }, delay7);
536779
537265
  }, [clearAndRemount, debugFlicker]);
536780
537266
  import_react124.useEffect(() => {
536781
537267
  const prev = prevColumnsRef.current;
@@ -537281,11 +537767,11 @@ function App2({
537281
537767
  import_react124.useEffect(() => {
537282
537768
  if (deferredCommitAt === null)
537283
537769
  return;
537284
- const delay6 = Math.max(0, deferredCommitAt - Date.now());
537770
+ const delay7 = Math.max(0, deferredCommitAt - Date.now());
537285
537771
  const timer = setTimeout(() => {
537286
537772
  setDeferredCommitAt(null);
537287
537773
  refreshDerived();
537288
- }, delay6);
537774
+ }, delay7);
537289
537775
  return () => clearTimeout(timer);
537290
537776
  }, [deferredCommitAt, refreshDerived]);
537291
537777
  const streamingRefreshTimeoutRef = import_react124.useRef(null);
@@ -543196,4 +543682,4 @@ function registerBunOAuthFlows() {
543196
543682
  registerBunOAuthFlows();
543197
543683
  await init_src5().then(() => exports_src2);
543198
543684
 
543199
- //# debugId=BCE8FF592C80D3DE64756E2164756E21
543685
+ //# debugId=0096EAA9E5BD45EC64756E2164756E21