@letta-ai/letta-code 0.34.31 → 0.34.32

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.
package/letta.js CHANGED
@@ -6044,7 +6044,7 @@ var package_default;
6044
6044
  var init_package = __esm(() => {
6045
6045
  package_default = {
6046
6046
  name: "@letta-ai/letta-code",
6047
- version: "0.34.31",
6047
+ version: "0.34.32",
6048
6048
  lettaStartupLogProtocol: 1,
6049
6049
  lettaConfigDirProtocol: 1,
6050
6050
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6322,7 +6322,7 @@ var init_package = __esm(() => {
6322
6322
  },
6323
6323
  lettaLifecycleProtocol: 1,
6324
6324
  lettaRuntimeGraphProtocol: 1,
6325
- lettaRuntimeGraphSha512: "sha512-E2rWRJpy7Cl1ZMcUvyUnnuFDfi7+nyq4GfZ6TzfxSrpiuiYWPXRRJOzb0KBdgHYRJRi+rdXWWKkZwvy9lgmLew==",
6325
+ lettaRuntimeGraphSha512: "sha512-k6/hR2IHpEKzR+Q6apFf2XdWJ1VIJXHIq74pZMH5EoGipLTIwCfuBzQnj1lmMiLaZC5+KXjGNgW9a4ZZb8/02A==",
6326
6326
  patchedDependencies: {
6327
6327
  "@earendil-works/pi-ai@0.99.1": "patches/@earendil-works%2Fpi-ai@0.99.1.patch"
6328
6328
  }
@@ -116346,11 +116346,10 @@ var init_pi_model_factory = __esm(() => {
116346
116346
 
116347
116347
  // src/backend/dev/pi-request-headers.ts
116348
116348
  function resolvePiRequestHeaders(input) {
116349
- if (input.provider !== "opencode-go")
116350
- return input.configuredHeaders;
116351
116349
  return {
116352
116350
  ...input.configuredHeaders,
116353
- "x-opencode-session": input.conversationId
116351
+ "x-letta-request-kind": input.requestKind,
116352
+ ...input.provider === "opencode-go" ? { "x-opencode-session": input.conversationId } : {}
116354
116353
  };
116355
116354
  }
116356
116355
 
@@ -116930,13 +116929,14 @@ async function runGenerateText(input, transcript2, defaultPrompt) {
116930
116929
  const headers = resolvePiRequestHeaders({
116931
116930
  provider: resolved2.model.provider,
116932
116931
  configuredHeaders: resolved2.headers,
116933
- conversationId: input.conversationId
116932
+ conversationId: input.conversationId,
116933
+ requestKind: "compaction"
116934
116934
  });
116935
116935
  const options = {
116936
116936
  ...resolved2.providerOptions,
116937
116937
  ...resolved2.apiKey ? { apiKey: resolved2.apiKey } : {},
116938
116938
  ...resolved2.timeout !== false ? { timeoutMs: resolved2.timeout } : {},
116939
- ...headers ? { headers } : {},
116939
+ headers,
116940
116940
  ...input.abortSignal ? { signal: input.abortSignal } : {},
116941
116941
  ...reasoning ? { reasoning } : {},
116942
116942
  maxRetries: 0,
@@ -117869,9 +117869,8 @@ function anthropicEffortForSettings(modelSettings) {
117869
117869
  const nestedReasoning = isRecord2(modelSettings.reasoning) ? modelSettings.reasoning : undefined;
117870
117870
  return stringValue2(modelSettings.effort) ?? stringValue2(nestedReasoning?.reasoning_effort) ?? stringValue2(modelSettings.reasoning_effort);
117871
117871
  }
117872
- function maxTokensForSettings(modelSettings) {
117873
- const maxTokens = modelSettings.max_tokens;
117874
- return typeof maxTokens === "number" && Number.isFinite(maxTokens) ? maxTokens : undefined;
117872
+ function finiteNumberValue(value) {
117873
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
117875
117874
  }
117876
117875
  function serviceTierForSettings(model, modelSettings) {
117877
117876
  if (model.api !== "openai-codex-responses")
@@ -118017,19 +118016,23 @@ class PiStreamAdapter {
118017
118016
  const headers = resolvePiRequestHeaders({
118018
118017
  provider: resolved2.model.provider,
118019
118018
  configuredHeaders: resolved2.headers,
118020
- conversationId: input.conversationId
118019
+ conversationId: input.conversationId,
118020
+ requestKind: "turn"
118021
118021
  });
118022
+ const maxTokens = finiteNumberValue(input.agent.model_settings.max_tokens);
118023
+ const temperature = finiteNumberValue(input.agent.model_settings.temperature);
118022
118024
  const options = {
118023
118025
  ...resolved2.providerOptions,
118024
118026
  ...resolved2.apiKey ? { apiKey: resolved2.apiKey } : {},
118025
118027
  ...resolved2.timeout !== false ? { timeoutMs: resolved2.timeout } : {},
118026
- ...headers ? { headers } : {},
118028
+ headers,
118027
118029
  ...this.abortSignal ? { signal: this.abortSignal } : {},
118028
118030
  maxRetries: 0,
118029
118031
  sessionId: input.conversationId,
118030
118032
  ...isRecord2(input.agent.model_settings.sampling_params) ? { samplingParams: input.agent.model_settings.sampling_params } : {},
118031
118033
  ...reasoning ? { reasoning } : {},
118032
- ...maxTokensForSettings(input.agent.model_settings) ? { maxTokens: maxTokensForSettings(input.agent.model_settings) } : {},
118034
+ ...maxTokens ? { maxTokens } : {},
118035
+ ...temperature !== undefined ? { temperature } : {},
118033
118036
  ...serviceTierForSettings(resolved2.model, input.agent.model_settings) ? {
118034
118037
  serviceTier: serviceTierForSettings(resolved2.model, input.agent.model_settings)
118035
118038
  } : {},
@@ -118037,6 +118040,19 @@ class PiStreamAdapter {
118037
118040
  parallelToolCalls: boolValue(input.agent.model_settings.parallel_tool_calls)
118038
118041
  } : {}
118039
118042
  };
118043
+ const verbosity = input.agent.model_settings.verbosity;
118044
+ if ((resolved2.model.api === "openai-responses" || resolved2.model.api === "openai-codex-responses") && (verbosity === "low" || verbosity === "medium" || verbosity === "high")) {
118045
+ const existing = options.onPayload;
118046
+ options.onPayload = async (payload, model) => {
118047
+ const next = await existing?.(payload, model) ?? payload;
118048
+ if (!isRecord2(next))
118049
+ return next;
118050
+ return {
118051
+ ...next,
118052
+ text: { ...isRecord2(next.text) ? next.text : {}, verbosity }
118053
+ };
118054
+ };
118055
+ }
118040
118056
  if (resolved2.model.api === "openai-responses") {
118041
118057
  options.onPayload = withOpenAIResponsesReplayIdSanitizer(options.onPayload);
118042
118058
  }
@@ -161584,7 +161600,21 @@ var init_shared_agent_listing = __esm(() => {
161584
161600
  init_request();
161585
161601
  });
161586
161602
 
161603
+ // src/utils/stdin.ts
161604
+ function readStdin() {
161605
+ return new Promise((resolve12, reject2) => {
161606
+ let value = "";
161607
+ process.stdin.setEncoding("utf8");
161608
+ process.stdin.on("data", (chunk2) => {
161609
+ value += chunk2;
161610
+ });
161611
+ process.stdin.on("end", () => resolve12(value));
161612
+ process.stdin.on("error", reject2);
161613
+ });
161614
+ }
161615
+
161587
161616
  // src/cli/subcommands/agents.ts
161617
+ import { readFile as readFile6 } from "node:fs/promises";
161588
161618
  import { parseArgs as parseArgs2 } from "node:util";
161589
161619
  function printUsage() {
161590
161620
  console.log(`
@@ -161608,8 +161638,12 @@ Create Options:
161608
161638
  --description <text> Agent description
161609
161639
  --tags <tag1,tag2> Tags (comma-separated)
161610
161640
  --pinned Pin the created agent globally
161641
+ --body <path> Create from a JSON agent create request instead of the
161642
+ options above ("-" reads stdin)
161611
161643
 
161612
- Creates a memfs-enabled agent with persona.md pre-populated.
161644
+ Creates a memfs-enabled agent with persona.md pre-populated. With --body, the
161645
+ request's system prompt, model settings, compaction settings, memory blocks,
161646
+ and tags are used as given.
161613
161647
 
161614
161648
  Notes:
161615
161649
  - Output is JSON only.
@@ -161661,8 +161695,44 @@ async function runAgentsSubcommand(argv) {
161661
161695
  printUsage();
161662
161696
  return 1;
161663
161697
  }
161698
+ async function readCreateBody(source) {
161699
+ const text2 = source === "-" ? await readStdin() : await readFile6(source, "utf8");
161700
+ const body3 = JSON.parse(text2);
161701
+ if (!body3 || typeof body3 !== "object" || Array.isArray(body3)) {
161702
+ throw new Error("--body must contain a JSON object");
161703
+ }
161704
+ return body3;
161705
+ }
161706
+ async function createAgentFromBody(source) {
161707
+ const { prepareRawCreateAgentBodyForMemfs: prepareRawCreateAgentBodyForMemfs2, enableMemfsIfCloud: enableMemfsIfCloud2 } = await Promise.resolve().then(() => (init_memory_filesystem2(), exports_memory_filesystem));
161708
+ const body3 = await prepareRawCreateAgentBodyForMemfs2(await readCreateBody(source));
161709
+ const agent = await getBackend().createAgent(body3);
161710
+ await enableMemfsIfCloud2(agent.id, { agentTags: agent.tags });
161711
+ return agent.id;
161712
+ }
161713
+ async function printCreatedAgent(agentId, pinned) {
161714
+ if (pinned) {
161715
+ settingsManager.pinAgent(agentId);
161716
+ }
161717
+ const updatedAgent = await getBackend().retrieveAgent(agentId);
161718
+ console.log(JSON.stringify(updatedAgent, null, 2));
161719
+ return 0;
161720
+ }
161664
161721
  async function runCreateAction(values4) {
161665
161722
  await settingsManager.initialize();
161723
+ if (typeof values4.body === "string") {
161724
+ const conflicting = BODY_EXCLUSIVE_OPTIONS.filter((option2) => values4[option2] !== undefined);
161725
+ if (conflicting.length > 0) {
161726
+ console.error(`--body cannot be combined with ${conflicting.map((option2) => `--${option2}`).join(", ")}`);
161727
+ return 1;
161728
+ }
161729
+ try {
161730
+ return await printCreatedAgent(await createAgentFromBody(values4.body), Boolean(values4.pinned));
161731
+ } catch (error4) {
161732
+ console.error(error4 instanceof Error ? error4.message : String(error4));
161733
+ return 1;
161734
+ }
161735
+ }
161666
161736
  const personalityInput = values4.personality;
161667
161737
  const personality = personalityInput ? resolvePersonalityId(personalityInput) : undefined;
161668
161738
  if (personalityInput && !personality) {
@@ -161702,12 +161772,7 @@ async function runCreateAction(values4) {
161702
161772
  agentTags: result2.agent.tags
161703
161773
  });
161704
161774
  }
161705
- if (values4.pinned) {
161706
- settingsManager.pinAgent(agentId);
161707
- }
161708
- const updatedAgent = await getBackend().retrieveAgent(agentId);
161709
- console.log(JSON.stringify(updatedAgent, null, 2));
161710
- return 0;
161775
+ return await printCreatedAgent(agentId, Boolean(values4.pinned));
161711
161776
  } catch (error4) {
161712
161777
  console.error(error4 instanceof Error ? error4.message : String(error4));
161713
161778
  return 1;
@@ -161766,7 +161831,7 @@ async function runListAction(values4) {
161766
161831
  return 1;
161767
161832
  }
161768
161833
  }
161769
- var AGENTS_OPTIONS;
161834
+ var AGENTS_OPTIONS, BODY_EXCLUSIVE_OPTIONS;
161770
161835
  var init_agents7 = __esm(() => {
161771
161836
  init_create5();
161772
161837
  init_personality();
@@ -161787,8 +161852,16 @@ var init_agents7 = __esm(() => {
161787
161852
  model: { type: "string" },
161788
161853
  personality: { type: "string" },
161789
161854
  description: { type: "string" },
161790
- pinned: { type: "boolean" }
161855
+ pinned: { type: "boolean" },
161856
+ body: { type: "string" }
161791
161857
  };
161858
+ BODY_EXCLUSIVE_OPTIONS = [
161859
+ "name",
161860
+ "model",
161861
+ "personality",
161862
+ "description",
161863
+ "tags"
161864
+ ];
161792
161865
  });
161793
161866
 
161794
161867
  // src/cli/subcommands/backend.ts
@@ -164589,6 +164662,13 @@ import {
164589
164662
  function isWindowsCommandShim(command) {
164590
164663
  return /\.(?:cmd|bat)$/i.test(command);
164591
164664
  }
164665
+ function getCommandProcessFactory({
164666
+ nativeSpawn = spawn5,
164667
+ platform: platform4 = process.platform,
164668
+ windowsSpawn = import_cross_spawn.default
164669
+ } = {}) {
164670
+ return platform4 === "win32" ? windowsSpawn : nativeSpawn;
164671
+ }
164592
164672
  function getPackageManagerProcessFactory({
164593
164673
  nativeSpawn = spawn5,
164594
164674
  platform: platform4 = process.platform,
@@ -169755,7 +169835,7 @@ var init_attachment_download = __esm(() => {
169755
169835
  });
169756
169836
 
169757
169837
  // src/channels/slack/file-upload.ts
169758
- import { readFile as readFile6 } from "node:fs/promises";
169838
+ import { readFile as readFile7 } from "node:fs/promises";
169759
169839
  import { basename as basename12, extname as extname4 } from "node:path";
169760
169840
  function resolveUploadMimeType(filePath) {
169761
169841
  switch (extname4(filePath).toLowerCase()) {
@@ -169782,7 +169862,7 @@ async function uploadSlackFile(slackClient, msg) {
169782
169862
  if (!msg.mediaPath) {
169783
169863
  throw new Error("mediaPath is required for Slack file uploads.");
169784
169864
  }
169785
- const buffer = await readFile6(msg.mediaPath);
169865
+ const buffer = await readFile7(msg.mediaPath);
169786
169866
  const uploadFileName = msg.fileName ?? basename12(msg.mediaPath);
169787
169867
  const uploadTitle = msg.title ?? uploadFileName;
169788
169868
  const uploadMimeType = resolveUploadMimeType(uploadFileName);
@@ -193322,8 +193402,8 @@ var require_CronFileParser = __commonJS((exports) => {
193322
193402
 
193323
193403
  class CronFileParser {
193324
193404
  static async parseFile(filePath) {
193325
- const { readFile: readFile7 } = await Promise.resolve().then(() => __importStar(__require("fs/promises")));
193326
- const data = await readFile7(filePath, "utf8");
193405
+ const { readFile: readFile8 } = await Promise.resolve().then(() => __importStar(__require("fs/promises")));
193406
+ const data = await readFile8(filePath, "utf8");
193327
193407
  return CronFileParser.#parseContent(data);
193328
193408
  }
193329
193409
  static parseFileSync(filePath) {
@@ -211550,7 +211630,7 @@ var init_mcp_client = __esm(() => {
211550
211630
  init_streamableHttp();
211551
211631
  DEFAULT_CLIENT_INFO = {
211552
211632
  name: "letta-code",
211553
- version: "0.34.31"
211633
+ version: "0.34.32"
211554
211634
  };
211555
211635
  });
211556
211636
 
@@ -213670,7 +213750,7 @@ import {
213670
213750
  rmSync as rmSync9,
213671
213751
  writeFileSync as writeFileSync21
213672
213752
  } from "node:fs";
213673
- import { link as link3, mkdir as mkdir8, readFile as readFile7, rm as rm5, writeFile as writeFile9 } from "node:fs/promises";
213753
+ import { link as link3, mkdir as mkdir8, readFile as readFile8, rm as rm5, writeFile as writeFile9 } from "node:fs/promises";
213674
213754
  import path10 from "node:path";
213675
213755
  function hasErrorCode(error5, code2) {
213676
213756
  return typeof error5 === "object" && error5 !== null && "code" in error5 && error5.code === code2;
@@ -213703,7 +213783,7 @@ function getRecoverableLockTokenSync(lockPath) {
213703
213783
  }
213704
213784
  async function getRecoverableLockToken(lockPath) {
213705
213785
  try {
213706
- const ownerToken = await readFile7(lockPath, "utf-8");
213786
+ const ownerToken = await readFile8(lockPath, "utf-8");
213707
213787
  return isLockOwnerProcessAlive(ownerToken) ? null : ownerToken;
213708
213788
  } catch {
213709
213789
  return null;
@@ -213812,7 +213892,7 @@ async function recoverStaleLock(lockPath, staleToken, recoveryOwner) {
213812
213892
  return false;
213813
213893
  let claimOwner;
213814
213894
  try {
213815
- claimOwner = await readFile7(claimPath, "utf-8");
213895
+ claimOwner = await readFile8(claimPath, "utf-8");
213816
213896
  } catch {
213817
213897
  return false;
213818
213898
  }
@@ -213829,7 +213909,7 @@ async function recoverStaleLock(lockPath, staleToken, recoveryOwner) {
213829
213909
  }
213830
213910
  return false;
213831
213911
  }
213832
- if (await readFile7(lockPath, "utf-8") !== staleToken)
213912
+ if (await readFile8(lockPath, "utf-8") !== staleToken)
213833
213913
  return false;
213834
213914
  await rm5(lockPath, { force: true });
213835
213915
  return true;
@@ -213870,7 +213950,7 @@ async function reclaimAbandonedLock(lockPath, allowDuringAcquisition = false) {
213870
213950
  if (acquisitionInProgress && !allowDuringAcquisition)
213871
213951
  return false;
213872
213952
  try {
213873
- if (await readFile7(handle2.lockPath, "utf-8") !== handle2.ownerToken) {
213953
+ if (await readFile8(handle2.lockPath, "utf-8") !== handle2.ownerToken) {
213874
213954
  abandonedLock = null;
213875
213955
  return false;
213876
213956
  }
@@ -214003,7 +214083,7 @@ async function releaseRemoteSettingsLock(handle2) {
214003
214083
  return;
214004
214084
  let released = false;
214005
214085
  try {
214006
- if (await readFile7(handle2.lockPath, "utf-8") !== handle2.ownerToken) {
214086
+ if (await readFile8(handle2.lockPath, "utf-8") !== handle2.ownerToken) {
214007
214087
  released = true;
214008
214088
  } else {
214009
214089
  await rm5(handle2.lockPath, { force: true });
@@ -214052,7 +214132,7 @@ import {
214052
214132
  rmSync as rmSync10,
214053
214133
  writeFileSync as writeFileSync22
214054
214134
  } from "node:fs";
214055
- import { readFile as readFile8, rm as rm6, writeFile as writeFile10 } from "node:fs/promises";
214135
+ import { readFile as readFile9, rm as rm6, writeFile as writeFile10 } from "node:fs/promises";
214056
214136
  import path11 from "node:path";
214057
214137
  function getRemoteSettingsPath() {
214058
214138
  return path11.join(resolveGlobalConfigDir(), "remote-settings.json");
@@ -214215,7 +214295,7 @@ function readCurrentRemoteSettingsSync(settingsPath) {
214215
214295
  }
214216
214296
  async function readCurrentRemoteSettings(settingsPath) {
214217
214297
  try {
214218
- const settings3 = JSON.parse(await readFile8(settingsPath, "utf-8"));
214298
+ const settings3 = JSON.parse(await readFile9(settingsPath, "utf-8"));
214219
214299
  const repairJournals = readCwdRepairJournals(settingsPath);
214220
214300
  return {
214221
214301
  repairJournals,
@@ -216284,7 +216364,7 @@ var WriteStdin_default = "Writes characters to an existing unified exec session
216284
216364
  var init_WriteStdin = () => {};
216285
216365
 
216286
216366
  // src/utils/text-files.ts
216287
- import { readFile as readFile9, writeFile as writeFile11 } from "node:fs/promises";
216367
+ import { readFile as readFile10, writeFile as writeFile11 } from "node:fs/promises";
216288
216368
  function getUtf16Bom(bytes) {
216289
216369
  if (bytes.length < 2)
216290
216370
  return null;
@@ -216312,7 +216392,7 @@ function decodeUtf8TextStrict(bytes, filePath) {
216312
216392
  }
216313
216393
  }
216314
216394
  async function readUtf8TextStrict(filePath) {
216315
- const bytes = await readFile9(filePath);
216395
+ const bytes = await readFile10(filePath);
216316
216396
  return decodeUtf8TextStrict(bytes, filePath);
216317
216397
  }
216318
216398
  async function writeUtf8Text(filePath, content) {
@@ -217083,7 +217163,7 @@ var init_manager = __esm(() => {
217083
217163
  });
217084
217164
 
217085
217165
  // src/tools/impl/artifact-files.ts
217086
- import { mkdir as mkdir9, readFile as readFile10, stat as stat5, writeFile as writeFile12 } from "node:fs/promises";
217166
+ import { mkdir as mkdir9, readFile as readFile11, stat as stat5, writeFile as writeFile12 } from "node:fs/promises";
217087
217167
  import { dirname as dirname18, isAbsolute as isAbsolute10, join as join46, relative as relative4, resolve as resolve15 } from "node:path";
217088
217168
  function assertArtifactsExperimentEnabled(toolName2) {
217089
217169
  if (!experimentManager.isEnabled("artifacts")) {
@@ -217140,7 +217220,7 @@ async function read_artifact_file(args) {
217140
217220
  if (stats.size > MAX_READ_FILE_BYTES) {
217141
217221
  throw new Error(`read_artifact_file: file is too large to read (${stats.size} bytes)`);
217142
217222
  }
217143
- const buffer = await readFile10(absolutePath);
217223
+ const buffer = await readFile11(absolutePath);
217144
217224
  return {
217145
217225
  path: relativePath,
217146
217226
  content: buffer.toString(encoding),
@@ -229375,6 +229455,673 @@ var init_analyzer = __esm(() => {
229375
229455
  ];
229376
229456
  });
229377
229457
 
229458
+ // src/agent/mcp-originator-authority-file.ts
229459
+ import { createHash as createHash9, randomUUID as randomUUID32 } from "node:crypto";
229460
+ import {
229461
+ closeSync as closeSync7,
229462
+ existsSync as existsSync39,
229463
+ fsyncSync as fsyncSync3,
229464
+ mkdirSync as mkdirSync32,
229465
+ openSync as openSync7,
229466
+ readFileSync as readFileSync35,
229467
+ renameSync as renameSync10,
229468
+ unlinkSync as unlinkSync10,
229469
+ writeFileSync as writeFileSync26
229470
+ } from "node:fs";
229471
+ import { dirname as dirname25, join as join55 } from "node:path";
229472
+ function isValidGeneration(generation4) {
229473
+ return typeof generation4 === "number" && Number.isSafeInteger(generation4) && generation4 >= 0;
229474
+ }
229475
+ function isValidUpdatedAtMs(updatedAtMs, nowMs) {
229476
+ return typeof updatedAtMs === "number" && Number.isSafeInteger(updatedAtMs) && updatedAtMs >= 0 && updatedAtMs <= nowMs + UPDATED_AT_FUTURE_SKEW_MS;
229477
+ }
229478
+ function authorityPersistentPath() {
229479
+ if (persistencePathOverride !== undefined)
229480
+ return persistencePathOverride;
229481
+ if (false)
229482
+ ;
229483
+ let serverUrl;
229484
+ try {
229485
+ serverUrl = getServerUrl();
229486
+ } catch {
229487
+ serverUrl = process.env.LETTA_BASE_URL ?? "uninitialized";
229488
+ }
229489
+ return authorityPersistentPathForServer(serverUrl);
229490
+ }
229491
+ function authorityPersistentPathForServer(serverUrl) {
229492
+ const namespace = createHash9("sha256").update(serverUrl).digest("hex").slice(0, 24);
229493
+ return join55(resolveGlobalConfigDir(), "state", namespace, "mcp-originator-authority-v1.json");
229494
+ }
229495
+ function mergeRetirementIntents(a2, b3) {
229496
+ if (a2 === undefined)
229497
+ return b3;
229498
+ if (b3 === undefined)
229499
+ return a2;
229500
+ return STATE_RANK[a2] >= STATE_RANK[b3] ? a2 : b3;
229501
+ }
229502
+ function mergeRecords(a2, b3) {
229503
+ if (!b3)
229504
+ return a2;
229505
+ const floor2 = Math.max(a2.floor ?? -1, b3.floor ?? -1);
229506
+ const state2 = STATE_RANK[a2.state] >= STATE_RANK[b3.state] ? a2.state : b3.state;
229507
+ const retiringTo = state2 === "live" ? mergeRetirementIntents(a2.retiringTo, b3.retiringTo) : undefined;
229508
+ return {
229509
+ ...floor2 >= 0 ? { floor: floor2 } : {},
229510
+ state: state2,
229511
+ ...retiringTo !== undefined ? { retiringTo } : {},
229512
+ updatedAtMs: Math.max(a2.updatedAtMs, b3.updatedAtMs)
229513
+ };
229514
+ }
229515
+ function readAuthorityRecords(path18) {
229516
+ const records = new Map;
229517
+ if (!existsSync39(path18))
229518
+ return { records, degraded: false };
229519
+ try {
229520
+ const parsed = JSON.parse(readFileSync35(path18, "utf8"));
229521
+ if (typeof parsed !== "object" || parsed === null || parsed.version !== 1 || typeof parsed.records !== "object" || parsed.records === null || Array.isArray(parsed.records))
229522
+ return { records, degraded: true };
229523
+ const nowMs = Date.now();
229524
+ for (const [runId, record6] of Object.entries(parsed.records)) {
229525
+ const retiringTo = record6?.retiringTo;
229526
+ if (record6 && (record6.state === "live" || record6.state === "headerless" || record6.state === "terminal") && (retiringTo === undefined || retiringTo === "headerless" || retiringTo === "terminal") && isValidUpdatedAtMs(record6.updatedAtMs, nowMs) && (record6.floor === undefined || isValidGeneration(record6.floor))) {
229527
+ records.set(runId, {
229528
+ ...record6.floor !== undefined ? { floor: record6.floor } : {},
229529
+ state: record6.state,
229530
+ ...record6.state === "live" && retiringTo !== undefined ? { retiringTo } : {},
229531
+ updatedAtMs: record6.updatedAtMs
229532
+ });
229533
+ } else {
229534
+ return { records, degraded: true };
229535
+ }
229536
+ }
229537
+ return { records, degraded: false };
229538
+ } catch {
229539
+ return { records, degraded: true };
229540
+ }
229541
+ }
229542
+ function writeAuthorityRecords(path18, records) {
229543
+ mkdirSync32(dirname25(path18), { recursive: true, mode: 448 });
229544
+ const file = {
229545
+ version: 1,
229546
+ records: Object.fromEntries(records)
229547
+ };
229548
+ const tmp = `${path18}.${process.pid}.${randomUUID32()}.tmp`;
229549
+ try {
229550
+ writeFileSync26(tmp, JSON.stringify(file), { mode: 384, flag: "wx" });
229551
+ const fd = openSync7(tmp, "r+");
229552
+ try {
229553
+ fsyncSync3(fd);
229554
+ } finally {
229555
+ closeSync7(fd);
229556
+ }
229557
+ renameSync10(tmp, path18);
229558
+ fsyncDirectory(dirname25(path18));
229559
+ } catch (error5) {
229560
+ try {
229561
+ unlinkSync10(tmp);
229562
+ } catch {}
229563
+ throw error5;
229564
+ }
229565
+ }
229566
+ var UPDATED_AT_FUTURE_SKEW_MS, persistencePathOverride, STATE_RANK;
229567
+ var init_mcp_originator_authority_file = __esm(() => {
229568
+ init_server_url();
229569
+ init_settings_path();
229570
+ init_durable_file_lock();
229571
+ UPDATED_AT_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000;
229572
+ STATE_RANK = {
229573
+ live: 0,
229574
+ headerless: 1,
229575
+ terminal: 2
229576
+ };
229577
+ });
229578
+
229579
+ // src/agent/mcp-originator-authority.ts
229580
+ import { mkdirSync as mkdirSync33 } from "node:fs";
229581
+ import { dirname as dirname26 } from "node:path";
229582
+ function pruneExpired(nowMs) {
229583
+ let pruned = false;
229584
+ for (const [runId, record6] of recordsBySuperRunId) {
229585
+ if (nowMs - record6.updatedAtMs > recordTtlMs) {
229586
+ recordsBySuperRunId.delete(runId);
229587
+ pruned = true;
229588
+ }
229589
+ }
229590
+ return pruned;
229591
+ }
229592
+ function authorityTransaction(mutate) {
229593
+ const path18 = authorityPersistentPath();
229594
+ if (!path18) {
229595
+ return mutate(recordsBySuperRunId, { degraded: false }).result;
229596
+ }
229597
+ mkdirSync33(dirname26(path18), { recursive: true, mode: 448 });
229598
+ const release = acquireDurableFileLock(path18, { waitMs: 2000 });
229599
+ try {
229600
+ const { records: disk, degraded } = readAuthorityRecords(path18);
229601
+ if (!degraded) {
229602
+ const memory3 = new Map(recordsBySuperRunId);
229603
+ recordsBySuperRunId.clear();
229604
+ for (const [runId, record6] of disk) {
229605
+ recordsBySuperRunId.set(runId, mergeRecords(record6, memory3.get(runId)) ?? record6);
229606
+ }
229607
+ for (const [runId, record6] of memory3) {
229608
+ if (!disk.has(runId))
229609
+ recordsBySuperRunId.set(runId, record6);
229610
+ }
229611
+ pruneExpired(Date.now());
229612
+ resumeDurableRetirementIntents();
229613
+ }
229614
+ const { result: result2, changed } = mutate(recordsBySuperRunId, { degraded });
229615
+ if (changed && !degraded)
229616
+ writeAuthorityRecords(path18, recordsBySuperRunId);
229617
+ return result2;
229618
+ } finally {
229619
+ release();
229620
+ }
229621
+ }
229622
+ function mutateDurableFirst(label, mutate) {
229623
+ if (!authorityPersistentPath()) {
229624
+ mutate(recordsBySuperRunId);
229625
+ return true;
229626
+ }
229627
+ for (let attempt2 = 1;attempt2 <= 3; attempt2 += 1) {
229628
+ try {
229629
+ const persisted = authorityTransaction((records, ctx) => {
229630
+ if (ctx.degraded)
229631
+ return { result: false, changed: false };
229632
+ mutate(records);
229633
+ return { result: true, changed: true };
229634
+ });
229635
+ if (persisted)
229636
+ return true;
229637
+ console.error(`[mcp-originator-authority] durable file is degraded for ${label}; the boundary holds in this process but is NOT durable across restart`);
229638
+ mutate(recordsBySuperRunId);
229639
+ return false;
229640
+ } catch (error5) {
229641
+ console.error(`[mcp-originator-authority] durable write failed for ${label} (attempt ${attempt2}/3)`, error5);
229642
+ }
229643
+ }
229644
+ console.error(`[mcp-originator-authority] durable write failed for ${label} after retries; the boundary still holds in this process but is NOT durable across restart`);
229645
+ mutate(recordsBySuperRunId);
229646
+ return false;
229647
+ }
229648
+ function scheduleRetirementRetry() {
229649
+ if (pendingRetirements.size === 0)
229650
+ return;
229651
+ if (retirementRetryTimer !== undefined)
229652
+ return;
229653
+ if (false)
229654
+ ;
229655
+ retirementRetryTimer = setTimeout(() => {
229656
+ retirementRetryTimer = undefined;
229657
+ retryPendingMcpOriginatorRetirements();
229658
+ }, retirementRetryIntervalMs);
229659
+ retirementRetryTimer.unref?.();
229660
+ }
229661
+ function retryPendingMcpOriginatorRetirements() {
229662
+ const nowMs = Date.now();
229663
+ let processed = 0;
229664
+ for (const [runId, pending2] of pendingRetirements) {
229665
+ if (nowMs - pending2.createdAtMs > recordTtlMs) {
229666
+ console.error(`[mcp-originator-authority] pending ${pending2.state} retirement for ${runId} outlived the ${Math.round(recordTtlMs / 60000)}-minute record TTL; dropping the retry (any token it fenced is dead at the server-side ceiling)`);
229667
+ pendingRetirements.delete(runId);
229668
+ continue;
229669
+ }
229670
+ if (processed >= MAX_RETIREMENT_RETRIES_PER_TICK) {
229671
+ continue;
229672
+ }
229673
+ processed += 1;
229674
+ const durable = mutateDurableFirst(`retirement retry (${pending2.state}) for ${runId}`, (records) => touchRecords(records, runId, pending2.generation, pending2.state, {
229675
+ preserveUpdatedAt: true
229676
+ }));
229677
+ if (durable)
229678
+ pendingRetirements.delete(runId);
229679
+ }
229680
+ if (pendingRetirements.size > 0)
229681
+ scheduleRetirementRetry();
229682
+ }
229683
+ function persistRetirementIntent(runId, state2, generation4) {
229684
+ const path18 = authorityPersistentPath();
229685
+ if (!path18)
229686
+ return;
229687
+ try {
229688
+ const release = acquireDurableFileLock(path18, { waitMs: 2000 });
229689
+ try {
229690
+ const { records: disk, degraded } = readAuthorityRecords(path18);
229691
+ if (degraded) {
229692
+ console.error(`[mcp-originator-authority] durable file is degraded for the retirement intent (${state2}) for ${runId}; the boundary holds in this process only`);
229693
+ return;
229694
+ }
229695
+ const existing = disk.get(runId);
229696
+ if (existing && existing.state !== "live")
229697
+ return;
229698
+ const floor2 = generation4 !== undefined && isValidGeneration(generation4) ? Math.max(existing?.floor ?? -1, generation4) : existing?.floor;
229699
+ disk.set(runId, {
229700
+ ...floor2 !== undefined && floor2 >= 0 ? { floor: floor2 } : {},
229701
+ state: "live",
229702
+ retiringTo: mergeRetirementIntents(existing?.retiringTo, state2) ?? state2,
229703
+ updatedAtMs: existing?.updatedAtMs ?? Date.now()
229704
+ });
229705
+ writeAuthorityRecords(path18, disk);
229706
+ } finally {
229707
+ release();
229708
+ }
229709
+ } catch (error5) {
229710
+ console.error(`[mcp-originator-authority] durable retirement intent (${state2}) write failed for ${runId}; peers cannot see the boundary until a retry lands the mark`, error5);
229711
+ }
229712
+ }
229713
+ function resumeDurableRetirementIntents() {
229714
+ for (const [runId, record6] of recordsBySuperRunId) {
229715
+ if (record6.state !== "live" || record6.retiringTo === undefined)
229716
+ continue;
229717
+ const existing = pendingRetirements.get(runId);
229718
+ if (existing && existing.createdAtMs <= record6.updatedAtMs)
229719
+ continue;
229720
+ pendingRetirements.set(runId, {
229721
+ state: record6.retiringTo,
229722
+ ...record6.floor !== undefined ? { generation: record6.floor } : {},
229723
+ createdAtMs: Math.min(existing?.createdAtMs ?? record6.updatedAtMs, record6.updatedAtMs)
229724
+ });
229725
+ }
229726
+ scheduleRetirementRetry();
229727
+ }
229728
+ function registerPendingRetirement(runId, state2, generation4, durable) {
229729
+ if (durable) {
229730
+ const pending2 = pendingRetirements.get(runId);
229731
+ if (pending2 && STATE_RANK[pending2.state] <= STATE_RANK[state2]) {
229732
+ pendingRetirements.delete(runId);
229733
+ }
229734
+ return;
229735
+ }
229736
+ persistRetirementIntent(runId, state2, generation4);
229737
+ const existing = pendingRetirements.get(runId);
229738
+ const merged = {
229739
+ state: existing && STATE_RANK[existing.state] > STATE_RANK[state2] ? existing.state : state2,
229740
+ createdAtMs: existing?.createdAtMs ?? Date.now()
229741
+ };
229742
+ const mergedGeneration = generation4 ?? existing?.generation;
229743
+ if (mergedGeneration !== undefined)
229744
+ merged.generation = mergedGeneration;
229745
+ pendingRetirements.set(runId, merged);
229746
+ scheduleRetirementRetry();
229747
+ }
229748
+ function touchRecords(records, runId, generation4, state2, options) {
229749
+ const existing = records.get(runId);
229750
+ const usableGeneration = generation4 !== undefined && isValidGeneration(generation4) ? generation4 : undefined;
229751
+ const floor2 = usableGeneration === undefined ? existing?.floor : Math.max(existing?.floor ?? -1, usableGeneration);
229752
+ const nextState = state2 === undefined ? existing?.state ?? "live" : existing?.state !== undefined && STATE_RANK[existing.state] > STATE_RANK[state2] ? existing.state : state2;
229753
+ records.set(runId, {
229754
+ ...floor2 !== undefined ? { floor: floor2 } : {},
229755
+ state: nextState,
229756
+ ...nextState === "live" && existing?.retiringTo !== undefined ? { retiringTo: existing.retiringTo } : {},
229757
+ updatedAtMs: options?.preserveUpdatedAt === true && existing !== undefined ? existing.updatedAtMs : Date.now()
229758
+ });
229759
+ }
229760
+ function admitMcpOriginatorDelivery(runId, generation4) {
229761
+ if (generation4 !== undefined && !isValidGeneration(generation4)) {
229762
+ console.error(`[mcp-originator-authority] malformed generation for ${runId}; denying admission (fail-closed)`);
229763
+ return { admitted: false, permanent: true };
229764
+ }
229765
+ if (!authorityPersistentPath()) {
229766
+ const record6 = recordsBySuperRunId.get(runId);
229767
+ if (record6) {
229768
+ if (record6.state !== "live" || record6.retiringTo !== undefined)
229769
+ return { admitted: false, permanent: true };
229770
+ if (record6.floor !== undefined && (generation4 === undefined || generation4 < record6.floor))
229771
+ return { admitted: false, permanent: true };
229772
+ }
229773
+ touchRecords(recordsBySuperRunId, runId, generation4);
229774
+ return { admitted: true };
229775
+ }
229776
+ try {
229777
+ return authorityTransaction((records, ctx) => {
229778
+ if (ctx.degraded) {
229779
+ console.error(`[mcp-originator-authority] durable file is degraded; denying admission for ${runId} (fail-closed, retryable)`);
229780
+ return {
229781
+ result: { admitted: false, permanent: false },
229782
+ changed: false
229783
+ };
229784
+ }
229785
+ const record6 = records.get(runId);
229786
+ if (record6) {
229787
+ if (record6.state !== "live" || record6.retiringTo !== undefined)
229788
+ return {
229789
+ result: { admitted: false, permanent: true },
229790
+ changed: false
229791
+ };
229792
+ if (record6.floor !== undefined && (generation4 === undefined || generation4 < record6.floor))
229793
+ return {
229794
+ result: { admitted: false, permanent: true },
229795
+ changed: false
229796
+ };
229797
+ }
229798
+ touchRecords(records, runId, generation4);
229799
+ return { result: { admitted: true }, changed: true };
229800
+ });
229801
+ } catch (error5) {
229802
+ console.error(`[mcp-originator-authority] admission transaction failed for ${runId}; denying the delivery (fail-closed, retryable)`, error5);
229803
+ return { admitted: false, permanent: false };
229804
+ }
229805
+ }
229806
+ function mcpOriginatorAuthorityPermitsUse(runId, generation4) {
229807
+ if (generation4 !== undefined && !isValidGeneration(generation4)) {
229808
+ console.error(`[mcp-originator-authority] malformed generation for ${runId}; withdrawing the token (fail-closed)`);
229809
+ return false;
229810
+ }
229811
+ try {
229812
+ return authorityTransaction((records, ctx) => {
229813
+ if (ctx.degraded)
229814
+ return { result: false, changed: false };
229815
+ const record6 = records.get(runId);
229816
+ if (!record6)
229817
+ return { result: true, changed: false };
229818
+ if (record6.state !== "live" || record6.retiringTo !== undefined)
229819
+ return { result: false, changed: false };
229820
+ if (record6.floor !== undefined && generation4 !== undefined && generation4 < record6.floor)
229821
+ return { result: false, changed: false };
229822
+ return { result: true, changed: false };
229823
+ });
229824
+ } catch (error5) {
229825
+ console.error(`[mcp-originator-authority] use check failed for ${runId}; withdrawing the token (fail-closed)`, error5);
229826
+ return false;
229827
+ }
229828
+ }
229829
+ function markMcpOriginatorHeaderless(runId, deletedGeneration) {
229830
+ const durable = mutateDurableFirst(`headerless mark for ${runId}`, (records) => touchRecords(records, runId, deletedGeneration, "headerless"));
229831
+ registerPendingRetirement(runId, "headerless", deletedGeneration, durable);
229832
+ return durable;
229833
+ }
229834
+ function markMcpOriginatorTerminal(runId, deletedGeneration) {
229835
+ const durable = mutateDurableFirst(`terminal mark for ${runId}`, (records) => touchRecords(records, runId, deletedGeneration, "terminal"));
229836
+ registerPendingRetirement(runId, "terminal", deletedGeneration, durable);
229837
+ return durable;
229838
+ }
229839
+ var AUTHORITY_RECORD_TTL_MS, recordTtlMs, recordsBySuperRunId, pendingRetirements, retirementRetryTimer, retirementRetryIntervalMs = 30000, MAX_RETIREMENT_RETRIES_PER_TICK = 25;
229840
+ var init_mcp_originator_authority = __esm(() => {
229841
+ init_durable_file_lock();
229842
+ init_mcp_originator_authority_file();
229843
+ AUTHORITY_RECORD_TTL_MS = 2 * 60 * 60 * 1000;
229844
+ recordTtlMs = AUTHORITY_RECORD_TTL_MS;
229845
+ recordsBySuperRunId = new Map;
229846
+ pendingRetirements = new Map;
229847
+ });
229848
+
229849
+ // src/agent/mcp-originator-keepalive.ts
229850
+ async function runKeepaliveTick(superRunId) {
229851
+ const entry = keepalives.get(superRunId);
229852
+ if (!entry || entry.ticking)
229853
+ return;
229854
+ const token2 = entry.hooks?.getToken();
229855
+ if (!token2) {
229856
+ stopMcpOriginatorKeepalive(superRunId);
229857
+ return;
229858
+ }
229859
+ entry.ticking = true;
229860
+ try {
229861
+ const result2 = await verifyWithHardBound(token2, verifyTimeoutMs);
229862
+ if (entry.hooks?.getToken() !== token2) {
229863
+ return;
229864
+ }
229865
+ entry.consecutiveFailures = 0;
229866
+ if (!result2.valid) {
229867
+ console.warn(`[mcp-originator-keepalive] server denied the originator token for super run ${superRunId}; withdrawing it (turn continues unattributed)`);
229868
+ entry.hooks?.withdraw();
229869
+ stopMcpOriginatorKeepalive(superRunId);
229870
+ return;
229871
+ }
229872
+ } catch (error5) {
229873
+ if (entry.hooks?.getToken() !== token2) {
229874
+ return;
229875
+ }
229876
+ entry.consecutiveFailures += 1;
229877
+ if (entry.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
229878
+ console.error(`[mcp-originator-keepalive] renewal failed ${entry.consecutiveFailures} times for super run ${superRunId}; stopping renewal (the server-side TTL now bounds the token):`, error5 instanceof Error ? error5.message : error5);
229879
+ stopMcpOriginatorKeepalive(superRunId);
229880
+ return;
229881
+ }
229882
+ } finally {
229883
+ entry.ticking = false;
229884
+ if (schedulingEnabled && keepalives.get(superRunId) === entry) {
229885
+ const delay3 = entry.verifyAsap ? 0 : nextDelayMs(entry.consecutiveFailures);
229886
+ entry.verifyAsap = false;
229887
+ entry.timer = setTimeout(() => {
229888
+ runKeepaliveTick(superRunId);
229889
+ }, delay3);
229890
+ entry.timer?.unref();
229891
+ }
229892
+ }
229893
+ }
229894
+ function nextDelayMs(consecutiveFailures) {
229895
+ if (consecutiveFailures <= 0)
229896
+ return intervalMs;
229897
+ const lastDelay = FAILURE_RETRY_DELAYS_MS[FAILURE_RETRY_DELAYS_MS.length - 1];
229898
+ return FAILURE_RETRY_DELAYS_MS[Math.min(consecutiveFailures, FAILURE_RETRY_DELAYS_MS.length) - 1] ?? lastDelay ?? intervalMs;
229899
+ }
229900
+ function verifyWithHardBound(token2, budgetMs) {
229901
+ return new Promise((resolve27, reject2) => {
229902
+ let settled = false;
229903
+ const timer = setTimeout(() => {
229904
+ if (settled)
229905
+ return;
229906
+ settled = true;
229907
+ reject2(new Error(`[mcp-originator-keepalive] verify exceeded the ${budgetMs}ms hard bound`));
229908
+ }, budgetMs);
229909
+ verifyImpl(token2, AbortSignal.timeout(budgetMs)).then((result2) => {
229910
+ if (settled)
229911
+ return;
229912
+ settled = true;
229913
+ clearTimeout(timer);
229914
+ resolve27(result2);
229915
+ }, (error5) => {
229916
+ if (settled)
229917
+ return;
229918
+ settled = true;
229919
+ clearTimeout(timer);
229920
+ reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
229921
+ });
229922
+ });
229923
+ }
229924
+ function startMcpOriginatorKeepalive(superRunId, hooks) {
229925
+ const existing = keepalives.get(superRunId);
229926
+ if (existing) {
229927
+ existing.hooks = hooks;
229928
+ existing.consecutiveFailures = 0;
229929
+ existing.verifyAsap = true;
229930
+ if (schedulingEnabled && !existing.ticking) {
229931
+ clearTimeout(existing.timer);
229932
+ existing.verifyAsap = false;
229933
+ existing.timer = setTimeout(() => {
229934
+ runKeepaliveTick(superRunId);
229935
+ }, 0);
229936
+ existing.timer?.unref();
229937
+ }
229938
+ return;
229939
+ }
229940
+ const entry = {
229941
+ timer: schedulingEnabled ? setTimeout(() => {
229942
+ runKeepaliveTick(superRunId);
229943
+ }, 0) : undefined,
229944
+ consecutiveFailures: 0,
229945
+ ticking: false,
229946
+ verifyAsap: false,
229947
+ hooks
229948
+ };
229949
+ entry.timer?.unref();
229950
+ keepalives.set(superRunId, entry);
229951
+ }
229952
+ function stopMcpOriginatorKeepalive(superRunId) {
229953
+ const entry = keepalives.get(superRunId);
229954
+ if (!entry)
229955
+ return;
229956
+ clearTimeout(entry.timer);
229957
+ keepalives.delete(superRunId);
229958
+ }
229959
+ function stopAllMcpOriginatorKeepalives() {
229960
+ for (const runId of [...keepalives.keys()]) {
229961
+ stopMcpOriginatorKeepalive(runId);
229962
+ }
229963
+ }
229964
+ var DEFAULT_KEEPALIVE_INTERVAL_MS = 120000, MAX_CONSECUTIVE_FAILURES = 3, FAILURE_RETRY_DELAYS_MS, VERIFY_TIMEOUT_MS = 30000, defaultVerify = async (token2, signal) => apiRequest("POST", "/v1/mcp-originator-tokens/verify", { token: token2 }, { signal }), verifyImpl, intervalMs, verifyTimeoutMs, keepalives, schedulingEnabled = true;
229965
+ var init_mcp_originator_keepalive = __esm(() => {
229966
+ init_request();
229967
+ FAILURE_RETRY_DELAYS_MS = [15000, 30000];
229968
+ verifyImpl = defaultVerify;
229969
+ intervalMs = DEFAULT_KEEPALIVE_INTERVAL_MS;
229970
+ verifyTimeoutMs = VERIFY_TIMEOUT_MS;
229971
+ keepalives = new Map;
229972
+ });
229973
+
229974
+ // src/agent/mcp-originator-tokens.ts
229975
+ function getMcpOriginatorToken(superRunId) {
229976
+ if (!superRunId)
229977
+ return;
229978
+ const entry = entriesBySuperRunId.get(superRunId);
229979
+ if (!entry || entry.token === null)
229980
+ return;
229981
+ if (!mcpOriginatorAuthorityPermitsUse(superRunId, entry.generation)) {
229982
+ deleteMcpOriginatorToken(superRunId);
229983
+ return;
229984
+ }
229985
+ return entry.token;
229986
+ }
229987
+ function deleteMcpOriginatorToken(superRunId) {
229988
+ entriesBySuperRunId.delete(superRunId);
229989
+ stopMcpOriginatorKeepalive(superRunId);
229990
+ }
229991
+ function keepaliveHooks(superRunId) {
229992
+ return {
229993
+ getToken: () => getMcpOriginatorToken(superRunId),
229994
+ withdraw: () => deleteMcpOriginatorToken(superRunId)
229995
+ };
229996
+ }
229997
+ function clearMcpOriginatorTokens() {
229998
+ entriesBySuperRunId.clear();
229999
+ stopAllMcpOriginatorKeepalives();
230000
+ }
230001
+ function readMcpOriginatorDelivery(payload) {
230002
+ const wire = typeof payload === "object" && payload !== null ? payload : {};
230003
+ const superRunId = typeof wire.super_run_id === "string" && wire.super_run_id.length > 0 ? wire.super_run_id : undefined;
230004
+ const token2 = typeof wire.mcp_originator_token === "string" && wire.mcp_originator_token.length > 0 ? wire.mcp_originator_token : undefined;
230005
+ const generation4 = typeof wire.mcp_originator_generation === "number" && Number.isInteger(wire.mcp_originator_generation) && wire.mcp_originator_generation >= 0 && Number.isSafeInteger(wire.mcp_originator_generation) ? wire.mcp_originator_generation : undefined;
230006
+ return {
230007
+ ...superRunId ? { superRunId } : {},
230008
+ ...token2 ? { token: token2 } : {},
230009
+ ...generation4 !== undefined ? { generation: generation4 } : {},
230010
+ ...wire.mcp_originator_generation !== undefined && generation4 === undefined ? { malformedGeneration: true } : {}
230011
+ };
230012
+ }
230013
+ function deliveryIsAtLeastAsNew(existing, incomingGeneration) {
230014
+ if (existing.generation === undefined)
230015
+ return true;
230016
+ if (incomingGeneration === undefined)
230017
+ return false;
230018
+ return incomingGeneration >= existing.generation;
230019
+ }
230020
+ function denyMalformedGeneration(frame, delivery, context3) {
230021
+ const rawGeneration = frame?.mcp_originator_generation;
230022
+ console.error(`[MCP originator] run ${delivery.superRunId}: ${context3}denying delivery with malformed generation (type=${typeof rawGeneration}${typeof rawGeneration === "string" ? ` length=${rawGeneration.length}` : ""})`);
230023
+ return "denied_permanent";
230024
+ }
230025
+ function installPreGatedMcpOriginatorDelivery(delivery, options) {
230026
+ if (!delivery.superRunId || delivery.malformedGeneration)
230027
+ return;
230028
+ const existing = entriesBySuperRunId.get(delivery.superRunId);
230029
+ if (delivery.token) {
230030
+ if (existing) {
230031
+ if (!deliveryIsAtLeastAsNew(existing, delivery.generation))
230032
+ return;
230033
+ } else if (options?.allowCreate === false && options?.mayRecreateOwner?.() !== true) {
230034
+ return;
230035
+ }
230036
+ entriesBySuperRunId.set(delivery.superRunId, {
230037
+ token: delivery.token,
230038
+ ...delivery.generation !== undefined ? { generation: delivery.generation } : existing?.generation !== undefined ? { generation: existing.generation } : {}
230039
+ });
230040
+ startMcpOriginatorKeepalive(delivery.superRunId, keepaliveHooks(delivery.superRunId));
230041
+ return;
230042
+ }
230043
+ if (!existing)
230044
+ return;
230045
+ if (!deliveryIsAtLeastAsNew(existing, delivery.generation))
230046
+ return;
230047
+ entriesBySuperRunId.set(delivery.superRunId, {
230048
+ token: null,
230049
+ ...delivery.generation !== undefined ? { generation: delivery.generation } : existing.generation !== undefined ? { generation: existing.generation } : {}
230050
+ });
230051
+ stopMcpOriginatorKeepalive(delivery.superRunId);
230052
+ }
230053
+ function recordMcpOriginatorDelivery(frame, options) {
230054
+ const delivery = readMcpOriginatorDelivery(frame);
230055
+ if (!delivery.superRunId)
230056
+ return "none";
230057
+ if (delivery.malformedGeneration) {
230058
+ return denyMalformedGeneration(frame, delivery, "");
230059
+ }
230060
+ const admission = admitMcpOriginatorDelivery(delivery.superRunId, delivery.generation);
230061
+ if (!admission.admitted) {
230062
+ return admission.permanent ? "denied_permanent" : "denied_retryable";
230063
+ }
230064
+ installPreGatedMcpOriginatorDelivery(delivery, options);
230065
+ return "admitted";
230066
+ }
230067
+ function gateMcpOriginatorDeliveryAdmission(frame) {
230068
+ const delivery = readMcpOriginatorDelivery(frame);
230069
+ if (!delivery.superRunId)
230070
+ return { verdict: "none" };
230071
+ if (delivery.malformedGeneration) {
230072
+ return {
230073
+ verdict: denyMalformedGeneration(frame, delivery, "pre-commit gate ")
230074
+ };
230075
+ }
230076
+ const admission = admitMcpOriginatorDelivery(delivery.superRunId, delivery.generation);
230077
+ if (!admission.admitted) {
230078
+ return {
230079
+ verdict: admission.permanent ? "denied_permanent" : "denied_retryable"
230080
+ };
230081
+ }
230082
+ return { verdict: "admitted", delivery };
230083
+ }
230084
+ function retireMcpOriginatorTokensOnOriginSwap(turnSuperRunId, queuedSuperRunId) {
230085
+ if (queuedSuperRunId === turnSuperRunId)
230086
+ return;
230087
+ for (const runId of [turnSuperRunId, queuedSuperRunId]) {
230088
+ if (!runId)
230089
+ continue;
230090
+ const generation4 = entriesBySuperRunId.get(runId)?.generation;
230091
+ if (markMcpOriginatorHeaderless(runId, generation4)) {
230092
+ deleteMcpOriginatorToken(runId);
230093
+ } else {
230094
+ console.error(`[mcp-originator-tokens] headerless mark for ${runId} is NOT durable; keeping the volatile entry (unusable in this process) so restart cannot resurrect authority`);
230095
+ }
230096
+ }
230097
+ }
230098
+ function retireMcpOriginatorTokenOnTerminal(superRunId) {
230099
+ if (!superRunId)
230100
+ return;
230101
+ const generation4 = entriesBySuperRunId.get(superRunId)?.generation;
230102
+ if (markMcpOriginatorTerminal(superRunId, generation4)) {
230103
+ deleteMcpOriginatorToken(superRunId);
230104
+ } else {
230105
+ console.error(`[mcp-originator-tokens] terminal mark for ${superRunId} is NOT durable; keeping the volatile entry (unusable in this process) so restart cannot resurrect authority`);
230106
+ }
230107
+ }
230108
+ function retireMcpOriginatorTokenOnMixedMerge(superRunId) {
230109
+ if (!superRunId)
230110
+ return;
230111
+ const generation4 = entriesBySuperRunId.get(superRunId)?.generation;
230112
+ if (markMcpOriginatorHeaderless(superRunId, generation4)) {
230113
+ deleteMcpOriginatorToken(superRunId);
230114
+ } else {
230115
+ console.error(`[mcp-originator-tokens] mixed-merge headerless mark for ${superRunId} is NOT durable; keeping the volatile entry (unusable in this process) so restart cannot resurrect authority`);
230116
+ }
230117
+ }
230118
+ var entriesBySuperRunId;
230119
+ var init_mcp_originator_tokens = __esm(() => {
230120
+ init_mcp_originator_authority();
230121
+ init_mcp_originator_keepalive();
230122
+ entriesBySuperRunId = new Map;
230123
+ });
230124
+
229378
230125
  // src/utils/message-image-normalization.ts
229379
230126
  function isSupportedBase64ImageMediaType(mediaType) {
229380
230127
  return SUPPORTED_BASE64_IMAGE_MEDIA_TYPES.has(mediaType);
@@ -229717,13 +230464,13 @@ var init_approval_result_normalization = __esm(() => {
229717
230464
 
229718
230465
  // src/agent/client-skills-watcher.ts
229719
230466
  import {
229720
- existsSync as existsSync39,
230467
+ existsSync as existsSync40,
229721
230468
  readdirSync as readdirSync14,
229722
230469
  realpathSync as realpathSync8,
229723
230470
  statSync as statSync18,
229724
230471
  watch as watch2
229725
230472
  } from "node:fs";
229726
- import { dirname as dirname25, relative as relative6, resolve as resolve27, sep as sep7 } from "node:path";
230473
+ import { dirname as dirname27, relative as relative6, resolve as resolve27, sep as sep7 } from "node:path";
229727
230474
  function defaultWatchFunction(path18, options, listener) {
229728
230475
  return watch2(path18, options, listener);
229729
230476
  }
@@ -229737,7 +230484,7 @@ function isDirectory(path18) {
229737
230484
  function findNearestExistingDirectory(path18) {
229738
230485
  let candidate = resolve27(path18);
229739
230486
  while (!isDirectory(candidate)) {
229740
- const parent = dirname25(candidate);
230487
+ const parent = dirname27(candidate);
229741
230488
  if (parent === candidate) {
229742
230489
  return null;
229743
230490
  }
@@ -229817,7 +230564,7 @@ class ClientSkillsWatcher {
229817
230564
  const watchPaths = new Set;
229818
230565
  let recursive = false;
229819
230566
  let awaitedChild = null;
229820
- if (existsSync39(root2)) {
230567
+ if (existsSync40(root2)) {
229821
230568
  recursive = true;
229822
230569
  watchPaths.add(root2);
229823
230570
  collectSymlinkDirectoryTargets(root2, watchPaths, new Set);
@@ -229870,16 +230617,16 @@ __export(exports_skills2, {
229870
230617
  SKILLS_DIR: () => SKILLS_DIR,
229871
230618
  PROJECT_SKILLS_DIR: () => PROJECT_SKILLS_DIR
229872
230619
  });
229873
- import { existsSync as existsSync40 } from "node:fs";
229874
- import { readdir as readdir4, readFile as readFile11, realpath as realpath3, stat as stat6 } from "node:fs/promises";
229875
- import { dirname as dirname26, join as join55 } from "node:path";
230620
+ import { existsSync as existsSync41 } from "node:fs";
230621
+ import { readdir as readdir4, readFile as readFile12, realpath as realpath3, stat as stat6 } from "node:fs/promises";
230622
+ import { dirname as dirname28, join as join56 } from "node:path";
229876
230623
  import { fileURLToPath as fileURLToPath6 } from "node:url";
229877
230624
  function getBundledSkillsPath() {
229878
- const thisDir = dirname26(fileURLToPath6(import.meta.url));
230625
+ const thisDir = dirname28(fileURLToPath6(import.meta.url));
229879
230626
  if (thisDir.includes("src/agent") || thisDir.includes("src\\agent")) {
229880
- return join55(thisDir, "../skills/builtin");
230627
+ return join56(thisDir, "../skills/builtin");
229881
230628
  }
229882
- return join55(thisDir, "skills");
230629
+ return join56(thisDir, "skills");
229883
230630
  }
229884
230631
  function compareSkills(a2, b3) {
229885
230632
  return a2.id.localeCompare(b3.id) || a2.source.localeCompare(b3.source) || a2.path.localeCompare(b3.path);
@@ -229926,10 +230673,10 @@ function isSkillAvailableForAgent(skill, agentId) {
229926
230673
  return true;
229927
230674
  }
229928
230675
  function getGlobalSkillsDir(env6 = process.env) {
229929
- return join55(resolveGlobalStateDir(env6, env6.HOME || env6.USERPROFILE || "~"), "skills");
230676
+ return join56(resolveGlobalStateDir(env6, env6.HOME || env6.USERPROFILE || "~"), "skills");
229930
230677
  }
229931
230678
  function getAgentSkillsDir(agentId) {
229932
- return join55(resolveGlobalStateDir(), "agents", agentId, "memory/skills");
230679
+ return join56(resolveGlobalStateDir(), "agents", agentId, "memory/skills");
229933
230680
  }
229934
230681
  async function getBundledSkills() {
229935
230682
  const bundledPath = getBundledSkillsPath();
@@ -229938,7 +230685,7 @@ async function getBundledSkills() {
229938
230685
  }
229939
230686
  async function discoverSkillsFromDir(skillsPath, source) {
229940
230687
  const errors6 = [];
229941
- if (!existsSync40(skillsPath)) {
230688
+ if (!existsSync41(skillsPath)) {
229942
230689
  return { skills: [], errors: [] };
229943
230690
  }
229944
230691
  const skills = [];
@@ -229952,7 +230699,7 @@ async function discoverSkillsFromDir(skillsPath, source) {
229952
230699
  }
229953
230700
  return { skills, errors: errors6 };
229954
230701
  }
229955
- async function discoverSkills(projectSkillsPath = join55(process.cwd(), SKILLS_DIR), agentId, options) {
230702
+ async function discoverSkills(projectSkillsPath = join56(process.cwd(), SKILLS_DIR), agentId, options) {
229956
230703
  const allErrors = [];
229957
230704
  const skillsById = new Map;
229958
230705
  const sourceSet = new Set(options?.sources ?? ALL_SKILL_SOURCES);
@@ -230007,7 +230754,7 @@ async function findSkillFiles(currentPath, rootPath, skills, errors6, source, vi
230007
230754
  try {
230008
230755
  const entries = await readdir4(currentPath, { withFileTypes: true });
230009
230756
  for (const entry of entries) {
230010
- const fullPath = join55(currentPath, entry.name);
230757
+ const fullPath = join56(currentPath, entry.name);
230011
230758
  try {
230012
230759
  let isDirectory2 = entry.isDirectory();
230013
230760
  let isFile = entry.isFile();
@@ -230046,7 +230793,7 @@ async function findSkillFiles(currentPath, rootPath, skills, errors6, source, vi
230046
230793
  }
230047
230794
  }
230048
230795
  async function parseSkillFile(filePath, rootPath, source) {
230049
- const content = await readFile11(filePath, "utf-8");
230796
+ const content = await readFile12(filePath, "utf-8");
230050
230797
  const { frontmatter, body: body3 } = parseFrontmatter(content);
230051
230798
  const normalizedRoot = rootPath.endsWith("/") ? rootPath.slice(0, -1) : rootPath;
230052
230799
  const relativePath = filePath.slice(normalizedRoot.length + 1);
@@ -230107,12 +230854,12 @@ var init_skills5 = __esm(() => {
230107
230854
  "video-generation",
230108
230855
  "working-across-computers"
230109
230856
  ]);
230110
- PROJECT_SKILLS_DIR = join55(".agents", "skills");
230857
+ PROJECT_SKILLS_DIR = join56(".agents", "skills");
230111
230858
  });
230112
230859
 
230113
230860
  // src/agent/shared-memory-skills.ts
230114
- import { existsSync as existsSync41 } from "node:fs";
230115
- import { dirname as dirname27, join as join56 } from "node:path";
230861
+ import { existsSync as existsSync42 } from "node:fs";
230862
+ import { dirname as dirname29, join as join57 } from "node:path";
230116
230863
  function getAttachedRepositoriesCache() {
230117
230864
  const global2 = globalThis;
230118
230865
  if (!global2[ATTACHED_REPOSITORIES_CACHE_KEY]) {
@@ -230187,7 +230934,7 @@ async function resolveSharedMemorySkillsContext(options) {
230187
230934
  for (const repository of repositories.sort((a2, b3) => a2.name.localeCompare(b3.name) || a2.id.localeCompare(b3.id))) {
230188
230935
  try {
230189
230936
  const repositoryName = validateAgentRepositoryName2(repository.name);
230190
- skillsDirs.push(join56(getRepositoryMountDir2(agentId, repositoryName), "skills"));
230937
+ skillsDirs.push(join57(getRepositoryMountDir2(agentId, repositoryName), "skills"));
230191
230938
  } catch (error5) {
230192
230939
  errors6.push({
230193
230940
  path: `shared-memory:${repository.name}`,
@@ -230201,10 +230948,10 @@ async function discoverSharedMemorySkills(skillsDirs) {
230201
230948
  const skillsById = new Map;
230202
230949
  const errors6 = [];
230203
230950
  for (const dir of skillsDirs) {
230204
- const repositoryMount = dirname27(dir);
230951
+ const repositoryMount = dirname29(dir);
230205
230952
  if (isCheckoutPending(repositoryMount))
230206
230953
  continue;
230207
- if (!existsSync41(repositoryMount)) {
230954
+ if (!existsSync42(repositoryMount)) {
230208
230955
  errors6.push({
230209
230956
  path: repositoryMount,
230210
230957
  message: "Attached repository is not mounted locally"
@@ -230250,8 +230997,8 @@ __export(exports_client_skills, {
230250
230997
  buildClientSkillsUpdateReminder: () => buildClientSkillsUpdateReminder,
230251
230998
  buildClientSkillsPayload: () => buildClientSkillsPayload
230252
230999
  });
230253
- import { existsSync as existsSync42 } from "node:fs";
230254
- import { join as join57, resolve as resolve28 } from "node:path";
231000
+ import { existsSync as existsSync43 } from "node:fs";
231001
+ import { join as join58, resolve as resolve28 } from "node:path";
230255
231002
  function getCache2() {
230256
231003
  const global2 = globalThis;
230257
231004
  if (!global2[CLIENT_SKILLS_CACHE_KEY]) {
@@ -230379,12 +231126,12 @@ function buildClientSkillsUpdateReminder(previous, current) {
230379
231126
  function getMemorySkillsDirs(agentId) {
230380
231127
  const dirs = new Set;
230381
231128
  const scopedMemoryDir = resolveScopedMemoryDir({ agentId });
230382
- if (scopedMemoryDir && scopedMemoryDir.trim().length > 0 && existsSync42(scopedMemoryDir)) {
230383
- dirs.add(join57(scopedMemoryDir.trim(), "skills"));
231129
+ if (scopedMemoryDir && scopedMemoryDir.trim().length > 0 && existsSync43(scopedMemoryDir)) {
231130
+ dirs.add(join58(scopedMemoryDir.trim(), "skills"));
230384
231131
  } else {
230385
231132
  const fallbackMemoryDir = (process.env.LETTA_MEMORY_DIR || process.env.MEMORY_DIR || "").trim();
230386
231133
  if (fallbackMemoryDir) {
230387
- dirs.add(join57(fallbackMemoryDir, "skills"));
231134
+ dirs.add(join58(fallbackMemoryDir, "skills"));
230388
231135
  }
230389
231136
  }
230390
231137
  return Array.from(dirs);
@@ -230426,8 +231173,8 @@ function toClientSkill(skill) {
230426
231173
  function resolveSkillDiscoveryContext(options) {
230427
231174
  const workingDirectory = options.workingDirectory ?? process.cwd();
230428
231175
  const configuredSkillsDirectory = options.skillsDirectory ?? getSkillsDirectory();
230429
- const legacySkillsDirectory = join57(workingDirectory, SKILLS_DIR);
230430
- const primaryProjectSkillsDirectory = join57(workingDirectory, PROJECT_SKILLS_DIR);
231176
+ const legacySkillsDirectory = join58(workingDirectory, SKILLS_DIR);
231177
+ const primaryProjectSkillsDirectory = join58(workingDirectory, PROJECT_SKILLS_DIR);
230431
231178
  const skillSources = options.skillSources ?? getSkillSources();
230432
231179
  const bundledSkills = skillSources.includes("bundled") ? undefined : options.bundledSkills ?? getBundledSkillAllowlist();
230433
231180
  return {
@@ -230894,6 +231641,13 @@ async function sendMessageStreamWithBackend(backend3, conversationId, messages,
230894
231641
  if (actingUserId) {
230895
231642
  extraHeaders[ACTING_USER_ID_HEADER] = actingUserId;
230896
231643
  }
231644
+ const originatorSuperRunId = executionRuntimeContext ? executionRuntimeContext.mcpOriginatorSuperRunId : getRuntimeContext()?.mcpOriginatorSuperRunId;
231645
+ const originatorToken = getMcpOriginatorToken(originatorSuperRunId);
231646
+ if (originatorToken && originatorSuperRunId) {
231647
+ extraHeaders[MCP_ORIGINATOR_TOKEN_HEADER] = originatorToken;
231648
+ extraHeaders[MCP_ORIGINATOR_ISOLATION_HEADER] = "1";
231649
+ extraHeaders[MCP_ORIGINATOR_SUPER_RUN_HEADER] = originatorSuperRunId;
231650
+ }
230897
231651
  const messageSummary = normalizedMessages.map((item) => {
230898
231652
  if (item.type === "approval") {
230899
231653
  return `approval:${item.approvals?.length ?? 0}`;
@@ -230963,9 +231717,10 @@ async function sendMessageStreamWithBackend(backend3, conversationId, messages,
230963
231717
  });
230964
231718
  return stream11;
230965
231719
  }
230966
- var streamRequestStartTimes, streamToolContextIds, RESPONSE_STATE_HEADER = "X-Letta-Response-State", RESPONSE_STATE_CACHE_SCOPE = "approval_boundary", CLOUD_API_SHUTDOWN_MAX_RETRIES = 3, CLOUD_API_SHUTDOWN_DEFAULT_RETRY_DELAY_MS = 1000, responseStateIdsByScope, sentClientSkillsByBackend, streamRequestContexts;
231720
+ var streamRequestStartTimes, streamToolContextIds, RESPONSE_STATE_HEADER = "X-Letta-Response-State", RESPONSE_STATE_CACHE_SCOPE = "approval_boundary", MCP_ORIGINATOR_TOKEN_HEADER = "x-letta-mcp-originator-token", MCP_ORIGINATOR_ISOLATION_HEADER = "x-letta-mcp-originator-isolation", MCP_ORIGINATOR_SUPER_RUN_HEADER = "x-letta-mcp-originator-super-run-id", CLOUD_API_SHUTDOWN_MAX_RETRIES = 3, CLOUD_API_SHUTDOWN_DEFAULT_RETRY_DELAY_MS = 1000, responseStateIdsByScope, sentClientSkillsByBackend, streamRequestContexts;
230967
231721
  var init_message = __esm(async () => {
230968
231722
  init_error();
231723
+ init_mcp_originator_tokens();
230969
231724
  init_backend2();
230970
231725
  init_disk_space();
230971
231726
  init_runtime_context();
@@ -232382,673 +233137,6 @@ var init_manager2 = __esm(async () => {
232382
233137
  MOD_SECRET_NAME_PATTERN = /^[A-Z_][A-Z0-9_]*$/;
232383
233138
  });
232384
233139
 
232385
- // src/agent/mcp-originator-authority-file.ts
232386
- import { createHash as createHash9, randomUUID as randomUUID32 } from "node:crypto";
232387
- import {
232388
- closeSync as closeSync7,
232389
- existsSync as existsSync43,
232390
- fsyncSync as fsyncSync3,
232391
- mkdirSync as mkdirSync32,
232392
- openSync as openSync7,
232393
- readFileSync as readFileSync35,
232394
- renameSync as renameSync10,
232395
- unlinkSync as unlinkSync10,
232396
- writeFileSync as writeFileSync26
232397
- } from "node:fs";
232398
- import { dirname as dirname28, join as join58 } from "node:path";
232399
- function isValidGeneration(generation4) {
232400
- return typeof generation4 === "number" && Number.isSafeInteger(generation4) && generation4 >= 0;
232401
- }
232402
- function isValidUpdatedAtMs(updatedAtMs, nowMs) {
232403
- return typeof updatedAtMs === "number" && Number.isSafeInteger(updatedAtMs) && updatedAtMs >= 0 && updatedAtMs <= nowMs + UPDATED_AT_FUTURE_SKEW_MS;
232404
- }
232405
- function authorityPersistentPath() {
232406
- if (persistencePathOverride !== undefined)
232407
- return persistencePathOverride;
232408
- if (false)
232409
- ;
232410
- let serverUrl;
232411
- try {
232412
- serverUrl = getServerUrl();
232413
- } catch {
232414
- serverUrl = process.env.LETTA_BASE_URL ?? "uninitialized";
232415
- }
232416
- return authorityPersistentPathForServer(serverUrl);
232417
- }
232418
- function authorityPersistentPathForServer(serverUrl) {
232419
- const namespace = createHash9("sha256").update(serverUrl).digest("hex").slice(0, 24);
232420
- return join58(resolveGlobalConfigDir(), "state", namespace, "mcp-originator-authority-v1.json");
232421
- }
232422
- function mergeRetirementIntents(a2, b3) {
232423
- if (a2 === undefined)
232424
- return b3;
232425
- if (b3 === undefined)
232426
- return a2;
232427
- return STATE_RANK[a2] >= STATE_RANK[b3] ? a2 : b3;
232428
- }
232429
- function mergeRecords(a2, b3) {
232430
- if (!b3)
232431
- return a2;
232432
- const floor2 = Math.max(a2.floor ?? -1, b3.floor ?? -1);
232433
- const state2 = STATE_RANK[a2.state] >= STATE_RANK[b3.state] ? a2.state : b3.state;
232434
- const retiringTo = state2 === "live" ? mergeRetirementIntents(a2.retiringTo, b3.retiringTo) : undefined;
232435
- return {
232436
- ...floor2 >= 0 ? { floor: floor2 } : {},
232437
- state: state2,
232438
- ...retiringTo !== undefined ? { retiringTo } : {},
232439
- updatedAtMs: Math.max(a2.updatedAtMs, b3.updatedAtMs)
232440
- };
232441
- }
232442
- function readAuthorityRecords(path18) {
232443
- const records = new Map;
232444
- if (!existsSync43(path18))
232445
- return { records, degraded: false };
232446
- try {
232447
- const parsed = JSON.parse(readFileSync35(path18, "utf8"));
232448
- if (typeof parsed !== "object" || parsed === null || parsed.version !== 1 || typeof parsed.records !== "object" || parsed.records === null || Array.isArray(parsed.records))
232449
- return { records, degraded: true };
232450
- const nowMs = Date.now();
232451
- for (const [runId, record6] of Object.entries(parsed.records)) {
232452
- const retiringTo = record6?.retiringTo;
232453
- if (record6 && (record6.state === "live" || record6.state === "headerless" || record6.state === "terminal") && (retiringTo === undefined || retiringTo === "headerless" || retiringTo === "terminal") && isValidUpdatedAtMs(record6.updatedAtMs, nowMs) && (record6.floor === undefined || isValidGeneration(record6.floor))) {
232454
- records.set(runId, {
232455
- ...record6.floor !== undefined ? { floor: record6.floor } : {},
232456
- state: record6.state,
232457
- ...record6.state === "live" && retiringTo !== undefined ? { retiringTo } : {},
232458
- updatedAtMs: record6.updatedAtMs
232459
- });
232460
- } else {
232461
- return { records, degraded: true };
232462
- }
232463
- }
232464
- return { records, degraded: false };
232465
- } catch {
232466
- return { records, degraded: true };
232467
- }
232468
- }
232469
- function writeAuthorityRecords(path18, records) {
232470
- mkdirSync32(dirname28(path18), { recursive: true, mode: 448 });
232471
- const file = {
232472
- version: 1,
232473
- records: Object.fromEntries(records)
232474
- };
232475
- const tmp = `${path18}.${process.pid}.${randomUUID32()}.tmp`;
232476
- try {
232477
- writeFileSync26(tmp, JSON.stringify(file), { mode: 384, flag: "wx" });
232478
- const fd = openSync7(tmp, "r+");
232479
- try {
232480
- fsyncSync3(fd);
232481
- } finally {
232482
- closeSync7(fd);
232483
- }
232484
- renameSync10(tmp, path18);
232485
- fsyncDirectory(dirname28(path18));
232486
- } catch (error5) {
232487
- try {
232488
- unlinkSync10(tmp);
232489
- } catch {}
232490
- throw error5;
232491
- }
232492
- }
232493
- var UPDATED_AT_FUTURE_SKEW_MS, persistencePathOverride, STATE_RANK;
232494
- var init_mcp_originator_authority_file = __esm(() => {
232495
- init_server_url();
232496
- init_settings_path();
232497
- init_durable_file_lock();
232498
- UPDATED_AT_FUTURE_SKEW_MS = 24 * 60 * 60 * 1000;
232499
- STATE_RANK = {
232500
- live: 0,
232501
- headerless: 1,
232502
- terminal: 2
232503
- };
232504
- });
232505
-
232506
- // src/agent/mcp-originator-authority.ts
232507
- import { mkdirSync as mkdirSync33 } from "node:fs";
232508
- import { dirname as dirname29 } from "node:path";
232509
- function pruneExpired(nowMs) {
232510
- let pruned = false;
232511
- for (const [runId, record6] of recordsBySuperRunId) {
232512
- if (nowMs - record6.updatedAtMs > recordTtlMs) {
232513
- recordsBySuperRunId.delete(runId);
232514
- pruned = true;
232515
- }
232516
- }
232517
- return pruned;
232518
- }
232519
- function authorityTransaction(mutate) {
232520
- const path18 = authorityPersistentPath();
232521
- if (!path18) {
232522
- return mutate(recordsBySuperRunId, { degraded: false }).result;
232523
- }
232524
- mkdirSync33(dirname29(path18), { recursive: true, mode: 448 });
232525
- const release = acquireDurableFileLock(path18, { waitMs: 2000 });
232526
- try {
232527
- const { records: disk, degraded } = readAuthorityRecords(path18);
232528
- if (!degraded) {
232529
- const memory3 = new Map(recordsBySuperRunId);
232530
- recordsBySuperRunId.clear();
232531
- for (const [runId, record6] of disk) {
232532
- recordsBySuperRunId.set(runId, mergeRecords(record6, memory3.get(runId)) ?? record6);
232533
- }
232534
- for (const [runId, record6] of memory3) {
232535
- if (!disk.has(runId))
232536
- recordsBySuperRunId.set(runId, record6);
232537
- }
232538
- pruneExpired(Date.now());
232539
- resumeDurableRetirementIntents();
232540
- }
232541
- const { result: result2, changed } = mutate(recordsBySuperRunId, { degraded });
232542
- if (changed && !degraded)
232543
- writeAuthorityRecords(path18, recordsBySuperRunId);
232544
- return result2;
232545
- } finally {
232546
- release();
232547
- }
232548
- }
232549
- function mutateDurableFirst(label, mutate) {
232550
- if (!authorityPersistentPath()) {
232551
- mutate(recordsBySuperRunId);
232552
- return true;
232553
- }
232554
- for (let attempt2 = 1;attempt2 <= 3; attempt2 += 1) {
232555
- try {
232556
- const persisted = authorityTransaction((records, ctx) => {
232557
- if (ctx.degraded)
232558
- return { result: false, changed: false };
232559
- mutate(records);
232560
- return { result: true, changed: true };
232561
- });
232562
- if (persisted)
232563
- return true;
232564
- console.error(`[mcp-originator-authority] durable file is degraded for ${label}; the boundary holds in this process but is NOT durable across restart`);
232565
- mutate(recordsBySuperRunId);
232566
- return false;
232567
- } catch (error5) {
232568
- console.error(`[mcp-originator-authority] durable write failed for ${label} (attempt ${attempt2}/3)`, error5);
232569
- }
232570
- }
232571
- console.error(`[mcp-originator-authority] durable write failed for ${label} after retries; the boundary still holds in this process but is NOT durable across restart`);
232572
- mutate(recordsBySuperRunId);
232573
- return false;
232574
- }
232575
- function scheduleRetirementRetry() {
232576
- if (pendingRetirements.size === 0)
232577
- return;
232578
- if (retirementRetryTimer !== undefined)
232579
- return;
232580
- if (false)
232581
- ;
232582
- retirementRetryTimer = setTimeout(() => {
232583
- retirementRetryTimer = undefined;
232584
- retryPendingMcpOriginatorRetirements();
232585
- }, retirementRetryIntervalMs);
232586
- retirementRetryTimer.unref?.();
232587
- }
232588
- function retryPendingMcpOriginatorRetirements() {
232589
- const nowMs = Date.now();
232590
- let processed = 0;
232591
- for (const [runId, pending2] of pendingRetirements) {
232592
- if (nowMs - pending2.createdAtMs > recordTtlMs) {
232593
- console.error(`[mcp-originator-authority] pending ${pending2.state} retirement for ${runId} outlived the ${Math.round(recordTtlMs / 60000)}-minute record TTL; dropping the retry (any token it fenced is dead at the server-side ceiling)`);
232594
- pendingRetirements.delete(runId);
232595
- continue;
232596
- }
232597
- if (processed >= MAX_RETIREMENT_RETRIES_PER_TICK) {
232598
- continue;
232599
- }
232600
- processed += 1;
232601
- const durable = mutateDurableFirst(`retirement retry (${pending2.state}) for ${runId}`, (records) => touchRecords(records, runId, pending2.generation, pending2.state, {
232602
- preserveUpdatedAt: true
232603
- }));
232604
- if (durable)
232605
- pendingRetirements.delete(runId);
232606
- }
232607
- if (pendingRetirements.size > 0)
232608
- scheduleRetirementRetry();
232609
- }
232610
- function persistRetirementIntent(runId, state2, generation4) {
232611
- const path18 = authorityPersistentPath();
232612
- if (!path18)
232613
- return;
232614
- try {
232615
- const release = acquireDurableFileLock(path18, { waitMs: 2000 });
232616
- try {
232617
- const { records: disk, degraded } = readAuthorityRecords(path18);
232618
- if (degraded) {
232619
- console.error(`[mcp-originator-authority] durable file is degraded for the retirement intent (${state2}) for ${runId}; the boundary holds in this process only`);
232620
- return;
232621
- }
232622
- const existing = disk.get(runId);
232623
- if (existing && existing.state !== "live")
232624
- return;
232625
- const floor2 = generation4 !== undefined && isValidGeneration(generation4) ? Math.max(existing?.floor ?? -1, generation4) : existing?.floor;
232626
- disk.set(runId, {
232627
- ...floor2 !== undefined && floor2 >= 0 ? { floor: floor2 } : {},
232628
- state: "live",
232629
- retiringTo: mergeRetirementIntents(existing?.retiringTo, state2) ?? state2,
232630
- updatedAtMs: existing?.updatedAtMs ?? Date.now()
232631
- });
232632
- writeAuthorityRecords(path18, disk);
232633
- } finally {
232634
- release();
232635
- }
232636
- } catch (error5) {
232637
- console.error(`[mcp-originator-authority] durable retirement intent (${state2}) write failed for ${runId}; peers cannot see the boundary until a retry lands the mark`, error5);
232638
- }
232639
- }
232640
- function resumeDurableRetirementIntents() {
232641
- for (const [runId, record6] of recordsBySuperRunId) {
232642
- if (record6.state !== "live" || record6.retiringTo === undefined)
232643
- continue;
232644
- const existing = pendingRetirements.get(runId);
232645
- if (existing && existing.createdAtMs <= record6.updatedAtMs)
232646
- continue;
232647
- pendingRetirements.set(runId, {
232648
- state: record6.retiringTo,
232649
- ...record6.floor !== undefined ? { generation: record6.floor } : {},
232650
- createdAtMs: Math.min(existing?.createdAtMs ?? record6.updatedAtMs, record6.updatedAtMs)
232651
- });
232652
- }
232653
- scheduleRetirementRetry();
232654
- }
232655
- function registerPendingRetirement(runId, state2, generation4, durable) {
232656
- if (durable) {
232657
- const pending2 = pendingRetirements.get(runId);
232658
- if (pending2 && STATE_RANK[pending2.state] <= STATE_RANK[state2]) {
232659
- pendingRetirements.delete(runId);
232660
- }
232661
- return;
232662
- }
232663
- persistRetirementIntent(runId, state2, generation4);
232664
- const existing = pendingRetirements.get(runId);
232665
- const merged = {
232666
- state: existing && STATE_RANK[existing.state] > STATE_RANK[state2] ? existing.state : state2,
232667
- createdAtMs: existing?.createdAtMs ?? Date.now()
232668
- };
232669
- const mergedGeneration = generation4 ?? existing?.generation;
232670
- if (mergedGeneration !== undefined)
232671
- merged.generation = mergedGeneration;
232672
- pendingRetirements.set(runId, merged);
232673
- scheduleRetirementRetry();
232674
- }
232675
- function touchRecords(records, runId, generation4, state2, options) {
232676
- const existing = records.get(runId);
232677
- const usableGeneration = generation4 !== undefined && isValidGeneration(generation4) ? generation4 : undefined;
232678
- const floor2 = usableGeneration === undefined ? existing?.floor : Math.max(existing?.floor ?? -1, usableGeneration);
232679
- const nextState = state2 === undefined ? existing?.state ?? "live" : existing?.state !== undefined && STATE_RANK[existing.state] > STATE_RANK[state2] ? existing.state : state2;
232680
- records.set(runId, {
232681
- ...floor2 !== undefined ? { floor: floor2 } : {},
232682
- state: nextState,
232683
- ...nextState === "live" && existing?.retiringTo !== undefined ? { retiringTo: existing.retiringTo } : {},
232684
- updatedAtMs: options?.preserveUpdatedAt === true && existing !== undefined ? existing.updatedAtMs : Date.now()
232685
- });
232686
- }
232687
- function admitMcpOriginatorDelivery(runId, generation4) {
232688
- if (generation4 !== undefined && !isValidGeneration(generation4)) {
232689
- console.error(`[mcp-originator-authority] malformed generation for ${runId}; denying admission (fail-closed)`);
232690
- return { admitted: false, permanent: true };
232691
- }
232692
- if (!authorityPersistentPath()) {
232693
- const record6 = recordsBySuperRunId.get(runId);
232694
- if (record6) {
232695
- if (record6.state !== "live" || record6.retiringTo !== undefined)
232696
- return { admitted: false, permanent: true };
232697
- if (record6.floor !== undefined && (generation4 === undefined || generation4 < record6.floor))
232698
- return { admitted: false, permanent: true };
232699
- }
232700
- touchRecords(recordsBySuperRunId, runId, generation4);
232701
- return { admitted: true };
232702
- }
232703
- try {
232704
- return authorityTransaction((records, ctx) => {
232705
- if (ctx.degraded) {
232706
- console.error(`[mcp-originator-authority] durable file is degraded; denying admission for ${runId} (fail-closed, retryable)`);
232707
- return {
232708
- result: { admitted: false, permanent: false },
232709
- changed: false
232710
- };
232711
- }
232712
- const record6 = records.get(runId);
232713
- if (record6) {
232714
- if (record6.state !== "live" || record6.retiringTo !== undefined)
232715
- return {
232716
- result: { admitted: false, permanent: true },
232717
- changed: false
232718
- };
232719
- if (record6.floor !== undefined && (generation4 === undefined || generation4 < record6.floor))
232720
- return {
232721
- result: { admitted: false, permanent: true },
232722
- changed: false
232723
- };
232724
- }
232725
- touchRecords(records, runId, generation4);
232726
- return { result: { admitted: true }, changed: true };
232727
- });
232728
- } catch (error5) {
232729
- console.error(`[mcp-originator-authority] admission transaction failed for ${runId}; denying the delivery (fail-closed, retryable)`, error5);
232730
- return { admitted: false, permanent: false };
232731
- }
232732
- }
232733
- function mcpOriginatorAuthorityPermitsUse(runId, generation4) {
232734
- if (generation4 !== undefined && !isValidGeneration(generation4)) {
232735
- console.error(`[mcp-originator-authority] malformed generation for ${runId}; withdrawing the token (fail-closed)`);
232736
- return false;
232737
- }
232738
- try {
232739
- return authorityTransaction((records, ctx) => {
232740
- if (ctx.degraded)
232741
- return { result: false, changed: false };
232742
- const record6 = records.get(runId);
232743
- if (!record6)
232744
- return { result: true, changed: false };
232745
- if (record6.state !== "live" || record6.retiringTo !== undefined)
232746
- return { result: false, changed: false };
232747
- if (record6.floor !== undefined && generation4 !== undefined && generation4 < record6.floor)
232748
- return { result: false, changed: false };
232749
- return { result: true, changed: false };
232750
- });
232751
- } catch (error5) {
232752
- console.error(`[mcp-originator-authority] use check failed for ${runId}; withdrawing the token (fail-closed)`, error5);
232753
- return false;
232754
- }
232755
- }
232756
- function markMcpOriginatorHeaderless(runId, deletedGeneration) {
232757
- const durable = mutateDurableFirst(`headerless mark for ${runId}`, (records) => touchRecords(records, runId, deletedGeneration, "headerless"));
232758
- registerPendingRetirement(runId, "headerless", deletedGeneration, durable);
232759
- return durable;
232760
- }
232761
- function markMcpOriginatorTerminal(runId, deletedGeneration) {
232762
- const durable = mutateDurableFirst(`terminal mark for ${runId}`, (records) => touchRecords(records, runId, deletedGeneration, "terminal"));
232763
- registerPendingRetirement(runId, "terminal", deletedGeneration, durable);
232764
- return durable;
232765
- }
232766
- var AUTHORITY_RECORD_TTL_MS, recordTtlMs, recordsBySuperRunId, pendingRetirements, retirementRetryTimer, retirementRetryIntervalMs = 30000, MAX_RETIREMENT_RETRIES_PER_TICK = 25;
232767
- var init_mcp_originator_authority = __esm(() => {
232768
- init_durable_file_lock();
232769
- init_mcp_originator_authority_file();
232770
- AUTHORITY_RECORD_TTL_MS = 2 * 60 * 60 * 1000;
232771
- recordTtlMs = AUTHORITY_RECORD_TTL_MS;
232772
- recordsBySuperRunId = new Map;
232773
- pendingRetirements = new Map;
232774
- });
232775
-
232776
- // src/agent/mcp-originator-keepalive.ts
232777
- async function runKeepaliveTick(superRunId) {
232778
- const entry = keepalives.get(superRunId);
232779
- if (!entry || entry.ticking)
232780
- return;
232781
- const token2 = entry.hooks?.getToken();
232782
- if (!token2) {
232783
- stopMcpOriginatorKeepalive(superRunId);
232784
- return;
232785
- }
232786
- entry.ticking = true;
232787
- try {
232788
- const result2 = await verifyWithHardBound(token2, verifyTimeoutMs);
232789
- if (entry.hooks?.getToken() !== token2) {
232790
- return;
232791
- }
232792
- entry.consecutiveFailures = 0;
232793
- if (!result2.valid) {
232794
- console.warn(`[mcp-originator-keepalive] server denied the originator token for super run ${superRunId}; withdrawing it (turn continues unattributed)`);
232795
- entry.hooks?.withdraw();
232796
- stopMcpOriginatorKeepalive(superRunId);
232797
- return;
232798
- }
232799
- } catch (error5) {
232800
- if (entry.hooks?.getToken() !== token2) {
232801
- return;
232802
- }
232803
- entry.consecutiveFailures += 1;
232804
- if (entry.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {
232805
- console.error(`[mcp-originator-keepalive] renewal failed ${entry.consecutiveFailures} times for super run ${superRunId}; stopping renewal (the server-side TTL now bounds the token):`, error5 instanceof Error ? error5.message : error5);
232806
- stopMcpOriginatorKeepalive(superRunId);
232807
- return;
232808
- }
232809
- } finally {
232810
- entry.ticking = false;
232811
- if (schedulingEnabled && keepalives.get(superRunId) === entry) {
232812
- const delay3 = entry.verifyAsap ? 0 : nextDelayMs(entry.consecutiveFailures);
232813
- entry.verifyAsap = false;
232814
- entry.timer = setTimeout(() => {
232815
- runKeepaliveTick(superRunId);
232816
- }, delay3);
232817
- entry.timer?.unref();
232818
- }
232819
- }
232820
- }
232821
- function nextDelayMs(consecutiveFailures) {
232822
- if (consecutiveFailures <= 0)
232823
- return intervalMs;
232824
- const lastDelay = FAILURE_RETRY_DELAYS_MS[FAILURE_RETRY_DELAYS_MS.length - 1];
232825
- return FAILURE_RETRY_DELAYS_MS[Math.min(consecutiveFailures, FAILURE_RETRY_DELAYS_MS.length) - 1] ?? lastDelay ?? intervalMs;
232826
- }
232827
- function verifyWithHardBound(token2, budgetMs) {
232828
- return new Promise((resolve30, reject2) => {
232829
- let settled = false;
232830
- const timer = setTimeout(() => {
232831
- if (settled)
232832
- return;
232833
- settled = true;
232834
- reject2(new Error(`[mcp-originator-keepalive] verify exceeded the ${budgetMs}ms hard bound`));
232835
- }, budgetMs);
232836
- verifyImpl(token2, AbortSignal.timeout(budgetMs)).then((result2) => {
232837
- if (settled)
232838
- return;
232839
- settled = true;
232840
- clearTimeout(timer);
232841
- resolve30(result2);
232842
- }, (error5) => {
232843
- if (settled)
232844
- return;
232845
- settled = true;
232846
- clearTimeout(timer);
232847
- reject2(error5 instanceof Error ? error5 : new Error(String(error5)));
232848
- });
232849
- });
232850
- }
232851
- function startMcpOriginatorKeepalive(superRunId, hooks) {
232852
- const existing = keepalives.get(superRunId);
232853
- if (existing) {
232854
- existing.hooks = hooks;
232855
- existing.consecutiveFailures = 0;
232856
- existing.verifyAsap = true;
232857
- if (schedulingEnabled && !existing.ticking) {
232858
- clearTimeout(existing.timer);
232859
- existing.verifyAsap = false;
232860
- existing.timer = setTimeout(() => {
232861
- runKeepaliveTick(superRunId);
232862
- }, 0);
232863
- existing.timer?.unref();
232864
- }
232865
- return;
232866
- }
232867
- const entry = {
232868
- timer: schedulingEnabled ? setTimeout(() => {
232869
- runKeepaliveTick(superRunId);
232870
- }, 0) : undefined,
232871
- consecutiveFailures: 0,
232872
- ticking: false,
232873
- verifyAsap: false,
232874
- hooks
232875
- };
232876
- entry.timer?.unref();
232877
- keepalives.set(superRunId, entry);
232878
- }
232879
- function stopMcpOriginatorKeepalive(superRunId) {
232880
- const entry = keepalives.get(superRunId);
232881
- if (!entry)
232882
- return;
232883
- clearTimeout(entry.timer);
232884
- keepalives.delete(superRunId);
232885
- }
232886
- function stopAllMcpOriginatorKeepalives() {
232887
- for (const runId of [...keepalives.keys()]) {
232888
- stopMcpOriginatorKeepalive(runId);
232889
- }
232890
- }
232891
- var DEFAULT_KEEPALIVE_INTERVAL_MS = 120000, MAX_CONSECUTIVE_FAILURES = 3, FAILURE_RETRY_DELAYS_MS, VERIFY_TIMEOUT_MS = 30000, defaultVerify = async (token2, signal) => apiRequest("POST", "/v1/mcp-originator-tokens/verify", { token: token2 }, { signal }), verifyImpl, intervalMs, verifyTimeoutMs, keepalives, schedulingEnabled = true;
232892
- var init_mcp_originator_keepalive = __esm(() => {
232893
- init_request();
232894
- FAILURE_RETRY_DELAYS_MS = [15000, 30000];
232895
- verifyImpl = defaultVerify;
232896
- intervalMs = DEFAULT_KEEPALIVE_INTERVAL_MS;
232897
- verifyTimeoutMs = VERIFY_TIMEOUT_MS;
232898
- keepalives = new Map;
232899
- });
232900
-
232901
- // src/agent/mcp-originator-tokens.ts
232902
- function getMcpOriginatorToken(superRunId) {
232903
- if (!superRunId)
232904
- return;
232905
- const entry = entriesBySuperRunId.get(superRunId);
232906
- if (!entry || entry.token === null)
232907
- return;
232908
- if (!mcpOriginatorAuthorityPermitsUse(superRunId, entry.generation)) {
232909
- deleteMcpOriginatorToken(superRunId);
232910
- return;
232911
- }
232912
- return entry.token;
232913
- }
232914
- function deleteMcpOriginatorToken(superRunId) {
232915
- entriesBySuperRunId.delete(superRunId);
232916
- stopMcpOriginatorKeepalive(superRunId);
232917
- }
232918
- function keepaliveHooks(superRunId) {
232919
- return {
232920
- getToken: () => getMcpOriginatorToken(superRunId),
232921
- withdraw: () => deleteMcpOriginatorToken(superRunId)
232922
- };
232923
- }
232924
- function clearMcpOriginatorTokens() {
232925
- entriesBySuperRunId.clear();
232926
- stopAllMcpOriginatorKeepalives();
232927
- }
232928
- function readMcpOriginatorDelivery(payload) {
232929
- const wire = typeof payload === "object" && payload !== null ? payload : {};
232930
- const superRunId = typeof wire.super_run_id === "string" && wire.super_run_id.length > 0 ? wire.super_run_id : undefined;
232931
- const token2 = typeof wire.mcp_originator_token === "string" && wire.mcp_originator_token.length > 0 ? wire.mcp_originator_token : undefined;
232932
- const generation4 = typeof wire.mcp_originator_generation === "number" && Number.isInteger(wire.mcp_originator_generation) && wire.mcp_originator_generation >= 0 && Number.isSafeInteger(wire.mcp_originator_generation) ? wire.mcp_originator_generation : undefined;
232933
- return {
232934
- ...superRunId ? { superRunId } : {},
232935
- ...token2 ? { token: token2 } : {},
232936
- ...generation4 !== undefined ? { generation: generation4 } : {},
232937
- ...wire.mcp_originator_generation !== undefined && generation4 === undefined ? { malformedGeneration: true } : {}
232938
- };
232939
- }
232940
- function deliveryIsAtLeastAsNew(existing, incomingGeneration) {
232941
- if (existing.generation === undefined)
232942
- return true;
232943
- if (incomingGeneration === undefined)
232944
- return false;
232945
- return incomingGeneration >= existing.generation;
232946
- }
232947
- function denyMalformedGeneration(frame, delivery, context3) {
232948
- const rawGeneration = frame?.mcp_originator_generation;
232949
- console.error(`[MCP originator] run ${delivery.superRunId}: ${context3}denying delivery with malformed generation (type=${typeof rawGeneration}${typeof rawGeneration === "string" ? ` length=${rawGeneration.length}` : ""})`);
232950
- return "denied_permanent";
232951
- }
232952
- function installPreGatedMcpOriginatorDelivery(delivery, options) {
232953
- if (!delivery.superRunId || delivery.malformedGeneration)
232954
- return;
232955
- const existing = entriesBySuperRunId.get(delivery.superRunId);
232956
- if (delivery.token) {
232957
- if (existing) {
232958
- if (!deliveryIsAtLeastAsNew(existing, delivery.generation))
232959
- return;
232960
- } else if (options?.allowCreate === false && options?.mayRecreateOwner?.() !== true) {
232961
- return;
232962
- }
232963
- entriesBySuperRunId.set(delivery.superRunId, {
232964
- token: delivery.token,
232965
- ...delivery.generation !== undefined ? { generation: delivery.generation } : existing?.generation !== undefined ? { generation: existing.generation } : {}
232966
- });
232967
- startMcpOriginatorKeepalive(delivery.superRunId, keepaliveHooks(delivery.superRunId));
232968
- return;
232969
- }
232970
- if (!existing)
232971
- return;
232972
- if (!deliveryIsAtLeastAsNew(existing, delivery.generation))
232973
- return;
232974
- entriesBySuperRunId.set(delivery.superRunId, {
232975
- token: null,
232976
- ...delivery.generation !== undefined ? { generation: delivery.generation } : existing.generation !== undefined ? { generation: existing.generation } : {}
232977
- });
232978
- stopMcpOriginatorKeepalive(delivery.superRunId);
232979
- }
232980
- function recordMcpOriginatorDelivery(frame, options) {
232981
- const delivery = readMcpOriginatorDelivery(frame);
232982
- if (!delivery.superRunId)
232983
- return "none";
232984
- if (delivery.malformedGeneration) {
232985
- return denyMalformedGeneration(frame, delivery, "");
232986
- }
232987
- const admission = admitMcpOriginatorDelivery(delivery.superRunId, delivery.generation);
232988
- if (!admission.admitted) {
232989
- return admission.permanent ? "denied_permanent" : "denied_retryable";
232990
- }
232991
- installPreGatedMcpOriginatorDelivery(delivery, options);
232992
- return "admitted";
232993
- }
232994
- function gateMcpOriginatorDeliveryAdmission(frame) {
232995
- const delivery = readMcpOriginatorDelivery(frame);
232996
- if (!delivery.superRunId)
232997
- return { verdict: "none" };
232998
- if (delivery.malformedGeneration) {
232999
- return {
233000
- verdict: denyMalformedGeneration(frame, delivery, "pre-commit gate ")
233001
- };
233002
- }
233003
- const admission = admitMcpOriginatorDelivery(delivery.superRunId, delivery.generation);
233004
- if (!admission.admitted) {
233005
- return {
233006
- verdict: admission.permanent ? "denied_permanent" : "denied_retryable"
233007
- };
233008
- }
233009
- return { verdict: "admitted", delivery };
233010
- }
233011
- function retireMcpOriginatorTokensOnOriginSwap(turnSuperRunId, queuedSuperRunId) {
233012
- if (queuedSuperRunId === turnSuperRunId)
233013
- return;
233014
- for (const runId of [turnSuperRunId, queuedSuperRunId]) {
233015
- if (!runId)
233016
- continue;
233017
- const generation4 = entriesBySuperRunId.get(runId)?.generation;
233018
- if (markMcpOriginatorHeaderless(runId, generation4)) {
233019
- deleteMcpOriginatorToken(runId);
233020
- } else {
233021
- console.error(`[mcp-originator-tokens] headerless mark for ${runId} is NOT durable; keeping the volatile entry (unusable in this process) so restart cannot resurrect authority`);
233022
- }
233023
- }
233024
- }
233025
- function retireMcpOriginatorTokenOnTerminal(superRunId) {
233026
- if (!superRunId)
233027
- return;
233028
- const generation4 = entriesBySuperRunId.get(superRunId)?.generation;
233029
- if (markMcpOriginatorTerminal(superRunId, generation4)) {
233030
- deleteMcpOriginatorToken(superRunId);
233031
- } else {
233032
- console.error(`[mcp-originator-tokens] terminal mark for ${superRunId} is NOT durable; keeping the volatile entry (unusable in this process) so restart cannot resurrect authority`);
233033
- }
233034
- }
233035
- function retireMcpOriginatorTokenOnMixedMerge(superRunId) {
233036
- if (!superRunId)
233037
- return;
233038
- const generation4 = entriesBySuperRunId.get(superRunId)?.generation;
233039
- if (markMcpOriginatorHeaderless(superRunId, generation4)) {
233040
- deleteMcpOriginatorToken(superRunId);
233041
- } else {
233042
- console.error(`[mcp-originator-tokens] mixed-merge headerless mark for ${superRunId} is NOT durable; keeping the volatile entry (unusable in this process) so restart cannot resurrect authority`);
233043
- }
233044
- }
233045
- var entriesBySuperRunId;
233046
- var init_mcp_originator_tokens = __esm(() => {
233047
- init_mcp_originator_authority();
233048
- init_mcp_originator_keepalive();
233049
- entriesBySuperRunId = new Map;
233050
- });
233051
-
233052
233140
  // src/backend/api/unified-mcp.ts
233053
233141
  var exports_unified_mcp = {};
233054
233142
  __export(exports_unified_mcp, {
@@ -233209,14 +233297,14 @@ async function runUnifiedMcpTool(params) {
233209
233297
  body: { args: params.args },
233210
233298
  ...params.originatorToken ? {
233211
233299
  headers: {
233212
- [MCP_ORIGINATOR_TOKEN_HEADER]: params.originatorToken,
233213
- [MCP_ORIGINATOR_ISOLATION_HEADER]: "1"
233300
+ [MCP_ORIGINATOR_TOKEN_HEADER2]: params.originatorToken,
233301
+ [MCP_ORIGINATOR_ISOLATION_HEADER2]: "1"
233214
233302
  }
233215
233303
  } : {}
233216
233304
  }), params.timeoutMs ?? 60000, "Running agent MCP tool");
233217
233305
  return parseRunResult(value);
233218
233306
  }
233219
- var MCP_ORIGINATOR_TOKEN_HEADER = "x-letta-mcp-originator-token", MCP_ORIGINATOR_ISOLATION_HEADER = "x-letta-mcp-originator-isolation";
233307
+ var MCP_ORIGINATOR_TOKEN_HEADER2 = "x-letta-mcp-originator-token", MCP_ORIGINATOR_ISOLATION_HEADER2 = "x-letta-mcp-originator-isolation";
233220
233308
  var init_unified_mcp = () => {};
233221
233309
 
233222
233310
  // src/mcp-runtime.ts
@@ -233328,7 +233416,7 @@ var init_mcp_runtime = __esm(() => {
233328
233416
  });
233329
233417
 
233330
233418
  // src/cli/subcommands/mcp-io.ts
233331
- import { readFile as readFile13 } from "node:fs/promises";
233419
+ import { readFile as readFile14 } from "node:fs/promises";
233332
233420
  function writeMcpOutput(stream11, message) {
233333
233421
  return new Promise((resolve30, reject2) => {
233334
233422
  let settled = false;
@@ -233425,20 +233513,9 @@ async function loadMcpToolArgs(inline, file, deps) {
233425
233513
  return parseJsonObject(inline, "Invalid --args JSON");
233426
233514
  if (!file)
233427
233515
  return {};
233428
- const raw2 = file === "-" ? await (deps.readStdin ?? readStdin)() : await (deps.readFile ?? ((path18) => readFile13(path18, "utf8")))(file);
233516
+ const raw2 = file === "-" ? await (deps.readStdin ?? readStdin)() : await (deps.readFile ?? ((path18) => readFile14(path18, "utf8")))(file);
233429
233517
  return parseJsonObject(raw2, `Invalid arguments in ${file}`);
233430
233518
  }
233431
- function readStdin() {
233432
- return new Promise((resolve30, reject2) => {
233433
- let value = "";
233434
- process.stdin.setEncoding("utf8");
233435
- process.stdin.on("data", (chunk2) => {
233436
- value += chunk2;
233437
- });
233438
- process.stdin.on("end", () => resolve30(value));
233439
- process.stdin.on("error", reject2);
233440
- });
233441
- }
233442
233519
  function parseJsonObject(raw2, label) {
233443
233520
  let parsed;
233444
233521
  try {
@@ -235614,11 +235691,11 @@ var init_worktree_lock = __esm(() => {
235614
235691
  });
235615
235692
 
235616
235693
  // src/tools/impl/enter-worktree-messages.ts
235617
- import { readFile as readFile14 } from "node:fs/promises";
235694
+ import { readFile as readFile15 } from "node:fs/promises";
235618
235695
  import path19 from "node:path";
235619
235696
  async function readProjectInstructions(worktreePath) {
235620
235697
  try {
235621
- const content = (await readFile14(path19.join(worktreePath, "AGENTS.md"), "utf8")).trim();
235698
+ const content = (await readFile15(path19.join(worktreePath, "AGENTS.md"), "utf8")).trim();
235622
235699
  if (!content)
235623
235700
  return null;
235624
235701
  const truncated = truncateByChars(content, LIMITS.READ_OUTPUT_CHARS, "EnterWorktree");
@@ -237904,7 +237981,7 @@ import {
237904
237981
  lstat,
237905
237982
  mkdir as mkdir10,
237906
237983
  readdir as readdir6,
237907
- readFile as readFile15,
237984
+ readFile as readFile16,
237908
237985
  realpath as realpath4,
237909
237986
  rmdir,
237910
237987
  stat as stat8,
@@ -238013,7 +238090,7 @@ async function readProvisionConfig(primaryRoot) {
238013
238090
  include: []
238014
238091
  };
238015
238092
  try {
238016
- const raw2 = await readFile15(path22.join(primaryRoot, ".letta", "settings.json"), "utf8");
238093
+ const raw2 = await readFile16(path22.join(primaryRoot, ".letta", "settings.json"), "utf8");
238017
238094
  const parsed = JSON.parse(raw2);
238018
238095
  const worktree = parsed.worktree;
238019
238096
  if (!worktree) {
@@ -238100,7 +238177,7 @@ async function copyLocalSettingsFile(primaryRoot, worktreePath) {
238100
238177
  }
238101
238178
  async function readWorktreeIncludeEntries(primaryRoot) {
238102
238179
  try {
238103
- const raw2 = await readFile15(path22.join(primaryRoot, ".worktreeinclude"), "utf8");
238180
+ const raw2 = await readFile16(path22.join(primaryRoot, ".worktreeinclude"), "utf8");
238104
238181
  return raw2.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0 && !line.startsWith("#"));
238105
238182
  } catch {
238106
238183
  return [];
@@ -243834,7 +243911,7 @@ async function terminateSubagentProcessTree(childProcess2, forceKillGraceMs) {
243834
243911
  await waitForProcessGroupExit(pid, FORCE_KILL_SETTLE_MS);
243835
243912
  }
243836
243913
  function spawnSubagentProcess(command, args, options) {
243837
- const childProcess2 = spawn10(command, args, {
243914
+ const childProcess2 = getCommandProcessFactory()(command, args, {
243838
243915
  cwd: options.cwd,
243839
243916
  env: options.env,
243840
243917
  detached: process.platform !== "win32"
@@ -243878,7 +243955,9 @@ function spawnManagedWorkloadProcess(command, args, options) {
243878
243955
  return spawnSubagentProcess(managedCommand, managedArgs, options);
243879
243956
  }
243880
243957
  var DEFAULT_FORCE_KILL_GRACE_MS = 2000, FORCE_KILL_SETTLE_MS = 500, PROCESS_EXIT_POLL_MS = 20;
243881
- var init_subagent_process = () => {};
243958
+ var init_subagent_process = __esm(() => {
243959
+ init_package_manager_spawn();
243960
+ });
243882
243961
 
243883
243962
  // src/utils/native-cli-env.ts
243884
243963
  import { homedir as homedir17 } from "node:os";
@@ -244356,7 +244435,6 @@ var init_claude_stream_session = __esm(() => {
244356
244435
  });
244357
244436
 
244358
244437
  // src/tools/impl/codex-app-server.ts
244359
- import { spawn as nodeSpawn } from "node:child_process";
244360
244438
  import { createInterface as createInterface9 } from "node:readline";
244361
244439
  async function listCodexModels(cwd2, env6) {
244362
244440
  const controller = new AbortController;
@@ -244377,6 +244455,11 @@ async function listCodexModels(cwd2, env6) {
244377
244455
  }))
244378
244456
  };
244379
244457
  const client = new CodexAppServerClient(transport3, () => {}, () => {});
244458
+ let startError;
244459
+ running.process.once("error", (error5) => {
244460
+ startError = error5.code === "ENOENT" ? new Error("Required executable 'codex' was not found on PATH") : error5;
244461
+ client.dispose();
244462
+ });
244380
244463
  const timer = setTimeout(() => client.dispose(), 30000);
244381
244464
  try {
244382
244465
  await client.initialize();
@@ -244395,6 +244478,10 @@ async function listCodexModels(cwd2, env6) {
244395
244478
  cursors.add(cursor);
244396
244479
  } while (cursor);
244397
244480
  return models3;
244481
+ } catch (error5) {
244482
+ client.dispose();
244483
+ await running.completion;
244484
+ throw startError ?? error5;
244398
244485
  } finally {
244399
244486
  clearTimeout(timer);
244400
244487
  client.dispose();
@@ -244409,7 +244496,7 @@ function textInput(text2) {
244409
244496
  }
244410
244497
  function spawnTransport(options) {
244411
244498
  const [command = "codex", ...args] = wrapManagedWorkloadLauncher(["codex", "app-server", "--stdio"], { env: options.env });
244412
- const child = nodeSpawn(command, args, {
244499
+ const child = getCommandProcessFactory()(command, args, {
244413
244500
  cwd: options.cwd,
244414
244501
  env: options.env,
244415
244502
  stdio: ["pipe", "pipe", "pipe"],
@@ -244419,7 +244506,7 @@ function spawnTransport(options) {
244419
244506
  stdin: child.stdin,
244420
244507
  stdout: child.stdout,
244421
244508
  stderr: child.stderr,
244422
- kill: () => child.kill(),
244509
+ kill: () => process.platform === "win32" ? void killWindowsProcessTree(child) : child.kill(),
244423
244510
  exited: new Promise((resolve35) => {
244424
244511
  child.once("close", (code2, signal) => resolve35({ code: code2, signal }));
244425
244512
  })
@@ -244499,7 +244586,7 @@ class CodexAppServerClient {
244499
244586
  await this.request("initialize", {
244500
244587
  clientInfo: {
244501
244588
  name: "letta-code",
244502
- version: "0.34.31"
244589
+ version: "0.34.32"
244503
244590
  },
244504
244591
  capabilities: null
244505
244592
  });
@@ -244915,6 +245002,7 @@ var sessions2, sessionCreations, DEFAULT_IDLE_TIMEOUT_MS, CODEX_NOT_SIGNED_IN_ER
244915
245002
  var init_codex_app_server = __esm(() => {
244916
245003
  init_subagent_process();
244917
245004
  init_native_cli_env();
245005
+ init_package_manager_spawn();
244918
245006
  sessions2 = new Map;
244919
245007
  sessionCreations = new Map;
244920
245008
  DEFAULT_IDLE_TIMEOUT_MS = 5 * 60000;
@@ -250024,12 +250112,12 @@ var init_manager4 = __esm(async () => {
250024
250112
  // src/agent/memory-conflict-repair.ts
250025
250113
  import { execFile as execFile15 } from "node:child_process";
250026
250114
  import { randomUUID as randomUUID42 } from "node:crypto";
250027
- import { readFile as readFile16, rm as rm9, writeFile as writeFile13 } from "node:fs/promises";
250115
+ import { readFile as readFile17, rm as rm9, writeFile as writeFile13 } from "node:fs/promises";
250028
250116
  import { join as join68 } from "node:path";
250029
250117
  import { promisify as promisify15 } from "node:util";
250030
250118
  async function readOptional(path29) {
250031
250119
  try {
250032
- return (await readFile16(path29, "utf8")).trim();
250120
+ return (await readFile17(path29, "utf8")).trim();
250033
250121
  } catch {
250034
250122
  return "";
250035
250123
  }
@@ -250070,7 +250158,7 @@ async function attemptPath(memoryDir) {
250070
250158
  }
250071
250159
  async function readAttempt(path29) {
250072
250160
  try {
250073
- return JSON.parse(await readFile16(path29, "utf8"));
250161
+ return JSON.parse(await readFile17(path29, "utf8"));
250074
250162
  } catch {
250075
250163
  return {};
250076
250164
  }
@@ -252249,7 +252337,7 @@ __export(exports_skill, {
252249
252337
  getResolvedSkillsDir: () => getResolvedSkillsDir
252250
252338
  });
252251
252339
  import { existsSync as existsSync46, readdirSync as readdirSync17 } from "node:fs";
252252
- import { readFile as readFile17 } from "node:fs/promises";
252340
+ import { readFile as readFile18 } from "node:fs/promises";
252253
252341
  import { dirname as dirname30, join as join70 } from "node:path";
252254
252342
  async function readSkillFromRoot(skillsRoot, skillId) {
252255
252343
  const discovery = await discoverSkills(skillsRoot, undefined, {
@@ -252261,7 +252349,7 @@ async function readSkillFromRoot(skillsRoot, skillId) {
252261
252349
  return null;
252262
252350
  }
252263
252351
  try {
252264
- const content = await readFile17(discoveredSkill.path, "utf-8");
252352
+ const content = await readFile18(discoveredSkill.path, "utf-8");
252265
252353
  return { content, path: discoveredSkill.path };
252266
252354
  } catch {
252267
252355
  return null;
@@ -252345,7 +252433,7 @@ async function readSkillContent(skillId, skillsDir, agentId, options = {}) {
252345
252433
  const sharedSkill = sharedMemoryDiscovery.skills.find((candidate) => candidate.id === skillId);
252346
252434
  if (sharedSkill) {
252347
252435
  try {
252348
- const content = await readFile17(sharedSkill.path, "utf-8");
252436
+ const content = await readFile18(sharedSkill.path, "utf-8");
252349
252437
  return { content, path: sharedSkill.path };
252350
252438
  } catch {}
252351
252439
  }
@@ -252358,14 +252446,14 @@ async function readSkillContent(skillId, skillsDir, agentId, options = {}) {
252358
252446
  if (bundledSkill?.path && isSkillAvailableForAgent(bundledSkill, agentId)) {
252359
252447
  try {
252360
252448
  const path30 = bundledSkill.path;
252361
- const content = await readFile17(path30, "utf-8");
252449
+ const content = await readFile18(path30, "utf-8");
252362
252450
  return { content, path: path30 };
252363
252451
  } catch {}
252364
252452
  }
252365
252453
  try {
252366
252454
  const bundledSkillsDir = join70(process.cwd(), "skills", "skills");
252367
252455
  const bundledSkillPath = join70(bundledSkillsDir, skillId, "SKILL.md");
252368
- const content = await readFile17(bundledSkillPath, "utf-8");
252456
+ const content = await readFile18(bundledSkillPath, "utf-8");
252369
252457
  return { content, path: bundledSkillPath };
252370
252458
  } catch {
252371
252459
  throw new Error(`Skill "${skillId}" not found. Check that the skill name is correct and that it appears in the available skills list.`);
@@ -253991,7 +254079,7 @@ var init_sdk_loader = __esm(() => {
253991
254079
  });
253992
254080
 
253993
254081
  // src/agent/preloaded-skills.ts
253994
- import { readFile as readFile18 } from "node:fs/promises";
254082
+ import { readFile as readFile19 } from "node:fs/promises";
253995
254083
  async function loadPreloadedSkills(ids, options = {}) {
253996
254084
  if (ids.length === 0)
253997
254085
  return "";
@@ -254006,7 +254094,7 @@ async function loadPreloadedSkills(ids, options = {}) {
254006
254094
  continue;
254007
254095
  try {
254008
254096
  contents.push(`<${id2}>
254009
- ${await readFile18(path31, "utf-8")}
254097
+ ${await readFile19(path31, "utf-8")}
254010
254098
  </${id2}>`);
254011
254099
  } catch {}
254012
254100
  }
@@ -263420,7 +263508,7 @@ var init_environments4 = __esm(() => {
263420
263508
  });
263421
263509
 
263422
263510
  // src/cli/subcommands/feedback.ts
263423
- import { readFile as readFile19 } from "node:fs/promises";
263511
+ import { readFile as readFile20 } from "node:fs/promises";
263424
263512
  import { parseArgs as parseArgs8 } from "node:util";
263425
263513
  function printUsage6(stdout = console.log) {
263426
263514
  stdout(`
@@ -263470,7 +263558,7 @@ async function runFeedbackSubcommand(argv, deps = {}) {
263470
263558
  let rawMessage = typeof inlineMessage === "string" ? inlineMessage : "";
263471
263559
  if (typeof messageFile === "string") {
263472
263560
  try {
263473
- rawMessage = await (deps.readMessageFile ?? ((path32) => readFile19(path32, "utf8")))(messageFile);
263561
+ rawMessage = await (deps.readMessageFile ?? ((path32) => readFile20(path32, "utf8")))(messageFile);
263474
263562
  } catch {
263475
263563
  stderr(`Could not read feedback file: ${messageFile}`);
263476
263564
  return 1;
@@ -265688,7 +265776,7 @@ var init_listen_log = __esm(() => {
265688
265776
 
265689
265777
  // src/utils/machine-metadata.ts
265690
265778
  import { execFile as execFile17 } from "node:child_process";
265691
- import { readFile as readFile20 } from "node:fs/promises";
265779
+ import { readFile as readFile21 } from "node:fs/promises";
265692
265780
  import { cpus, totalmem } from "node:os";
265693
265781
  function getMachineMetadata() {
265694
265782
  machineMetadata ??= collectMachineMetadata().catch(() => ({
@@ -265703,7 +265791,7 @@ function localSources() {
265703
265791
  architecture: process.arch,
265704
265792
  cpu: cpus()[0]?.model,
265705
265793
  memoryBytes: Math.min(totalmem(), limit4 || Number.POSITIVE_INFINITY),
265706
- read: (path32, signal) => readFile20(path32, { encoding: "utf8", signal }),
265794
+ read: (path32, signal) => readFile21(path32, { encoding: "utf8", signal }),
265707
265795
  run: (command, args, signal) => new Promise((resolve38, reject2) => {
265708
265796
  execFile17(command, args, {
265709
265797
  encoding: "utf8",
@@ -266282,7 +266370,7 @@ var init_auth3 = __esm(() => {
266282
266370
 
266283
266371
  // src/websocket/listener/manual-instance-lock.ts
266284
266372
  import { createHash as createHash15, randomUUID as randomUUID50 } from "node:crypto";
266285
- import { link as link4, mkdir as mkdir12, readFile as readFile21, rm as rm11, unlink as unlink3, writeFile as writeFile15 } from "node:fs/promises";
266373
+ import { link as link4, mkdir as mkdir12, readFile as readFile22, rm as rm11, unlink as unlink3, writeFile as writeFile15 } from "node:fs/promises";
266286
266374
  import { uptime as uptime2 } from "node:os";
266287
266375
  import path32 from "node:path";
266288
266376
  function hasErrorCode3(error5, code2) {
@@ -266381,7 +266469,7 @@ async function recoverDeadOwner(lockPath, staleContents, recoveryOwnerContents,
266381
266469
  }
266382
266470
  let claimContents;
266383
266471
  try {
266384
- claimContents = await readFile21(claimPath, "utf-8");
266472
+ claimContents = await readFile22(claimPath, "utf-8");
266385
266473
  } catch (error5) {
266386
266474
  if (hasErrorCode3(error5, "ENOENT")) {
266387
266475
  continue;
@@ -266401,7 +266489,7 @@ async function recoverDeadOwner(lockPath, staleContents, recoveryOwnerContents,
266401
266489
  }
266402
266490
  let currentContents;
266403
266491
  try {
266404
- currentContents = await readFile21(lockPath, "utf-8");
266492
+ currentContents = await readFile22(lockPath, "utf-8");
266405
266493
  } catch (error5) {
266406
266494
  return hasErrorCode3(error5, "ENOENT");
266407
266495
  }
@@ -266453,7 +266541,7 @@ async function acquireManualListenerLock(scope, overrides = {}) {
266453
266541
  return;
266454
266542
  let currentContents;
266455
266543
  try {
266456
- currentContents = await readFile21(lockPath, "utf-8");
266544
+ currentContents = await readFile22(lockPath, "utf-8");
266457
266545
  } catch (error5) {
266458
266546
  if (hasErrorCode3(error5, "ENOENT")) {
266459
266547
  released = true;
@@ -266473,7 +266561,7 @@ async function acquireManualListenerLock(scope, overrides = {}) {
266473
266561
  }
266474
266562
  let incumbentContents;
266475
266563
  try {
266476
- incumbentContents = await readFile21(lockPath, "utf-8");
266564
+ incumbentContents = await readFile22(lockPath, "utf-8");
266477
266565
  } catch (error5) {
266478
266566
  if (hasErrorCode3(error5, "ENOENT")) {
266479
266567
  continue;
@@ -269047,7 +269135,7 @@ function handleMemoryProtocolCommand(parsed, context3) {
269047
269135
  ensureLocalMemfsCheckout: ensureLocalMemfsCheckout2,
269048
269136
  isMemfsEnabledOnServer: isMemfsEnabledOnServer2
269049
269137
  } = await Promise.resolve().then(() => (init_memory_filesystem2(), exports_memory_filesystem));
269050
- const { readFile: readFile22 } = await import("node:fs/promises");
269138
+ const { readFile: readFile23 } = await import("node:fs/promises");
269051
269139
  const { existsSync: existsSync52 } = await import("node:fs");
269052
269140
  const { isAbsolute: isAbsolute25, join: join80, normalize: normalize5, relative: relative8, sep: sep8 } = await import("node:path");
269053
269141
  if (isAbsolute25(parsed.path) || parsed.path.length === 0) {
@@ -269073,7 +269161,7 @@ function handleMemoryProtocolCommand(parsed, context3) {
269073
269161
  return;
269074
269162
  }
269075
269163
  }
269076
- const buffer = await readFile22(absolutePath);
269164
+ const buffer = await readFile23(absolutePath);
269077
269165
  const content = encoding === "base64" ? buffer.toString("base64") : buffer.toString("utf-8");
269078
269166
  const pathspec = rel.split(sep8).join("/");
269079
269167
  safeSocketSend(socket, {
@@ -278361,7 +278449,7 @@ ${lanes.join(`
278361
278449
  writeOutputIsTTY() {
278362
278450
  return process.stdout.isTTY;
278363
278451
  },
278364
- readFile: readFile22,
278452
+ readFile: readFile23,
278365
278453
  writeFile: writeFile22,
278366
278454
  watchFile: watchFile2,
278367
278455
  watchDirectory,
@@ -278554,7 +278642,7 @@ ${lanes.join(`
278554
278642
  function fsWatchWorker(fileOrDirectory, recursive, callback) {
278555
278643
  return _fs.watch(fileOrDirectory, fsSupportsRecursiveFsWatch ? { persistent: true, recursive: !!recursive } : { persistent: true }, callback);
278556
278644
  }
278557
- function readFile22(fileName, _encoding) {
278645
+ function readFile23(fileName, _encoding) {
278558
278646
  let buffer;
278559
278647
  try {
278560
278648
  buffer = _fs.readFileSync(fileName);
@@ -309501,7 +309589,7 @@ ${lanes.join(`
309501
309589
  const possibleOption = getSpellingSuggestion(unknownOption, diagnostics2.optionDeclarations, getOptionName);
309502
309590
  return possibleOption ? createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics2.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) : createDiagnosticForNodeInSourceFileOrCompilerDiagnostic(sourceFile, node, diagnostics2.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
309503
309591
  }
309504
- function parseCommandLineWorker(diagnostics2, commandLine, readFile22) {
309592
+ function parseCommandLineWorker(diagnostics2, commandLine, readFile23) {
309505
309593
  const options = {};
309506
309594
  let watchOptions;
309507
309595
  const fileNames = [];
@@ -309539,7 +309627,7 @@ ${lanes.join(`
309539
309627
  }
309540
309628
  }
309541
309629
  function parseResponseFile(fileName) {
309542
- const text3 = tryReadFile(fileName, readFile22 || ((fileName2) => sys.readFile(fileName2)));
309630
+ const text3 = tryReadFile(fileName, readFile23 || ((fileName2) => sys.readFile(fileName2)));
309543
309631
  if (!isString7(text3)) {
309544
309632
  errors6.push(text3);
309545
309633
  return;
@@ -309642,8 +309730,8 @@ ${lanes.join(`
309642
309730
  unknownDidYouMeanDiagnostic: Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
309643
309731
  optionTypeMismatchDiagnostic: Diagnostics.Compiler_option_0_expects_an_argument
309644
309732
  };
309645
- function parseCommandLine2(commandLine, readFile22) {
309646
- return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile22);
309733
+ function parseCommandLine2(commandLine, readFile23) {
309734
+ return parseCommandLineWorker(compilerOptionsDidYouMeanDiagnostics, commandLine, readFile23);
309647
309735
  }
309648
309736
  function getOptionFromName(optionName, allowShort) {
309649
309737
  return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
@@ -309711,8 +309799,8 @@ ${lanes.join(`
309711
309799
  result3.originalFileName = result3.fileName;
309712
309800
  return parseJsonSourceFileConfigFileContent(result3, host, getNormalizedAbsolutePath(getDirectoryPath(configFileName), cwd2), optionsToExtend, getNormalizedAbsolutePath(configFileName, cwd2), undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
309713
309801
  }
309714
- function readConfigFile(fileName, readFile22) {
309715
- const textOrDiagnostic = tryReadFile(fileName, readFile22);
309802
+ function readConfigFile(fileName, readFile23) {
309803
+ const textOrDiagnostic = tryReadFile(fileName, readFile23);
309716
309804
  return isString7(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
309717
309805
  }
309718
309806
  function parseConfigFileTextToJson(fileName, jsonText) {
@@ -309722,14 +309810,14 @@ ${lanes.join(`
309722
309810
  error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
309723
309811
  };
309724
309812
  }
309725
- function readJsonConfigFile(fileName, readFile22) {
309726
- const textOrDiagnostic = tryReadFile(fileName, readFile22);
309813
+ function readJsonConfigFile(fileName, readFile23) {
309814
+ const textOrDiagnostic = tryReadFile(fileName, readFile23);
309727
309815
  return isString7(textOrDiagnostic) ? parseJsonText(fileName, textOrDiagnostic) : { fileName, parseDiagnostics: [textOrDiagnostic] };
309728
309816
  }
309729
- function tryReadFile(fileName, readFile22) {
309817
+ function tryReadFile(fileName, readFile23) {
309730
309818
  let text3;
309731
309819
  try {
309732
- text3 = readFile22(fileName);
309820
+ text3 = readFile23(fileName);
309733
309821
  } catch (e2) {
309734
309822
  return createCompilerDiagnostic(Diagnostics.Cannot_read_file_0_Colon_1, fileName, e2.message);
309735
309823
  }
@@ -377159,12 +377247,12 @@ ${lanes.join(`
377159
377247
  function createCompilerHost(options, setParentNodes) {
377160
377248
  return createCompilerHostWorker(options, setParentNodes);
377161
377249
  }
377162
- function createGetSourceFile(readFile22, setParentNodes) {
377250
+ function createGetSourceFile(readFile23, setParentNodes) {
377163
377251
  return (fileName, languageVersionOrOptions, onError) => {
377164
377252
  let text3;
377165
377253
  try {
377166
377254
  mark2("beforeIORead");
377167
- text3 = readFile22(fileName);
377255
+ text3 = readFile23(fileName);
377168
377256
  mark2("afterIORead");
377169
377257
  measure("I/O Read", "beforeIORead", "afterIORead");
377170
377258
  } catch (e2) {
@@ -377955,7 +378043,7 @@ ${lanes.join(`
377955
378043
  getRedirectFromOutput,
377956
378044
  forEachResolvedProjectReference: forEachResolvedProjectReference2
377957
378045
  });
377958
- const readFile22 = host.readFile.bind(host);
378046
+ const readFile23 = host.readFile.bind(host);
377959
378047
  (_e = tracing) == null || _e.push(tracing.Phase.Program, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
377960
378048
  const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
377961
378049
  (_f = tracing) == null || _f.pop();
@@ -378131,7 +378219,7 @@ ${lanes.join(`
378131
378219
  shouldTransformImportCall,
378132
378220
  emitBuildInfo,
378133
378221
  fileExists,
378134
- readFile: readFile22,
378222
+ readFile: readFile23,
378135
378223
  directoryExists: directoryExists2,
378136
378224
  getSymlinkCache,
378137
378225
  realpath: (_o = host.realpath) == null ? undefined : _o.bind(host),
@@ -452818,7 +452906,7 @@ async function handleApprovalStop(params) {
452818
452906
  if (shouldInterrupt()) {
452819
452907
  return interruptTermination();
452820
452908
  }
452821
- executionResults = await executeApprovals(decisions, undefined, {
452909
+ executionResults = await executeApprovals(decisions, params.onChunk, {
452822
452910
  toolContextId: turnToolContextId ?? undefined,
452823
452911
  abortSignal,
452824
452912
  onStreamingOutput: emitToolExecutionOutput,
@@ -454187,12 +454275,12 @@ function rowToolCalls(row, index, diagnostics2) {
454187
454275
  }
454188
454276
  return calls;
454189
454277
  }
454190
- function contentText3(content) {
454278
+ function contentText2(content) {
454191
454279
  if (typeof content === "string") {
454192
454280
  if (content.startsWith(CONTENT_JSON_PREFIX)) {
454193
454281
  const encoded = content.slice(CONTENT_JSON_PREFIX.length);
454194
454282
  try {
454195
- return contentText3(JSON.parse(encoded));
454283
+ return contentText2(JSON.parse(encoded));
454196
454284
  } catch {
454197
454285
  return encoded;
454198
454286
  }
@@ -454278,7 +454366,7 @@ var init_hermes = __esm(() => {
454278
454366
  });
454279
454367
  };
454280
454368
  if (row.role === "user") {
454281
- const content = contentText3(row.content);
454369
+ const content = contentText2(row.content);
454282
454370
  if (content) {
454283
454371
  emit({
454284
454372
  type: "message",
@@ -454298,7 +454386,7 @@ var init_hermes = __esm(() => {
454298
454386
  ...timestamp ? { timestamp } : {}
454299
454387
  });
454300
454388
  }
454301
- const content = contentText3(row.content);
454389
+ const content = contentText2(row.content);
454302
454390
  if (content) {
454303
454391
  emit({
454304
454392
  type: "message",
@@ -454321,7 +454409,7 @@ var init_hermes = __esm(() => {
454321
454409
  if (row.role === "tool") {
454322
454410
  emit({
454323
454411
  type: "tool_result",
454324
- content: contentText3(row.content),
454412
+ content: contentText2(row.content),
454325
454413
  ...typeof row.tool_call_id === "string" && row.tool_call_id ? { callId: row.tool_call_id } : {},
454326
454414
  ...timestamp ? { timestamp } : {}
454327
454415
  });
@@ -456313,7 +456401,7 @@ var exports_reflection_memory_v2 = {};
456313
456401
  __export(exports_reflection_memory_v2, {
456314
456402
  buildMemfsV2ParentMemorySnapshot: () => buildMemfsV2ParentMemorySnapshot
456315
456403
  });
456316
- import { readFile as readFile22 } from "node:fs/promises";
456404
+ import { readFile as readFile23 } from "node:fs/promises";
456317
456405
  function renderProjectedTree(files) {
456318
456406
  const root2 = { directories: new Map, files: [] };
456319
456407
  for (const file of files) {
@@ -456366,7 +456454,7 @@ async function buildMemfsV2ParentMemorySnapshot(memoryDir, requestedMaxChars) {
456366
456454
  `).length - prefix.length - suffix.length - 20;
456367
456455
  if (remaining <= 0)
456368
456456
  break;
456369
- const content = (await readFile22(file.fullPath, "utf-8")).slice(0, remaining);
456457
+ const content = (await readFile23(file.fullPath, "utf-8")).slice(0, remaining);
456370
456458
  lines.push(`${prefix}${content}${suffix}`);
456371
456459
  }
456372
456460
  lines.push("</parent_memory>");
@@ -456384,7 +456472,7 @@ import {
456384
456472
  appendFile,
456385
456473
  mkdir as mkdir13,
456386
456474
  readdir as readdir9,
456387
- readFile as readFile23,
456475
+ readFile as readFile24,
456388
456476
  stat as stat13,
456389
456477
  writeFile as writeFile16
456390
456478
  } from "node:fs/promises";
@@ -456432,7 +456520,7 @@ async function collectParentMemoryFiles(memoryDir) {
456432
456520
  continue;
456433
456521
  }
456434
456522
  try {
456435
- const content = await readFile23(entryPath, "utf-8");
456523
+ const content = await readFile24(entryPath, "utf-8");
456436
456524
  const { frontmatter } = parseFrontmatter(content);
456437
456525
  const description = typeof frontmatter.description === "string" ? frontmatter.description : undefined;
456438
456526
  files.push({
@@ -456735,7 +456823,7 @@ async function ensurePaths(paths) {
456735
456823
  }
456736
456824
  async function readTranscriptLines(paths) {
456737
456825
  try {
456738
- const raw2 = await readFile23(paths.transcriptPath, "utf-8");
456826
+ const raw2 = await readFile24(paths.transcriptPath, "utf-8");
456739
456827
  return raw2.split(`
456740
456828
  `).map((line) => line.trim()).filter((line) => line.length > 0);
456741
456829
  } catch {
@@ -456808,7 +456896,7 @@ function buildUnreflectedStateFromTranscript(lines) {
456808
456896
  async function readState(paths) {
456809
456897
  let raw2 = null;
456810
456898
  try {
456811
- raw2 = await readFile23(paths.statePath, "utf-8");
456899
+ raw2 = await readFile24(paths.statePath, "utf-8");
456812
456900
  } catch {
456813
456901
  raw2 = null;
456814
456902
  }
@@ -457140,7 +457228,7 @@ function isReflectionAutoPriority(value) {
457140
457228
  return value === "high" || value === "medium" || value === "low";
457141
457229
  }
457142
457230
  async function readReflectionAutoSelection(options) {
457143
- const raw2 = options.selectionReport ?? (options.selectionOutputPath ? await readFile23(options.selectionOutputPath, "utf-8") : "");
457231
+ const raw2 = options.selectionReport ?? (options.selectionOutputPath ? await readFile24(options.selectionOutputPath, "utf-8") : "");
457144
457232
  const parsed = parseReflectionAutoSelectionJson(raw2);
457145
457233
  if (!parsed || typeof parsed !== "object") {
457146
457234
  throw new Error("Reflection selector did not return valid JSON.");
@@ -460376,6 +460464,7 @@ async function handleIncomingMessageInner(msg, socket, runtime, onStatusChange,
460376
460464
  }
460377
460465
  const approvalResult = await handleApprovalStop({
460378
460466
  approvals,
460467
+ onChunk: (chunk2) => onChunk(buffers, chunk2),
460379
460468
  runtime,
460380
460469
  socket,
460381
460470
  agentId,
@@ -461089,7 +461178,7 @@ var init_write_file_command = __esm(() => {
461089
461178
  });
461090
461179
 
461091
461180
  // src/websocket/listener/file-commands.ts
461092
- import { readdir as readdir10, readFile as readFile24 } from "node:fs/promises";
461181
+ import { readdir as readdir10, readFile as readFile25 } from "node:fs/promises";
461093
461182
  import { homedir as homedir31 } from "node:os";
461094
461183
  import path44 from "node:path";
461095
461184
  function trackListenerError3(errorType, error5, context3) {
@@ -461144,7 +461233,7 @@ async function getIgnoreConfig(root2) {
461144
461233
  return cached3;
461145
461234
  let patterns2 = [];
461146
461235
  try {
461147
- const content = await readFile24(path44.join(absRoot, ".letta", ".lettaignore"), "utf-8");
461236
+ const content = await readFile25(path44.join(absRoot, ".letta", ".lettaignore"), "utf-8");
461148
461237
  patterns2 = parseLettaIgnore(content);
461149
461238
  } catch {
461150
461239
  patterns2 = [];
@@ -461509,7 +461598,7 @@ function createFileCommandSession(params) {
461509
461598
  if (stats.size > MAX_BASE64_READ_BYTES) {
461510
461599
  throw new Error(`File too large for base64 read (max ${Math.floor(MAX_BASE64_READ_BYTES / 1048576)}MB)`);
461511
461600
  }
461512
- const bytes = await readFile24(parsed.path);
461601
+ const bytes = await readFile25(parsed.path);
461513
461602
  content = bytes.toString("base64");
461514
461603
  } else {
461515
461604
  content = await readUtf8TextStrict(parsed.path);
@@ -462240,7 +462329,7 @@ __export(exports_custom, {
462240
462329
  COMMANDS_DIR: () => COMMANDS_DIR
462241
462330
  });
462242
462331
  import { existsSync as existsSync63 } from "node:fs";
462243
- import { readdir as readdir11, readFile as readFile25 } from "node:fs/promises";
462332
+ import { readdir as readdir11, readFile as readFile26 } from "node:fs/promises";
462244
462333
  import { basename as basename28, dirname as dirname37, join as join96 } from "node:path";
462245
462334
  function getGlobalCommandsDir() {
462246
462335
  return join96(resolveGlobalConfigDir(), "commands");
@@ -462302,7 +462391,7 @@ async function findCommandFiles(currentPath, rootPath, commands, source) {
462302
462391
  } catch (_error) {}
462303
462392
  }
462304
462393
  async function parseCommandFile(filePath, rootPath, source) {
462305
- const content = await readFile25(filePath, "utf-8");
462394
+ const content = await readFile26(filePath, "utf-8");
462306
462395
  const { frontmatter, body: body3 } = parseFrontmatter(content);
462307
462396
  const id2 = basename28(filePath, ".md");
462308
462397
  const relativePath = dirname37(filePath).slice(rootPath.length);
@@ -468529,7 +468618,7 @@ var init_listen_client = __esm(async () => {
468529
468618
 
468530
468619
  // src/websocket/app-server-auth.ts
468531
468620
  import { createHash as createHash19, createHmac, timingSafeEqual } from "node:crypto";
468532
- import { readFile as readFile26 } from "node:fs/promises";
468621
+ import { readFile as readFile27 } from "node:fs/promises";
468533
468622
  import { isIP as isIP2 } from "node:net";
468534
468623
  import { isAbsolute as isAbsolute26 } from "node:path";
468535
468624
  function parseAppServerWebsocketAuthSettings(args) {
@@ -468770,7 +468859,7 @@ function bearerTokenFromHeaders(headers) {
468770
468859
  async function readTrimmedSecret(path46) {
468771
468860
  let raw2;
468772
468861
  try {
468773
- raw2 = await readFile26(path46, "utf8");
468862
+ raw2 = await readFile27(path46, "utf8");
468774
468863
  } catch (error5) {
468775
468864
  const message2 = error5 instanceof Error ? error5.message : String(error5);
468776
468865
  throw new Error(`failed to read websocket auth secret ${path46}: ${message2}`);
@@ -475437,7 +475526,7 @@ var init_sandbox_files = __esm(() => {
475437
475526
  });
475438
475527
 
475439
475528
  // src/cli/subcommands/sandbox.ts
475440
- import { readFile as readFile27, stat as stat15, writeFile as writeFile19 } from "node:fs/promises";
475529
+ import { readFile as readFile28, stat as stat15, writeFile as writeFile19 } from "node:fs/promises";
475441
475530
  import { basename as basename29, resolve as resolve40 } from "node:path";
475442
475531
  import { parseArgs as parseArgs16 } from "node:util";
475443
475532
  function printUsage13() {
@@ -475587,7 +475676,7 @@ async function runSandboxSubcommand(argv, deps = {}) {
475587
475676
  const fileStat = await (deps.statLocalPath ?? stat15)(localPath2);
475588
475677
  if (!fileStat.isFile())
475589
475678
  throw new Error(`${localPath2} is not a file`);
475590
- const data2 = await (deps.readLocalFile ?? readFile27)(localPath2);
475679
+ const data2 = await (deps.readLocalFile ?? readFile28)(localPath2);
475591
475680
  const sandbox2 = await ensureSandbox();
475592
475681
  const result3 = await (deps.uploadFile ?? uploadFileToSandbox)(sandbox2.sandboxId, { blob: new Blob([data2]), name: basename29(localPath2) });
475593
475682
  console.log(JSON.stringify({ ...result3, ...targetOutput }, null, 2));
@@ -475664,22 +475753,11 @@ function normalizeKey(key4) {
475664
475753
  function printError(error5) {
475665
475754
  console.error(error5 instanceof Error ? error5.message : String(error5));
475666
475755
  }
475667
- async function readProcessStdin() {
475668
- return new Promise((resolve41, reject2) => {
475669
- let data = "";
475670
- process.stdin.setEncoding("utf8");
475671
- process.stdin.on("data", (chunk2) => {
475672
- data += chunk2;
475673
- });
475674
- process.stdin.on("end", () => resolve41(data));
475675
- process.stdin.on("error", reject2);
475676
- });
475677
- }
475678
475756
  async function runSecretSubcommand(argv, deps = {}) {
475679
475757
  const listSecrets = deps.listSecrets ?? refreshAndListSecrets;
475680
475758
  const setSecret = deps.setSecret ?? setSecretOnServer;
475681
475759
  const deleteSecret = deps.deleteSecret ?? deleteSecretOnServer;
475682
- const readStdin2 = deps.readStdin ?? readProcessStdin;
475760
+ const readInput = deps.readStdin ?? readStdin;
475683
475761
  const initializeSettings = deps.initializeSettings ?? (async () => settingsManager.initialize());
475684
475762
  let parsed;
475685
475763
  try {
@@ -475753,7 +475831,7 @@ async function runSecretSubcommand(argv, deps = {}) {
475753
475831
  console.error("Pass either a positional value or --env/--stdin, not both.");
475754
475832
  return 1;
475755
475833
  }
475756
- const piped = (await readStdin2()).replace(/\r?\n$/, "");
475834
+ const piped = (await readInput()).replace(/\r?\n$/, "");
475757
475835
  if (!piped) {
475758
475836
  console.error("No value received on stdin.");
475759
475837
  return 1;
@@ -479376,7 +479454,7 @@ var init_teleport2 = __esm(() => {
479376
479454
  });
479377
479455
 
479378
479456
  // src/cli/subcommands/trajectories/readers.ts
479379
- import { readdir as readdir14, readFile as readFile28, stat as stat16 } from "node:fs/promises";
479457
+ import { readdir as readdir14, readFile as readFile29, stat as stat16 } from "node:fs/promises";
479380
479458
  import { join as join103 } from "node:path";
479381
479459
  async function loadSessionTranscript(item) {
479382
479460
  const stats = await stat16(item.path);
@@ -479386,7 +479464,7 @@ async function loadSessionTranscript(item) {
479386
479464
  if (item.path.endsWith(".db")) {
479387
479465
  return exportHermesSession(item.path, item.id);
479388
479466
  }
479389
- return readFile28(item.path, "utf-8");
479467
+ return readFile29(item.path, "utf-8");
479390
479468
  }
479391
479469
  async function assembleEventDirectory(sessionDir) {
479392
479470
  const eventsSubdir = join103(sessionDir, "events");
@@ -479395,7 +479473,7 @@ async function assembleEventDirectory(sessionDir) {
479395
479473
  if (names2.length === 0) {
479396
479474
  throw new Error(`No event files found in ${eventsDir}`);
479397
479475
  }
479398
- const events = await Promise.all(names2.map(async (name) => JSON.parse(await readFile28(join103(eventsDir, name), "utf-8"))));
479476
+ const events = await Promise.all(names2.map(async (name) => JSON.parse(await readFile29(join103(eventsDir, name), "utf-8"))));
479399
479477
  return JSON.stringify(events);
479400
479478
  }
479401
479479
  async function openReadOnlyDatabase(path48) {
@@ -479468,7 +479546,7 @@ import { createHash as createHash20 } from "node:crypto";
479468
479546
  import {
479469
479547
  mkdir as mkdir17,
479470
479548
  readdir as readdir15,
479471
- readFile as readFile29,
479549
+ readFile as readFile30,
479472
479550
  rm as rm12,
479473
479551
  stat as stat17,
479474
479552
  writeFile as writeFile20
@@ -479641,7 +479719,7 @@ async function runTrajectoryExport(options) {
479641
479719
  if (!supported.includes(explicit.source)) {
479642
479720
  throw new Error(`Unknown source "${explicit.source}" in --transcript. The installed trajectory package supports: ${supported.join(", ")}.`);
479643
479721
  }
479644
- await exportTranscript(explicit.source, basename31(explicit.path).replace(/\.[^.]+$/, ""), explicit.path, () => readFile29(explicit.path, "utf-8"));
479722
+ await exportTranscript(explicit.source, basename31(explicit.path).replace(/\.[^.]+$/, ""), explicit.path, () => readFile30(explicit.path, "utf-8"));
479645
479723
  }
479646
479724
  for (const checkpoint of options.deepagents ?? []) {
479647
479725
  await exportCheckpoint(checkpoint, `${basename31(checkpoint.path)}-${checkpoint.threadId}`);
@@ -479658,12 +479736,12 @@ var init_export = __esm(() => {
479658
479736
  });
479659
479737
 
479660
479738
  // src/cli/subcommands/trajectories/review.ts
479661
- import { readFile as readFile30 } from "node:fs/promises";
479739
+ import { readFile as readFile31 } from "node:fs/promises";
479662
479740
  import { isAbsolute as isAbsolute27, join as join105 } from "node:path";
479663
479741
  async function readManifest(dir) {
479664
479742
  let raw2;
479665
479743
  try {
479666
- raw2 = await readFile30(join105(dir, "manifest.json"), "utf-8");
479744
+ raw2 = await readFile31(join105(dir, "manifest.json"), "utf-8");
479667
479745
  } catch {
479668
479746
  throw new Error(`No manifest at ${join105(dir, "manifest.json")}. Run: letta trajectories export --out ${dir}`);
479669
479747
  }
@@ -479676,7 +479754,7 @@ async function resolveSessionFile(dir, target2) {
479676
479754
  if (target2.endsWith(".json")) {
479677
479755
  const direct = isAbsolute27(target2) ? target2 : join105(dir, target2);
479678
479756
  try {
479679
- await readFile30(direct, "utf-8");
479757
+ await readFile31(direct, "utf-8");
479680
479758
  return direct;
479681
479759
  } catch {}
479682
479760
  }
@@ -479728,7 +479806,7 @@ async function searchSessions(dir, keyword, options = {}) {
479728
479806
  for (const session3 of filterSessions(manifest2.sessions, options)) {
479729
479807
  let records2;
479730
479808
  try {
479731
- records2 = JSON.parse(await readFile30(join105(dir, session3.file), "utf-8"));
479809
+ records2 = JSON.parse(await readFile31(join105(dir, session3.file), "utf-8"));
479732
479810
  } catch {
479733
479811
  continue;
479734
479812
  }
@@ -479759,7 +479837,7 @@ var TOOL_RESULT_MAX_CHARS = 500, REASONING_MAX_CHARS = 300, TOOL_ARGS_MAX_CHARS
479759
479837
  var init_review = () => {};
479760
479838
 
479761
479839
  // src/cli/subcommands/trajectories.ts
479762
- import { readFile as readFile31 } from "node:fs/promises";
479840
+ import { readFile as readFile32 } from "node:fs/promises";
479763
479841
  import { parseArgs as parseArgs23 } from "node:util";
479764
479842
  function printUsage19() {
479765
479843
  console.log(`
@@ -479866,7 +479944,7 @@ async function runView(flags, target2, options) {
479866
479944
  return 1;
479867
479945
  }
479868
479946
  const path48 = await resolveSessionFile(flags.dir, target2);
479869
- const records2 = JSON.parse(await readFile31(path48, "utf-8"));
479947
+ const records2 = JSON.parse(await readFile32(path48, "utf-8"));
479870
479948
  console.log(renderSession(records2, options));
479871
479949
  return 0;
479872
479950
  }
@@ -490844,7 +490922,7 @@ var init_reflection_arena_hf_upload = __esm(() => {
490844
490922
  // src/cli/helpers/reflection-arena.ts
490845
490923
  import { execFile as execFileCb5 } from "node:child_process";
490846
490924
  import { randomInt as randomInt2, randomUUID as randomUUID64 } from "node:crypto";
490847
- import { appendFile as appendFile4, mkdir as mkdir19, readFile as readFile32, writeFile as writeFile22 } from "node:fs/promises";
490925
+ import { appendFile as appendFile4, mkdir as mkdir19, readFile as readFile33, writeFile as writeFile22 } from "node:fs/promises";
490848
490926
  import { join as join109 } from "node:path";
490849
490927
  import { promisify as promisify20 } from "node:util";
490850
490928
  function sampleReflectionArenaComparisonModel(excludedModels = []) {
@@ -490911,7 +490989,7 @@ async function saveReflectionArenaRun(run) {
490911
490989
  `, "utf-8");
490912
490990
  }
490913
490991
  async function loadReflectionArenaRun(runId) {
490914
- const raw2 = await readFile32(getReflectionArenaRunPath(runId), "utf-8");
490992
+ const raw2 = await readFile33(getReflectionArenaRunPath(runId), "utf-8");
490915
490993
  return JSON.parse(raw2);
490916
490994
  }
490917
490995
  async function updateReflectionArenaRun(runId, update3) {
@@ -491103,7 +491181,7 @@ async function appendChoiceRecord(run) {
491103
491181
  }
491104
491182
  async function readTranscriptPayloadForTelemetry(payloadPath) {
491105
491183
  try {
491106
- const transcript2 = await readFile32(payloadPath, "utf-8");
491184
+ const transcript2 = await readFile33(payloadPath, "utf-8");
491107
491185
  return {
491108
491186
  transcriptPayload: transcript2.slice(0, REFLECTION_ARENA_TELEMETRY_TRANSCRIPT_MAX_CHARS),
491109
491187
  transcriptPayloadChars: transcript2.length,
@@ -510842,7 +510920,7 @@ var init_use_chatgpt_rate_limit_state = __esm(() => {
510842
510920
  });
510843
510921
 
510844
510922
  // src/utils/aws-credentials.ts
510845
- import { readFile as readFile33 } from "node:fs/promises";
510923
+ import { readFile as readFile34 } from "node:fs/promises";
510846
510924
  import { homedir as homedir35 } from "node:os";
510847
510925
  import { join as join115 } from "node:path";
510848
510926
  async function parseAwsCredentials() {
@@ -510850,11 +510928,11 @@ async function parseAwsCredentials() {
510850
510928
  const configPath = join115(homedir35(), ".aws", "config");
510851
510929
  const profiles = new Map;
510852
510930
  try {
510853
- const content = await readFile33(credentialsPath, "utf-8");
510931
+ const content = await readFile34(credentialsPath, "utf-8");
510854
510932
  parseIniFile(content, profiles, false);
510855
510933
  } catch {}
510856
510934
  try {
510857
- const content = await readFile33(configPath, "utf-8");
510935
+ const content = await readFile34(configPath, "utf-8");
510858
510936
  parseIniFile(content, profiles, true);
510859
510937
  } catch {}
510860
510938
  return Array.from(profiles.values());
@@ -525361,7 +525439,7 @@ The deployment target for this project is CITATION-DOGFOOD-OK.
525361
525439
 
525362
525440
  // src/mods/learning-harness.ts
525363
525441
  import { spawn as spawn15 } from "node:child_process";
525364
- import { access as access2, copyFile as copyFile2, mkdir as mkdir20, readFile as readFile34, writeFile as writeFile23 } from "node:fs/promises";
525442
+ import { access as access2, copyFile as copyFile2, mkdir as mkdir20, readFile as readFile35, writeFile as writeFile23 } from "node:fs/promises";
525365
525443
  import path49 from "node:path";
525366
525444
  function slugify2(value) {
525367
525445
  const slug = value.trim().toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
@@ -526853,7 +526931,7 @@ async function runModLearning(options) {
526853
526931
  return report;
526854
526932
  }
526855
526933
  async function readModLearningEnv(envPath) {
526856
- return JSON.parse(await readFile34(envPath, "utf8"));
526934
+ return JSON.parse(await readFile35(envPath, "utf8"));
526857
526935
  }
526858
526936
  var init_learning_harness = __esm(async () => {
526859
526937
  await init_mod_engine();
@@ -539182,4 +539260,4 @@ function registerBunOAuthFlows() {
539182
539260
  registerBunOAuthFlows();
539183
539261
  await init_src5().then(() => exports_src2);
539184
539262
 
539185
- //# debugId=5AEE6E35869AE1C864756E2164756E21
539263
+ //# debugId=856A9C1BADE9BA4D64756E2164756E21