@letta-ai/letta-code 0.34.62 → 0.34.64

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 (61) hide show
  1. package/dist/channels-public.js +2 -1
  2. package/dist/channels-public.js.map +3 -3
  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/agent/subagents/remote-turn-wait.d.ts.map +1 -1
  8. package/dist/types/backend/api/agent-message.d.ts +2 -0
  9. package/dist/types/backend/api/agent-message.d.ts.map +1 -1
  10. package/dist/types/backend/api/metadata.d.ts +0 -12
  11. package/dist/types/backend/api/metadata.d.ts.map +1 -1
  12. package/dist/types/backend/api/unified-mcp.d.ts.map +1 -1
  13. package/dist/types/backend/local/local-backend.d.ts.map +1 -1
  14. package/dist/types/backend/local/local-message-list-options.d.ts +7 -0
  15. package/dist/types/backend/local/local-message-list-options.d.ts.map +1 -0
  16. package/dist/types/backend/local/local-store.d.ts +2 -0
  17. package/dist/types/backend/local/local-store.d.ts.map +1 -1
  18. package/dist/types/backend/local/local-transcript-history.d.ts +8 -0
  19. package/dist/types/backend/local/local-transcript-history.d.ts.map +1 -1
  20. package/dist/types/backend/local/local-transcript.d.ts +1 -0
  21. package/dist/types/backend/local/local-transcript.d.ts.map +1 -1
  22. package/dist/types/backend/local/system-prompt-compilation.d.ts +2 -1
  23. package/dist/types/backend/local/system-prompt-compilation.d.ts.map +1 -1
  24. package/dist/types/channels/xml.d.ts +5 -0
  25. package/dist/types/channels/xml.d.ts.map +1 -1
  26. package/dist/types/channels-public.d.ts +1 -0
  27. package/dist/types/channels-public.d.ts.map +1 -1
  28. package/dist/types/queue/queue-runtime.d.ts +1 -1
  29. package/dist/types/queue/queue-runtime.d.ts.map +1 -1
  30. package/dist/types/queue/turn-queue-runtime.d.ts +4 -0
  31. package/dist/types/queue/turn-queue-runtime.d.ts.map +1 -1
  32. package/dist/types/reminders/engine.d.ts +3 -3
  33. package/dist/types/reminders/engine.d.ts.map +1 -1
  34. package/dist/types/tools/external-tool-background.d.ts.map +1 -1
  35. package/dist/types/tools/impl/claude-steer-timeouts.d.ts +5 -0
  36. package/dist/types/tools/impl/claude-steer-timeouts.d.ts.map +1 -1
  37. package/dist/types/tools/impl/external-coding-agent.d.ts +1 -1
  38. package/dist/types/tools/impl/external-coding-agent.d.ts.map +1 -1
  39. package/dist/types/tools/impl/external-fork-context.d.ts +6 -0
  40. package/dist/types/tools/impl/external-fork-context.d.ts.map +1 -1
  41. package/dist/types/tools/impl/monitor-script.d.ts +1 -0
  42. package/dist/types/tools/impl/monitor-script.d.ts.map +1 -1
  43. package/dist/types/tools/impl/monitor.d.ts +1 -0
  44. package/dist/types/tools/impl/monitor.d.ts.map +1 -1
  45. package/dist/types/tools/impl/remote-connect-retry.d.ts +4 -0
  46. package/dist/types/tools/impl/remote-connect-retry.d.ts.map +1 -0
  47. package/dist/types/tools/impl/remote-external-coding-agent.d.ts.map +1 -1
  48. package/dist/types/tools/impl/remote-follow-up-retry.d.ts +9 -0
  49. package/dist/types/tools/impl/remote-follow-up-retry.d.ts.map +1 -0
  50. package/dist/types/tools/impl/task.d.ts.map +1 -1
  51. package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
  52. package/dist/types/utils/message-queue-bridge.d.ts +1 -1
  53. package/dist/types/utils/message-queue-bridge.d.ts.map +1 -1
  54. package/dist/types/utils/task-notifications.d.ts +6 -0
  55. package/dist/types/utils/task-notifications.d.ts.map +1 -1
  56. package/letta.js +376 -253
  57. package/npm-shrinkwrap.json +18 -14
  58. package/package.json +2 -2
  59. package/scripts/source-file-size-baseline.json +2 -2
  60. package/skills/image-generation/SKILL.md +2 -0
  61. 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.62",
6142
+ version: "0.34.64",
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();
@@ -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
  });
@@ -164889,10 +164901,25 @@ function formatTaskNotification(notification) {
164889
164901
  </task-notification>${notification.outputFile ? `
164890
164902
  Full transcript available at: ${notification.outputFile}` : ""}`;
164891
164903
  }
164904
+ function subagentResultReminder() {
164905
+ const reminder = process.env.LETTA_SUBAGENT_RESULT_REMINDER;
164906
+ return reminder ? `
164907
+
164908
+ <system-reminder>
164909
+ ${reminder}
164910
+ </system-reminder>` : "";
164911
+ }
164912
+ function taskNotificationMessage(text2) {
164913
+ const parts = text2.split(/(?<=<\/task-notification>)\n(?=Full transcript available at:)/).map((part) => ({ type: "text", text: part }));
164914
+ const reminder = subagentResultReminder();
164915
+ if (reminder)
164916
+ parts.push({ type: "text", text: reminder.trimStart() });
164917
+ return { text: text2, content: parts };
164918
+ }
164892
164919
  function formatMonitorEventNotification(notification) {
164893
164920
  return `<task-notification>
164894
164921
  <task-id>${escapeXml(notification.taskId)}</task-id>
164895
- <summary>${escapeXml(`Monitor event: "${notification.event}"`)}</summary>
164922
+ <summary>${escapeXml(notification.description?.trim() ? `Monitor: ${notification.description}` : "Monitor event")}</summary>
164896
164923
  <result>
164897
164924
  <event>${escapeXml(notification.event)}</event>
164898
164925
  </result>
@@ -203342,7 +203369,7 @@ var init_mcp_client = __esm(() => {
203342
203369
  init_streamableHttp();
203343
203370
  DEFAULT_CLIENT_INFO = {
203344
203371
  name: "letta-code",
203345
- version: "0.34.62"
203372
+ version: "0.34.64"
203346
203373
  };
203347
203374
  });
203348
203375
 
@@ -216520,6 +216547,74 @@ var init_tool_registry = __esm(() => {
216520
216547
  MOD_TOOLS_KEY = Symbol.for("@letta/modTools");
216521
216548
  });
216522
216549
 
216550
+ // src/queue/turn-queue-runtime.ts
216551
+ function stringifyUnexpectedContent(content) {
216552
+ try {
216553
+ return JSON.stringify(content) ?? String(content);
216554
+ } catch {
216555
+ return String(content);
216556
+ }
216557
+ }
216558
+ function appendContentParts(target, content) {
216559
+ if (typeof content === "string") {
216560
+ target.push({ type: "text", text: content });
216561
+ return;
216562
+ }
216563
+ if (!Array.isArray(content)) {
216564
+ if (content === null || content === undefined)
216565
+ return;
216566
+ target.push({ type: "text", text: stringifyUnexpectedContent(content) });
216567
+ return;
216568
+ }
216569
+ target.push(...content);
216570
+ }
216571
+ function escapeResultText(text2) {
216572
+ return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
216573
+ }
216574
+ function buildTaskNotificationContent(item) {
216575
+ return item.content ?? item.text;
216576
+ }
216577
+ function buildExternalToolNotificationContent(item) {
216578
+ if (item.content === undefined)
216579
+ return item.text;
216580
+ const parts = [
216581
+ { type: "text", text: item.text },
216582
+ { type: "text", text: `
216583
+ <external-tool-result>` }
216584
+ ];
216585
+ const content = typeof item.content === "string" ? [{ type: "text", text: item.content }] : item.content;
216586
+ for (const part of content) {
216587
+ parts.push(part.type === "text" ? { type: "text", text: `<text>${escapeResultText(part.text)}</text>` } : part);
216588
+ }
216589
+ parts.push({ type: "text", text: "</external-tool-result>" });
216590
+ return parts;
216591
+ }
216592
+ function mergeQueuedTurnInput(queued, options) {
216593
+ if (queued.length === 0) {
216594
+ return null;
216595
+ }
216596
+ const separatorText = options.separatorText ?? `
216597
+ `;
216598
+ const mergedParts = [];
216599
+ let isFirst = true;
216600
+ for (const item of queued) {
216601
+ if (!isFirst) {
216602
+ mergedParts.push({ type: "text", text: separatorText });
216603
+ }
216604
+ isFirst = false;
216605
+ if (item.kind === "task_notification") {
216606
+ appendContentParts(mergedParts, buildTaskNotificationContent(item));
216607
+ continue;
216608
+ }
216609
+ if (item.kind === "cron_prompt") {
216610
+ mergedParts.push({ type: "text", text: item.text });
216611
+ continue;
216612
+ }
216613
+ appendContentParts(mergedParts, options.normalizeUserContent(item.content));
216614
+ }
216615
+ return mergedParts.length > 0 ? mergedParts : null;
216616
+ }
216617
+
216523
216618
  // src/tools/external-tool-background.ts
216524
216619
  function interruptedExternalToolResult(toolName2) {
216525
216620
  return {
@@ -216653,16 +216748,22 @@ async function autoBackgroundExternalTool(toolName2, tool, operation, options) {
216653
216748
  if (entry.completionNotificationSuppressed || await options?.shouldEnqueue?.() === false)
216654
216749
  return;
216655
216750
  const content = truncateByChars(raw2, LIMITS.TOOL_RETURN_MAX_CHARS + 1000, toolName2);
216751
+ const text2 = formatTaskNotification({
216752
+ taskId,
216753
+ status,
216754
+ summary: `${label} ${toolName2} ${status}`,
216755
+ result: content.content,
216756
+ usage: { durationMs: Date.now() - startedAt }
216757
+ });
216656
216758
  enqueue({
216657
216759
  kind: "task_notification",
216658
- text: formatTaskNotification({
216659
- taskId,
216660
- status,
216661
- summary: `${label} ${toolName2} ${status}`,
216662
- result: content.content,
216663
- usage: { durationMs: Date.now() - startedAt }
216664
- }),
216665
- ...richContent ? { content: richContent } : {},
216760
+ text: text2,
216761
+ ...richContent ? {
216762
+ content: buildExternalToolNotificationContent({
216763
+ text: text2,
216764
+ content: richContent
216765
+ })
216766
+ } : {},
216666
216767
  ...scope
216667
216768
  });
216668
216769
  });
@@ -226015,13 +226116,13 @@ function parseSearchResult(value) {
226015
226116
  }
226016
226117
  return { toolId, jsonSchema, score };
226017
226118
  }
226018
- async function withTimeout2(promise2, timeoutMs, operation) {
226119
+ async function withTimeout2(promise2, timeoutMs, operation, timeoutMessage) {
226019
226120
  let timer;
226020
226121
  try {
226021
226122
  return await Promise.race([
226022
226123
  promise2,
226023
226124
  new Promise((_resolve, reject2) => {
226024
- timer = setTimeout(() => reject2(new Error(`${operation} timed out after ${timeoutMs}ms`)), timeoutMs);
226125
+ timer = setTimeout(() => reject2(new Error(timeoutMessage ?? `${operation} timed out after ${timeoutMs}ms`)), timeoutMs);
226025
226126
  })
226026
226127
  ]);
226027
226128
  } finally {
@@ -226087,7 +226188,7 @@ async function runUnifiedMcpTool(params) {
226087
226188
  [MCP_ORIGINATOR_ISOLATION_HEADER3]: "1"
226088
226189
  }
226089
226190
  } : {}
226090
- }), params.timeoutMs ?? 60000, "Running agent MCP tool");
226191
+ }), 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.`);
226091
226192
  return parseRunResult(value);
226092
226193
  }
226093
226194
  var MCP_ORIGINATOR_TOKEN_HEADER3 = "x-letta-mcp-originator-token", MCP_ORIGINATOR_ISOLATION_HEADER3 = "x-letta-mcp-originator-isolation";
@@ -234648,7 +234749,14 @@ async function startScriptMonitor(args, hooks) {
234648
234749
  };
234649
234750
  const events = createMonitorEventStream({
234650
234751
  emit(event) {
234651
- hooks.queueEvent({ taskId, event, scope, actingUserId, secrets: secrets2 });
234752
+ hooks.queueEvent({
234753
+ taskId,
234754
+ description: args.description,
234755
+ event,
234756
+ scope,
234757
+ actingUserId,
234758
+ secrets: secrets2
234759
+ });
234652
234760
  },
234653
234761
  stopSource() {
234654
234762
  stop2("output rate too high", `
