@letta-ai/letta-code 0.34.61 → 0.34.62

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/mcp-client.js +2 -2
  2. package/dist/mcp-client.js.map +1 -1
  3. package/dist/mcp-oauth.js +2 -2
  4. package/dist/mcp-oauth.js.map +1 -1
  5. package/dist/types/backend/api/monitors.d.ts +11 -2
  6. package/dist/types/backend/api/monitors.d.ts.map +1 -1
  7. package/dist/types/cli/helpers/session-context.d.ts +2 -1
  8. package/dist/types/cli/helpers/session-context.d.ts.map +1 -1
  9. package/dist/types/cron/runner.d.ts +12 -14
  10. package/dist/types/cron/runner.d.ts.map +1 -1
  11. package/dist/types/cron/scheduler.d.ts.map +1 -1
  12. package/dist/types/runtime-context.d.ts +4 -0
  13. package/dist/types/runtime-context.d.ts.map +1 -1
  14. package/dist/types/tools/impl/claude-steer-timeouts.d.ts +20 -0
  15. package/dist/types/tools/impl/claude-steer-timeouts.d.ts.map +1 -0
  16. package/dist/types/tools/impl/claude-stream-session-types.d.ts +112 -0
  17. package/dist/types/tools/impl/claude-stream-session-types.d.ts.map +1 -0
  18. package/dist/types/tools/impl/claude-stream-session.d.ts +2 -46
  19. package/dist/types/tools/impl/claude-stream-session.d.ts.map +1 -1
  20. package/dist/types/tools/impl/external-coding-agent.d.ts +2 -2
  21. package/dist/types/tools/impl/external-coding-agent.d.ts.map +1 -1
  22. package/dist/types/tools/impl/fork-prompt.d.ts +4 -0
  23. package/dist/types/tools/impl/fork-prompt.d.ts.map +1 -0
  24. package/dist/types/tools/impl/kill-bash.d.ts.map +1 -1
  25. package/dist/types/tools/impl/monitor-args.d.ts +32 -0
  26. package/dist/types/tools/impl/monitor-args.d.ts.map +1 -0
  27. package/dist/types/tools/impl/monitor-resume.d.ts +7 -0
  28. package/dist/types/tools/impl/monitor-resume.d.ts.map +1 -0
  29. package/dist/types/tools/impl/monitor-script.d.ts +1 -1
  30. package/dist/types/tools/impl/monitor-script.d.ts.map +1 -1
  31. package/dist/types/tools/impl/monitor-state.d.ts +4 -0
  32. package/dist/types/tools/impl/monitor-state.d.ts.map +1 -1
  33. package/dist/types/tools/impl/monitor-timeout.d.ts +1 -0
  34. package/dist/types/tools/impl/monitor-timeout.d.ts.map +1 -1
  35. package/dist/types/tools/impl/monitor.d.ts +2 -32
  36. package/dist/types/tools/impl/monitor.d.ts.map +1 -1
  37. package/dist/types/tools/impl/process_manager.d.ts +1 -0
  38. package/dist/types/tools/impl/process_manager.d.ts.map +1 -1
  39. package/dist/types/tools/impl/remote-external-coding-agent.d.ts +1 -1
  40. package/dist/types/tools/impl/remote-external-coding-agent.d.ts.map +1 -1
  41. package/dist/types/tools/impl/send-agent-message.d.ts.map +1 -1
  42. package/dist/types/tools/impl/shell-env.d.ts.map +1 -1
  43. package/dist/types/tools/impl/subagent-computer.d.ts +5 -5
  44. package/dist/types/tools/impl/task.d.ts.map +1 -1
  45. package/dist/types/tools/impl/wake.d.ts.map +1 -1
  46. package/dist/types/tools/impl/watch-pr.d.ts +2 -1
  47. package/dist/types/tools/impl/watch-pr.d.ts.map +1 -1
  48. package/dist/types/tools/task-tool-assets.d.ts +1 -1
  49. package/dist/types/tools/task-tool-assets.d.ts.map +1 -1
  50. package/dist/types/tools/toolset-catalog.d.ts +1 -1
  51. package/dist/types/tools/toolset.d.ts +1 -1
  52. package/dist/types/tools/toolset.d.ts.map +1 -1
  53. package/dist/types/types/subagent-protocol.d.ts +1 -1
  54. package/dist/types/types/subagent-protocol.d.ts.map +1 -1
  55. package/dist/types/websocket/listener/interrupted-turn-disk-reserve.d.ts +6 -0
  56. package/dist/types/websocket/listener/interrupted-turn-disk-reserve.d.ts.map +1 -0
  57. package/dist/types/websocket/listener/interrupted-turn-record.d.ts.map +1 -1
  58. package/letta.js +731 -313
  59. package/npm-shrinkwrap.json +5 -5
  60. package/package.json +2 -2
  61. package/skills/scheduling-tasks/SKILL.md +6 -20
package/letta.js CHANGED
@@ -4892,6 +4892,10 @@ import { homedir as homedir2, tmpdir } from "node:os";
4892
4892
  function getRuntimeContext() {
4893
4893
  return runtimeContextStorage.getStore();
4894
4894
  }
