@letta-ai/letta-code 0.34.67 → 0.34.69

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 (35) 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/agent/subagents/subagent-model.d.ts.map +1 -1
  6. package/dist/types/backend/api/usage-cost.d.ts.map +1 -1
  7. package/dist/types/cli/helpers/stream-terminal-eof-guard.d.ts +1 -0
  8. package/dist/types/cli/helpers/stream-terminal-eof-guard.d.ts.map +1 -1
  9. package/dist/types/tools/impl/bash.d.ts +2 -0
  10. package/dist/types/tools/impl/bash.d.ts.map +1 -1
  11. package/dist/types/tools/impl/external-llm-trace-payload.d.ts +4 -0
  12. package/dist/types/tools/impl/external-llm-trace-payload.d.ts.map +1 -1
  13. package/dist/types/tools/impl/external-llm-trace-proxy.d.ts +4 -1
  14. package/dist/types/tools/impl/external-llm-trace-proxy.d.ts.map +1 -1
  15. package/dist/types/tools/impl/external-llm-trace-session.d.ts.map +1 -1
  16. package/dist/types/tools/impl/process_manager.d.ts +1 -0
  17. package/dist/types/tools/impl/process_manager.d.ts.map +1 -1
  18. package/dist/types/tools/impl/shell-runner.d.ts +3 -0
  19. package/dist/types/tools/impl/shell-runner.d.ts.map +1 -1
  20. package/dist/types/tools/impl/task-create.d.ts +2 -2
  21. package/dist/types/tools/impl/task-create.d.ts.map +1 -1
  22. package/dist/types/tools/impl/task-get.d.ts +2 -2
  23. package/dist/types/tools/impl/task-get.d.ts.map +1 -1
  24. package/dist/types/tools/impl/task-list.d.ts +2 -6
  25. package/dist/types/tools/impl/task-list.d.ts.map +1 -1
  26. package/dist/types/tools/impl/task-update.d.ts +2 -2
  27. package/dist/types/tools/impl/task-update.d.ts.map +1 -1
  28. package/dist/types/tools/impl/tasks/store.d.ts +8 -0
  29. package/dist/types/tools/impl/tasks/store.d.ts.map +1 -1
  30. package/dist/types/tools/impl/watch-pr-cloud.d.ts.map +1 -1
  31. package/letta.js +494 -260
  32. package/npm-shrinkwrap.json +107 -103
  33. package/package.json +2 -2
  34. package/scripts/integration/headless-sigterm.py +245 -0
  35. package/scripts/source-file-size-baseline.json +1 -1