@@ -234761,6 +234869,7 @@ async function startScriptMonitor(args, hooks) {
234761
234869
  events.finish();
234762
234870
  hooks.queueEvent({
234763
234871
  taskId,
234872
+ description: args.description,
234764
234873
  event: hooks.timeoutEvent(args.timeout_ms),
234765
234874
  scope,
234766
234875
  actingUserId,
@@ -234906,7 +235015,7 @@ function applyMonitorMaxTimeout(text2, timeoutMs = getMonitorMaxTimeoutMs()) {
234906
235015
  return text2.replaceAll("{{MONITOR_MAX_TIMEOUT}}", formatMonitorMaxTimeout(timeoutMs));
234907
235016
  }
234908
235017
  function getMonitorTimeoutEvent(timeoutMs, tool = "Monitor") {
234909
- 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.]";
235018
+ 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.]";
234910
235019
  }
234911
235020
  var HOUR_MS = 3600000, DAY_MS, DEFAULT_MAX_TIMEOUT_MS, SEVEN_DAYS_MS;
234912
235021
  var init_monitor_timeout = __esm(() => {
@@ -235287,7 +235396,8 @@ function queueMonitorEvent(params) {
235287
235396
  kind: "task_notification",
235288
235397
  text: formatMonitorEventNotification({
235289
235398
  taskId,
235290
- event: sanitizedEvent
235399
+ event: sanitizedEvent,
235400
+ description: sanitizeMonitorText(params.description ?? "", secrets2)
235291
235401
  }),
235292
235402
  ...scope,
235293
235403
  ...actingUserId !== undefined ? { actingUserId } : {}
@@ -235366,6 +235476,7 @@ function startCommandMonitor(args) {
235366
235476
  emit(event) {
235367
235477
  queueMonitorEvent({
235368
235478
  taskId,
235479
+ description: args.description,
235369
235480
  event,
235370
235481
  scope,
235371
235482
  actingUserId,
@@ -235489,6 +235600,7 @@ function startCommandMonitor(args) {
235489
235600
  `);
235490
235601
  queueMonitorEvent({
235491
235602
  taskId,
235603
+ description: args.description,
235492
235604
  event: getMonitorTimeoutEvent(args.timeout_ms),
235493
235605
  scope,
235494
235606
  actingUserId,
@@ -235544,6 +235656,7 @@ function startWebSocketMonitor(args) {
235544
235656
  emit(event) {
235545
235657
  queueMonitorEvent({
235546
235658
  taskId,
235659
+ description: args.description,
235547
235660
  event,
235548
235661
  scope,
235549
235662
  actingUserId,
@@ -235597,6 +235710,7 @@ function startWebSocketMonitor(args) {
235597
235710
  `);
235598
235711
  queueMonitorEvent({
235599
235712
  taskId,
235713
+ description: args.description,
235600
235714
  event,
235601
235715
  scope,
235602
235716
  actingUserId,
@@ -235630,6 +235744,7 @@ function startWebSocketMonitor(args) {
235630
235744
  `);
235631
235745
  queueMonitorEvent({
235632
235746
  taskId,
235747
+ description: args.description,
235633
235748
  event,
235634
235749
  scope,
235635
235750
  actingUserId,
@@ -235655,6 +235770,7 @@ function startWebSocketMonitor(args) {
235655
235770
  `);
235656
235771
  queueMonitorEvent({
235657
235772
  taskId,
235773
+ description: args.description,
235658
235774
  event,
235659
235775
  scope,
235660
235776
  actingUserId,
@@ -235671,6 +235787,7 @@ function startWebSocketMonitor(args) {
235671
235787
  return;
235672
235788
  queueMonitorEvent({
235673
235789
  taskId,
235790
+ description: args.description,
235674
235791
  event: getMonitorTimeoutEvent(args.timeout_ms),
235675
235792
  scope,
235676
235793
  actingUserId,
@@ -238332,14 +238449,14 @@ function createRemoteIdleNotifier(subagentId, parentScope) {
238332
238449
  addToMessageQueue({
238333
238450
  kind: "task_notification",
238334
238451
  ...scope,
238335
- text: formatTaskNotification({
238452
+ ...taskNotificationMessage(formatTaskNotification({
238336
238453
  taskId: subagentId,
238337
238454
  status: "running",
238338
238455
  summary: `Agent loop stopped with ${count} background process${count === 1 ? "" : "es"} still running`,
238339
238456
  result: `${text2}
238340
238457
 
238341
238458
  The child agent's loop has stopped with ${count} background process${count === 1 ? "" : "es"} still running. It will resume when they finish, and a final notification will follow.`
238342
- })
238459
+ }))
238343
238460
  });
238344
238461
  };
238345
238462
  }
@@ -238817,12 +238934,15 @@ function buildAgentSendContent(sender, noWait, message) {
238817
238934
  { type: "text", text: message }
238818
238935
  ];
238819
238936
  }
238937
+ function buildAgentSendCliTarget(agentId, conversationId) {
238938
+ return conversationId === "default" ? `--agent ${agentId} --conversation default` : `--conversation ${conversationId}`;
238939
+ }
238820
238940
  function buildAgentSendReminder(sender, noWait) {
238821
238941
  if (!sender.agentId)
238822
238942
  return "";
238823
238943
  const address = sender.conversationId ? `, conversation ${sender.conversationId}` : "";
238824
238944
  const isDefault = sender.conversationId === "default";
238825
- const cliTarget = isDefault ? `--agent ${sender.agentId} --conversation default` : `--conversation ${sender.conversationId}`;
238945
+ const cliTarget = buildAgentSendCliTarget(sender.agentId, sender.conversationId ?? "");
238826
238946
  const toolTarget = isDefault ? `agent_id ${sender.agentId} and conversation_id default` : `conversation_id ${sender.conversationId}`;
238827
238947
  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.";
238828
238948
  return `<system-reminder>
@@ -239023,9 +239143,10 @@ function withNativeCliPath(env6, platform7 = process.platform) {
239023
239143
  var init_native_cli_env = () => {};
239024
239144
 
239025
239145
  // src/tools/impl/claude-steer-timeouts.ts
239026
- 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";
239146
+ 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";
239027
239147
  var init_claude_steer_timeouts = __esm(() => {
239028
239148
  REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS = CLAUDE_TURN_START_TIMEOUT_MS + CLAUDE_CONTROL_RESPONSE_TIMEOUT_MS + 30000;
239149
+ REMOTE_SUBAGENT_MESSAGE_DEDUPE_PENDING_TTL_MS = 5 * REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS;
239029
239150
  });
239030
239151
 
239031
239152
  // src/tools/impl/external-llm-trace-payload.ts
@@ -240495,7 +240616,7 @@ class CodexAppServerClient {
240495
240616
  await this.request("initialize", {
240496
240617
  clientInfo: {
240497
240618
  name: "letta-code",
240498
- version: "0.34.62"
240619
+ version: "0.34.64"
240499
240620
  },
240500
240621
  capabilities: null
240501
240622
  });
@@ -241990,7 +242111,7 @@ ${SYSTEM_REMINDER_CLOSE}`;
241990
242111
  return null;
241991
242112
  }
241992
242113
  }
241993
- async function defaultListServerSideServers(agentId) {
242114
+ async function defaultListServerSideServers(agentId, timeoutMs = 3000) {
241994
242115
  let serverSideAvailable = false;
241995
242116
  try {
241996
242117
  const { getBackend: getBackend2 } = await Promise.resolve().then(() => (init_backend2(), exports_backend));
@@ -242006,7 +242127,7 @@ async function defaultListServerSideServers(agentId) {
242006
242127
  const { LETTA_CLOUD_API_URL: LETTA_CLOUD_API_URL2 } = await Promise.resolve().then(() => (init_oauth(), exports_oauth));
242007
242128
  const { listUnifiedMcpServers: listUnifiedMcpServers2 } = await Promise.resolve().then(() => (init_unified_mcp(), exports_unified_mcp));
242008
242129
  const client = await getClient2();
242009
- const allServers = await listUnifiedMcpServers2(client, agentId, 3000);
242130
+ const allServers = await listUnifiedMcpServers2(client, agentId, timeoutMs);
242010
242131
  const servers = getServerUrl2() === LETTA_CLOUD_API_URL2 ? allServers.filter((server2) => server2.serverType !== "stdio") : allServers;
242011
242132
  return servers.map((server2) => ({
242012
242133
  name: server2.serverName,
@@ -242020,26 +242141,20 @@ function formatMcpServerEntry(entry) {
242020
242141
  return `${entry.name} (${entry.toolCount} ${entry.toolCount === 1 ? "tool" : "tools"})`;
242021
242142
  }
242022
242143
  function buildMcpServersReminderText(entries) {
242023
- if (entries.length === 0) {
242024
- return `${SYSTEM_REMINDER_OPEN}
242025
- MCP servers with available tools: None
242026
- Do not automatically store results of principal-restricted operations in shared memory.
242027
- ${SYSTEM_REMINDER_CLOSE}`;
242028
- }
242029
- const rendered = entries.map(formatMcpServerEntry).join(", ");
242144
+ 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"}`;
242030
242145
  return `${SYSTEM_REMINDER_OPEN}
242031
- MCP servers with available tools: ${rendered}
242032
- Do not automatically store results of principal-restricted operations in shared memory.
242033
- 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).
242034
- ${SYSTEM_REMINDER_CLOSE}`;
242146
+ ${inventory}
242147
+ ${MCP_MEMORY_GUIDANCE}
242148
+ ${entries?.length === 0 ? "" : `${MCP_TOOL_USAGE}
242149
+ `}${SYSTEM_REMINDER_CLOSE}`;
242035
242150
  }
242036
- async function listMcpServersForAgent(agentId, _state, deps = {}) {
242151
+ async function listMcpServersForAgent(agentId, _state, deps = {}, timeoutMs = 3000) {
242037
242152
  const localNames = (deps.getLocalServerNames ?? ((id) => settingsManager.getMcpServers(id).map((server2) => server2.name)))(agentId);
242038
242153
  const entries = localNames.map((name) => ({
242039
242154
  name,
242040
242155
  toolCount: null
242041
242156
  }));
242042
- const serverSideEntries = await (deps.listServerSideServers ?? defaultListServerSideServers)(agentId);
242157
+ const serverSideEntries = await (deps.listServerSideServers ?? defaultListServerSideServers)(agentId, timeoutMs);
242043
242158
  if (serverSideEntries)
242044
242159
  entries.push(...serverSideEntries);
242045
242160
  return [...new Map(entries.map((entry) => [entry.name, entry])).values()];
@@ -242257,7 +242372,7 @@ function prependReminderPartsToContent(content, reminderParts) {
242257
242372
  }
242258
242373
  return [...reminderParts, { type: "text", text: text2 }];
242259
242374
  }
242260
- 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;
242375
+ 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;
242261
242376
  var init_engine = __esm(() => {
242262
242377
  init_agent_info();
242263
242378
  init_conversation_bootstrap();
@@ -243413,7 +243528,14 @@ function buildExternalCodingAgentMcpReminder(entries2) {
243413
243528
  async function resolveExternalCodingAgentMcpReminder(parentAgentId, mcp, deps = {}) {
243414
243529
  if (mcp?.inherit === false)
243415
243530
  return;
243416
- const inventory = await listMcpServersForAgent(await getMcpScopeAgentId(parentAgentId, undefined, deps.lookupParentAgent), createSharedReminderState(), deps);
243531
+ const scopeAgentId = await getMcpScopeAgentId(parentAgentId, undefined, deps.lookupParentAgent);
243532
+ let inventory;
243533
+ try {
243534
+ inventory = await listMcpServersForAgent(scopeAgentId, createSharedReminderState(), deps, 5000);
243535
+ } catch (error4) {
243536
+ debugLog("mcp", "Failed to load worker MCP inventory: %s", error4);
243537
+ return buildMcpServersReminderText(null);
243538
+ }
243417
243539
  return buildExternalCodingAgentMcpReminder(selectExternalCodingAgentMcpEntries(inventory, mcp?.servers));
243418
243540
  }
243419
243541
  function buildExternalCodingAgentCommand(options) {
@@ -243817,6 +243939,7 @@ var init_external_coding_agent = __esm(() => {
243817
243939
  init_engine();
243818
243940
  init_runtime_context();
243819
243941
  init_secret_substitution();
243942
+ init_debug();
243820
243943
  init_native_cli_env();
243821
243944
  init_claude_stream_session();
243822
243945
  init_codex_app_server();
@@ -245026,7 +245149,7 @@ async function fetchParentConversationMessages(params) {
245026
245149
  }
245027
245150
  return messages.reverse();
245028
245151
  }
245029
- function contentText3(content) {
245152
+ function contentText2(content) {
245030
245153
  if (typeof content === "string")
245031
245154
  return content;
245032
245155
  if (!Array.isArray(content))
@@ -245052,7 +245175,7 @@ function renderToolCall(call) {
245052
245175
  }
245053
245176
  function renderToolResult(result3) {
245054
245177
  const raw2 = result3.tool_return ?? result3.func_response;
245055
- const text2 = typeof raw2 === "string" ? raw2 : contentText3(raw2) || (raw2 == null ? "" : JSON.stringify(raw2));
245178
+ const text2 = typeof raw2 === "string" ? raw2 : contentText2(raw2) || (raw2 == null ? "" : JSON.stringify(raw2));
245056
245179
  return {
245057
245180
  type: "tool_result",
245058
245181
  call_id: result3.tool_call_id ?? undefined,
@@ -245088,11 +245211,11 @@ function userEvents(text2, speaker) {
245088
245211
  function renderMessage(message2) {
245089
245212
  switch (message2.message_type) {
245090
245213
  case "user_message": {
245091
- const text2 = contentText3(message2.content).replace(SYSTEM_REMINDER_PATTERN, "").trim();
245214
+ const text2 = contentText2(message2.content).replace(SYSTEM_REMINDER_PATTERN, "").trim();
245092
245215
  return userEvents(text2, message2.name ?? undefined);
245093
245216
  }
245094
245217
  case "assistant_message": {
245095
- const text2 = contentText3(message2.content).trim();
245218
+ const text2 = contentText2(message2.content).trim();
245096
245219
  return text2 ? [
245097
245220
  {
245098
245221
  type: "message",
@@ -245238,7 +245361,7 @@ async function prependParentContext(params) {
245238
245361
  prompt: [
245239
245362
  "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.",
245240
245363
  "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.",
245241
- `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>"\`.`,
245364
+ `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}\`.`,
245242
245365
  "<parent_history>",
245243
245366
  serializeHistoryRecord({
245244
245367
  type: "metadata",
@@ -245255,13 +245378,25 @@ async function prependParentContext(params) {
245255
245378
  `)
245256
245379
  };
245257
245380
  }
245381
+ function withReportBackInstruction(prompt, parentAgentId, parentConversationId) {
245382
+ if (!parentConversationId)
245383
+ return prompt;
245384
+ return [
245385
+ prompt,
245386
+ "",
245387
+ `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.`
245388
+ ].join(`
245389
+ `);
245390
+ }
245258
245391
  async function prepareExternalWorkerPrompt(params) {
245259
- if (!params.forkContext)
245260
- return { prompt: params.prompt };
245392
+ const parentConversationId = params.parentConversationId ?? getConversationId() ?? (params.forkContext ? "default" : undefined);
245393
+ const prompt = withReportBackInstruction(params.prompt, params.parentAgentId, parentConversationId);
245394
+ if (!params.forkContext || !parentConversationId)
245395
+ return { prompt };
245261
245396
  return prependParentContext({
245262
- prompt: params.prompt,
245397
+ prompt,
245263
245398
  parentAgentId: params.parentAgentId,
245264
- parentConversationId: params.parentConversationId ?? getConversationId() ?? "default",
245399
+ parentConversationId,
245265
245400
  signal: params.signal
245266
245401
  });
245267
245402
  }
@@ -245270,6 +245405,7 @@ var init_external_fork_context = __esm(() => {
245270
245405
  init_context();
245271
245406
  init_parent_transcript();
245272
245407
  init_backend2();
245408
+ init_agent_message();
245273
245409
  });
245274
245410
 
245275
245411
  // src/tools/impl/fork-prompt.ts
@@ -245767,6 +245903,64 @@ function isVersionBelow(version3, minimum) {
245767
245903
  return result3 === -1;
245768
245904
  }
245769
245905
 
245906
+ // src/tools/impl/remote-connect-retry.ts
245907
+ import { setTimeout as delay5 } from "node:timers/promises";
245908
+ async function connectRemoteWorkerWithRetry(connect, signal) {
245909
+ const backoffs = [1000, 3000];
245910
+ for (let attempt2 = 0;; attempt2++) {
245911
+ signal?.throwIfAborted();
245912
+ try {
245913
+ return await connect();
245914
+ } catch (error4) {
245915
+ signal?.throwIfAborted();
245916
+ const message2 = error4 instanceof Error ? error4.message : String(error4);
245917
+ const status = extractHttpStatus(message2);
245918
+ 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);
245919
+ const backoff3 = backoffs[attempt2];
245920
+ if (!transient || backoff3 === undefined)
245921
+ throw error4;
245922
+ await delay5(backoff3, undefined, { signal });
245923
+ }
245924
+ }
245925
+ }
245926
+ var init_remote_connect_retry = __esm(() => {
245927
+ init_error_reporting();
245928
+ });
245929
+
245930
+ // src/tools/impl/remote-follow-up-retry.ts
245931
+ async function sendRemoteFollowUpWithReconnect(client, command, connect, attach, computer) {
245932
+ try {
245933
+ try {
245934
+ return await client.sendSubagentMessage(command, {
245935
+ timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS
245936
+ });
245937
+ } catch (error4) {
245938
+ if (!(error4 instanceof Error) || error4.message !== "App-server socket closed")
245939
+ throw error4;
245940
+ client.close();
245941
+ const reconnected = await connect();
245942
+ attach(reconnected);
245943
+ return await reconnected.sendSubagentMessage(command, {
245944
+ timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS
245945
+ });
245946
+ }
245947
+ } catch (error4) {
245948
+ if (error4 instanceof Error && error4.message === "App-server socket closed")
245949
+ 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.`);
245950
+ if (error4 instanceof Error && error4.message === `Timed out waiting for ${command.request_id}`)
245951
+ 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.`);
245952
+ throw error4;
245953
+ }
245954
+ }
245955
+ var RemoteFollowUpTimeoutError, RemoteFollowUpSocketClosedError;
245956
+ var init_remote_follow_up_retry = __esm(() => {
245957
+ init_claude_steer_timeouts();
245958
+ RemoteFollowUpTimeoutError = class RemoteFollowUpTimeoutError extends Error {
245959
+ };
245960
+ RemoteFollowUpSocketClosedError = class RemoteFollowUpSocketClosedError extends Error {
245961
+ };
245962
+ });
245963
+
245770
245964
  // src/tools/impl/remote-subagent-events.ts
245771
245965
  function followRemoteSubagentEvents(subagentId, read2) {
245772
245966
  let cursor = 0;
@@ -245911,7 +246105,11 @@ function classifyRemoteExternalWorkerControlError(error4) {
245911
246105
  return "outdated_computer";
245912
246106
  if (error4 instanceof RemoteFollowUpTimeoutError)
245913
246107
  return "steer_timeout";
246108
+ if (error4 instanceof RemoteFollowUpSocketClosedError)
246109
+ return "socket_closed";
245914
246110
  const message2 = errorMessage5(error4);
246111
+ if (message2 === "App-server socket closed")
246112
+ return "socket_closed";
245915
246113
  if (message2 === CLAUDE_TURN_START_TIMEOUT_ERROR || message2 === CLAUDE_INTERRUPT_ACK_TIMEOUT_ERROR)
245916
246114
  return "worker_busy";
245917
246115
  if (/^Computer ".*" is offline(?:\.|$)/.test(message2) || message2.startsWith("Timed out waiting for cloud sandbox "))
@@ -246143,7 +246341,7 @@ async function launchRemoteExternalCodingAgent(params, deps) {
246143
246341
  const toolCallId = params.toolCallId ?? `remote-${randomUUID46()}`;
246144
246342
  let client;
246145
246343
  try {
246146
- client = await connect();
246344
+ client = await connectRemoteWorkerWithRetry(connect, params.signal);
246147
246345
  } catch (error4) {
246148
246346
  return fail2("connect", `Can't reach ${computer}: ${errorMessage5(error4)}`);
246149
246347
  }
@@ -246333,7 +246531,7 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246333
246531
  const bareAgentId = formatExternalCodingAgentId(target.type, target.sessionId);
246334
246532
  let response;
246335
246533
  try {
246336
- response = await client.sendSubagentMessage({
246534
+ response = await sendRemoteFollowUpWithReconnect(client, {
246337
246535
  request_id: requestId,
246338
246536
  runtime: {
246339
246537
  agent_id: params.parentScope.agentId,
@@ -246343,12 +246541,9 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246343
246541
  agent_id: bareAgentId,
246344
246542
  message: params.message,
246345
246543
  tool_call_id: toolCallId
246346
- }, { timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS });
246544
+ }, connect, (reconnected) => follower.attach(reconnected), target.computer);
246347
246545
  } catch (error4) {
246348
246546
  follower.close();
246349
- if (errorMessage5(error4) === `Timed out waiting for ${requestId}`) {
246350
- 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.`);
246351
- }
246352
246547
  throw error4;
246353
246548
  }
246354
246549
  if (!response.success) {
@@ -246420,7 +246615,7 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246420
246615
  outputFile: tracked.outputFile
246421
246616
  };
246422
246617
  }
246423
- var REMOTE_EXTERNAL_WORKER_STOPPED, DISPLAY_NAMES, RemoteWorkerLostError, OutdatedRemoteWorkerError, RemoteFollowUpTimeoutError, MAX_RECONNECT_DELAY_MS = 30000;
246618
+ var REMOTE_EXTERNAL_WORKER_STOPPED, DISPLAY_NAMES, RemoteWorkerLostError, OutdatedRemoteWorkerError, MAX_RECONNECT_DELAY_MS = 30000;
246424
246619
  var init_remote_external_coding_agent = __esm(() => {
246425
246620
  init_subagent_state();
246426
246621
  init_app_server_client();
@@ -246432,6 +246627,8 @@ var init_remote_external_coding_agent = __esm(() => {
246432
246627
  init_error_reporting();
246433
246628
  init_claude_steer_timeouts();
246434
246629
  init_external_coding_agent();
246630
+ init_remote_connect_retry();
246631
+ init_remote_follow_up_retry();
246435
246632
  init_remote_subagent_events();
246436
246633
  REMOTE_EXTERNAL_WORKER_STOPPED = Symbol("remote external worker stopped");
246437
246634
  DISPLAY_NAMES = {
@@ -246444,8 +246641,6 @@ var init_remote_external_coding_agent = __esm(() => {
246444
246641
  };
246445
246642
  OutdatedRemoteWorkerError = class OutdatedRemoteWorkerError extends Error {
246446
246643
  };
246447
- RemoteFollowUpTimeoutError = class RemoteFollowUpTimeoutError extends Error {
246448
- };
246449
246644
  });
246450
246645
 
246451
246646
  // src/tools/impl/subagent-computer.ts
@@ -247096,7 +247291,7 @@ ${formatSubagentError(result3.error || "Subagent execution failed")}`;
247096
247291
  });
247097
247292
  addToMessageQueueFn({
247098
247293
  kind: "task_notification",
247099
- text: notificationXml,
247294
+ ...taskNotificationMessage(notificationXml),
247100
247295
  agentId: resolvedParentScope?.agentId,
247101
247296
  conversationId: resolvedParentScope?.conversationId,
247102
247297
  actingUserId: bgTask.actingUserId,
@@ -247157,7 +247352,7 @@ ${formatSubagentError(errorMessage6)}`,
247157
247352
  });
247158
247353
  addToMessageQueueFn({
247159
247354
  kind: "task_notification",
247160
- text: notificationXml,
247355
+ ...taskNotificationMessage(notificationXml),
247161
247356
  agentId: resolvedParentScope?.agentId,
247162
247357
  conversationId: resolvedParentScope?.conversationId,
247163
247358
  actingUserId: bgTask.actingUserId,
@@ -247455,7 +247650,7 @@ Conversation ID: ${result3.conversation_id}` : "";
247455
247650
  Output file: ${result3.output_file}
247456
247651
  Event log: ${taskEventsFileFor(result3.output_file)}
247457
247652
 
247458
- You will be notified automatically when this task completes — a <task-notification> message will be delivered with the result. No need to poll or sleep-wait; continue with your current work. To see what it is doing meanwhile, Read the output file: one line per tool call, tool result, and message, live. For exact details (full tool arguments and outputs, such as a command's error), read the event log.`;
247653
+ You will be notified automatically when this task completes — a <task-notification> message will be delivered with the result. No need to poll or sleep-wait; continue with your current work. To see what it is doing meanwhile, Read the output file: one line per tool call, tool result, and message, live. For exact details (full tool arguments and outputs, such as a command's error), read the event log.${subagentResultReminder()}`;
247459
247654
  }
247460
247655
  var init_task = __esm(() => {
247461
247656
  init_context();
@@ -249306,7 +249501,7 @@ var init_github_pull_request_watch = __esm(() => {
249306
249501
  });
249307
249502
 
249308
249503
  // src/tools/impl/github-pull-request-cloud.ts
249309
- import { setTimeout as delay5 } from "node:timers/promises";
249504
+ import { setTimeout as delay6 } from "node:timers/promises";
249310
249505
  async function requestSnapshot(ref, signal) {
249311
249506
  const client = await getClient();
249312
249507
  try {
@@ -249378,7 +249573,7 @@ function createGitHubPullRequestSnapshotFetcher(deps = {}) {
249378
249573
  const now2 = deps.now ?? Date.now;
249379
249574
  const random3 = deps.random ?? Math.random;
249380
249575
  const wait = deps.wait ?? (async (ms, signal) => {
249381
- await delay5(ms, undefined, { signal });
249576
+ await delay6(ms, undefined, { signal });
249382
249577
  });
249383
249578
  let hasSnapshot = false;
249384
249579
  let unsupported = false;
@@ -249731,7 +249926,7 @@ import {
249731
249926
  writeFileSync as writeFileSync33
249732
249927
  } from "node:fs";
249733
249928
  import { dirname as dirname32, join as join74 } from "node:path";
249734
- import { setTimeout as delay6 } from "node:timers/promises";
249929
+ import { setTimeout as delay7 } from "node:timers/promises";
249735
249930
  function errorText(error4) {
249736
249931
  const message2 = error4 instanceof Error ? error4.message : String(error4);
249737
249932
  return scrubSecretsFromString(message2, {}).replace(/\s+/g, " ").trim().slice(0, 500);
@@ -249740,7 +249935,7 @@ function pollDelayMs(failedPolls) {
249740
249935
  return Math.min(WATCH_POLL_MS * 2 ** failedPolls, WATCH_MAX_POLL_MS);
249741
249936
  }
249742
249937
  async function defaultWait(signal, milliseconds) {
249743
- await delay6(milliseconds, undefined, { signal });
249938
+ await delay7(milliseconds, undefined, { signal });
249744
249939
  }
249745
249940
  function saveSnapshot(path32, snapshot2) {
249746
249941
  if (!path32)
@@ -249985,8 +250180,6 @@ ${event}
249985
250180
  let freshnessNoticeSent = false;
249986
250181
  let nextPollMs = WATCH_POLL_MS;
249987
250182
  let failedPolls = 0;
249988
- let failureStartedAt;
249989
- let lastNotifiedError;
249990
250183
  while (processState.status === "running") {
249991
250184
  try {
249992
250185
  await wait(controller.signal, nextPollMs);
@@ -250004,14 +250197,7 @@ ${event}
250004
250197
  freshnessNoticeSent = false;
250005
250198
  }
250006
250199
  nextPollMs = WATCH_POLL_MS;
250007
- if (lastNotifiedError !== undefined) {
250008
- emit([
250009
- `WatchPR recovered after ${failedPolls} failed poll${failedPolls === 1 ? "" : "s"}.`
250010
- ]);
250011
- }
250012
250200
  failedPolls = 0;
250013
- failureStartedAt = undefined;
250014
- lastNotifiedError = undefined;
250015
250201
  const sameHead = current.headSha === previous.headSha;
250016
250202
  const stableCurrent = { ...current, readinessConfirmed: false };
250017
250203
  stableCurrent.readinessConfirmed = Boolean(sameHead && hasGitHubPullRequestReadyConditions(previous) && hasGitHubPullRequestReadyConditions(stableCurrent));
@@ -250052,7 +250238,6 @@ ${event}
250052
250238
  }
250053
250239
  failedPolls += 1;
250054
250240
  nextPollMs = pollDelayMs(failedPolls);
250055
- failureStartedAt ??= now2();
250056
250241
  const message2 = errorText(error4);
250057
250242
  if (!output.append(`[poll error ${failedPolls}] ${message2}
250058
250243
  `)) {
@@ -250061,12 +250246,6 @@ ${event}
250061
250246
  controller.abort();
250062
250247
  return;
250063
250248
  }
250064
- if (now2() - failureStartedAt >= WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS && message2 !== lastNotifiedError) {
250065
- emit([
250066
- `WatchPR could not refresh ${ref.url}: ${message2}. Retrying.`
250067
- ]);
250068
- lastNotifiedError = message2;
250069
- }
250070
250249
  }
250071
250250
  }
250072
250251
  })().catch((error4) => {
@@ -250103,7 +250282,7 @@ Output file: ${outputFile}`
250103
250282
  };
250104
250283
  });
250105
250284
  }
250106
- var WATCH_POLL_MS = 30000, WATCH_MAX_POLL_MS, WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS, WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS;
250285
+ var WATCH_POLL_MS = 30000, WATCH_MAX_POLL_MS, WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS;
250107
250286
  var init_watch_pr = __esm(() => {
250108
250287
  init_monitors();
250109
250288
  init_runtime_context();
@@ -250121,7 +250300,6 @@ var init_watch_pr = __esm(() => {
250121
250300
  init_monitor_timeout();
250122
250301
  init_process_manager();
250123
250302
  WATCH_MAX_POLL_MS = 5 * 60000;
250124
- WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS = 5 * 60000;
250125
250303
  WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS = 30 * 60000;
250126
250304
  });
250127
250305
 
@@ -257430,71 +257608,6 @@ function withMessageAttribution(message2, actingUserId) {
257430
257608
  return { ...message2, attribution: { acting_user_id: actingUserId } };
257431
257609
  }
257432
257610
 
257433
- // src/queue/turn-queue-runtime.ts
257434
- function stringifyUnexpectedContent(content) {
257435
- try {
257436
- return JSON.stringify(content) ?? String(content);
257437
- } catch {
257438
- return String(content);
257439
- }
257440
- }
257441
- function appendContentParts(target, content) {
257442
- if (typeof content === "string") {
257443
- target.push({ type: "text", text: content });
257444
- return;
257445
- }
257446
- if (!Array.isArray(content)) {
257447
- if (content === null || content === undefined)
257448
- return;
257449
- target.push({ type: "text", text: stringifyUnexpectedContent(content) });
257450
- return;
257451
- }
257452
- target.push(...content);
257453
- }
257454
- function escapeResultText(text2) {
257455
- return text2.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
257456
- }
257457
- function buildTaskNotificationContent(item) {
257458
- if (item.content === undefined)
257459
- return item.text;
257460
- const parts = [
257461
- { type: "text", text: item.text },
257462
- { type: "text", text: `
257463
- <external-tool-result>` }
257464
- ];
257465
- const content = typeof item.content === "string" ? [{ type: "text", text: item.content }] : item.content;
257466
- for (const part of content) {
257467
- parts.push(part.type === "text" ? { type: "text", text: `<text>${escapeResultText(part.text)}</text>` } : part);
257468
- }
257469
- parts.push({ type: "text", text: "</external-tool-result>" });
257470
- return parts;
257471
- }
257472
- function mergeQueuedTurnInput(queued2, options) {
257473
- if (queued2.length === 0) {
257474
- return null;
257475
- }
257476
- const separatorText = options.separatorText ?? `
257477
- `;
257478
- const mergedParts = [];
257479
- let isFirst = true;
257480
- for (const item of queued2) {
257481
- if (!isFirst) {
257482
- mergedParts.push({ type: "text", text: separatorText });
257483
- }
257484
- isFirst = false;
257485
- if (item.kind === "task_notification") {
257486
- appendContentParts(mergedParts, buildTaskNotificationContent(item));
257487
- continue;
257488
- }
257489
- if (item.kind === "cron_prompt") {
257490
- mergedParts.push({ type: "text", text: item.text });
257491
- continue;
257492
- }
257493
- appendContentParts(mergedParts, options.normalizeUserContent(item.content));
257494
- }
257495
- return mergedParts.length > 0 ? mergedParts : null;
257496
- }
257497
-
257498
257611
  // src/websocket/helpers/listener-queue-adapter.ts
257499
257612
  function getListenerBlockedReason(lifecycle, pendingApprovalsLen) {
257500
257613
  if (lifecycle.kind === "cancelling") {
@@ -258051,11 +258164,11 @@ function scheduleDurableQueueRestore(listener, capacityReleased = true) {
258051
258164
  clearDurableQueueRestoreRetry(listener);
258052
258165
  return;
258053
258166
  }
258054
- const delay7 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
258167
+ const delay8 = Math.min(DURABLE_QUEUE_RESTORE_MAX_RETRY_DELAY_MS, DURABLE_QUEUE_RESTORE_RETRY_DELAY_MS * 2 ** Math.min(failures - 1, 16));
258055
258168
  listener.durableQueueRestoreTimer = setTimeout(() => {
258056
258169
  listener.durableQueueRestoreTimer = undefined;
258057
258170
  scheduleDurableQueueRestore(listener, false);
258058
- }, delay7);
258171
+ }, delay8);
258059
258172
  listener.durableQueueRestoreTimer.unref?.();
258060
258173
  } finally {
258061
258174
  listener.durableQueueRestoreScheduled = false;
@@ -264872,7 +264985,7 @@ async function acquireRecoveryClaim(runtime, onLost = () => {}, dependencies = {
264872
264985
  }
264873
264986
  return null;
264874
264987
  }
264875
- 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);
264988
+ 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);
264876
264989
  runtime.listener.activeRecoveryClaims ??= new Set;
264877
264990
  runtime.listener.activeRecoveryClaims.add(claim);
264878
264991
  refusalCounts.delete(runtime.listener);
@@ -427760,12 +427873,12 @@ ${options.prefix}` : `
427760
427873
  this.pendingTimeouts = /* @__PURE__ */ new Map;
427761
427874
  this.logger = logger.hasLevel(3) ? logger : undefined;
427762
427875
  }
427763
- schedule(operationId, delay7, cb) {
427876
+ schedule(operationId, delay8, cb) {
427764
427877
  const pendingTimeout = this.pendingTimeouts.get(operationId);
427765
427878
  if (pendingTimeout) {
427766
427879
  this.host.clearTimeout(pendingTimeout);
427767
427880
  }
427768
- this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay7, operationId, this, cb));
427881
+ this.pendingTimeouts.set(operationId, this.host.setTimeout(_ThrottledOperations.run, delay8, operationId, this, cb));
427769
427882
  if (this.logger) {
427770
427883
  this.logger.info(`Scheduled: ${operationId}${pendingTimeout ? ", Cancelled earlier one" : ""}`);
427771
427884
  }
@@ -427786,9 +427899,9 @@ ${options.prefix}` : `
427786
427899
  }
427787
427900
  };
427788
427901
  var GcTimer = class _GcTimer {
427789
- constructor(host, delay7, logger) {
427902
+ constructor(host, delay8, logger) {
427790
427903
  this.host = host;
427791
- this.delay = delay7;
427904
+ this.delay = delay8;
427792
427905
  this.logger = logger;
427793
427906
  }
427794
427907
  scheduleCollect() {
@@ -435828,12 +435941,12 @@ Project '${project.projectName}' (${ProjectKind[project.projectKind]}) ${counter
435828
435941
  const project = this.projectService.tryGetDefaultProjectForFile(fileName);
435829
435942
  return project && { fileName, project };
435830
435943
  }
435831
- getDiagnostics(next, delay7, fileArgs) {
435944
+ getDiagnostics(next, delay8, fileArgs) {
435832
435945
  if (this.suppressDiagnosticEvents) {
435833
435946
  return;
435834
435947
  }
435835
435948
  if (fileArgs.length > 0) {
435836
- this.updateErrorCheck(next, fileArgs, delay7);
435949
+ this.updateErrorCheck(next, fileArgs, delay8);
435837
435950
  }
435838
435951
  }
435839
435952
  change(args) {
@@ -436195,7 +436308,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
436195
436308
  const spans = languageService.getBraceMatchingAtPosition(file, position);
436196
436309
  return !spans ? undefined : simplifiedResult ? spans.map((span) => toProtocolTextSpan(span, scriptInfo)) : spans;
436197
436310
  }
436198
- getDiagnosticsForProject(next, delay7, fileName) {
436311
+ getDiagnosticsForProject(next, delay8, fileName) {
436199
436312
  if (this.suppressDiagnosticEvents) {
436200
436313
  return;
436201
436314
  }
@@ -436229,7 +436342,7 @@ Additional information: BADCLIENT: Bad error code, ${badCode} not found in range
436229
436342
  }
436230
436343
  const sortedFiles = [...highPriorityFiles, ...mediumPriorityFiles, ...lowPriorityFiles, ...veryLowPriorityFiles];
436231
436344
  const checkList = sortedFiles.map((fileName2) => ({ fileName: fileName2, project }));
436232
- this.updateErrorCheck(next, checkList, delay7, false);
436345
+ this.updateErrorCheck(next, checkList, delay8, false);
436233
436346
  }
436234
436347
  configurePlugin(args) {
436235
436348
  this.projectService.configurePlugin(args);
@@ -440535,7 +440648,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
440535
440648
  retryStates.delete(runtime);
440536
440649
  return;
440537
440650
  }
440538
- const delay7 = retryDelay(state2.attempt);
440651
+ const delay8 = retryDelay(state2.attempt);
440539
440652
  state2.attempt += 1;
440540
440653
  state2.scheduled = true;
440541
440654
  state2.timer = setTimeout(() => {
@@ -440544,7 +440657,7 @@ function scheduleRecoveredApprovalRetry(runtime, retry3) {
440544
440657
  state2.timer = undefined;
440545
440658
  state2.scheduled = false;
440546
440659
  scheduleRecoveredApprovalRetry(runtime, state2.retry);
440547
- }, delay7);
440660
+ }, delay8);
440548
440661
  state2.timer.unref?.();
440549
440662
  };
440550
440663
  state2.retry().then((handled) => {
@@ -446607,12 +446720,12 @@ function rowToolCalls(row, index, diagnostics2) {
446607
446720
  }
446608
446721
  return calls;
446609
446722
  }
446610
- function contentText4(content) {
446723
+ function contentText3(content) {
446611
446724
  if (typeof content === "string") {
446612
446725
  if (content.startsWith(CONTENT_JSON_PREFIX)) {
446613
446726
  const encoded = content.slice(CONTENT_JSON_PREFIX.length);
446614
446727
  try {
446615
- return contentText4(JSON.parse(encoded));
446728
+ return contentText3(JSON.parse(encoded));
446616
446729
  } catch {
446617
446730
  return encoded;
446618
446731
  }
@@ -446698,7 +446811,7 @@ var init_hermes = __esm(() => {
446698
446811
  });
446699
446812
  };
446700
446813
  if (row.role === "user") {
446701
- const content = contentText4(row.content);
446814
+ const content = contentText3(row.content);
446702
446815
  if (content) {
446703
446816
  emit({
446704
446817
  type: "message",
@@ -446718,7 +446831,7 @@ var init_hermes = __esm(() => {
446718
446831
  ...timestamp ? { timestamp } : {}
446719
446832
  });
446720
446833
  }
446721
- const content = contentText4(row.content);
446834
+ const content = contentText3(row.content);
446722
446835
  if (content) {
446723
446836
  emit({
446724
446837
  type: "message",
@@ -446741,7 +446854,7 @@ var init_hermes = __esm(() => {
446741
446854
  if (row.role === "tool") {
446742
446855
  emit({
446743
446856
  type: "tool_result",
446744
- content: contentText4(row.content),
446857
+ content: contentText3(row.content),
446745
446858
  ...typeof row.tool_call_id === "string" && row.tool_call_id ? { callId: row.tool_call_id } : {},
446746
446859
  ...timestamp ? { timestamp } : {}
446747
446860
  });
@@ -453811,10 +453924,10 @@ async function registerWithCloudRetry(opts, callbacks) {
453811
453924
  }
453812
453925
  attempt2++;
453813
453926
  const backoffDelay = Math.min(REGISTER_INITIAL_DELAY_MS * 2 ** (attempt2 - 1), REGISTER_MAX_DELAY_MS);
453814
- const delay7 = error4 instanceof RegistrationError && error4.retryAfterMs !== undefined ? Math.max(error4.retryAfterMs, backoffDelay) : backoffDelay;
453815
- const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay7 * REGISTER_JITTER_RATIO));
453927
+ const delay8 = error4 instanceof RegistrationError && error4.retryAfterMs !== undefined ? Math.max(error4.retryAfterMs, backoffDelay) : backoffDelay;
453928
+ const jitterWindow = Math.min(REGISTER_MAX_JITTER_MS, Math.floor(delay8 * REGISTER_JITTER_RATIO));
453816
453929
  const jitter2 = jitterWindow > 0 ? Math.floor((callbacks?.random ?? Math.random)() * jitterWindow) : 0;
453817
- const retryDelay2 = delay7 + jitter2;
453930
+ const retryDelay2 = delay8 + jitter2;
453818
453931
  if (error4 instanceof Error) {
453819
453932
  callbacks?.onRetry?.(attempt2, retryDelay2, error4);
453820
453933
  }
@@ -460668,7 +460781,7 @@ function applyCatalogModels(next, options = {}) {
460668
460781
  }
460669
460782
  if (options.requireManagedDefault !== false) {
460670
460783
  const defaults6 = next.filter((model2) => model2.isDefault || model2.id === "auto");
460671
- if (defaults6.length !== 1) {
460784
+ if (defaults6.length === 0) {
460672
460785
  return false;
460673
460786
  }
460674
460787
  }
@@ -463107,6 +463220,7 @@ async function stopMonitor(command) {
463107
463220
  actingUserId: command.runtime.acting_user_id,
463108
463221
  text: formatMonitorEventNotification({
463109
463222
  taskId: command.process_id,
463223
+ description: process21.description,
463110
463224
  event: "The user cancelled this Monitor. Do not restart it unless the user asks."
463111
463225
  })
463112
463226
  });
@@ -463323,12 +463437,19 @@ async function handleSubagentMessageCommand(command, parent, deps = {}) {
463323
463437
  }
463324
463438
  })();
463325
463439
  responses.set(key4, {
463326
- expiresAt: now2 + DEDUPE_TTL_MS,
463440
+ expiresAt: now2 + REMOTE_SUBAGENT_MESSAGE_DEDUPE_PENDING_TTL_MS,
463327
463441
  response
463328
463442
  });
463329
463443
  const result3 = await response;
463330
- if (!result3.success && responses.get(key4)?.response === response)
463331
- responses.delete(key4);
463444
+ if (responses.get(key4)?.response === response) {
463445
+ if (!result3.success)
463446
+ responses.delete(key4);
463447
+ else
463448
+ responses.set(key4, {
463449
+ expiresAt: (deps.now ?? Date.now)() + DEDUPE_TTL_MS,
463450
+ response
463451
+ });
463452
+ }
463332
463453
  return result3;
463333
463454
  }
463334
463455
  async function handleSubagentStopCommand(command, parent) {
@@ -463388,6 +463509,7 @@ var DEDUPE_TTL_MS = 30000, responses;
463388
463509
  var init_subagent_control = __esm(() => {
463389
463510
  init_subagent_state();
463390
463511
  init_runtime_context();
463512
+ init_claude_steer_timeouts();
463391
463513
  init_claude_stream_session();
463392
463514
  init_codex_app_server();
463393
463515
  init_cursor_session();
@@ -463503,6 +463625,7 @@ var exports_task_control = {};
463503
463625
  __export(exports_task_control, {
463504
463626
  handleTaskControlCommand: () => handleTaskControlCommand
463505
463627
  });
463628
+ import WebSocket12 from "ws";
463506
463629
  async function handleTaskControlCommand(command, context3) {
463507
463630
  const {
463508
463631
  runtime,
@@ -463512,12 +463635,17 @@ async function handleTaskControlCommand(command, context3) {
463512
463635
  runDetachedListenerTask: runDetachedListenerTask2,
463513
463636
  safeSocketSend
463514
463637
  } = context3;
463638
+ const arrivedOnRelay = connectionId !== undefined && connectionId === runtime.connectionId;
463639
+ const sendReply = (response) => {
463640
+ const replySocket = socket.readyState !== WebSocket12.OPEN && arrivedOnRelay && runtime.socket?.readyState === WebSocket12.OPEN ? runtime.socket : socket;
463641
+ safeSocketSend(replySocket, response, response.type, command.type);
463642
+ };
463515
463643
  const execute = async () => {
463516
463644
  if (command.type === "subagent_stop" && command.conversation) {
463517
463645
  const response2 = await stopListenerConversation(command, context3.abortConversation ?? (async () => {
463518
463646
  throw new Error("Listener cancellation is unavailable");
463519
463647
  }));
463520
- safeSocketSend(socket, response2, response2.type, command.type);
463648
+ sendReply(response2);
463521
463649
  return;
463522
463650
  }
463523
463651
  if (command.type === "monitor_stop") {
@@ -463532,7 +463660,7 @@ async function handleTaskControlCommand(command, context3) {
463532
463660
  }
463533
463661
  const parent = getOrCreateScopedRuntime2(runtime, command.runtime.agent_id, command.runtime.conversation_id);
463534
463662
  const response = command.type === "launch_subagent" ? await handleLaunchSubagentCommand(command, parent, connectionId) : command.type === "subagent_message" ? await handleSubagentMessageCommand(command, parent) : await handleSubagentStopCommand(command, parent);
463535
- safeSocketSend(socket, response, response.type, command.type);
463663
+ sendReply(response);
463536
463664
  };
463537
463665
  if (command.type === "launch_subagent" || command.type === "subagent_message") {
463538
463666
  runDetachedListenerTask2(command.type, execute);
@@ -465010,9 +465138,9 @@ var init_restored_queue_pump = __esm(() => {
465010
465138
  });
465011
465139
 
465012
465140
  // src/websocket/listener/socket-send.ts
465013
- import WebSocket12 from "ws";
465141
+ import WebSocket13 from "ws";
465014
465142
  function safeSocketSend(socket, payload, errorType, context3) {
465015
- if (socket.readyState !== WebSocket12.OPEN)
465143
+ if (socket.readyState !== WebSocket13.OPEN)
465016
465144
  return false;
465017
465145
  try {
465018
465146
  const serialized = typeof payload === "string" ? payload : JSON.stringify(payload);
@@ -465307,7 +465435,7 @@ var init_sync_replay = __esm(() => {
465307
465435
  });
465308
465436
 
465309
465437
  // src/websocket/listener/lifecycle.ts
465310
- import WebSocket13 from "ws";
465438
+ import WebSocket14 from "ws";
465311
465439
  function createRuntime() {
465312
465440
  const bootWorkingDirectory = getCurrentWorkingDirectory();
465313
465441
  return {
@@ -465577,7 +465705,7 @@ async function attachOpenListenerSocket(runtime, socket, opts, options = {}) {
465577
465705
  abortStartupIngress();
465578
465706
  return;
465579
465707
  }
465580
- const streamTransport = streamSocket?.readyState === WebSocket13.OPEN ? streamSocket : null;
465708
+ const streamTransport = streamSocket?.readyState === WebSocket14.OPEN ? streamSocket : null;
465581
465709
  await startConnectedListenerRuntime(runtime, transport3, opts, processQueuedTurn, {
465582
465710
  startHeartbeat: options.startHeartbeat ?? false,
465583
465711
  startCronScheduler: options.startCronScheduler ?? true,
@@ -465662,10 +465790,10 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
465662
465790
  opts.onError(new Error("Failed to connect after 5 minutes of retrying"));
465663
465791
  return;
465664
465792
  }
465665
- const delay7 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
465666
- opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay7, opts.connectionId);
465793
+ const delay8 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
465794
+ opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay8, opts.connectionId);
465667
465795
  await new Promise((resolve39) => {
465668
- runtime.reconnectTimeout = setTimeout(resolve39, delay7);
465796
+ runtime.reconnectTimeout = setTimeout(resolve39, delay8);
465669
465797
  });
465670
465798
  runtime.reconnectTimeout = null;
465671
465799
  if (runtime !== getActiveRuntime() || runtime.intentionallyClosed) {
@@ -465848,7 +465976,7 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
465848
465976
  streamSocket.removeAllListeners("message");
465849
465977
  streamSocket.removeAllListeners("open");
465850
465978
  streamSocket.removeAllListeners("close");
465851
- if (streamSocket.readyState === WebSocket13.OPEN || streamSocket.readyState === WebSocket13.CONNECTING) {
465979
+ if (streamSocket.readyState === WebSocket14.OPEN || streamSocket.readyState === WebSocket14.CONNECTING) {
465852
465980
  streamSocket.close();
465853
465981
  }
465854
465982
  }
@@ -466973,7 +467101,7 @@ __export(exports_app_server, {
466973
467101
  });
466974
467102
  import { createServer as createServer7 } from "node:http";
466975
467103
  import { hostname as hostname4 } from "node:os";
466976
- import WebSocket14, { WebSocketServer } from "ws";
467104
+ import WebSocket15, { WebSocketServer } from "ws";
466977
467105
  function getRequiredAddressInfo(server2) {
466978
467106
  const address = server2.address();
466979
467107
  if (!address || typeof address === "string") {
@@ -466989,12 +467117,12 @@ function getWebSocketUrl(baseUrl, path46) {
466989
467117
  function closeSocket(socket, code = 1001, reason = "closing") {
466990
467118
  if (!socket)
466991
467119
  return;
466992
- if (socket.readyState === WebSocket14.OPEN || socket.readyState === WebSocket14.CONNECTING) {
467120
+ if (socket.readyState === WebSocket15.OPEN || socket.readyState === WebSocket15.CONNECTING) {
466993
467121
  socket.close(code, reason);
466994
467122
  }
466995
467123
  }
466996
467124
  function terminateSocket(socket) {
466997
- if (!socket || socket.readyState === WebSocket14.CLOSED)
467125
+ if (!socket || socket.readyState === WebSocket15.CLOSED)
466998
467126
  return;
466999
467127
  socket.terminate();
467000
467128
  }
@@ -467181,7 +467309,7 @@ async function startAppServer(options = {}) {
467181
467309
  client.terminate();
467182
467310
  continue;
467183
467311
  }
467184
- if (client.readyState === WebSocket14.OPEN) {
467312
+ if (client.readyState === WebSocket15.OPEN) {
467185
467313
  const sentAt = Date.now();
467186
467314
  client.ping();
467187
467315
  watchdog?.recordPing(sentAt);
@@ -477945,7 +478073,7 @@ async function runUsageSubcommand(argv) {
477945
478073
  console.log(`Usage:
477946
478074
  letta usage
477947
478075
 
477948
- Show a Markdown overview of your plan, credit balance, and letta/* model quota.
478076
+ Show a Markdown overview of your plan and remaining credit balance.
477949
478077
  Local backend: model usage requires BYOK.
477950
478078
 
477951
478079
  Options:
@@ -477959,20 +478087,12 @@ Options:
477959
478087
  await settingsManager.initialize();
477960
478088
  await getClient();
477961
478089
  await settingsManager.flush();
477962
- const [balance, quota] = await Promise.all([
477963
- getBalanceMetadata(),
477964
- getModelQuotaMetadata()
477965
- ]);
478090
+ const balance = await getBalanceMetadata();
477966
478091
  const usage = `# Letta usage overview
477967
478092
  Current plan: ${balance.billing_tier}
477968
478093
 
477969
478094
  ## Usage Credits (non-BYOK models)
477970
478095
  * Balance: ${balance.total_balance} credits
477971
-
477972
- ## Usage Quota (\`letta/*\` models)
477973
- * Bucket (full/high/medium/low/empty): ${quota.lettaTier.bucket} (daily: ${quota.lettaTier.dailyBucket ?? "Unavailable"})
477974
- * Quota Window End: ${quota.quotaWindowEnd}
477975
- * Daily Quota Window End: ${quota.dailyQuotaWindowEnd ?? "Unavailable"}
477976
478096
  `;
477977
478097
  await new Promise((resolve42, reject2) => {
477978
478098
  process.stdout.write(usage, (error4) => error4 ? reject2(error4) : resolve42());
@@ -482240,7 +482360,7 @@ async function handleChannelsSlashCommand(runtime, args) {
482240
482360
 
482241
482361
  // src/channels/gateway-local.ts
482242
482362
  import { createHash as createHash23 } from "node:crypto";
482243
- import WebSocket15 from "ws";
482363
+ import WebSocket16 from "ws";
482244
482364
  async function executeChannelServiceCommand(command) {
482245
482365
  if (!isDetachedChannelsCommand(command)) {
482246
482366
  throw new Error(`Unsupported ChannelGateway command: ${command.type}`);
@@ -482311,7 +482431,7 @@ async function startLocalChannelGateway(options) {
482311
482431
  await settingsManager.initialize();
482312
482432
  const client = createAppServerClient({
482313
482433
  url: options.appServerUrl,
482314
- WebSocket: WebSocket15
482434
+ WebSocket: WebSocket16
482315
482435
  });
482316
482436
  await client.connect();
482317
482437
  let serverInfo;
@@ -483231,6 +483351,15 @@ function createStartupBackend(backend3, usesRemoteComputer, actingUserId = resol
483231
483351
  }
483232
483352
  var init_headless_startup_backend = () => {};
483233
483353
 
483354
+ // src/queue/queued-message-line.ts
483355
+ function serializeQueuedMessageAsUserLine(message2) {
483356
+ return JSON.stringify({
483357
+ type: "user",
483358
+ message: { role: "user", content: message2.content ?? message2.text },
483359
+ _queuedKind: message2.kind
483360
+ });
483361
+ }
483362
+
483234
483363
  // src/utils/headless-stdout-guard.ts
483235
483364
  function installHeadlessStdoutGuard() {
483236
483365
  process.stdout.on("error", (err) => {
@@ -484419,7 +484548,8 @@ function toBidirectionalQueuedInput(content, queuedKind) {
484419
484548
  if (queuedKind === "task_notification") {
484420
484549
  return {
484421
484550
  kind: "task_notification",
484422
- text: contentToTaskNotificationText(content)
484551
+ text: contentToTaskNotificationText(content),
484552
+ content
484423
484553
  };
484424
484554
  }
484425
484555
  return {
@@ -486504,7 +486634,8 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
486504
486634
  msgQueueRuntime.enqueue({
486505
486635
  kind: "task_notification",
486506
486636
  source: "task_notification",
486507
- text: input.text
486637
+ text: input.text,
486638
+ content: input.content
486508
486639
  });
486509
486640
  } else if (input.kind === "cron_prompt") {
486510
486641
  msgQueueRuntime.enqueue({
@@ -486520,14 +486651,6 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
486520
486651
  });
486521
486652
  }
486522
486653
  }
486523
- const serializeQueuedMessageAsUserLine = (queuedMessage) => JSON.stringify({
486524
- type: "user",
486525
- message: {
486526
- role: "user",
486527
- content: queuedMessage.text
486528
- },
486529
- _queuedKind: queuedMessage.kind
486530
- });
486531
486654
  setMessageQueueAdder((queuedMessage) => {
486532
486655
  const syntheticUserLine = serializeQueuedMessageAsUserLine(queuedMessage);
486533
486656
  maybeNotifyBlocked(syntheticUserLine);
@@ -530825,9 +530948,9 @@ function App2({
530825
530948
  }
530826
530949
  const elapsedSinceClear = Date.now() - lastClearAtRef.current;
530827
530950
  const rateLimitDelay = elapsedSinceClear >= MIN_CLEAR_INTERVAL_MS ? 0 : MIN_CLEAR_INTERVAL_MS - elapsedSinceClear;
530828
- const delay7 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
530951
+ const delay8 = Math.max(RESIZE_SETTLE_MS, rateLimitDelay);
530829
530952
  if (debugFlicker) {
530830
- console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay7}ms elapsedSinceClear=${elapsedSinceClear}ms`);
530953
+ console.error(`[debug:flicker:resize-schedule] target=${targetColumns} delay=${delay8}ms elapsedSinceClear=${elapsedSinceClear}ms`);
530831
530954
  }
530832
530955
  resizeClearTimeout.current = setTimeout(() => {
530833
530956
  resizeClearTimeout.current = null;
@@ -530847,7 +530970,7 @@ function App2({
530847
530970
  console.error(`[debug:flicker:resize-fire] clear target=${targetColumns}`);
530848
530971
  }
530849
530972
  clearAndRemount(targetColumns);
530850
- }, delay7);
530973
+ }, delay8);
530851
530974
  }, [clearAndRemount, debugFlicker]);
530852
530975
  import_react124.useEffect(() => {
530853
530976
  const prev = prevColumnsRef.current;
@@ -531353,11 +531476,11 @@ function App2({
531353
531476
  import_react124.useEffect(() => {
531354
531477
  if (deferredCommitAt === null)
531355
531478
  return;
531356
- const delay7 = Math.max(0, deferredCommitAt - Date.now());
531479
+ const delay8 = Math.max(0, deferredCommitAt - Date.now());
531357
531480
  const timer = setTimeout(() => {
531358
531481
  setDeferredCommitAt(null);
531359
531482
  refreshDerived();
531360
- }, delay7);
531483
+ }, delay8);
531361
531484
  return () => clearTimeout(timer);
531362
531485
  }, [deferredCommitAt, refreshDerived]);
531363
531486
  const streamingRefreshTimeoutRef = import_react124.useRef(null);
@@ -533355,7 +533478,7 @@ USAGE
533355
533478
  letta memory ... Memory filesystem subcommands
533356
533479
  letta agents ... Agents subcommands (JSON-only)
533357
533480
  letta model ... Get, list, or set models and reasoning (JSON-only)
533358
- letta usage Show account credits and Letta quota (Markdown)
533481
+ letta usage Show account plan and remaining credits (Markdown)
533359
533482
  letta computers ... List available remote computers (JSON-only)
533360
533483
  letta teleport ... Move the current conversation between computers
533361
533484
  letta messages ... Messages subcommands (JSON-only)
@@ -537302,4 +537425,4 @@ function registerBunOAuthFlows() {
537302
537425
  registerBunOAuthFlows();
537303
537426
  await init_src5().then(() => exports_src2);
537304
537427
 
537305
- //# debugId=F554CFFB3971F63D64756E2164756E21
537428
+ //# debugId=E9010BF867CFE3EB64756E2164756E21