@letta-ai/letta-code 0.34.63 → 0.34.65

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 (58) hide show
  1. package/dist/agent-presets.js +5 -5
  2. package/dist/agent-presets.js.map +1 -1
  3. package/dist/mcp-client.js +2 -2
  4. package/dist/mcp-client.js.map +1 -1
  5. package/dist/mcp-oauth.js +2 -2
  6. package/dist/mcp-oauth.js.map +1 -1
  7. package/dist/types/backend/api/agent-message.d.ts +2 -0
  8. package/dist/types/backend/api/agent-message.d.ts.map +1 -1
  9. package/dist/types/backend/api/metadata.d.ts +0 -12
  10. package/dist/types/backend/api/metadata.d.ts.map +1 -1
  11. package/dist/types/backend/api/unified-mcp.d.ts.map +1 -1
  12. package/dist/types/backend/local/local-backend.d.ts.map +1 -1
  13. package/dist/types/backend/local/local-message-list-options.d.ts +7 -0
  14. package/dist/types/backend/local/local-message-list-options.d.ts.map +1 -0
  15. package/dist/types/backend/local/local-store.d.ts +2 -0
  16. package/dist/types/backend/local/local-store.d.ts.map +1 -1
  17. package/dist/types/backend/local/local-transcript-history.d.ts +8 -0
  18. package/dist/types/backend/local/local-transcript-history.d.ts.map +1 -1
  19. package/dist/types/backend/local/local-transcript.d.ts +1 -0
  20. package/dist/types/backend/local/local-transcript.d.ts.map +1 -1
  21. package/dist/types/backend/local/system-prompt-compilation.d.ts +2 -1
  22. package/dist/types/backend/local/system-prompt-compilation.d.ts.map +1 -1
  23. package/dist/types/experiments/manager.d.ts.map +1 -1
  24. package/dist/types/experiments/types.d.ts +1 -1
  25. package/dist/types/experiments/types.d.ts.map +1 -1
  26. package/dist/types/reminders/engine.d.ts +3 -3
  27. package/dist/types/reminders/engine.d.ts.map +1 -1
  28. package/dist/types/tools/impl/claude-steer-timeouts.d.ts +5 -0
  29. package/dist/types/tools/impl/claude-steer-timeouts.d.ts.map +1 -1
  30. package/dist/types/tools/impl/external-coding-agent.d.ts +1 -1
  31. package/dist/types/tools/impl/external-coding-agent.d.ts.map +1 -1
  32. package/dist/types/tools/impl/external-fork-context.d.ts +6 -0
  33. package/dist/types/tools/impl/external-fork-context.d.ts.map +1 -1
  34. package/dist/types/tools/impl/github-pull-request-cloud.d.ts +3 -1
  35. package/dist/types/tools/impl/github-pull-request-cloud.d.ts.map +1 -1
  36. package/dist/types/tools/impl/monitor-script.d.ts +1 -0
  37. package/dist/types/tools/impl/monitor-script.d.ts.map +1 -1
  38. package/dist/types/tools/impl/monitor.d.ts +1 -0
  39. package/dist/types/tools/impl/monitor.d.ts.map +1 -1
  40. package/dist/types/tools/impl/remote-connect-retry.d.ts +4 -0
  41. package/dist/types/tools/impl/remote-connect-retry.d.ts.map +1 -0
  42. package/dist/types/tools/impl/remote-external-coding-agent.d.ts.map +1 -1
  43. package/dist/types/tools/impl/remote-follow-up-retry.d.ts +9 -0
  44. package/dist/types/tools/impl/remote-follow-up-retry.d.ts.map +1 -0
  45. package/dist/types/tools/impl/watch-pr-cloud.d.ts +29 -0
  46. package/dist/types/tools/impl/watch-pr-cloud.d.ts.map +1 -0
  47. package/dist/types/tools/impl/watch-pr.d.ts +1 -0
  48. package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
  49. package/dist/types/types/protocol_v2.d.ts +2 -1
  50. package/dist/types/types/protocol_v2.d.ts.map +1 -1
  51. package/dist/types/utils/task-notifications.d.ts +1 -0
  52. package/dist/types/utils/task-notifications.d.ts.map +1 -1
  53. package/letta.js +420 -171
  54. package/npm-shrinkwrap.json +18 -14
  55. package/package.json +2 -2
  56. package/scripts/source-file-size-baseline.json +2 -2
  57. package/skills/image-generation/SKILL.md +2 -0
  58. package/skills/self-configuration/SKILL.md +7 -5
package/letta.js CHANGED
@@ -3472,7 +3472,7 @@ function trackEndTurnNoAssistant(params) {
3472
3472
  });
3473
3473
  }
3474
3474
  function extractHttpStatus(message) {
3475
- const match = /(?:^|:\s*)([45]\d{2})\b/.exec(message);
3475
+ const match = /(?:^|:\s*)(?:HTTP\s+)?([45]\d{2})\b/.exec(message);
3476
3476
  return match ? Number(match[1]) : undefined;
3477
3477
  }