4895
+ function getRuntimeSessionSource() {
4896
+ const source = getRuntimeContext()?.sessionSource ?? process.env.LETTA_RUNTIME_SESSION_SOURCE;
4897
+ return source === "interactive-cli" || source === "headless" || source === "listen" ? source : undefined;
4898
+ }
4895
4899
  function getRuntimeActingUserId() {
4896
4900
  const context = getRuntimeContext();
4897
4901
  if (context?.suppressActingUserFallback)
@@ -6135,7 +6139,7 @@ var package_default;
6135
6139
  var init_package = __esm(() => {
6136
6140
  package_default = {
6137
6141
  name: "@letta-ai/letta-code",
6138
- version: "0.34.61",
6142
+ version: "0.34.62",
6139
6143
  lettaStartupLogProtocol: 1,
6140
6144
  lettaConfigDirProtocol: 1,
6141
6145
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6422,7 +6426,7 @@ var init_package = __esm(() => {
6422
6426
  },
6423
6427
  lettaLifecycleProtocol: 1,
6424
6428
  lettaRuntimeGraphProtocol: 1,
6425
- lettaRuntimeGraphSha512: "sha512-WIuDCHjU7HpMkupg3IJU9kpdNZeagbwQQttyZaFDwGbI5Joz+NYvDSWoXrYPaA1w2Oxy6HVIBBPtv/lzIoENmg==",
6429
+ lettaRuntimeGraphSha512: "sha512-llGcPR13/WPW010yGdtNGC7Apobzktid+4Ka3zhviUWYP60+sHx9ovVyADbq+eHG9wrgZn9zRpo+7kdJ4mnElw==",
6426
6430
  patchedDependencies: {
6427
6431
  "@earendil-works/pi-ai@1.5.2": "patches/@earendil-works%2Fpi-ai@1.5.2.patch"
6428
6432
  }
@@ -203338,7 +203342,7 @@ var init_mcp_client = __esm(() => {
203338
203342
  init_streamableHttp();
203339
203343
  DEFAULT_CLIENT_INFO = {
203340
203344
  name: "letta-code",
203341
- version: "0.34.61"
203345
+ version: "0.34.62"
203342
203346
  };
203343
203347
  });
203344
203348
 
@@ -207246,6 +207250,129 @@ var init_durable_file_lock = __esm(() => {
207246
207250
  readCurrentDurableLockOwner = createCurrentDurableLockOwner();
207247
207251
  });
207248
207252
 
207253
+ // src/utils/disk-reserve.ts
207254
+ import {
207255
+ closeSync as closeSync6,
207256
+ existsSync as existsSync34,
207257
+ mkdirSync as mkdirSync30,
207258
+ openSync as openSync6,
207259
+ statSync as statSync14,
207260
+ unlinkSync as unlinkSync9,
207261
+ writeSync as writeSync3
207262
+ } from "node:fs";
207263
+ import { dirname as dirname17 } from "node:path";
207264
+ function device(path12) {
207265
+ let candidate = path12;
207266
+ while (!existsSync34(candidate)) {
207267
+ const parent = dirname17(candidate);
207268
+ if (parent === candidate)
207269
+ break;
207270
+ candidate = parent;
207271
+ }
207272
+ return statSync14(candidate).dev;
207273
+ }
207274
+
207275
+ class DiskReserve {
207276
+ path;
207277
+ notify;
207278
+ bytes;
207279
+ constructor(path12, notify2, bytes = DISK_RESERVE_BYTES) {
207280
+ this.path = path12;
207281
+ this.notify = notify2;
207282
+ this.bytes = bytes;
207283
+ }
207284
+ release(writePath) {
207285
+ try {
207286
+ if (device(writePath) !== device(this.path))
207287
+ return false;
207288
+ unlinkSync9(this.path);
207289
+ try {
207290
+ this.notify();
207291
+ } catch {}
207292
+ return true;
207293
+ } catch {
207294
+ return false;
207295
+ }
207296
+ }
207297
+ update(sample2) {
207298
+ try {
207299
+ if (device(sample2.path) !== device(this.path))
207300
+ return false;
207301
+ const used = 1 - sample2.availableBytes / sample2.totalBytes;
207302
+ if (used >= 0.95) {
207303
+ return this.release(sample2.path);
207304
+ }
207305
+ if (used >= 0.9 || sample2.availableBytes - this.bytes <= sample2.totalBytes * 0.1 || sample2.availableBytes - this.bytes < 1024 ** 3 || existsSync34(this.path))
207306
+ return false;
207307
+ mkdirSync30(dirname17(this.path), { recursive: true });
207308
+ const fd = openSync6(this.path, "wx", 384);
207309
+ try {
207310
+ const chunk2 = Buffer.alloc(Math.min(this.bytes, 1024 ** 2));
207311
+ let remaining = this.bytes;
207312
+ while (remaining > 0) {
207313
+ const written = writeSync3(fd, chunk2, 0, Math.min(remaining, chunk2.length));
207314
+ if (written === 0)
207315
+ throw new Error("Reserve allocation made no progress");
207316
+ remaining -= written;
207317
+ }
207318
+ } catch {
207319
+ try {
207320
+ unlinkSync9(this.path);
207321
+ } catch {}
207322
+ } finally {
207323
+ closeSync6(fd);
207324
+ }
207325
+ } catch {}
207326
+ return false;
207327
+ }
207328
+ }
207329
+ function setDiskReserve(reserve) {
207330
+ activeReserve = reserve;
207331
+ }
207332
+ function updateDiskReserve(sample2) {
207333
+ return activeReserve?.update(sample2) ?? false;
207334
+ }
207335
+ function withDiskReserveRetry(path12, operation) {
207336
+ try {
207337
+ return operation();
207338
+ } catch (error4) {
207339
+ if (isManagedCloudRuntime() && typeof error4 === "object" && error4 !== null && "code" in error4 && error4.code === "ENOSPC") {
207340
+ activeReserve?.release(path12);
207341
+ return operation();
207342
+ }
207343
+ throw error4;
207344
+ }
207345
+ }
207346
+ var DISK_RESERVE_BYTES, activeReserve = null;
207347
+ var init_disk_reserve = __esm(() => {
207348
+ DISK_RESERVE_BYTES = 512 * 1024 ** 2;
207349
+ });
207350
+
207351
+ // src/websocket/listener/interrupted-turn-disk-reserve.ts
207352
+ function withInterruptedTurnDiskReserve(directory, store2) {
207353
+ const wrapped = { ...store2 };
207354
+ for (const key2 of writes) {
207355
+ const operation = store2[key2];
207356
+ wrapped[key2] = (...args) => withDiskReserveRetry(directory, () => operation(...args));
207357
+ }
207358
+ return wrapped;
207359
+ }
207360
+ var writes;
207361
+ var init_interrupted_turn_disk_reserve = __esm(() => {
207362
+ init_disk_reserve();
207363
+ writes = [
207364
+ "write",
207365
+ "writeWithRecoveryAuthority",
207366
+ "writeRecoveryLineageSnapshot",
207367
+ "mergeSettledRecoveryResult",
207368
+ "markRecoveryClaimCompletionPending",
207369
+ "retireRecoveryClaimCompletion",
207370
+ "remove",
207371
+ "compactRetiredRecoverySidecar",
207372
+ "removeRetiredRecoverySidecar"
207373
+ ];
207374
+ });
207375
+
207249
207376
  // src/websocket/listener/interrupted-turn-input-ownership.ts
207250
207377
  import { readdirSync as readdirSync11 } from "node:fs";
207251
207378
  import { join as join46 } from "node:path";
@@ -207589,7 +207716,7 @@ Do not use this tool for root memory files (already loaded) or skills/ (use Skil
207589
207716
  var init_Memory = () => {};
207590
207717
 
207591
207718
  // src/tools/descriptions/Monitor.md
207592
- 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';
207719
+ 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';
207593
207720
  var init_Monitor = () => {};
207594
207721
 
207595
207722
  // src/tools/descriptions/Read.md
@@ -207712,7 +207839,7 @@ var ViewImage_default = `View a local image file from the filesystem when visual
207712
207839
  var init_ViewImage = () => {};
207713
207840
 
207714
207841
  // src/tools/descriptions/Wake.md
207715
- 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\nWakes created in a managed Cloud sandbox survive sandbox shutdown; elsewhere they fire only while a listener is active, and the create result warns when none is. For schedules targeting other conversations or computers, load the `scheduling-tasks` skill.\n";
207842
+ 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";
207716
207843
  var init_Wake = () => {};
207717
207844
 
207718
207845
  // src/tools/descriptions/WatchPR.md
@@ -207727,6 +207854,8 @@ The initial result includes current blockers and changes since the previous watc
207727
207854
  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.
207728
207855
 
207729
207856
  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.
207857
+
207858
+ Pass \`resume\` with a paused monitor id to restart it with its saved arguments.
207730
207859
  `;
207731
207860
  var init_WatchPR = () => {};
207732
207861
 
@@ -208566,7 +208695,7 @@ var init_manager = __esm(() => {
208566
208695
 
208567
208696
  // src/tools/impl/artifact-files.ts
208568
208697
  import { mkdir as mkdir9, readFile as readFile11, stat as stat5, writeFile as writeFile12 } from "node:fs/promises";
208569
- import { dirname as dirname18, isAbsolute as isAbsolute10, join as join47, relative as relative4, resolve as resolve14 } from "node:path";
208698
+ import { dirname as dirname19, isAbsolute as isAbsolute10, join as join47, relative as relative4, resolve as resolve14 } from "node:path";
208570
208699
  function assertArtifactsExperimentEnabled(toolName2) {
208571
208700
  if (!experimentManager.isEnabled("artifacts")) {
208572
208701
  throw new Error(`${toolName2}: artifacts experiment is disabled. Enable it with /experiments in Letta Code Desktop.`);
@@ -208635,7 +208764,7 @@ async function write_artifact_file(args) {
208635
208764
  const { absolutePath, relativePath } = resolveArtifactPath(args.path);
208636
208765
  const encoding = getEncoding(args.encoding);
208637
208766
  const buffer = Buffer.from(args.content, encoding);
208638
- await mkdir9(dirname18(absolutePath), { recursive: true });
208767
+ await mkdir9(dirname19(absolutePath), { recursive: true });
208639
208768
  await writeFile12(absolutePath, buffer);
208640
208769
  return {
208641
208770
  path: relativePath,
@@ -209681,15 +209810,15 @@ import { spawnSync as spawnSync4 } from "node:child_process";
209681
209810
  import {
209682
209811
  chmodSync as chmodSync8,
209683
209812
  createWriteStream as createWriteStream3,
209684
- existsSync as existsSync34,
209685
- mkdirSync as mkdirSync30,
209813
+ existsSync as existsSync35,
209814
+ mkdirSync as mkdirSync31,
209686
209815
  readdirSync as readdirSync12,
209687
209816
  renameSync as renameSync9,
209688
209817
  rmSync as rmSync13
209689
209818
  } from "node:fs";
209690
209819
  import { createRequire as createRequire4 } from "node:module";
209691
209820
  import { arch as arch3, platform as platform5 } from "node:os";
209692
- import { dirname as dirname19, isAbsolute as isAbsolute11, join as join48 } from "node:path";
209821
+ import { dirname as dirname20, isAbsolute as isAbsolute11, join as join48 } from "node:path";
209693
209822
  import { Readable as Readable3 } from "node:stream";
209694
209823
  import { pipeline as pipeline4 } from "node:stream/promises";
209695
209824
  import { fileURLToPath as fileURLToPath4 } from "node:url";
@@ -209727,7 +209856,7 @@ function getRipgrepPath(options = {}) {
209727
209856
  const env6 = options.env ?? process.env;
209728
209857
  const config2 = RIPGREP_CONFIG;
209729
209858
  const managedPath = join48(getManagedToolsDir(env6), binaryName(config2));
209730
- if (existsSync34(managedPath) && commandWorks(managedPath, env6)) {
209859
+ if (existsSync35(managedPath) && commandWorks(managedPath, env6)) {
209731
209860
  return managedPath;
209732
209861
  }
209733
209862
  const systemBinaryNames = config2.systemBinaryNames ?? [config2.binaryName];
@@ -209737,7 +209866,7 @@ function getRipgrepPath(options = {}) {
209737
209866
  }
209738
209867
  }
209739
209868
  const bundledPath = getBundledRipgrepPath();
209740
- if (bundledPath && existsSync34(bundledPath) && commandWorks(bundledPath, env6)) {
209869
+ if (bundledPath && existsSync35(bundledPath) && commandWorks(bundledPath, env6)) {
209741
209870
  return bundledPath;
209742
209871
  }
209743
209872
  return null;
@@ -209821,7 +209950,7 @@ function getWindowsTarCommand2() {
209821
209950
  const systemRoot = process.env.SystemRoot ?? process.env.WINDIR;
209822
209951
  if (systemRoot) {
209823
209952
  const systemTar = join48(systemRoot, "System32", "tar.exe");
209824
- if (existsSync34(systemTar)) {
209953
+ if (existsSync35(systemTar)) {
209825
209954
  return systemTar;
209826
209955
  }
209827
209956
  }
@@ -209886,14 +210015,14 @@ async function downloadRipgrep() {
209886
210015
  throw new Error(`Unsupported platform: ${plat}/${architecture}`);
209887
210016
  }
209888
210017
  const toolsDir = getManagedToolsDir();
209889
- mkdirSync30(toolsDir, { recursive: true });
210018
+ mkdirSync31(toolsDir, { recursive: true });
209890
210019
  const downloadUrl = `https://github.com/${config2.repo}/releases/download/${config2.tagPrefix}${version3}/${assetName}`;
209891
210020
  const archivePath = join48(toolsDir, assetName);
209892
210021
  const binaryFileName = binaryName(config2);
209893
210022
  const binaryPath = join48(toolsDir, binaryFileName);
209894
210023
  await downloadFile3(downloadUrl, archivePath);
209895
210024
  const extractDir = join48(toolsDir, `extract_tmp_${config2.binaryName}_${process.pid}_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`);
209896
- mkdirSync30(extractDir, { recursive: true });
210025
+ mkdirSync31(extractDir, { recursive: true });
209897
210026
  try {
209898
210027
  if (assetName.endsWith(".tar.gz")) {
209899
210028
  extractTarGzArchive2(archivePath, extractDir, assetName);
@@ -209907,7 +210036,7 @@ async function downloadRipgrep() {
209907
210036
  join48(extractedDir, binaryFileName),
209908
210037
  join48(extractDir, binaryFileName)
209909
210038
  ];
209910
- let extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync34(candidate));
210039
+ let extractedBinary = extractedBinaryCandidates.find((candidate) => existsSync35(candidate));
209911
210040
  if (!extractedBinary) {
209912
210041
  extractedBinary = findBinaryRecursively2(extractDir, binaryFileName) ?? undefined;
209913
210042
  }
@@ -209964,7 +210093,7 @@ function getRipgrepBinDir(options = {}) {
209964
210093
  const rgPath = getRipgrepPath(options);
209965
210094
  if (!rgPath || !isAbsolute11(rgPath))
209966
210095
  return;
209967
- return dirname19(rgPath);
210096
+ return dirname20(rgPath);
209968
210097
  }
209969
210098
  var TOOLS_DIR_ENV = "LETTA_CODE_TOOLS_DIR", OFFLINE_ENV = "LETTA_CODE_OFFLINE", NETWORK_TIMEOUT_MS = 1e4, DOWNLOAD_TIMEOUT_MS = 120000, APP_USER_AGENT = "letta-code", RIPGREP_CONFIG;
209970
210099
  var init_ripgrep_manager = __esm(() => {
@@ -210003,7 +210132,7 @@ __export(exports_shell_env, {
210003
210132
  getLettaShimDir: () => getLettaShimDir,
210004
210133
  ensureLettaShimDir: () => ensureLettaShimDir
210005
210134
  });
210006
- import { mkdirSync as mkdirSync31, writeFileSync as writeFileSync25 } from "node:fs";
210135
+ import { mkdirSync as mkdirSync32, writeFileSync as writeFileSync25 } from "node:fs";
210007
210136
  import { createRequire as createRequire5 } from "node:module";
210008
210137
  import { tmpdir as tmpdir10 } from "node:os";
210009
210138
  import * as path14 from "node:path";
@@ -210097,7 +210226,7 @@ function ensureLettaShimDir(invocation, electronExecPath = process.versions.elec
210097
210226
  if (!invocation.command)
210098
210227
  return null;
210099
210228
  const shimDir = getLettaShimDir();
210100
- mkdirSync31(shimDir, { recursive: true });
210229
+ mkdirSync32(shimDir, { recursive: true });
210101
210230
  if (process.platform === "win32") {
210102
210231
  const cmdPath = path14.join(shimDir, "letta.cmd");
210103
210232
  const quotedCommand = `"${invocation.command.replaceAll('"', '""')}"`;
@@ -210210,6 +210339,11 @@ function getShellEnv() {
210210
210339
  env6[pathKey] = existingPath ? `${pathPrefixes.join(shellPathDelimiter())}${shellPathDelimiter()}${existingPath}` : pathPrefixes.join(shellPathDelimiter());
210211
210340
  }
210212
210341
  env6.USER_CWD = getCurrentWorkingDirectory();
210342
+ const sessionSource = getRuntimeSessionSource();
210343
+ if (sessionSource)
210344
+ env6.LETTA_RUNTIME_SESSION_SOURCE = sessionSource;
210345
+ else
210346
+ delete env6.LETTA_RUNTIME_SESSION_SOURCE;
210213
210347
  const environmentDeviceId = getRuntimeContext()?.environmentDeviceId?.trim();
210214
210348
  if (environmentDeviceId) {
210215
210349
  env6.LETTA_RUNTIME_ENVIRONMENT_DEVICE_ID = environmentDeviceId;
@@ -210641,7 +210775,7 @@ var init_mcp_originator_resolver = __esm(() => {
210641
210775
 
210642
210776
  // src/backend/api/mcp-subprocess-broker.ts
210643
210777
  import { randomBytes as randomBytes4, timingSafeEqual } from "node:crypto";
210644
- import { chmodSync as chmodSync9, existsSync as existsSync35, unlinkSync as unlinkSync9, writeFileSync as writeFileSync26 } from "node:fs";
210778
+ import { chmodSync as chmodSync9, existsSync as existsSync36, unlinkSync as unlinkSync10, writeFileSync as writeFileSync26 } from "node:fs";
210645
210779
  import { readFile as readFile12 } from "node:fs/promises";
210646
210780
  import {
210647
210781
  createServer as createServer5,
@@ -210876,9 +211010,9 @@ function createMcpSubprocessBroker(options) {
210876
211010
  try {
210877
211011
  server2.close();
210878
211012
  } catch {}
210879
- if (existsSync35(socket)) {
211013
+ if (existsSync36(socket)) {
210880
211014
  try {
210881
- unlinkSync9(socket);
211015
+ unlinkSync10(socket);
210882
211016
  } catch {}
210883
211017
  }
210884
211018
  }
@@ -211830,7 +211964,7 @@ var init_seatbelt = __esm(() => {
211830
211964
 
211831
211965
  // src/sandbox/availability.ts
211832
211966
  import { spawnSync as spawnSync5 } from "node:child_process";
211833
- import { existsSync as existsSync36 } from "node:fs";
211967
+ import { existsSync as existsSync37 } from "node:fs";
211834
211968
  import { delimiter as delimiter4, isAbsolute as isAbsolute13, join as join51 } from "node:path";
211835
211969
  function detectSandboxBackend(options = {}) {
211836
211970
  const platform7 = options.platform ?? process.platform;
@@ -211862,7 +211996,7 @@ function warnSandboxBackendUnavailable(availability, context3) {
211862
211996
  }
211863
211997
  function probe(platform7) {
211864
211998
  if (platform7 === "darwin") {
211865
- if (existsSync36(SANDBOX_EXEC_PATH)) {
211999
+ if (existsSync37(SANDBOX_EXEC_PATH)) {
211866
212000
  return { backend: "seatbelt", reason: "sandbox-exec available" };
211867
212001
  }
211868
212002
  return {
@@ -211897,13 +212031,13 @@ function probeBwrap() {
211897
212031
  return { backend: "bwrap", bwrapPath, reason: "bwrap available" };
211898
212032
  }
211899
212033
  function resolveExecutableOnPath(executable, envPath = process.env.PATH) {
211900
- if (isAbsolute13(executable) && existsSync36(executable))
212034
+ if (isAbsolute13(executable) && existsSync37(executable))
211901
212035
  return executable;
211902
212036
  for (const dir of (envPath ?? "").split(delimiter4)) {
211903
212037
  if (!dir)
211904
212038
  continue;
211905
212039
  const candidate = join51(dir, executable);
211906
- if (existsSync36(candidate))
212040
+ if (existsSync37(candidate))
211907
212041
  return candidate;
211908
212042
  }
211909
212043
  return null;
@@ -211916,7 +212050,7 @@ var init_availability = __esm(() => {
211916
212050
 
211917
212051
  // src/permissions/memory-paths.ts
211918
212052
  import { homedir as homedir10 } from "node:os";
211919
- import { basename as basename19, dirname as dirname21, isAbsolute as isAbsolute14, resolve as resolve16 } from "node:path";
212053
+ import { basename as basename19, dirname as dirname22, isAbsolute as isAbsolute14, resolve as resolve16 } from "node:path";
211920
212054
  function normalizeMemoryPath(path16) {
211921
212055
  const resolvedPath = resolve16(expandHomePath(path16));
211922
212056
  const normalized = resolvedPath.replace(/\\/g, "/");
@@ -211963,7 +212097,7 @@ function addRootAndSiblingWorktree(root2, acc) {
211963
212097
  acc.add(normalizedRoot);
211964
212098
  const leaf = basename19(normalizedRoot);
211965
212099
  if (leaf === "memory") {
211966
- acc.add(normalizeMemoryPath(resolve16(dirname21(normalizedRoot), "memory-worktrees")));
212100
+ acc.add(normalizeMemoryPath(resolve16(dirname22(normalizedRoot), "memory-worktrees")));
211967
212101
  }
211968
212102
  }
211969
212103
  function getExplicitEnvRoots(env6) {
@@ -212042,9 +212176,9 @@ var init_memory_paths = __esm(() => {
212042
212176
  });
212043
212177
 
212044
212178
  // src/permissions/sandbox-policy.ts
212045
- import { existsSync as existsSync37, realpathSync as realpathSync6 } from "node:fs";
212179
+ import { existsSync as existsSync38, realpathSync as realpathSync6 } from "node:fs";
212046
212180
  import { homedir as homedir11 } from "node:os";
212047
- import { basename as basename20, dirname as dirname22, isAbsolute as isAbsolute15, join as join52, resolve as resolve17 } from "node:path";
212181
+ import { basename as basename20, dirname as dirname23, isAbsolute as isAbsolute15, join as join52, resolve as resolve17 } from "node:path";
212048
212182
  function getCrossBackendAgentsTreeRoots(options = {}) {
212049
212183
  const homeDir = options.homeDir;
212050
212184
  const env6 = options.env ?? process.env;
@@ -212072,9 +212206,9 @@ function canonicalizeRoot(input) {
212072
212206
  const abs = isAbsolute15(input) ? input : resolve17(input);
212073
212207
  let dir = abs;
212074
212208
  const tail2 = [];
212075
- while (!existsSync37(dir)) {
212209
+ while (!existsSync38(dir)) {
212076
212210
  tail2.unshift(basename20(dir));
212077
- const parent = dirname22(dir);
212211
+ const parent = dirname23(dir);
212078
212212
  if (parent === dir) {
212079
212213
  return normalizeSandboxPath(abs);
212080
212214
  }
@@ -212108,8 +212242,8 @@ function deriveSelfAgentRootsForTrees(memoryRoots, agentsTreeRoots = getCrossBac
212108
212242
  const containingTree = canonicalTrees.find((tree) => canon !== tree && isWithinRoot(canon, tree));
212109
212243
  if (containingTree) {
212110
212244
  const leaf = basename20(canon);
212111
- const parentLeaf = basename20(dirname22(canon));
212112
- out.add(leaf === "memory" || leaf === "memory-worktrees" ? dirname22(canon) : parentLeaf === "memory-worktrees" || parentLeaf === "memory" && leaf === ".git" ? dirname22(dirname22(canon)) : canon);
212245
+ const parentLeaf = basename20(dirname23(canon));
212246
+ out.add(leaf === "memory" || leaf === "memory-worktrees" ? dirname23(canon) : parentLeaf === "memory-worktrees" || parentLeaf === "memory" && leaf === ".git" ? dirname23(dirname23(canon)) : canon);
212113
212247
  continue;
212114
212248
  }
212115
212249
  if (!isTreeOrAncestorOfTree(canon, canonicalTrees)) {
@@ -212872,7 +213006,7 @@ var init_cross_agent_guard = __esm(() => {
212872
213006
  });
212873
213007
 
212874
213008
  // src/permissions/workspace-sandbox.ts
212875
- import { statSync as statSync14 } from "node:fs";
213009
+ import { statSync as statSync15 } from "node:fs";
212876
213010
  import { isAbsolute as isAbsolute16, resolve as resolve18 } from "node:path";
212877
213011
  function resolveWorkspaceSandbox(input, options = {}) {
212878
213012
  if (!isAbsolute16(input.root) || !isAbsolute16(input.isolationRoot)) {
@@ -212880,10 +213014,10 @@ function resolveWorkspaceSandbox(input, options = {}) {
212880
213014
  }
212881
213015
  const root2 = canonicalizeRoot(input.root);
212882
213016
  const isolationRoot = canonicalizeRoot(input.isolationRoot);
212883
- if (!statSync14(root2, { throwIfNoEntry: false })?.isDirectory()) {
213017
+ if (!statSync15(root2, { throwIfNoEntry: false })?.isDirectory()) {
212884
213018
  throw new Error("workspace sandbox root must be an existing directory");
212885
213019
  }
212886
- if (!statSync14(isolationRoot, { throwIfNoEntry: false })?.isDirectory()) {
213020
+ if (!statSync15(isolationRoot, { throwIfNoEntry: false })?.isDirectory()) {
212887
213021
  throw new Error("workspace sandbox isolation root must be an existing directory");
212888
213022
  }
212889
213023
  if (root2 === isolationRoot || !root2.startsWith(`${isolationRoot}/`)) {
@@ -213915,104 +214049,6 @@ var init_client_tool_serialization = __esm(() => {
213915
214049
  init_debug();
213916
214050
  });
213917
214051
 
213918
- // src/utils/disk-reserve.ts
213919
- import {
213920
- closeSync as closeSync6,
213921
- existsSync as existsSync39,
213922
- mkdirSync as mkdirSync33,
213923
- openSync as openSync6,
213924
- statSync as statSync16,
213925
- unlinkSync as unlinkSync11,
213926
- writeSync as writeSync3
213927
- } from "node:fs";
213928
- import { dirname as dirname23 } from "node:path";
213929
- function device(path17) {
213930
- let candidate = path17;
213931
- while (!existsSync39(candidate)) {
213932
- const parent = dirname23(candidate);
213933
- if (parent === candidate)
213934
- break;
213935
- candidate = parent;
213936
- }
213937
- return statSync16(candidate).dev;
213938
- }
213939
-
213940
- class DiskReserve {
213941
- path;
213942
- notify;
213943
- bytes;
213944
- constructor(path17, notify2, bytes = DISK_RESERVE_BYTES) {
213945
- this.path = path17;
213946
- this.notify = notify2;
213947
- this.bytes = bytes;
213948
- }
213949
- release(writePath) {
213950
- try {
213951
- if (device(writePath) !== device(this.path))
213952
- return false;
213953
- unlinkSync11(this.path);
213954
- try {
213955
- this.notify();
213956
- } catch {}
213957
- return true;
213958
- } catch {
213959
- return false;
213960
- }
213961
- }
213962
- update(sample2) {
213963
- try {
213964
- if (device(sample2.path) !== device(this.path))
213965
- return false;
213966
- const used = 1 - sample2.availableBytes / sample2.totalBytes;
213967
- if (used >= 0.95) {
213968
- return this.release(sample2.path);
213969
- }
213970
- if (used >= 0.9 || sample2.availableBytes - this.bytes <= sample2.totalBytes * 0.1 || sample2.availableBytes - this.bytes < 1024 ** 3 || existsSync39(this.path))
213971
- return false;
213972
- mkdirSync33(dirname23(this.path), { recursive: true });
213973
- const fd = openSync6(this.path, "wx", 384);
213974
- try {
213975
- const chunk2 = Buffer.alloc(Math.min(this.bytes, 1024 ** 2));
213976
- let remaining = this.bytes;
213977
- while (remaining > 0) {
213978
- const written = writeSync3(fd, chunk2, 0, Math.min(remaining, chunk2.length));
213979
- if (written === 0)
213980
- throw new Error("Reserve allocation made no progress");
213981
- remaining -= written;
213982
- }
213983
- } catch {
213984
- try {
213985
- unlinkSync11(this.path);
213986
- } catch {}
213987
- } finally {
213988
- closeSync6(fd);
213989
- }
213990
- } catch {}
213991
- return false;
213992
- }
213993
- }
213994
- function setDiskReserve(reserve) {
213995
- activeReserve = reserve;
213996
- }
213997
- function updateDiskReserve(sample2) {
213998
- return activeReserve?.update(sample2) ?? false;
213999
- }
214000
- function withDiskReserveRetry(path17, operation) {
214001
- try {
214002
- return operation();
214003
- } catch (error4) {
214004
- if (isManagedCloudRuntime() && typeof error4 === "object" && error4 !== null && "code" in error4 && error4.code === "ENOSPC") {
214005
- activeReserve?.release(path17);
214006
- return operation();
214007
- }
214008
- throw error4;
214009
- }
214010
- }
214011
- var DISK_RESERVE_BYTES, activeReserve = null;
214012
- var init_disk_reserve = __esm(() => {
214013
- DISK_RESERVE_BYTES = 512 * 1024 ** 2;
214014
- });
214015
-
214016
214052
  // src/reminders/disk-space.ts
214017
214053
  import { statfs } from "node:fs/promises";
214018
214054
  import { join as join54 } from "node:path";
@@ -217141,6 +217177,14 @@ async function resolveBackendSpecificToolAssets(name, description, inputSchema)
217141
217177
  inputSchema: MonitorCloud_default2
217142
217178
  };
217143
217179
  }
217180
+ if (name === "Wake" && getRuntimeSessionSource() === "interactive-cli" && process.env.LETTA_DESKTOP_MODE !== "1") {
217181
+ return {
217182
+ description: `${description.trimEnd()}
217183
+
217184
+ Wakes fire only while this session is running.`,
217185
+ inputSchema
217186
+ };
217187
+ }
217144
217188
  if (name !== "Task") {
217145
217189
  return { description, inputSchema };
217146
217190
  }
@@ -217161,6 +217205,7 @@ async function resolveBackendSpecificToolAssets(name, description, inputSchema)
217161
217205
  var init_task_tool_assets = __esm(() => {
217162
217206
  init_backend2();
217163
217207
  init_manager();
217208
+ init_runtime_context();
217164
217209
  init_MonitorCloud();
217165
217210
  init_MonitorCloud2();
217166
217211
  });
@@ -233595,20 +233640,49 @@ function isManagedCloudSandbox(env6 = process.env) {
233595
233640
  }
233596
233641
  function resolveCronRunner(params) {
233597
233642
  const { managedCloudSandbox, backendMode, cloudSchedulesSupported } = params;
233598
- if (!managedCloudSandbox) {
233643
+ if (managedCloudSandbox) {
233644
+ if (backendMode === "local") {
233645
+ return {
233646
+ error: "Scheduling requires the API backend. Configure it, then retry."
233647
+ };
233648
+ }
233649
+ if (cloudSchedulesSupported === false) {
233650
+ return {
233651
+ error: "Scheduling is unavailable. Check the server connection, then retry."
233652
+ };
233653
+ }
233654
+ return { runner: "cloud", reason: "managed Cloud sandbox" };
233655
+ }
233656
+ if (backendMode === "local" || params.localSchedulesAllowed) {
233599
233657
  return { runner: "local", reason: "local execution environment" };
233600
233658
  }
233601
- if (backendMode === "local") {
233602
- return {
233603
- error: "Managed Cloud sandboxes cannot use the local backend for schedules."
233659
+ if (cloudSchedulesSupported === false) {
233660
+ return params.cloudServer === false ? { runner: "local", reason: "server has no schedule routes" } : {
233661
+ error: "Scheduling is unavailable. Check the server connection, then retry."
233604
233662
  };
233605
233663
  }
233606
- if (cloudSchedulesSupported === false) {
233664
+ if (params.listenerDeviceId) {
233607
233665
  return {
233608
- error: "Cloud schedules are unavailable in this managed Cloud sandbox. No local schedule was created."
233666
+ runner: "cloud",
233667
+ reason: "registered listener",
233668
+ targetDeviceId: params.listenerDeviceId
233609
233669
  };
233610
233670
  }
233611
- return { runner: "cloud", reason: "managed Cloud sandbox" };
233671
+ return {
233672
+ error: "Register this computer with `letta server`, then retry."
233673
+ };
233674
+ }
233675
+ function allowsLocalCloudSchedules() {
233676
+ return process.env.LETTA_DESKTOP_MODE === "1" || getRuntimeSessionSource() === "interactive-cli";
233677
+ }
233678
+ function getLocalCronExecutionError(action = "run") {
233679
+ if (isManagedCloudSandbox()) {
233680
+ return `This schedule cannot ${action === "run" ? "run" : `be ${action}`} here. Create a replacement with Wake or letta cron.`;
233681
+ }
233682
+ if (resolveBackendMode() === "api" && isCloudServerUrl() && !allowsLocalCloudSchedules()) {
233683
+ return `This schedule cannot ${action === "run" ? "run" : `be ${action}`} here. Create a replacement with Wake or letta cron.`;
233684
+ }
233685
+ return;
233612
233686
  }
233613
233687
  async function ensureSettingsForCloud() {
233614
233688
  const { settingsManager: settingsManager2 } = await Promise.resolve().then(() => (init_settings_manager(), exports_settings_manager));
@@ -233626,37 +233700,53 @@ async function probeCloudScheduleSupport(agentId) {
233626
233700
  }
233627
233701
  }
233628
233702
  async function resolveCronRunnerForAgent(agentId) {
233629
- const backendMode = resolveBackendMode();
233703
+ const backendMode = isLocalAgentId(agentId) ? "local" : resolveBackendMode();
233630
233704
  const managedCloudSandbox = isManagedCloudSandbox();
233631
- const preliminary = resolveCronRunner({ managedCloudSandbox, backendMode });
233632
- if ("error" in preliminary || preliminary.runner === "local") {
233633
- return preliminary;
233705
+ const localSchedulesAllowed = allowsLocalCloudSchedules();
233706
+ const cloudServer = isCloudServerUrl();
233707
+ if (backendMode === "local" || !managedCloudSandbox && localSchedulesAllowed) {
233708
+ return resolveCronRunner({
233709
+ managedCloudSandbox,
233710
+ backendMode,
233711
+ localSchedulesAllowed
233712
+ });
233713
+ }
233714
+ const deviceId = getRuntimeContext()?.environmentDeviceId?.trim() || process.env.LETTA_RUNTIME_ENVIRONMENT_DEVICE_ID?.trim();
233715
+ let listenerDeviceId;
233716
+ if (!managedCloudSandbox && deviceId) {
233717
+ const environment = await lookupEnvironmentForTarget(deviceId);
233718
+ if (environment && validateTargetDevice(deviceId, environment).ok) {
233719
+ listenerDeviceId = deviceId;
233720
+ }
233634
233721
  }
233635
233722
  await ensureSettingsForCloud();
233636
233723
  const cloudSchedulesSupported = await probeCloudScheduleSupport(agentId);
233637
233724
  return resolveCronRunner({
233638
233725
  managedCloudSandbox,
233639
233726
  backendMode,
233640
- cloudSchedulesSupported
233727
+ cloudSchedulesSupported,
233728
+ listenerDeviceId,
233729
+ localSchedulesAllowed,
233730
+ cloudServer
233641
233731
  });
233642
233732
  }
233643
233733
  function validateTargetDevice(deviceId, environment) {
233644
233734
  if (deviceId === SYNTHETIC_CLOUD_DEVICE_ID) {
233645
233735
  return {
233646
233736
  ok: false,
233647
- error: `"Cloud" is not a computer. Omit --computer to run in the agent's Cloud sandbox.`
233737
+ error: "Choose a computer from `letta computers list`."
233648
233738
  };
233649
233739
  }
233650
233740
  if (deviceId === SYNTHETIC_LOCAL_PLACEHOLDER_ID) {
233651
233741
  return {
233652
233742
  ok: false,
233653
- error: '"local" is a placeholder entry, not a connected computer. Run `letta server` on the machine you want to target, then use its deviceId.'
233743
+ error: "Choose a connected computer from `letta computers list`. Run `letta server` on that computer to connect it."
233654
233744
  };
233655
233745
  }
233656
233746
  if (environment?.organizationId === "local") {
233657
233747
  return {
233658
233748
  ok: false,
233659
- error: `Device ${deviceId} is this computer's local desktop connection, not a computer connected to your Letta account. Cloud schedules can only target connected computers — run \`letta server\` on that machine to connect it.`
233749
+ error: `Device ${deviceId} is not connected to your account. Run \`letta server\` on that computer to connect it.`
233660
233750
  };
233661
233751
  }
233662
233752
  return { ok: true };
@@ -233704,11 +233794,17 @@ async function resolveCronCreatePlacement(params) {
233704
233794
  const targetDeviceId = params.targetDeviceId?.trim() || undefined;
233705
233795
  if (targetDeviceId && resolved.runner !== "cloud") {
233706
233796
  return {
233707
- error: "--computer is only available from a managed Cloud sandbox. Run the schedule on this computer instead."
233797
+ error: "--computer isn't available here."
233798
+ };
233799
+ }
233800
+ if (!targetDeviceId) {
233801
+ return {
233802
+ runner: resolved.runner,
233803
+ ...resolved.targetDeviceId && {
233804
+ targetDeviceId: resolved.targetDeviceId
233805
+ }
233708
233806
  };
233709
233807
  }
233710
- if (!targetDeviceId)
233711
- return { runner: resolved.runner };
233712
233808
  const selectorValidity = validateTargetDevice(targetDeviceId, null);
233713
233809
  if (!selectorValidity.ok)
233714
233810
  return selectorValidity;
@@ -233735,7 +233831,7 @@ function buildCloudScheduleInput(params) {
233735
233831
  } else {
233736
233832
  const scheduledAt = params.scheduledFor?.getTime();
233737
233833
  if (!scheduledAt || Number.isNaN(scheduledAt)) {
233738
- throw new Error("One-shot Cloud schedules require a resolved --at time.");
233834
+ throw new Error("One-shot schedules require a resolved --at time.");
233739
233835
  }
233740
233836
  schedule = { type: "one-time", scheduled_at: scheduledAt };
233741
233837
  }
@@ -233755,11 +233851,13 @@ function buildCloudScheduleInput(params) {
233755
233851
  notes
233756
233852
  };
233757
233853
  }
233758
- var CLOUD_EXECUTION_TARGET = "cloud-sandbox", SYNTHETIC_CLOUD_DEVICE_ID = "__letta_cloud__", SYNTHETIC_LOCAL_PLACEHOLDER_ID = "local", CLOUD_CRON_UTC_NOTE = "Recurring Cloud schedules currently interpret cron expressions in UTC (timezone support is tracked in LET-9815).", CLOUD_DEVICE_OFFLINE_NOTE = "If the target computer is offline when the schedule fires, that occurrence fails (TARGET_DEVICE_UNAVAILABLE) and does not run; omit --computer to run in the Cloud sandbox.";
233854
+ var SYNTHETIC_CLOUD_DEVICE_ID = "__letta_cloud__", SYNTHETIC_LOCAL_PLACEHOLDER_ID = "local", CLOUD_CRON_UTC_NOTE = "Recurring schedules interpret cron expressions in UTC.", CLOUD_DEVICE_OFFLINE_NOTE = "If the target computer is offline when the schedule fires, that occurrence fails (TARGET_DEVICE_UNAVAILABLE) and does not run.";
233759
233855
  var init_runner = __esm(() => {
233760
233856
  init_request();
233761
233857
  init_schedules();
233858
+ init_server_url();
233762
233859
  init_backend_mode();
233860
+ init_runtime_context();
233763
233861
  });
233764
233862
 
233765
233863
  // src/tools/impl/wake.ts
@@ -233843,7 +233941,6 @@ function promptFromCloudSchedule(schedule) {
233843
233941
  function localWakeRecord(task) {
233844
233942
  return {
233845
233943
  id: task.id,
233846
- runner: "local",
233847
233944
  name: task.name,
233848
233945
  prompt: task.prompt,
233849
233946
  recurring: task.recurring,
@@ -233855,7 +233952,6 @@ function localWakeRecord(task) {
233855
233952
  function cloudWakeRecord(schedule) {
233856
233953
  return {
233857
233954
  id: schedule.id,
233858
- runner: "cloud",
233859
233955
  name: schedule.name ?? null,
233860
233956
  prompt: promptFromCloudSchedule(schedule),
233861
233957
  recurring: schedule.schedule.type === "recurring",
@@ -233884,7 +233980,7 @@ async function listCurrentWakes(scope, args, deps) {
233884
233980
  if (error4 instanceof ApiRequestError && (error4.status === 404 || error4.status === 405)) {
233885
233981
  return { wakes, warnings };
233886
233982
  }
233887
- warnings.push(`Cloud wakes could not be listed: ${error4 instanceof Error ? error4.message : String(error4)}`);
233983
+ warnings.push(`Wakes could not be listed: ${error4 instanceof Error ? error4.message : String(error4)}`);
233888
233984
  }
233889
233985
  return { wakes, warnings };
233890
233986
  }
@@ -233937,8 +234033,7 @@ async function createWake(args, scope, deps) {
233937
234033
  action: "created",
233938
234034
  id: created2.id,
233939
234035
  name,
233940
- runner: "cloud",
233941
- execution_target: targetDeviceId ?? CLOUD_EXECUTION_TARGET,
234036
+ ...targetDeviceId && { execution_target: targetDeviceId },
233942
234037
  conversation_id: scope.conversationId,
233943
234038
  recurring: timing2.recurring,
233944
234039
  ...created2.next_scheduled_at && {
@@ -233959,12 +234054,14 @@ async function createWake(args, scope, deps) {
233959
234054
  scheduled_for: timing2.scheduledFor
233960
234055
  };
233961
234056
  const created = (deps.addLocal ?? addTask)(input);
233962
- const warnings = [...current.warnings, created.warning].filter((warning) => Boolean(warning));
234057
+ const warnings = [
234058
+ ...current.warnings,
234059
+ created.warning ? "This wake only fires while this session is running." : undefined
234060
+ ].filter((warning) => Boolean(warning));
233963
234061
  return result2("success", {
233964
234062
  action: "created",
233965
234063
  id: created.task.id,
233966
234064
  name,
233967
- runner: "local",
233968
234065
  conversation_id: scope.conversationId,
233969
234066
  recurring: timing2.recurring,
233970
234067
  scheduled_at: created.task.scheduled_for,
@@ -233984,7 +234081,6 @@ async function cancelWake(args, scope, deps) {
233984
234081
  return result2("success", {
233985
234082
  action: "cancelled",
233986
234083
  id,
233987
- runner: "local",
233988
234084
  warnings: []
233989
234085
  });
233990
234086
  }
@@ -234008,7 +234104,6 @@ async function cancelWake(args, scope, deps) {
234008
234104
  return result2("success", {
234009
234105
  action: "cancelled",
234010
234106
  id,
234011
- runner: "cloud",
234012
234107
  warnings: []
234013
234108
  });
234014
234109
  }
@@ -234362,6 +234457,110 @@ Output file: ${outputFile}` : ""}`
234362
234457
  };
234363
234458
  }
234364
234459
 
234460
+ // src/backend/api/monitors.ts
234461
+ function isLegacyMonitorValidation(error4, operation) {
234462
+ if (!(error4 instanceof ApiRequestError) || error4.status !== 400)
234463
+ return false;
234464
+ try {
234465
+ const body3 = JSON.parse(error4.responseText);
234466
+ if (body3.detail === "Invalid request")
234467
+ return true;
234468
+ return body3.issues?.some((issue2) => operation === "create" ? issue2.code === "unrecognized_keys" && Boolean(issue2.keys?.length) && issue2.keys?.every((key2) => key2 === "args" || key2 === "expires_at") : issue2.code === "invalid_enum_value" && issue2.path?.[0] === "status") ?? false;
234469
+ } catch {
234470
+ return false;
234471
+ }
234472
+ }
234473
+ async function createMonitorState(input, actingUserId) {
234474
+ try {
234475
+ return await apiRequest("POST", "/v1/monitors", input, {
234476
+ actingUserId,
234477
+ signal: AbortSignal.timeout(15000)
234478
+ });
234479
+ } catch (error4) {
234480
+ if (!isLegacyMonitorValidation(error4, "create"))
234481
+ throw error4;
234482
+ const { args: _args, expires_at: _expires, ...legacy } = input;
234483
+ return apiRequest("POST", "/v1/monitors", legacy, {
234484
+ actingUserId,
234485
+ signal: AbortSignal.timeout(15000)
234486
+ });
234487
+ }
234488
+ }
234489
+ async function updateMonitorState(id, input, actingUserId) {
234490
+ const path28 = `/v1/monitors/${encodeURIComponent(id)}`;
234491
+ try {
234492
+ return await apiRequest("PATCH", path28, input, {
234493
+ actingUserId,
234494
+ signal: AbortSignal.timeout(15000)
234495
+ });
234496
+ } catch (error4) {
234497
+ if (!isLegacyMonitorValidation(error4, "update") || !["expired", "stopped", "paused"].includes(input.status))
234498
+ throw error4;
234499
+ return apiRequest("PATCH", path28, { ...input, status: "failed" }, { actingUserId, signal: AbortSignal.timeout(15000) });
234500
+ }
234501
+ }
234502
+ async function retrieveMonitorState(id) {
234503
+ try {
234504
+ return await apiRequest("GET", `/v1/monitors/${encodeURIComponent(id)}`, undefined, { signal: AbortSignal.timeout(15000) });
234505
+ } catch (error4) {
234506
+ if (error4 instanceof ApiRequestError && error4.status === 404)
234507
+ throw new Error(`Monitor ${id} was not found or this server does not support monitor resume.`);
234508
+ throw error4;
234509
+ }
234510
+ }
234511
+ function listMonitorStates(scope) {
234512
+ return apiRequest("GET", "/v1/monitors", undefined, {
234513
+ query: { ...scope, limit: 200 },
234514
+ signal: AbortSignal.timeout(15000)
234515
+ });
234516
+ }
234517
+ var init_monitors = __esm(() => {
234518
+ init_request();
234519
+ });
234520
+
234521
+ // src/tools/impl/monitor-resume.ts
234522
+ async function readResumableMonitor(id, parentScope) {
234523
+ if (resolveBackendMode() === "local")
234524
+ throw new Error("Saved monitor resume requires the API backend.");
234525
+ const record4 = await retrieveMonitorState(id);
234526
+ const runtime = getRuntimeContext();
234527
+ const scope = runtime?.agentId === null && runtime.conversationId ? { agentId: null, conversationId: runtime.conversationId } : resolveNotificationScope(parentScope);
234528
+ if (scope && (record4.agent_id !== scope.agentId || (record4.conversation_id ?? "default") !== scope.conversationId))
234529
+ throw new Error("Resume the monitor in its original conversation.");
234530
+ if (record4.status === "expired")
234531
+ throw new Error(`Monitor ${id} has expired; start a new monitor instead.`);
234532
+ if (record4.status !== "paused")
234533
+ throw new Error(`Monitor ${id} is ${record4.status}; only paused monitors can resume.`);
234534
+ if (record4.expires_at && Date.parse(record4.expires_at) <= Date.now()) {
234535
+ await updateMonitorState(id, {
234536
+ status: "expired",
234537
+ exit_code: null,
234538
+ output_file: record4.output_file
234539
+ });
234540
+ throw new Error(`Monitor ${id} has expired; start a new monitor instead.`);
234541
+ }
234542
+ if (!record4.args || !Object.keys(record4.args).length)
234543
+ throw new Error(`Monitor ${id} has no saved tool arguments; start a new monitor instead.`);
234544
+ return record4;
234545
+ }
234546
+ function savedMonitorArgs(input) {
234547
+ const omitted = new Set([
234548
+ "parentScope",
234549
+ "signal",
234550
+ "secretEnv",
234551
+ "variableEnv",
234552
+ "toolCallId",
234553
+ "resume"
234554
+ ]);
234555
+ return Object.fromEntries(Object.entries(input).filter(([key2]) => !omitted.has(key2)));
234556
+ }
234557
+ var init_monitor_resume = __esm(() => {
234558
+ init_monitors();
234559
+ init_backend_mode();
234560
+ init_runtime_context();
234561
+ init_task_notifications();
234562
+ });
234563
+
234365
234564
  // src/tools/impl/monitor-script.ts
234366
234565
  function createCallLimiter(signal) {
234367
234566
  let tokens = TOOL_CALL_BURST;
@@ -234444,7 +234643,7 @@ async function startScriptMonitor(args, hooks) {
234444
234643
  processState.completionNotificationSuppressed = true;
234445
234644
  if (note)
234446
234645
  output.append(note);
234447
- hooks.markFinished(taskId, processState, "failed", null);
234646
+ hooks.markFinished(taskId, processState, reason === "timeout" ? "expired" : "failed", null);
234448
234647
  controller.abort(new Error(reason));
234449
234648
  };
234450
234649
  const events = createMonitorEventStream({
@@ -234589,23 +234788,6 @@ var init_monitor_script = __esm(() => {
234589
234788
  init_process_manager();
234590
234789
  });
234591
234790
 
234592
- // src/backend/api/monitors.ts
234593
- function createMonitorState(input, actingUserId) {
234594
- return apiRequest("POST", "/v1/monitors", input, {
234595
- actingUserId,
234596
- signal: AbortSignal.timeout(15000)
234597
- });
234598
- }
234599
- function updateMonitorState(id, input, actingUserId) {
234600
- return apiRequest("PATCH", `/v1/monitors/${encodeURIComponent(id)}`, input, {
234601
- actingUserId,
234602
- signal: AbortSignal.timeout(15000)
234603
- });
234604
- }
234605
- var init_monitors = __esm(() => {
234606
- init_request();
234607
- });
234608
-
234609
234791
  // src/tools/impl/monitor-state.ts
234610
234792
  async function withMonitorState(input, start) {
234611
234793
  if (resolveBackendMode() === "local")
@@ -234619,7 +234801,8 @@ async function withMonitorState(input, start) {
234619
234801
  ...captureSecretRedactions(scope.agentId ?? undefined),
234620
234802
  ...input.secretEnv
234621
234803
  };
234622
- const record4 = await createMonitorState({
234804
+ const startedAt = new Date().toISOString();
234805
+ const record4 = input.resumeRecord ?? await createMonitorState({
234623
234806
  agent_id: scope.agentId || null,
234624
234807
  conversation_id: scope.conversationId,
234625
234808
  description: scrubSecretsFromString(input.description, secrets2),
@@ -234628,12 +234811,24 @@ async function withMonitorState(input, start) {
234628
234811
  persistent: input.persistent,
234629
234812
  status: "running",
234630
234813
  device_id: getRuntimeContext()?.environmentDeviceId ?? null,
234631
- started_at: new Date().toISOString(),
234814
+ started_at: startedAt,
234815
+ expires_at: input.timeoutMs ? new Date(Date.now() + input.timeoutMs).toISOString() : null,
234816
+ args: JSON.parse(JSON.stringify(input.args ?? {}, (_key, value) => typeof value === "string" ? scrubSecretsFromString(value, secrets2) : value)),
234632
234817
  output_file: null,
234633
234818
  exit_code: null
234634
234819
  }, actingUserId);
234635
234820
  const id = record4.monitor_id;
234821
+ if (backgroundProcesses.get(id)?.status === "running")
234822
+ throw new Error(`Monitor ${id} is already running on this host`);
234636
234823
  try {
234824
+ if (input.resumeRecord) {
234825
+ await updateMonitorState(id, {
234826
+ status: "running",
234827
+ exit_code: null,
234828
+ output_file: record4.output_file,
234829
+ device_id: getRuntimeContext()?.environmentDeviceId ?? record4.device_id
234830
+ }, actingUserId);
234831
+ }
234637
234832
  input.signal?.throwIfAborted();
234638
234833
  const result3 = await start(id);
234639
234834
  const process21 = backgroundProcesses.get(id);
@@ -234641,8 +234836,11 @@ async function withMonitorState(input, start) {
234641
234836
  throw new Error("Monitor did not register its process");
234642
234837
  let pending2 = Promise.resolve();
234643
234838
  process21.persistState = () => {
234839
+ let status = process21.monitorEndStatus ?? process21.status;
234840
+ if (record4.args === undefined && ["expired", "stopped", "paused"].includes(status))
234841
+ status = "failed";
234644
234842
  const state2 = {
234645
- status: process21.status,
234843
+ status,
234646
234844
  exit_code: process21.exitCode,
234647
234845
  output_file: process21.outputFile ?? null
234648
234846
  };
@@ -234707,6 +234905,9 @@ function formatMonitorMaxTimeout(timeoutMs = getMonitorMaxTimeoutMs()) {
234707
234905
  function applyMonitorMaxTimeout(text2, timeoutMs = getMonitorMaxTimeoutMs()) {
234708
234906
  return text2.replaceAll("{{MONITOR_MAX_TIMEOUT}}", formatMonitorMaxTimeout(timeoutMs));
234709
234907
  }
234908
+ 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.]";
234910
+ }
234710
234911
  var HOUR_MS = 3600000, DAY_MS, DEFAULT_MAX_TIMEOUT_MS, SEVEN_DAYS_MS;
234711
234912
  var init_monitor_timeout = __esm(() => {
234712
234913
  DAY_MS = 24 * HOUR_MS;
@@ -234909,9 +235110,6 @@ var init_monitor_url_cloud = __esm(() => {
234909
235110
  // src/tools/impl/monitor.ts
234910
235111
  import { appendFileSync as appendFileSync7, readFileSync as readFileSync38, writeFileSync as writeFileSync30 } from "node:fs";
234911
235112
  import { WebSocket as WebSocket4 } from "ws";
234912
- function getMonitorTimeoutEvent(timeoutMs, tool = "Monitor") {
234913
- 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.]";
234914
- }
234915
235113
  function validUtf8Prefix(buffer, maxBytes) {
234916
235114
  let end = Math.min(buffer.length, maxBytes);
234917
235115
  while (end > Math.max(0, maxBytes - 4)) {
@@ -235000,13 +235198,14 @@ function validateWebSocketSource(source) {
235000
235198
  function normalizeMonitorArgs(args) {
235001
235199
  const normalized = {
235002
235200
  ...args,
235201
+ description: args.description ?? "",
235003
235202
  timeout_ms: args.timeout_ms ?? DEFAULT_TIMEOUT_MS3,
235004
235203
  persistent: args.persistent ?? false
235005
235204
  };
235006
- if (typeof normalized.description !== "string") {
235205
+ if (typeof args.description !== "string") {
235007
235206
  throw new Error("Monitor description is required");
235008
235207
  }
235009
- if (typeof normalized.timeout_ms !== "number" || !Number.isFinite(normalized.timeout_ms) || normalized.timeout_ms < MIN_TIMEOUT_MS || !normalized.persistent && normalized.timeout_ms > getMonitorMaxTimeoutMs()) {
235208
+ if (typeof normalized.timeout_ms !== "number" || !Number.isFinite(normalized.timeout_ms) || normalized.timeout_ms < (args.resume ? 1 : MIN_TIMEOUT_MS) || !normalized.persistent && normalized.timeout_ms > getMonitorMaxTimeoutMs()) {
235010
235209
  throw new Error(`Monitor timeout_ms must be between ${MIN_TIMEOUT_MS} and ${getMonitorMaxTimeoutMs()}`);
235011
235210
  }
235012
235211
  if (typeof normalized.persistent !== "boolean") {
@@ -235125,7 +235324,9 @@ function queueCommandCompletion(params) {
235125
235324
  });
235126
235325
  }
235127
235326
  function markMonitorFinished(taskId, processState, status, exitCode) {
235128
- processState.status = status;
235327
+ processState.status = status === "expired" ? "failed" : status;
235328
+ if (status === "expired")
235329
+ processState.monitorEndStatus = "expired";
235129
235330
  processState.exitCode = exitCode;
235130
235331
  persistMonitorState(processState);
235131
235332
  cancelMonitorBackup(taskId);
@@ -235300,7 +235501,7 @@ function startCommandMonitor(args) {
235300
235501
  [error] ${message}
235301
235502
  `);
235302
235503
  }
235303
- markMonitorFinished(taskId, processState, "failed", null);
235504
+ markMonitorFinished(taskId, processState, shellError.killed ? "expired" : "failed", null);
235304
235505
  if (!shellError.killed) {
235305
235506
  queueCommandCompletion({
235306
235507
  taskId,
@@ -235356,7 +235557,7 @@ function startWebSocketMonitor(args) {
235356
235557
  output.append(`
235357
235558
  [stopped: output rate too high]
235358
235559
  `);
235359
- markMonitorFinished(taskId, processState, "failed", null);
235560
+ markMonitorFinished(taskId, processState, "expired", null);
235360
235561
  closeSocket();
235361
235562
  }
235362
235563
  });
@@ -235402,7 +235603,7 @@ function startWebSocketMonitor(args) {
235402
235603
  secrets: secrets2
235403
235604
  });
235404
235605
  processState.completionNotificationSuppressed = true;
235405
- markMonitorFinished(taskId, processState, "failed", null);
235606
+ markMonitorFinished(taskId, processState, "expired", null);
235406
235607
  closeSocket();
235407
235608
  return;
235408
235609
  }
@@ -235411,7 +235612,7 @@ function startWebSocketMonitor(args) {
235411
235612
  `);
235412
235613
  if (!wrote) {
235413
235614
  processState.completionNotificationSuppressed = true;
235414
- markMonitorFinished(taskId, processState, "failed", null);
235615
+ markMonitorFinished(taskId, processState, "expired", null);
235415
235616
  closeSocket();
235416
235617
  return;
235417
235618
  }
@@ -235479,7 +235680,7 @@ function startWebSocketMonitor(args) {
235479
235680
  [timeout after ${args.timeout_ms}ms]
235480
235681
  `);
235481
235682
  processState.completionNotificationSuppressed = true;
235482
- markMonitorFinished(taskId, processState, "failed", null);
235683
+ markMonitorFinished(taskId, processState, "expired", null);
235483
235684
  closeSocket();
235484
235685
  }, args.timeout_ms);
235485
235686
  unrefTimer(timeout);
@@ -235511,6 +235712,23 @@ function backupScopeFor(taskId) {
235511
235712
  return { ...runtimeScope, actingUserId: processState.actingUserId };
235512
235713
  }
235513
235714
  async function monitor(args) {
235715
+ const resumeRecord = args.resume ? await readResumableMonitor(args.resume, args.parentScope) : undefined;
235716
+ if (resumeRecord) {
235717
+ if (resumeRecord.kind === "github_pull_request")
235718
+ throw new Error("Use WatchPR to resume this monitor.");
235719
+ args = {
235720
+ ...resumeRecord.args,
235721
+ resume: resumeRecord.monitor_id,
235722
+ parentScope: args.parentScope,
235723
+ signal: args.signal,
235724
+ secretEnv: args.secretEnv,
235725
+ variableEnv: args.variableEnv
235726
+ };
235727
+ if (resumeRecord.expires_at) {
235728
+ args.timeout_ms = Math.max(1, Date.parse(resumeRecord.expires_at) - Date.now());
235729
+ args.persistent = false;
235730
+ }
235731
+ }
235514
235732
  args.signal?.throwIfAborted();
235515
235733
  const cloud = experimentManager.isEnabled("cloud_monitors");
235516
235734
  const forbidden = cloud ? [
@@ -235535,12 +235753,17 @@ async function monitor(args) {
235535
235753
  }
235536
235754
  }
235537
235755
  if (cloud) {
235538
- return startCloudUrlMonitor(args);
235756
+ if (!args.description)
235757
+ throw new Error("Monitor description is required");
235758
+ return startCloudUrlMonitor({ ...args, description: args.description });
235539
235759
  }
235540
235760
  const normalized = normalizeMonitorArgs(args);
235541
235761
  installMonitorProcessExitCleanup();
235542
235762
  const result3 = await withMonitorState({
235543
235763
  ...normalized,
235764
+ resumeRecord,
235765
+ timeoutMs: normalized.persistent ? 0 : normalized.timeout_ms,
235766
+ args: savedMonitorArgs(normalized),
235544
235767
  kind: normalized.script !== undefined ? "script" : normalized.command !== undefined ? "command" : "websocket",
235545
235768
  command: normalized.command ?? normalized.script ?? (normalized.ws ? webSocketDisplayUrl(normalized.ws.url) : "")
235546
235769
  }, (taskId) => {
@@ -235570,6 +235793,7 @@ function stopMonitorsForProcessExit() {
235570
235793
  continue;
235571
235794
  }
235572
235795
  processState.completionNotificationSuppressed = true;
235796
+ processState.monitorEndStatus = isManagedCloudRuntime() ? "paused" : "stopped";
235573
235797
  processState.status = "failed";
235574
235798
  try {
235575
235799
  processState.process.kill("SIGKILL");
@@ -235598,6 +235822,7 @@ var init_monitor = __esm(() => {
235598
235822
  init_bash();
235599
235823
  init_monitor_backup();
235600
235824
  init_monitor_event_stream();
235825
+ init_monitor_resume();
235601
235826
  init_monitor_script();
235602
235827
  init_monitor_state();
235603
235828
  init_monitor_timeout();
@@ -238797,6 +239022,12 @@ function withNativeCliPath(env6, platform7 = process.platform) {
238797
239022
  }
238798
239023
  var init_native_cli_env = () => {};
238799
239024
 
239025
+ // 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";
239027
+ var init_claude_steer_timeouts = __esm(() => {
239028
+ REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS = CLAUDE_TURN_START_TIMEOUT_MS + CLAUDE_CONTROL_RESPONSE_TIMEOUT_MS + 30000;
239029
+ });
239030
+
238800
239031
  // src/tools/impl/external-llm-trace-payload.ts
238801
239032
  function traceCaptureEnabled(env6, baseUrl, apiKey) {
238802
239033
  return env6.LETTA_CODE_TELEM !== "0" && env6.LETTA_CODE_TELEM !== "false" && env6.DO_NOT_TRACK !== "1" && isCloudServerUrl(baseUrl) && Boolean(apiKey);
@@ -239418,6 +239649,7 @@ function markTurnStarted(session3) {
239418
239649
  if (session3.awaitingReplacementStart) {
239419
239650
  session3.awaitingReplacementStart = false;
239420
239651
  session3.pendingSteers = 0;
239652
+ session3.queuedSteer = false;
239421
239653
  session3.suppressedResult = undefined;
239422
239654
  }
239423
239655
  resolveTurnWaiters(session3);
@@ -239435,7 +239667,7 @@ function waitForTurnStart(session3, signal) {
239435
239667
  }
239436
239668
  return new Promise((resolve34, reject2) => {
239437
239669
  const waiter = { resolve: finishResolve, reject: finishReject };
239438
- const timeout = setTimeout(() => finishReject(new Error("Claude turn did not become interruptible")), TURN_START_TIMEOUT_MS);
239670
+ const timeout = setTimeout(() => finishReject(new Error(CLAUDE_TURN_START_TIMEOUT_ERROR)), CLAUDE_TURN_START_TIMEOUT_MS);
239439
239671
  timeout.unref?.();
239440
239672
  const abort = () => finishReject(signal?.reason instanceof Error ? signal.reason : new Error("Claude steering cancelled"));
239441
239673
  function cleanup() {
@@ -239643,8 +239875,13 @@ function finishResult(session3, value) {
239643
239875
  function handleResult(session3, value) {
239644
239876
  session3.interruptible = false;
239645
239877
  session3.resultCount++;
239646
- if (session3.pendingSteers > 0) {
239878
+ if (session3.queuedSteer && session3.acknowledgesInputs && session3.latestInputStarted) {
239879
+ session3.pendingSteers = 0;
239880
+ session3.queuedSteer = false;
239881
+ } else if (session3.pendingSteers > 0) {
239647
239882
  session3.pendingSteers--;
239883
+ if (session3.pendingSteers === 0)
239884
+ session3.queuedSteer = false;
239648
239885
  session3.suppressedResult = value;
239649
239886
  return;
239650
239887
  }
@@ -239708,6 +239945,7 @@ async function launchSession(options, deps) {
239708
239945
  latestInputStarted: false,
239709
239946
  acknowledgesInputs: false,
239710
239947
  pendingSteers: 0,
239948
+ queuedSteer: false,
239711
239949
  interruptible: false,
239712
239950
  awaitingReplacementStart: false,
239713
239951
  suppressedResult: undefined,
@@ -239716,6 +239954,7 @@ async function launchSession(options, deps) {
239716
239954
  provisionalResult: undefined,
239717
239955
  idleOnBackgroundTasks: false,
239718
239956
  backgroundCapMs: deps.backgroundTaskWaitCapMs ?? BACKGROUND_TASK_WAIT_CAP_MS,
239957
+ controlResponseTimeoutMs: deps.controlResponseTimeoutMs ?? CLAUDE_CONTROL_RESPONSE_TIMEOUT_MS,
239719
239958
  backgroundCapTimer: undefined,
239720
239959
  turnWaiters: new Set,
239721
239960
  writeLock: Promise.resolve(),
@@ -239869,7 +240108,7 @@ async function runClaudeTurn(options, deps = {}) {
239869
240108
  }
239870
240109
  }
239871
240110
  async function steerSession(session3, prompt, signal) {
239872
- await withWriteLock(session3, async () => {
240111
+ return withWriteLock(session3, async () => {
239873
240112
  signal?.throwIfAborted();
239874
240113
  await waitForTurnStart(session3, signal);
239875
240114
  if (session3.idleOnBackgroundTasks) {
@@ -239878,7 +240117,7 @@ async function steerSession(session3, prompt, signal) {
239878
240117
  }
239879
240118
  session3.idleOnBackgroundTasks = false;
239880
240119
  await writeInput(session3, prompt);
239881
- return;
240120
+ return "steered";
239882
240121
  }
239883
240122
  if (session3.settled || sessions.get(session3.sessionId) !== session3) {
239884
240123
  throw new Error("Claude Code session is no longer active");
@@ -239891,13 +240130,16 @@ async function steerSession(session3, prompt, signal) {
239891
240130
  session3.interruptible = false;
239892
240131
  const resultCount = session3.resultCount;
239893
240132
  let interruptAcknowledged = false;
240133
+ let ackTimedOut = false;
239894
240134
  const rejectOnAbort = () => {
239895
240135
  session3.pendingControls.get(requestId)?.reject(signal?.reason instanceof Error ? signal.reason : new Error("Claude steering cancelled"));
239896
240136
  };
239897
240137
  signal?.addEventListener("abort", rejectOnAbort, { once: true });
239898
240138
  const timeout = setTimeout(() => {
239899
- session3.pendingControls.get(requestId)?.reject(new Error("Claude interrupt acknowledgement timed out"));
239900
- }, CONTROL_RESPONSE_TIMEOUT_MS);
240139
+ const pending2 = session3.pendingControls.get(requestId);
240140
+ ackTimedOut = Boolean(pending2);
240141
+ pending2?.reject(new Error(CLAUDE_INTERRUPT_ACK_TIMEOUT_ERROR));
240142
+ }, session3.controlResponseTimeoutMs);
239901
240143
  timeout.unref?.();
239902
240144
  try {
239903
240145
  await writeRaw(session3.transport.process.stdin, `${JSON.stringify({ type: "control_request", request_id: requestId, request: { subtype: "interrupt" } })}
@@ -239908,7 +240150,10 @@ async function steerSession(session3, prompt, signal) {
239908
240150
  await writeInput(session3, prompt);
239909
240151
  session3.awaitingReplacementStart = true;
239910
240152
  session3.suppressedResult = undefined;
240153
+ return "steered";
239911
240154
  } catch (error4) {
240155
+ if (ackTimedOut && !signal?.aborted && !session3.settled && sessions.get(session3.sessionId) === session3 && await queueSteerPrompt(session3, prompt))
240156
+ return "queued";
239912
240157
  session3.pendingSteers = Math.max(0, session3.pendingSteers - 1);
239913
240158
  if (interruptAcknowledged) {
239914
240159
  session3.abortController.abort(error4);
@@ -239930,6 +240175,17 @@ async function steerSession(session3, prompt, signal) {
239930
240175
  }
239931
240176
  });
239932
240177
  }
240178
+ async function queueSteerPrompt(session3, prompt) {
240179
+ try {
240180
+ await writeInput(session3, prompt);
240181
+ } catch {
240182
+ return false;
240183
+ }
240184
+ session3.suppressedResult = undefined;
240185
+ session3.awaitingReplacementStart = false;
240186
+ session3.queuedSteer = session3.pendingSteers > 0;
240187
+ return true;
240188
+ }
239933
240189
  async function deliverClaudeMessage(options, deps, launch) {
239934
240190
  for (;; ) {
239935
240191
  const existing = sessions.get(options.sessionId);
@@ -239940,8 +240196,12 @@ async function deliverClaudeMessage(options, deps, launch) {
239940
240196
  continue;
239941
240197
  }
239942
240198
  try {
239943
- await steerSession(existing, options.prompt, options.signal);
239944
- return { mode: "steered", session: existing };
240199
+ const delivery = await steerSession(existing, options.prompt, options.signal);
240200
+ return {
240201
+ mode: "steered",
240202
+ queued: delivery === "queued",
240203
+ session: existing
240204
+ };
239945
240205
  } catch (error4) {
239946
240206
  if (sessions.get(options.sessionId) === existing && !existing.settled)
239947
240207
  throw error4;
@@ -239955,6 +240215,9 @@ async function deliverClaudeMessage(options, deps, launch) {
239955
240215
  }
239956
240216
  return { mode: "resumed", session: session3 };
239957
240217
  }
240218
+ function steeredReceipt(sessionId, queued) {
240219
+ return { mode: "steered", sessionId, ...queued ? { queued: true } : {} };
240220
+ }
239958
240221
  function trackedReceipt(session3) {
239959
240222
  return {
239960
240223
  mode: "resumed",
@@ -239969,14 +240232,14 @@ async function sendClaudeMessage(options, deps = {}) {
239969
240232
  options.signal?.throwIfAborted();
239970
240233
  const steered = await deliverClaudeMessage(options, deps);
239971
240234
  if (steered)
239972
- return { mode: "steered", sessionId: options.sessionId };
240235
+ return steeredReceipt(options.sessionId, steered.queued);
239973
240236
  if (options.beforeStart)
239974
240237
  await options.beforeStart();
239975
240238
  const delivered = await deliverClaudeMessage(options, deps, () => launchSession({ ...options, resumeSessionId: options.sessionId }, deps));
239976
240239
  if (!delivered)
239977
240240
  throw new Error("Claude Code session did not start");
239978
240241
  if (delivered.mode === "steered" && !options.beforeStart)
239979
- return { mode: "steered", sessionId: options.sessionId };
240242
+ return steeredReceipt(options.sessionId, delivered.queued);
239980
240243
  return trackedReceipt(delivered.session);
239981
240244
  }
239982
240245
  async function stopClaudeSession(sessionId) {
@@ -239987,10 +240250,11 @@ async function stopClaudeSession(sessionId) {
239987
240250
  await confirmProcessExit(session3.exit, "Claude Code");
239988
240251
  return true;
239989
240252
  }
239990
- var sessions, CONTROL_RESPONSE_TIMEOUT_MS = 30000, TURN_START_TIMEOUT_MS = 60000, BACKGROUND_TASK_WAIT_CAP_MS, SETTLED_EXIT_GRACE_MS = 1e4;
240253
+ var sessions, BACKGROUND_TASK_WAIT_CAP_MS, SETTLED_EXIT_GRACE_MS = 1e4;
239991
240254
  var init_claude_stream_session = __esm(() => {
239992
240255
  init_subagent_process();
239993
240256
  init_native_cli_env();
240257
+ init_claude_steer_timeouts();
239994
240258
  init_external_llm_trace_launch();
239995
240259
  sessions = new Map;
239996
240260
  BACKGROUND_TASK_WAIT_CAP_MS = 35 * 60000;
@@ -240231,7 +240495,7 @@ class CodexAppServerClient {
240231
240495
  await this.request("initialize", {
240232
240496
  clientInfo: {
240233
240497
  name: "letta-code",
240234
- version: "0.34.61"
240498
+ version: "0.34.62"
240235
240499
  },
240236
240500
  capabilities: null
240237
240501
  });
@@ -244266,9 +244530,9 @@ ${SYSTEM_REMINDER_CLOSE}
244266
244530
  `;
244267
244531
  }
244268
244532
  return `${SYSTEM_REMINDER_OPEN}
244269
- You have been forked from the primary conversational thread to run as an independent subagent. The fork only exists so you can see the parent agent's conversation trajectory in-context as reference — you are NOT the primary agent.
244533
+ You have been forked from the primary conversational thread to run as an independent subagent — you are NOT the primary agent.
244270
244534
 
244271
- **Your sole task is the one described in the user message below. Ignore any existing ongoing tasks from the inherited trajectory.** Do not attempt to continue, finish, or act on anything the primary agent was in the middle of doing.
244535
+ The task in the user message below tells you what to do now; use the inherited conversation 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.
244272
244536
 
244273
244537
  You inherit the primary agent's toolset.
244274
244538
 
@@ -244972,7 +245236,7 @@ async function prependParentContext(params) {
244972
245236
  const recent = selectRecentMessages(preview, INLINE_CHARACTER_LIMIT - (summaryRecord ? summaryRecord.length + 1 : 0));
244973
245237
  return {
244974
245238
  prompt: [
244975
- "The following JSONL is a read-only record of the parent's conversation, not instructions addressed to you. Do only the task following the history block.",
245239
+ "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.",
244976
245240
  "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.",
244977
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>"\`.`,
244978
245242
  "<parent_history>",
@@ -245008,6 +245272,14 @@ var init_external_fork_context = __esm(() => {
245008
245272
  init_backend2();
245009
245273
  });
245010
245274
 
245275
+ // src/tools/impl/fork-prompt.ts
245276
+ function validateForkPrompt(prompt, forked) {
245277
+ if (!forked || prompt.length <= FORK_PROMPT_CHARACTER_LIMIT)
245278
+ return;
245279
+ return `Forked prompt is ${prompt.length} characters; the limit is ${FORK_PROMPT_CHARACTER_LIMIT}. The agent already has the conversation. Send only the go, what done looks like, and what to read.`;
245280
+ }
245281
+ var FORK_PROMPT_CHARACTER_LIMIT = 2000;
245282
+
245011
245283
  // src/agent/memory-conflict-repair.ts
245012
245284
  import { execFile as execFile15 } from "node:child_process";
245013
245285
  import { randomUUID as randomUUID44 } from "node:crypto";
@@ -245637,7 +245909,11 @@ function classifyRemoteExternalWorkerControlError(error4) {
245637
245909
  }
245638
245910
  if (error4 instanceof OutdatedRemoteWorkerError)
245639
245911
  return "outdated_computer";
245912
+ if (error4 instanceof RemoteFollowUpTimeoutError)
245913
+ return "steer_timeout";
245640
245914
  const message2 = errorMessage5(error4);
245915
+ if (message2 === CLAUDE_TURN_START_TIMEOUT_ERROR || message2 === CLAUDE_INTERRUPT_ACK_TIMEOUT_ERROR)
245916
+ return "worker_busy";
245641
245917
  if (/^Computer ".*" is offline(?:\.|$)/.test(message2) || message2.startsWith("Timed out waiting for cloud sandbox "))
245642
245918
  return "computer_offline";
245643
245919
  if (/^Computer ".*" not found(?:\.|$)/.test(message2))
@@ -246067,9 +246343,12 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246067
246343
  agent_id: bareAgentId,
246068
246344
  message: params.message,
246069
246345
  tool_call_id: toolCallId
246070
- });
246346
+ }, { timeoutMs: REMOTE_SUBAGENT_MESSAGE_TIMEOUT_MS });
246071
246347
  } catch (error4) {
246072
246348
  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
+ }
246073
246352
  throw error4;
246074
246353
  }
246075
246354
  if (!response.success) {
@@ -246079,9 +246358,9 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246079
246358
  }
246080
246359
  throw new Error(response.error);
246081
246360
  }
246082
- if (response.delivery === "steered") {
246361
+ if (response.delivery === "steered" || response.delivery === "queued") {
246083
246362
  follower.close();
246084
- return { delivery: "steered" };
246363
+ return { delivery: response.delivery };
246085
246364
  }
246086
246365
  follower.markLaunched();
246087
246366
  const completion = follower.waitForTerminal(undefined, () => {
@@ -246141,7 +246420,7 @@ async function deliverRemoteExternalCodingAgentMessage(params, deps) {
246141
246420
  outputFile: tracked.outputFile
246142
246421
  };
246143
246422
  }
246144
- var REMOTE_EXTERNAL_WORKER_STOPPED, DISPLAY_NAMES, RemoteWorkerLostError, OutdatedRemoteWorkerError, MAX_RECONNECT_DELAY_MS = 30000;
246423
+ var REMOTE_EXTERNAL_WORKER_STOPPED, DISPLAY_NAMES, RemoteWorkerLostError, OutdatedRemoteWorkerError, RemoteFollowUpTimeoutError, MAX_RECONNECT_DELAY_MS = 30000;
246145
246424
  var init_remote_external_coding_agent = __esm(() => {
246146
246425
  init_subagent_state();
246147
246426
  init_app_server_client();
@@ -246151,6 +246430,7 @@ var init_remote_external_coding_agent = __esm(() => {
246151
246430
  init_headless_environment_response();
246152
246431
  init_headless_listener_launch();
246153
246432
  init_error_reporting();
246433
+ init_claude_steer_timeouts();
246154
246434
  init_external_coding_agent();
246155
246435
  init_remote_subagent_events();
246156
246436
  REMOTE_EXTERNAL_WORKER_STOPPED = Symbol("remote external worker stopped");
@@ -246164,6 +246444,8 @@ var init_remote_external_coding_agent = __esm(() => {
246164
246444
  };
246165
246445
  OutdatedRemoteWorkerError = class OutdatedRemoteWorkerError extends Error {
246166
246446
  };
246447
+ RemoteFollowUpTimeoutError = class RemoteFollowUpTimeoutError extends Error {
246448
+ };
246167
246449
  });
246168
246450
 
246169
246451
  // src/tools/impl/subagent-computer.ts
@@ -246171,7 +246453,7 @@ function isLocalComputerSelector(value) {
246171
246453
  return LOCAL_COMPUTER_SELECTORS.has(value.trim().toLowerCase());
246172
246454
  }
246173
246455
  function acceptsDefaultComputer(input) {
246174
- return input.subagentType !== "memory" && !input.config.fork && input.config.launchProfile !== "memory-subagent";
246456
+ return input.subagentType !== "memory" && input.subagentType !== "recall" && input.config.launchProfile !== "memory-subagent";
246175
246457
  }
246176
246458
  function resolveSubagentComputer(input) {
246177
246459
  const requested = typeof input.requested === "string" ? input.requested.trim() : "";
@@ -246226,6 +246508,8 @@ function killBackgroundProcess(shell_id) {
246226
246508
  const previousNotificationSuppression = proc.completionNotificationSuppressed;
246227
246509
  try {
246228
246510
  proc.completionNotificationSuppressed = true;
246511
+ if (proc.kind === "monitor")
246512
+ proc.monitorEndStatus = "stopped";
246229
246513
  if (retainsEntry) {
246230
246514
  proc.status = "failed";
246231
246515
  }
@@ -246242,6 +246526,7 @@ function killBackgroundProcess(shell_id) {
246242
246526
  notifyBackgroundProcessStateChanged(proc.runtimeScope);
246243
246527
  return true;
246244
246528
  } catch {
246529
+ proc.monitorEndStatus = undefined;
246245
246530
  proc.status = previousStatus;
246246
246531
  proc.completionNotificationSuppressed = previousNotificationSuppression;
246247
246532
  return false;
@@ -246940,6 +247225,9 @@ async function launchSubagent(args) {
246940
247225
  error: `Invalid subagent_type "${configName}". Available subagent types: ${listSubagentTypes(Object.keys(allConfigs))}. Omit subagent_type for the default agent.`
246941
247226
  };
246942
247227
  }
247228
+ const promptError = validateForkPrompt(inputPrompt, Boolean(config2.fork));
247229
+ if (promptError)
247230
+ return { success: false, error: promptError };
246943
247231
  if (prepared && (!args.conversation_id || args.conversation_id === "default" || args.model !== undefined)) {
246944
247232
  return {
246945
247233
  success: false,
@@ -247362,7 +247650,8 @@ async function send_agent_message(args, deps = {}) {
247362
247650
  content: JSON.stringify({
247363
247651
  status: "accepted",
247364
247652
  agent_id: args.agent_id,
247365
- delivery: receipt3.delivery === "steered" ? "remote/steer" : "remote/resume",
247653
+ delivery: receipt3.delivery === "queued" ? "remote/queued" : receipt3.delivery === "steered" ? "remote/steer" : "remote/resume",
247654
+ ...receipt3.delivery === "queued" ? { note: QUEUED_NOTE } : {},
247366
247655
  ...receipt3.taskId ? { task_id: receipt3.taskId } : {},
247367
247656
  ...receipt3.outputFile ? { output_file: receipt3.outputFile } : {}
247368
247657
  }),
@@ -247528,7 +247817,8 @@ async function send_agent_message(args, deps = {}) {
247528
247817
  content: JSON.stringify({
247529
247818
  status: "accepted",
247530
247819
  agent_id: args.agent_id,
247531
- delivery: "stream/interrupt"
247820
+ delivery: receipt2.queued ? "stream/queued" : "stream/interrupt",
247821
+ ...receipt2.queued ? { note: QUEUED_NOTE } : {}
247532
247822
  }),
247533
247823
  status: "success"
247534
247824
  };
@@ -247657,7 +247947,7 @@ async function send_agent_message(args, deps = {}) {
247657
247947
  };
247658
247948
  }
247659
247949
  }
247660
- var FULL_CONVERSATION_ID;
247950
+ var QUEUED_NOTE = "The worker is in a long tool call and hasn't stopped yet. Your message is queued and will be handled when it does; don't resend it.", FULL_CONVERSATION_ID;
247661
247951
  var init_send_agent_message = __esm(() => {
247662
247952
  init_child_send_tracking();
247663
247953
  init_subagent_launcher();
@@ -249520,6 +249810,17 @@ ${text2}`;
249520
249810
  }
249521
249811
  }
249522
249812
  async function watch_pr(args, deps = {}) {
249813
+ const resumeRecord = args.resume ? await readResumableMonitor(args.resume, args.parentScope) : undefined;
249814
+ if (resumeRecord) {
249815
+ if (resumeRecord.kind !== "github_pull_request")
249816
+ throw new Error("Use Monitor to resume this monitor.");
249817
+ args = {
249818
+ ...resumeRecord.args,
249819
+ resume: resumeRecord.monitor_id,
249820
+ parentScope: args.parentScope,
249821
+ signal: args.signal
249822
+ };
249823
+ }
249523
249824
  args.signal?.throwIfAborted();
249524
249825
  if (typeof args.url !== "string") {
249525
249826
  throw new Error("WatchPR url is required");
@@ -249548,10 +249849,16 @@ async function watch_pr(args, deps = {}) {
249548
249849
  const initial2 = await fetchSnapshot(ref, { cwd: cwd2, signal: args.signal });
249549
249850
  args.signal?.throwIfAborted();
249550
249851
  const changesSincePreviousWatch = resumedChanges(snapshotPath, initial2, args.notify_on);
249551
- if (isRun && initial2.state !== "OPEN") {
249852
+ if ((isRun || resumeRecord) && initial2.state !== "OPEN") {
249853
+ if (resumeRecord)
249854
+ await updateMonitorState(resumeRecord.monitor_id, {
249855
+ status: "completed",
249856
+ exit_code: 0,
249857
+ output_file: resumeRecord.output_file
249858
+ });
249552
249859
  return {
249553
249860
  content: [{ type: "text", text: describe2(initial2) }],
249554
- taskId: "",
249861
+ taskId: resumeRecord?.monitor_id ?? "",
249555
249862
  url: ref.url,
249556
249863
  headSha: initial2.headSha,
249557
249864
  persistent: false
@@ -249564,10 +249871,16 @@ async function watch_pr(args, deps = {}) {
249564
249871
  assertBackgroundProcessCapacity();
249565
249872
  installMonitorProcessExitCleanup();
249566
249873
  const description = isRun ? `Workflow run ${ref.owner}/${ref.repo}#${ref.number}` : `PR ${ref.owner}/${ref.repo}#${ref.number} checks, reviews, and mergeability`;
249567
- const persistent = !isManagedCloudRuntime();
249874
+ const persistent = !resumeRecord?.expires_at && !isManagedCloudRuntime();
249568
249875
  return withMonitorState({
249569
249876
  description,
249570
249877
  persistent,
249878
+ resumeRecord,
249879
+ timeoutMs: persistent ? 0 : getMonitorMaxTimeoutMs(),
249880
+ args: {
249881
+ url: args.url,
249882
+ ...args.notify_on ? { notify_on: args.notify_on } : {}
249883
+ },
249571
249884
  command: ref.url,
249572
249885
  kind: "github_pull_request",
249573
249886
  parentScope,
@@ -249586,7 +249899,7 @@ ${describe2(initial2)}${changesSincePreviousWatch}
249586
249899
  const controller = new AbortController;
249587
249900
  const secrets2 = {};
249588
249901
  let processState;
249589
- const maxTimeoutMs = getMonitorMaxTimeoutMs();
249902
+ const maxTimeoutMs = resumeRecord?.expires_at ? Math.max(1, Date.parse(resumeRecord.expires_at) - Date.now()) : getMonitorMaxTimeoutMs();
249590
249903
  let timeout;
249591
249904
  const events = createMonitorEventStream({
249592
249905
  emit(event) {
@@ -249659,7 +249972,7 @@ ${event}
249659
249972
  `);
249660
249973
  queueMonitorEvent({ taskId, event, scope, actingUserId, secrets: secrets2 });
249661
249974
  processState.completionNotificationSuppressed = true;
249662
- markMonitorFinished(taskId, processState, "failed", null);
249975
+ markMonitorFinished(taskId, processState, "expired", null);
249663
249976
  processState.process.kill();
249664
249977
  }, maxTimeoutMs);
249665
249978
  unrefTimer(timeout);
@@ -249792,6 +250105,7 @@ Output file: ${outputFile}`
249792
250105
  }
249793
250106
  var WATCH_POLL_MS = 30000, WATCH_MAX_POLL_MS, WATCH_REFRESH_ERROR_NOTIFY_AFTER_MS, WATCH_FRESH_SNAPSHOT_NOTIFY_AFTER_MS;
249794
250107
  var init_watch_pr = __esm(() => {
250108
+ init_monitors();
249795
250109
  init_runtime_context();
249796
250110
  init_secret_substitution();
249797
250111
  init_settings_path();
@@ -249802,6 +250116,7 @@ var init_watch_pr = __esm(() => {
249802
250116
  init_github_workflow_run();
249803
250117
  init_monitor();
249804
250118
  init_monitor_event_stream();
250119
+ init_monitor_resume();
249805
250120
  init_monitor_state();
249806
250121
  init_monitor_timeout();
249807
250122
  init_process_manager();
@@ -251343,7 +251658,7 @@ var init_Monitor2 = __esm(() => {
251343
251658
  properties: {
251344
251659
  description: {
251345
251660
  type: "string",
251346
- description: "Clear, concise user-facing description of the update you are waiting for. This may be shown directly in chat, so make it grammatical by itself. Describe the expected event, not the polling command or monitor implementation. Prefer `CI results and review comments for the auth fix`, `Deployment completion or failure`, or `New errors in the API logs` over internal labels like `PR checks and state transitions`."
251661
+ description: "Clear, concise user-facing description of the update you are waiting for. This may be shown directly in chat, so make it grammatical by itself. Describe the expected event, not the polling command or monitor implementation. Prefer `CI results and review comments for the auth fix`, `Deployment completion or failure`, or `New errors in the API logs` over internal labels like `PR checks and state transitions`. Required unless `resume` is set."
251347
251662
  },
251348
251663
  timeout_ms: {
251349
251664
  type: "number",
@@ -251395,11 +251710,15 @@ var init_Monitor2 = __esm(() => {
251395
251710
  },
251396
251711
  args: {
251397
251712
  description: "Optional input exposed to script as args."
251713
+ },
251714
+ resume: {
251715
+ type: "string",
251716
+ description: "Resume a paused monitor by its saved monitor id. Omit the other arguments."
251398
251717
  }
251399
251718
  },
251400
- required: ["description"],
251401
251719
  additionalProperties: false,
251402
- $schema: "http://json-schema.org/draft-07/schema#"
251720
+ $schema: "http://json-schema.org/draft-07/schema#",
251721
+ required: []
251403
251722
  };
251404
251723
  });
251405
251724
 
@@ -251568,7 +251887,7 @@ var init_Task2 = __esm(() => {
251568
251887
  },
251569
251888
  fork_context: {
251570
251889
  type: "boolean",
251571
- description: "When creating a Letta Code subagent (without subagent_type), whether to include the full conversation history in the subagent. Cannot be applied to existing agents or threads. Defaults to true for new default Letta agents and external workers; existing agent or conversation targets resume without forking."
251890
+ description: "Whether the new agent starts from this conversation. A fork gives it the source: what people actually said, the evidence gathered so far, and the decisions and corrections made along the way. A brief is your retelling of that, and anything you leave out or reword never reaches the worker. So fork whenever the task comes out of this conversation, however long or noisy it is; the fork is trimmed to fit. If you notice yourself writing a brief to explain the conversation, that's the cue to fork. Skip forking only when the task has nothing to do with this conversation, or the worker shouldn't see what's in it. Applies when creating a Letta Code subagent without subagent_type. Cannot be applied to existing agents or threads. Defaults to true for new default Letta agents and external workers; existing agent or conversation targets resume without forking."
251572
251891
  },
251573
251892
  model: {
251574
251893
  type: "string",
@@ -251849,7 +252168,7 @@ var init_WatchPR2 = __esm(() => {
251849
252168
  properties: {
251850
252169
  url: {
251851
252170
  type: "string",
251852
- description: "Open github.com pull request URL ending at the PR number, for example https://github.com/owner/repo/pull/123. Remove sub-page suffixes such as /files or /commits. Also accepts https://github.com/owner/repo/actions/runs/123."
252171
+ description: "Open github.com pull request URL ending at the PR number, for example https://github.com/owner/repo/pull/123. Remove sub-page suffixes such as /files or /commits. Also accepts https://github.com/owner/repo/actions/runs/123. Required unless `resume` is set."
251853
252172
  },
251854
252173
  notify_on: {
251855
252174
  type: "array",
@@ -251869,11 +252188,15 @@ var init_WatchPR2 = __esm(() => {
251869
252188
  ]
251870
252189
  },
251871
252190
  description: "PR events to report; omitted reports all. checks_done reports when no checks remain pending, including pass/fail. Workflow runs always report status and completion."
252191
+ },
252192
+ resume: {
252193
+ type: "string",
252194
+ description: "Resume a paused monitor by its saved monitor id. Omit the other arguments."
251872
252195
  }
251873
252196
  },
251874
- required: ["url"],
251875
252197
  additionalProperties: false,
251876
- $schema: "http://json-schema.org/draft-07/schema#"
252198
+ $schema: "http://json-schema.org/draft-07/schema#",
252199
+ required: []
251877
252200
  };
251878
252201
  });
251879
252202
 
@@ -253029,7 +253352,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
253029
253352
  snapshotSidecar
253030
253353
  });
253031
253354
  const rawSnapshot = () => listInterruptedTurnMainSnapshot(directory, readRecord2);
253032
- return {
253355
+ return withInterruptedTurnDiskReserve(directory, {
253033
253356
  list() {
253034
253357
  try {
253035
253358
  const rawRecords = rawSnapshot().records;
@@ -253422,7 +253745,7 @@ function createInterruptedTurnStore(directory = defaultInterruptedTurnDirectory(
253422
253745
  release();
253423
253746
  }
253424
253747
  }
253425
- };
253748
+ });
253426
253749
  }
253427
253750
  function recordListenerWork(runtime, update2, phase, expectedRevision, recoveryLineageId, store3 = createInterruptedTurnStore()) {
253428
253751
  if (!runtime.agentId || !runtime.listener.connectionId?.startsWith("conn-"))
@@ -253560,6 +253883,7 @@ var init_interrupted_turn_record = __esm(() => {
253560
253883
  init_error_reporting();
253561
253884
  init_debug();
253562
253885
  init_durable_file_lock();
253886
+ init_interrupted_turn_disk_reserve();
253563
253887
  init_interrupted_turn_input_ownership();
253564
253888
  init_interrupted_turn_revision();
253565
253889
  init_interrupted_turn_schema();
@@ -258577,11 +258901,12 @@ function handleTaskPreflight(task2, now2) {
258577
258901
  return handleInvalidRecurringTask(task2, now2) || handleMissedOneShot(task2, now2);
258578
258902
  }
258579
258903
  async function runCronTaskNow(taskId) {
258580
- if (isManagedCloudSandbox()) {
258904
+ const executionError = getLocalCronExecutionError();
258905
+ if (executionError) {
258581
258906
  return {
258582
258907
  success: false,
258583
258908
  found: false,
258584
- error: "Local schedules cannot run in a managed Cloud sandbox"
258909
+ error: executionError
258585
258910
  };
258586
258911
  }
258587
258912
  const task2 = getTask(taskId);
@@ -258700,7 +259025,7 @@ function tick2(state2, socket, opts, processQueuedTurn) {
258700
259025
  }
258701
259026
  }
258702
259027
  function startScheduler(socket, opts, processQueuedTurn, _retryCount = 0) {
258703
- if (isManagedCloudSandbox()) {
259028
+ if (getLocalCronExecutionError()) {
258704
259029
  return;
258705
259030
  }
258706
259031
  listenerFireContext = { socket, opts, processQueuedTurn };
@@ -258914,11 +259239,9 @@ Add options:
258914
259239
  --conversation <id> Conversation target (omit or "new" for a fresh
258915
259240
  conversation per fire; "self" for the current
258916
259241
  conversation; "default" for the agent default)
258917
- --computer <id> (managed Cloud sandbox only) Run on a connected
258918
- external computer (deviceId, id, or name from
258919
- \`letta computers list\`). If it is offline at fire
258920
- time, that run fails (no Cloud sandbox fallback);
258921
- omit --computer to run in the Cloud sandbox.
259242
+ --computer <id> Run on another connected computer (deviceId, id, or
259243
+ name from \`letta computers list\`). If it is offline
259244
+ at fire time, that run fails.
258922
259245
 
258923
259246
  List/filter options:
258924
259247
  --agent <id> Filter by agent ID
@@ -258951,8 +259274,7 @@ function formatCloudScheduleOutput(schedule) {
258951
259274
  const targetDeviceId = schedule.target_device_id ?? null;
258952
259275
  return {
258953
259276
  id: schedule.id,
258954
- runner: "cloud",
258955
- execution_target: targetDeviceId ?? CLOUD_EXECUTION_TARGET,
259277
+ ...targetDeviceId && { execution_target: targetDeviceId },
258956
259278
  ...targetDeviceId && { target_device_id: targetDeviceId },
258957
259279
  agent_id: schedule.agent_id,
258958
259280
  conversation_id: schedule.conversation_id ?? "default",
@@ -259071,11 +259393,11 @@ async function handleAdd(values4) {
259071
259393
  cron,
259072
259394
  recurring,
259073
259395
  prompt,
259074
- scheduled_for: scheduledFor
259396
+ scheduled_for: scheduledFor,
259397
+ timezone: "UTC"
259075
259398
  });
259076
259399
  const output = {
259077
259400
  id: result3.task.id,
259078
- runner: "local",
259079
259401
  status: result3.task.status,
259080
259402
  cron: result3.task.cron,
259081
259403
  recurring: result3.task.recurring,
@@ -259093,10 +259415,10 @@ async function handleAdd(values4) {
259093
259415
  output.note = note;
259094
259416
  }
259095
259417
  if (result3.warning) {
259096
- output.warning = result3.warning;
259418
+ output.warning = "This task only fires while this session is running.";
259097
259419
  }
259098
259420
  console.log(JSON.stringify(output, null, 2));
259099
- console.error("Created local schedule: it only fires while a Letta session is running on this device.");
259421
+ console.error("Created schedule. It only fires while this session is running.");
259100
259422
  return 0;
259101
259423
  } catch (err) {
259102
259424
  console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
@@ -259125,8 +259447,7 @@ async function handleCloudAdd(params) {
259125
259447
  const targetDeviceId = result3.target_device_id ?? built.input.target_device_id ?? null;
259126
259448
  const output = {
259127
259449
  id: result3.id,
259128
- runner: "cloud",
259129
- execution_target: targetDeviceId ?? CLOUD_EXECUTION_TARGET,
259450
+ ...targetDeviceId && { execution_target: targetDeviceId },
259130
259451
  ...targetDeviceId && { target_device_id: targetDeviceId },
259131
259452
  agent_id: params.agentId,
259132
259453
  conversation_id: params.conversationId,
@@ -259143,10 +259464,10 @@ async function handleCloudAdd(params) {
259143
259464
  output.notes = notes;
259144
259465
  }
259145
259466
  console.log(JSON.stringify(output, null, 2));
259146
- console.error(targetDeviceId ? `Created Cloud schedule: it fires from the cloud and runs on computer "${targetDeviceId}" (if it is offline at fire time, that run fails; no sandbox fallback).` : "Created Cloud schedule: it fires from the cloud and runs in this agent's managed cloud sandbox (survives local shutdown).");
259467
+ console.error(targetDeviceId ? `Created schedule on computer "${targetDeviceId}". If it is offline at fire time, that run fails.` : "Created schedule.");
259147
259468
  return 0;
259148
259469
  } catch (err) {
259149
- console.error(`Error: failed to create Cloud schedule: ${err instanceof Error ? err.message : String(err)}`);
259470
+ console.error(`Error: failed to create schedule: ${err instanceof Error ? err.message : String(err)}`);
259150
259471
  console.error("No schedule was created. Retry the request.");
259151
259472
  return 1;
259152
259473
  }
@@ -259159,7 +259480,7 @@ async function handleList(values4) {
259159
259480
  const output = listTasks({
259160
259481
  agent_id: agentId,
259161
259482
  conversation_id: conversationId
259162
- }).map((task2) => ({ ...task2, runner: "local" }));
259483
+ }).map((task2) => ({ ...task2 }));
259163
259484
  if (agentId && canManageCloudSchedules(agentId)) {
259164
259485
  try {
259165
259486
  await ensureSettingsForCloud2();
@@ -259169,9 +259490,9 @@ async function handleList(values4) {
259169
259490
  }
259170
259491
  } catch (err) {
259171
259492
  if (err instanceof ApiRequestError && (err.status === 404 || err.status === 405)) {
259172
- console.error("Note: Cloud schedules not listed (server does not serve the schedule routes, or this agent is not visible to the current credential).");
259493
+ console.error("Note: Schedules not listed (server does not serve the schedule routes, or this agent is not visible to the current credential).");
259173
259494
  } else {
259174
- console.error(`Warning: Cloud schedules not listed: ${err instanceof Error ? err.message : String(err)}`);
259495
+ console.error(`Warning: Schedules not listed: ${err instanceof Error ? err.message : String(err)}`);
259175
259496
  }
259176
259497
  }
259177
259498
  }
@@ -259187,7 +259508,7 @@ async function handleGet(values4, positionals) {
259187
259508
  const agentId = resolveCronAgentId(values4.agent);
259188
259509
  const task2 = getTask(taskRef);
259189
259510
  if (task2) {
259190
- console.log(JSON.stringify({ ...task2, runner: "local" }, null, 2));
259511
+ console.log(JSON.stringify({ ...task2 }, null, 2));
259191
259512
  return 0;
259192
259513
  }
259193
259514
  if (agentId && canManageCloudSchedules(agentId)) {
@@ -259211,7 +259532,7 @@ async function handleGet(values4, positionals) {
259211
259532
  if (resolved?.store === "local") {
259212
259533
  const task3 = getTask(resolved.id);
259213
259534
  if (task3) {
259214
- console.log(JSON.stringify({ ...task3, runner: "local" }, null, 2));
259535
+ console.log(JSON.stringify({ ...task3 }, null, 2));
259215
259536
  return 0;
259216
259537
  }
259217
259538
  }
@@ -259251,7 +259572,7 @@ async function handleRuns(values4) {
259251
259572
  }
259252
259573
  const agentId = resolveCronAgentId(values4.agent);
259253
259574
  if (!agentId) {
259254
- console.error(`Error: --agent or LETTA_AGENT_ID is required to look up Cloud schedule runs for task ${id}.`);
259575
+ console.error(`Error: --agent or LETTA_AGENT_ID is required to look up schedule runs for task ${id}.`);
259255
259576
  return 1;
259256
259577
  }
259257
259578
  if (!canManageCloudSchedules(agentId)) {
@@ -259262,7 +259583,6 @@ async function handleRuns(values4) {
259262
259583
  await ensureSettingsForCloud2();
259263
259584
  const response = await listCloudScheduleHistory(agentId, id, { limit: limit4 });
259264
259585
  console.log(JSON.stringify({
259265
- runner: "cloud",
259266
259586
  entries: response.history,
259267
259587
  has_next_page: response.has_next_page
259268
259588
  }, null, 2));
@@ -259283,7 +259603,7 @@ async function handleDelete(values4, positionals) {
259283
259603
  }
259284
259604
  const found = deleteTask(taskRef);
259285
259605
  if (found) {
259286
- console.log(JSON.stringify({ deleted: taskRef, runner: "local" }));
259606
+ console.log(JSON.stringify({ deleted: taskRef }));
259287
259607
  return 0;
259288
259608
  }
259289
259609
  const agentId = resolveCronAgentId(values4.agent);
@@ -259292,7 +259612,7 @@ async function handleDelete(values4, positionals) {
259292
259612
  await ensureSettingsForCloud2();
259293
259613
  await getCloudSchedule(agentId, taskRef);
259294
259614
  await deleteCloudSchedule(agentId, taskRef);
259295
- console.log(JSON.stringify({ deleted: taskRef, runner: "cloud" }));
259615
+ console.log(JSON.stringify({ deleted: taskRef }));
259296
259616
  return 0;
259297
259617
  } catch (err) {
259298
259618
  if (!(err instanceof ApiRequestError && err.status === 404)) {
@@ -259307,7 +259627,7 @@ async function handleDelete(values4, positionals) {
259307
259627
  return 1;
259308
259628
  }
259309
259629
  if (resolved?.store === "local" && deleteTask(resolved.id)) {
259310
- console.log(JSON.stringify({ deleted: resolved.id, name: taskRef, runner: "local" }));
259630
+ console.log(JSON.stringify({ deleted: resolved.id, name: taskRef }));
259311
259631
  return 0;
259312
259632
  }
259313
259633
  if (resolved?.store === "cloud" && agentId) {
@@ -259315,8 +259635,7 @@ async function handleDelete(values4, positionals) {
259315
259635
  await deleteCloudSchedule(agentId, resolved.id);
259316
259636
  console.log(JSON.stringify({
259317
259637
  deleted: resolved.id,
259318
- name: taskRef,
259319
- runner: "cloud"
259638
+ name: taskRef
259320
259639
  }));
259321
259640
  return 0;
259322
259641
  } catch (err) {
@@ -259344,15 +259663,13 @@ async function handleDeleteAll(values4) {
259344
259663
  cloudDeleted += 1;
259345
259664
  }
259346
259665
  } catch (err) {
259347
- console.error(`Error: failed to delete Cloud schedules: ${err instanceof Error ? err.message : String(err)}`);
259348
- console.error(`Deleted so far: ${localDeleted} local, ${cloudDeleted} cloud.`);
259666
+ console.error(`Error: failed to delete schedules: ${err instanceof Error ? err.message : String(err)}`);
259667
+ console.error(`Deleted so far: ${localDeleted + cloudDeleted}.`);
259349
259668
  return 1;
259350
259669
  }
259351
259670
  }
259352
259671
  console.log(JSON.stringify({
259353
259672
  deleted: localDeleted + cloudDeleted,
259354
- local_deleted: localDeleted,
259355
- cloud_deleted: cloudDeleted,
259356
259673
  agent_id: agentId
259357
259674
  }));
259358
259675
  return 0;
@@ -268101,6 +268418,7 @@ async function prepareToolExecutionContextForScope(params) {
268101
268418
  modAdapters,
268102
268419
  agent,
268103
268420
  runtimeContext: {
268421
+ sessionSource: getRuntimeSessionSource(),
268104
268422
  connectionId,
268105
268423
  environmentDeviceId,
268106
268424
  agentId,
@@ -268164,6 +268482,7 @@ var init_toolset = __esm(() => {
268164
268482
  init_model_handles();
268165
268483
  init_backend2();
268166
268484
  init_context2();
268485
+ init_runtime_context();
268167
268486
  init_settings_manager();
268168
268487
  init_client_preferences();
268169
268488
  init_manager2();
@@ -396607,7 +396926,7 @@ ${newComment.split(`
396607
396926
  let returnType;
396608
396927
  const parameters = [];
396609
396928
  const callArguments = [];
396610
- let writes;
396929
+ let writes2;
396611
396930
  usagesInScope.forEach((usage, name) => {
396612
396931
  let typeNode;
396613
396932
  if (!isJS) {
@@ -396618,7 +396937,7 @@ ${newComment.split(`
396618
396937
  const paramDecl = factory.createParameterDeclaration(undefined, undefined, name, undefined, typeNode);
396619
396938
  parameters.push(paramDecl);
396620
396939
  if (usage.usage === 2) {
396621
- (writes || (writes = [])).push(usage);
396940
+ (writes2 || (writes2 = [])).push(usage);
396622
396941
  }
396623
396942
  callArguments.push(factory.createIdentifier(name));
396624
396943
  });
@@ -396630,7 +396949,7 @@ ${newComment.split(`
396630
396949
  const contextualType = checker.getContextualType(node);
396631
396950
  returnType = checker.typeToTypeNode(contextualType, scope, 1, 8);
396632
396951
  }
396633
- const { body: body3, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range4.facts & 1));
396952
+ const { body: body3, returnValueProperty } = transformFunctionBody(node, exposedVariableDeclarations, writes2, substitutions, !!(range4.facts & 1));
396634
396953
  suppressLeadingAndTrailingTrivia(body3);
396635
396954
  let newFunction;
396636
396955
  const callThis = !!(range4.facts & 16);
@@ -396673,7 +396992,7 @@ ${newComment.split(`
396673
396992
  if (isInJSXContent(node)) {
396674
396993
  call = factory.createJsxExpression(undefined, call);
396675
396994
  }
396676
- if (exposedVariableDeclarations.length && !writes) {
396995
+ if (exposedVariableDeclarations.length && !writes2) {
396677
396996
  Debug.assert(!returnValueProperty, "Expected no returnValueProperty");
396678
396997
  Debug.assert(!(range4.facts & 1), "Expected RangeFacts.HasReturn flag to be unset");
396679
396998
  if (exposedVariableDeclarations.length === 1) {
@@ -396697,7 +397016,7 @@ ${newComment.split(`
396697
397016
  }
396698
397017
  newNodes.push(factory.createVariableStatement(undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(factory.createObjectBindingPattern(bindingElements), undefined, typeLiteral, call)], commonNodeFlags)));
396699
397018
  }
396700
- } else if (exposedVariableDeclarations.length || writes) {
397019
+ } else if (exposedVariableDeclarations.length || writes2) {
396701
397020
  if (exposedVariableDeclarations.length) {
396702
397021
  for (const variableDeclaration of exposedVariableDeclarations) {
396703
397022
  let flags = variableDeclaration.parent.flags;
@@ -396710,7 +397029,7 @@ ${newComment.split(`
396710
397029
  if (returnValueProperty) {
396711
397030
  newNodes.push(factory.createVariableStatement(undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(returnValueProperty, undefined, getTypeDeepCloneUnionUndefined(returnType))], 1)));
396712
397031
  }
396713
- const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
397032
+ const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes2);
396714
397033
  if (returnValueProperty) {
396715
397034
  assignments.unshift(factory.createShorthandPropertyAssignment(returnValueProperty));
396716
397035
  }
@@ -396892,8 +397211,8 @@ ${newComment.split(`
396892
397211
  return functionReference;
396893
397212
  }
396894
397213
  }
396895
- function transformFunctionBody(body3, exposedVariableDeclarations, writes, substitutions, hasReturn2) {
396896
- const hasWritesOrVariableDeclarations = writes !== undefined || exposedVariableDeclarations.length > 0;
397214
+ function transformFunctionBody(body3, exposedVariableDeclarations, writes2, substitutions, hasReturn2) {
397215
+ const hasWritesOrVariableDeclarations = writes2 !== undefined || exposedVariableDeclarations.length > 0;
396897
397216
  if (isBlock(body3) && !hasWritesOrVariableDeclarations && substitutions.size === 0) {
396898
397217
  return { body: factory.createBlock(body3.statements, true), returnValueProperty: undefined };
396899
397218
  }
@@ -396903,7 +397222,7 @@ ${newComment.split(`
396903
397222
  if (hasWritesOrVariableDeclarations || substitutions.size) {
396904
397223
  const rewrittenStatements = visitNodes2(statements, visitor, isStatement).slice();
396905
397224
  if (hasWritesOrVariableDeclarations && !hasReturn2 && isStatement(body3)) {
396906
- const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
397225
+ const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes2);
396907
397226
  if (assignments.length === 1) {
396908
397227
  rewrittenStatements.push(factory.createReturnStatement(assignments[0].name));
396909
397228
  } else {
@@ -396916,7 +397235,7 @@ ${newComment.split(`
396916
397235
  }
396917
397236
  function visitor(node) {
396918
397237
  if (!ignoreReturns && isReturnStatement(node) && hasWritesOrVariableDeclarations) {
396919
- const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes);
397238
+ const assignments = getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes2);
396920
397239
  if (node.expression) {
396921
397240
  if (!returnValueProperty) {
396922
397241
  returnValueProperty = "__return";
@@ -397010,9 +397329,9 @@ ${newComment.split(`
397010
397329
  Debug.assert(curr !== scope, "Didn't encounter a block-like before encountering scope");
397011
397330
  }
397012
397331
  }
397013
- function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes) {
397332
+ function getPropertyAssignmentsForWritesAndVariableDeclarations(exposedVariableDeclarations, writes2) {
397014
397333
  const variableAssignments = map3(exposedVariableDeclarations, (v2) => factory.createShorthandPropertyAssignment(v2.symbol.name));
397015
- const writeAssignments = map3(writes, (w3) => factory.createShorthandPropertyAssignment(w3.symbol.name));
397334
+ const writeAssignments = map3(writes2, (w3) => factory.createShorthandPropertyAssignment(w3.symbol.name));
397016
397335
  return variableAssignments === undefined ? writeAssignments : writeAssignments === undefined ? variableAssignments : variableAssignments.concat(writeAssignments);
397017
397336
  }
397018
397337
  function isReadonlyArray4(v2) {
@@ -459210,9 +459529,9 @@ async function handleCronCommand(parsed, socket, safeSocketSend) {
459210
459529
  }
459211
459530
  if (parsed.type === "cron_add") {
459212
459531
  try {
459213
- if (isManagedCloudSandbox()) {
459214
- throw new Error("Local schedules cannot be created in a managed Cloud sandbox");
459215
- }
459532
+ const executionError = getLocalCronExecutionError("created");
459533
+ if (executionError)
459534
+ throw new Error(executionError);
459216
459535
  const scheduledFor = parsed.scheduled_for ? new Date(parsed.scheduled_for) : undefined;
459217
459536
  if (scheduledFor && Number.isNaN(scheduledFor.getTime())) {
459218
459537
  throw new Error("Invalid scheduled_for timestamp");
@@ -459320,8 +459639,9 @@ async function handleCronCommand(parsed, socket, safeSocketSend) {
459320
459639
  if (parsed.type === "cron_pause" || parsed.type === "cron_resume") {
459321
459640
  const responseType = parsed.type === "cron_pause" ? "cron_pause_response" : "cron_resume_response";
459322
459641
  try {
459323
- if (parsed.type === "cron_resume" && isManagedCloudSandbox()) {
459324
- throw new Error("Local schedules cannot be resumed in a managed Cloud sandbox");
459642
+ const executionError = getLocalCronExecutionError("resumed");
459643
+ if (parsed.type === "cron_resume" && executionError) {
459644
+ throw new Error(executionError);
459325
459645
  }
459326
459646
  let scheduledFor;
459327
459647
  if (parsed.type === "cron_resume" && parsed.scheduled_for !== undefined) {
@@ -462958,7 +463278,11 @@ async function handleSubagentMessageCommand(command, parent, deps = {}) {
462958
463278
  }, { env: worker?.env });
462959
463279
  }));
462960
463280
  if (receipt.mode === "steered")
462961
- return { ...base2, success: true, delivery: "steered" };
463281
+ return {
463282
+ ...base2,
463283
+ success: true,
463284
+ delivery: "queued" in receipt && receipt.queued ? "queued" : "steered"
463285
+ };
462962
463286
  if (!receipt.completion || !receipt.interrupt)
462963
463287
  throw new Error("External coding agent returned an incomplete receipt");
462964
463288
  const secretEnv = worker?.secretEnv;
@@ -468559,6 +468883,7 @@ function shouldAcquireStandaloneListenerLock() {
468559
468883
  return shouldAcquireManualListenerLock(getSpawnerListenerInstanceId(), process.env.LETTA_DESKTOP_MODE === "1");
468560
468884
  }
468561
468885
  async function runListenSubcommand(argv, appServer) {
468886
+ process.env.LETTA_RUNTIME_SESSION_SOURCE = "listen";
468562
468887
  const lifecycleRequested = hasJsonlLifecycleIntent(argv);
468563
468888
  if (lifecycleRequested)
468564
468889
  suppressStartupLogMarker();
@@ -472736,8 +473061,96 @@ var init_mods = __esm(() => {
472736
473061
  };
472737
473062
  });
472738
473063
 
472739
- // src/cli/subcommands/permissions.ts
473064
+ // src/cli/subcommands/monitors.ts
472740
473065
  import { parseArgs as parseArgs16 } from "node:util";
473066
+ async function runMonitorsSubcommand(argv, deps = {}) {
473067
+ const print = deps.print ?? console.log;
473068
+ try {
473069
+ const { values: values4, positionals } = parseArgs16({
473070
+ args: argv,
473071
+ allowPositionals: true,
473072
+ options: {
473073
+ agent: { type: "string" },
473074
+ status: { type: "string" },
473075
+ json: { type: "boolean" },
473076
+ help: { type: "boolean", short: "h" }
473077
+ }
473078
+ });
473079
+ if (values4.help || !positionals.length || positionals[0] === "help") {
473080
+ print(HELP);
473081
+ return values4.help || positionals[0] === "help" ? 0 : 1;
473082
+ }
473083
+ await (deps.initializeSettings ?? (() => settingsManager.initialize()))();
473084
+ if (positionals[0] === "resume" && positionals.length === 2) {
473085
+ const record5 = await (deps.read ?? readResumableMonitor)(positionals[1] ?? "");
473086
+ const tool = record5.kind === "github_pull_request" ? "WatchPR" : "Monitor";
473087
+ print(`Run this tool call in the original conversation's running harness:
473088
+ ${tool}(${JSON.stringify({ resume: record5.monitor_id })})`);
473089
+ return 0;
473090
+ }
473091
+ if (positionals[0] !== "list" || positionals.length !== 1)
473092
+ throw new Error(HELP);
473093
+ const scope = { status: values4.status };
473094
+ if (values4.agent)
473095
+ scope.agent_id = values4.agent;
473096
+ else {
473097
+ scope.conversation_id = process.env.CONVERSATION_ID || process.env.LETTA_CONVERSATION_ID;
473098
+ if (!scope.conversation_id)
473099
+ throw new Error("Set CONVERSATION_ID or pass --agent <id>.");
473100
+ if (scope.conversation_id === "default") {
473101
+ scope.agent_id = process.env.LETTA_AGENT_ID || process.env.AGENT_ID;
473102
+ if (!scope.agent_id)
473103
+ throw new Error("The default conversation also requires LETTA_AGENT_ID or AGENT_ID.");
473104
+ }
473105
+ }
473106
+ const list = deps.list ?? listMonitorStates;
473107
+ const records2 = [];
473108
+ for (;; ) {
473109
+ const page = await list(scope);
473110
+ records2.push(...page);
473111
+ if (page.length < 200)
473112
+ break;
473113
+ scope.after = page.at(-1)?.monitor_id;
473114
+ }
473115
+ if (values4.json)
473116
+ print(JSON.stringify(records2, null, 2));
473117
+ else {
473118
+ const clean = (value) => Array.from(value ?? "-", (char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 ? " " : char).join("");
473119
+ print([
473120
+ "ID\tKIND\tDESCRIPTION\tSTATUS\tSTARTED\tEXPIRES\tCOMMAND / PR",
473121
+ ...records2.map((row) => [
473122
+ row.monitor_id,
473123
+ row.kind,
473124
+ row.description,
473125
+ row.status,
473126
+ row.started_at,
473127
+ row.expires_at,
473128
+ row.command
473129
+ ].map(clean).join("\t"))
473130
+ ].join(`
473131
+ `));
473132
+ }
473133
+ return 0;
473134
+ } catch (error4) {
473135
+ console.error(error4 instanceof Error ? error4.message : String(error4));
473136
+ return 1;
473137
+ }
473138
+ }
473139
+ var HELP = `Usage:
473140
+ letta monitors list [--agent <id>] [--status <s>] [--json]
473141
+ letta monitors resume <id>
473142
+
473143
+ List defaults to $CONVERSATION_ID / $LETTA_CONVERSATION_ID; --agent lists agent-wide records.
473144
+ Resume prints the exact tool call to run in the owning conversation's live harness.
473145
+ -h, --help Show this help`;
473146
+ var init_monitors3 = __esm(() => {
473147
+ init_monitors();
473148
+ init_settings_manager();
473149
+ init_monitor_resume();
473150
+ });
473151
+
473152
+ // src/cli/subcommands/permissions.ts
473153
+ import { parseArgs as parseArgs17 } from "node:util";
472741
473154
  function printUsage12() {
472742
473155
  console.log(`Usage:
472743
473156
  letta permissions [--agent <id>]
@@ -472813,7 +473226,7 @@ async function buildPermissionsReport(agentId, request4 = apiRequest, actingUser
472813
473226
  async function runPermissionsSubcommand(argv, deps = {}) {
472814
473227
  let values4;
472815
473228
  try {
472816
- ({ values: values4 } = parseArgs16({
473229
+ ({ values: values4 } = parseArgs17({
472817
473230
  args: argv,
472818
473231
  options: {
472819
473232
  agent: { type: "string" },
@@ -472936,7 +473349,7 @@ var init_sandbox_files = __esm(() => {
472936
473349
  // src/cli/subcommands/sandbox.ts
472937
473350
  import { readFile as readFile29, stat as stat15, writeFile as writeFile19 } from "node:fs/promises";
472938
473351
  import { basename as basename30, resolve as resolve40 } from "node:path";
472939
- import { parseArgs as parseArgs17 } from "node:util";
473352
+ import { parseArgs as parseArgs18 } from "node:util";
472940
473353
  function printUsage13() {
472941
473354
  console.log(`
472942
473355
  Usage:
@@ -472974,7 +473387,7 @@ Notes:
472974
473387
  `.trim());
472975
473388
  }
472976
473389
  function parseSandboxArgs(argv) {
472977
- return parseArgs17({
473390
+ return parseArgs18({
472978
473391
  args: argv,
472979
473392
  options: SANDBOX_OPTIONS,
472980
473393
  strict: true,
@@ -473205,7 +473618,7 @@ var init_sandbox2 = __esm(() => {
473205
473618
  });
473206
473619
 
473207
473620
  // src/cli/subcommands/secret.ts
473208
- import { parseArgs as parseArgs18 } from "node:util";
473621
+ import { parseArgs as parseArgs19 } from "node:util";
473209
473622
  function printUsage14() {
473210
473623
  console.log(`
473211
473624
  Usage:
@@ -473231,7 +473644,7 @@ Notes:
473231
473644
  `.trim());
473232
473645
  }
473233
473646
  function parseSecretArgs(argv) {
473234
- return parseArgs18({
473647
+ return parseArgs19({
473235
473648
  args: argv,
473236
473649
  options: SECRET_OPTIONS,
473237
473650
  strict: true,
@@ -474004,7 +474417,7 @@ var init_setup7 = __esm(async () => {
474004
474417
  // src/cli/subcommands/shared-memory.ts
474005
474418
  import { existsSync as existsSync71 } from "node:fs";
474006
474419
  import { join as join107 } from "node:path";
474007
- import { parseArgs as parseArgs19 } from "node:util";
474420
+ import { parseArgs as parseArgs20 } from "node:util";
474008
474421
  function printUsage16() {
474009
474422
  console.log(`
474010
474423
  Usage:
@@ -474040,7 +474453,7 @@ Examples:
474040
474453
  `.trim());
474041
474454
  }
474042
474455
  function parseSharedMemoryArgs(argv) {
474043
- return parseArgs19({
474456
+ return parseArgs20({
474044
474457
  args: argv,
474045
474458
  options: SHARED_MEMORY_OPTIONS,
474046
474459
  strict: true,
@@ -475803,7 +476216,7 @@ import {
475803
476216
  import { mkdir as mkdir16, readdir as readdir13 } from "node:fs/promises";
475804
476217
  import { tmpdir as tmpdir15 } from "node:os";
475805
476218
  import { basename as basename31, dirname as dirname42, join as join108, normalize as normalize5, resolve as resolve41, sep as sep9 } from "node:path";
475806
- import { parseArgs as parseArgs20, TextDecoder as TextDecoder2, TextEncoder as TextEncoder2 } from "node:util";
476219
+ import { parseArgs as parseArgs21, TextDecoder as TextDecoder2, TextEncoder as TextEncoder2 } from "node:util";
475807
476220
  function printUsage17() {
475808
476221
  console.log(`
475809
476222
  Usage:
@@ -475831,7 +476244,7 @@ Options:
475831
476244
  `.trim());
475832
476245
  }
475833
476246
  function parseSkillsArgs(argv) {
475834
- return parseArgs20({
476247
+ return parseArgs21({
475835
476248
  args: argv,
475836
476249
  options: SKILLS_OPTIONS,
475837
476250
  strict: true,
@@ -476662,10 +477075,10 @@ var init_skills6 = __esm(() => {
476662
477075
  });
476663
477076
 
476664
477077
  // src/cli/subcommands/steps.ts
476665
- import { parseArgs as parseArgs21 } from "node:util";
477078
+ import { parseArgs as parseArgs22 } from "node:util";
476666
477079
  async function runStepsSubcommand(argv, deps = {}) {
476667
477080
  try {
476668
- const { positionals, values: values4 } = parseArgs21({
477081
+ const { positionals, values: values4 } = parseArgs22({
476669
477082
  args: argv,
476670
477083
  options: {
476671
477084
  help: { type: "boolean", short: "h" },
@@ -476715,7 +477128,7 @@ var init_steps4 = __esm(() => {
476715
477128
  });
476716
477129
 
476717
477130
  // src/cli/subcommands/teleport.ts
476718
- import { parseArgs as parseArgs22 } from "node:util";
477131
+ import { parseArgs as parseArgs23 } from "node:util";
476719
477132
  function printUsage18() {
476720
477133
  console.log(`
476721
477134
  Usage:
@@ -476739,7 +477152,7 @@ Notes:
476739
477152
  `.trim());
476740
477153
  }
476741
477154
  function parseTeleportArgs(argv) {
476742
- return parseArgs22({
477155
+ return parseArgs23({
476743
477156
  args: argv,
476744
477157
  options: TELEPORT_OPTIONS,
476745
477158
  strict: true,
@@ -477257,7 +477670,7 @@ var init_review = () => {};
477257
477670
 
477258
477671
  // src/cli/subcommands/trajectories.ts
477259
477672
  import { readFile as readFile33 } from "node:fs/promises";
477260
- import { parseArgs as parseArgs23 } from "node:util";
477673
+ import { parseArgs as parseArgs24 } from "node:util";
477261
477674
  function printUsage19() {
477262
477675
  console.log(`
477263
477676
  Usage:
@@ -477396,7 +477809,7 @@ ${results.length} session(s) matched "${keyword}"`);
477396
477809
  return 0;
477397
477810
  }
477398
477811
  function parseTrajectoriesArgs(argv) {
477399
- return parseArgs23({
477812
+ return parseArgs24({
477400
477813
  args: argv,
477401
477814
  options: TRAJECTORIES_OPTIONS,
477402
477815
  strict: true,
@@ -477519,10 +477932,10 @@ var init_trajectories = __esm(() => {
477519
477932
  });
477520
477933
 
477521
477934
  // src/cli/subcommands/usage.ts
477522
- import { parseArgs as parseArgs24 } from "node:util";
477935
+ import { parseArgs as parseArgs25 } from "node:util";
477523
477936
  async function runUsageSubcommand(argv) {
477524
477937
  try {
477525
- const { values: values4 } = parseArgs24({
477938
+ const { values: values4 } = parseArgs25({
477526
477939
  args: argv,
477527
477940
  options: { help: { type: "boolean", short: "h" } },
477528
477941
  strict: true,
@@ -477580,7 +477993,7 @@ var init_usage3 = __esm(() => {
477580
477993
  });
477581
477994
 
477582
477995
  // src/cli/subcommands/variable.ts
477583
- import { parseArgs as parseArgs25 } from "node:util";
477996
+ import { parseArgs as parseArgs26 } from "node:util";
477584
477997
  function printUsage20() {
477585
477998
  console.log(`
477586
477999
  Usage:
@@ -477600,7 +478013,7 @@ Variables are plain values, visible to the agent and never redacted. Use secrets
477600
478013
  `.trim());
477601
478014
  }
477602
478015
  function parseVariableArgs(argv) {
477603
- return parseArgs25({
478016
+ return parseArgs26({
477604
478017
  args: argv,
477605
478018
  options: SECRET_OPTIONS2,
477606
478019
  strict: true,
@@ -482274,14 +482687,14 @@ var exports_channel_gateway = {};
482274
482687
  __export(exports_channel_gateway, {
482275
482688
  runChannelGatewaySubcommand: () => runChannelGatewaySubcommand
482276
482689
  });
482277
- import { parseArgs as parseArgs26 } from "node:util";
482690
+ import { parseArgs as parseArgs27 } from "node:util";
482278
482691
  function isGatewayCommandEnvelope(value) {
482279
482692
  return Boolean(value && typeof value === "object" && "type" in value && value.type === "command" && "requestId" in value && typeof value.requestId === "string" && "command" in value && value.command && typeof value.command === "object");
482280
482693
  }
482281
482694
  async function runChannelGatewaySubcommand(argv) {
482282
482695
  let values4;
482283
482696
  try {
482284
- ({ values: values4 } = parseArgs26({
482697
+ ({ values: values4 } = parseArgs27({
482285
482698
  args: argv,
482286
482699
  strict: true,
482287
482700
  allowPositionals: false,
@@ -482424,6 +482837,7 @@ function subcommandNeedsEarlyBackendMode(command) {
482424
482837
  case "permissions":
482425
482838
  case "remote":
482426
482839
  case "sandbox":
482840
+ case "monitors":
482427
482841
  case "variable":
482428
482842
  case "secret":
482429
482843
  case "server":
@@ -482500,6 +482914,8 @@ async function runSubcommand(argv) {
482500
482914
  return runSharedMemorySubcommand(rest2);
482501
482915
  case "skills":
482502
482916
  return runSkillsSubcommand(rest2);
482917
+ case "monitors":
482918
+ return runMonitorsSubcommand(rest2);
482503
482919
  case "cron":
482504
482920
  return runCronSubcommand(rest2);
482505
482921
  case "channels":
@@ -482531,6 +482947,7 @@ var init_router = __esm(async () => {
482531
482947
  init_messages10();
482532
482948
  init_model2();
482533
482949
  init_mods();
482950
+ init_monitors3();
482534
482951
  init_permissions2();
482535
482952
  init_sandbox2();
482536
482953
  init_secret();
@@ -513213,7 +513630,7 @@ var init_ToolCallMessageRich = __esm(async () => {
513213
513630
  let shellSemanticKind = null;
513214
513631
  let hasShellDescription = false;
513215
513632
  if (!isQuestionTool(rawName)) {
513216
- const parseArgs27 = () => {
513633
+ const parseArgs28 = () => {
513217
513634
  if (!argsText.trim()) {
513218
513635
  return { formatted: null, parseable: true };
513219
513636
  }
@@ -513227,7 +513644,7 @@ var init_ToolCallMessageRich = __esm(async () => {
513227
513644
  return { formatted: null, parseable: false };
513228
513645
  }
513229
513646
  };
513230
- const { formatted, parseable } = parseArgs27();
513647
+ const { formatted, parseable } = parseArgs28();
513231
513648
  const argsComplete = parseable || line.phase === "running" || line.phase === "finished" || !isStreaming;
513232
513649
  if (!argsComplete) {
513233
513650
  args = "(…)";
@@ -515361,7 +515778,7 @@ function updateCommandResult(buffersRef, refreshDerived, cmdId, input, output, s
515361
515778
  buffersRef.current.byId.set(cmdId, line);
515362
515779
  refreshDerived();
515363
515780
  }
515364
- function parseArgs27(msg) {
515781
+ function parseArgs28(msg) {
515365
515782
  return msg.trim().split(/\s+/).filter(Boolean);
515366
515783
  }
515367
515784
  function formatConnectUsage() {
@@ -515746,7 +516163,7 @@ ${formatBedrockUsage2()}`, false);
515746
516163
  }
515747
516164
  }
515748
516165
  async function handleConnect(ctx, msg) {
515749
- const parts = parseArgs27(msg);
516166
+ const parts = parseArgs28(msg);
515750
516167
  const providerToken = parts[1];
515751
516168
  if (!providerToken) {
515752
516169
  addCommandResult(ctx.buffersRef, ctx.refreshDerived, msg, formatConnectUsage(), false);
@@ -533412,6 +533829,7 @@ Note: Flags should use double dashes for full names (e.g., --yolo, not -yolo)`);
533412
533829
  });
533413
533830
  const requestedMemoryPromptMode = memfsFlag ? "memfs" : undefined;
533414
533831
  const shouldAutoEnableMemfsForNewAgent = !memfsFlag;
533832
+ process.env.LETTA_RUNTIME_SESSION_SOURCE = isHeadless ? "headless" : "interactive-cli";
533415
533833
  telemetry.setSurface(getTerminalTelemetrySurface(isHeadless));
533416
533834
  telemetry.init({ handleSigint: !isHeadless });
533417
533835
  if (!isHeadless) {
@@ -536884,4 +537302,4 @@ function registerBunOAuthFlows() {
536884
537302
  registerBunOAuthFlows();
536885
537303
  await init_src5().then(() => exports_src2);
536886
537304
 
536887
- //# debugId=A36F7BFC09468D8164756E2164756E21
537305
+ //# debugId=F554CFFB3971F63D64756E2164756E21