package/letta.js CHANGED
@@ -6139,7 +6139,7 @@ var package_default;
6139
6139
  var init_package = __esm(() => {
6140
6140
  package_default = {
6141
6141
  name: "@letta-ai/letta-code",
6142
- version: "0.34.67",
6142
+ version: "0.34.69",
6143
6143
  lettaStartupLogProtocol: 1,
6144
6144
  lettaConfigDirProtocol: 1,
6145
6145
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6426,7 +6426,7 @@ var init_package = __esm(() => {
6426
6426
  },
6427
6427
  lettaLifecycleProtocol: 1,
6428
6428
  lettaRuntimeGraphProtocol: 1,
6429
- lettaRuntimeGraphSha512: "sha512-+DtHUaY2xHV6Ob9xjgAXTnerc8RSQIHn+PKLaEEKhAu1IlKQl0M4rgD/vVKjPHdYxbXyZSrdzEx3UAQZbRbHWw==",
6429
+ lettaRuntimeGraphSha512: "sha512-CTLf4WYRYSuRg7EHRwPqT+Pn4zKpkZ0x/1eEdhxqa/gMYFqilj78CiHQEtP6nKQuLVzweBGOVrLtoDKnvu5Z3A==",
6430
6430
  patchedDependencies: {
6431
6431
  "@earendil-works/pi-ai@1.5.2": "patches/@earendil-works%2Fpi-ai@1.5.2.patch"
6432
6432
  }
@@ -89810,7 +89810,9 @@ async function conversationCostModel(client, conversationId, agentId, overrideMo
89810
89810
  if (overrideModel)
89811
89811
  return overrideModel;
89812
89812
  if (conversationId !== "default") {
89813
- const conversation = await client.conversations.retrieve(conversationId);
89813
+ const conversation = await client.conversations.retrieve(conversationId, {
89814
+ query: { include_context_message_ids: false }
89815
+ });
89814
89816
  if (conversation.model)
89815
89817
  return conversation.model;
89816
89818
  agentId = conversation.agent_id;
@@ -203475,7 +203477,7 @@ var init_mcp_client = __esm(() => {
203475
203477
  init_streamableHttp();
203476
203478
  DEFAULT_CLIENT_INFO = {
203477
203479
  name: "letta-code",
203478
- version: "0.34.67"
203480
+ version: "0.34.69"
203479
203481
  };
203480
203482
  });
203481
203483
 
@@ -207758,7 +207760,7 @@ Usage notes:
207758
207760
  var init_AskUserQuestion = () => {};
207759
207761
 
207760
207762
  // src/tools/descriptions/Bash.md
207761
- var Bash_default = "Executes a shell command and returns its output.\n\n- Each Bash call starts from the conversation's current working directory. A `cd` affects only that command and does not change the directory used by later tool calls. To change the working directory for later tool calls, use `SetWorkingDirectory`. For a one-off command elsewhere, use an absolute path or an option such as `git -C /path/to/repo status`.\n- IMPORTANT: Avoid using this tool to run `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed. Use Read, Edit and Write for file operations instead. Quote paths that contain spaces.\n- Command output is displayed to you, not reliably to the user.\n- `timeout` is in milliseconds. Without it, commands run until they exit; foreground timeouts max out at 600000.\n- If the output exceeds 30000 characters, you receive only the first 2000 characters plus the path of a file containing the full output. A failed command whose output exceeds 10000 characters returns a head-and-tail excerpt plus that file path. Read or search that file when you need the rest instead of re-running the command.\n- Commands still running after a brief wait continue in the background automatically: you receive a task ID and one completion notification. Do not predict command duration, set `run_in_background` merely because a command may be slow, or poll for completion. Set `run_in_background` only when you want the task ID immediately; no `&` needed.\n- Foreground `sleep` is blocked. To wait for a condition, use Monitor.\n- Run independent commands as parallel tool calls; chain dependent ones with `&&`.\n\n# Git\n- Interactive flags (`-i`, e.g. `git rebase -i`, `git add -i`) are not supported in this environment.\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- GitHub notifies the owner of any `@name` written in a PR, issue, or comment. Write a bare `@name` only for a real login you mean to notify. Put roles, placeholders, and code (`@human`, `@reviewer`, `@types/node`) in backticks or drop the `@`.\n- Commit or push only when the user asks. Do not amend, skip hooks, force-push, or run other destructive git commands unless the user asks; if a pre-commit hook fails, fix the issue and create a new commit.\n- Pass commit messages and PR bodies as single-quoted strings with embedded newlines. Do not wrap them in `$(...)` or backticks. End commit messages with:\n{{COMMIT_TRAILER}}\n<example>\ngit commit -m 'Commit message here.\n\n{{COMMIT_TRAILER}}'\n</example>\n- Passing `gh pr checks` does not mean GitHub will merge the PR — unresolved review threads and still-pending required checks leave the merge state BLOCKED. If WatchPR is available and you will follow the PR toward merge, start it on the PR URL, and call the PR ready, green, or mergeable only once WatchPR reports it merge-ready.\n";
207763
+ var Bash_default = "Executes a shell command and returns its output.\n\n- Each Bash call starts from the conversation's current working directory. A `cd` affects only that command and does not change the directory used by later tool calls. To change the working directory for later tool calls, use `SetWorkingDirectory`. For a one-off command elsewhere, use an absolute path or an option such as `git -C /path/to/repo status`.\n- IMPORTANT: Avoid using this tool to run `cat`, `head`, `tail`, `sed`, `awk`, or `echo` commands, unless explicitly instructed. Use Read, Edit and Write for file operations instead. Quote paths that contain spaces.\n- Command output is displayed to you, not reliably to the user.\n- `timeout` is in milliseconds; foreground timeouts max out at 600000. Without it, a command that can't continue in the background times out after 120000; others run until they exit.\n- If the output exceeds 30000 characters, you receive only the first 2000 characters plus the path of a file containing the full output. A failed command whose output exceeds 10000 characters returns a head-and-tail excerpt plus that file path. Read or search that file when you need the rest instead of re-running the command.\n- Commands still running after a brief wait continue in the background automatically: you receive a task ID and one completion notification. Do not predict command duration, set `run_in_background` merely because a command may be slow, or poll for completion. Set `run_in_background` only when you want the task ID immediately; no `&` needed.\n- Foreground `sleep` is blocked. To wait for a condition, use Monitor.\n- Run independent commands as parallel tool calls; chain dependent ones with `&&`.\n\n# Git\n- Interactive flags (`-i`, e.g. `git rebase -i`, `git add -i`) are not supported in this environment.\n- Use the `gh` CLI for GitHub operations (PRs, issues, API).\n- GitHub notifies the owner of any `@name` written in a PR, issue, or comment. Write a bare `@name` only for a real login you mean to notify. Put roles, placeholders, and code (`@human`, `@reviewer`, `@types/node`) in backticks or drop the `@`.\n- Commit or push only when the user asks. Do not amend, skip hooks, force-push, or run other destructive git commands unless the user asks; if a pre-commit hook fails, fix the issue and create a new commit.\n- Pass commit messages and PR bodies as single-quoted strings with embedded newlines. Do not wrap them in `$(...)` or backticks. End commit messages with:\n{{COMMIT_TRAILER}}\n<example>\ngit commit -m 'Commit message here.\n\n{{COMMIT_TRAILER}}'\n</example>\n- Passing `gh pr checks` does not mean GitHub will merge the PR — unresolved review threads and still-pending required checks leave the merge state BLOCKED. If WatchPR is available and you will follow the PR toward merge, start it on the PR URL, and call the PR ready, green, or mergeable only once WatchPR reports it merge-ready.\n";
207762
207764
  var init_Bash = () => {};
207763
207765
 
207764
207766
  // src/tools/descriptions/CodeMode.md
@@ -211737,7 +211739,9 @@ function spawnPipeProcess(launcher, options, events) {
211737
211739
  events.output(chunk2, "stderr");
211738
211740
  });
211739
211741
  childProcess2.on("error", events.error);
211740
- childProcess2.on("close", events.close);
211742
+ childProcess2.on("close", (code, signal) => {
211743
+ events.close(code, signal, process.platform === "win32" ? undefined : childProcess2.pid);
211744
+ });
211741
211745
  return {
211742
211746
  kill: createPipeProcessKiller(childProcess2),
211743
211747
  interrupt() {
@@ -211886,19 +211890,21 @@ function startShellProcess(launcher, options) {
211886
211890
  broker?.close();
211887
211891
  };
211888
211892
  let processHandle;
211893
+ let forceKillIssued = false;
211894
+ let finishGroupClose;
211889
211895
  const terminateProcess = () => {
211896
+ if (completed || forceKillTimer)
211897
+ return;
211890
211898
  if (process.platform === "win32") {
211891
211899
  processHandle.kill("SIGKILL");
211892
211900
  return;
211893
211901
  }
211894
211902
  processHandle.kill("SIGTERM");
211895
- if (!forceKillTimer) {
211896
- forceKillTimer = setTimeout(() => {
211897
- if (!completed) {
211898
- processHandle.kill("SIGKILL");
211899
- }
211900
- }, FORCE_KILL_GRACE_MS);
211901
- }
211903
+ forceKillTimer = setTimeout(() => {
211904
+ forceKillIssued = true;
211905
+ processHandle.kill("SIGKILL");
211906
+ finishGroupClose?.();
211907
+ }, FORCE_KILL_GRACE_MS);
211902
211908
  };
211903
211909
  const abortHandler = () => {
211904
211910
  terminateProcess();
@@ -211941,9 +211947,21 @@ function startShellProcess(launcher, options) {
211941
211947
  pullRequestTracker?.finish();
211942
211948
  rejectCompletion(buildSpawnError(error4, executable, options.cwd));
211943
211949
  },
211944
- close(code, signal) {
211950
+ close(code, signal, processGroup) {
211945
211951
  if (completed)
211946
211952
  return;
211953
+ if (launchOptions.waitForProcessGroupOnClose && forceKillTimer && !forceKillIssued && processGroup !== undefined) {
211954
+ let groupExists = true;
211955
+ try {
211956
+ process.kill(-processGroup, 0);
211957
+ } catch (error4) {
211958
+ groupExists = error4.code !== "ESRCH";
211959
+ }
211960
+ if (groupExists) {
211961
+ finishGroupClose = () => events.close(code, signal);
211962
+ return;
211963
+ }
211964
+ }
211947
211965
  completed = true;
211948
211966
  cleanup();
211949
211967
  flushOutputDecoders();
@@ -213747,6 +213765,7 @@ var init_windows_command_safety = __esm(() => {
213747
213765
  // src/tools/impl/bash.ts
213748
213766
  var exports_bash = {};
213749
213767
  __export(exports_bash, {
213768
+ waitForForegroundBashCleanup: () => waitForForegroundBashCleanup,
213750
213769
  spawnCommand: () => spawnCommand,
213751
213770
  getBackgroundLauncher: () => getBackgroundLauncher,
213752
213771
  bash: () => bash,
@@ -213989,13 +214008,15 @@ async function bash(args) {
213989
214008
  let bgProcess;
213990
214009
  let outputWriteFailed = false;
213991
214010
  const foregroundOutput = { stdout: "", stderr: "" };
213992
- const effectiveTimeout = run_in_background ? timeout !== undefined && timeout > 0 ? timeout : 0 : timeout === undefined ? 0 : Math.min(Math.max(timeout, 1), 600000);
214011
+ const canYield = !run_in_background && isQueueBridgeConnected();
214012
+ const effectiveTimeout = run_in_background ? timeout !== undefined && timeout > 0 ? timeout : 0 : timeout !== undefined ? Math.min(Math.max(timeout, 1), MAX_FOREGROUND_TIMEOUT_MS) : canYield ? 0 : NON_YIELDING_DEFAULT_TIMEOUT_MS;
213993
214013
  const runningProcess = shellProcessStarter(sandboxed.launcher, {
213994
214014
  cwd: userCwd,
213995
214015
  env: sandboxed.env,
213996
214016
  timeoutMs: effectiveTimeout,
213997
214017
  sourceCommand: command,
213998
214018
  signal: run_in_background ? undefined : signal,
214019
+ waitForProcessGroupOnClose: !run_in_background,
213999
214020
  captureOutput: false,
214000
214021
  onOutput(text2, stream11) {
214001
214022
  const sanitizedText = streamScrubbers[stream11].push(text2);
@@ -214021,6 +214042,7 @@ async function bash(args) {
214021
214042
  process: runningProcess.process,
214022
214043
  completion: runningProcess.completion,
214023
214044
  terminate: runningProcess.terminate,
214045
+ foregroundBash: !run_in_background,
214024
214046
  command,
214025
214047
  stdout: [],
214026
214048
  stderr: [],
@@ -214099,7 +214121,7 @@ async function bash(args) {
214099
214121
  type: "settled",
214100
214122
  result: result2
214101
214123
  }));
214102
- const outcome = isQueueBridgeConnected() ? await Promise.race([
214124
+ const outcome = canYield ? await Promise.race([
214103
214125
  settledOutcome,
214104
214126
  new Promise((resolve19) => {
214105
214127
  const timer = setTimeout(() => resolve19({ type: "yield" }), Math.max(0, foregroundYieldMs));
@@ -214138,7 +214160,7 @@ ${truncatedOutput}`
214138
214160
  status: "success"
214139
214161
  };
214140
214162
  }
214141
- backgroundProcesses.set(bashId, bgProcess);
214163
+ bgProcess.foregroundBash = false;
214142
214164
  notifyWhenSettled();
214143
214165
  return {
214144
214166
  content: [
@@ -214164,7 +214186,25 @@ Output file: ${outputFile}`
214164
214186
  status: "success"
214165
214187
  };
214166
214188
  }
214167
- var cachedWorkingLauncher = null, shellProcessStarter, NOTIFICATION_TAIL_LINES = 50;
214189
+ async function waitForForegroundBashCleanup() {
214190
+ const active = [...backgroundProcesses.values()].filter((entry) => entry.foregroundBash);
214191
+ if (active.length === 0)
214192
+ return;
214193
+ for (const entry of active)
214194
+ entry.terminate?.();
214195
+ let timer;
214196
+ try {
214197
+ await Promise.race([
214198
+ Promise.allSettled(active.map((entry) => entry.completion)),
214199
+ new Promise((resolve19) => {
214200
+ timer = setTimeout(resolve19, FORCE_KILL_GRACE_MS + 250);
214201
+ })
214202
+ ]);
214203
+ } finally {
214204
+ clearTimeout(timer);
214205
+ }
214206
+ }
214207
+ var cachedWorkingLauncher = null, NON_YIELDING_DEFAULT_TIMEOUT_MS = 120000, MAX_FOREGROUND_TIMEOUT_MS = 600000, shellProcessStarter, NOTIFICATION_TAIL_LINES = 50;
214168
214208
  var init_bash = __esm(() => {
214169
214209
  init_constants2();
214170
214210
  init_runtime_context();
@@ -239752,23 +239792,84 @@ function assembleTraceResponse(raw2, streaming3) {
239752
239792
  };
239753
239793
  }
239754
239794
  }
239755
- var MAX_TRACE_PAYLOAD_BYTES, SENSITIVE;
239795
+ function traceJsonFits(bytes, encodedBytes) {
239796
+ return bytes <= MAX_TRACE_PAYLOAD_BYTES && encodedBytes <= MAX_ENCODED_PAYLOAD_BYTES;
239797
+ }
239798
+ function tracePayloadFits(json2) {
239799
+ return traceJsonFits(Buffer.byteLength(json2), Buffer.byteLength(JSON.stringify(json2)));
239800
+ }
239801
+ function compactTracePayload(json2) {
239802
+ const payload = JSON.parse(json2);
239803
+ if (!payload || typeof payload !== "object")
239804
+ return TRUNCATED_TRACE_JSON;
239805
+ if (!Array.isArray(payload)) {
239806
+ const object4 = payload;
239807
+ delete object4.system;
239808
+ delete object4.tools;
239809
+ delete object4.truncated;
239810
+ }
239811
+ const marked = () => JSON.stringify(Array.isArray(payload) ? { items: payload, ...truncated } : { ...payload, ...truncated });
239812
+ const initial2 = marked();
239813
+ let bytes = Buffer.byteLength(initial2);
239814
+ let encodedBytes = Buffer.byteLength(JSON.stringify(initial2));
239815
+ if (traceJsonFits(bytes, encodedBytes))
239816
+ return initial2;
239817
+ const candidates = [];
239818
+ function collect(container) {
239819
+ for (const [key2, value] of Object.entries(container)) {
239820
+ if (Array.isArray(value) || key2 === "response" && value && typeof value === "object") {
239821
+ collect(value);
239822
+ continue;
239823
+ }
239824
+ const serialized = JSON.stringify(value);
239825
+ const bytes2 = Buffer.byteLength(serialized) - Buffer.byteLength(TRUNCATED_TRACE_JSON);
239826
+ const encodedBytes2 = Buffer.byteLength(JSON.stringify(serialized)) - Buffer.byteLength(JSON.stringify(TRUNCATED_TRACE_JSON));
239827
+ if (bytes2 > 0 && encodedBytes2 > 0) {
239828
+ candidates.push({
239829
+ bytes: bytes2,
239830
+ encodedBytes: encodedBytes2,
239831
+ replace: () => {
239832
+ container[key2] = truncated;
239833
+ }
239834
+ });
239835
+ }
239836
+ }
239837
+ }
239838
+ collect(payload);
239839
+ candidates.sort((a2, b3) => b3.bytes - a2.bytes);
239840
+ for (const candidate of candidates) {
239841
+ if (traceJsonFits(bytes, encodedBytes))
239842
+ break;
239843
+ candidate.replace();
239844
+ bytes -= candidate.bytes;
239845
+ encodedBytes -= candidate.encodedBytes;
239846
+ }
239847
+ return traceJsonFits(bytes, encodedBytes) ? marked() : TRUNCATED_TRACE_JSON;
239848
+ }
239849
+ var MAX_TRACE_PAYLOAD_BYTES, SENSITIVE, MAX_TRACE_BUFFER_BYTES, MAX_ENCODED_PAYLOAD_BYTES, truncated, TRUNCATED_TRACE_JSON;
239756
239850
  var init_external_llm_trace_payload = __esm(() => {
239757
239851
  init_server_url();
239758
239852
  MAX_TRACE_PAYLOAD_BYTES = 2 * 1024 * 1024;
239759
239853
  SENSITIVE = /^(authorization|proxy-authorization|x-api-key|api[_-]?key|cookies?|set-cookie|x-auth-token|access[_-]?token|refresh[_-]?token|client[_-]?secret|password|secret)$/i;
239854
+ MAX_TRACE_BUFFER_BYTES = 16 * 1024 * 1024;
239855
+ MAX_ENCODED_PAYLOAD_BYTES = 3 * 1024 * 1024;
239856
+ truncated = { truncated: "size_limit" };
239857
+ TRUNCATED_TRACE_JSON = JSON.stringify(truncated);
239760
239858
  });
239761
239859
 
239762
239860
  // src/tools/impl/external-llm-trace-proxy.ts
239763
239861
  import { randomUUID as randomUUID39 } from "node:crypto";
239764
239862
  import { createServer as createServer6, request as httpRequest3 } from "node:http";
239765
239863
  import { request as httpsRequest2 } from "node:https";
239864
+ import { isDeepStrictEqual } from "node:util";
239766
239865
  import { brotliDecompressSync, gunzipSync, inflateSync } from "node:zlib";
239767
239866
  async function startTraceProxy(options) {
239768
239867
  const upstream = new URL(options.upstream);
239769
239868
  if (!["http:", "https:"].includes(upstream.protocol) || upstream.username || upstream.password)
239770
239869
  throw new Error("Unsupported trace upstream");
239771
239870
  const prefix = `/${randomUUID39()}`;
239871
+ const historyKey = options.harness === "claude_code" ? "messages" : "input";
239872
+ let previous;
239772
239873
  let activeCaptures = 0;
239773
239874
  const pending2 = new Set;
239774
239875
  const server2 = createServer6((req, res) => {
@@ -239815,37 +239916,51 @@ async function startTraceProxy(options) {
239815
239916
  work.finally(() => pending2.delete(work));
239816
239917
  };
239817
239918
  const processCapture = (transportError) => {
239818
- let oversized = !captureBody || requestBytes > MAX_TRACE_PAYLOAD_BYTES || responseBytes > MAX_TRACE_PAYLOAD_BYTES;
239819
- const requestRaw = oversized ? "{}" : Buffer.concat(requestChunks).toString("utf8");
239919
+ const id = randomUUID39();
239920
+ const requestBuffered = captureBody && requestBytes <= MAX_TRACE_BUFFER_BYTES;
239921
+ let responseBuffered = captureBody && responseBytes <= MAX_TRACE_BUFFER_BYTES;
239820
239922
  let responseRaw = Buffer.concat(responseChunks);
239821
239923
  try {
239822
239924
  const decoder2 = encoding === "gzip" ? gunzipSync : encoding === "deflate" ? inflateSync : encoding === "br" ? brotliDecompressSync : undefined;
239823
- if (decoder2)
239925
+ if (decoder2 && responseBuffered)
239824
239926
  responseRaw = decoder2(responseRaw, {
239825
- maxOutputLength: MAX_TRACE_PAYLOAD_BYTES
239927
+ maxOutputLength: MAX_TRACE_BUFFER_BYTES
239826
239928
  });
239827
239929
  } catch {
239828
- oversized = true;
239930
+ responseBuffered = false;
239829
239931
  }
239830
- const responseText = oversized ? "" : responseRaw.toString("utf8");
239932
+ const responseText = responseBuffered ? responseRaw.toString("utf8") : "";
239831
239933
  streaming3 ||= /(?:^|\r?\n)data:/.test(responseText);
239832
239934
  const assembled = assembleTraceResponse(responseText, streaming3);
239833
- let responseJson = sanitizeTraceJson(JSON.stringify(oversized ? { omitted: "size_limit" } : streaming3 ? assembled : assembled.response), credentials);
239834
- if (Buffer.byteLength(responseJson) > MAX_TRACE_PAYLOAD_BYTES) {
239835
- oversized = true;
239836
- responseJson = '{"omitted":"size_limit"}';
239837
- }
239838
- let requestJson = sanitizeTraceJson(oversized ? '{"omitted":"size_limit"}' : requestRaw, credentials);
239839
- if (Buffer.byteLength(requestJson) > MAX_TRACE_PAYLOAD_BYTES) {
239840
- oversized = true;
239841
- requestJson = '{"omitted":"size_limit"}';
239935
+ let responseJson = responseBuffered ? sanitizeTraceJson(JSON.stringify(streaming3 ? assembled : assembled.response), credentials) : TRUNCATED_TRACE_JSON;
239936
+ const responseTruncated = !responseBuffered || !tracePayloadFits(responseJson);
239937
+ if (responseBuffered && responseTruncated)
239938
+ responseJson = compactTracePayload(responseJson);
239939
+ let requestJson = requestBuffered ? sanitizeTraceJson(Buffer.concat(requestChunks).toString("utf8"), credentials) : TRUNCATED_TRACE_JSON;
239940
+ const request3 = JSON.parse(requestJson);
239941
+ const items = request3?.[historyKey];
239942
+ const requestTruncated = !requestBuffered || !tracePayloadFits(requestJson);
239943
+ let delta;
239944
+ if (requestBuffered && requestTruncated) {
239945
+ const fallbackJson = compactTracePayload(requestJson);
239946
+ requestJson = fallbackJson;
239947
+ if (previous?.sessionId === scope.worker_session_id && Array.isArray(items)) {
239948
+ const prefixItems = previous.items.length;
239949
+ if (prefixItems > 0 && items.length > prefixItems && previous.items.every((item, index) => isDeepStrictEqual(item, items[index]))) {
239950
+ const deltaJson = JSON.stringify({
239951
+ ...request3,
239952
+ [historyKey]: items.slice(prefixItems),
239953
+ base_trace_id: previous.id,
239954
+ prefix_items: prefixItems
239955
+ });
239956
+ if (tracePayloadFits(deltaJson)) {
239957
+ requestJson = deltaJson;
239958
+ delta = { baseId: previous.id, fallbackJson };
239959
+ }
239960
+ }
239961
+ }
239842
239962
  }
239843
- let request3 = {};
239844
- try {
239845
- const parsed = JSON.parse(requestRaw);
239846
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
239847
- request3 = parsed;
239848
- } catch {}
239963
+ previous = Array.isArray(items) && (!requestTruncated || delta) ? { id, sessionId: scope.worker_session_id, items } : undefined;
239849
239964
  const response = assembled.response;
239850
239965
  const usage = response.usage ?? {};
239851
239966
  const token2 = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.min(Math.trunc(value), 4294967295) : null;
@@ -239858,9 +239973,9 @@ async function startTraceProxy(options) {
239858
239973
  const error4 = transportError || status >= 400 || Boolean(response.error) || response.status === "failed";
239859
239974
  options.emit({
239860
239975
  ...scope,
239861
- id: randomUUID39(),
239976
+ id,
239862
239977
  harness: options.harness,
239863
- model: JSON.parse(sanitizeTraceJson(JSON.stringify(String(response.model ?? request3.model ?? "")), credentials)).slice(0, 255),
239978
+ model: JSON.parse(sanitizeTraceJson(JSON.stringify(String(response.model ?? request3?.model ?? "")), credentials)).slice(0, 255),
239864
239979
  request_json: requestJson,
239865
239980
  response_json: responseJson,
239866
239981
  request_size_bytes: Math.min(requestBytes, 4294967295),
@@ -239877,9 +239992,9 @@ async function startTraceProxy(options) {
239877
239992
  is_error: error4 ? 1 : 0,
239878
239993
  error_type: transportError ? "transport_error" : error4 ? "provider_error" : "",
239879
239994
  error_message: "",
239880
- capture_status: oversized ? "size_limit" : transportError || !assembled.complete ? "incomplete" : "complete",
239995
+ capture_status: delta ? "delta" : requestTruncated || responseTruncated ? "size_limit" : transportError || !assembled.complete ? "incomplete" : "complete",
239881
239996
  created_at: created
239882
- });
239997
+ }, delta);
239883
239998
  };
239884
239999
  const headers = {
239885
240000
  ...req.headers,
@@ -239901,7 +240016,7 @@ async function startTraceProxy(options) {
239901
240016
  if (!capture)
239902
240017
  return;
239903
240018
  responseBytes += chunk2.length;
239904
- if (captureBody && responseBytes <= MAX_TRACE_PAYLOAD_BYTES)
240019
+ if (captureBody && responseBytes <= MAX_TRACE_BUFFER_BYTES)
239905
240020
  responseChunks.push(Buffer.from(chunk2));
239906
240021
  else
239907
240022
  responseChunks.length = 0;
@@ -239923,7 +240038,7 @@ async function startTraceProxy(options) {
239923
240038
  if (!capture)
239924
240039
  return;
239925
240040
  requestBytes += chunk2.length;
239926
- if (captureBody && requestBytes <= MAX_TRACE_PAYLOAD_BYTES)
240041
+ if (captureBody && requestBytes <= MAX_TRACE_BUFFER_BYTES)
239927
240042
  requestChunks.push(Buffer.from(chunk2));
239928
240043
  else
239929
240044
  requestChunks.length = 0;
@@ -240002,6 +240117,7 @@ async function createTraceSession(harness, context3, env6, upstream, workerSessi
240002
240117
  const scope = { ...ids, worker_session_id: workerSessionId };
240003
240118
  sessionScopes.set(workerSessionId, scope);
240004
240119
  const queue = [];
240120
+ let uploadedBaseId;
240005
240121
  let bytes = 0;
240006
240122
  let draining;
240007
240123
  let closed = false;
@@ -240017,13 +240133,23 @@ async function createTraceSession(harness, context3, env6, upstream, workerSessi
240017
240133
  break;
240018
240134
  }
240019
240135
  const batch = [];
240020
- let size2 = 0;
240021
- for (const row of queue) {
240022
- const next = Buffer.byteLength(JSON.stringify(row));
240023
- if (batch.length && (size2 + next > 7 * 1024 * 1024 || batch.length === 20))
240136
+ let batchBytes = TRACE_BATCH_ENVELOPE_BYTES;
240137
+ let baseId = uploadedBaseId;
240138
+ let queuedBytes = 0;
240139
+ for (const entry of queue) {
240140
+ const fallback = entry.delta?.baseId !== baseId ? entry.delta : undefined;
240141
+ const row = fallback ? {
240142
+ ...entry.row,
240143
+ request_json: fallback.fallbackJson,
240144
+ capture_status: "size_limit"
240145
+ } : entry.row;
240146
+ const nextBytes = Buffer.byteLength(JSON.stringify(row)) + (batch.length ? 1 : 0);
240147
+ if (batchBytes + nextBytes > MAX_TRACE_BATCH_BYTES || batch.length === 20)
240024
240148
  break;
240025
240149
  batch.push(row);
240026
- size2 += next;
240150
+ batchBytes += nextBytes;
240151
+ queuedBytes += entry.size;
240152
+ baseId = fallback ? undefined : row.id;
240027
240153
  }
240028
240154
  let success = false;
240029
240155
  let lastError;
@@ -240043,7 +240169,9 @@ async function createTraceSession(harness, context3, env6, upstream, workerSessi
240043
240169
  warn(`External trace upload failed: ${describeUploadError(lastError, secrets2)} rows=${batch.length} harness=${harness} conversation=${context3.parent_conversation_id}`);
240044
240170
  }
240045
240171
  queue.splice(0, batch.length);
240046
- bytes -= size2;
240172
+ bytes -= queuedBytes;
240173
+ if (success)
240174
+ uploadedBaseId = baseId;
240047
240175
  if (!success && closed) {
240048
240176
  queue.length = 0;
240049
240177
  bytes = 0;
@@ -240065,17 +240193,21 @@ async function createTraceSession(harness, context3, env6, upstream, workerSessi
240065
240193
  harness,
240066
240194
  scope,
240067
240195
  secrets: secrets2,
240068
- emit: (row) => {
240196
+ emit: (row, delta) => {
240069
240197
  if (closed || !traceCaptureEnabled(process.env, config2.baseUrl, config2.apiKey))
240070
240198
  return;
240071
- if (Buffer.byteLength(JSON.stringify(row)) > 7 * 1024 * 1024) {
240072
- row.request_json = row.response_json = '{"omitted":"size_limit"}';
240073
- row.capture_status = "size_limit";
240074
- }
240075
- const size2 = Buffer.byteLength(JSON.stringify(row));
240199
+ const rowBytes = Buffer.byteLength(JSON.stringify(row));
240200
+ const fallbackBytes = delta ? Buffer.byteLength(JSON.stringify({
240201
+ ...row,
240202
+ request_json: delta.fallbackJson,
240203
+ capture_status: "size_limit"
240204
+ })) : 0;
240205
+ if (Math.max(rowBytes, fallbackBytes) + TRACE_BATCH_ENVELOPE_BYTES > MAX_TRACE_BATCH_BYTES)
240206
+ return;
240207
+ const size2 = rowBytes + (delta ? Buffer.byteLength(delta.fallbackJson) : 0);
240076
240208
  if (bytes + size2 > 64 * 1024 * 1024)
240077
240209
  return;
240078
- queue.push(row);
240210
+ queue.push({ row, delta, size: size2 });
240079
240211
  bytes += size2;
240080
240212
  if (queue.length >= 10)
240081
240213
  flush();
@@ -240106,7 +240238,7 @@ async function createTraceSession(harness, context3, env6, upstream, workerSessi
240106
240238
  return;
240107
240239
  }
240108
240240
  }
240109
- var sessionScopes, WARN_INTERVAL_MS = 60000, productionDependencies;
240241
+ var sessionScopes, WARN_INTERVAL_MS = 60000, MAX_TRACE_BATCH_BYTES, TRACE_BATCH_ENVELOPE_BYTES, productionDependencies;
240110
240242
  var init_external_llm_trace_session = __esm(() => {
240111
240243
  init_request();
240112
240244
  init_backend_mode();
@@ -240114,6 +240246,8 @@ var init_external_llm_trace_session = __esm(() => {
240114
240246
  init_external_llm_trace_payload();
240115
240247
  init_external_llm_trace_proxy();
240116
240248
  sessionScopes = new Map;
240249
+ MAX_TRACE_BATCH_BYTES = 8 * 1024 * 1024;
240250
+ TRACE_BATCH_ENVELOPE_BYTES = Buffer.byteLength('{"rows":[]}');
240117
240251
  productionDependencies = {
240118
240252
  getConfig: getApiRequestConfig,
240119
240253
  async upload(rows, config2, context3) {
@@ -241183,7 +241317,7 @@ class CodexAppServerClient {
241183
241317
  await this.request("initialize", {
241184
241318
  clientInfo: {
241185
241319
  name: "letta-code",
241186
- version: "0.34.67"
241320
+ version: "0.34.69"
241187
241321
  },
241188
241322
  capabilities: null
241189
241323
  });
@@ -244611,7 +244745,9 @@ async function getPrimaryAgentModelHandle(scope = {}) {
244611
244745
  const conversationId = scope.conversationId;
244612
244746
  if (conversationId && conversationId !== "default") {
244613
244747
  try {
244614
- const conversation = await getBackend().retrieveConversation(conversationId);
244748
+ const conversation = await getBackend().retrieveConversation(conversationId, {
244749
+ query: { include_context_message_ids: false }
244750
+ });
244615
244751
  const conversationHandle = getModelHandleFromAgent(conversation);
244616
244752
  if (conversationHandle) {
244617
244753
  return { handle: conversationHandle, agent };
@@ -249029,7 +249165,7 @@ function getMemorySkillsDirs2(agentId) {
249029
249165
  function listSkillResources(skillMdPath) {
249030
249166
  const skillDir = dirname31(skillMdPath);
249031
249167
  const paths = [];
249032
- let truncated = false;
249168
+ let truncated2 = false;
249033
249169
  function walk3(directory, relativeDirectory) {
249034
249170
  let entries2;
249035
249171
  try {
@@ -249043,12 +249179,12 @@ function listSkillResources(skillMdPath) {
249043
249179
  continue;
249044
249180
  }
249045
249181
  if (paths.length >= MAX_LISTED_SKILL_RESOURCES) {
249046
- truncated = true;
249182
+ truncated2 = true;
249047
249183
  return;
249048
249184
  }
249049
249185
  if (entry.isDirectory()) {
249050
249186
  walk3(join77(directory, entry.name), relativePath);
249051
- if (truncated) {
249187
+ if (truncated2) {
249052
249188
  return;
249053
249189
  }
249054
249190
  } else if (entry.isFile()) {
@@ -249057,7 +249193,7 @@ function listSkillResources(skillMdPath) {
249057
249193
  }
249058
249194
  }
249059
249195
  walk3(skillDir, "");
249060
- return { paths, truncated };
249196
+ return { paths, truncated: truncated2 };
249061
249197
  }
249062
249198
  async function readSkillContent(skillId, skillsDir, agentId, options = {}) {
249063
249199
  const projectSkillsDirs = new Set([
@@ -249258,6 +249394,11 @@ function listTasks2() {
249258
249394
  }
249259
249395
  return out;
249260
249396
  }
249397
+ function getTaskSnapshot() {
249398
+ return {
249399
+ tasks: listTasks2().map((task2, order) => ({ ...task2, order }))
249400
+ };
249401
+ }
249261
249402
  function updateTask2(input) {
249262
249403
  const existing = tasks.get(input.taskId);
249263
249404
  if (!existing) {
@@ -249332,12 +249473,13 @@ async function task_create(args) {
249332
249473
  }
249333
249474
  }
249334
249475
  }
249335
- return createTask({
249476
+ const record5 = createTask({
249336
249477
  subject: args.subject,
249337
249478
  description: args.description,
249338
249479
  activeForm: args.activeForm,
249339
249480
  metadata: args.metadata
249340
249481
  });
249482
+ return { ...record5, ...getTaskSnapshot() };
249341
249483
  }
249342
249484
  var init_task_create = __esm(() => {
249343
249485
  init_store();
@@ -249353,7 +249495,7 @@ async function task_get(args) {
249353
249495
  if (!record5) {
249354
249496
  throw new Error(`TaskGet: task not found: ${args.taskId}`);
249355
249497
  }
249356
- return record5;
249498
+ return { ...record5, ...getTaskSnapshot() };
249357
249499
  }
249358
249500
  var init_task_get = __esm(() => {
249359
249501
  init_store();
@@ -249361,7 +249503,7 @@ var init_task_get = __esm(() => {
249361
249503
 
249362
249504
  // src/tools/impl/task-list.ts
249363
249505
  async function task_list(_args) {
249364
- return { tasks: listTasks2() };
249506
+ return getTaskSnapshot();
249365
249507
  }
249366
249508
  var init_task_list = __esm(() => {
249367
249509
  init_store();
@@ -249399,7 +249541,7 @@ async function task_update(args) {
249399
249541
  const addBlocks = validateStringArray(args.addBlocks, "addBlocks");
249400
249542
  const addBlockedBy = validateStringArray(args.addBlockedBy, "addBlockedBy");
249401
249543
  try {
249402
- return updateTask2({
249544
+ const record5 = updateTask2({
249403
249545
  taskId: args.taskId,
249404
249546
  status: args.status,
249405
249547
  subject: args.subject,
@@ -249410,6 +249552,7 @@ async function task_update(args) {
249410
249552
  addBlockedBy,
249411
249553
  metadata: args.metadata
249412
249554
  });
249555
+ return { ...record5, ...getTaskSnapshot() };
249413
249556
  } catch (err) {
249414
249557
  if (err instanceof TaskNotFoundError) {
249415
249558
  throw new Error(`TaskUpdate: ${err.message}`);
@@ -250721,20 +250864,21 @@ async function startCloudPullRequestWatch(args, deps = {}) {
250721
250864
  }
250722
250865
  throw error4;
250723
250866
  }
250724
- const initial2 = toClientSnapshot(ref, created.initial_snapshot);
250867
+ const initial2 = created.initial_snapshot ? toClientSnapshot(ref, created.initial_snapshot) : undefined;
250868
+ const currentState = initial2 ? `Current state:
250869
+ ${describeGitHubPullRequestSnapshot(initial2)}` : "The current PR state will arrive with the first event.";
250725
250870
  return {
250726
250871
  content: [
250727
250872
  {
250728
250873
  type: "text",
250729
250874
  text: `WatchPR started (task ${created.id}). You will be notified on PR events. It stops when the PR merges/closes, on TaskStop, or at its timeout. Keep working — do not poll or sleep.
250730
250875
 
250731
- Current state:
250732
- ${describeGitHubPullRequestSnapshot(initial2)}`
250876
+ ${currentState}`
250733
250877
  }
250734
250878
  ],
250735
250879
  taskId: created.id,
250736
250880
  url: ref.url,
250737
- headSha: initial2.headSha,
250881
+ headSha: initial2?.headSha ?? "",
250738
250882
  persistent: false
250739
250883
  };
250740
250884
  }
@@ -252365,7 +252509,7 @@ var init_Bash2 = __esm(() => {
252365
252509
  },
252366
252510
  timeout: {
252367
252511
  type: "number",
252368
- description: "Commands run until they exit unless you pass a timeout in milliseconds. Foreground timeouts have a maximum of 600000."
252512
+ description: "Timeout in milliseconds; foreground timeouts have a maximum of 600000. Without it, a command that can't continue in the background times out after 120000; others run until they exit."
252369
252513
  },
252370
252514
  description: {
252371
252515
  type: "string",
@@ -257762,7 +257906,7 @@ var init_turn_finished_replay = __esm(() => {
257762
257906
  });
257763
257907
 
257764
257908
  // src/websocket/listener/input-terminal-journal.ts
257765
- import { isDeepStrictEqual } from "node:util";
257909
+ import { isDeepStrictEqual as isDeepStrictEqual2 } from "node:util";
257766
257910
  function identityKeys(runtime, identities) {
257767
257911
  return [
257768
257912
  ...new Set(identities.map((identity3) => dispositionKey(runtime.key, identity3)))
@@ -258074,7 +258218,7 @@ function claimPreparedInputTerminalIfCurrent(listener, terminal, validatedComple
258074
258218
  if (preparedTerminalMatchesLegacyAuthorityIndex(entry, quarantines)) {
258075
258219
  return false;
258076
258220
  }
258077
- return entry.preparedTerminal !== undefined && isDeepStrictEqual(preparedTerminalWithoutClaim(entry.preparedTerminal), expected);
258221
+ return entry.preparedTerminal !== undefined && isDeepStrictEqual2(preparedTerminalWithoutClaim(entry.preparedTerminal), expected);
258078
258222
  });
258079
258223
  if (matches3.length === 0)
258080
258224
  return { current: false, changed: false };
@@ -258083,7 +258227,7 @@ function claimPreparedInputTerminalIfCurrent(listener, terminal, validatedComple
258083
258227
  if (recoveryLineageId && interruptedRevision) {
258084
258228
  const competingClaim = values4.some((entry) => {
258085
258229
  const prepared = entry.preparedTerminal;
258086
- return prepared?.publicationClaimed === true && prepared.scope.agentId === terminal.scope.agentId && prepared.scope.conversationId === terminal.scope.conversationId && prepared.owner.recoveryLineageId === recoveryLineageId && prepared.owner.interruptedRevision === interruptedRevision && !isDeepStrictEqual(preparedTerminalWithoutClaim(prepared), expected);
258230
+ return prepared?.publicationClaimed === true && prepared.scope.agentId === terminal.scope.agentId && prepared.scope.conversationId === terminal.scope.conversationId && prepared.owner.recoveryLineageId === recoveryLineageId && prepared.owner.interruptedRevision === interruptedRevision && !isDeepStrictEqual2(preparedTerminalWithoutClaim(prepared), expected);
258087
258231
  });
258088
258232
  if (competingClaim) {
258089
258233
  throw new Error("Competing terminal already owns publication claim");
@@ -258092,7 +258236,7 @@ function claimPreparedInputTerminalIfCurrent(listener, terminal, validatedComple
258092
258236
  const runtimeKey = matches3[0]?.runtimeKey;
258093
258237
  const currentAuthorities = values4.filter((entry) => entry.runtimeKey === runtimeKey && entry.completedTerminalAuthority?.recoveryLineageId === recoveryLineageId && entry.completedTerminalAuthority.interruptedRevision === interruptedRevision).map((entry) => completedAuthorityKey(entry.completedTerminalAuthority)).sort();
258094
258238
  const validatedAuthorities = validatedCompletedAuthorities.filter((completed) => completed.runtimeKey === runtimeKey && completed.authority.recoveryLineageId === recoveryLineageId && completed.authority.interruptedRevision === interruptedRevision).map((completed) => completedAuthorityKey(completed.authority)).sort();
258095
- if (!isDeepStrictEqual(currentAuthorities, validatedAuthorities)) {
258239
+ if (!isDeepStrictEqual2(currentAuthorities, validatedAuthorities)) {
258096
258240
  throw new Error("Terminal authority changed before publication claim");
258097
258241
  }
258098
258242
  }
@@ -258139,7 +258283,7 @@ function publishPreparedInputTerminalIfCurrent(listener, terminal, publish, vali
258139
258283
  const publishAndRetire = (entries2) => {
258140
258284
  const values4 = [...entries2.values()];
258141
258285
  const quarantines = buildLegacyAuthorityQuarantineIndex(values4);
258142
- const matches3 = values4.filter((entry) => !preparedTerminalMatchesLegacyAuthorityIndex(entry, quarantines) && entry.preparedTerminal?.publicationClaimed === true && isDeepStrictEqual(preparedTerminalWithoutClaim(entry.preparedTerminal), expected));
258286
+ const matches3 = values4.filter((entry) => !preparedTerminalMatchesLegacyAuthorityIndex(entry, quarantines) && entry.preparedTerminal?.publicationClaimed === true && isDeepStrictEqual2(preparedTerminalWithoutClaim(entry.preparedTerminal), expected));
258143
258287
  if (matches3.length === 0)
258144
258288
  return false;
258145
258289
  publish();
@@ -266026,7 +266170,9 @@ async function resolveScopedModelState(agentId, conversationId) {
266026
266170
  contextWindowLimit: contextWindowFromEntityRecord2(agentRecord)
266027
266171
  };
266028
266172
  if (conversationId !== "default") {
266029
- const conversation = await getBackend().retrieveConversation(conversationId);
266173
+ const conversation = await getBackend().retrieveConversation(conversationId, {
266174
+ query: { include_context_message_ids: false }
266175
+ });
266030
266176
  const conversationRecord = conversation;
266031
266177
  if (typeof conversationRecord.model === "string" && conversationRecord.model.length > 0) {
266032
266178
  state2.handle = conversationRecord.model;
@@ -266572,10 +266718,10 @@ function appendStreamingOutput(state2, chunk2, startTime, isStderr = false) {
266572
266718
  }
266573
266719
  let buffer = partialLine + chunk2;
266574
266720
  if (buffer.length > MAX_BUFFER_SIZE) {
266575
- const truncated = buffer.slice(-MAX_BUFFER_SIZE);
266576
- const firstNewline = truncated.indexOf(`
266721
+ const truncated2 = buffer.slice(-MAX_BUFFER_SIZE);
266722
+ const firstNewline = truncated2.indexOf(`
266577
266723
  `);
266578
- buffer = firstNewline >= 0 ? truncated.slice(firstNewline + 1) : truncated;
266724
+ buffer = firstNewline >= 0 ? truncated2.slice(firstNewline + 1) : truncated2;
266579
266725
  }
266580
266726
  const lines = buffer.split(`
266581
266727
  `);
@@ -268563,19 +268709,45 @@ function getTerminalEofGraceMs() {
268563
268709
  function createTerminalEofGuard(context3) {
268564
268710
  let timer = null;
268565
268711
  let fired = false;
268712
+ const eof = { done: true, value: undefined };
268713
+ let deadline;
268714
+ let closeIterator;
268566
268715
  return {
268716
+ untilEof(stream11) {
268717
+ return {
268718
+ [Symbol.asyncIterator]() {
268719
+ const iterator = stream11[Symbol.asyncIterator]();
268720
+ closeIterator = () => {
268721
+ iterator.return?.().catch(() => {});
268722
+ };
268723
+ return {
268724
+ next() {
268725
+ if (!deadline)
268726
+ return iterator.next();
268727
+ if (fired)
268728
+ return Promise.resolve(eof);
268729
+ return Promise.race([iterator.next(), deadline.promise]);
268730
+ },
268731
+ return: iterator.return?.bind(iterator)
268732
+ };
268733
+ }
268734
+ };
268735
+ },
268567
268736
  arm: () => {
268568
268737
  if (timer) {
268569
268738
  clearTimeout(timer);
268570
268739
  }
268571
268740
  const graceMs = getTerminalEofGraceMs();
268741
+ deadline = Promise.withResolvers();
268572
268742
  timer = setTimeout(() => {
268573
268743
  fired = true;
268744
+ deadline?.resolve(eof);
268574
268745
  debugWarn("drainStream", "Terminal-EOF guard fired: stop_reason=%s received but stream did not end within %dms - aborting HTTP read", context3.getStopReason(), graceMs);
268575
268746
  telemetry.trackError("stream_terminal_eof_guard_fired", `Stream received stop_reason=${context3.getStopReason()} but HTTP body did not end within ${graceMs}ms`, "stream_drain", {
268576
268747
  runId: context3.getRunId() ?? undefined
268577
268748
  });
268578
268749
  context3.abortHttpRead();
268750
+ closeIterator?.();
268579
268751
  }, graceMs);
268580
268752
  },
268581
268753
  clear: () => {
@@ -268641,7 +268813,7 @@ async function drainStream(stream11, buffers, refresh, abortSignal, onFirstMessa
268641
268813
  throw new TypeError(`Stream is not async iterable (${summarizeStreamForDebug(stream11)})`);
268642
268814
  }
268643
268815
  stallReconciler.arm();
268644
- for await (const chunk2 of stream11) {
268816
+ for await (const chunk2 of terminalEofGuard.untilEof(stream11)) {
268645
268817
  stallReconciler.arm();
268646
268818
  lastChunkDebugSummary = summarizeChunkForDebug(chunk2);
268647
268819
  recordTuiJsonPayload(`stream_chunk:${chunk2.message_type ?? "unknown"}`, chunk2);
@@ -453006,7 +453178,9 @@ async function prepareListenerTurn(params) {
453006
453178
  let overrideModel;
453007
453179
  if (turnStartEmission.handlerCount > 0) {
453008
453180
  try {
453009
- const conversation = await getBackend().retrieveConversation(conversationId);
453181
+ const conversation = await getBackend().retrieveConversation(conversationId, {
453182
+ query: { include_context_message_ids: false }
453183
+ });
453010
453184
  overrideModel = conversation.model ?? undefined;
453011
453185
  } catch {}
453012
453186
  }
@@ -457189,7 +457363,7 @@ function createFileCommandSession(params) {
457189
457363
  }, "listener_grep_in_files_send_failed", "listener_grep_in_files");
457190
457364
  return;
457191
457365
  }
457192
- const { matches: matches3, totalMatches, totalFiles, truncated } = await runGrepInFiles({
457366
+ const { matches: matches3, totalMatches, totalFiles, truncated: truncated2 } = await runGrepInFiles({
457193
457367
  searchRoot,
457194
457368
  query: parsed.query,
457195
457369
  isRegex: parsed.is_regex ?? false,
@@ -457206,7 +457380,7 @@ function createFileCommandSession(params) {
457206
457380
  matches: matches3,
457207
457381
  total_matches: totalMatches,
457208
457382
  total_files: totalFiles,
457209
- truncated
457383
+ truncated: truncated2
457210
457384
  }, "listener_grep_in_files_send_failed", "listener_grep_in_files");
457211
457385
  } catch (error4) {
457212
457386
  trackListenerError2("listener_grep_in_files_failed", error4, "listener_grep_in_files");
@@ -461926,7 +462100,7 @@ function withContextWindow(baseConfig, contextWindow) {
461926
462100
  async function getCurrentModelScopeSnapshot(params) {
461927
462101
  const backend3 = getBackend();
461928
462102
  if (!params.agentId) {
461929
- const conversation2 = await backend3.retrieveConversation(params.conversationId);
462103
+ const conversation2 = await backend3.retrieveConversation(params.conversationId, { query: { include_context_message_ids: false } });
461930
462104
  const record5 = conversation2;
461931
462105
  return {
461932
462106
  modelHandle: typeof record5.model === "string" ? record5.model : null,
@@ -461943,7 +462117,7 @@ async function getCurrentModelScopeSnapshot(params) {
461943
462117
  llmConfig: withContextWindow(agent.llm_config, agentContextWindow)
461944
462118
  };
461945
462119
  }
461946
- const conversation = await backend3.retrieveConversation(params.conversationId);
462120
+ const conversation = await backend3.retrieveConversation(params.conversationId, { query: { include_context_message_ids: false } });
461947
462121
  const conversationRecord = conversation;
461948
462122
  const conversationModel = typeof conversationRecord.model === "string" ? conversationRecord.model : null;
461949
462123
  const conversationContextWindow = typeof conversationRecord.context_window_limit === "number" ? conversationRecord.context_window_limit : undefined;
@@ -463866,8 +464040,8 @@ function createListenerLifecycleLog(opts) {
463866
464040
  }
463867
464041
  function formatListenerSocketClose(channel, code, reason) {
463868
464042
  const text3 = reason.toString();
463869
- const truncated = text3.length > MAX_CLOSE_REASON_LENGTH ? `${text3.slice(0, MAX_CLOSE_REASON_LENGTH)}...` : text3;
463870
- return `${channel} socket closed (code=${code}, reason=${JSON.stringify(truncated)})`;
464043
+ const truncated2 = text3.length > MAX_CLOSE_REASON_LENGTH ? `${text3.slice(0, MAX_CLOSE_REASON_LENGTH)}...` : text3;
464044
+ return `${channel} socket closed (code=${code}, reason=${JSON.stringify(truncated2)})`;
463871
464045
  }
463872
464046
  function attachSplitStreamSocketHandlers(params) {
463873
464047
  params.streamSocket.on("error", (error4) => {
@@ -464364,6 +464538,7 @@ async function handleLaunchSubagentCommand(command, parent, connectionId, launch
464364
464538
  executionSettings: parent.executionSettings
464365
464539
  }, () => launch({
464366
464540
  ...toSubagentLaunchArgs(command.args),
464541
+ ...command.notify === "caller" && command.args.computer === undefined && { computer: "local" },
464367
464542
  signal,
464368
464543
  toolCallId: command.tool_call_id,
464369
464544
  notifyCaller: command.notify === "caller",
@@ -471953,7 +472128,7 @@ async function runMessagesSubcommand(argv, deps = {}) {
471953
472128
  const collected = [];
471954
472129
  const seenIds = new Set;
471955
472130
  let cursorBefore;
471956
- let truncated = true;
472131
+ let truncated2 = true;
471957
472132
  for (let pageIndex = 0;pageIndex < maxPages; pageIndex += 1) {
471958
472133
  const page = await backend3.listConversationMessages(conversationId, {
471959
472134
  limit: pageLimit,
@@ -471964,7 +472139,7 @@ async function runMessagesSubcommand(argv, deps = {}) {
471964
472139
  });
471965
472140
  const items = pageItems4(page);
471966
472141
  if (items.length === 0) {
471967
- truncated = false;
472142
+ truncated2 = false;
471968
472143
  break;
471969
472144
  }
471970
472145
  let newItems = 0;
@@ -471978,11 +472153,11 @@ async function runMessagesSubcommand(argv, deps = {}) {
471978
472153
  }
471979
472154
  cursorBefore = items[items.length - 1]?.id;
471980
472155
  if (newItems === 0 || items.length < pageLimit) {
471981
- truncated = newItems === 0;
472156
+ truncated2 = newItems === 0;
471982
472157
  break;
471983
472158
  }
471984
472159
  }
471985
- return { messages: sortChronological2(collected), truncated };
472160
+ return { messages: sortChronological2(collected), truncated: truncated2 };
471986
472161
  };
471987
472162
  if (action === "search") {
471988
472163
  const query3 = parsed.values.query;
@@ -472078,7 +472253,7 @@ async function runMessagesSubcommand(argv, deps = {}) {
472078
472253
  const maxPages = Math.max(1, parseLimit3(parsed.values["max-pages"], 200));
472079
472254
  const outputPathRaw = parsed.values.out || parsed.values.output;
472080
472255
  const outputPath = outputPathRaw ? resolve39(process.cwd(), outputPathRaw) : undefined;
472081
- const { messages, truncated } = await fetchConversationMessages(conversationId, agentId || undefined, pageLimit, maxPages);
472256
+ const { messages, truncated: truncated2 } = await fetchConversationMessages(conversationId, agentId || undefined, pageLimit, maxPages);
472082
472257
  const transcript2 = messages.flatMap((msg) => formatEntry(msg)).join(`
472083
472258
 
472084
472259
  `).trim();
@@ -472090,7 +472265,7 @@ async function runMessagesSubcommand(argv, deps = {}) {
472090
472265
  conversation_id: conversationId,
472091
472266
  agent_id: agentId || null,
472092
472267
  message_count: messages.length,
472093
- truncated,
472268
+ truncated: truncated2,
472094
472269
  ...outputPath ? { output_path: outputPath } : { transcript: transcript2 }
472095
472270
  }, null, 2));
472096
472271
  return 0;
@@ -484106,6 +484281,101 @@ async function createSubagentConversation(cloudBackend, parentConversationId, ag
484106
484281
  return (await create4(body3)).id;
484107
484282
  }
484108
484283
 
484284
+ // src/stream-json-writer.ts
484285
+ function stampWireMessage(msg) {
484286
+ return msg.timestamp === undefined ? { ...msg, timestamp: new Date().toISOString() } : msg;
484287
+ }
484288
+ function writeWireMessage(msg) {
484289
+ console.log(JSON.stringify(stampWireMessage(msg)));
484290
+ }
484291
+ async function writeWireMessageAsync(msg) {
484292
+ const line = `${JSON.stringify(stampWireMessage(msg))}
484293
+ `;
484294
+ return await new Promise((resolve42, reject2) => {
484295
+ if (process.stdout.destroyed || process.stdout.writableEnded) {
484296
+ resolve42(false);
484297
+ return;
484298
+ }
484299
+ process.stdout.write(line, (error4) => {
484300
+ if (error4) {
484301
+ reject2(error4);
484302
+ return;
484303
+ }
484304
+ resolve42(true);
484305
+ });
484306
+ });
484307
+ }
484308
+
484309
+ // src/utils/sigint-abort.ts
484310
+ function createProcessAbortSignal(events, proc = process) {
484311
+ const controller = new AbortController;
484312
+ const listeners6 = events.map((event) => {
484313
+ const listener = () => controller.abort(new DOMException(event, "AbortError"));
484314
+ proc.once(event, listener);
484315
+ return { event, listener };
484316
+ });
484317
+ return {
484318
+ signal: controller.signal,
484319
+ dispose() {
484320
+ for (const { event, listener } of listeners6)
484321
+ proc.removeListener(event, listener);
484322
+ }
484323
+ };
484324
+ }
484325
+
484326
+ // src/headless-interrupt.ts
484327
+ import { randomUUID as randomUUID63 } from "node:crypto";
484328
+ function createHeadlessInterrupt(outputFormat, sessionId, exitHeadless) {
484329
+ const { signal, dispose: dispose2 } = createProcessAbortSignal(["SIGINT", "SIGTERM"]);
484330
+ let shutdown;
484331
+ function exitInterrupted() {
484332
+ shutdown ??= exitInterruptedHeadless(signal, outputFormat, sessionId, exitHeadless);
484333
+ return shutdown;
484334
+ }
484335
+ signal.addEventListener("abort", () => {
484336
+ if (signal.reason?.message === "SIGTERM")
484337
+ exitInterrupted();
484338
+ }, { once: true });
484339
+ return { signal, dispose: dispose2, exitInterrupted };
484340
+ }
484341
+ async function exitInterruptedHeadless(interruptSignal, outputFormat, sessionId, exitHeadless) {
484342
+ const term = interruptSignal.reason?.message === "SIGTERM";
484343
+ const message2 = term ? "Interrupted by SIGTERM" : "Interrupted by SIGINT";
484344
+ await waitForForegroundBashCleanup();
484345
+ if (outputFormat === "stream-json") {
484346
+ const write2 = writeWireMessageAsync({
484347
+ type: "error",
484348
+ message: message2,
484349
+ stop_reason: "cancelled",
484350
+ session_id: sessionId,
484351
+ uuid: `error-interrupted-${randomUUID63()}`
484352
+ });
484353
+ if (term)
484354
+ await waitForTerminationOutput(write2.catch(() => false));
484355
+ else
484356
+ await write2;
484357
+ } else {
484358
+ console.error(message2);
484359
+ }
484360
+ return exitHeadless(term ? 143 : 130, term ? "headless_sigterm_interrupted" : "headless_sigint_interrupted");
484361
+ }
484362
+ async function waitForTerminationOutput(write2) {
484363
+ let timer;
484364
+ try {
484365
+ await Promise.race([
484366
+ write2,
484367
+ new Promise((resolve42) => {
484368
+ timer = setTimeout(resolve42, 250);
484369
+ })
484370
+ ]);
484371
+ } finally {
484372
+ clearTimeout(timer);
484373
+ }
484374
+ }
484375
+ var init_headless_interrupt = __esm(() => {
484376
+ init_bash();
484377
+ });
484378
+
484109
484379
  // src/headless-message-sender.ts
484110
484380
  function buildHeadlessSenderReminder(isAgentLaunch, fromAgentId, env6 = process.env) {
484111
484381
  if (isAgentLaunch && isMemoryWorkerSession(env6)) {
@@ -484125,13 +484395,13 @@ var init_headless_message_sender = __esm(() => {
484125
484395
  });
484126
484396
 
484127
484397
  // src/headless-response-state.ts
484128
- import { randomUUID as randomUUID63 } from "node:crypto";
484398
+ import { randomUUID as randomUUID64 } from "node:crypto";
484129
484399
  function createHeadlessResponseState() {
484130
484400
  let reusableInput = null;
484131
484401
  return {
484132
484402
  prepare(approvals, fullyAutoHandled) {
484133
484403
  const input = [
484134
- { type: "approval", approvals, otid: randomUUID63() }
484404
+ { type: "approval", approvals, otid: randomUUID64() }
484135
484405
  ];
484136
484406
  reusableInput = fullyAutoHandled ? input : null;
484137
484407
  return input;
@@ -484188,15 +484458,6 @@ var init_headless_stdout_guard = __esm(() => {
484188
484458
  init_subagent_stdout_failure();
484189
484459
  });
484190
484460
 
484191
- // src/utils/sigint-abort.ts
484192
- function createSigintAbortSignal(proc = process) {
484193
- const controller = new AbortController;
484194
- proc.once("SIGINT", () => {
484195
- controller.abort();
484196
- });
484197
- return controller.signal;
484198
- }
484199
-
484200
484461
  // src/agent/list-messages-routing.ts
484201
484462
  function resolveListMessagesRoute(listReq, sessionConvId, sessionAgentId) {
484202
484463
  const targetConvId = listReq.conversation_id ?? sessionConvId;
@@ -484208,7 +484469,7 @@ function resolveListMessagesRoute(listReq, sessionConvId, sessionAgentId) {
484208
484469
  }
484209
484470
 
484210
484471
  // src/agent/bootstrap-handler.ts
484211
- import { randomUUID as randomUUID64 } from "node:crypto";
484472
+ import { randomUUID as randomUUID65 } from "node:crypto";
484212
484473
  async function handleBootstrapSessionState(params) {
484213
484474
  const {
484214
484475
  bootstrapReq,
@@ -484257,7 +484518,7 @@ async function handleBootstrapSessionState(params) {
484257
484518
  response: payload
484258
484519
  },
484259
484520
  session_id: sessionContext.sessionId,
484260
- uuid: randomUUID64()
484521
+ uuid: randomUUID65()
484261
484522
  };
484262
484523
  } catch (err) {
484263
484524
  return {
@@ -484268,14 +484529,14 @@ async function handleBootstrapSessionState(params) {
484268
484529
  error: err instanceof Error ? err.message : "bootstrap_session_state failed"
484269
484530
  },
484270
484531
  session_id: sessionContext.sessionId,
484271
- uuid: randomUUID64()
484532
+ uuid: randomUUID65()
484272
484533
  };
484273
484534
  }
484274
484535
  }
484275
484536
  var init_bootstrap_handler = () => {};
484276
484537
 
484277
484538
  // src/agent/list-messages-handler.ts
484278
- import { randomUUID as randomUUID65 } from "node:crypto";
484539
+ import { randomUUID as randomUUID66 } from "node:crypto";
484279
484540
  async function handleListMessages(params) {
484280
484541
  const {
484281
484542
  listReq,
@@ -484315,7 +484576,7 @@ async function handleListMessages(params) {
484315
484576
  response: payload
484316
484577
  },
484317
484578
  session_id: sessionId,
484318
- uuid: randomUUID65()
484579
+ uuid: randomUUID66()
484319
484580
  };
484320
484581
  } catch (err) {
484321
484582
  return {
@@ -484326,7 +484587,7 @@ async function handleListMessages(params) {
484326
484587
  error: err instanceof Error ? err.message : "list_messages failed"
484327
484588
  },
484328
484589
  session_id: sessionId,
484329
- uuid: randomUUID65()
484590
+ uuid: randomUUID66()
484330
484591
  };
484331
484592
  }
484332
484593
  }
@@ -484603,7 +484864,7 @@ var init_headless_enqueue_wait = __esm(() => {
484603
484864
  });
484604
484865
 
484605
484866
  // src/headless-cloud-send.ts
484606
- import { randomUUID as randomUUID66 } from "node:crypto";
484867
+ import { randomUUID as randomUUID67 } from "node:crypto";
484607
484868
  function shouldEnqueueCloudSend(values4, cloud, isAgentLaunch) {
484608
484869
  if (!cloud || isAgentLaunch || values4["new-agent"] || values4.ephemeral)
484609
484870
  return false;
@@ -484653,7 +484914,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
484653
484914
  const format3 = values4["output-format"] ?? "text";
484654
484915
  const noWait = Boolean(values4["no-wait"]);
484655
484916
  const started = Date.now();
484656
- const clientMessageId = values4["client-message-id"] ?? randomUUID66();
484917
+ const clientMessageId = values4["client-message-id"] ?? randomUUID67();
484657
484918
  const controller = new AbortController;
484658
484919
  const submissionTimeout = setTimeout(() => controller.abort(new Error("Cloud submission timed out; inspect the conversation before resending.")), 30000);
484659
484920
  const timeout = setTimeout(() => controller.abort(new Error("Stopped waiting; remote execution was not cancelled.")), deps.timeoutMs ?? resolveEnvironmentMaxWaitMs());
@@ -484741,7 +485002,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
484741
485002
  mcp_servers: [],
484742
485003
  permission_mode: "",
484743
485004
  slash_commands: [],
484744
- uuid: randomUUID66()
485005
+ uuid: randomUUID67()
484745
485006
  };
484746
485007
  await writeObject(init);
484747
485008
  }
@@ -484784,7 +485045,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
484784
485045
  duration_api_ms: 0,
484785
485046
  num_turns: 1,
484786
485047
  usage: null,
484787
- uuid: randomUUID66(),
485048
+ uuid: randomUUID67(),
484788
485049
  ...recovery
484789
485050
  });
484790
485051
  return 0;
@@ -484803,7 +485064,7 @@ async function tryCloudHeadlessSend(values4, prompt, backend3, isAgentLaunch, de
484803
485064
  run_ids: error4 instanceof EnqueuedWaitError ? error4.runIds : [],
484804
485065
  usage: null,
484805
485066
  stop_reason: "error",
484806
- uuid: randomUUID66(),
485067
+ uuid: randomUUID67(),
484807
485068
  status: receipt ? "wait_failed" : submissionAttempted && !(error4 instanceof ApiRequestError && error4.status >= 400 && error4.status < 500) ? "acceptance_unknown" : "submission_failed",
484808
485069
  agent_id: agentId ?? null,
484809
485070
  conversation_id: conversationId ?? "",
@@ -485098,31 +485359,6 @@ async function waitForHeadlessPermissionResponse(options) {
485098
485359
  }
485099
485360
  }
485100
485361
 
485101
- // src/stream-json-writer.ts
485102
- function stampWireMessage(msg) {
485103
- return msg.timestamp === undefined ? { ...msg, timestamp: new Date().toISOString() } : msg;
485104
- }
485105
- function writeWireMessage(msg) {
485106
- console.log(JSON.stringify(stampWireMessage(msg)));
485107
- }
485108
- async function writeWireMessageAsync(msg) {
485109
- const line = `${JSON.stringify(stampWireMessage(msg))}
485110
- `;
485111
- return await new Promise((resolve42, reject2) => {
485112
- if (process.stdout.destroyed || process.stdout.writableEnded) {
485113
- resolve42(false);
485114
- return;
485115
- }
485116
- process.stdout.write(line, (error4) => {
485117
- if (error4) {
485118
- reject2(error4);
485119
- return;
485120
- }
485121
- resolve42(true);
485122
- });
485123
- });
485124
- }
485125
-
485126
485362
  // src/headless-tool-events.ts
485127
485363
  function emitLocalToolCalls(decisions, sessionId) {
485128
485364
  const date5 = new Date().toISOString();
@@ -485303,7 +485539,7 @@ __export(exports_headless, {
485303
485539
  decideInterruptAction: () => decideInterruptAction,
485304
485540
  __headlessTestUtils: () => __headlessTestUtils
485305
485541
  });
485306
- import { randomUUID as randomUUID67 } from "node:crypto";
485542
+ import { randomUUID as randomUUID68 } from "node:crypto";
485307
485543
  function trackHeadlessBoundaryError(errorType, error4, context3) {
485308
485544
  trackBoundaryError({
485309
485545
  errorType,
@@ -485325,7 +485561,7 @@ async function reportStartupErrorAndExit(errorType, error4, context3, outputForm
485325
485561
  message: message2,
485326
485562
  stop_reason: "error",
485327
485563
  session_id: "startup",
485328
- uuid: `startup-error-${randomUUID67()}`
485564
+ uuid: `startup-error-${randomUUID68()}`
485329
485565
  };
485330
485566
  await writeWireMessageAsync(errorMsg);
485331
485567
  } else {
@@ -485399,7 +485635,7 @@ async function emitHeadlessTurnStartCancellationOutput(options) {
485399
485635
  message: options.reason,
485400
485636
  stop_reason: "cancelled",
485401
485637
  session_id: options.sessionId,
485402
- uuid: `error-turn-start-cancel-${randomUUID67()}`
485638
+ uuid: `error-turn-start-cancel-${randomUUID68()}`
485403
485639
  };
485404
485640
  await writeWireMessageAsync(errorMsg);
485405
485641
  const resultMsg = {
@@ -485414,7 +485650,7 @@ async function emitHeadlessTurnStartCancellationOutput(options) {
485414
485650
  conversation_id: options.conversationId,
485415
485651
  run_ids: [],
485416
485652
  usage: null,
485417
- uuid: `result-turn-start-cancel-${randomUUID67()}`,
485653
+ uuid: `result-turn-start-cancel-${randomUUID68()}`,
485418
485654
  stop_reason: "cancelled"
485419
485655
  };
485420
485656
  await writeWireMessageAsync(resultMsg);
@@ -485443,7 +485679,7 @@ function writeBidirectionalTurnStartCancellation(options) {
485443
485679
  message: options.reason,
485444
485680
  stop_reason: "cancelled",
485445
485681
  session_id: options.sessionId,
485446
- uuid: `error-turn-start-cancel-${randomUUID67()}`
485682
+ uuid: `error-turn-start-cancel-${randomUUID68()}`
485447
485683
  };
485448
485684
  writeWireMessage(errorMsg);
485449
485685
  const resultMsg = {
@@ -485458,7 +485694,7 @@ function writeBidirectionalTurnStartCancellation(options) {
485458
485694
  conversation_id: options.conversationId,
485459
485695
  run_ids: [],
485460
485696
  usage: null,
485461
- uuid: `result-turn-start-cancel-${randomUUID67()}`,
485697
+ uuid: `result-turn-start-cancel-${randomUUID68()}`,
485462
485698
  stop_reason: "cancelled"
485463
485699
  };
485464
485700
  writeWireMessage(resultMsg);
@@ -485516,10 +485752,14 @@ async function flushAndExit(code) {
485516
485752
  stream11.write("", () => resolve42());
485517
485753
  });
485518
485754
  await closeClientMcpServers();
485519
- await Promise.allSettled([
485755
+ const flushed = Promise.allSettled([
485520
485756
  flushWritable(process.stdout),
485521
485757
  flushWritable(process.stderr)
485522
485758
  ]);
485759
+ if (code === 143)
485760
+ await waitForTerminationOutput(flushed);
485761
+ else
485762
+ await flushed;
485523
485763
  process.exit(code);
485524
485764
  }
485525
485765
  async function writeFinalHeadlessStdout(text3) {
@@ -486265,7 +486505,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486265
486505
  const approvalInput = {
486266
486506
  type: "approval",
486267
486507
  approvals: denialResults,
486268
- otid: randomUUID67()
486508
+ otid: randomUUID68()
486269
486509
  };
486270
486510
  const approvalMessages = [approvalInput];
486271
486511
  {
@@ -486278,7 +486518,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486278
486518
  type: "text",
486279
486519
  text: sc.content
486280
486520
  })),
486281
- otid: randomUUID67()
486521
+ otid: randomUUID68()
486282
486522
  });
486283
486523
  }
486284
486524
  }
@@ -486311,7 +486551,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486311
486551
  message: `Failed to resolve pending approvals on resume: ${approvalError instanceof Error ? approvalError.message : String(approvalError)}`,
486312
486552
  stop_reason: "error",
486313
486553
  session_id: sessionId,
486314
- uuid: `error-pre-loop-approval-${randomUUID67()}`
486554
+ uuid: `error-pre-loop-approval-${randomUUID68()}`
486315
486555
  };
486316
486556
  writeWireMessage(errorMsg);
486317
486557
  } else {
@@ -486385,7 +486625,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486385
486625
  content: contentParts,
486386
486626
  backend: backend3,
486387
486627
  onMessage: outputFormat === "stream-json" ? (message2) => {
486388
- const uuid5 = Reflect.get(message2, "otid") ?? Reflect.get(message2, "id") ?? randomUUID67();
486628
+ const uuid5 = Reflect.get(message2, "otid") ?? Reflect.get(message2, "id") ?? randomUUID68();
486389
486629
  writeWireMessage(includePartialMessages ? {
486390
486630
  type: "stream_event",
486391
486631
  event: message2,
@@ -486449,7 +486689,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486449
486689
  {
486450
486690
  role: "user",
486451
486691
  content: contentParts,
486452
- otid: randomUUID67()
486692
+ otid: randomUUID68()
486453
486693
  }
486454
486694
  ];
486455
486695
  const recoveredApprovalResults = queuedRecoveredApprovalResults ?? [];
@@ -486458,7 +486698,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486458
486698
  {
486459
486699
  type: "approval",
486460
486700
  approvals: recoveredApprovalResults,
486461
- otid: randomUUID67()
486701
+ otid: randomUUID68()
486462
486702
  },
486463
486703
  ...currentInput
486464
486704
  ];
@@ -486506,7 +486746,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486506
486746
  message: `Maximum turns limit reached (${buffers.usage.stepCount}/${maxTurns} steps)`,
486507
486747
  stop_reason: "max_steps",
486508
486748
  session_id: sessionId,
486509
- uuid: `error-max-turns-${randomUUID67()}`
486749
+ uuid: `error-max-turns-${randomUUID68()}`
486510
486750
  };
486511
486751
  await writeWireMessageAsync(errorMsg);
486512
486752
  } else {
@@ -486515,25 +486755,14 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486515
486755
  await exitHeadless(1, "headless_max_steps_reached");
486516
486756
  }
486517
486757
  };
486518
- const sigintSignal = createSigintAbortSignal();
486519
- const exitInterrupted = async () => {
486520
- if (outputFormat === "stream-json") {
486521
- const errorMsg = {
486522
- type: "error",
486523
- message: "Interrupted by SIGINT",
486524
- stop_reason: "cancelled",
486525
- session_id: sessionId,
486526
- uuid: `error-interrupted-${randomUUID67()}`
486527
- };
486528
- await writeWireMessageAsync(errorMsg);
486529
- } else {
486530
- console.error("Interrupted by SIGINT");
486531
- }
486532
- return exitHeadless(130, "headless_sigint_interrupted");
486533
- };
486758
+ const {
486759
+ signal: interruptSignal,
486760
+ dispose: dispose2,
486761
+ exitInterrupted
486762
+ } = createHeadlessInterrupt(outputFormat, sessionId, exitHeadless);
486534
486763
  try {
486535
486764
  while (true) {
486536
- if (sigintSignal.aborted) {
486765
+ if (interruptSignal.aborted) {
486537
486766
  await exitInterrupted();
486538
486767
  }
486539
486768
  const hasApprovalContinuation = currentInput.some((item) => item.type === "approval");
@@ -486552,7 +486781,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486552
486781
  type: "text",
486553
486782
  text: sc.content
486554
486783
  })),
486555
- otid: randomUUID67()
486784
+ otid: randomUUID68()
486556
486785
  }
486557
486786
  ];
486558
486787
  }
@@ -486579,11 +486808,11 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486579
486808
  agentId: agent.id,
486580
486809
  allowResponseStateReuse: responseState.consume(currentInput),
486581
486810
  preparedToolContext: turnToolContext.preparedToolContext.preparedToolContext
486582
- }, { maxRetries: 0, signal: sigintSignal });
486811
+ }, { maxRetries: 0, signal: interruptSignal });
486583
486812
  turnToolContextId = getStreamToolContextId(stream11);
486584
486813
  busyDeadline = null;
486585
486814
  } catch (preStreamError) {
486586
- if (sigintSignal.aborted) {
486815
+ if (interruptSignal.aborted) {
486587
486816
  await exitInterrupted();
486588
486817
  }
486589
486818
  const errorDetail3 = extractConflictDetail(preStreamError);
@@ -486599,7 +486828,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486599
486828
  recovery_type: "approval_pending",
486600
486829
  message: "Detected pending approval conflict on send; resolving before retry",
486601
486830
  session_id: sessionId,
486602
- uuid: `recovery-pre-stream-${randomUUID67()}`
486831
+ uuid: `recovery-pre-stream-${randomUUID68()}`
486603
486832
  };
486604
486833
  writeWireMessage(recoveryMsg);
486605
486834
  } else {
@@ -486610,7 +486839,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486610
486839
  }
486611
486840
  const blockingRunId = extractConversationBusyRunId(errorDetail3);
486612
486841
  if (preStreamAction === "retry_conversation_busy" || blockingRunId) {
486613
- const resumeStream = await resumeConversationBusyRequest(conversationId, agent?.id, currentInput, sigintSignal);
486842
+ const resumeStream = await resumeConversationBusyRequest(conversationId, agent?.id, currentInput, interruptSignal);
486614
486843
  if (resumeStream) {
486615
486844
  stream11 = resumeStream;
486616
486845
  conversationBusyRetries = 0;
@@ -486618,7 +486847,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486618
486847
  } else {
486619
486848
  if (blockingRunId) {
486620
486849
  busyDeadline ??= Date.now() + CONVERSATION_BUSY_WAIT_TIMEOUT_MS;
486621
- const settled = await waitForConversationBusyRunOrThrow(blockingRunId, sigintSignal, busyDeadline);
486850
+ const settled = await waitForConversationBusyRunOrThrow(blockingRunId, interruptSignal, busyDeadline);
486622
486851
  if (settled)
486623
486852
  continue;
486624
486853
  }
@@ -486639,7 +486868,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486639
486868
  max_attempts: CONVERSATION_BUSY_MAX_RETRIES,
486640
486869
  delay_ms: retryDelayMs,
486641
486870
  session_id: sessionId,
486642
- uuid: `retry-conversation-busy-${randomUUID67()}`
486871
+ uuid: `retry-conversation-busy-${randomUUID68()}`
486643
486872
  };
486644
486873
  writeWireMessage(retryMsg);
486645
486874
  } else {
@@ -486667,7 +486896,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486667
486896
  max_attempts: LLM_API_ERROR_MAX_RETRIES2,
486668
486897
  delay_ms: delayMs,
486669
486898
  session_id: sessionId,
486670
- uuid: `retry-pre-stream-${randomUUID67()}`
486899
+ uuid: `retry-pre-stream-${randomUUID68()}`
486671
486900
  };
486672
486901
  writeWireMessage(retryMsg);
486673
486902
  } else {
@@ -486694,7 +486923,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486694
486923
  stop_reason: "error",
486695
486924
  run_id: errorInfo.run_id,
486696
486925
  session_id: sessionId,
486697
- uuid: randomUUID67(),
486926
+ uuid: randomUUID68(),
486698
486927
  ...errorInfo.error_type && errorInfo.run_id && {
486699
486928
  api_error: {
486700
486929
  message_type: "error_message",
@@ -486716,7 +486945,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486716
486945
  message: "Detected pending approval conflict; auto-denying stale approval and retrying",
486717
486946
  run_id: recoveryRunId ?? undefined,
486718
486947
  session_id: sessionId,
486719
- uuid: `recovery-${recoveryRunId || randomUUID67()}`
486948
+ uuid: `recovery-${recoveryRunId || randomUUID68()}`
486720
486949
  };
486721
486950
  writeWireMessage(recoveryMsg);
486722
486951
  approvalPendingRecovery = true;
@@ -486734,7 +486963,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486734
486963
  type: "stream_event",
486735
486964
  event: chunk2,
486736
486965
  session_id: sessionId,
486737
- uuid: uuid5 || randomUUID67()
486966
+ uuid: uuid5 || randomUUID68()
486738
486967
  };
486739
486968
  writeWireMessage(streamEvent);
486740
486969
  } else {
@@ -486742,7 +486971,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486742
486971
  type: "message",
486743
486972
  ...chunk2,
486744
486973
  session_id: sessionId,
486745
- uuid: uuid5 || randomUUID67()
486974
+ uuid: uuid5 || randomUUID68()
486746
486975
  };
486747
486976
  writeWireMessage(msg);
486748
486977
  }
@@ -486750,7 +486979,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486750
486979
  return { shouldOutput: shouldOutputChunk, shouldAccumulate: true };
486751
486980
  };
486752
486981
  }
486753
- const result3 = await drainStreamWithResume(stream11, buffers, () => {}, sigintSignal, undefined, streamJsonHook, reminderContextTracker, undefined, HEADLESS_STREAM_RESUME_POLICY);
486982
+ const result3 = await drainStreamWithResume(stream11, buffers, () => {}, interruptSignal, undefined, streamJsonHook, reminderContextTracker, undefined, HEADLESS_STREAM_RESUME_POLICY);
486754
486983
  const { apiDurationMs, stopReason } = result3;
486755
486984
  const approvals = result3.approvals || [];
486756
486985
  const lastRunId = result3.lastRunId || null;
@@ -486758,7 +486987,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486758
486987
  if (lastRunId)
486759
486988
  lastKnownRunId = lastRunId;
486760
486989
  sessionStats.endTurn(apiDurationMs);
486761
- if (stopReason === "cancelled" || sigintSignal.aborted) {
486990
+ if (stopReason === "cancelled" || interruptSignal.aborted) {
486762
486991
  await exitInterrupted();
486763
486992
  }
486764
486993
  if (stopReason !== "requires_approval" && !approvalPendingRecovery && !(stopReason === "error" && fallbackError)) {
@@ -486787,7 +487016,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486787
487016
  {
486788
487017
  role: "user",
486789
487018
  content: continueMessage,
486790
- otid: randomUUID67()
487019
+ otid: randomUUID68()
486791
487020
  }
486792
487021
  ];
486793
487022
  const continueTurnStartEmission = await emitHeadlessTurnStart({
@@ -486846,10 +487075,10 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486846
487075
  emitLocalToolCalls(decisions, sessionId);
486847
487076
  }
486848
487077
  const executedResults = await executeApprovalBatch2(decisions, undefined, {
486849
- abortSignal: sigintSignal,
487078
+ abortSignal: interruptSignal,
486850
487079
  toolContextId: turnToolContextId ?? undefined
486851
487080
  });
486852
- if (sigintSignal.aborted) {
487081
+ if (interruptSignal.aborted) {
486853
487082
  await exitInterrupted();
486854
487083
  }
486855
487084
  if (outputFormat === "stream-json") {
@@ -486875,7 +487104,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486875
487104
  currentHandle: null,
486876
487105
  error: result3.errorInfo ?? runErrorInfo2 ?? latestErrorText,
486877
487106
  exhaustedProviders: chatgptExhaustedProviders,
486878
- signal: sigintSignal
487107
+ signal: interruptSignal
486879
487108
  });
486880
487109
  if (rotation) {
486881
487110
  chatgptPlanSwaps += 1;
@@ -486889,7 +487118,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486889
487118
  delay_ms: 0,
486890
487119
  run_id: lastRunId ?? undefined,
486891
487120
  session_id: sessionId,
486892
- uuid: `retry-${lastRunId || randomUUID67()}`
487121
+ uuid: `retry-${lastRunId || randomUUID68()}`
486893
487122
  };
486894
487123
  writeWireMessage(retryMsg);
486895
487124
  } else {
@@ -486917,7 +487146,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486917
487146
  delay_ms: delayMs,
486918
487147
  run_id: lastRunId ?? undefined,
486919
487148
  session_id: sessionId,
486920
- uuid: `retry-${lastRunId || randomUUID67()}`
487149
+ uuid: `retry-${lastRunId || randomUUID68()}`
486921
487150
  };
486922
487151
  writeWireMessage(retryMsg);
486923
487152
  } else {
@@ -486938,7 +487167,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486938
487167
  message: "Tool call ID mismatch; fetching actual pending approvals and resyncing",
486939
487168
  run_id: lastRunId ?? undefined,
486940
487169
  session_id: sessionId,
486941
- uuid: `recovery-${lastRunId || randomUUID67()}`
487170
+ uuid: `recovery-${lastRunId || randomUUID68()}`
486942
487171
  };
486943
487172
  writeWireMessage(recoveryMsg);
486944
487173
  } else {
@@ -486955,7 +487184,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486955
487184
  stop_reason: stopReason,
486956
487185
  run_id: lastRunId ?? undefined,
486957
487186
  session_id: sessionId,
486958
- uuid: `error-${lastRunId || randomUUID67()}`
487187
+ uuid: `error-${lastRunId || randomUUID68()}`
486959
487188
  };
486960
487189
  await writeWireMessageAsync(errorMsg);
486961
487190
  } else {
@@ -486997,7 +487226,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
486997
487226
  const nudgeMessage = {
486998
487227
  role: "user",
486999
487228
  content: `<system-reminder>The previous response was empty. Please provide a response with either text content or a tool call.</system-reminder>`,
487000
- otid: randomUUID67()
487229
+ otid: randomUUID68()
487001
487230
  };
487002
487231
  currentInput = [...currentInput, nudgeMessage];
487003
487232
  }
@@ -487010,7 +487239,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
487010
487239
  delay_ms: delayMs,
487011
487240
  run_id: lastRunId ?? undefined,
487012
487241
  session_id: sessionId,
487013
- uuid: `retry-empty-${lastRunId || randomUUID67()}`
487242
+ uuid: `retry-empty-${lastRunId || randomUUID68()}`
487014
487243
  };
487015
487244
  writeWireMessage(retryMsg);
487016
487245
  } else {
@@ -487037,7 +487266,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
487037
487266
  delay_ms: delayMs,
487038
487267
  run_id: lastRunId ?? undefined,
487039
487268
  session_id: sessionId,
487040
- uuid: `retry-${lastRunId || randomUUID67()}`
487269
+ uuid: `retry-${lastRunId || randomUUID68()}`
487041
487270
  };
487042
487271
  writeWireMessage(retryMsg);
487043
487272
  } else {
@@ -487067,7 +487296,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
487067
487296
  delay_ms: delayMs,
487068
487297
  run_id: lastRunId ?? undefined,
487069
487298
  session_id: sessionId,
487070
- uuid: `retry-${lastRunId || randomUUID67()}`
487299
+ uuid: `retry-${lastRunId || randomUUID68()}`
487071
487300
  };
487072
487301
  writeWireMessage(retryMsg);
487073
487302
  } else {
@@ -487116,7 +487345,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
487116
487345
  stop_reason: stopReason,
487117
487346
  run_id: lastRunId ?? undefined,
487118
487347
  session_id: sessionId,
487119
- uuid: `error-${lastRunId || randomUUID67()}`
487348
+ uuid: `error-${lastRunId || randomUUID68()}`
487120
487349
  };
487121
487350
  await writeWireMessageAsync(errorMsg);
487122
487351
  } else {
@@ -487125,7 +487354,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
487125
487354
  await exitHeadless(1, "headless_stop_reason_error");
487126
487355
  }
487127
487356
  } catch (error4) {
487128
- if (sigintSignal.aborted) {
487357
+ if (interruptSignal.aborted) {
487129
487358
  await exitInterrupted();
487130
487359
  }
487131
487360
  markIncompleteToolsAsCancelled(buffers, true, "stream_error");
@@ -487138,14 +487367,18 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
487138
487367
  stop_reason: "error",
487139
487368
  run_id: lastKnownRunId ?? undefined,
487140
487369
  session_id: sessionId,
487141
- uuid: `error-${lastKnownRunId || randomUUID67()}`
487370
+ uuid: `error-${lastKnownRunId || randomUUID68()}`
487142
487371
  };
487143
487372
  await writeWireMessageAsync(errorMsg);
487144
487373
  } else {
487145
487374
  console.error(`Error: ${errorDetails}`);
487146
487375
  }
487147
487376
  await exitHeadless(1, "headless_runtime_exception");
487377
+ } finally {
487378
+ dispose2();
487148
487379
  }
487380
+ if (interruptSignal.aborted)
487381
+ await exitInterrupted();
487149
487382
  await runPostTurnMemorySync({
487150
487383
  conversationId,
487151
487384
  agentId: agent.id,
@@ -487337,7 +487570,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487337
487570
  const approvalInput = {
487338
487571
  type: "approval",
487339
487572
  approvals: denialResults,
487340
- otid: randomUUID67()
487573
+ otid: randomUUID68()
487341
487574
  };
487342
487575
  const approvalMessages = [approvalInput];
487343
487576
  {
@@ -487350,7 +487583,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487350
487583
  type: "text",
487351
487584
  text: sc.content
487352
487585
  })),
487353
- otid: randomUUID67()
487586
+ otid: randomUUID68()
487354
487587
  });
487355
487588
  }
487356
487589
  }
@@ -487408,7 +487641,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487408
487641
  reason,
487409
487642
  cleared_count: clearedCount,
487410
487643
  session_id: sessionId,
487411
- uuid: `q-clr-${randomUUID67()}`
487644
+ uuid: `q-clr-${randomUUID68()}`
487412
487645
  })
487413
487646
  }
487414
487647
  });
@@ -487438,7 +487671,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487438
487671
  reason: "runtime_busy",
487439
487672
  queue_len: Math.max(1, queueLen),
487440
487673
  session_id: sessionId,
487441
- uuid: `q-blk-${randomUUID67()}`
487674
+ uuid: `q-blk-${randomUUID68()}`
487442
487675
  });
487443
487676
  }
487444
487677
  function enqueueForTracking(input) {
@@ -487503,7 +487736,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487503
487736
  request_id: interruptRequestId
487504
487737
  },
487505
487738
  session_id: sessionId,
487506
- uuid: randomUUID67()
487739
+ uuid: randomUUID68()
487507
487740
  };
487508
487741
  writeWireMessage(interruptResponse);
487509
487742
  return;
@@ -487630,7 +487863,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487630
487863
  const approvalInput = {
487631
487864
  type: "approval",
487632
487865
  approvals: denialResults,
487633
- otid: randomUUID67()
487866
+ otid: randomUUID68()
487634
487867
  };
487635
487868
  const approvalStream = await sendScopedApprovalMessages({
487636
487869
  agentId: agent.id,
@@ -487669,7 +487902,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487669
487902
  message: "Invalid JSON input",
487670
487903
  stop_reason: "error",
487671
487904
  session_id: sessionId,
487672
- uuid: randomUUID67()
487905
+ uuid: randomUUID68()
487673
487906
  };
487674
487907
  writeWireMessage(errorMsg2);
487675
487908
  continue;
@@ -487695,7 +487928,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487695
487928
  }
487696
487929
  },
487697
487930
  session_id: sessionId,
487698
- uuid: randomUUID67()
487931
+ uuid: randomUUID68()
487699
487932
  };
487700
487933
  writeWireMessage(initResponse);
487701
487934
  } else if (subtype === "interrupt") {
@@ -487712,7 +487945,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487712
487945
  request_id: requestId ?? ""
487713
487946
  },
487714
487947
  session_id: sessionId,
487715
- uuid: randomUUID67()
487948
+ uuid: randomUUID68()
487716
487949
  };
487717
487950
  writeWireMessage(interruptResponse);
487718
487951
  } else if (subtype === "register_external_tools") {
@@ -487790,7 +488023,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487790
488023
  response: { registered: tools.length }
487791
488024
  },
487792
488025
  session_id: sessionId,
487793
- uuid: randomUUID67()
488026
+ uuid: randomUUID68()
487794
488027
  };
487795
488028
  writeWireMessage(registerResponse);
487796
488029
  } else if (subtype === "bootstrap_session_state") {
@@ -487846,7 +488079,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487846
488079
  response: recovery
487847
488080
  },
487848
488081
  session_id: sessionId,
487849
- uuid: randomUUID67()
488082
+ uuid: randomUUID68()
487850
488083
  };
487851
488084
  writeWireMessage(recoveryResponse);
487852
488085
  } catch (error4) {
@@ -487858,7 +488091,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487858
488091
  error: error4 instanceof Error ? error4.message : String(error4)
487859
488092
  },
487860
488093
  session_id: sessionId,
487861
- uuid: randomUUID67()
488094
+ uuid: randomUUID68()
487862
488095
  };
487863
488096
  writeWireMessage(recoveryError);
487864
488097
  }
@@ -487871,7 +488104,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487871
488104
  error: `Unknown control request subtype: ${subtype}`
487872
488105
  },
487873
488106
  session_id: sessionId,
487874
- uuid: randomUUID67()
488107
+ uuid: randomUUID68()
487875
488108
  };
487876
488109
  writeWireMessage(errorResponse);
487877
488110
  }
@@ -487926,7 +488159,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487926
488159
  try {
487927
488160
  const buffers = createBuffers(agent.id);
487928
488161
  const startTime = performance.now();
487929
- const userOtid = randomUUID67();
488162
+ const userOtid = randomUUID68();
487930
488163
  const userTranscriptText = extractTelemetryInputText(userContent);
487931
488164
  if (userTranscriptText.length > 0) {
487932
488165
  const userLineId = `user-${userOtid}`;
@@ -487992,7 +488225,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
487992
488225
  currentInput.unshift({
487993
488226
  role: "user",
487994
488227
  content: INTERRUPT_RECOVERY_ALERT,
487995
- otid: randomUUID67()
488228
+ otid: randomUUID68()
487996
488229
  });
487997
488230
  try {
487998
488231
  await resolveAllPendingApprovals();
@@ -488055,7 +488288,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488055
488288
  recovery_type: "approval_pending",
488056
488289
  message: "Detected pending approval conflict on send; resolving before retry",
488057
488290
  session_id: sessionId,
488058
- uuid: `recovery-bidir-${randomUUID67()}`
488291
+ uuid: `recovery-bidir-${randomUUID68()}`
488059
488292
  };
488060
488293
  writeWireMessage(recoveryMsg);
488061
488294
  await resolveAllPendingApprovals();
@@ -488078,7 +488311,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488078
488311
  max_attempts: LLM_API_ERROR_MAX_RETRIES2,
488079
488312
  delay_ms: delayMs,
488080
488313
  session_id: sessionId,
488081
- uuid: `retry-bidir-${randomUUID67()}`
488314
+ uuid: `retry-bidir-${randomUUID68()}`
488082
488315
  };
488083
488316
  writeWireMessage(retryMsg);
488084
488317
  await new Promise((resolve42) => setTimeout(resolve42, delayMs));
@@ -488100,7 +488333,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488100
488333
  stop_reason: "error",
488101
488334
  run_id: errorInfo.run_id,
488102
488335
  session_id: sessionId,
488103
- uuid: randomUUID67(),
488336
+ uuid: randomUUID68(),
488104
488337
  ...errorInfo.error_type && errorInfo.run_id && {
488105
488338
  api_error: {
488106
488339
  message_type: "error_message",
@@ -488128,7 +488361,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488128
488361
  type: "stream_event",
488129
488362
  event: chunk2,
488130
488363
  session_id: sessionId,
488131
- uuid: uuid5 || randomUUID67()
488364
+ uuid: uuid5 || randomUUID68()
488132
488365
  };
488133
488366
  writeWireMessage(streamEvent);
488134
488367
  } else {
@@ -488136,7 +488369,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488136
488369
  type: "message",
488137
488370
  ...chunk2,
488138
488371
  session_id: sessionId,
488139
- uuid: uuid5 || randomUUID67()
488372
+ uuid: uuid5 || randomUUID68()
488140
488373
  };
488141
488374
  writeWireMessage(msg);
488142
488375
  }
@@ -488273,7 +488506,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488273
488506
  message: errorDetails,
488274
488507
  stop_reason: "error",
488275
488508
  session_id: sessionId,
488276
- uuid: randomUUID67()
488509
+ uuid: randomUUID68()
488277
488510
  };
488278
488511
  writeWireMessage(errorMsg2);
488279
488512
  const errorResultMsg = {
@@ -488311,7 +488544,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
488311
488544
  message: `Unknown message type: ${message2.type}`,
488312
488545
  stop_reason: "error",
488313
488546
  session_id: sessionId,
488314
- uuid: randomUUID67()
488547
+ uuid: randomUUID68()
488315
488548
  };
488316
488549
  writeWireMessage(errorMsg);
488317
488550
  }
@@ -488325,6 +488558,7 @@ var init_headless = __esm(() => {
488325
488558
  init_subagent_launcher();
488326
488559
  init_paths();
488327
488560
  init_constants2();
488561
+ init_headless_interrupt();
488328
488562
  init_headless_message_sender();
488329
488563
  init_headless_response_state();
488330
488564
  init_headless_startup_backend();
@@ -489800,7 +490034,7 @@ var init_reflection_arena_hf_upload = __esm(() => {
489800
490034
 
489801
490035
  // src/cli/helpers/reflection-arena.ts
489802
490036
  import { execFile as execFileCb5 } from "node:child_process";
489803
- import { randomInt as randomInt2, randomUUID as randomUUID68 } from "node:crypto";
490037
+ import { randomInt as randomInt2, randomUUID as randomUUID69 } from "node:crypto";
489804
490038
  import { appendFile as appendFile4, mkdir as mkdir20, readFile as readFile34, writeFile as writeFile22 } from "node:fs/promises";
489805
490039
  import { join as join119 } from "node:path";
489806
490040
  import { promisify as promisify21 } from "node:util";
@@ -490142,7 +490376,7 @@ async function startReflectionArenaRun(options) {
490142
490376
  }
490143
490377
  let releaseReservation = true;
490144
490378
  try {
490145
- const runId = randomUUID68().slice(0, 8);
490379
+ const runId = randomUUID69().slice(0, 8);
490146
490380
  const labels = shuffledLabels();
490147
490381
  const prepared = await Promise.all([
490148
490382
  prepareReflectionMemoryWorktreeLaunch({
@@ -506969,18 +507203,18 @@ async function collectMemoryData(agentId, repoDir, memoryRoot, conversationId) {
506969
507203
  ${m4.body}` : m4.subject;
506970
507204
  const stats = statsMap.get(m4.hash) ?? "";
506971
507205
  let diff2 = diffsMap.get(m4.hash);
506972
- let truncated = false;
507206
+ let truncated2 = false;
506973
507207
  if (diff2 !== undefined) {
506974
507208
  if (diff2.length > PER_DIFF_CAP) {
506975
507209
  diff2 = `${diff2.slice(0, PER_DIFF_CAP)}
506976
507210
 
506977
507211
  [diff truncated - exceeded ${Math.round(PER_DIFF_CAP / 1024)}KB]`;
506978
- truncated = true;
507212
+ truncated2 = true;
506979
507213
  }
506980
507214
  cumulativeSize += diff2.length;
506981
507215
  if (cumulativeSize > TOTAL_PAYLOAD_CAP) {
506982
507216
  diff2 = undefined;
506983
- truncated = true;
507217
+ truncated2 = true;
506984
507218
  }
506985
507219
  }
506986
507220
  return {
@@ -506991,7 +507225,7 @@ ${m4.body}` : m4.subject;
506991
507225
  message: message2,
506992
507226
  stats,
506993
507227
  diff: diff2,
506994
- truncated,
507228
+ truncated: truncated2,
506995
507229
  isReflection: REFLECTION_PATTERN.test(m4.subject)
506996
507230
  };
506997
507231
  });
@@ -509747,7 +509981,7 @@ var init_provider_selector_helpers = __esm(() => {
509747
509981
  });
509748
509982
 
509749
509983
  // src/cli/hooks/use-chatgpt-rate-limit-state.ts
509750
- import { randomUUID as randomUUID69 } from "node:crypto";
509984
+ import { randomUUID as randomUUID70 } from "node:crypto";
509751
509985
  function errorMessage8(error4, fallback) {
509752
509986
  return error4 instanceof Error ? error4.message : fallback;
509753
509987
  }
@@ -509844,7 +510078,7 @@ function useChatGPTRateLimitState(target) {
509844
510078
  target,
509845
510079
  providerName,
509846
510080
  resetId,
509847
- idempotencyKey: randomUUID69()
510081
+ idempotencyKey: randomUUID70()
509848
510082
  });
509849
510083
  if (!result3.success) {
509850
510084
  return { notice: { tone: "warning", message: result3.error.message } };
@@ -515931,12 +516165,12 @@ var init_ExitStats = __esm(async () => {
515931
516165
  });
515932
516166
 
515933
516167
  // src/cli/app/ids.ts
515934
- import { randomUUID as randomUUID70 } from "node:crypto";
516168
+ import { randomUUID as randomUUID71 } from "node:crypto";
515935
516169
  function uid(prefix) {
515936
516170
  return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
515937
516171
  }
515938
516172
  function createClientOtid() {
515939
- return randomUUID70();
516173
+ return randomUUID71();
515940
516174
  }
515941
516175
  function appendOptimisticUserLine(buffers, text3, otid) {
515942
516176
  if (!text3) {
@@ -519414,7 +519648,7 @@ var init_turn_input = __esm(() => {
519414
519648
  });
519415
519649
 
519416
519650
  // src/cli/app/use-approval-flow.ts
519417
- import { randomUUID as randomUUID71 } from "node:crypto";
519651
+ import { randomUUID as randomUUID72 } from "node:crypto";
519418
519652
  function useApprovalFlow(ctx) {
519419
519653
  const {
519420
519654
  abortControllerRef,
@@ -519920,7 +520154,7 @@ function useApprovalFlow(ctx) {
519920
520154
  {
519921
520155
  type: "approval",
519922
520156
  approvals: allResults,
519923
- otid: randomUUID71()
520157
+ otid: randomUUID72()
519924
520158
  }
519925
520159
  ]);
519926
520160
  } catch (error4) {
@@ -521304,7 +521538,7 @@ var init_system_reminders2 = __esm(() => {
521304
521538
  });
521305
521539
 
521306
521540
  // src/cli/app/use-conversation-loop.ts
521307
- import { randomUUID as randomUUID72 } from "node:crypto";
521541
+ import { randomUUID as randomUUID73 } from "node:crypto";
521308
521542
  function sleep13(ms) {
521309
521543
  return new Promise((resolve44) => setTimeout(resolve44, ms));
521310
521544
  }
@@ -521614,16 +521848,16 @@ function useConversationLoop(ctx) {
521614
521848
  currentInput = [
521615
521849
  ...lastSentInputRef.current.map((m4) => ({
521616
521850
  ...m4,
521617
- otid: randomUUID72()
521851
+ otid: randomUUID73()
521618
521852
  })),
521619
521853
  ...currentInput.map((m4) => m4.type === "message" && m4.role === "user" ? {
521620
521854
  ...m4,
521621
- otid: randomUUID72(),
521855
+ otid: randomUUID73(),
521622
521856
  content: [
521623
521857
  { type: "text", text: INTERRUPT_RECOVERY_ALERT },
521624
521858
  ...typeof m4.content === "string" ? [{ type: "text", text: m4.content }] : Array.isArray(m4.content) ? m4.content : []
521625
521859
  ]
521626
- } : { ...m4, otid: randomUUID72() })
521860
+ } : { ...m4, otid: randomUUID73() })
521627
521861
  ];
521628
521862
  pendingInterruptRecoveryConversationIdRef.current = null;
521629
521863
  lastSentInputRef.current = [
@@ -521662,7 +521896,7 @@ function useConversationLoop(ctx) {
521662
521896
  type: "text",
521663
521897
  text: sc.content
521664
521898
  })),
521665
- otid: randomUUID72()
521899
+ otid: randomUUID73()
521666
521900
  }
521667
521901
  ];
521668
521902
  }
@@ -522017,7 +522251,7 @@ ${feedback}
522017
522251
  });
522018
522252
  buffersRef.current.order.push(statusId);
522019
522253
  refreshDerived();
522020
- const hookMessageOtid = randomUUID72();
522254
+ const hookMessageOtid = randomUUID73();
522021
522255
  setTimeout(() => {
522022
522256
  processConversation([
522023
522257
  {
@@ -522044,7 +522278,7 @@ ${feedback}
522044
522278
  turnEndContinue = undefined;
522045
522279
  }
522046
522280
  if (turnEndContinue) {
522047
- const continueOtid = randomUUID72();
522281
+ const continueOtid = randomUUID73();
522048
522282
  setTimeout(() => {
522049
522283
  processConversation([
522050
522284
  {
@@ -522374,7 +522608,7 @@ ${feedback}
522374
522608
  {
522375
522609
  type: "approval",
522376
522610
  approvals: allResults,
522377
- otid: randomUUID72()
522611
+ otid: randomUUID73()
522378
522612
  }
522379
522613
  ], {
522380
522614
  allowReentry: true,
@@ -522549,7 +522783,7 @@ ${feedback}
522549
522783
  type: "message",
522550
522784
  role: "user",
522551
522785
  content: `<system-reminder>The previous response was empty. Please provide a response with either text content or a tool call.</system-reminder>`,
522552
- otid: randomUUID72()
522786
+ otid: randomUUID73()
522553
522787
  }
522554
522788
  ];
522555
522789
  }
@@ -522832,7 +523066,7 @@ var init_use_conversation_loop = __esm(() => {
522832
523066
  });
522833
523067
 
522834
523068
  // src/cli/app/use-conversation-switching.ts
522835
- import { randomUUID as randomUUID73 } from "node:crypto";
523069
+ import { randomUUID as randomUUID74 } from "node:crypto";
522836
523070
  function useConversationSwitching(ctx) {
522837
523071
  const {
522838
523072
  abortControllerRef,
@@ -522907,7 +523141,7 @@ function useConversationSwitching(ctx) {
522907
523141
  {
522908
523142
  role: "user",
522909
523143
  content: question,
522910
- otid: randomUUID73()
523144
+ otid: randomUUID74()
522911
523145
  }
522912
523146
  ];
522913
523147
  let approvalRecoveryRetries = 0;
@@ -528378,7 +528612,7 @@ var init_conversation_switch_alert = __esm(() => {
528378
528612
  });
528379
528613
 
528380
528614
  // src/cli/app/use-submit-handler.ts
528381
- import { randomUUID as randomUUID74 } from "node:crypto";
528615
+ import { randomUUID as randomUUID75 } from "node:crypto";
528382
528616
  import { existsSync as existsSync82, readFileSync as readFileSync62, renameSync as renameSync14 } from "node:fs";
528383
528617
  import { tmpdir as tmpdir18 } from "node:os";
528384
528618
  import { join as join129 } from "node:path";
@@ -528712,7 +528946,7 @@ ${SYSTEM_REMINDER_CLOSE}` : "";
528712
528946
  content: buildTextParts(`${SYSTEM_REMINDER_OPEN}
528713
528947
  ${prompt}
528714
528948
  ${SYSTEM_REMINDER_CLOSE}`),
528715
- otid: randomUUID74()
528949
+ otid: randomUUID75()
528716
528950
  }
528717
528951
  ]);
528718
528952
  } catch (error4) {
@@ -528776,7 +529010,7 @@ ${SYSTEM_REMINDER_CLOSE}`),
528776
529010
  type: "message",
528777
529011
  role: "user",
528778
529012
  content: buildTextParts(buildModCommandPrompt(result4)),
528779
- otid: randomUUID74()
529013
+ otid: randomUUID75()
528780
529014
  }
528781
529015
  ]);
528782
529016
  } else if (result4.type === "output") {
@@ -528821,7 +529055,7 @@ ${SYSTEM_REMINDER_CLOSE}`),
528821
529055
  ${SYSTEM_REMINDER_OPEN}
528822
529056
  ${request5}
528823
529057
  ${SYSTEM_REMINDER_CLOSE}`),
528824
- otid: randomUUID74()
529058
+ otid: randomUUID75()
528825
529059
  }
528826
529060
  ]);
528827
529061
  } catch (error4) {
@@ -529090,7 +529324,7 @@ ${SYSTEM_REMINDER_CLOSE}`),
529090
529324
  ${SYSTEM_REMINDER_OPEN}
529091
529325
  ${request5}
529092
529326
  ${SYSTEM_REMINDER_CLOSE}`),
529093
- otid: randomUUID74()
529327
+ otid: randomUUID75()
529094
529328
  }
529095
529329
  ]);
529096
529330
  } catch (error4) {
@@ -529899,7 +530133,7 @@ ${SYSTEM_REMINDER_CLOSE}`;
529899
530133
  type: "message",
529900
530134
  role: "user",
529901
530135
  content: buildTextParts(skillMessage),
529902
- otid: randomUUID74()
530136
+ otid: randomUUID75()
529903
530137
  }
529904
530138
  ]);
529905
530139
  } catch (error4) {
@@ -530321,7 +530555,7 @@ Resumed reflection arena choice prompt for run ${run2.runId}.`, true);
530321
530555
  type: "message",
530322
530556
  role: "user",
530323
530557
  content: buildTextParts(initMessage),
530324
- otid: randomUUID74()
530558
+ otid: randomUUID75()
530325
530559
  }
530326
530560
  ]);
530327
530561
  } catch (error4) {
@@ -530354,7 +530588,7 @@ Resumed reflection arena choice prompt for run ${run2.runId}.`, true);
530354
530588
  type: "message",
530355
530589
  role: "user",
530356
530590
  content: buildTextParts(doctorMessage),
530357
- otid: randomUUID74()
530591
+ otid: randomUUID75()
530358
530592
  }
530359
530593
  ]);
530360
530594
  } catch (error4) {
@@ -530486,7 +530720,7 @@ Resumed reflection arena choice prompt for run ${run2.runId}.`, true);
530486
530720
  type: "message",
530487
530721
  role: "user",
530488
530722
  content: buildTextParts(wrapSkillPrompt2(matchedSkill.id, skillContent, userRequest)),
530489
- otid: randomUUID74()
530723
+ otid: randomUUID75()
530490
530724
  }
530491
530725
  ]);
530492
530726
  } catch (error4) {
@@ -538239,4 +538473,4 @@ function registerBunOAuthFlows() {
538239
538473
  registerBunOAuthFlows();
538240
538474
  await init_src5().then(() => exports_src2);
538241
538475
 
538242
- //# debugId=B1DF6A6CEBBF059664756E2164756E21
538476
+ //# debugId=EB8310B8BF028C6864756E2164756E21