3478
3478
  function reportExternalWorkerLaunchFailure(options) {
@@ -6139,7 +6139,7 @@ var package_default;
6139
6139
  var init_package = __esm(() => {
6140
6140
  package_default = {
6141
6141
  name: "@letta-ai/letta-code",
6142
- version: "0.34.63",
6142
+ version: "0.34.65",
6143
6143
  lettaStartupLogProtocol: 1,
6144
6144
  lettaConfigDirProtocol: 1,
6145
6145
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6426,7 +6426,7 @@ var init_package = __esm(() => {
6426
6426
  },
6427
6427
  lettaLifecycleProtocol: 1,
6428
6428
  lettaRuntimeGraphProtocol: 1,
6429
- lettaRuntimeGraphSha512: "sha512-llGcPR13/WPW010yGdtNGC7Apobzktid+4Ka3zhviUWYP60+sHx9ovVyADbq+eHG9wrgZn9zRpo+7kdJ4mnElw==",
6429
+ lettaRuntimeGraphSha512: "sha512-YBw5454QIS1lIoAD6ih1iX/HMCzk64xnt+DSnT2DImzzMMJXgHXqXap7e1O2wPQbkVfm5HI9Q+5a9KskU8GYRw==",
6430
6430
  patchedDependencies: {
6431
6431
  "@earendil-works/pi-ai@1.5.2": "patches/@earendil-works%2Fpi-ai@1.5.2.patch"
6432
6432
  }
@@ -6587,9 +6587,6 @@ function getFeedbackClientType(env = process.env) {
6587
6587
  async function getBalanceMetadata(options = {}) {
6588
6588
  return apiRequest("GET", "/v1/metadata/balance", undefined, options.signal ? { signal: options.signal } : {});
6589
6589
  }
6590
- async function getModelQuotaMetadata() {
6591
- return apiRequest("GET", "/v1/organizations/self/quotas");
6592
- }
6593
6590
  async function getBillingTier() {
6594
6591
  try {
6595
6592
  const balance = await getBalanceMetadata();
@@ -90324,7 +90321,7 @@ If you come across a reference to something you do not currently have any inform
90324
90321
  ## Working across time
90325
90322
  To act across time, you must create future invocations explicitly. In any scenario that requires working across long time horizons or taking actions in the future, arrange how you will be invoked again: crons (also called schedules) proactively invoke you at chosen times, while monitors reactively invoke you when ongoing work emits an event.
90326
90323
 
90327
- Use Monitor when work already in progress can signal a result you need to act on, such as pull request checks and reviews, deployments, background services, or long-running jobs. Use Wake for a future turn in the current conversation. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90324
+ When you are waiting for something to happen, such as pull request checks and reviews, a deployment, a background service, or a long-running job, use Monitor: it brings you back when the thing happens. Use Wake only when there is an explicit time condition, such as a reminder or a follow-up at a set time, or when no monitor is possible. Never use a wake to poll for something a monitor could watch. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90328
90325
 
90329
90326
  You **MUST** be proactive in arranging the appropriate future invocation when work continues beyond the current turn. Do not wait for the user to notice and return with the result.
90330
90327
 
@@ -90506,7 +90503,7 @@ If you come across a reference to something you do not currently have any inform
90506
90503
  ## Working across time
90507
90504
  To act across time, you must create future invocations explicitly. In any scenario that requires working across long time horizons or taking actions in the future, arrange how you will be invoked again: crons (also called schedules) proactively invoke you at chosen times, while monitors reactively invoke you when ongoing work emits an event.
90508
90505
 
90509
- Use Monitor when work already in progress can signal a result you need to act on, such as pull request checks and reviews, deployments, background services, or long-running jobs. Use Wake for a future turn in the current conversation. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90506
+ When you are waiting for something to happen, such as pull request checks and reviews, a deployment, a background service, or a long-running job, use Monitor: it brings you back when the thing happens. Use Wake only when there is an explicit time condition, such as a reminder or a follow-up at a set time, or when no monitor is possible. Never use a wake to poll for something a monitor could watch. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90510
90507
 
90511
90508
  You **MUST** be proactive in arranging the appropriate future invocation when work continues beyond the current turn. Do not wait for the user to notice and return with the result.
90512
90509
 
@@ -90622,7 +90619,7 @@ You can have multiple concurrent conversations. Memory is shared across all of t
90622
90619
 
90623
90620
  To act across time, you must create future invocations explicitly. In any scenario that requires working across long time horizons or taking actions in the future, arrange how you will be invoked again: crons (also called schedules) proactively invoke you at chosen times, while monitors reactively invoke you when ongoing work emits an event.
90624
90621
 
90625
- Use Monitor when work already in progress can signal a result you need to act on, such as pull request checks and reviews, deployments, background services, or long-running jobs. Use Wake for a future turn in the current conversation. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90622
+ When you are waiting for something to happen, such as pull request checks and reviews, a deployment, a background service, or a long-running job, use Monitor: it brings you back when the thing happens. Use Wake only when there is an explicit time condition, such as a reminder or a follow-up at a set time, or when no monitor is possible. Never use a wake to poll for something a monitor could watch. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90626
90623
 
90627
90624
  You **MUST** be proactive in arranging the appropriate future invocation when work continues beyond the current turn. Do not wait for the user to notice and return with the result.
90628
90625
 
@@ -90841,7 +90838,7 @@ If you come across a reference to something you do not currently have any inform
90841
90838
  ## Working across time
90842
90839
  To act across time, you must create future invocations explicitly. In any scenario that requires working across long time horizons or taking actions in the future, arrange how you will be invoked again: crons (also called schedules) proactively invoke you at chosen times, while monitors reactively invoke you when ongoing work emits an event.
90843
90840
 
90844
- Use Monitor when work already in progress can signal a result you need to act on, such as pull request checks and reviews, deployments, background services, or long-running jobs. Use Wake for a future turn in the current conversation. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90841
+ When you are waiting for something to happen, such as pull request checks and reviews, a deployment, a background service, or a long-running job, use Monitor: it brings you back when the thing happens. Use Wake only when there is an explicit time condition, such as a reminder or a follow-up at a set time, or when no monitor is possible. Never use a wake to poll for something a monitor could watch. Use \`letta cron\` when you need another conversation, runner, or computer, or need to inspect run history or replace a schedule. Do **NOT** commit to actions beyond the current session without arranging a future invocation.
90845
90842
 
90846
90843
  You **MUST** be proactive in arranging the appropriate future invocation when work continues beyond the current turn. Do not wait for the user to notice and return with the result.
90847
90844
 
@@ -101815,6 +101812,27 @@ function emptyLocalUsage() {
101815
101812
  };
101816
101813
  }
101817
101814
 
101815
+ // src/backend/local/local-message-list-options.ts
101816
+ function getListLimit(body) {
101817
+ const limit4 = body?.limit;
101818
+ return typeof limit4 === "number" && limit4 > 0 ? limit4 : undefined;
101819
+ }
101820
+ function getListOrder(body) {
101821
+ const order = body?.order;
101822
+ return order === "asc" ? "asc" : "desc";
101823
+ }
101824
+ function getCursor(body, key) {
101825
+ const value = body?.[key];
101826
+ return typeof value === "string" && value.length > 0 ? value : undefined;
101827
+ }
101828
+ function getIncludedMessageTypes(body) {
101829
+ const value = body?.include_return_message_types;
101830
+ if (!Array.isArray(value))
101831
+ return;
101832
+ const messageTypes = value.filter((item) => typeof item === "string" && item.length > 0);
101833
+ return messageTypes.length > 0 ? new Set(messageTypes) : undefined;
101834
+ }
101835
+
101818
101836
  // src/backend/local/local-stream-chunks.ts
101819
101837
  function toStoredOutputFields(chunk) {
101820
101838
  const {
@@ -101919,6 +101937,19 @@ function readLocalTranscriptRowsForHistory(path8, inContextMessageIds) {
101919
101937
  });
101920
101938
  return rows;
101921
101939
  }
101940
+ function countLocalTranscriptMessagesOutsideContext(path8, messageFormat, inContextMessageIds) {
101941
+ if (inContextMessageIds.length === 0)
101942
+ return 0;
101943
+ const inContextIds = new Set(inContextMessageIds);
101944
+ const outsideContextIds = new Set;
101945
+ forEachJsonlRow(path8, (row) => {
101946
+ const message = messageFormat === LOCAL_TRANSCRIPT_LEGACY_MESSAGE_FORMAT ? row : isLocalTranscriptAppendEntry(row) ? row.message : undefined;
101947
+ if (isRecord2(message) && typeof message.id === "string" && !inContextIds.has(message.id)) {
101948
+ outsideContextIds.add(message.id);
101949
+ }
101950
+ });
101951
+ return outsideContextIds.size;
101952
+ }
101922
101953
  var LOCAL_OMITTED_IMAGE_PLACEHOLDER = "[image omitted: not in context]";
101923
101954
  var init_local_transcript_history = __esm(() => {
101924
101955
  init_local_transcript();
@@ -101991,25 +102022,6 @@ function parseToolInput(input) {
101991
102022
  return input;
101992
102023
  }
101993
102024
  }
101994
- function getListLimit(body) {
101995
- const limit4 = body?.limit;
101996
- return typeof limit4 === "number" && limit4 > 0 ? limit4 : undefined;
101997
- }
101998
- function getListOrder(body) {
101999
- const order = body?.order;
102000
- return order === "asc" ? "asc" : "desc";
102001
- }
102002
- function getCursor(body, key) {
102003
- const value = body?.[key];
102004
- return typeof value === "string" && value.length > 0 ? value : undefined;
102005
- }
102006
- function getIncludedMessageTypes(body) {
102007
- const value = body?.include_return_message_types;
102008
- if (!Array.isArray(value))
102009
- return;
102010
- const messageTypes = value.filter((item) => typeof item === "string" && item.length > 0);
102011
- return messageTypes.length > 0 ? new Set(messageTypes) : undefined;
102012
- }
102013
102025
  function encodePathSegment(value) {
102014
102026
  return Buffer.from(value).toString("base64url");
102015
102027
  }
@@ -102457,6 +102469,14 @@ class LocalStore {
102457
102469
  this.ensureConversation(conversationId, resolvedAgentId);
102458
102470
  return this.localMessagesForConversation(conversationId, resolvedAgentId).map(cloneLocalMessage);
102459
102471
  }
102472
+ countMessagesOutsideContext(conversationId, agentId) {
102473
+ const conversation = this.findConversation(conversationId, agentId);
102474
+ if (!conversation)
102475
+ return 0;
102476
+ const key = this.conversationKey(conversation.id, agentId);
102477
+ const metadata = this.validateTranscriptMetadata(key);
102478
+ return metadata ? countLocalTranscriptMessagesOutsideContext(metadata.messagesPath, metadata.messageFormat, conversation.in_context_message_ids) : 0;
102479
+ }
102460
102480
  settleInterruptedToolCalls(conversationIdOrAgentId, options = {}) {
102461
102481
  const targets = this.toolSettlementTargets(conversationIdOrAgentId, options.agentId);
102462
102482
  let settledCount = 0;
@@ -110134,7 +110154,7 @@ function compileLocalSystemPrompt(options) {
110134
110154
  agentId: options.agent.id,
110135
110155
  conversationId: options.conversationId,
110136
110156
  compiledAt,
110137
- previousMessageCount: options.previousMessageCount ?? 0
110157
+ previousMessageCount: typeof options.previousMessageCount === "function" ? options.previousMessageCount() : options.previousMessageCount ?? 0
110138
110158
  });
110139
110159
  const coreMemory = [memfs.content, metadata].filter((part) => part.trim().length > 0).join(`
110140
110160
 
@@ -110355,7 +110375,7 @@ var init_local_backend = __esm(() => {
110355
110375
  systemPrompt: appendAvailableSkillsBlock(input.agent.system, clientSkills2)
110356
110376
  };
110357
110377
  }
110358
- const persisted = await this.getOrCompileSystemPrompt(input.conversationId, input.agentId, input.agent, input.history.length);
110378
+ const persisted = await this.getOrCompileSystemPrompt(input.conversationId, input.agentId, input.agent);
110359
110379
  const clientSkills = Array.isArray(input.body.client_skills) ? input.body.client_skills : [];
110360
110380
  return {
110361
110381
  systemPrompt: appendAvailableSkillsBlock(persisted.content, clientSkills),
@@ -110542,7 +110562,7 @@ var init_local_backend = __esm(() => {
110542
110562
  const compiled = await this.getOrCompileSystemPrompt(conversationId, agentId);
110543
110563
  return { systemPrompt: compiled.content };
110544
110564
  }
110545
- async getOrCompileSystemPrompt(conversationId, agentId, agent = this.store.retrieveAgentRecord(agentId), previousMessageCount = 0) {
110565
+ async getOrCompileSystemPrompt(conversationId, agentId, agent = this.store.retrieveAgentRecord(agentId)) {
110546
110566
  const existing = this.store.getCompiledSystemPrompt(conversationId, agentId);
110547
110567
  const rawSystemHash = hashRawSystemPrompt(agent.system);
110548
110568
  const memfsRevision = this.isMemfsEnabledForAgent(agentId) ? getCommittedMemfsRevision(this.memoryDirForAgent(agentId)) : undefined;
@@ -110550,10 +110570,7 @@ var init_local_backend = __esm(() => {
110550
110570
  return existing;
110551
110571
  }
110552
110572
  if (existing?.rawSystemHash === rawSystemHash && existing.memfsRevision !== memfsRevision) {
110553
- const compiled = await this.compileAndMaybePersistSystemPrompt(conversationId, agentId, {
110554
- dryRun: true,
110555
- previousMessageCount
110556
- });
110573
+ const compiled = await this.compileAndMaybePersistSystemPrompt(conversationId, agentId, { dryRun: true });
110557
110574
  if (compiled.memfsRevision !== existing.memfsRevision) {
110558
110575
  const midConversationSystemPrompt = formatMidConversationMemoryUpdate(compiled);
110559
110576
  this.store.setCompiledSystemPrompt(conversationId, agentId, {
@@ -110567,8 +110584,7 @@ var init_local_backend = __esm(() => {
110567
110584
  return existing;
110568
110585
  }
110569
110586
  return this.compileAndMaybePersistSystemPrompt(conversationId, agentId, {
110570
- dryRun: false,
110571
- previousMessageCount
110587
+ dryRun: false
110572
110588
  });
110573
110589
  }
110574
110590
  async compileAndMaybePersistSystemPrompt(conversationId, agentId, options) {
@@ -110577,14 +110593,10 @@ var init_local_backend = __esm(() => {
110577
110593
  if (memfsEnabled) {
110578
110594
  await this.ensureLocalMemoryRepo(agentId, [], agent.name);
110579
110595
  }
110580
- const previousMessageCount = options.previousMessageCount ?? this.store.listConversationMessages(conversationId, {
110581
- agent_id: agentId,
110582
- order: "asc"
110583
- }).length;
110584
110596
  const compiled = compileLocalSystemPrompt({
110585
110597
  agent,
110586
110598
  conversationId,
110587
- previousMessageCount,
110599
+ previousMessageCount: () => this.store.countMessagesOutsideContext(conversationId, agentId),
110588
110600
  memoryDir: memfsEnabled ? this.memoryDirForAgent(agentId) : undefined,
110589
110601
  includeMemfs: memfsEnabled
110590
110602
  });
@@ -164907,7 +164919,7 @@ function taskNotificationMessage(text2) {
164907
164919
  function formatMonitorEventNotification(notification) {
164908
164920
  return `<task-notification>
164909
164921
  <task-id>${escapeXml(notification.taskId)}</task-id>
164910
- <summary>${escapeXml(`Monitor event: "${notification.event}"`)}</summary>
164922
+ <summary>${escapeXml(notification.description?.trim() ? `Monitor: ${notification.description}` : "Monitor event")}</summary>
164911
164923
  <result>
164912
164924
  <event>${escapeXml(notification.event)}</event>
164913
164925
  </result>
@@ -203357,7 +203369,7 @@ var init_mcp_client = __esm(() => {
203357
203369
  init_streamableHttp();
203358
203370
  DEFAULT_CLIENT_INFO = {
203359
203371
  name: "letta-code",
203360
- version: "0.34.63"
203372
+ version: "0.34.65"
203361
203373
  };
203362
203374
  });
203363
203375
 
@@ -207640,7 +207652,7 @@ Usage notes:
207640
207652
  var init_AskUserQuestion = () => {};
207641
207653
 
207642
207654
  // src/tools/descriptions/Bash.md
207643
- var Bash_default = "Executes a shell command and returns its output.\n\n- Each Bash call starts from the conversation's current working directory. A `cd` affects only that command and does not change the directory used by later tool calls. To change the working directory for later tool calls, use `SetWorkingDirectory`. For a one-off command elsewhere, use an absolute path or an option such as `git -C /path/to/repo status`.\n- IMPORTANT: Avoid using this tool to run `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed. Use Read, Edit and Write for file operations instead. Quote paths that contain spaces.\n- Command output is displayed to you, not reliably to the user.\n- `timeout` is in milliseconds. Without it, commands run until they exit; foreground timeouts max out at 600000.\n- If the output exceeds 30000 characters, you receive only the first 2000 characters plus the path of a file containing the full output. A failed command whose output exceeds 10000 characters returns a head-and-tail excerpt plus that file path. Read or search that file when you need the rest instead of re-running the command.\n- Commands still running after a brief wait continue in the background automatically: you receive a task ID and one completion notification. Do not predict command duration, set `run_in_background` merely because a command may be slow, or poll for completion. Set `run_in_background` only when you want the task ID immediately; no `&` needed.\n- Foreground `sleep` is blocked. To be notified once when a condition is true, run a command that exits then, e.g. `until grep -q \"Ready\" dev.log; do sleep 0.5; done`. For one notification per event, use Monitor.\n- Run independent commands as parallel tool calls; chain dependent ones with `&&`.\n\n# Git\n- Interactive flags (`-i`, e.g. `git rebase -i`, `git add -i`) are not supported in this environment.\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- GitHub notifies the owner of any `@name` written in a PR, issue, or comment. Write a bare `@name` only for a real login you mean to notify. Put roles, placeholders, and code (`@human`, `@reviewer`, `@types/node`) in backticks or drop the `@`.\n- Commit or push only when the user asks. Do not amend, skip hooks, force-push, or run other destructive git commands unless the user asks; if a pre-commit hook fails, fix the issue and create a new commit.\n- Pass commit messages and PR bodies as single-quoted strings with embedded newlines. Do not wrap them in `$(...)` or backticks. End commit messages with:\n{{COMMIT_TRAILER}}\n<example>\ngit commit -m 'Commit message here.\n\n{{COMMIT_TRAILER}}'\n</example>\n- Passing `gh pr checks` does not mean GitHub will merge the PR — unresolved review threads and still-pending required checks leave the merge state BLOCKED. If WatchPR is available and you will follow the PR toward merge, start it on the PR URL, and call the PR ready, green, or mergeable only once WatchPR reports it merge-ready.\n";
207655
+ var Bash_default = "Executes a shell command and returns its output.\n\n- Each Bash call starts from the conversation's current working directory. A `cd` affects only that command and does not change the directory used by later tool calls. To change the working directory for later tool calls, use `SetWorkingDirectory`. For a one-off command elsewhere, use an absolute path or an option such as `git -C /path/to/repo status`.\n- IMPORTANT: Avoid using this tool to run `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed. Use Read, Edit and Write for file operations instead. Quote paths that contain spaces.\n- Command output is displayed to you, not reliably to the user.\n- `timeout` is in milliseconds. Without it, commands run until they exit; foreground timeouts max out at 600000.\n- If the output exceeds 30000 characters, you receive only the first 2000 characters plus the path of a file containing the full output. A failed command whose output exceeds 10000 characters returns a head-and-tail excerpt plus that file path. Read or search that file when you need the rest instead of re-running the command.\n- Commands still running after a brief wait continue in the background automatically: you receive a task ID and one completion notification. Do not predict command duration, set `run_in_background` merely because a command may be slow, or poll for completion. Set `run_in_background` only when you want the task ID immediately; no `&` needed.\n- Foreground `sleep` is blocked. To wait for a condition, use Monitor.\n- Run independent commands as parallel tool calls; chain dependent ones with `&&`.\n\n# Git\n- Interactive flags (`-i`, e.g. `git rebase -i`, `git add -i`) are not supported in this environment.\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- GitHub notifies the owner of any `@name` written in a PR, issue, or comment. Write a bare `@name` only for a real login you mean to notify. Put roles, placeholders, and code (`@human`, `@reviewer`, `@types/node`) in backticks or drop the `@`.\n- Commit or push only when the user asks. Do not amend, skip hooks, force-push, or run other destructive git commands unless the user asks; if a pre-commit hook fails, fix the issue and create a new commit.\n- Pass commit messages and PR bodies as single-quoted strings with embedded newlines. Do not wrap them in `$(...)` or backticks. End commit messages with:\n{{COMMIT_TRAILER}}\n<example>\ngit commit -m 'Commit message here.\n\n{{COMMIT_TRAILER}}'\n</example>\n- Passing `gh pr checks` does not mean GitHub will merge the PR — unresolved review threads and still-pending required checks leave the merge state BLOCKED. If WatchPR is available and you will follow the PR toward merge, start it on the PR URL, and call the PR ready, green, or mergeable only once WatchPR reports it merge-ready.\n";
207644
207656
  var init_Bash = () => {};
207645
207657
 
207646
207658
  // src/tools/descriptions/CodeMode.md
@@ -207731,7 +207743,34 @@ Do not use this tool for root memory files (already loaded) or skills/ (use Skil
207731
207743
  var init_Memory = () => {};
207732
207744
 
207733
207745
  // src/tools/descriptions/Monitor.md
207734
- var Monitor_default = 'Start a background monitor that streams events from a long-running script. Each stdout line is an event — you keep working and notifications arrive in the chat. Events arrive on their own schedule and are not replies from the user, even if one lands while you\'re waiting for the user to answer a question.\n\nUse Monitor when you need one notification per occurrence: indefinitely ("every time an ERROR line appears": `tail -f`, `inotifywait -m`, `while true`), or until a known end ("each CI step result, stop when the run completes": a command that emits lines and then exits). For a single notification ("tell me when the server is ready"), run a command that exits when the condition is true, e.g. `until grep -q "Ready" dev.log; do sleep 0.5; done`, in the background with your shell tool; you get one completion notification. An unbounded command used for a single notification stays armed until timeout, and `tail -f log | grep -m 1 ...` can hang the same way.\n\nFor open github.com pull requests, use WatchPR instead. It covers the whole PR surface and keeps watching after CI finishes. Use Monitor only when WatchPR does not apply.\n\n- Every pipe stage must flush per line or matches sit in its buffer unseen: `grep` needs `--line-buffered`, `awk` needs `fflush()`. `| head -N` delivers nothing until N matches accumulate.\n- In poll loops, handle transient failures (`curl ... || true`). Poll remote APIs every 30s+, local checks every 0.5–1s.\n- Only stdout is the event stream. Stderr goes to the output file named in the result, without notifications; merge it with `2>&1` for commands you run directly so failures reach your filter.\n- Every stdout line is a conversation message, so filter to the lines you\'d act on. Lines within 200ms are batched into one notification. Monitors that produce too many events are stopped automatically; restart with a tighter filter.\n\n**Coverage — silence is not success.** When watching a job for an outcome, your filter must match every terminal state, not just the happy path. A monitor that greps only for the success marker stays silent through a crashloop, a hung process, or an unexpected exit — and silence looks identical to "still running." Match failures too, e.g. `grep -E --line-buffered "elapsed_steps=|Traceback|Error|FAILED|Killed|OOM"`, and in poll loops emit on every terminal status (`succeeded|failed|cancelled|timeout`).\n\nExit ends the watch (exit code is reported). Timeout → killed. Set `persistent: true` for session-length watches (log tails, long-lived event streams). In managed Cloud sandboxes, every monitor, including persistent ones, stops after {{MONITOR_MAX_TIMEOUT}} (this sandbox\'s monitor cap); elsewhere persistent monitors run until TaskStop or session end. Call Monitor again to re-arm it if you still need to watch. For much longer Cloud waits, schedule a Wake or cron (which does not keep the sandbox running between turns) and combine it with shorter monitors. Use TaskStop to cancel early.\n\nWhen someone is waiting on the result, set `backup_after_seconds` (e.g. 900). If the monitor goes that long without an event, a durable Wake brings you back to check the real state, so a queued, hung, or dead watch can\'t leave them waiting in silence.\n\nInstead of `command`, `ws` streams each WebSocket text frame as an event (prefer it over `websocat`), and `script` runs a JavaScript watch loop with CodeMode\'s globals plus `emit(text)` and `sleep(ms)`; `decide()` spends money on every call, so call it only when an observed change needs judgment.\n\nPass `resume` with a paused monitor id to restart it with its saved arguments.\n';
207746
+ var Monitor_default = `Start a background monitor that streams events from a long-running script. Each stdout line is an event — you keep working and notifications arrive in the chat. Events arrive on their own schedule and are not replies from the user, even if one lands while you're waiting for the user to answer a question.
207747
+
207748
+ Use Monitor whenever you are waiting for something to happen. Wake is only for an explicit time condition, or when no monitor is possible.
207749
+
207750
+ Pick the command by how many notifications you need:
207751
+ - One ("tell me when the server is ready"): a command that exits when the condition is true, e.g. \`until grep -q "Ready" dev.log; do sleep 0.5; done\`. You are notified when it exits.
207752
+ - One per occurrence, indefinitely ("every time an ERROR line appears"): an unbounded command (\`tail -f\`, \`inotifywait -m\`, \`while true\`).
207753
+ - One per occurrence, until a known end ("each CI step result, stop when the run completes"): a command that emits lines and then exits.
207754
+
207755
+ An unbounded command used for a single notification stays armed until timeout, and \`tail -f log | grep -m 1 ...\` can hang the same way.
207756
+
207757
+ For open github.com pull requests, use WatchPR instead. It covers the whole PR surface and keeps watching after CI finishes. Use Monitor only when WatchPR does not apply.
207758
+
207759
+ - Every pipe stage must flush per line or matches sit in its buffer unseen: \`grep\` needs \`--line-buffered\`, \`awk\` needs \`fflush()\`. \`| head -N\` delivers nothing until N matches accumulate.
207760
+ - In poll loops, handle transient failures (\`curl ... || true\`). Poll remote APIs every 30s+, local checks every 0.5–1s.
207761
+ - Only stdout is the event stream. Stderr goes to the output file named in the result, without notifications; merge it with \`2>&1\` for commands you run directly so failures reach your filter.
207762
+ - Every stdout line is a conversation message, so filter to the lines you'd act on. Lines within 200ms are batched into one notification. Monitors that produce too many events are stopped automatically; restart with a tighter filter.
207763
+
207764
+ **Coverage — silence is not success.** When watching a job for an outcome, your filter must match every terminal state, not just the happy path. A monitor that greps only for the success marker stays silent through a crashloop, a hung process, or an unexpected exit — and silence looks identical to "still running." Match failures too, e.g. \`grep -E --line-buffered "elapsed_steps=|Traceback|Error|FAILED|Killed|OOM"\`, and in poll loops emit on every terminal status (\`succeeded|failed|cancelled|timeout\`).
207765
+
207766
+ Exit ends the watch (exit code is reported). Timeout → killed. Set \`persistent: true\` for session-length watches (log tails, long-lived event streams). In managed Cloud sandboxes, every monitor, including persistent ones, stops after {{MONITOR_MAX_TIMEOUT}} (this sandbox's monitor cap); elsewhere persistent monitors run until TaskStop or session end. Call Monitor again to re-arm it if you still need to watch. For much longer Cloud waits, schedule a Wake or cron (which does not keep the sandbox running between turns) and combine it with shorter monitors. Use TaskStop to cancel early.
207767
+
207768
+ Set \`backup_after_seconds\` (e.g. 900) as the durable fallback when someone is waiting on the result. If the monitor goes that long without an event, a durable Wake brings you back to check the real state, so a queued, hung, or dead watch can't leave them waiting in silence.
207769
+
207770
+ Instead of \`command\`, \`ws\` streams each WebSocket text frame as an event (prefer it over \`websocat\`), and \`script\` runs a JavaScript watch loop with CodeMode's globals plus \`emit(text)\` and \`sleep(ms)\`; \`decide()\` spends money on every call, so call it only when an observed change needs judgment.
207771
+
207772
+ Pass \`resume\` with a paused monitor id to restart it with its saved arguments.
207773
+ `;
207735
207774
  var init_Monitor = () => {};
207736
207775
 
207737
207776
  // src/tools/descriptions/Read.md
@@ -207854,23 +207893,23 @@ var ViewImage_default = `View a local image file from the filesystem when visual
207854
207893
  var init_ViewImage = () => {};
207855
207894
 
207856
207895
  // src/tools/descriptions/Wake.md
207857
- var Wake_default = "Schedule a future turn for the current conversation. Wake is the durable, time-based counterpart to Monitor: use Monitor when ongoing work can emit an event, and Wake when you need to act at a future time even if nothing emits one.\n\nWake is always self-bound. It cannot target another agent, conversation, or computer.\n\n- `create`: provide `name`, `prompt`, and exactly one of `after_seconds`, `scheduled_at`, or `cron`.\n- `list`: list active and paused wakes for this conversation.\n- `cancel`: provide the `id` returned by create or list.\n\nWrite `prompt` as a note to your future self, not a script: what you are waiting on, what you planned and why, and what to check before acting. When the wake fires, the situation or people's wishes may have changed since you wrote it.\n\nUse `after_seconds` for ordinary follow-ups. `scheduled_at` must be RFC 3339 with `Z` or an explicit UTC offset. `cron` is a recurring five-field UTC expression and cannot run more often than hourly. For calendar requests such as \"tomorrow at 9am,\" resolve the time in the user's timezone (inferred from context), pass an explicit offset, and state the timezone you used.\n\nFor schedules targeting other conversations or computers, load the `scheduling-tasks` skill.\n";
207896
+ var Wake_default = "Schedule a future turn for the current conversation at a time you choose.\n\nDo not use Wake to wait for something to happen. If you can check for the condition (a job finishing, a deploy landing, a file or reply appearing), use Monitor: it brings you back when the thing happens, while a wake fires at a time you guessed, which is either too early or later than necessary. Never use a wake to poll.\n\nUse Wake only when:\n- there is an explicit time condition: a reminder, a follow-up at a set time, a recurring check-in; or\n- no monitor is possible, because nothing you can check would show the change.\n\nWake is always self-bound. It cannot target another agent, conversation, or computer.\n\n- `create`: provide `name`, `prompt`, and exactly one of `after_seconds`, `scheduled_at`, or `cron`.\n- `list`: list active and paused wakes for this conversation.\n- `cancel`: provide the `id` returned by create or list.\n\nWrite `prompt` as a note to your future self, not a script: what you are waiting on, what you planned and why, and what to check before acting. When the wake fires, the situation or people's wishes may have changed since you wrote it.\n\nUse `after_seconds` for follow-ups after a delay. `scheduled_at` must be RFC 3339 with `Z` or an explicit UTC offset. `cron` is a recurring five-field UTC expression and cannot run more often than hourly. For calendar requests such as \"tomorrow at 9am,\" resolve the time in the user's timezone (inferred from context), pass an explicit offset, and state the timezone you used.\n\nFor schedules targeting other conversations or computers, load the `scheduling-tasks` skill.\n";
207858
207897
  var init_Wake = () => {};
207859
207898
 
207860
207899
  // src/tools/descriptions/WatchPR.md
207861
- var WatchPR_default = `Watch one open github.com pull request until it merges, closes, is stopped with TaskStop, or the session ends.
207900
+ var WatchPR_default = `Watch one open github.com PR until merge, close, TaskStop or timeout; local watches also stop at session end.
207862
207901
 
207863
- In managed Cloud sandboxes, WatchPR also stops after {{MONITOR_MAX_TIMEOUT}} (this sandbox's monitor cap) and sends a timeout notification. Call WatchPR again to re-arm it if you still need to watch. For much longer waits, use Wake or cron (which does not keep the sandbox running between turns) and combine it with shorter watches. Local watches have no duration limit.
207902
+ In managed Cloud, WatchPR stops after {{MONITOR_MAX_TIMEOUT}} (the monitor cap) and sends a timeout notification. Call WatchPR again to re-arm it if you still need to watch. For much longer waits, use Wake or cron (which does not keep the sandbox running between turns) and combine it with shorter watches. Outside managed Cloud, local watches have no duration limit.
207864
207903
 
207865
207904
  Use WatchPR instead of writing a Monitor or shell polling loop when you need ongoing notifications about a PR: checks, comments, reviews, review threads, pushes, conflicts, merge state, merge, and close. Start at most one watch per PR.
207866
207905
 
207867
- The initial result includes current blockers and changes since the previous watch ended for the same agent, conversation, and PR, when a locally saved snapshot is at most seven days old. The first snapshot is never merge-ready: readiness requires a second consecutive read on the same head, so \`awaiting a second same-head readiness read\` is expected at startup. Later changes arrive as task notifications in this conversation. It uses the locally authenticated \`gh\` CLI and keeps watching after checks become green because reviews, comments, conflicts, and new pushes can still arrive. Green checks are not the same as a mergeable PR, so report the PR as ready, green, or mergeable only once the watcher reports it merge-ready.
207906
+ The initial result includes current blockers. Local watches also compare a saved snapshot up to seven days old. The first snapshot is never merge-ready: readiness requires a second consecutive read on the same head, so \`awaiting a second same-head readiness read\` is expected at startup. Later changes arrive as task notifications in this conversation. Cloud watches run remotely when enabled; others poll locally via the Cloud GitHub integration or \`gh\`. It keeps watching green PRs for feedback, conflicts and pushes. Green checks are not the same as a mergeable PR, so report the PR as ready, green, or mergeable only once the watcher reports it merge-ready.
207868
207907
 
207869
207908
  Pass a URL ending at the PR number, such as \`https://github.com/owner/repo/pull/123\`. Remove \`/files\`, \`/commits\`, \`/checks\`, and other suffixes. The watcher is read-only and errors if the PR is already merged or closed.
207870
207909
 
207871
- Use \`notify_on\` to limit PR notifications (for example \`["merged", "closed", "conflict"]\` or \`["checks_done"]\`); watcher errors still report. For several PRs, start one watch per URL. Workflow run URLs (\`https://github.com/owner/repo/actions/runs/123\`) report status changes and completion with conclusion and failed jobs/steps, including runs without a PR. Reruns remain a separate action.
207910
+ Use \`notify_on\` to limit PR notifications (for example \`["merged", "closed", "conflict"]\` or \`["checks_done"]\`); watcher errors still report. Workflow run URLs (\`https://github.com/owner/repo/actions/runs/123\`) report status changes and completion with conclusion and failed jobs/steps, including runs without a PR. Reruns remain a separate action.
207872
207911
 
207873
- Pass \`resume\` with a paused monitor id to restart it with its saved arguments.
207912
+ Pass \`resume\` with a local paused monitor id to restart it; a cloud id returns status only, without replaying a PR snapshot. Cloud watches continue between sessions.
207874
207913
  `;
207875
207914
  var init_WatchPR = () => {};
207876
207915
 
@@ -208660,6 +208699,12 @@ var init_manager = __esm(() => {
208660
208699
  init_settings_manager();
208661
208700
  ENABLED_TOGGLE_VALUES = new Set(["1", "true", "yes"]);
208662
208701
  EXPERIMENT_DEFINITIONS = [
208702
+ {
208703
+ id: "cloud_watch_pr",
208704
+ label: "Cloud WatchPR",
208705
+ description: "Run pull request watches in Cloud instead of polling locally.",
208706
+ envVar: "LETTA_CLOUD_WATCH_PR"
208707
+ },
208663
208708
  {
208664
208709
  id: "cloud_monitors",
208665
208710
  label: "Cloud monitors",
@@ -217173,7 +217218,26 @@ var init_subagent_tool_policy = __esm(() => {
217173
217218
  });
217174
217219
 
217175
217220
  // src/tools/descriptions/MonitorCloud.md
217176
- var MonitorCloud_default = 'Start a background monitor that streams events from a public http(s) URL. Each change to the HTTP status or body is an event — you keep working and notifications arrive in the chat. Events arrive on their own schedule and are not replies from the user, even if one lands while you\'re waiting for the user to answer a question.\n\nUse Monitor when you need one notification per occurrence: until the timeout ("every time the status changes"), or until a known end ("each CI step result, stop when the run completes": use `match` with `stop_on_match: true`). For a single notification ("tell me when the server is ready"), use `match` with `stop_on_match: true`.\n\nFor open github.com pull requests, use WatchPR instead. It covers the whole PR surface and keeps watching after CI finishes. Use Monitor only when WatchPR does not apply.\n\n- Cloud polls the URL with GET every 60s by default. Set `interval_seconds` to 60 or more. The first response is the baseline; by default, it notifies only when the HTTP status or body changes.\n- Use `select` to compare one JSON field instead of the whole body, and `match` to be notified when it reaches a value, with `stop_on_match` to finish after that. The first response is checked against `match` too, so a pipeline that already finished notifies right away. A value that keeps matching does not notify again.\n- Every event is a conversation message, so filter to the events you\'d act on.\n\n**Coverage — silence is not success.** When watching a job for an outcome, your filter must match every terminal state, not just the happy path. A monitor that matches only the success marker stays silent through a crashloop, a hung process, or an unexpected exit — and silence looks identical to "still running." Match failures too, e.g. `select: "0.status"`, `match: {"equals": ["success", "failed", "canceled"]}`, `stop_on_match: true`.\n\nA match ends the watch when `stop_on_match` is true. Timeout → killed. Set `timeout_ms` for longer watches; the default is 24 hours and the maximum is 7 days. Call Monitor again to re-arm it if you still need to watch. For much longer Cloud waits, schedule a Wake or cron (which does not keep the sandbox running between turns) and combine it with shorter monitors. Use TaskStop to cancel early.\n\nWhen someone is waiting on the result, schedule a Wake or cron to check the real state, so a queued, hung, or dead watch can\'t leave them waiting in silence.\n\nFor an authenticated API, pass `headers` that reference agent secrets as `$NAME`, the same as in shell commands: `{"PRIVATE-TOKEN": "$GITLAB_TOKEN"}`. Cloud fills them in on every poll, so the token is never written into the monitor.\n';
217221
+ var MonitorCloud_default = `Start a background monitor that streams events from a public http(s) URL. Each change to the HTTP status or body is an event — you keep working and notifications arrive in the chat. Events arrive on their own schedule and are not replies from the user, even if one lands while you're waiting for the user to answer a question.
217222
+
217223
+ Use Monitor whenever you are waiting for something to happen that a URL can show. Wake is only for an explicit time condition, or when no monitor is possible.
217224
+
217225
+ Use Monitor when you need one notification per occurrence: until the timeout ("every time the status changes"), or until a known end ("each CI step result, stop when the run completes": use \`match\` with \`stop_on_match: true\`). For a single notification ("tell me when the server is ready"), use \`match\` with \`stop_on_match: true\`.
217226
+
217227
+ For open github.com pull requests, use WatchPR instead. It covers the whole PR surface and keeps watching after CI finishes. Use Monitor only when WatchPR does not apply.
217228
+
217229
+ - Cloud polls the URL with GET every 60s by default. Set \`interval_seconds\` to 60 or more. The first response is the baseline; by default, it notifies only when the HTTP status or body changes.
217230
+ - Use \`select\` to compare one JSON field instead of the whole body, and \`match\` to be notified when it reaches a value, with \`stop_on_match\` to finish after that. The first response is checked against \`match\` too, so a pipeline that already finished notifies right away. A value that keeps matching does not notify again.
217231
+ - Every event is a conversation message, so filter to the events you'd act on.
217232
+
217233
+ **Coverage — silence is not success.** When watching a job for an outcome, your filter must match every terminal state, not just the happy path. A monitor that matches only the success marker stays silent through a crashloop, a hung process, or an unexpected exit — and silence looks identical to "still running." Match failures too, e.g. \`select: "0.status"\`, \`match: {"equals": ["success", "failed", "canceled"]}\`, \`stop_on_match: true\`.
217234
+
217235
+ A match ends the watch when \`stop_on_match\` is true. Timeout → killed. Set \`timeout_ms\` for longer watches; the default is 24 hours and the maximum is 7 days. Call Monitor again to re-arm it if you still need to watch. For much longer Cloud waits, schedule a Wake or cron (which does not keep the sandbox running between turns) and combine it with shorter monitors. Use TaskStop to cancel early.
217236
+
217237
+ When someone is waiting on the result, schedule a Wake or cron to check the real state, so a queued, hung, or dead watch can't leave them waiting in silence.
217238
+
217239
+ For an authenticated API, pass \`headers\` that reference agent secrets as \`$NAME\`, the same as in shell commands: \`{"PRIVATE-TOKEN": "$GITLAB_TOKEN"}\`. Cloud fills them in on every poll, so the token is never written into the monitor.
217240
+ `;
217177
217241
  var init_MonitorCloud = () => {};
217178
217242
 
217179
217243
  // src/tools/schemas/MonitorCloud.json
@@ -225996,7 +226060,7 @@ var init_manager2 = __esm(() => {
225996
226060
  "Workflow"
225997
226061
  ]);
225998
226062
  SCOPED_BACKGROUND_TOOLS = new Set(["Monitor", "Workflow", "CodeMode"]);
225999
- TOOL_CALL_ID_TOOLS = new Set(["Task", "Skill", "Monitor"]);
226063
+ TOOL_CALL_ID_TOOLS = new Set(["Task", "Skill", "Monitor", "WatchPR"]);
226000
226064
  FILE_MUTATING_TOOLS = new Set(["Edit", "Write"]);
226001
226065
  ARTIFACT_TOOL_NAMES = [
226002
226066
  "read_artifact_file",
@@ -226104,13 +226168,13 @@ function parseSearchResult(value) {
226104
226168
  }
226105
226169
  return { toolId, jsonSchema, score };
226106
226170
  }
226107
- async function withTimeout2(promise2, timeoutMs, operation) {
226171
+ async function withTimeout2(promise2, timeoutMs, operation, timeoutMessage) {
226108
226172
  let timer;
226109
226173
  try {
226110
226174
  return await Promise.race([
226111
226175
  promise2,
226112
226176
  new Promise((_resolve, reject2) => {
226113
- timer = setTimeout(() => reject2(new Error(`${operation} timed out after ${timeoutMs}ms`)), timeoutMs);
226177
+ timer = setTimeout(() => reject2(new Error(timeoutMessage ?? `${operation} timed out after ${timeoutMs}ms`)), timeoutMs);
226114
226178
  })
226115
226179
  ]);
226116
226180
  } finally {
@@ -226176,7 +226240,7 @@ async function runUnifiedMcpTool(params) {
226176
226240
  [MCP_ORIGINATOR_ISOLATION_HEADER3]: "1"
226177
226241
  }
226178
226242
  } : {}
226179
- }), params.timeoutMs ?? 60000, "Running agent MCP tool");
226243
+ }), params.timeoutMs ?? 60000, "Running agent MCP tool", `MCP tool call hit the cloud server's ${(params.timeoutMs ?? 60000) / 1000}-second limit; the MCP server may still be processing the request. Retry with a smaller or more selective request, or set the tool's own timeout argument below ${(params.timeoutMs ?? 60000) / 1000} seconds if it has one.`);
226180
226244
  return parseRunResult(value);
226181
226245
  }
226182
226246
  var MCP_ORIGINATOR_TOKEN_HEADER3 = "x-letta-mcp-originator-token", MCP_ORIGINATOR_ISOLATION_HEADER3 = "x-letta-mcp-originator-isolation";
@@ -234737,7 +234801,14 @@ async function startScriptMonitor(args, hooks) {
234737
234801
  };
234738
234802
  const events = createMonitorEventStream({
234739
234803
  emit(event) {
234740
- hooks.queueEvent({ taskId, event, scope, actingUserId, secrets: secrets2 });
234804
+ hooks.queueEvent({
234805
+ taskId,
234806
+ description: args.description,
234807
+ event,
234808
+ scope,
234809
+ actingUserId,
234810
+ secrets: secrets2
234811
+ });
234741
234812
  },
234742
234813
  stopSource() {
234743
234814
  stop2("output rate too high", `
@@ -234850,6 +234921,7 @@ async function startScriptMonitor(args, hooks) {
234850
234921
  events.finish();
234851
234922
  hooks.queueEvent({
234852
234923
  taskId,
234924
+ description: args.description,
234853
234925
  event: hooks.timeoutEvent(args.timeout_ms),
234854
234926
  scope,
234855
234927
  actingUserId,
@@ -234995,7 +235067,7 @@ function applyMonitorMaxTimeout(text2, timeoutMs = getMonitorMaxTimeoutMs()) {
234995
235067
  return text2.replaceAll("{{MONITOR_MAX_TIMEOUT}}", formatMonitorMaxTimeout(timeoutMs));
234996
235068
  }
234997
235069
  function getMonitorTimeoutEvent(timeoutMs, tool = "Monitor") {
234998
- return isManagedCloudRuntime() && timeoutMs === getMonitorMaxTimeoutMs() ? `${tool} stopped at the ${timeoutMs / 3600000}-hour Cloud sandbox limit. If you still need to watch, simply re-arm it by calling ${tool} again. For much longer waits, schedule a Wake or cron, which does not keep the sandbox running between turns.` : "[Monitor timed out — re-arm if needed.]";
235070
+ return isManagedCloudRuntime() && timeoutMs === getMonitorMaxTimeoutMs() ? `${tool} stopped at the ${timeoutMs / 3600000}-hour Cloud sandbox limit. If you still need to watch, re-arm it by calling ${tool} again.` : "[Monitor timed out — re-arm if needed.]";
234999
235071
  }
235000
235072
  var HOUR_MS = 3600000, DAY_MS, DEFAULT_MAX_TIMEOUT_MS, SEVEN_DAYS_MS;
235001
235073
  var init_monitor_timeout = __esm(() => {
@@ -235376,7 +235448,8 @@ function queueMonitorEvent(params) {
235376
235448
  kind: "task_notification",
235377
235449
  text: formatMonitorEventNotification({
235378
235450
  taskId,
235379
- event: sanitizedEvent
235451
+ event: sanitizedEvent,
235452
+ description: sanitizeMonitorText(params.description ?? "", secrets2)
235380
235453
  }),
235381
235454
  ...scope,
235382
235455
  ...actingUserId !== undefined ? { actingUserId } : {}
@@ -235455,6 +235528,7 @@ function startCommandMonitor(args) {
235455
235528
  emit(event) {
235456
235529
  queueMonitorEvent({
235457
235530
  taskId,
235531
+ description: args.description,
235458
235532
  event,
235459
235533
  scope,
235460
235534
  actingUserId,
@@ -235578,6 +235652,7 @@ function startCommandMonitor(args) {
235578
235652
  `);
235579
235653
  queueMonitorEvent({
235580
235654
  taskId,
235655
+ description: args.description,
235581
235656
  event: getMonitorTimeoutEvent(args.timeout_ms),
235582
235657
  scope,
235583
235658
  actingUserId,
@@ -235633,6 +235708,7 @@ function startWebSocketMonitor(args) {
235633
235708
  emit(event) {
235634
235709
  queueMonitorEvent({
235635
235710
  taskId,
235711
+ description: args.description,
235636
235712
  event,
235637
235713
  scope,
235638
235714
  actingUserId,
@@ -235686,6 +235762,7 @@ function startWebSocketMonitor(args) {
235686
235762
  `);
235687
235763
  queueMonitorEvent({
235688
235764
  taskId,
235765
+ description: args.description,
235689
235766
  event,
235690
235767
  scope,
235691
235768
  actingUserId,
@@ -235719,6 +235796,7 @@ function startWebSocketMonitor(args) {
235719
235796
  `);
235720
235797
  queueMonitorEvent({
235721
235798
  taskId,
235799
+ description: args.description,
235722
235800
  event,
235723
235801
  scope,
235724
235802
  actingUserId,
@@ -235744,6 +235822,7 @@ function startWebSocketMonitor(args) {
235744
235822
  `);
235745
235823
  queueMonitorEvent({
235746
235824
  taskId,
235825
+ description: args.description,
235747
235826
  event,
235748
235827
  scope,
235749
235828
  actingUserId,
@@ -235760,6 +235839,7 @@ function startWebSocketMonitor(args) {
235760
235839
  return;
235761
235840
  queueMonitorEvent({
235762
235841
  taskId,
235842
+ description: args.description,
235763
235843
  event: getMonitorTimeoutEvent(args.timeout_ms),
235764
235844
  scope,
235765
235845
  actingUserId,
@@ -238906,12 +238986,15 @@ function buildAgentSendContent(sender, noWait, message) {
238906
238986
  { type: "text", text: message }
238907
238987
  ];
238908
238988
  }
238989
+ function buildAgentSendCliTarget(agentId, conversationId) {
238990
+ return conversationId === "default" ? `--agent ${agentId} --conversation default` : `--conversation ${conversationId}`;
238991
+ }
238909
238992
  function buildAgentSendReminder(sender, noWait) {
238910
238993
  if (!sender.agentId)
238911
238994
  return "";
238912
238995
  const address = sender.conversationId ? `, conversation ${sender.conversationId}` : "";
238913
238996
  const isDefault = sender.conversationId === "default";
238914
- const cliTarget = isDefault ? `--agent ${sender.agentId} --conversation default` : `--conversation ${sender.conversationId}`;
238997
+ const cliTarget = buildAgentSendCliTarget(sender.agentId, sender.conversationId ?? "");
238915
238998
  const toolTarget = isDefault ? `agent_id ${sender.agentId} and conversation_id default` : `conversation_id ${sender.conversationId}`;
238916
238999
  const instruction = !noWait ? "The sender will only see the final message you generate (not tool calls or reasoning). Include your answer in your final response." : sender.conversationId ? `To reply, call SendAgentMessage with ${toolTarget}. Only if that tool is unavailable, run letta -p ${cliTarget} --no-wait "your reply". Ordinary assistant output is not forwarded to the sender.` : "Ordinary assistant output is not forwarded to the sender. No return conversation was supplied.";
238917
239000
  return `<system-reminder>
@@ -239112,9 +239195,10 @@ function withNativeCliPath(env6, platform7 = process.platform) {
239112
239195
  var init_native_cli_env = () => {};
239113
239196
 
239114
239197
  // src/tools/impl/claude-steer-timeouts.ts
239115
- var CLAUDE_TURN_START_TIMEOUT_MS = 60000, CLAUDE_CONTROL_RESPONSE_TIMEOUT_MS = 30000, REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS, CLAUDE_TURN_START_TIMEOUT_ERROR = "Claude turn did not become interruptible", CLAUDE_INTERRUPT_ACK_TIMEOUT_ERROR = "Claude interrupt acknowledgement timed out";
239198
+ var CLAUDE_TURN_START_TIMEOUT_MS = 60000, CLAUDE_CONTROL_RESPONSE_TIMEOUT_MS = 30000, REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS, REMOTE_SUBAGENT_MESSAGE_DEDUPE_PENDING_TTL_MS, CLAUDE_TURN_START_TIMEOUT_ERROR = "Claude turn did not become interruptible", CLAUDE_INTERRUPT_ACK_TIMEOUT_ERROR = "Claude interrupt acknowledgement timed out";
239116
239199
  var init_claude_steer_timeouts = __esm(() => {
239117
239200
  REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS = CLAUDE_TURN_START_TIMEOUT_MS + CLAUDE_CONTROL_RESPONSE_TIMEOUT_MS + 30000;
239201
+ REMOTE_SUBAGENT_MESSAGE_DEDUPE_PENDING_TTL_MS = 5 * REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS;
239118
239202
  });
239119
239203
 
239120
239204
  // src/tools/impl/external-llm-trace-payload.ts
@@ -240584,7 +240668,7 @@ class CodexAppServerClient {
240584
240668
  await this.request("initialize", {
240585
240669
  clientInfo: {
240586
240670
  name: "letta-code",
240587
- version: "0.34.63"
240671
+ version: "0.34.65"
240588
240672
  },
240589
240673
  capabilities: null
240590
240674
  });
@@ -242079,7 +242163,7 @@ ${SYSTEM_REMINDER_CLOSE}`;
242079
242163
  return null;
242080
242164
  }
242081
242165
  }
242082
- async function defaultListServerSideServers(agentId) {
242166
+ async function defaultListServerSideServers(agentId, timeoutMs = 3000) {
242083
242167
  let serverSideAvailable = false;
242084
242168
  try {
242085
242169
  const { getBackend: getBackend2 } = await Promise.resolve().then(() => (init_backend2(), exports_backend));
@@ -242095,7 +242179,7 @@ async function defaultListServerSideServers(agentId) {
242095
242179
  const { LETTA_CLOUD_API_URL: LETTA_CLOUD_API_URL2 } = await Promise.resolve().then(() => (init_oauth(), exports_oauth));
242096
242180
  const { listUnifiedMcpServers: listUnifiedMcpServers2 } = await Promise.resolve().then(() => (init_unified_mcp(), exports_unified_mcp));
242097
242181
  const client = await getClient2();
242098
- const allServers = await listUnifiedMcpServers2(client, agentId, 3000);
242182
+ const allServers = await listUnifiedMcpServers2(client, agentId, timeoutMs);
242099
242183
  const servers = getServerUrl2() === LETTA_CLOUD_API_URL2 ? allServers.filter((server2) => server2.serverType !== "stdio") : allServers;
242100
242184
  return servers.map((server2) => ({
242101
242185
  name: server2.serverName,
@@ -242109,26 +242193,20 @@ function formatMcpServerEntry(entry) {
242109
242193
  return `${entry.name} (${entry.toolCount} ${entry.toolCount === 1 ? "tool" : "tools"})`;
242110
242194
  }
242111
242195
  function buildMcpServersReminderText(entries) {
242112
- if (entries.length === 0) {
242113
- return `${SYSTEM_REMINDER_OPEN}
242114
- MCP servers with available tools: None
242115
- Do not automatically store results of principal-restricted operations in shared memory.
242116
- ${SYSTEM_REMINDER_CLOSE}`;
242117
- }
242118
- const rendered = entries.map(formatMcpServerEntry).join(", ");
242196
+ const inventory = entries === null ? 'MCP server list could not be loaded. Run `letta mcp search "<what you want to do>"` to find tools.' : `MCP servers with available tools: ${entries.length ? entries.map(formatMcpServerEntry).join(", ") : "None"}`;
242119
242197
  return `${SYSTEM_REMINDER_OPEN}
242120
- MCP servers with available tools: ${rendered}
242121
- Do not automatically store results of principal-restricted operations in shared memory.
242122
- Find tools (with schemas) with \`letta mcp search "<what you want to do>"\`, list one server's tools with \`letta mcp tools <server>\` (\`--full\` includes schemas, \`letta mcp schema <tool-name>\` fetches one), and invoke one with \`letta mcp call <tool-name> --args '{"key":"value"}'\`. For large or quote-heavy arguments, use \`--args-file <path>\` (\`-\` for stdin) instead of \`--args\`. Exit code 2 means the tool returned an error result: read its \`content\`, fix the arguments, and retry (exit 1 is a CLI/usage error).
242123
- ${SYSTEM_REMINDER_CLOSE}`;
242198
+ ${inventory}
242199
+ ${MCP_MEMORY_GUIDANCE}
242200
+ ${entries?.length === 0 ? "" : `${MCP_TOOL_USAGE}
242201
+ `}${SYSTEM_REMINDER_CLOSE}`;
242124
242202
  }
242125
- async function listMcpServersForAgent(agentId, _state, deps = {}) {
242203
+ async function listMcpServersForAgent(agentId, _state, deps = {}, timeoutMs = 3000) {
242126
242204
  const localNames = (deps.getLocalServerNames ?? ((id) => settingsManager.getMcpServers(id).map((server2) => server2.name)))(agentId);
242127
242205
  const entries = localNames.map((name) => ({
242128
242206
  name,
242129
242207
  toolCount: null
242130
242208
  }));
242131
- const serverSideEntries = await (deps.listServerSideServers ?? defaultListServerSideServers)(agentId);
242209
+ const serverSideEntries = await (deps.listServerSideServers ?? defaultListServerSideServers)(agentId, timeoutMs);
242132
242210
  if (serverSideEntries)
242133
242211
  entries.push(...serverSideEntries);
242134
242212
  return [...new Map(entries.map((entry) => [entry.name, entry])).values()];
@@ -242346,7 +242424,7 @@ function prependReminderPartsToContent(content, reminderParts) {
242346
242424
  }
242347
242425
  return [...reminderParts, { type: "text", text: text2 }];
242348
242426
  }
242349
- var PERMISSION_MODE_DESCRIPTIONS, MAX_COMMAND_REMINDERS_PER_TURN = 10, MAX_TOOLSET_REMINDERS_PER_TURN = 5, MAX_COMMAND_INPUT_CHARS = 2000, MAX_COMMAND_OUTPUT_CHARS = 4000, MAX_TOOL_LIST_CHARS = 3000, sharedReminderProviders;
242427
+ var MCP_MEMORY_GUIDANCE = "Do not automatically store results of principal-restricted operations in shared memory.", MCP_TOOL_USAGE = `Find tools (with schemas) with \`letta mcp search "<what you want to do>"\`, list one server's tools with \`letta mcp tools <server>\` (\`--full\` includes schemas, \`letta mcp schema <tool-name>\` fetches one), and invoke one with \`letta mcp call <tool-name> --args '{"key":"value"}'\`. For large or quote-heavy arguments, use \`--args-file <path>\` (\`-\` for stdin) instead of \`--args\`. Exit code 2 means the tool returned an error result: read its \`content\`, fix the arguments, and retry (exit 1 is a CLI/usage error).`, PERMISSION_MODE_DESCRIPTIONS, MAX_COMMAND_REMINDERS_PER_TURN = 10, MAX_TOOLSET_REMINDERS_PER_TURN = 5, MAX_COMMAND_INPUT_CHARS = 2000, MAX_COMMAND_OUTPUT_CHARS = 4000, MAX_TOOL_LIST_CHARS = 3000, sharedReminderProviders;
242350
242428
  var init_engine = __esm(() => {
242351
242429
  init_agent_info();
242352
242430
  init_conversation_bootstrap();
@@ -243502,7 +243580,14 @@ function buildExternalCodingAgentMcpReminder(entries2) {
243502
243580
  async function resolveExternalCodingAgentMcpReminder(parentAgentId, mcp, deps = {}) {
243503
243581
  if (mcp?.inherit === false)
243504
243582
  return;
243505
- const inventory = await listMcpServersForAgent(await getMcpScopeAgentId(parentAgentId, undefined, deps.lookupParentAgent), createSharedReminderState(), deps);
243583
+ const scopeAgentId = await getMcpScopeAgentId(parentAgentId, undefined, deps.lookupParentAgent);
243584
+ let inventory;
243585
+ try {
243586
+ inventory = await listMcpServersForAgent(scopeAgentId, createSharedReminderState(), deps, 5000);
243587
+ } catch (error4) {
243588
+ debugLog("mcp", "Failed to load worker MCP inventory: %s", error4);
243589
+ return buildMcpServersReminderText(null);
243590
+ }
243506
243591
  return buildExternalCodingAgentMcpReminder(selectExternalCodingAgentMcpEntries(inventory, mcp?.servers));
243507
243592
  }
243508
243593
  function buildExternalCodingAgentCommand(options) {
@@ -243906,6 +243991,7 @@ var init_external_coding_agent = __esm(() => {
243906
243991
  init_engine();
243907
243992
  init_runtime_context();
243908
243993
  init_secret_substitution();
243994
+ init_debug();
243909
243995
  init_native_cli_env();
243910
243996
  init_claude_stream_session();
243911
243997
  init_codex_app_server();
@@ -245327,7 +245413,7 @@ async function prependParentContext(params) {
245327
245413
  prompt: [
245328
245414
  "The following JSONL is a read-only record of the parent's conversation. The task after the history block tells you what to do now; use the history as the source for everything else. If the task conflicts with what people said in the history, follow what people said in the history. Do not resume unrelated work from the history.",
245329
245415
  "Records marked injected came from the harness, not the human. Tool calls and results are linked by call_id. Records marked truncated have omitted content; use the commands below to read further.",
245330
- `This shows the parent's current context: the latest compaction summary when available, followed by its most recent in-context messages, up to 50,000 characters (an oversized summary is kept whole). If context lookup failed, it shows a recent-history fallback instead. For earlier or omitted history, search with \`letta messages search --query "<words>" --agent ${params.parentAgentId} --conversation ${params.parentConversationId}\`, or page back with \`letta messages list --agent ${params.parentAgentId} --conversation ${params.parentConversationId}\`. To ask the parent something or report back mid-task, run \`letta -p --agent ${params.parentAgentId} --conversation ${params.parentConversationId} --no-wait "<message>"\`.`,
245416
+ `This shows the parent's current context: the latest compaction summary when available, followed by its most recent in-context messages, up to 50,000 characters (an oversized summary is kept whole). If context lookup failed, it shows a recent-history fallback instead. For earlier or omitted history, search with \`letta messages search --query "<words>" --agent ${params.parentAgentId} --conversation ${params.parentConversationId}\`, or page back with \`letta messages list --agent ${params.parentAgentId} --conversation ${params.parentConversationId}\`.`,
245331
245417
  "<parent_history>",
245332
245418
  serializeHistoryRecord({
245333
245419
  type: "metadata",
@@ -245344,13 +245430,25 @@ async function prependParentContext(params) {
245344
245430
  `)
245345
245431
  };
245346
245432
  }
245433
+ function withReportBackInstruction(prompt, parentAgentId, parentConversationId) {
245434
+ if (!parentConversationId)
245435
+ return prompt;
245436
+ return [
245437
+ prompt,
245438
+ "",
245439
+ `When you open a pull request (draft or ready) or hit a blocker you can't get past, tell the parent right away, then keep working: run \`letta -p ${buildAgentSendCliTarget(parentAgentId, parentConversationId)} --no-wait "<what happened, with the link>. Tell the person who asked now; a draft is a result."\` (for a blocker, end with "Tell the person who asked now."). Use the same command to ask the parent something mid-task.`
245440
+ ].join(`
245441
+ `);
245442
+ }
245347
245443
  async function prepareExternalWorkerPrompt(params) {
245348
- if (!params.forkContext)
245349
- return { prompt: params.prompt };
245444
+ const parentConversationId = params.parentConversationId ?? getConversationId() ?? (params.forkContext ? "default" : undefined);
245445
+ const prompt = withReportBackInstruction(params.prompt, params.parentAgentId, parentConversationId);
245446
+ if (!params.forkContext || !parentConversationId)
245447
+ return { prompt };
245350
245448
  return prependParentContext({
245351
- prompt: params.prompt,
245449
+ prompt,
245352
245450
  parentAgentId: params.parentAgentId,
245353
- parentConversationId: params.parentConversationId ?? getConversationId() ?? "default",
245451
+ parentConversationId,
245354
245452
  signal: params.signal
245355
245453
  });
245356
245454
  }
@@ -245359,6 +245457,7 @@ var init_external_fork_context = __esm(() => {
245359
245457
  init_context();
245360
245458
  init_parent_transcript();
245361
245459
  init_backend2();
245460
+ init_agent_message();
245362
245461
  });
245363
245462
 
245364
245463
  // src/tools/impl/fork-prompt.ts
@@ -245856,6 +245955,64 @@ function isVersionBelow(version3, minimum) {
245856
245955
  return result3 === -1;
245857
245956
  }
245858
245957
 
245958
+ // src/tools/impl/remote-connect-retry.ts
245959
+ import { setTimeout as delay5 } from "node:timers/promises";
245960
+ async function connectRemoteWorkerWithRetry(connect, signal) {
245961
+ const backoffs = [1000, 3000];
245962
+ for (let attempt2 = 0;; attempt2++) {
245963
+ signal?.throwIfAborted();
245964
+ try {
245965
+ return await connect();
245966
+ } catch (error4) {
245967
+ signal?.throwIfAborted();
245968
+ const message2 = error4 instanceof Error ? error4.message : String(error4);
245969
+ const status = extractHttpStatus(message2);
245970
+ const transient = status !== undefined ? status >= 500 : /ECONNRESET|ETIMEDOUT|ECONNREFUSED|EPIPE|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|socket closed|connection reset|timed out|closed before opening/i.test(message2);
245971
+ const backoff3 = backoffs[attempt2];
245972
+ if (!transient || backoff3 === undefined)
245973
+ throw error4;
245974
+ await delay5(backoff3, undefined, { signal });
245975
+ }
245976
+ }
245977
+ }
245978
+ var init_remote_connect_retry = __esm(() => {
245979
+ init_error_reporting();
245980
+ });
245981
+
245982
+ // src/tools/impl/remote-follow-up-retry.ts
245983
+ async function sendRemoteFollowUpWithReconnect(client, command, connect, attach, computer) {
245984
+ try {
245985
+ try {
245986
+ return await client.sendSubagentMessage(command, {
245987
+ timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS
245988
+ });
245989
+ } catch (error4) {
245990
+ if (!(error4 instanceof Error) || error4.message !== "App-server socket closed")
245991
+ throw error4;
245992
+ client.close();
245993
+ const reconnected = await connect();
245994
+ attach(reconnected);
245995
+ return await reconnected.sendSubagentMessage(command, {
245996
+ timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS
245997
+ });
245998
+ }
245999
+ } catch (error4) {
246000
+ if (error4 instanceof Error && error4.message === "App-server socket closed")
246001
+ throw new RemoteFollowUpSocketClosedError(`The connection to ${computer} dropped before it confirmed the follow-up, even after one retry. The message may not have been delivered; check the worker's output, or send it again.`);
246002
+ if (error4 instanceof Error && error4.message === `Timed out waiting for ${command.request_id}`)
246003
+ throw new RemoteFollowUpTimeoutError(`${computer} didn't confirm the follow-up within ${Math.round(REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS / 1000)}s. The message may not have been delivered; check the worker's output, or send it again.`);
246004
+ throw error4;
246005
+ }
246006
+ }
246007
+ var RemoteFollowUpTimeoutError, RemoteFollowUpSocketClosedError;
246008
+ var init_remote_follow_up_retry = __esm(() => {
246009
+ init_claude_steer_timeouts();
246010
+ RemoteFollowUpTimeoutError = class RemoteFollowUpTimeoutError extends Error {
246011
+ };
246012
+ RemoteFollowUpSocketClosedError = class RemoteFollowUpSocketClosedError extends Error {
246013
+ };
246014
+ });
246015
+
245859
246016
  // src/tools/impl/remote-subagent-events.ts
245860
246017
  function followRemoteSubagentEvents(subagentId, read2) {
245861
246018
  let cursor = 0;
@@ -246000,7 +246157,11 @@ function classifyRemoteExternalWorkerControlError(error4) {
246000
246157
  return "outdated_computer";
246001
246158
  if (error4 instanceof RemoteFollowUpTimeoutError)
246002
246159
  return "steer_timeout";
246160
+ if (error4 instanceof RemoteFollowUpSocketClosedError)
246161
+ return "socket_closed";
246003
246162
  const message2 = errorMessage5(error4);
246163
+ if (message2 === "App-server socket closed")
246164
+ return "socket_closed";
246004
246165
  if (message2 === CLAUDE_TURN_START_TIMEOUT_ERROR || message2 === CLAUDE_INTERRUPT_ACK_TIMEOUT_ERROR)
246005
246166
  return "worker_busy";
246006
246167
  if (/^Computer ".*" is offline(?:\.|$)/.test(message2) || message2.startsWith("Timed out waiting for cloud sandbox "))
@@ -246232,7 +246393,7 @@ async function launchRemoteExternalCodingAgent(params, deps) {
246232
246393
  const toolCallId = params.toolCallId ?? `remote-${randomUUID46()}`;
246233
246394
  let client;
246234
246395
  try {
246235
- client = await connect();
246396
+ client = await connectRemoteWorkerWithRetry(connect, params.signal);
246236
246397
  } catch (error4) {
246237
246398
  return fail2("connect", `Can't reach ${computer}: ${errorMessage5(error4)}`);
246238
246399
  }
@@ -246422,7 +246583,7 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246422
246583
  const bareAgentId = formatExternalCodingAgentId(target.type, target.sessionId);
246423
246584
  let response;
246424
246585
  try {
246425
- response = await client.sendSubagentMessage({
246586
+ response = await sendRemoteFollowUpWithReconnect(client, {
246426
246587
  request_id: requestId,
246427
246588
  runtime: {
246428
246589
  agent_id: params.parentScope.agentId,
@@ -246432,12 +246593,9 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246432
246593
  agent_id: bareAgentId,
246433
246594
  message: params.message,
246434
246595
  tool_call_id: toolCallId
246435
- }, { timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS });
246596
+ }, connect, (reconnected) => follower.attach(reconnected), target.computer);
246436
246597
  } catch (error4) {
246437
246598
  follower.close();
246438
- if (errorMessage5(error4) === `Timed out waiting for ${requestId}`) {
246439
- throw new RemoteFollowUpTimeoutError(`${target.computer} didn't confirm the follow-up within ${Math.round(REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS / 1000)}s. The message may not have been delivered; check the worker's output, or send it again.`);
246440
- }
246441
246599
  throw error4;
246442
246600
  }
246443
246601
  if (!response.success) {
@@ -246509,7 +246667,7 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246509
246667
  outputFile: tracked.outputFile
246510
246668
  };
246511
246669
  }
246512
- var REMOTE_EXTERNAL_WORKER_STOPPED, DISPLAY_NAMES, RemoteWorkerLostError, OutdatedRemoteWorkerError, RemoteFollowUpTimeoutError, MAX_RECONNECT_DELAY_MS = 30000;
246670
+ var REMOTE_EXTERNAL_WORKER_STOPPED, DISPLAY_NAMES, RemoteWorkerLostError, OutdatedRemoteWorkerError, MAX_RECONNECT_DELAY_MS = 30000;
246513
246671
  var init_remote_external_coding_agent = __esm(() => {
246514
246672
  init_subagent_state();
246515
246673
  init_app_server_client();
@@ -246521,6 +246679,8 @@ var init_remote_external_coding_agent = __esm(() => {
246521
246679
  init_error_reporting();
246522
246680
  init_claude_steer_timeouts();
246523
246681
  init_external_coding_agent();
246682
+ init_remote_connect_retry();
246683
+ init_remote_follow_up_retry();
246524
246684
  init_remote_subagent_events();
246525
246685
  REMOTE_EXTERNAL_WORKER_STOPPED = Symbol("remote external worker stopped");
246526
246686
  DISPLAY_NAMES = {
@@ -246533,8 +246693,6 @@ var init_remote_external_coding_agent = __esm(() => {
246533
246693
  };
246534
246694
  OutdatedRemoteWorkerError = class OutdatedRemoteWorkerError extends Error {
246535
246695
  };
246536
- RemoteFollowUpTimeoutError = class RemoteFollowUpTimeoutError extends Error {
246537
- };
246538
246696
  });
246539
246697
 
246540
246698
  // src/tools/impl/subagent-computer.ts
@@ -249395,7 +249553,7 @@ var init_github_pull_request_watch = __esm(() => {
249395
249553
  });
249396
249554
 
249397
249555
  // src/tools/impl/github-pull-request-cloud.ts
249398
- import { setTimeout as delay5 } from "node:timers/promises";
249556
+ import { setTimeout as delay6 } from "node:timers/promises";
249399
249557
  async function requestSnapshot(ref, signal) {
249400
249558
  const client = await getClient();
249401
249559
  try {
@@ -249467,7 +249625,7 @@ function createGitHubPullRequestSnapshotFetcher(deps = {}) {
249467
249625
  const now2 = deps.now ?? Date.now;
249468
249626
  const random3 = deps.random ?? Math.random;
249469
249627
  const wait = deps.wait ?? (async (ms, signal) => {
249470
- await delay5(ms, undefined, { signal });
249628
+ await delay6(ms, undefined, { signal });
249471
249629
  });
249472
249630
  let hasSnapshot = false;
249473
249631
  let unsupported = false;
@@ -249511,6 +249669,10 @@ function createGitHubPullRequestSnapshotFetcher(deps = {}) {
249511
249669
  continue;
249512
249670
  }
249513
249671
  if (entry?.inaccessible) {
249672
+ if (!hasSnapshot && deps.allowInaccessibleFallback) {
249673
+ unsupported = true;
249674
+ return fetchGh(ref, options);
249675
+ }
249514
249676
  throw new Error(`Cloud could not access ${ref.url}`);
249515
249677
  }
249516
249678
  if (!entry?.snapshot) {
@@ -249810,6 +249972,96 @@ var init_github_workflow_run = __esm(() => {
249810
249972
  init_github_pull_request_cloud();
249811
249973
  });
249812
249974
 
249975
+ // src/tools/impl/watch-pr-cloud.ts
249976
+ async function startCloudPullRequestWatch(args, deps = {}) {
249977
+ const resuming = Boolean(args.resume && isCloudMonitorId(args.resume));
249978
+ if (args.resume && !resuming)
249979
+ return;
249980
+ const enabled = deps.enabled ?? (() => experimentManager.isEnabled("cloud_watch_pr") && isManagedCloudRuntime() && resolveBackendMode() === "api" && isCloudServerUrl());
249981
+ if (!resuming && !enabled())
249982
+ return;
249983
+ if (!resuming && args.url?.includes("/actions/runs/"))
249984
+ return;
249985
+ const scope = resolveNotificationScope(args.parentScope);
249986
+ if (!scope || scope.conversationId === "default")
249987
+ return;
249988
+ const path32 = `/v1/conversations/${encodeURIComponent(scope.conversationId)}/cloud-monitors`;
249989
+ const request4 = deps.request ?? apiRequest;
249990
+ if (resuming) {
249991
+ const record5 = await request4("GET", `${path32}/${encodeURIComponent(args.resume ?? "")}`, undefined, actingUserRequestOptions(scope.actingUserId));
249992
+ if (record5.source.type !== "github_pull_request")
249993
+ throw new Error("Use Monitor for this cloud monitor.");
249994
+ const { owner, repo, number: number6 } = record5.source;
249995
+ return {
249996
+ content: [
249997
+ {
249998
+ type: "text",
249999
+ text: `WatchPR ${record5.id} is ${record5.status}. Cloud watches continue between sessions; start a new watch after it stops.`
250000
+ }
250001
+ ],
250002
+ taskId: record5.id,
250003
+ url: `https://github.com/${owner}/${repo}/pull/${number6}`,
250004
+ headSha: "",
250005
+ persistent: false
250006
+ };
250007
+ }
250008
+ if (typeof args.url !== "string")
250009
+ throw new Error("WatchPR url is required");
250010
+ const ref = parseGitHubPullRequestUrl(args.url);
250011
+ let created;
250012
+ try {
250013
+ created = await request4("POST", path32, {
250014
+ description: `PR ${ref.owner}/${ref.repo}#${ref.number} checks, reviews, and mergeability`,
250015
+ source: {
250016
+ type: "github_pull_request",
250017
+ owner: ref.owner,
250018
+ repo: ref.repo,
250019
+ number: ref.number,
250020
+ ...args.notify_on && { notify_on: args.notify_on }
250021
+ },
250022
+ timeout_ms: getMonitorMaxTimeoutMs(),
250023
+ ...args.toolCallId && { tool_call_id: args.toolCallId }
250024
+ }, actingUserRequestOptions(scope.actingUserId));
250025
+ } catch (error4) {
250026
+ if (error4 instanceof ApiRequestError && error4.status === 400) {
250027
+ let body3 = {};
250028
+ try {
250029
+ body3 = JSON.parse(error4.responseText);
250030
+ } catch {}
250031
+ if (body3.errorCode === "REPOSITORY_INACCESSIBLE" || body3.errorCode === "CLOUD_WATCH_PR_DISABLED")
250032
+ return;
250033
+ }
250034
+ throw error4;
250035
+ }
250036
+ const initial2 = toClientSnapshot(ref, created.initial_snapshot);
250037
+ return {
250038
+ content: [
250039
+ {
250040
+ type: "text",
250041
+ text: `WatchPR started (task ${created.id}). You will be notified on PR events. It stops when the PR merges/closes, on TaskStop, or at its timeout. Keep working — do not poll or sleep.
250042
+
250043
+ Current state:
250044
+ ${describeGitHubPullRequestSnapshot(initial2)}`
250045
+ }
250046
+ ],
250047
+ taskId: created.id,
250048
+ url: ref.url,
250049
+ headSha: initial2.headSha,
250050
+ persistent: false
250051
+ };
250052
+ }
250053
+ var init_watch_pr_cloud = __esm(() => {
250054
+ init_request();
250055
+ init_server_url();
250056
+ init_backend_mode();
250057
+ init_manager();
250058
+ init_task_notifications();
250059
+ init_github_pull_request_cloud();
250060
+ init_github_pull_request_watch();
250061
+ init_monitor_timeout();
250062
+ init_monitor_url_cloud();
250063
+ });
250064
+
249813
250065
  // src/tools/impl/watch-pr.ts
249814
250066
  import { createHash as createHash12, randomUUID as randomUUID48 } from "node:crypto";
249815
250067
  import {
@@ -249820,7 +250072,7 @@ import {
249820
250072
  writeFileSync as writeFileSync33
249821
250073
  } from "node:fs";
249822
250074
  import { dirname as dirname32, join as join74 } from "node:path";
249823
- import { setTimeout as delay6 } from "node:timers/promises";
250075
+ import { setTimeout as delay7 } from "node:timers/promises";
249824
250076
  function errorText(error4) {
249825
250077
  const message2 = error4 instanceof Error ? error4.message : String(error4);
249826
250078
  return scrubSecretsFromString(message2, {}).replace(/\s+/g, " ").trim().slice(0, 500);
@@ -249829,7 +250081,7 @@ function pollDelayMs(failedPolls) {
249829
250081
  return Math.min(WATCH_POLL_MS * 2 ** failedPolls, WATCH_MAX_POLL_MS);
249830
250082
  }
249831
250083
  async function defaultWait(signal, milliseconds) {
249832
- await delay6(milliseconds, undefined, { signal });
250084
+ await delay7(milliseconds, undefined, { signal });
249833
250085
  }
249834
250086
  function saveSnapshot(path32, snapshot2) {
249835
250087
  if (!path32)
@@ -249899,6 +250151,9 @@ ${text2}`;
249899
250151
  }
249900
250152
  }
249901
250153
  async function watch_pr(args, deps = {}) {
250154
+ const cloud = await startCloudPullRequestWatch(args);
250155
+ if (cloud)
250156
+ return cloud;
249902
250157
  const resumeRecord = args.resume ? await readResumableMonitor(args.resume, args.parentScope) : undefined;
249903
250158
  if (resumeRecord) {
249904
250159
  if (resumeRecord.kind !== "github_pull_request")
@@ -249918,7 +250173,9 @@ async function watch_pr(args, deps = {}) {
249918
250173
  const ref = isRun ? parseGitHubWorkflowRunUrl(args.url) : parseGitHubPullRequestUrl(args.url);
249919
250174
  const describe2 = isRun ? describeWorkflowRun : describeGitHubPullRequestSnapshot;
249920
250175
  const cwd2 = getCurrentWorkingDirectory();
249921
- const fetchSnapshot = deps.fetchSnapshot ?? (isRun ? createGitHubWorkflowRunFetcher() : createGitHubPullRequestSnapshotFetcher());
250176
+ const fetchSnapshot = deps.fetchSnapshot ?? (isRun ? createGitHubWorkflowRunFetcher() : createGitHubPullRequestSnapshotFetcher({
250177
+ allowInaccessibleFallback: experimentManager.isEnabled("cloud_watch_pr") && isManagedCloudRuntime()
250178
+ }));
249922
250179
  const runtimeContext = getRuntimeContext();
249923
250180
  const parentScope = args.parentScope ?? (runtimeContext?.agentId ? {
249924
250181
  agentId: runtimeContext.agentId,
@@ -250074,8 +250331,6 @@ ${event}
250074
250331
  let freshnessNoticeSent = false;
250075
250332
  let nextPollMs = WATCH_POLL_MS;
250076
250333
  let failedPolls = 0;
250077
- let failureStartedAt;
250078
- let lastNotifiedError;
250079
250334
  while (processState.status === "running") {
250080
250335
  try {
250081
250336
  await wait(controller.signal, nextPollMs);
@@ -250093,14 +250348,7 @@ ${event}
250093
250348
  freshnessNoticeSent = false;
250094
250349
  }
250095
250350
  nextPollMs = WATCH_POLL_MS;
250096
- if (lastNotifiedError !== undefined) {
250097
- emit([
250098
- `WatchPR recovered after ${failedPolls} failed poll${failedPolls === 1 ? "" : "s"}.`
250099
- ]);
250100
- }
250101
250351
  failedPolls = 0;
250102
- failureStartedAt = undefined;
250103
- lastNotifiedError = undefined;
250104
250352
  const sameHead = current.headSha === previous.headSha;
250105
250353
  const stableCurrent = { ...current, readinessConfirmed: false };
250106
250354
  stableCurrent.readinessConfirmed = Boolean(sameHead && hasGitHubPullRequestReadyConditions(previous) && hasGitHubPullRequestReadyConditions(stableCurrent));
@@ -250141,7 +250389,6 @@ ${event}
250141
250389
  }
250142
250390
  failedPolls += 1;
250143
250391
  nextPollMs = pollDelayMs(failedPolls);
250144
- failureStartedAt ??= now2();
250145
250392
  const message2 = errorText(error4);
250146
250393
  if (!output.append(`[poll error ${failedPolls}] ${message2}
250147
250394
  `)) {
@@ -250150,12 +250397,6 @@ ${event}
250150
250397
  controller.abort();
250151
250398
  return;
250152
250399
  }
250153
- if (now2() - failureStartedAt >= WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS && message2 !== lastNotifiedError) {
250154
- emit([
250155
- `WatchPR could not refresh ${ref.url}: ${message2}. Retrying.`
250156
- ]);
250157
- lastNotifiedError = message2;
250158
- }
250159
250400
  }
250160
250401
  }
250161
250402
  })().catch((error4) => {
@@ -250192,9 +250433,10 @@ Output file: ${outputFile}`
250192
250433
  };
250193
250434
  });
250194
250435
  }
250195
- var WATCH_POLL_MS = 30000, WATCH_MAX_POLL_MS, WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS, WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS;
250436
+ var WATCH_POLL_MS = 30000, WATCH_MAX_POLL_MS, WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS;
250196
250437
  var init_watch_pr = __esm(() => {
250197
250438
  init_monitors();
250439
+ init_manager();
250198
250440
  init_runtime_context();
250199
250441
  init_secret_substitution();
250200
250442
  init_settings_path();
@@ -250209,8 +250451,8 @@ var init_watch_pr = __esm(() => {
250209
250451
  init_monitor_state();
250210
250452
  init_monitor_timeout();
250211
250453
  init_process_manager();
250454
+ init_watch_pr_cloud();
250212
250455
  WATCH_MAX_POLL_MS = 5 * 60000;
250213
- WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS = 5 * 60000;
250214
250456
  WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS = 30 * 60000;
250215
250457
  });
250216
250458
 
@@ -258075,11 +258317,11 @@ function scheduleDurableQueueRestore(listener, capacityReleased = true) {
258075
258317
  clearDurableQueueRestoreRetry(listener);
258076
258318
  return;
258077
258319
  }
258078
- const delay7 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
258320
+ const delay8 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
258079
258321
  listener.durableQueueRestoreTimer = setTimeout(() => {
258080
258322
  listener.durableQueueRestoreTimer = undefined;
258081
258323
  scheduleDurableQueueRestore(listener, false);
258082
- }, delay7);
258324
+ }, delay8);
258083
258325
  listener.durableQueueRestoreTimer.unref?.();
258084
258326
  } finally {
258085
258327
  listener.durableQueueRestoreScheduled = false;
@@ -264896,7 +265138,7 @@ async function acquireRecoveryClaim(runtime, onLost = () => {}, dependencies = {
264896
265138
  }
264897
265139
  return null;
264898
265140
  }
264899
- const claim = new RecoveryClaim(runtime, runtime.agentId, runtime.conversationId, connectionId, connectionGeneration, response.token, response.fence, request4, dependencies.schedule ?? ((callback, delay7) => setTimeout(callback, delay7)), dependencies.cancel ?? ((timer) => clearTimeout(timer)), onLost, now2, requestedAt + RECOVERY_CLAIM_TTL_MS - RECOVERY_CLAIM_EXPIRY_MARGIN_MS);
265141
+ const claim = new RecoveryClaim(runtime, runtime.agentId, runtime.conversationId, connectionId, connectionGeneration, response.token, response.fence, request4, dependencies.schedule ?? ((callback, delay8) => setTimeout(callback, delay8)), dependencies.cancel ?? ((timer) => clearTimeout(timer)), onLost, now2, requestedAt + RECOVERY_CLAIM_TTL_MS - RECOVERY_CLAIM_EXPIRY_MARGIN_MS);
264900
265142
  runtime.listener.activeRecoveryClaims ??= new Set;
264901
265143
  runtime.listener.activeRecoveryClaims.add(claim);
264902
265144
  refusalCounts.delete(runtime.listener);
@@ -427784,12 +428026,12 @@ ${options.prefix}` : `
427784
428026
  this.pendingTimeouts = /* @__PURE__ */ new Map;
427785
428027
  this.logger = logger.hasLevel(3) ? logger : undefined;
427786
428028
  }
427787
- schedule(operationId, delay7, cb) {
428029
+ schedule(operationId, delay8, cb) {
427788
428030
  const pendingTimeout = this.pendingTimeouts.get(operationId);
427789
428031
  if (pendingTimeout) {
427790
428032
  this.host.clearTimeout(pendingTimeout);
427791
428033
  }
427792
- this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay7, operationId, this, cb));
428034
+ this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay8, operationId, this, cb));
427793
428035
  if (this.logger) {
427794
428036
  this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`);
427795
428037
  }
@@ -427810,9 +428052,9 @@ ${options.prefix}` : `
427810
428052
  }
427811
428053
  };
427812
428054
  var GcTimer = class _GcTimer {
427813
- constructor(host, delay7, logger) {
428055
+ constructor(host, delay8, logger) {
427814
428056
  this.host = host;
427815
- this.delay = delay7;
428057
+ this.delay = delay8;
427816
428058
  this.logger = logger;
427817
428059
  }
427818
428060
  scheduleCollect() {
@@ -435852,12 +436094,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
435852
436094
  const project = this.projectService.tryGetDefaultProjectForFile(fileName);
435853
436095
  return project && { fileName, project };
435854
436096
  }
435855
- getDiagnostics(next, delay7, fileArgs) {
436097
+ getDiagnostics(next, delay8, fileArgs) {
435856
436098
  if (this.suppressDiagnosticEvents) {
435857
436099
  return;
435858
436100
  }
435859
436101
  if (fileArgs.length > 0) {
435860
- this.updateErrorCheck(next, fileArgs, delay7);
436102
+ this.updateErrorCheck(next, fileArgs, delay8);
435861
436103
  }
435862
436104
  }
435863
436105
  change(args) {
@@ -436219,7 +436461,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
436219
436461
  const spans = languageService.getBraceMatchingAtPosition(file, position);
436220
436462
  return !spans ? undefined : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans;
436221
436463
  }
436222
- getDiagnosticsForProject(next, delay7, fileName) {
436464
+ getDiagnosticsForProject(next, delay8, fileName) {
436223
436465
  if (this.suppressDiagnosticEvents) {
436224
436466
  return;
436225
436467
  }
@@ -436253,7 +436495,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
436253
436495
  }
436254
436496
  const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles];
436255
436497
  const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project }));
436256
- this.updateErrorCheck(next, checkList, delay7, false);
436498
+ this.updateErrorCheck(next, checkList, delay8, false);
436257
436499
  }
436258
436500
  configurePlugin(args) {
436259
436501
  this.projectService.configurePlugin(args);
@@ -440559,7 +440801,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
440559
440801
  retryStates.delete(runtime);
440560
440802
  return;
440561
440803
  }
440562
- const delay7 = retryDelay(state2.attempt);
440804
+ const delay8 = retryDelay(state2.attempt);
440563
440805
  state2.attempt += 1;
440564
440806
  state2.scheduled = true;
440565
440807
  state2.timer = setTimeout(() => {
@@ -440568,7 +440810,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
440568
440810
  state2.timer = undefined;
440569
440811
  state2.scheduled = false;
440570
440812
  scheduleRecoveredApprovalRetry(runtime, state2.retry);
440571
- }, delay7);
440813
+ }, delay8);
440572
440814
  state2.timer.unref?.();
440573
440815
  };
440574
440816
  state2.retry().then((handled) => {
@@ -453835,10 +454077,10 @@ async function registerWithCloudRetry(opts, callbacks) {
453835
454077
  }
453836
454078
  attempt2++;
453837
454079
  const backoffDelay = Math.min(REGISTER_INITIAL_DELAY_MS * 2 ** (attempt2 - 1), REGISTER_MAX_DELAY_MS);
453838
- const delay7 = error4 instanceof RegistrationError && error4.retryAfterMs !== undefined ? Math.max(error4.retryAfterMs, backoffDelay) : backoffDelay;
453839
- const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay7 * REGISTER_JITTER_RATIO));
454080
+ const delay8 = error4 instanceof RegistrationError && error4.retryAfterMs !== undefined ? Math.max(error4.retryAfterMs, backoffDelay) : backoffDelay;
454081
+ const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay8 * REGISTER_JITTER_RATIO));
453840
454082
  const jitter2 = jitterWindow > 0 ? Math.floor((callbacks?.random ?? Math.random)() * jitterWindow) : 0;
453841
- const retryDelay2 = delay7 + jitter2;
454083
+ const retryDelay2 = delay8 + jitter2;
453842
454084
  if (error4 instanceof Error) {
453843
454085
  callbacks?.onRetry?.(attempt2, retryDelay2, error4);
453844
454086
  }
@@ -460692,7 +460934,7 @@ function applyCatalogModels(next, options = {}) {
460692
460934
  }
460693
460935
  if (options.requireManagedDefault !== false) {
460694
460936
  const defaults6 = next.filter((model2) => model2.isDefault || model2.id === "auto");
460695
- if (defaults6.length !== 1) {
460937
+ if (defaults6.length === 0) {
460696
460938
  return false;
460697
460939
  }
460698
460940
  }
@@ -463131,6 +463373,7 @@ async function stopMonitor(command) {
463131
463373
  actingUserId: command.runtime.acting_user_id,
463132
463374
  text: formatMonitorEventNotification({
463133
463375
  taskId: command.process_id,
463376
+ description: process21.description,
463134
463377
  event: "The user cancelled this Monitor. Do not restart it unless the user asks."
463135
463378
  })
463136
463379
  });
@@ -463347,12 +463590,19 @@ async function handleSubagentMessageCommand(command, parent, deps = {}) {
463347
463590
  }
463348
463591
  })();
463349
463592
  responses.set(key4, {
463350
- expiresAt: now2 + DEDUPE_TTL_MS,
463593
+ expiresAt: now2 + REMOTE_SUBAGENT_MESSAGE_DEDUPE_PENDING_TTL_MS,
463351
463594
  response
463352
463595
  });
463353
463596
  const result3 = await response;
463354
- if (!result3.success && responses.get(key4)?.response === response)
463355
- responses.delete(key4);
463597
+ if (responses.get(key4)?.response === response) {
463598
+ if (!result3.success)
463599
+ responses.delete(key4);
463600
+ else
463601
+ responses.set(key4, {
463602
+ expiresAt: (deps.now ?? Date.now)() + DEDUPE_TTL_MS,
463603
+ response
463604
+ });
463605
+ }
463356
463606
  return result3;
463357
463607
  }
463358
463608
  async function handleSubagentStopCommand(command, parent) {
@@ -463412,6 +463662,7 @@ var DEDUPE_TTL_MS = 30000, responses;
463412
463662
  var init_subagent_control = __esm(() => {
463413
463663
  init_subagent_state();
463414
463664
  init_runtime_context();
463665
+ init_claude_steer_timeouts();
463415
463666
  init_claude_stream_session();
463416
463667
  init_codex_app_server();
463417
463668
  init_cursor_session();
@@ -463527,6 +463778,7 @@ var exports_task_control = {};
463527
463778
  __export(exports_task_control, {
463528
463779
  handleTaskControlCommand: () => handleTaskControlCommand
463529
463780
  });
463781
+ import WebSocket12 from "ws";
463530
463782
  async function handleTaskControlCommand(command, context3) {
463531
463783
  const {
463532
463784
  runtime,
@@ -463536,12 +463788,17 @@ async function handleTaskControlCommand(command, context3) {
463536
463788
  runDetachedListenerTask: runDetachedListenerTask2,
463537
463789
  safeSocketSend
463538
463790
  } = context3;
463791
+ const arrivedOnRelay = connectionId !== undefined && connectionId === runtime.connectionId;
463792
+ const sendReply = (response) => {
463793
+ const replySocket = socket.readyState !== WebSocket12.OPEN && arrivedOnRelay && runtime.socket?.readyState === WebSocket12.OPEN ? runtime.socket : socket;
463794
+ safeSocketSend(replySocket, response, response.type, command.type);
463795
+ };
463539
463796
  const execute = async () => {
463540
463797
  if (command.type === "subagent_stop" && command.conversation) {
463541
463798
  const response2 = await stopListenerConversation(command, context3.abortConversation ?? (async () => {
463542
463799
  throw new Error("Listener cancellation is unavailable");
463543
463800
  }));
463544
- safeSocketSend(socket, response2, response2.type, command.type);
463801
+ sendReply(response2);
463545
463802
  return;
463546
463803
  }
463547
463804
  if (command.type === "monitor_stop") {
@@ -463556,7 +463813,7 @@ async function handleTaskControlCommand(command, context3) {
463556
463813
  }
463557
463814
  const parent = getOrCreateScopedRuntime2(runtime, command.runtime.agent_id, command.runtime.conversation_id);
463558
463815
  const response = command.type === "launch_subagent" ? await handleLaunchSubagentCommand(command, parent, connectionId) : command.type === "subagent_message" ? await handleSubagentMessageCommand(command, parent) : await handleSubagentStopCommand(command, parent);
463559
- safeSocketSend(socket, response, response.type, command.type);
463816
+ sendReply(response);
463560
463817
  };
463561
463818
  if (command.type === "launch_subagent" || command.type === "subagent_message") {
463562
463819
  runDetachedListenerTask2(command.type, execute);
@@ -465034,9 +465291,9 @@ var init_restored_queue_pump = __esm(() => {
465034
465291
  });
465035
465292
 
465036
465293
  // src/websocket/listener/socket-send.ts
465037
- import WebSocket12 from "ws";
465294
+ import WebSocket13 from "ws";
465038
465295
  function safeSocketSend(socket, payload, errorType, context3) {
465039
- if (socket.readyState !== WebSocket12.OPEN)
465296
+ if (socket.readyState !== WebSocket13.OPEN)
465040
465297
  return false;
465041
465298
  try {
465042
465299
  const serialized = typeof payload === "string" ? payload : JSON.stringify(payload);
@@ -465331,7 +465588,7 @@ var init_sync_replay = __esm(() => {
465331
465588
  });
465332
465589
 
465333
465590
  // src/websocket/listener/lifecycle.ts
465334
- import WebSocket13 from "ws";
465591
+ import WebSocket14 from "ws";
465335
465592
  function createRuntime() {
465336
465593
  const bootWorkingDirectory = getCurrentWorkingDirectory();
465337
465594
  return {
@@ -465601,7 +465858,7 @@ async function attachOpenListenerSocket(runtime, socket, opts, options = {}) {
465601
465858
  abortStartupIngress();
465602
465859
  return;
465603
465860
  }
465604
- const streamTransport = streamSocket?.readyState === WebSocket13.OPEN ? streamSocket : null;
465861
+ const streamTransport = streamSocket?.readyState === WebSocket14.OPEN ? streamSocket : null;
465605
465862
  await startConnectedListenerRuntime(runtime, transport3, opts, processQueuedTurn, {
465606
465863
  startHeartbeat: options.startHeartbeat ?? false,
465607
465864
  startCronScheduler: options.startCronScheduler ?? true,
@@ -465686,10 +465943,10 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
465686
465943
  opts.onError(new Error("Failed to connect after 5 minutes of retrying"));
465687
465944
  return;
465688
465945
  }
465689
- const delay7 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
465690
- opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay7, opts.connectionId);
465946
+ const delay8 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
465947
+ opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay8, opts.connectionId);
465691
465948
  await new Promise((resolve39) => {
465692
- runtime.reconnectTimeout = setTimeout(resolve39, delay7);
465949
+ runtime.reconnectTimeout = setTimeout(resolve39, delay8);
465693
465950
  });
465694
465951
  runtime.reconnectTimeout = null;
465695
465952
  if (runtime !== getActiveRuntime() || runtime.intentionallyClosed) {
@@ -465872,7 +466129,7 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
465872
466129
  streamSocket.removeAllListeners("message");
465873
466130
  streamSocket.removeAllListeners("open");
465874
466131
  streamSocket.removeAllListeners("close");
465875
- if (streamSocket.readyState === WebSocket13.OPEN || streamSocket.readyState === WebSocket13.CONNECTING) {
466132
+ if (streamSocket.readyState === WebSocket14.OPEN || streamSocket.readyState === WebSocket14.CONNECTING) {
465876
466133
  streamSocket.close();
465877
466134
  }
465878
466135
  }
@@ -466997,7 +467254,7 @@ __export(exports_app_server, {
466997
467254
  });
466998
467255
  import { createServer as createServer7 } from "node:http";
466999
467256
  import { hostname as hostname4 } from "node:os";
467000
- import WebSocket14, { WebSocketServer } from "ws";
467257
+ import WebSocket15, { WebSocketServer } from "ws";
467001
467258
  function getRequiredAddressInfo(server2) {
467002
467259
  const address = server2.address();
467003
467260
  if (!address || typeof address === "string") {
@@ -467013,12 +467270,12 @@ function getWebSocketUrl(baseUrl, path46) {
467013
467270
  function closeSocket(socket, code = 1001, reason = "closing") {
467014
467271
  if (!socket)
467015
467272
  return;
467016
- if (socket.readyState === WebSocket14.OPEN || socket.readyState === WebSocket14.CONNECTING) {
467273
+ if (socket.readyState === WebSocket15.OPEN || socket.readyState === WebSocket15.CONNECTING) {
467017
467274
  socket.close(code, reason);
467018
467275
  }
467019
467276
  }
467020
467277
  function terminateSocket(socket) {
467021
- if (!socket || socket.readyState === WebSocket14.CLOSED)
467278
+ if (!socket || socket.readyState === WebSocket15.CLOSED)
467022
467279
  return;
467023
467280
  socket.terminate();
467024
467281
  }
@@ -467205,7 +467462,7 @@ async function startAppServer(options = {}) {
467205
467462
  client.terminate();
467206
467463
  continue;
467207
467464
  }
467208
- if (client.readyState === WebSocket14.OPEN) {
467465
+ if (client.readyState === WebSocket15.OPEN) {
467209
467466
  const sentAt = Date.now();
467210
467467
  client.ping();
467211
467468
  watchdog?.recordPing(sentAt);
@@ -477969,7 +478226,7 @@ async function runUsageSubcommand(argv) {
477969
478226
  console.log(`Usage:
477970
478227
  letta usage
477971
478228
 
477972
- Show a Markdown overview of your plan, credit balance, and letta/* model quota.
478229
+ Show a Markdown overview of your plan and remaining credit balance.
477973
478230
  Local backend: model usage requires BYOK.
477974
478231
 
477975
478232
  Options:
@@ -477983,20 +478240,12 @@ Options:
477983
478240
  await settingsManager.initialize();
477984
478241
  await getClient();
477985
478242
  await settingsManager.flush();
477986
- const [balance, quota] = await Promise.all([
477987
- getBalanceMetadata(),
477988
- getModelQuotaMetadata()
477989
- ]);
478243
+ const balance = await getBalanceMetadata();
477990
478244
  const usage = `# Letta usage overview
477991
478245
  Current plan: ${balance.billing_tier}
477992
478246
 
477993
478247
  ## Usage Credits (non-BYOK models)
477994
478248
  * Balance: ${balance.total_balance} credits
477995
-
477996
- ## Usage Quota (\`letta/*\` models)
477997
- * Bucket (full/high/medium/low/empty): ${quota.lettaTier.bucket} (daily: ${quota.lettaTier.dailyBucket ?? "Unavailable"})
477998
- * Quota Window End: ${quota.quotaWindowEnd}
477999
- * Daily Quota Window End: ${quota.dailyQuotaWindowEnd ?? "Unavailable"}
478000
478249
  `;
478001
478250
  await new Promise((resolve42, reject2) => {
478002
478251
  process.stdout.write(usage, (error4) => error4 ? reject2(error4) : resolve42());
@@ -482264,7 +482513,7 @@ async function handleChannelsSlashCommand(runtime, args) {
482264
482513
 
482265
482514
  // src/channels/gateway-local.ts
482266
482515
  import { createHash as createHash23 } from "node:crypto";
482267
- import WebSocket15 from "ws";
482516
+ import WebSocket16 from "ws";
482268
482517
  async function executeChannelServiceCommand(command) {
482269
482518
  if (!isDetachedChannelsCommand(command)) {
482270
482519
  throw new Error(`Unsupported ChannelGateway command: ${command.type}`);
@@ -482335,7 +482584,7 @@ async function startLocalChannelGateway(options) {
482335
482584
  await settingsManager.initialize();
482336
482585
  const client = createAppServerClient({
482337
482586
  url: options.appServerUrl,
482338
- WebSocket: WebSocket15
482587
+ WebSocket: WebSocket16
482339
482588
  });
482340
482589
  await client.connect();
482341
482590
  let serverInfo;
@@ -530852,9 +531101,9 @@ function App2({
530852
531101
  }
530853
531102
  const elapsedSinceClear = Date.now() - lastClearAtRef.current;
530854
531103
  const rateLimitDelay = elapsedSinceClear >= MIN_CLEAR_INTERVAL_MS ? 0 : MIN_CLEAR_INTERVAL_MS - elapsedSinceClear;
530855
- const delay7 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
531104
+ const delay8 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
530856
531105
  if (debugFlicker) {
530857
- console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay7}ms elapsedSinceClear=${elapsedSinceClear}ms`);
531106
+ console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay8}ms elapsedSinceClear=${elapsedSinceClear}ms`);
530858
531107
  }
530859
531108
  resizeClearTimeout.current = setTimeout(() => {
530860
531109
  resizeClearTimeout.current = null;
@@ -530874,7 +531123,7 @@ function App2({
530874
531123
  console.error(`[debug:flicker:resize-fire] clear target=${targetColumns}`);
530875
531124
  }
530876
531125
  clearAndRemount(targetColumns);
530877
- }, delay7);
531126
+ }, delay8);
530878
531127
  }, [clearAndRemount, debugFlicker]);
530879
531128
  import_react124.useEffect(() => {
530880
531129
  const prev = prevColumnsRef.current;
@@ -531380,11 +531629,11 @@ function App2({
531380
531629
  import_react124.useEffect(() => {
531381
531630
  if (deferredCommitAt === null)
531382
531631
  return;
531383
- const delay7 = Math.max(0, deferredCommitAt - Date.now());
531632
+ const delay8 = Math.max(0, deferredCommitAt - Date.now());
531384
531633
  const timer = setTimeout(() => {
531385
531634
  setDeferredCommitAt(null);
531386
531635
  refreshDerived();
531387
- }, delay7);
531636
+ }, delay8);
531388
531637
  return () => clearTimeout(timer);
531389
531638
  }, [deferredCommitAt, refreshDerived]);
531390
531639
  const streamingRefreshTimeoutRef = import_react124.useRef(null);
@@ -533382,7 +533631,7 @@ USAGE
533382
533631
  letta memory ... Memory filesystem subcommands
533383
533632
  letta agents ... Agents subcommands (JSON-only)
533384
533633
  letta model ... Get, list, or set models and reasoning (JSON-only)
533385
- letta usage Show account credits and Letta quota (Markdown)
533634
+ letta usage Show account plan and remaining credits (Markdown)
533386
533635
  letta computers ... List available remote computers (JSON-only)
533387
533636
  letta teleport ... Move the current conversation between computers
533388
533637
  letta messages ... Messages subcommands (JSON-only)
@@ -537329,4 +537578,4 @@ function registerBunOAuthFlows() {
537329
537578
  registerBunOAuthFlows();
537330
537579
  await init_src5().then(() => exports_src2);
537331
537580
 
537332
- //# debugId=17512937B3B5F6D064756E2164756E21
537581
+ //# debugId=070ABAF64C8E926164756E2164756E21