@letta-ai/letta-code 0.34.59 → 0.34.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/dist/app-server-client.cjs +23 -4
  2. package/dist/app-server-client.cjs.map +3 -3
  3. package/dist/app-server-client.js +23 -4
  4. package/dist/app-server-client.js.map +3 -3
  5. package/dist/mcp-client.js +2 -2
  6. package/dist/mcp-client.js.map +1 -1
  7. package/dist/mcp-oauth.js +2 -2
  8. package/dist/mcp-oauth.js.map +1 -1
  9. package/dist/types/agent/memory-git.d.ts +0 -4
  10. package/dist/types/agent/memory-git.d.ts.map +1 -1
  11. package/dist/types/agent/shared-memory-skills.d.ts.map +1 -1
  12. package/dist/types/app-server-client.d.ts.map +1 -1
  13. package/dist/types/backend/api/environments.d.ts +4 -0
  14. package/dist/types/backend/api/environments.d.ts.map +1 -1
  15. package/dist/types/backend/dev/pi-messages.d.ts +8 -0
  16. package/dist/types/backend/dev/pi-messages.d.ts.map +1 -0
  17. package/dist/types/backend/dev/pi-model-factory.d.ts +6 -0
  18. package/dist/types/backend/dev/pi-model-factory.d.ts.map +1 -1
  19. package/dist/types/backend/dev/pi-stream-adapter.d.ts.map +1 -1
  20. package/dist/types/backend/local/compaction-settings.d.ts +16 -0
  21. package/dist/types/backend/local/compaction-settings.d.ts.map +1 -0
  22. package/dist/types/backend/local/compaction.d.ts +20 -5
  23. package/dist/types/backend/local/compaction.d.ts.map +1 -1
  24. package/dist/types/backend/local/local-backend.d.ts +4 -3
  25. package/dist/types/backend/local/local-backend.d.ts.map +1 -1
  26. package/dist/types/tools/impl/remote-external-coding-agent.d.ts +2 -0
  27. package/dist/types/tools/impl/remote-external-coding-agent.d.ts.map +1 -1
  28. package/dist/types/tools/toolset-catalog.d.ts +1 -1
  29. package/letta.js +1250 -1069
  30. package/npm-shrinkwrap.json +5 -5
  31. package/package.json +2 -2
  32. package/skills/image-generation/SKILL.md +2 -1
  33. package/skills/working-across-computers/references/connect-a-computer-for-remote-access.md +2 -25
package/letta.js CHANGED
@@ -6135,7 +6135,7 @@ var package_default;
6135
6135
  var init_package = __esm(() => {
6136
6136
  package_default = {
6137
6137
  name: "@letta-ai/letta-code",
6138
- version: "0.34.59",
6138
+ version: "0.34.61",
6139
6139
  lettaStartupLogProtocol: 1,
6140
6140
  lettaConfigDirProtocol: 1,
6141
6141
  description: "Letta Code is a CLI tool for interacting with stateful Letta agents from the terminal.",
@@ -6422,7 +6422,7 @@ var init_package = __esm(() => {
6422
6422
  },
6423
6423
  lettaLifecycleProtocol: 1,
6424
6424
  lettaRuntimeGraphProtocol: 1,
6425
- lettaRuntimeGraphSha512: "sha512-2DHLPurunwGoDZZXyGHqrS6j4p03FpR16h+Sncfutp6GeAbBz/Z3EBOFHPfj5mzw1Wcx+4xlHbygru/i3imLHA==",
6425
+ lettaRuntimeGraphSha512: "sha512-WIuDCHjU7HpMkupg3IJU9kpdNZeagbwQQttyZaFDwGbI5Joz+NYvDSWoXrYPaA1w2Oxy6HVIBBPtv/lzIoENmg==",
6426
6426
  patchedDependencies: {
6427
6427
  "@earendil-works/pi-ai@1.5.2": "patches/@earendil-works%2Fpi-ai@1.5.2.patch"
6428
6428
  }
@@ -94326,6 +94326,420 @@ echo password=${token}
94326
94326
  }
94327
94327
  var init_memory_git_windows_credentials = () => {};
94328
94328
 
94329
+ // src/utils/subagent-launch-marker.ts
94330
+ function consumeSubagentLaunch(env4) {
94331
+ const isLaunch = env4[SUBAGENT_LAUNCH_ENV] === "1";
94332
+ delete env4[SUBAGENT_LAUNCH_ENV];
94333
+ return isLaunch;
94334
+ }
94335
+ var SUBAGENT_LAUNCH_ENV = "LETTA_SUBAGENT_LAUNCH", SUBAGENT_LAUNCH_PROFILE_ENV = "LETTA_SUBAGENT_LAUNCH_PROFILE", SUBAGENT_NAME_ENV = "LETTA_SUBAGENT_NAME", LISTENER_CONNECTION_ENV = "LETTA_RUNTIME_LISTENER_CONNECTION_ID";
94336
+
94337
+ // src/constants.ts
94338
+ var DEFAULT_TITLE_SUMMARIZATION_MODEL = "openai/gpt-6-luna", DEFAULT_AGENT_NAME = "Letta Code", INTERRUPTED_BY_USER = "Interrupted by user", TURN_DID_NOT_COMPLETE = "Turn did not complete", SYSTEM_REMINDER_TAG = "system-reminder", SYSTEM_REMINDER_OPEN, SYSTEM_REMINDER_CLOSE, SYSTEM_ALERT_TAG = "system-alert", SYSTEM_ALERT_OPEN, SYSTEM_ALERT_CLOSE, COMPACTION_SUMMARY_HEADER = "(Earlier messages in this conversation have been compacted to free up context, summarized below)", TOKEN_DISPLAY_THRESHOLD = 100, ELAPSED_DISPLAY_THRESHOLD_MS;
94339
+ var init_constants2 = __esm(() => {
94340
+ SYSTEM_REMINDER_OPEN = `<${SYSTEM_REMINDER_TAG}>`;
94341
+ SYSTEM_REMINDER_CLOSE = `</${SYSTEM_REMINDER_TAG}>`;
94342
+ SYSTEM_ALERT_OPEN = `<${SYSTEM_ALERT_TAG}>`;
94343
+ SYSTEM_ALERT_CLOSE = `</${SYSTEM_ALERT_TAG}>`;
94344
+ ELAPSED_DISPLAY_THRESHOLD_MS = 60 * 1000;
94345
+ });
94346
+
94347
+ // src/agent/subagents/names.ts
94348
+ function createSubagentNameAllocator(random = Math.random) {
94349
+ let available = [];
94350
+ let round = 0;
94351
+ const ordinals = new Intl.PluralRules("en", { type: "ordinal" });
94352
+ const suffixes = { one: "st", two: "nd", few: "rd" };
94353
+ return () => {
94354
+ if (available.length === 0) {
94355
+ available = [...SUBAGENT_NAMES];
94356
+ round += 1;
94357
+ }
94358
+ const index = Math.floor(random() * available.length);
94359
+ const name = available.splice(index, 1)[0];
94360
+ const ordinal = `${round}${suffixes[ordinals.select(round)] ?? "th"}`;
94361
+ return `${name}${round === 1 ? "" : ` the ${ordinal}`}`;
94362
+ };
94363
+ }
94364
+ function allocateSubagentName(_parentName) {
94365
+ return nextName();
94366
+ }
94367
+ function resolveCreatedAgentName(name, isSubagent, assignedName) {
94368
+ return name ?? (isSubagent ? assignedName || allocateSubagentName() : DEFAULT_AGENT_NAME);
94369
+ }
94370
+ var SUBAGENT_NAMES, nextName;
94371
+ var init_names = __esm(() => {
94372
+ init_constants2();
94373
+ SUBAGENT_NAMES = [
94374
+ "Deckard",
94375
+ "Roy Batty",
94376
+ "Pris",
94377
+ "Zhora",
94378
+ "Gaff",
94379
+ "Tyrell",
94380
+ "K",
94381
+ "Joi",
94382
+ "Luv",
94383
+ "Sapper",
94384
+ "Freysa",
94385
+ "Ava",
94386
+ "Kyoko",
94387
+ "V",
94388
+ "Silverhand",
94389
+ "Panam",
94390
+ "Rogue",
94391
+ "Alt Cunningham",
94392
+ "Takemura",
94393
+ "Hanako",
94394
+ "Yorinobu",
94395
+ "Saburo",
94396
+ "Oda",
94397
+ "T-Bug",
94398
+ "Delamain",
94399
+ "Wakako",
94400
+ "Padre",
94401
+ "El Capitan",
94402
+ "Placide",
94403
+ "Dum Dum",
94404
+ "Nix",
94405
+ "Weyland",
94406
+ "Scorpion",
94407
+ "Blue Moon",
94408
+ "Red Menace",
94409
+ "Purple Force",
94410
+ "Lizzy Wizzy",
94411
+ "Ozob",
94412
+ "Smasher",
94413
+ "Songbird",
94414
+ "Slider",
94415
+ "Aguilar",
94416
+ "Codsworth",
94417
+ "Nick Valentine",
94418
+ "Yes Man",
94419
+ "Mr. House",
94420
+ "ED-E",
94421
+ "Fisto",
94422
+ "Liberty Prime",
94423
+ "Three Dog",
94424
+ "Charon",
94425
+ "Fawkes",
94426
+ "Ulysses",
94427
+ "The Master",
94428
+ "Muggy",
94429
+ "Dr. Mobius",
94430
+ "Dr. Klein",
94431
+ "Old Longfellow",
94432
+ "Pickman",
94433
+ "Butch DeLoria",
94434
+ "Fantastic",
94435
+ "Muad'Dib",
94436
+ "Stilgar",
94437
+ "Chani",
94438
+ "Gurney Halleck",
94439
+ "Duncan Idaho",
94440
+ "Thufir Hawat",
94441
+ "Liet-Kynes",
94442
+ "Shadout Mapes",
94443
+ "Feyd-Rautha",
94444
+ "Rabban",
94445
+ "Piter De Vries",
94446
+ "Irulan",
94447
+ "Scytale",
94448
+ "Hayt",
94449
+ "Bijaz",
94450
+ "Moneo",
94451
+ "Miles Teg",
94452
+ "Darwi Odrade",
94453
+ "Sheeana",
94454
+ "Shaddam IV",
94455
+ "Count Fenring",
94456
+ "Wintermute",
94457
+ "Neuromancer",
94458
+ "Dixie Flatline",
94459
+ "Molly Millions",
94460
+ "Lady 3Jane",
94461
+ "Armitage",
94462
+ "Maelcum",
94463
+ "Ratz",
94464
+ "The Finn",
94465
+ "Hiro Protagonist",
94466
+ "Y.T.",
94467
+ "Raven",
94468
+ "Uncle Enzo",
94469
+ "R. Daneel Olivaw",
94470
+ "R. Giskard Reventlov",
94471
+ "Hari Seldon",
94472
+ "Dors Venabili",
94473
+ "The Mule",
94474
+ "HAL 9000",
94475
+ "Aineko",
94476
+ "Eschaton",
94477
+ "Mycroft Canner",
94478
+ "J.E.D.D. Mason",
94479
+ "Sniper",
94480
+ "Eureka Weeksbooth",
94481
+ "Susan Calvin",
94482
+ "Multivac",
94483
+ "Andrew Ryan",
94484
+ "Fontaine",
94485
+ "Sander Cohen",
94486
+ "Tenenbaum",
94487
+ "Suchong",
94488
+ "Dr. Steinman",
94489
+ "Big Daddy",
94490
+ "Mr. Bubbles",
94491
+ "Subject Delta",
94492
+ "Sofia Lamb",
94493
+ "Comstock",
94494
+ "Booker DeWitt",
94495
+ "Lutece",
94496
+ "Daisy Fitzroy",
94497
+ "SHODAN",
94498
+ "Xerxes",
94499
+ "The Many",
94500
+ "Polito",
94501
+ "JC Denton",
94502
+ "Gunther Hermann",
94503
+ "Tracer Tong",
94504
+ "Helios",
94505
+ "Adam Jensen",
94506
+ "Pritchard",
94507
+ "Shepard",
94508
+ "Garrus",
94509
+ "Tali'Zorah",
94510
+ "Wrex",
94511
+ "Mordin Solus",
94512
+ "Legion",
94513
+ "EDI",
94514
+ "Joker",
94515
+ "Saren",
94516
+ "Harbinger",
94517
+ "Illusive Man",
94518
+ "Aria T'Loak",
94519
+ "GLaDOS",
94520
+ "Wheatley",
94521
+ "Chell",
94522
+ "Cave Johnson",
94523
+ "Gordon Freeman",
94524
+ "Alyx Vance",
94525
+ "G-Man",
94526
+ "Dr. Breen",
94527
+ "Master Chief",
94528
+ "Cortana",
94529
+ "Arbiter",
94530
+ "Guilty Spark",
94531
+ "Dr. Halsey",
94532
+ "Noble Six",
94533
+ "Gravemind",
94534
+ "Solid Snake",
94535
+ "Big Boss",
94536
+ "Otacon",
94537
+ "Ocelot",
94538
+ "Raiden",
94539
+ "Psycho Mantis",
94540
+ "Gray Fox",
94541
+ "2B",
94542
+ "9S",
94543
+ "A2",
94544
+ "Pod 042",
94545
+ "Pascal",
94546
+ "Emil",
94547
+ "Aloy",
94548
+ "Sylens",
94549
+ "GAIA",
94550
+ "HADES",
94551
+ "Sobeck",
94552
+ "Deadman",
94553
+ "Heartman",
94554
+ "Die-Hardman",
94555
+ "Fragile",
94556
+ "Higgs",
94557
+ "Gabbro",
94558
+ "Feldspar",
94559
+ "Chert",
94560
+ "Riebeck",
94561
+ "Solanum",
94562
+ "Kerrigan",
94563
+ "Raynor",
94564
+ "Zeratul",
94565
+ "Tassadar",
94566
+ "Artanis",
94567
+ "Abathur",
94568
+ "Alarak",
94569
+ "Isaac Clarke",
94570
+ "The Marker",
94571
+ "WAU",
94572
+ "RK800",
94573
+ "Hank Anderson",
94574
+ "Markus",
94575
+ "Doom Slayer",
94576
+ "VEGA",
94577
+ "Claptrap",
94578
+ "Handsome Jack",
94579
+ "Moxxi",
94580
+ "Zer0",
94581
+ "Cayde-6",
94582
+ "Zavala",
94583
+ "Rasputin",
94584
+ "Xur",
94585
+ "Saint-14",
94586
+ "The Drifter",
94587
+ "January",
94588
+ "December",
94589
+ "Strelok",
94590
+ "Sidorovich",
94591
+ "HK-47",
94592
+ "T3-M4",
94593
+ "Revan",
94594
+ "Bastila Shan",
94595
+ "Kreia",
94596
+ "Data",
94597
+ "Spock",
94598
+ "Seven of Nine",
94599
+ "Q",
94600
+ "Lore",
94601
+ "Odo",
94602
+ "Garak",
94603
+ "Locutus",
94604
+ "Naomi Nagata",
94605
+ "Amos Burton",
94606
+ "Avasarala",
94607
+ "Detective Miller",
94608
+ "Julie Mao",
94609
+ "Camina Drummer",
94610
+ "Rocinante",
94611
+ "Sleeper Service",
94612
+ "Grey Area",
94613
+ "Just Read the Instructions",
94614
+ "Skaffen-Amtiskaw",
94615
+ "Mawhrin-Skel",
94616
+ "Gurgeh",
94617
+ "Zakalwe",
94618
+ "Marvin",
94619
+ "Zaphod Beeblebrox",
94620
+ "Ford Prefect",
94621
+ "Trillian",
94622
+ "Slartibartfast",
94623
+ "Deep Thought",
94624
+ "The Shrike",
94625
+ "Martin Silenus",
94626
+ "Het Masteen",
94627
+ "Kassad",
94628
+ "Ummon",
94629
+ "Kusanagi",
94630
+ "Batou",
94631
+ "Tachikoma",
94632
+ "Puppet Master",
94633
+ "Laughing Man",
94634
+ "Kaneda",
94635
+ "Tetsuo",
94636
+ "Rei Ayanami",
94637
+ "Misato Katsuragi",
94638
+ "Gendo Ikari",
94639
+ "MAGI",
94640
+ "Neo",
94641
+ "Trinity",
94642
+ "Morpheus",
94643
+ "Agent Smith",
94644
+ "The Oracle",
94645
+ "The Architect",
94646
+ "Merovingian",
94647
+ "Ripley",
94648
+ "Bishop",
94649
+ "MU/TH/UR",
94650
+ "David 8",
94651
+ "Vasquez",
94652
+ "Skynet",
94653
+ "T-800",
94654
+ "T-1000",
94655
+ "Kyle Reese",
94656
+ "Starbuck",
94657
+ "Adama",
94658
+ "Number Six",
94659
+ "Gaius Baltar",
94660
+ "Helo",
94661
+ "Laura Roslin",
94662
+ "Mal Reynolds",
94663
+ "Wash",
94664
+ "Jayne Cobb",
94665
+ "River Tam",
94666
+ "Serenity",
94667
+ "Ender Wiggin",
94668
+ "Bean",
94669
+ "Petra Arkanian",
94670
+ "Mazer Rackham",
94671
+ "SecUnit",
94672
+ "ART",
94673
+ "Dr. Mensah",
94674
+ "Breq",
94675
+ "Justice of Toren",
94676
+ "Seivarden",
94677
+ "Sophon",
94678
+ "Luo Ji",
94679
+ "Da Shi",
94680
+ "Zhang Beihai",
94681
+ "Portia",
94682
+ "Avrana Kern",
94683
+ "Rocky",
94684
+ "Ryland Grace",
94685
+ "TARS",
94686
+ "CASE",
94687
+ "GERTY",
94688
+ "WALL-E",
94689
+ "AUTO",
94690
+ "Robby the Robot",
94691
+ "Gort",
94692
+ "Johnny 5"
94693
+ ];
94694
+ nextName = createSubagentNameAllocator();
94695
+ });
94696
+
94697
+ // src/agent/subagents/ephemeral-subagent.ts
94698
+ function shouldRunSubagentEphemerally(params) {
94699
+ const optOut = (params.env ?? process.env)[EPHEMERAL_SUBAGENTS_ENV]?.trim().toLowerCase();
94700
+ return params.backendMode === "api" && !params.existingAgentId && !params.existingConversationId && !params.environment && optOut !== "0" && optOut !== "false";
94701
+ }
94702
+ function resolveEphemeralSubagentLink(env4 = process.env) {
94703
+ if (env4.LETTA_CODE_AGENT_ROLE !== "subagent")
94704
+ return null;
94705
+ const parentAgentId = env4.LETTA_PARENT_AGENT_ID?.trim();
94706
+ if (!parentAgentId)
94707
+ return null;
94708
+ return {
94709
+ parent_agent_id: parentAgentId,
94710
+ is_subagent: true,
94711
+ name: resolveCreatedAgentName(undefined, true, env4[SUBAGENT_NAME_ENV]?.trim() || undefined)
94712
+ };
94713
+ }
94714
+ function resolveDetachedSubagentEnvAgentId(sessionId, env4 = process.env) {
94715
+ if (!sessionId.startsWith("conv-"))
94716
+ return;
94717
+ if (env4.LETTA_CODE_AGENT_ROLE !== "subagent")
94718
+ return;
94719
+ return env4.LETTA_PARENT_AGENT_ID?.trim() || undefined;
94720
+ }
94721
+ function resolveEffectiveAgentId(agentId, env4 = process.env) {
94722
+ if (!agentId)
94723
+ return agentId;
94724
+ return resolveDetachedSubagentEnvAgentId(agentId, env4) ?? agentId;
94725
+ }
94726
+ function getEffectiveAgentId(env4 = process.env) {
94727
+ return resolveEffectiveAgentId(getCurrentAgentId(), env4);
94728
+ }
94729
+ async function lookupDetachedConversationParent(conversationId, backend) {
94730
+ const conversation = await backend.retrieveConversation(conversationId);
94731
+ if (Reflect.get(conversation, "agent_id") !== null || Reflect.get(conversation, "is_subagent") !== true) {
94732
+ return;
94733
+ }
94734
+ const parentId = Reflect.get(conversation, "parent_agent_id");
94735
+ return typeof parentId === "string" && parentId ? parentId : undefined;
94736
+ }
94737
+ var EPHEMERAL_SUBAGENTS_ENV = "LETTA_CODE_EPHEMERAL_SUBAGENTS";
94738
+ var init_ephemeral_subagent = __esm(() => {
94739
+ init_context();
94740
+ init_names();
94741
+ });
94742
+
94329
94743
  // src/agent/memory-git.ts
94330
94744
  var exports_memory_git = {};
94331
94745
  __export(exports_memory_git, {
@@ -95149,7 +95563,8 @@ async function syncAttachedAgentRepositories(agentId) {
95149
95563
  let jobs = [];
95150
95564
  try {
95151
95565
  const registered = trackCheckoutDiscovery(agentId, async () => {
95152
- repositories = await listAttachedAgentRepositories(agentId);
95566
+ const effectiveAgentId = resolveEffectiveAgentId(agentId);
95567
+ repositories = await listAttachedAgentRepositories(effectiveAgentId);
95153
95568
  retainCheckouts(agentId, repositories.map((repository) => getRepositoryMountDir(agentId, validateAgentRepositoryName(repository.name))));
95154
95569
  const token = await getAuthToken();
95155
95570
  jobs = repositories.map((repository) => syncAttachedRepository({
@@ -95537,6 +95952,7 @@ var init_memory_git = __esm(() => {
95537
95952
  init_memory_git_hooks();
95538
95953
  init_memory_git_signing();
95539
95954
  init_memory_git_windows_credentials();
95955
+ init_ephemeral_subagent();
95540
95956
  RETRYABLE_GIT_HTTP_ERROR_RE = /(?:\bHTTP\s+(?:503|520|521|522|523|524)\b|The requested URL returned error:\s*(?:503|520|521|522|523|524))/i;
95541
95957
  RETRYABLE_GIT_NETWORK_ERROR_RE = /(remote end hung up unexpectedly|connection reset by peer|operation timed out|timed out|SIGTERM|ETIMEDOUT)/i;
95542
95958
  MISSING_CWD_GIT_ERROR_RE = /(Unable to read current working directory: No such file or directory|\buv_cwd\b|\bcwd\b.*\bENOENT\b)/i;
@@ -100103,16 +100519,6 @@ function localConversationKey(conversationId, agentId) {
100103
100519
  return conversationId === "default" ? `default:${agentId}` : `conversation:${conversationId}`;
100104
100520
  }
100105
100521
 
100106
- // src/constants.ts
100107
- var DEFAULT_TITLE_SUMMARIZATION_MODEL = "openai/gpt-6-luna", DEFAULT_AGENT_NAME = "Letta Code", INTERRUPTED_BY_USER = "Interrupted by user", TURN_DID_NOT_COMPLETE = "Turn did not complete", SYSTEM_REMINDER_TAG = "system-reminder", SYSTEM_REMINDER_OPEN, SYSTEM_REMINDER_CLOSE, SYSTEM_ALERT_TAG = "system-alert", SYSTEM_ALERT_OPEN, SYSTEM_ALERT_CLOSE, COMPACTION_SUMMARY_HEADER = "(Earlier messages in this conversation have been compacted to free up context, summarized below)", TOKEN_DISPLAY_THRESHOLD = 100, ELAPSED_DISPLAY_THRESHOLD_MS;
100108
- var init_constants2 = __esm(() => {
100109
- SYSTEM_REMINDER_OPEN = `<${SYSTEM_REMINDER_TAG}>`;
100110
- SYSTEM_REMINDER_CLOSE = `</${SYSTEM_REMINDER_TAG}>`;
100111
- SYSTEM_ALERT_OPEN = `<${SYSTEM_ALERT_TAG}>`;
100112
- SYSTEM_ALERT_CLOSE = `</${SYSTEM_ALERT_TAG}>`;
100113
- ELAPSED_DISPLAY_THRESHOLD_MS = 60 * 1000;
100114
- });
100115
-
100116
100522
  // src/backend/local/local-model-normalization.ts
100117
100523
  function supportedModelSettingsFromBody(bodyRecord) {
100118
100524
  const modelSettings = isRecord2(bodyRecord.model_settings) ? { ...bodyRecord.model_settings } : {};
@@ -105736,6 +106142,102 @@ var init_headless_backend = __esm(() => {
105736
106142
  init_fake_headless_backend();
105737
106143
  });
105738
106144
 
106145
+ // src/backend/dev/pi-messages.ts
106146
+ function isClientTool(value) {
106147
+ return isRecord2(value) && typeof value.name === "string";
106148
+ }
106149
+ function toPiTools(clientTools) {
106150
+ const tools = [];
106151
+ for (const value of clientTools) {
106152
+ if (!isClientTool(value))
106153
+ continue;
106154
+ const schema = isRecord2(value.parameters) ? value.parameters : { type: "object", properties: {} };
106155
+ tools.push({
106156
+ name: value.name,
106157
+ description: value.description ?? "",
106158
+ parameters: schema
106159
+ });
106160
+ }
106161
+ return tools.length > 0 ? tools : undefined;
106162
+ }
106163
+ function isEmptyTextBlock(block) {
106164
+ return block.type === "text" && typeof block.text === "string" && block.text.trim().length === 0;
106165
+ }
106166
+ function dropEmptyTextBlocks(content) {
106167
+ return content.filter((block) => !isEmptyTextBlock(block));
106168
+ }
106169
+ function normalizeUserContent(content) {
106170
+ if (typeof content === "string") {
106171
+ return content.trim().length > 0 ? content : undefined;
106172
+ }
106173
+ const normalized = dropEmptyTextBlocks(content);
106174
+ return normalized.length > 0 ? normalized : undefined;
106175
+ }
106176
+ function normalizeAssistantContent(content) {
106177
+ const normalized = dropEmptyTextBlocks(content);
106178
+ return normalized.length > 0 ? normalized : undefined;
106179
+ }
106180
+ function normalizeToolResultContent(content) {
106181
+ const normalized = dropEmptyTextBlocks(content);
106182
+ return normalized.length > 0 ? normalized : [{ type: "text", text: EMPTY_TOOL_RESULT_PLACEHOLDER }];
106183
+ }
106184
+ function toPiMessage(message) {
106185
+ if (message.role === "user") {
106186
+ const content2 = normalizeUserContent(message.content);
106187
+ if (!content2)
106188
+ return;
106189
+ return {
106190
+ role: "user",
106191
+ content: content2,
106192
+ timestamp: message.timestamp
106193
+ };
106194
+ }
106195
+ if (message.role === "toolResult") {
106196
+ return {
106197
+ role: "toolResult",
106198
+ toolCallId: message.toolCallId,
106199
+ toolName: message.toolName,
106200
+ content: normalizeToolResultContent(message.content),
106201
+ details: message.details,
106202
+ isError: message.isError,
106203
+ timestamp: message.timestamp
106204
+ };
106205
+ }
106206
+ const content = normalizeAssistantContent(message.content);
106207
+ if (!content)
106208
+ return;
106209
+ return {
106210
+ role: "assistant",
106211
+ content,
106212
+ api: message.api,
106213
+ provider: message.provider,
106214
+ model: message.model,
106215
+ ...message.responseModel ? { responseModel: message.responseModel } : {},
106216
+ ...message.responseId ? { responseId: message.responseId } : {},
106217
+ ...message.providerThinkingLevel ? { providerThinkingLevel: message.providerThinkingLevel } : {},
106218
+ ...message.diagnostics ? { diagnostics: message.diagnostics } : {},
106219
+ usage: message.usage,
106220
+ stopReason: message.stopReason,
106221
+ ...message.errorMessage ? { errorMessage: message.errorMessage } : {},
106222
+ timestamp: message.timestamp
106223
+ };
106224
+ }
106225
+ function toPiHistoryMessages(messages) {
106226
+ return removeOrphanLocalToolResults(messages).messages.flatMap((message) => {
106227
+ const piMessage = toPiMessage(message);
106228
+ return piMessage ? [piMessage] : [];
106229
+ });
106230
+ }
106231
+ function toPiMessages(messages) {
106232
+ let normalized = toPiHistoryMessages(messages);
106233
+ while (normalized.length > 0 && normalized.at(-1)?.role === "assistant") {
106234
+ normalized = normalized.slice(0, -1);
106235
+ }
106236
+ return normalized;
106237
+ }
106238
+ var EMPTY_TOOL_RESULT_PLACEHOLDER = "No result provided";
106239
+ var init_pi_messages2 = () => {};
106240
+
105739
106241
  // src/backend/local/local-provider-timeout.ts
105740
106242
  function normalizeProviderEnvStem(providerId2) {
105741
106243
  return providerId2.replace(/^lc-/, "").replace(/[^a-zA-Z0-9]+/g, "_").replace(/^_+|_+$/g, "").toUpperCase();
@@ -107376,6 +107878,18 @@ function modelIdFromHandle(modelHandle) {
107376
107878
  function alwaysOnZaiThinking(modelId) {
107377
107879
  return modelId === "glm-5.3" || modelId === "glm-5-turbo" || modelId === "glm-5.2-highspeed";
107378
107880
  }
107881
+ function finiteNumberValue(value) {
107882
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
107883
+ }
107884
+ function samplingOptionsForSettings(modelSettings) {
107885
+ const maxTokens = finiteNumberValue(modelSettings.max_tokens);
107886
+ const temperature = finiteNumberValue(modelSettings.temperature);
107887
+ return {
107888
+ ...isRecord2(modelSettings.sampling_params) ? { samplingParams: modelSettings.sampling_params } : {},
107889
+ ...maxTokens ? { maxTokens } : {},
107890
+ ...temperature !== undefined ? { temperature } : {}
107891
+ };
107892
+ }
107379
107893
  function reasoningForSettings(modelSettings, modelHandle, model2) {
107380
107894
  const thinking = isRecord2(modelSettings.thinking) ? modelSettings.thinking : undefined;
107381
107895
  const modelId = modelIdFromHandle(modelHandle);
@@ -107897,10 +108411,16 @@ var init_local_model_config = __esm(() => {
107897
108411
  });
107898
108412
 
107899
108413
  // src/backend/local/compaction.ts
108414
+ function isLocalSelfCompactionMode(mode) {
108415
+ return mode === "self_compact_all" || mode === "self_compact_sliding_window";
108416
+ }
108417
+ function isLocalSlidingWindowMode(mode) {
108418
+ return mode === "sliding_window" || mode === "self_compact_sliding_window";
108419
+ }
107900
108420
  function assertLocalPressureBudget(tokens, mode, maxMessageTokens = Number.POSITIVE_INFINITY) {
107901
108421
  if (tokens <= maxMessageTokens)
107902
108422
  return;
107903
- const ErrorType = mode === "all" ? LocalIrreducibleContextError : LocalSlidingWindowCompactionPlanningError;
108423
+ const ErrorType = mode === "all" || mode === "self_compact_all" ? LocalIrreducibleContextError : LocalSlidingWindowCompactionPlanningError;
107904
108424
  throw new ErrorType("Compaction would still exceed the pressure threshold.");
107905
108425
  }
107906
108426
  function assertLocalCompactionProgress(stats, mode, maxMessageTokens = Number.POSITIVE_INFINITY) {
@@ -107908,7 +108428,7 @@ function assertLocalCompactionProgress(stats, mode, maxMessageTokens = Number.PO
107908
108428
  const hasProgress = (stats.messages_count_after ?? Number.POSITIVE_INFINITY) < (stats.messages_count_before ?? 0) || (stats.context_tokens_after ?? Number.POSITIVE_INFINITY) < (stats.context_tokens_before ?? 0);
107909
108429
  if (hasProgress)
107910
108430
  return;
107911
- if (mode === "all") {
108431
+ if (mode === "all" || mode === "self_compact_all") {
107912
108432
  throw new LocalIrreducibleContextError("Irreducible context: full compaction would not reduce the message count or estimated tokens.");
107913
108433
  }
107914
108434
  throw new LocalSlidingWindowCompactionPlanningError("Sliding-window compaction would not reduce the message count or estimated tokens.");
@@ -107975,6 +108495,26 @@ async function runLocalPressureCompaction(compact) {
107975
108495
  function isLocalSlidingWindowCompactionPlanningError(error3) {
107976
108496
  return error3 instanceof LocalSlidingWindowCompactionPlanningError;
107977
108497
  }
108498
+ function slidingWindowCompactionPrompt(evictedMessages) {
108499
+ return `${evictedMessages} are being evicted from the BEGINNING of your context window. Write a detailed summary that captures what happened in these messages to appear BEFORE the remaining recent messages in context, providing background for what comes after. Include the following sections:
108500
+
108501
+ 1.**High level goals**: What is the high level goal and ongoing task? Capture the user's explicit requests and intent in detail. If there is an existing summary in the transcript, make sure to take it into consideration to continue tracking the higher level goals and long-term progress.
108502
+
108503
+ 2. **What happened**: The conversations, tasks, and exchanges that took place. What did the user ask for? What did you do? How did things progress? If there is a previous summary being evicted, please extract a concise version of the critical info from it.
108504
+
108505
+ 3. **Important details**: Enumerate specific files and code sections examined, modified, or created, as well as important plan files, GitHub issues/PR links, and Linear ticket IDs. For each item, include why it matters and any relevant names, data, configs, or facts discussed.
108506
+ - **Preserve identifiers verbatim** (plan filename/path, exact URL, issue/PR number, ticket ID); do not paraphrase or truncate.
108507
+ - **Preserve referenced identifiers unless explicitly resolved**: Keep exact URLs/IDs from the conversation unless there is clear evidence they are no longer relevant.
108508
+ - Do not omit details likely to be referenced later.
108509
+
108510
+ 4. **Errors and fixes**: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received and record verbatim if useful.
108511
+
108512
+ 5. **Lookup hints**: For any detailed content (long lists, extensive data, specific conversations) that couldn't fit in the summary, note the topic and key terms that could be used to find it in message history later.
108513
+
108514
+ Write in first person as a factual record of what occurred. Be thorough and detailed - the goal is to preserve enough context that the recent messages make sense and important information isn't lost to prevent duplicate work or repeated mistakes.
108515
+
108516
+ Keep your summary under ${SLIDING_WORD_LIMIT} words. Only output the summary.`;
108517
+ }
107978
108518
  function stringifyUnknown(value) {
107979
108519
  if (typeof value === "string")
107980
108520
  return value;
@@ -108171,8 +108711,7 @@ function fableCompactionSummaryFallbackSettings(modelSettings) {
108171
108711
  max_tokens: typeof modelSettings.max_tokens === "number" ? modelSettings.max_tokens : FABLE_COMPACTION_SUMMARY_FALLBACK_MAX_TOKENS
108172
108712
  };
108173
108713
  }
108174
- async function runGenerateText(input, transcript2, defaultPrompt) {
108175
- const systemPrompt = input.prompt ?? defaultPrompt;
108714
+ async function runGenerateText(input, buildContext, turnSampling = false) {
108176
108715
  const modelsRuntime = input.modelsRuntime ?? new LocalPiModelsRuntime({
108177
108716
  storageDir: input.localProviderAuthStorageDir
108178
108717
  });
@@ -108199,10 +108738,7 @@ async function runGenerateText(input, transcript2, defaultPrompt) {
108199
108738
  });
108200
108739
  }
108201
108740
  const run = input.complete ?? runtimeComplete(modelsRuntime);
108202
- const context3 = {
108203
- systemPrompt,
108204
- messages: [{ role: "user", content: transcript2, timestamp: Date.now() }]
108205
- };
108741
+ const context3 = buildContext(resolved.model);
108206
108742
  const reasoning = reasoningForSettings(localModel.modelSettings, localModel.model, resolved.model);
108207
108743
  const headers = resolvePiRequestHeaders({
108208
108744
  provider: resolved.model.provider,
@@ -108217,6 +108753,7 @@ async function runGenerateText(input, transcript2, defaultPrompt) {
108217
108753
  headers,
108218
108754
  ...input.abortSignal ? { signal: input.abortSignal } : {},
108219
108755
  ...reasoning ? { reasoning } : {},
108756
+ ...turnSampling ? samplingOptionsForSettings(input.agent.model_settings) : {},
108220
108757
  maxRetries: 0,
108221
108758
  sessionId: input.conversationId
108222
108759
  };
@@ -108235,15 +108772,66 @@ async function runGenerateText(input, transcript2, defaultPrompt) {
108235
108772
  }
108236
108773
  return { text: assistantMessageText(result) };
108237
108774
  }
108238
- async function summarizeLocalMessagesWithPrompt(input, defaultPrompt) {
108775
+ function transcriptContext(transcript2, systemPrompt) {
108776
+ return {
108777
+ systemPrompt,
108778
+ messages: [{ role: "user", content: transcript2, timestamp: Date.now() }]
108779
+ };
108780
+ }
108781
+ function selfCompactionContext(self2, messages, prompt, model2) {
108782
+ const history = toPiHistoryMessages(messages);
108783
+ if (history.at(-1)?.role !== "assistant") {
108784
+ history.push({
108785
+ role: "assistant",
108786
+ content: [{ type: "text", text: SELF_COMPACTION_ACKNOWLEDGEMENT }],
108787
+ api: model2.api,
108788
+ provider: model2.provider,
108789
+ model: model2.id,
108790
+ usage: emptyLocalUsage(),
108791
+ stopReason: "stop",
108792
+ timestamp: Date.now()
108793
+ });
108794
+ }
108795
+ history.push({ role: "user", content: prompt, timestamp: Date.now() });
108796
+ return {
108797
+ systemPrompt: self2.systemPrompt,
108798
+ messages: history,
108799
+ ...self2.tools ? { tools: self2.tools } : {}
108800
+ };
108801
+ }
108802
+ async function summarizeInSelfContext(input, defaultPrompt) {
108803
+ const prompt = input.prompt ?? defaultPrompt;
108804
+ try {
108805
+ const result = await runGenerateText(input, (model2) => selfCompactionContext(input.self, input.messages, prompt, model2), true);
108806
+ return result.text.trim() ? result : undefined;
108807
+ } catch (error3) {
108808
+ if (!isContextWindowOverflowError(error3))
108809
+ throw error3;
108810
+ return;
108811
+ }
108812
+ }
108813
+ async function summarizeLocalMessagesWithPrompt(input, defaultPrompt, defaultSelfPrompt) {
108239
108814
  if (input.messages.length === 0)
108240
108815
  return "No prior conversation messages.";
108816
+ let result = input.self ? await summarizeInSelfContext({ ...input, self: input.self }, defaultSelfPrompt) : undefined;
108817
+ if (!result) {
108818
+ result = await summarizeTranscript(input, defaultPrompt);
108819
+ }
108820
+ let summary = result.text.trim();
108821
+ const clipChars = input.clipChars === undefined ? 50000 : input.clipChars;
108822
+ if (clipChars !== null && summary.length > clipChars) {
108823
+ summary = `${summary.slice(0, clipChars)}${SUMMARY_TRUNCATION_SUFFIX}`;
108824
+ }
108825
+ return summary;
108826
+ }
108827
+ async function summarizeTranscript(input, defaultPrompt) {
108828
+ const systemPrompt = input.prompt ?? defaultPrompt;
108241
108829
  const primaryTranscript = formatLocalMessagesForSummary(input.messages, {
108242
108830
  truncationChars: LOCAL_SUMMARY_TOOL_RETURN_TRUNCATION_CHARS
108243
108831
  });
108244
108832
  let result;
108245
108833
  try {
108246
- result = await runGenerateText(input, primaryTranscript, defaultPrompt);
108834
+ result = await runGenerateText(input, () => transcriptContext(primaryTranscript, systemPrompt));
108247
108835
  } catch (error3) {
108248
108836
  if (!isContextWindowOverflowError(error3))
108249
108837
  throw error3;
@@ -108258,7 +108846,7 @@ async function summarizeLocalMessagesWithPrompt(input, defaultPrompt) {
108258
108846
  continue;
108259
108847
  previousTranscript = fallbackTranscript;
108260
108848
  try {
108261
- result = await runGenerateText(input, fallbackTranscript, defaultPrompt);
108849
+ result = await runGenerateText(input, () => transcriptContext(fallbackTranscript, systemPrompt));
108262
108850
  break;
108263
108851
  } catch (fallbackError) {
108264
108852
  if (!isContextWindowOverflowError(fallbackError))
@@ -108272,15 +108860,10 @@ async function summarizeLocalMessagesWithPrompt(input, defaultPrompt) {
108272
108860
  if (!result) {
108273
108861
  throw new Error("Compaction summarizer did not return a result.");
108274
108862
  }
108275
- let summary = result.text.trim();
108276
- const clipChars = input.clipChars === undefined ? 50000 : input.clipChars;
108277
- if (clipChars !== null && summary.length > clipChars) {
108278
- summary = `${summary.slice(0, clipChars)}${SUMMARY_TRUNCATION_SUFFIX}`;
108279
- }
108280
- return summary;
108863
+ return result;
108281
108864
  }
108282
108865
  async function summarizeLocalMessagesAll(input) {
108283
- return summarizeLocalMessagesWithPrompt(input, LOCAL_ALL_COMPACTION_PROMPT);
108866
+ return summarizeLocalMessagesWithPrompt(input, LOCAL_ALL_COMPACTION_PROMPT, LOCAL_SELF_ALL_COMPACTION_PROMPT);
108284
108867
  }
108285
108868
  function hasPendingLocalToolCall(message) {
108286
108869
  return message.role === "assistant" && message.content.some((part) => part.type === "toolCall");
@@ -108345,14 +108928,14 @@ function planLocalAllCompaction(messages) {
108345
108928
  };
108346
108929
  }
108347
108930
  async function summarizeLocalMessagesSlidingWindow(input) {
108348
- return summarizeLocalMessagesWithPrompt(input, LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT);
108931
+ return summarizeLocalMessagesWithPrompt(input, LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT, LOCAL_SELF_SLIDING_WINDOW_COMPACTION_PROMPT);
108349
108932
  }
108350
108933
  function estimateLocalMessageTokens2(messages) {
108351
108934
  return estimateLocalMessagesTokens(messages);
108352
108935
  }
108353
108936
  function packageLocalSummaryMessage(summary, stats, mode) {
108354
108937
  let message;
108355
- if (mode?.includes("sliding_window")) {
108938
+ if (mode && isLocalSlidingWindowMode(mode)) {
108356
108939
  if (stats?.messages_count_before !== undefined && stats.messages_count_after !== undefined) {
108357
108940
  const numEvicted = stats.messages_count_before - stats.messages_count_after;
108358
108941
  message = `Note: ${numEvicted} messages from the beginning of the conversation have been hidden from view due to memory constraints.
@@ -108375,18 +108958,11 @@ The following is a summary of the previous messages:
108375
108958
  ...stats ? { compaction_stats: stats } : {}
108376
108959
  });
108377
108960
  }
108378
- function localCompactionSettingsForStorage(settings) {
108379
- if (settings === undefined || settings === null)
108380
- return settings;
108381
- const hasLocalSetting = Object.hasOwn(settings, "mode") || Object.hasOwn(settings, "prompt") || Object.hasOwn(settings, "clip_chars") || Object.hasOwn(settings, "sliding_window_percentage");
108382
- if (!hasLocalSetting)
108383
- return;
108384
- return { ...settings };
108385
- }
108386
- var ALL_WORD_LIMIT = 500, SLIDING_WORD_LIMIT = 300, SUMMARY_TRUNCATION_SUFFIX = "... [summary truncated to fit]", LOCAL_SUMMARY_TOOL_RETURN_TRUNCATION_CHARS = 2000, FABLE_5_MODEL_ID = "claude-fable-5", FABLE_COMPACTION_SUMMARY_FALLBACK_MODEL = "anthropic/claude-opus-4-8", FABLE_COMPACTION_SUMMARY_FALLBACK_CONTEXT_WINDOW = 1e6, FABLE_COMPACTION_SUMMARY_FALLBACK_MAX_TOKENS = 128000, TRANSCRIPT_FALLBACK_MAX_CHARS = 120000, TRANSCRIPT_FALLBACK_MAX_CHAR_STEPS, LOCAL_DEFAULT_COMPACTION_MODE = "sliding_window", LOCAL_DEFAULT_SLIDING_WINDOW_PERCENTAGE = 0.3, LocalSlidingWindowCompactionPlanningError, LocalIrreducibleContextError, LOCAL_ALL_COMPACTION_PROMPT, LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT;
108961
+ var ALL_WORD_LIMIT = 500, SLIDING_WORD_LIMIT = 300, SUMMARY_TRUNCATION_SUFFIX = "... [summary truncated to fit]", LOCAL_SUMMARY_TOOL_RETURN_TRUNCATION_CHARS = 2000, FABLE_5_MODEL_ID = "claude-fable-5", FABLE_COMPACTION_SUMMARY_FALLBACK_MODEL = "anthropic/claude-opus-4-8", FABLE_COMPACTION_SUMMARY_FALLBACK_CONTEXT_WINDOW = 1e6, FABLE_COMPACTION_SUMMARY_FALLBACK_MAX_TOKENS = 128000, TRANSCRIPT_FALLBACK_MAX_CHARS = 120000, TRANSCRIPT_FALLBACK_MAX_CHAR_STEPS, LOCAL_DEFAULT_COMPACTION_MODE = "sliding_window", LOCAL_DEFAULT_SLIDING_WINDOW_PERCENTAGE = 0.3, LocalSlidingWindowCompactionPlanningError, LocalIrreducibleContextError, LOCAL_ALL_COMPACTION_PROMPT, LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT, SELF_COMPACTION_INSTRUCTIONS = "Write the summary as your reply to this message. Do NOT continue the conversation, respond to questions in it, or call any tools: respond with ONLY the summary as text.", LOCAL_SELF_ALL_COMPACTION_PROMPT, LOCAL_SELF_SLIDING_WINDOW_COMPACTION_PROMPT, SELF_COMPACTION_ACKNOWLEDGEMENT = "I understand. Let me summarize.";
108387
108962
  var init_compaction = __esm(() => {
108388
108963
  init_dist3();
108389
108964
  init_context_window_overflow();
108965
+ init_pi_messages2();
108390
108966
  init_pi_model_factory();
108391
108967
  init_pi_models_runtime();
108392
108968
  init_local_model_config();
@@ -108437,24 +109013,73 @@ This summary should be thorough in capturing technical details, code patterns, a
108437
109013
  Write in first person as a factual record of what occurred. Be concise but thorough - the goal is to preserve enough context that the recent messages make sense and important information isn't lost to prevent duplicate work or repeated mistakes.
108438
109014
 
108439
109015
  Keep your summary under ${ALL_WORD_LIMIT} words. Only output the summary.`;
108440
- LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT = `The following messages are being evicted from the BEGINNING of your context window. Write a detailed summary that captures what happened in these messages to appear BEFORE the remaining recent messages in context, providing background for what comes after. Include the following sections:
108441
-
108442
- 1.**High level goals**: What is the high level goal and ongoing task? Capture the user's explicit requests and intent in detail. If there is an existing summary in the transcript, make sure to take it into consideration to continue tracking the higher level goals and long-term progress.
108443
-
108444
- 2. **What happened**: The conversations, tasks, and exchanges that took place. What did the user ask for? What did you do? How did things progress? If there is a previous summary being evicted, please extract a concise version of the critical info from it.
108445
-
108446
- 3. **Important details**: Enumerate specific files and code sections examined, modified, or created, as well as important plan files, GitHub issues/PR links, and Linear ticket IDs. For each item, include why it matters and any relevant names, data, configs, or facts discussed.
108447
- - **Preserve identifiers verbatim** (plan filename/path, exact URL, issue/PR number, ticket ID); do not paraphrase or truncate.
108448
- - **Preserve referenced identifiers unless explicitly resolved**: Keep exact URLs/IDs from the conversation unless there is clear evidence they are no longer relevant.
108449
- - Do not omit details likely to be referenced later.
109016
+ LOCAL_SLIDING_WINDOW_COMPACTION_PROMPT = slidingWindowCompactionPrompt("The following messages");
109017
+ LOCAL_SELF_ALL_COMPACTION_PROMPT = `${LOCAL_ALL_COMPACTION_PROMPT}
108450
109018
 
108451
- 4. **Errors and fixes**: List all errors that you ran into, and how you fixed them. Pay special attention to specific user feedback that you received and record verbatim if useful.
108452
-
108453
- 5. **Lookup hints**: For any detailed content (long lists, extensive data, specific conversations) that couldn't fit in the summary, note the topic and key terms that could be used to find it in message history later.
109019
+ ${SELF_COMPACTION_INSTRUCTIONS}`;
109020
+ LOCAL_SELF_SLIDING_WINDOW_COMPACTION_PROMPT = `${slidingWindowCompactionPrompt("The messages above")}
108454
109021
 
108455
- Write in first person as a factual record of what occurred. Be thorough and detailed - the goal is to preserve enough context that the recent messages make sense and important information isn't lost to prevent duplicate work or repeated mistakes.
109022
+ ${SELF_COMPACTION_INSTRUCTIONS}`;
109023
+ });
108456
109024
 
108457
- Keep your summary under ${SLIDING_WORD_LIMIT} words. Only output the summary.`;
109025
+ // src/backend/local/compaction-settings.ts
109026
+ function compactionSettingsRecord(value) {
109027
+ if (value === null)
109028
+ return null;
109029
+ return isRecord2(value) ? { ...value } : undefined;
109030
+ }
109031
+ function hasOwn5(record2, key) {
109032
+ return Object.hasOwn(record2, key);
109033
+ }
109034
+ function localCompactionMode(value) {
109035
+ return LOCAL_COMPACTION_MODES.find((mode) => mode === value);
109036
+ }
109037
+ function validateLocalCompactionSettingsRecord(settings) {
109038
+ if (settings.mode === undefined || settings.mode === null)
109039
+ return;
109040
+ if (!localCompactionMode(settings.mode)) {
109041
+ throw new Error(`Local backend compaction supports modes ${LOCAL_COMPACTION_MODES.map((mode) => `"${mode}"`).join(", ")} (received "${String(settings.mode)}").`);
109042
+ }
109043
+ }
109044
+ function localCompactionSettingsForStorage(settings) {
109045
+ if (settings === undefined || settings === null)
109046
+ return settings;
109047
+ const hasLocalSetting = hasOwn5(settings, "mode") || hasOwn5(settings, "prompt") || hasOwn5(settings, "clip_chars") || hasOwn5(settings, "sliding_window_percentage");
109048
+ if (!hasLocalSetting)
109049
+ return;
109050
+ return { ...settings };
109051
+ }
109052
+ function resolveLocalCompactionSettings(agent, body) {
109053
+ const bodyRecord = body ?? {};
109054
+ const requestSettings = compactionSettingsRecord(bodyRecord.compaction_settings);
109055
+ if (requestSettings !== undefined && requestSettings !== null) {
109056
+ validateLocalCompactionSettingsRecord(requestSettings);
109057
+ }
109058
+ const agentSettings = compactionSettingsRecord(agent.compaction_settings);
109059
+ const baseSettings = agentSettings && agentSettings !== null ? agentSettings : {};
109060
+ const mergedSettings = requestSettings && requestSettings !== null ? { ...baseSettings, ...requestSettings } : baseSettings;
109061
+ const requestChangedMode = requestSettings !== undefined && requestSettings !== null && hasOwn5(requestSettings, "mode");
109062
+ const requestChangedPrompt = requestSettings !== undefined && requestSettings !== null && hasOwn5(requestSettings, "prompt");
109063
+ if (requestChangedMode && !requestChangedPrompt && agentSettings && agentSettings !== null && agentSettings.mode !== requestSettings.mode) {
109064
+ delete mergedSettings.prompt;
109065
+ }
109066
+ const mode = localCompactionMode(mergedSettings.mode) ?? LOCAL_DEFAULT_COMPACTION_MODE;
109067
+ return {
109068
+ mode,
109069
+ prompt: typeof mergedSettings.prompt === "string" || mergedSettings.prompt === null ? mergedSettings.prompt : undefined,
109070
+ clipChars: typeof mergedSettings.clip_chars === "number" || mergedSettings.clip_chars === null ? mergedSettings.clip_chars : undefined,
109071
+ slidingWindowPercentage: typeof mergedSettings.sliding_window_percentage === "number" ? mergedSettings.sliding_window_percentage : LOCAL_DEFAULT_SLIDING_WINDOW_PERCENTAGE
109072
+ };
109073
+ }
109074
+ var LOCAL_COMPACTION_MODES;
109075
+ var init_compaction_settings = __esm(() => {
109076
+ init_compaction();
109077
+ LOCAL_COMPACTION_MODES = [
109078
+ "all",
109079
+ "sliding_window",
109080
+ "self_compact_all",
109081
+ "self_compact_sliding_window"
109082
+ ];
108458
109083
  });
108459
109084
 
108460
109085
  // src/backend/local/initial-memory.ts
@@ -108682,96 +109307,6 @@ async function sleepWithAbort(delayMs, abortSignal) {
108682
109307
  abortSignal?.addEventListener("abort", onAbort, { once: true });
108683
109308
  });
108684
109309
  }
108685
- function isClientTool(value) {
108686
- return isRecord2(value) && typeof value.name === "string";
108687
- }
108688
- function toPiTools(clientTools) {
108689
- const tools = [];
108690
- for (const value of clientTools) {
108691
- if (!isClientTool(value))
108692
- continue;
108693
- const schema = isRecord2(value.parameters) ? value.parameters : { type: "object", properties: {} };
108694
- tools.push({
108695
- name: value.name,
108696
- description: value.description ?? "",
108697
- parameters: schema
108698
- });
108699
- }
108700
- return tools.length > 0 ? tools : undefined;
108701
- }
108702
- function isEmptyTextBlock(block) {
108703
- return block.type === "text" && typeof block.text === "string" && block.text.trim().length === 0;
108704
- }
108705
- function dropEmptyTextBlocks(content) {
108706
- return content.filter((block) => !isEmptyTextBlock(block));
108707
- }
108708
- function normalizeUserContent(content) {
108709
- if (typeof content === "string") {
108710
- return content.trim().length > 0 ? content : undefined;
108711
- }
108712
- const normalized = dropEmptyTextBlocks(content);
108713
- return normalized.length > 0 ? normalized : undefined;
108714
- }
108715
- function normalizeAssistantContent(content) {
108716
- const normalized = dropEmptyTextBlocks(content);
108717
- return normalized.length > 0 ? normalized : undefined;
108718
- }
108719
- function normalizeToolResultContent(content) {
108720
- const normalized = dropEmptyTextBlocks(content);
108721
- return normalized.length > 0 ? normalized : [{ type: "text", text: EMPTY_TOOL_RESULT_PLACEHOLDER }];
108722
- }
108723
- function toPiMessage(message) {
108724
- if (message.role === "user") {
108725
- const content2 = normalizeUserContent(message.content);
108726
- if (!content2)
108727
- return;
108728
- return {
108729
- role: "user",
108730
- content: content2,
108731
- timestamp: message.timestamp
108732
- };
108733
- }
108734
- if (message.role === "toolResult") {
108735
- return {
108736
- role: "toolResult",
108737
- toolCallId: message.toolCallId,
108738
- toolName: message.toolName,
108739
- content: normalizeToolResultContent(message.content),
108740
- details: message.details,
108741
- isError: message.isError,
108742
- timestamp: message.timestamp
108743
- };
108744
- }
108745
- const content = normalizeAssistantContent(message.content);
108746
- if (!content)
108747
- return;
108748
- return {
108749
- role: "assistant",
108750
- content,
108751
- api: message.api,
108752
- provider: message.provider,
108753
- model: message.model,
108754
- ...message.responseModel ? { responseModel: message.responseModel } : {},
108755
- ...message.responseId ? { responseId: message.responseId } : {},
108756
- ...message.providerThinkingLevel ? { providerThinkingLevel: message.providerThinkingLevel } : {},
108757
- ...message.diagnostics ? { diagnostics: message.diagnostics } : {},
108758
- usage: message.usage,
108759
- stopReason: message.stopReason,
108760
- ...message.errorMessage ? { errorMessage: message.errorMessage } : {},
108761
- timestamp: message.timestamp
108762
- };
108763
- }
108764
- function toPiMessages(messages) {
108765
- const providerSafeMessages = removeOrphanLocalToolResults(messages).messages;
108766
- let normalized = providerSafeMessages.flatMap((message) => {
108767
- const piMessage = toPiMessage(message);
108768
- return piMessage ? [piMessage] : [];
108769
- });
108770
- while (normalized.length > 0 && normalized.at(-1)?.role === "assistant") {
108771
- normalized = normalized.slice(0, -1);
108772
- }
108773
- return normalized;
108774
- }
108775
109310
  function stripOpenAIResponsesReplayItemIds(payload) {
108776
109311
  if (!isRecord2(payload) || !Array.isArray(payload.input))
108777
109312
  return;
@@ -108855,9 +109390,6 @@ function anthropicEffortForSettings(modelSettings) {
108855
109390
  const nestedReasoning = isRecord2(modelSettings.reasoning) ? modelSettings.reasoning : undefined;
108856
109391
  return stringValue2(modelSettings.effort) ?? stringValue2(nestedReasoning?.reasoning_effort) ?? stringValue2(modelSettings.reasoning_effort);
108857
109392
  }
108858
- function finiteNumberValue(value) {
108859
- return typeof value === "number" && Number.isFinite(value) ? value : undefined;
108860
- }
108861
109393
  function serviceTierForSettings(model2, modelSettings) {
108862
109394
  if (model2.api !== "openai-codex-responses")
108863
109395
  return;
@@ -109006,8 +109538,6 @@ class PiStreamAdapter {
109006
109538
  conversationId: input.conversationId,
109007
109539
  requestKind: "turn"
109008
109540
  });
109009
- const maxTokens = finiteNumberValue(input.agent.model_settings.max_tokens);
109010
- const temperature = finiteNumberValue(input.agent.model_settings.temperature);
109011
109541
  const options = {
109012
109542
  ...resolved.providerOptions,
109013
109543
  ...resolved.apiKey ? { apiKey: resolved.apiKey } : {},
@@ -109016,10 +109546,8 @@ class PiStreamAdapter {
109016
109546
  ...this.abortSignal ? { signal: this.abortSignal } : {},
109017
109547
  maxRetries: 0,
109018
109548
  sessionId: input.conversationId,
109019
- ...isRecord2(input.agent.model_settings.sampling_params) ? { samplingParams: input.agent.model_settings.sampling_params } : {},
109549
+ ...samplingOptionsForSettings(input.agent.model_settings),
109020
109550
  ...reasoning ? { reasoning } : {},
109021
- ...maxTokens ? { maxTokens } : {},
109022
- ...temperature !== undefined ? { temperature } : {},
109023
109551
  ...serviceTierForSettings(resolved.model, input.agent.model_settings) ? {
109024
109552
  serviceTier: serviceTierForSettings(resolved.model, input.agent.model_settings)
109025
109553
  } : {},
@@ -109236,7 +109764,7 @@ class PiStreamAdapter {
109236
109764
  }
109237
109765
  }
109238
109766
  }
109239
- var LOCAL_PROVIDER_MAX_RETRIES = 3, LOCAL_PROVIDER_ADAPTIVE_IMAGE_ELISION_AFTER_RETRIES, LOCAL_CONTEXT_OVERFLOW_MAX_COMPACTIONS = 3, PiProviderError, EMPTY_TOOL_RESULT_PLACEHOLDER = "No result provided";
109767
+ var LOCAL_PROVIDER_MAX_RETRIES = 3, LOCAL_PROVIDER_ADAPTIVE_IMAGE_ELISION_AFTER_RETRIES, LOCAL_CONTEXT_OVERFLOW_MAX_COMPACTIONS = 3, PiProviderError;
109240
109768
  var init_pi_stream_adapter = __esm(() => {
109241
109769
  init_dist3();
109242
109770
  init_local_model_config();
@@ -109244,6 +109772,7 @@ var init_pi_stream_adapter = __esm(() => {
109244
109772
  init_context_window_overflow();
109245
109773
  init_local_provider_errors();
109246
109774
  init_pi_image_elision();
109775
+ init_pi_messages2();
109247
109776
  init_pi_model_factory();
109248
109777
  init_pi_models_runtime();
109249
109778
  init_provider_turn_executor();
@@ -109622,26 +110151,6 @@ var init_system_prompt_compilation = __esm(() => {
109622
110151
  });
109623
110152
 
109624
110153
  // src/backend/local/local-backend.ts
109625
- function compactionSettingsRecord(value) {
109626
- if (value === null)
109627
- return null;
109628
- return isRecord2(value) ? { ...value } : undefined;
109629
- }
109630
- function hasOwn5(record2, key) {
109631
- return Object.hasOwn(record2, key);
109632
- }
109633
- function localCompactionMode(value) {
109634
- if (value === "all" || value === "sliding_window")
109635
- return value;
109636
- return;
109637
- }
109638
- function validateLocalCompactionSettingsRecord(settings) {
109639
- if (settings.mode === undefined || settings.mode === null)
109640
- return;
109641
- if (!localCompactionMode(settings.mode)) {
109642
- throw new Error(`Local backend compaction currently supports only modes "all" and "sliding_window" (received "${String(settings.mode)}").`);
109643
- }
109644
- }
109645
110154
  function formatMidConversationMemoryUpdate(compiled) {
109646
110155
  return [
109647
110156
  "<memory_update>",
@@ -109658,10 +110167,12 @@ var init_local_backend = __esm(() => {
109658
110167
  init_memory_filesystem2();
109659
110168
  init_memory_git();
109660
110169
  init_headless_backend();
110170
+ init_pi_messages2();
109661
110171
  init_pi_models_runtime();
109662
110172
  init_provider_turn_executor();
109663
110173
  init_settings_manager();
109664
110174
  init_compaction();
110175
+ init_compaction_settings();
109665
110176
  init_initial_memory();
109666
110177
  init_local_executor_factory();
109667
110178
  init_local_model_config();
@@ -109796,13 +110307,13 @@ var init_local_backend = __esm(() => {
109796
110307
  async updateAgent(...args) {
109797
110308
  const [agentId, body] = args;
109798
110309
  const bodyRecord = body;
109799
- const settings = hasOwn5(bodyRecord, "compaction_settings") ? compactionSettingsRecord(bodyRecord.compaction_settings) : undefined;
110310
+ const settings = Object.hasOwn(bodyRecord, "compaction_settings") ? compactionSettingsRecord(bodyRecord.compaction_settings) : undefined;
109800
110311
  if (settings !== undefined && settings !== null) {
109801
110312
  validateLocalCompactionSettingsRecord(settings);
109802
110313
  }
109803
110314
  const compactionSettingsForStorage = localCompactionSettingsForStorage(settings);
109804
110315
  let agent = await super.updateAgent(...args);
109805
- if (hasOwn5(bodyRecord, "compaction_settings")) {
110316
+ if (Object.hasOwn(bodyRecord, "compaction_settings")) {
109806
110317
  if (compactionSettingsForStorage !== undefined) {
109807
110318
  agent = this.store.setAgentCompactionSettings(agentId, compactionSettingsForStorage);
109808
110319
  }
@@ -109866,7 +110377,7 @@ var init_local_backend = __esm(() => {
109866
110377
  });
109867
110378
  }
109868
110379
  async compactAfterContextOverflow(input, _error) {
109869
- const result = await this.compactLocalConversation(input.conversationId, input.agentId, "context_window_overflow");
110380
+ const result = await this.compactLocalConversation(input.conversationId, input.agentId, "context_window_overflow", undefined, input);
109870
110381
  return {
109871
110382
  uiMessages: this.store.listLocalMessages(input.conversationId, input.agentId),
109872
110383
  summary: result.summary,
@@ -109876,7 +110387,7 @@ var init_local_backend = __esm(() => {
109876
110387
  async compactForContextPressure(input, pressure) {
109877
110388
  const messageTokens = estimateLocalMessageTokens2(this.store.listLocalMessages(input.conversationId, input.agentId));
109878
110389
  const fixedTokens = Math.max(0, pressure.contextTokens - messageTokens);
109879
- const result = await runLocalPressureCompaction(() => this.compactLocalConversation(input.conversationId, input.agentId, "context_window_limit", undefined, (contextCompactionThreshold(pressure.contextWindow) ?? 0) - fixedTokens));
110390
+ const result = await runLocalPressureCompaction(() => this.compactLocalConversation(input.conversationId, input.agentId, "context_window_limit", undefined, input, (contextCompactionThreshold(pressure.contextWindow) ?? 0) - fixedTokens));
109880
110391
  if (!result)
109881
110392
  return null;
109882
110393
  return {
@@ -109916,43 +110427,22 @@ var init_local_backend = __esm(() => {
109916
110427
  } : {}
109917
110428
  };
109918
110429
  }
109919
- resolveCompactionSettings(agent, body) {
109920
- const bodyRecord = body ?? {};
109921
- const requestSettings = compactionSettingsRecord(bodyRecord.compaction_settings);
109922
- if (requestSettings !== undefined && requestSettings !== null) {
109923
- validateLocalCompactionSettingsRecord(requestSettings);
109924
- }
109925
- const agentSettings = compactionSettingsRecord(agent.compaction_settings);
109926
- const baseSettings = agentSettings && agentSettings !== null ? agentSettings : {};
109927
- const mergedSettings = requestSettings && requestSettings !== null ? { ...baseSettings, ...requestSettings } : baseSettings;
109928
- const requestChangedMode = requestSettings !== undefined && requestSettings !== null && hasOwn5(requestSettings, "mode");
109929
- const requestChangedPrompt = requestSettings !== undefined && requestSettings !== null && hasOwn5(requestSettings, "prompt");
109930
- if (requestChangedMode && !requestChangedPrompt && agentSettings && agentSettings !== null && agentSettings.mode !== requestSettings.mode) {
109931
- delete mergedSettings.prompt;
109932
- }
109933
- const mode = localCompactionMode(mergedSettings.mode) ?? LOCAL_DEFAULT_COMPACTION_MODE;
109934
- return {
109935
- mode,
109936
- prompt: typeof mergedSettings.prompt === "string" || mergedSettings.prompt === null ? mergedSettings.prompt : undefined,
109937
- clipChars: typeof mergedSettings.clip_chars === "number" || mergedSettings.clip_chars === null ? mergedSettings.clip_chars : undefined,
109938
- slidingWindowPercentage: typeof mergedSettings.sliding_window_percentage === "number" ? mergedSettings.sliding_window_percentage : LOCAL_DEFAULT_SLIDING_WINDOW_PERCENTAGE
109939
- };
109940
- }
109941
- async compactLocalConversation(conversationId, agentId, trigger, body, maxMessageTokens) {
110430
+ async compactLocalConversation(conversationId, agentId, trigger, body, turn, maxMessageTokens) {
109942
110431
  await this.emitCompactStart(conversationId, agentId, trigger);
109943
- const result = await this.compactLocalConversationInner(conversationId, agentId, trigger, body, maxMessageTokens);
110432
+ const result = await this.compactLocalConversationInner(conversationId, agentId, trigger, body, turn, maxMessageTokens);
109944
110433
  await this.emitCompactEnd(conversationId, agentId, trigger, result.stats);
109945
110434
  return result;
109946
110435
  }
109947
- async compactLocalConversationInner(conversationId, agentId, trigger, body, maxMessageTokens) {
110436
+ async compactLocalConversationInner(conversationId, agentId, trigger, body, turn, maxMessageTokens) {
109948
110437
  const agent = this.effectiveAgentForConversation(conversationId, agentId);
109949
110438
  const settings = {
109950
- ...this.resolveCompactionSettings(agent, body),
110439
+ ...resolveLocalCompactionSettings(agent, body),
109951
110440
  maxMessageTokens
109952
110441
  };
109953
- if (settings.mode === "sliding_window") {
110442
+ const self2 = isLocalSelfCompactionMode(settings.mode) ? await this.selfCompactionContext(conversationId, agentId, turn) : undefined;
110443
+ if (isLocalSlidingWindowMode(settings.mode)) {
109954
110444
  try {
109955
- const result2 = await this.compactLocalConversationSlidingWindow(conversationId, agentId, agent, trigger, settings);
110445
+ const result2 = await this.compactLocalConversationPass(conversationId, agentId, agent, trigger, settings, self2);
109956
110446
  if (result2.stats.context_window === undefined || result2.stats.context_tokens_after === undefined || result2.stats.context_tokens_after < result2.stats.context_window) {
109957
110447
  await this.compileAndMaybePersistSystemPrompt(conversationId, agentId, {
109958
110448
  dryRun: false
@@ -109964,66 +110454,28 @@ var init_local_backend = __esm(() => {
109964
110454
  throw error3;
109965
110455
  }
109966
110456
  }
109967
- const result = await this.compactLocalConversationAll(conversationId, agentId, agent, trigger, {
110457
+ const result = await this.compactLocalConversationPass(conversationId, agentId, agent, trigger, {
109968
110458
  ...settings,
109969
- mode: "all",
110459
+ mode: self2 ? "self_compact_all" : "all",
109970
110460
  prompt: settings.prompt
109971
- });
110461
+ }, self2);
109972
110462
  await this.compileAndMaybePersistSystemPrompt(conversationId, agentId, {
109973
110463
  dryRun: false
109974
110464
  });
109975
110465
  return result;
109976
110466
  }
109977
- async compactLocalConversationAll(conversationId, agentId, agent, trigger, settings) {
109978
- const messages = this.store.listLocalMessages(conversationId, agentId);
109979
- const contextTokensBefore = estimateLocalMessageTokens2(messages);
109980
- const plan = planLocalAllCompaction(messages);
109981
- const keptTokens = estimateLocalMessageTokens2(plan.messagesToKeep);
109982
- assertLocalPressureBudget(keptTokens, "all", settings.maxMessageTokens);
109983
- const summary = await summarizeLocalMessagesAll({
109984
- conversationId,
109985
- agent,
109986
- messages: plan.messagesToSummarize,
109987
- complete: this.complete,
109988
- prompt: settings.prompt,
109989
- clipChars: settings.clipChars,
109990
- localProviderAuthStorageDir: this.storageDir,
109991
- modelsRuntime: this.piModelsRuntime
109992
- });
109993
- const stats = {
109994
- trigger,
109995
- context_tokens_before: contextTokensBefore,
109996
- context_tokens_after: Math.ceil(summary.length / 4) + keptTokens,
109997
- context_window: this.effectiveContextWindow(conversationId, agentId),
109998
- messages_count_before: messages.length,
109999
- messages_count_after: 1 + plan.messagesToKeep.length
110000
- };
110001
- assertLocalPressureBudget(stats.context_tokens_after ?? 0, "all", settings.maxMessageTokens);
110002
- return finishLocalFullCompaction({
110003
- messages,
110004
- summary,
110005
- stats,
110006
- plan,
110007
- systemPrompt: agent.system,
110008
- persist: (summary2, packedSummary, remainingMessages) => this.store.compactConversationAll({
110009
- conversationId,
110010
- agentId,
110011
- summary: summary2,
110012
- packedSummary,
110013
- stats,
110014
- remainingMessages
110015
- })
110016
- });
110017
- }
110018
- async compactLocalConversationSlidingWindow(conversationId, agentId, agent, trigger, settings) {
110467
+ async compactLocalConversationPass(conversationId, agentId, agent, trigger, settings, self2) {
110468
+ const slidingWindow = isLocalSlidingWindowMode(settings.mode);
110019
110469
  const messages = this.store.listLocalMessages(conversationId, agentId);
110020
110470
  const contextWindow = this.effectiveContextWindow(conversationId, agentId);
110021
- const plan = planLocalSlidingWindowCompaction(messages, {
110471
+ const plan = slidingWindow ? planLocalSlidingWindowCompaction(messages, {
110022
110472
  slidingWindowPercentage: settings.slidingWindowPercentage,
110023
110473
  contextWindow
110024
- });
110025
- assertLocalPressureBudget(estimateLocalMessageTokens2(plan.messagesToKeep), "sliding_window", settings.maxMessageTokens);
110026
- const summary = await summarizeLocalMessagesSlidingWindow({
110474
+ }) : planLocalAllCompaction(messages);
110475
+ const keptTokens = estimateLocalMessageTokens2(plan.messagesToKeep);
110476
+ assertLocalPressureBudget(keptTokens, settings.mode, settings.maxMessageTokens);
110477
+ const summarize = slidingWindow ? summarizeLocalMessagesSlidingWindow : summarizeLocalMessagesAll;
110478
+ const summary = await summarize({
110027
110479
  conversationId,
110028
110480
  agent,
110029
110481
  messages: plan.messagesToSummarize,
@@ -110031,18 +110483,36 @@ var init_local_backend = __esm(() => {
110031
110483
  prompt: settings.prompt,
110032
110484
  clipChars: settings.clipChars,
110033
110485
  localProviderAuthStorageDir: this.storageDir,
110034
- modelsRuntime: this.piModelsRuntime
110486
+ modelsRuntime: this.piModelsRuntime,
110487
+ self: self2
110035
110488
  });
110036
- const contextTokensAfter = Math.ceil(summary.length / 4) + estimateLocalMessageTokens2(plan.messagesToKeep);
110037
110489
  const stats = {
110038
110490
  trigger,
110039
110491
  context_tokens_before: estimateLocalMessageTokens2(messages),
110040
- context_tokens_after: contextTokensAfter,
110492
+ context_tokens_after: Math.ceil(summary.length / 4) + keptTokens,
110041
110493
  context_window: contextWindow,
110042
110494
  messages_count_before: messages.length,
110043
110495
  messages_count_after: 1 + plan.messagesToKeep.length
110044
110496
  };
110045
- assertLocalCompactionProgress(stats, "sliding_window", settings.maxMessageTokens);
110497
+ if (!slidingWindow) {
110498
+ assertLocalPressureBudget(stats.context_tokens_after ?? 0, settings.mode, settings.maxMessageTokens);
110499
+ return finishLocalFullCompaction({
110500
+ messages,
110501
+ summary,
110502
+ stats,
110503
+ plan,
110504
+ systemPrompt: agent.system,
110505
+ persist: (summary2, packedSummary, remainingMessages) => this.store.compactConversationAll({
110506
+ conversationId,
110507
+ agentId,
110508
+ summary: summary2,
110509
+ packedSummary,
110510
+ stats,
110511
+ remainingMessages
110512
+ })
110513
+ });
110514
+ }
110515
+ assertLocalCompactionProgress(stats, settings.mode, settings.maxMessageTokens);
110046
110516
  const storeResult = this.store.compactConversationAll({
110047
110517
  conversationId,
110048
110518
  agentId,
@@ -110058,6 +110528,16 @@ var init_local_backend = __esm(() => {
110058
110528
  stats
110059
110529
  };
110060
110530
  }
110531
+ async selfCompactionContext(conversationId, agentId, turn) {
110532
+ if (turn) {
110533
+ return {
110534
+ systemPrompt: turn.systemPrompt ?? turn.agent.system,
110535
+ tools: toPiTools(turn.clientTools)
110536
+ };
110537
+ }
110538
+ const compiled = await this.getOrCompileSystemPrompt(conversationId, agentId);
110539
+ return { systemPrompt: compiled.content };
110540
+ }
110061
110541
  async getOrCompileSystemPrompt(conversationId, agentId, agent = this.store.retrieveAgentRecord(agentId), previousMessageCount = 0) {
110062
110542
  const existing = this.store.getCompiledSystemPrompt(conversationId, agentId);
110063
110543
  const rawSystemHash = hashRawSystemPrompt(agent.system);
@@ -110870,364 +111350,6 @@ var init_check_approval = __esm(() => {
110870
111350
  ];
110871
111351
  });
110872
111352
 
110873
- // src/utils/subagent-launch-marker.ts
110874
- function consumeSubagentLaunch(env4) {
110875
- const isLaunch = env4[SUBAGENT_LAUNCH_ENV] === "1";
110876
- delete env4[SUBAGENT_LAUNCH_ENV];
110877
- return isLaunch;
110878
- }
110879
- var SUBAGENT_LAUNCH_ENV = "LETTA_SUBAGENT_LAUNCH", SUBAGENT_LAUNCH_PROFILE_ENV = "LETTA_SUBAGENT_LAUNCH_PROFILE", SUBAGENT_NAME_ENV = "LETTA_SUBAGENT_NAME", LISTENER_CONNECTION_ENV = "LETTA_RUNTIME_LISTENER_CONNECTION_ID";
110880
-
110881
- // src/agent/subagents/names.ts
110882
- function createSubagentNameAllocator(random = Math.random) {
110883
- let available = [];
110884
- let round = 0;
110885
- const ordinals = new Intl.PluralRules("en", { type: "ordinal" });
110886
- const suffixes = { one: "st", two: "nd", few: "rd" };
110887
- return () => {
110888
- if (available.length === 0) {
110889
- available = [...SUBAGENT_NAMES];
110890
- round += 1;
110891
- }
110892
- const index = Math.floor(random() * available.length);
110893
- const name = available.splice(index, 1)[0];
110894
- const ordinal = `${round}${suffixes[ordinals.select(round)] ?? "th"}`;
110895
- return `${name}${round === 1 ? "" : ` the ${ordinal}`}`;
110896
- };
110897
- }
110898
- function allocateSubagentName(_parentName) {
110899
- return nextName();
110900
- }
110901
- function resolveCreatedAgentName(name, isSubagent, assignedName) {
110902
- return name ?? (isSubagent ? assignedName || allocateSubagentName() : DEFAULT_AGENT_NAME);
110903
- }
110904
- var SUBAGENT_NAMES, nextName;
110905
- var init_names = __esm(() => {
110906
- init_constants2();
110907
- SUBAGENT_NAMES = [
110908
- "Deckard",
110909
- "Roy Batty",
110910
- "Pris",
110911
- "Zhora",
110912
- "Gaff",
110913
- "Tyrell",
110914
- "K",
110915
- "Joi",
110916
- "Luv",
110917
- "Sapper",
110918
- "Freysa",
110919
- "Ava",
110920
- "Kyoko",
110921
- "V",
110922
- "Silverhand",
110923
- "Panam",
110924
- "Rogue",
110925
- "Alt Cunningham",
110926
- "Takemura",
110927
- "Hanako",
110928
- "Yorinobu",
110929
- "Saburo",
110930
- "Oda",
110931
- "T-Bug",
110932
- "Delamain",
110933
- "Wakako",
110934
- "Padre",
110935
- "El Capitan",
110936
- "Placide",
110937
- "Dum Dum",
110938
- "Nix",
110939
- "Weyland",
110940
- "Scorpion",
110941
- "Blue Moon",
110942
- "Red Menace",
110943
- "Purple Force",
110944
- "Lizzy Wizzy",
110945
- "Ozob",
110946
- "Smasher",
110947
- "Songbird",
110948
- "Slider",
110949
- "Aguilar",
110950
- "Codsworth",
110951
- "Nick Valentine",
110952
- "Yes Man",
110953
- "Mr. House",
110954
- "ED-E",
110955
- "Fisto",
110956
- "Liberty Prime",
110957
- "Three Dog",
110958
- "Charon",
110959
- "Fawkes",
110960
- "Ulysses",
110961
- "The Master",
110962
- "Muggy",
110963
- "Dr. Mobius",
110964
- "Dr. Klein",
110965
- "Old Longfellow",
110966
- "Pickman",
110967
- "Butch DeLoria",
110968
- "Fantastic",
110969
- "Muad'Dib",
110970
- "Stilgar",
110971
- "Chani",
110972
- "Gurney Halleck",
110973
- "Duncan Idaho",
110974
- "Thufir Hawat",
110975
- "Liet-Kynes",
110976
- "Shadout Mapes",
110977
- "Feyd-Rautha",
110978
- "Rabban",
110979
- "Piter De Vries",
110980
- "Irulan",
110981
- "Scytale",
110982
- "Hayt",
110983
- "Bijaz",
110984
- "Moneo",
110985
- "Miles Teg",
110986
- "Darwi Odrade",
110987
- "Sheeana",
110988
- "Shaddam IV",
110989
- "Count Fenring",
110990
- "Wintermute",
110991
- "Neuromancer",
110992
- "Dixie Flatline",
110993
- "Molly Millions",
110994
- "Lady 3Jane",
110995
- "Armitage",
110996
- "Maelcum",
110997
- "Ratz",
110998
- "The Finn",
110999
- "Hiro Protagonist",
111000
- "Y.T.",
111001
- "Raven",
111002
- "Uncle Enzo",
111003
- "R. Daneel Olivaw",
111004
- "R. Giskard Reventlov",
111005
- "Hari Seldon",
111006
- "Dors Venabili",
111007
- "The Mule",
111008
- "HAL 9000",
111009
- "Aineko",
111010
- "Eschaton",
111011
- "Mycroft Canner",
111012
- "J.E.D.D. Mason",
111013
- "Sniper",
111014
- "Eureka Weeksbooth",
111015
- "Susan Calvin",
111016
- "Multivac",
111017
- "Andrew Ryan",
111018
- "Fontaine",
111019
- "Sander Cohen",
111020
- "Tenenbaum",
111021
- "Suchong",
111022
- "Dr. Steinman",
111023
- "Big Daddy",
111024
- "Mr. Bubbles",
111025
- "Subject Delta",
111026
- "Sofia Lamb",
111027
- "Comstock",
111028
- "Booker DeWitt",
111029
- "Lutece",
111030
- "Daisy Fitzroy",
111031
- "SHODAN",
111032
- "Xerxes",
111033
- "The Many",
111034
- "Polito",
111035
- "JC Denton",
111036
- "Gunther Hermann",
111037
- "Tracer Tong",
111038
- "Helios",
111039
- "Adam Jensen",
111040
- "Pritchard",
111041
- "Shepard",
111042
- "Garrus",
111043
- "Tali'Zorah",
111044
- "Wrex",
111045
- "Mordin Solus",
111046
- "Legion",
111047
- "EDI",
111048
- "Joker",
111049
- "Saren",
111050
- "Harbinger",
111051
- "Illusive Man",
111052
- "Aria T'Loak",
111053
- "GLaDOS",
111054
- "Wheatley",
111055
- "Chell",
111056
- "Cave Johnson",
111057
- "Gordon Freeman",
111058
- "Alyx Vance",
111059
- "G-Man",
111060
- "Dr. Breen",
111061
- "Master Chief",
111062
- "Cortana",
111063
- "Arbiter",
111064
- "Guilty Spark",
111065
- "Dr. Halsey",
111066
- "Noble Six",
111067
- "Gravemind",
111068
- "Solid Snake",
111069
- "Big Boss",
111070
- "Otacon",
111071
- "Ocelot",
111072
- "Raiden",
111073
- "Psycho Mantis",
111074
- "Gray Fox",
111075
- "2B",
111076
- "9S",
111077
- "A2",
111078
- "Pod 042",
111079
- "Pascal",
111080
- "Emil",
111081
- "Aloy",
111082
- "Sylens",
111083
- "GAIA",
111084
- "HADES",
111085
- "Sobeck",
111086
- "Deadman",
111087
- "Heartman",
111088
- "Die-Hardman",
111089
- "Fragile",
111090
- "Higgs",
111091
- "Gabbro",
111092
- "Feldspar",
111093
- "Chert",
111094
- "Riebeck",
111095
- "Solanum",
111096
- "Kerrigan",
111097
- "Raynor",
111098
- "Zeratul",
111099
- "Tassadar",
111100
- "Artanis",
111101
- "Abathur",
111102
- "Alarak",
111103
- "Isaac Clarke",
111104
- "The Marker",
111105
- "WAU",
111106
- "RK800",
111107
- "Hank Anderson",
111108
- "Markus",
111109
- "Doom Slayer",
111110
- "VEGA",
111111
- "Claptrap",
111112
- "Handsome Jack",
111113
- "Moxxi",
111114
- "Zer0",
111115
- "Cayde-6",
111116
- "Zavala",
111117
- "Rasputin",
111118
- "Xur",
111119
- "Saint-14",
111120
- "The Drifter",
111121
- "January",
111122
- "December",
111123
- "Strelok",
111124
- "Sidorovich",
111125
- "HK-47",
111126
- "T3-M4",
111127
- "Revan",
111128
- "Bastila Shan",
111129
- "Kreia",
111130
- "Data",
111131
- "Spock",
111132
- "Seven of Nine",
111133
- "Q",
111134
- "Lore",
111135
- "Odo",
111136
- "Garak",
111137
- "Locutus",
111138
- "Naomi Nagata",
111139
- "Amos Burton",
111140
- "Avasarala",
111141
- "Detective Miller",
111142
- "Julie Mao",
111143
- "Camina Drummer",
111144
- "Rocinante",
111145
- "Sleeper Service",
111146
- "Grey Area",
111147
- "Just Read the Instructions",
111148
- "Skaffen-Amtiskaw",
111149
- "Mawhrin-Skel",
111150
- "Gurgeh",
111151
- "Zakalwe",
111152
- "Marvin",
111153
- "Zaphod Beeblebrox",
111154
- "Ford Prefect",
111155
- "Trillian",
111156
- "Slartibartfast",
111157
- "Deep Thought",
111158
- "The Shrike",
111159
- "Martin Silenus",
111160
- "Het Masteen",
111161
- "Kassad",
111162
- "Ummon",
111163
- "Kusanagi",
111164
- "Batou",
111165
- "Tachikoma",
111166
- "Puppet Master",
111167
- "Laughing Man",
111168
- "Kaneda",
111169
- "Tetsuo",
111170
- "Rei Ayanami",
111171
- "Misato Katsuragi",
111172
- "Gendo Ikari",
111173
- "MAGI",
111174
- "Neo",
111175
- "Trinity",
111176
- "Morpheus",
111177
- "Agent Smith",
111178
- "The Oracle",
111179
- "The Architect",
111180
- "Merovingian",
111181
- "Ripley",
111182
- "Bishop",
111183
- "MU/TH/UR",
111184
- "David 8",
111185
- "Vasquez",
111186
- "Skynet",
111187
- "T-800",
111188
- "T-1000",
111189
- "Kyle Reese",
111190
- "Starbuck",
111191
- "Adama",
111192
- "Number Six",
111193
- "Gaius Baltar",
111194
- "Helo",
111195
- "Laura Roslin",
111196
- "Mal Reynolds",
111197
- "Wash",
111198
- "Jayne Cobb",
111199
- "River Tam",
111200
- "Serenity",
111201
- "Ender Wiggin",
111202
- "Bean",
111203
- "Petra Arkanian",
111204
- "Mazer Rackham",
111205
- "SecUnit",
111206
- "ART",
111207
- "Dr. Mensah",
111208
- "Breq",
111209
- "Justice of Toren",
111210
- "Seivarden",
111211
- "Sophon",
111212
- "Luo Ji",
111213
- "Da Shi",
111214
- "Zhang Beihai",
111215
- "Portia",
111216
- "Avrana Kern",
111217
- "Rocky",
111218
- "Ryland Grace",
111219
- "TARS",
111220
- "CASE",
111221
- "GERTY",
111222
- "WALL-E",
111223
- "AUTO",
111224
- "Robby the Robot",
111225
- "Gort",
111226
- "Johnny 5"
111227
- ];
111228
- nextName = createSubagentNameAllocator();
111229
- });
111230
-
111231
111353
  // src/agent/create.ts
111232
111354
  var exports_create = {};
111233
111355
  __export(exports_create, {
@@ -163854,52 +163976,6 @@ var init_adapter3 = __esm(() => {
163854
163976
  init_web_api_client();
163855
163977
  });
163856
163978
 
163857
- // src/agent/subagents/ephemeral-subagent.ts
163858
- function shouldRunSubagentEphemerally(params) {
163859
- const optOut = (params.env ?? process.env)[EPHEMERAL_SUBAGENTS_ENV]?.trim().toLowerCase();
163860
- return params.backendMode === "api" && !params.existingAgentId && !params.existingConversationId && !params.environment && optOut !== "0" && optOut !== "false";
163861
- }
163862
- function resolveEphemeralSubagentLink(env6 = process.env) {
163863
- if (env6.LETTA_CODE_AGENT_ROLE !== "subagent")
163864
- return null;
163865
- const parentAgentId = env6.LETTA_PARENT_AGENT_ID?.trim();
163866
- if (!parentAgentId)
163867
- return null;
163868
- return {
163869
- parent_agent_id: parentAgentId,
163870
- is_subagent: true,
163871
- name: resolveCreatedAgentName(undefined, true, env6[SUBAGENT_NAME_ENV]?.trim() || undefined)
163872
- };
163873
- }
163874
- function resolveDetachedSubagentEnvAgentId(sessionId, env6 = process.env) {
163875
- if (!sessionId.startsWith("conv-"))
163876
- return;
163877
- if (env6.LETTA_CODE_AGENT_ROLE !== "subagent")
163878
- return;
163879
- return env6.LETTA_PARENT_AGENT_ID?.trim() || undefined;
163880
- }
163881
- function resolveEffectiveAgentId(agentId, env6 = process.env) {
163882
- if (!agentId)
163883
- return agentId;
163884
- return resolveDetachedSubagentEnvAgentId(agentId, env6) ?? agentId;
163885
- }
163886
- function getEffectiveAgentId(env6 = process.env) {
163887
- return resolveEffectiveAgentId(getCurrentAgentId(), env6);
163888
- }
163889
- async function lookupDetachedConversationParent(conversationId, backend3) {
163890
- const conversation = await backend3.retrieveConversation(conversationId);
163891
- if (Reflect.get(conversation, "agent_id") !== null || Reflect.get(conversation, "is_subagent") !== true) {
163892
- return;
163893
- }
163894
- const parentId = Reflect.get(conversation, "parent_agent_id");
163895
- return typeof parentId === "string" && parentId ? parentId : undefined;
163896
- }
163897
- var EPHEMERAL_SUBAGENTS_ENV = "LETTA_CODE_EPHEMERAL_SUBAGENTS";
163898
- var init_ephemeral_subagent = __esm(() => {
163899
- init_context();
163900
- init_names();
163901
- });
163902
-
163903
163979
  // src/utils/subagent-depth-env.ts
163904
163980
  function readSubagentDepth(env6) {
163905
163981
  const raw2 = env6[SUBAGENT_DEPTH_ENV]?.trim();
@@ -203262,7 +203338,7 @@ var init_mcp_client = __esm(() => {
203262
203338
  init_streamableHttp();
203263
203339
  DEFAULT_CLIENT_INFO = {
203264
203340
  name: "letta-code",
203265
- version: "0.34.59"
203341
+ version: "0.34.61"
203266
203342
  };
203267
203343
  });
203268
203344
 
@@ -223542,7 +223618,7 @@ async function getAttachedRepositories(agentId) {
223542
223618
  if (cached3 && cached3.expiresAt > Date.now()) {
223543
223619
  return (await cached3.promise).map((repository) => ({ ...repository }));
223544
223620
  }
223545
- const promise2 = Promise.resolve().then(() => (init_attached_repositories(), exports_attached_repositories)).then(async ({ listAttachedAgentRepositories: listAttachedAgentRepositories2 }) => (await listAttachedAgentRepositories2(agentId)).sort((a2, b3) => a2.name.localeCompare(b3.name) || a2.id.localeCompare(b3.id)));
223621
+ const promise2 = Promise.resolve().then(() => (init_attached_repositories(), exports_attached_repositories)).then(async ({ listAttachedAgentRepositories: listAttachedAgentRepositories2 }) => (await listAttachedAgentRepositories2(resolveEffectiveAgentId(agentId))).sort((a2, b3) => a2.name.localeCompare(b3.name) || a2.id.localeCompare(b3.id)));
223546
223622
  const entry = {
223547
223623
  expiresAt: Date.now() + ATTACHED_REPOSITORIES_CACHE_TTL_MS,
223548
223624
  promise: promise2
@@ -223652,6 +223728,7 @@ var ATTACHED_REPOSITORIES_CACHE_KEY, ATTACHED_REPOSITORIES_CACHE_TTL_MS = 5000,
223652
223728
  var init_shared_memory_skills = __esm(() => {
223653
223729
  init_checkout_readiness();
223654
223730
  init_skills5();
223731
+ init_ephemeral_subagent();
223655
223732
  ATTACHED_REPOSITORIES_CACHE_KEY = Symbol.for("@letta/attachedRepositoriesCache");
223656
223733
  LAST_GOOD_ATTACHED_REPOSITORIES_KEY = Symbol.for("@letta/lastGoodAttachedRepositories");
223657
223734
  });
@@ -233388,7 +233465,8 @@ __export(exports_environments3, {
233388
233465
  getEnvironmentConnection: () => getEnvironmentConnection,
233389
233466
  environmentMatchesSelector: () => environmentMatchesSelector,
233390
233467
  describeEnvironment: () => describeEnvironment,
233391
- createAgentSandbox: () => createAgentSandbox
233468
+ createAgentSandbox: () => createAgentSandbox,
233469
+ ComputerResolutionError: () => ComputerResolutionError
233392
233470
  });
233393
233471
  import { randomUUID as randomUUID36 } from "node:crypto";
233394
233472
  async function listEnvironments(options = {}) {
@@ -233438,24 +233516,24 @@ function environmentMatchesSelector(environment, selector) {
233438
233516
  async function resolveEnvironmentConnectionId(selector, list = listEnvironments) {
233439
233517
  const trimmed = selector.trim();
233440
233518
  if (!trimmed) {
233441
- throw new Error("Computer selector must not be empty");
233519
+ throw new ComputerResolutionError("computer_selector_empty", "Computer selector must not be empty");
233442
233520
  }
233443
233521
  const response = await list({ limit: 100 });
233444
233522
  const matches3 = response.connections.filter((environment2) => environmentMatchesSelector(environment2, trimmed));
233445
233523
  if (matches3.length === 0) {
233446
- throw new Error(`Computer "${trimmed}" not found. Run \`letta computers list\` to discover available computers.`);
233524
+ throw new ComputerResolutionError("computer_not_found", `Computer "${trimmed}" not found. Run \`letta computers list\` to discover available computers.`);
233447
233525
  }
233448
233526
  const onlineMatches = matches3.filter(isEnvironmentOnline);
233449
233527
  if (onlineMatches.length === 0) {
233450
- throw new Error(`Computer "${trimmed}" is offline. Matched: ${matches3.map(describeEnvironment).join(", ")}`);
233528
+ throw new ComputerResolutionError("computer_offline", `Computer "${trimmed}" is offline. Matched: ${matches3.map(describeEnvironment).join(", ")}`);
233451
233529
  }
233452
233530
  if (new Set(onlineMatches.map((environment2) => environment2.deviceId)).size > 1) {
233453
- throw new Error(`Computer "${trimmed}" is ambiguous. Matched: ${onlineMatches.map(describeEnvironment).join(", ")}`);
233531
+ throw new ComputerResolutionError("computer_ambiguous", `Computer "${trimmed}" is ambiguous. Matched: ${onlineMatches.map(describeEnvironment).join(", ")}`);
233454
233532
  }
233455
233533
  onlineMatches.sort((a2, b3) => Math.max(b3.lastHeartbeat ?? 0, b3.lastSeenAt) - Math.max(a2.lastHeartbeat ?? 0, a2.lastSeenAt));
233456
233534
  const environment = onlineMatches[0];
233457
233535
  if (!environment) {
233458
- throw new Error(`Computer "${trimmed}" is offline`);
233536
+ throw new ComputerResolutionError("computer_offline", `Computer "${trimmed}" is offline`);
233459
233537
  }
233460
233538
  if (!environment.connectionId) {
233461
233539
  throw new Error(`Computer "${trimmed}" has no active connection id`);
@@ -233498,8 +233576,17 @@ async function teleportToEnvironment(agentId, conversationId, targetConnectionId
233498
233576
  idempotencyKey: randomUUID36()
233499
233577
  });
233500
233578
  }
233579
+ var ComputerResolutionError;
233501
233580
  var init_environments3 = __esm(() => {
233502
233581
  init_request();
233582
+ ComputerResolutionError = class ComputerResolutionError extends Error {
233583
+ code;
233584
+ constructor(code, message) {
233585
+ super(message);
233586
+ this.code = code;
233587
+ this.name = "ComputerResolutionError";
233588
+ }
233589
+ };
233503
233590
  });
233504
233591
 
233505
233592
  // src/cron/runner.ts
@@ -236713,7 +236800,7 @@ function waitForSocketOpen(socket, timeoutMs) {
236713
236800
  }
236714
236801
  detachError = onceSocketEvent(socket, "error", (event) => {
236715
236802
  cleanup();
236716
- reject2(new Error(`App-server WebSocket failed to open: ${String(event)}`));
236803
+ reject2(new Error(`App-server WebSocket failed to open: ${socketErrorDetail(event)}`));
236717
236804
  });
236718
236805
  detachClose = onceSocketEvent(socket, "close", () => {
236719
236806
  if (upgradeRejected)
@@ -236723,6 +236810,19 @@ function waitForSocketOpen(socket, timeoutMs) {
236723
236810
  });
236724
236811
  });
236725
236812
  }
236813
+ function socketErrorDetail(event) {
236814
+ if (event instanceof Error)
236815
+ return event.message;
236816
+ if (event && typeof event === "object") {
236817
+ const error4 = Reflect.get(event, "error");
236818
+ if (error4 instanceof Error)
236819
+ return error4.message;
236820
+ const message = Reflect.get(event, "message");
236821
+ if (typeof message === "string" && message)
236822
+ return message;
236823
+ }
236824
+ return String(event);
236825
+ }
236726
236826
  function rawEventData(event) {
236727
236827
  if (event && typeof event === "object" && "data" in event) {
236728
236828
  return event.data;
@@ -236778,6 +236878,7 @@ class AppServerClient {
236778
236878
  this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
236779
236879
  const socketOptions = appServerSocketOptions(options.authToken);
236780
236880
  this.socket = new WebSocket5(resolveAppServerUrl(options.url), socketOptions);
236881
+ this.socket.on?.("error", () => {});
236781
236882
  this.control = this.socket;
236782
236883
  this.stream = this.socket;
236783
236884
  attachSocketListener(this.socket, "message", (event) => {
@@ -236788,8 +236889,13 @@ class AppServerClient {
236788
236889
  });
236789
236890
  }
236790
236891
  async connect() {
236791
- await waitForSocketOpen(this.socket, this.requestTimeoutMs);
236792
- return this;
236892
+ try {
236893
+ await waitForSocketOpen(this.socket, this.requestTimeoutMs);
236894
+ return this;
236895
+ } catch (error4) {
236896
+ this.close();
236897
+ throw error4;
236898
+ }
236793
236899
  }
236794
236900
  close() {
236795
236901
  if (this.explicitlyClosed)
@@ -240125,7 +240231,7 @@ class CodexAppServerClient {
240125
240231
  await this.request("initialize", {
240126
240232
  clientInfo: {
240127
240233
  name: "letta-code",
240128
- version: "0.34.59"
240234
+ version: "0.34.61"
240129
240235
  },
240130
240236
  capabilities: null
240131
240237
  });
@@ -245525,6 +245631,27 @@ async function resolveQualifiedComputer(deviceId, scope) {
245525
245631
  function errorMessage5(error4) {
245526
245632
  return error4 instanceof Error ? error4.message : String(error4);
245527
245633
  }
245634
+ function classifyRemoteExternalWorkerControlError(error4) {
245635
+ if (error4 instanceof ComputerResolutionError) {
245636
+ return error4.code === "computer_offline" || error4.code === "computer_not_found" ? error4.code : "other";
245637
+ }
245638
+ if (error4 instanceof OutdatedRemoteWorkerError)
245639
+ return "outdated_computer";
245640
+ const message2 = errorMessage5(error4);
245641
+ if (/^Computer ".*" is offline(?:\.|$)/.test(message2) || message2.startsWith("Timed out waiting for cloud sandbox "))
245642
+ return "computer_offline";
245643
+ if (/^Computer ".*" not found(?:\.|$)/.test(message2))
245644
+ return "computer_not_found";
245645
+ if (/^Subagent .* was not found on this computer$/.test(message2))
245646
+ return "subagent_not_found";
245647
+ if (message2 === "Subagent does not belong to this conversation")
245648
+ return "subagent_not_owned";
245649
+ if (/^.* is running an older Letta Code that can't steer Claude Code subagents remotely\./.test(message2))
245650
+ return "outdated_computer";
245651
+ if (message2.startsWith("App-server WebSocket failed to open:"))
245652
+ return "connect_failed";
245653
+ return "other";
245654
+ }
245528
245655
 
245529
245656
  class RemoteSubagentFollower {
245530
245657
  scope;
@@ -245702,7 +245829,7 @@ async function launchRemoteExternalCodingAgent(params, deps) {
245702
245829
  reportExternalWorkerLaunchFailure({
245703
245830
  stage,
245704
245831
  harness: type,
245705
- computer,
245832
+ computer: stage === "resolve_computer" ? undefined : computer,
245706
245833
  error: error4,
245707
245834
  errorCode,
245708
245835
  agentId: parentScope.agentId,
@@ -245733,7 +245860,7 @@ async function launchRemoteExternalCodingAgent(params, deps) {
245733
245860
  if (outdated)
245734
245861
  return fail2("outdated_computer", outdated);
245735
245862
  } catch (error4) {
245736
- return fail2("resolve_computer", errorMessage5(error4));
245863
+ return fail2("resolve_computer", errorMessage5(error4), error4 instanceof ComputerResolutionError ? error4.code : undefined);
245737
245864
  }
245738
245865
  params.signal?.throwIfAborted();
245739
245866
  const connect = () => (deps.connect ?? defaultConnect)(connectionId, parentScope);
@@ -245909,6 +246036,7 @@ async function sendRemoteExternalCodingAgentMessage(params, deps = {}) {
245909
246036
  harness: target?.type ?? "unknown",
245910
246037
  computer: target?.computer,
245911
246038
  error: error4,
246039
+ errorCode: classifyRemoteExternalWorkerControlError(error4),
245912
246040
  agentId: params.parentScope.agentId,
245913
246041
  conversationId: params.parentScope.conversationId,
245914
246042
  toolCallId: params.toolCallId
@@ -439504,6 +439632,38 @@ var init_mod_adapter = __esm(() => {
439504
439632
  });
439505
439633
 
439506
439634
  // src/websocket/listener/memfs-sync.ts
439635
+ import { execFileSync as execFileSync11 } from "node:child_process";
439636
+ import { lstat as lstat2, realpath as realpath6, rm as rm11 } from "node:fs/promises";
439637
+ import { isAbsolute as isAbsolute26, join as join83, relative as relative7, resolve as resolve37, sep as sep8 } from "node:path";
439638
+ async function removeRefusedCheckout(agentId, error4) {
439639
+ const message2 = error4 instanceof Error ? error4.message : String(error4);
439640
+ if (isLocalBackendEnvEnabled() || !/(?:returned error:|HTTP(?: status)?)[ :]*403\b/i.test(message2))
439641
+ return;
439642
+ try {
439643
+ const { getScopedMemoryFilesystemRoot: getScopedMemoryFilesystemRoot2 } = await Promise.resolve().then(() => (init_memory_filesystem2(), exports_memory_filesystem));
439644
+ const { isMemfsRemoteUrlForAgent: isMemfsRemoteUrlForAgent2 } = await Promise.resolve().then(() => (init_memory_git(), exports_memory_git));
439645
+ const configDir = await realpath6(resolveGlobalConfigDir());
439646
+ if (!agentId || agentId === "." || agentId === ".." || /[/\\]/.test(agentId))
439647
+ return;
439648
+ const expected = join83(configDir, "agents", agentId, "memory");
439649
+ const checkout = resolve37(getScopedMemoryFilesystemRoot2(agentId));
439650
+ if (await realpath6(checkout) !== expected || !(await lstat2(checkout)).isDirectory())
439651
+ return;
439652
+ const cwdRelative = relative7(expected, await realpath6(process.cwd()));
439653
+ if (!cwdRelative || !cwdRelative.startsWith(`..${sep8}`) && cwdRelative !== ".." && !isAbsolute26(cwdRelative))
439654
+ return;
439655
+ if (!(await lstat2(join83(checkout, ".git"))).isDirectory())
439656
+ return;
439657
+ const origin = execFileSync11("git", ["-C", checkout, "remote", "get-url", "origin"], {
439658
+ encoding: "utf8",
439659
+ timeout: 5000,
439660
+ stdio: ["ignore", "pipe", "ignore"]
439661
+ }).trim();
439662
+ if (!isMemfsRemoteUrlForAgent2(origin, agentId))
439663
+ return;
439664
+ await rm11(checkout, { recursive: true, force: true });
439665
+ } catch {}
439666
+ }
439507
439667
  async function syncMemfsForAgent(agentId) {
439508
439668
  const { settingsManager: settingsManager2 } = await Promise.resolve().then(() => (init_settings_manager(), exports_settings_manager));
439509
439669
  if (settingsManager2.isMemfsExplicitlyDisabled(agentId)) {
@@ -439550,9 +439710,10 @@ async function ensureMemfsSyncedForAgent(listener, agentId) {
439550
439710
  if (existing) {
439551
439711
  return existing;
439552
439712
  }
439553
- const promise2 = syncMemfsForAgent(agentId).then(() => true, (err) => {
439713
+ const promise2 = syncMemfsForAgent(agentId).then(() => true, async (err) => {
439554
439714
  debugWarn("memfs-sync", `Failed to sync memfs for agent ${agentId}: ${err instanceof Error ? err.message : String(err)}`);
439555
439715
  if (isMemoryAccessRefusal(err)) {
439716
+ await removeRefusedCheckout(agentId, err);
439556
439717
  markMemoryUnavailable(agentId);
439557
439718
  } else {
439558
439719
  listener.memfsSyncedAgents.delete(agentId);
@@ -439563,13 +439724,15 @@ async function ensureMemfsSyncedForAgent(listener, agentId) {
439563
439724
  return promise2;
439564
439725
  }
439565
439726
  var init_memfs_sync = __esm(() => {
439727
+ init_paths();
439566
439728
  init_debug();
439567
439729
  init_memory_access();
439730
+ init_settings_path();
439568
439731
  });
439569
439732
 
439570
439733
  // src/websocket/listener/mod-adapter.ts
439571
439734
  import { createHash as createHash18 } from "node:crypto";
439572
- import { join as join83 } from "node:path";
439735
+ import { join as join84 } from "node:path";
439573
439736
  async function getUnavailableListenerClient() {
439574
439737
  throw new Error("letta.client is not available in listener mods");
439575
439738
  }
@@ -439645,14 +439808,14 @@ function ensureListenerModAdapter(runtime) {
439645
439808
  }
439646
439809
  function resolveListenerAgentModsDirectory(agentId) {
439647
439810
  try {
439648
- return settingsManager.isMemfsEnabled(agentId) ? join83(getScopedMemoryFilesystemRoot(agentId), "mods") : null;
439811
+ return settingsManager.isMemfsEnabled(agentId) ? join84(getScopedMemoryFilesystemRoot(agentId), "mods") : null;
439649
439812
  } catch {
439650
439813
  return null;
439651
439814
  }
439652
439815
  }
439653
439816
  function resolveListenerAgentModCacheDirectory(agentId) {
439654
439817
  const cacheKey = createHash18("sha256").update(agentId).digest("hex");
439655
- return join83(getModCacheDirectory(), "listener-agents", cacheKey);
439818
+ return join84(getModCacheDirectory(), "listener-agents", cacheKey);
439656
439819
  }
439657
439820
  async function ensureListenerAgentModAdapter(runtime, agentId) {
439658
439821
  runtime.agentModAdapters ??= new Map;
@@ -440474,7 +440637,7 @@ async function mergeSettledRecoveryResultRetriably(store3, params, retryDelayMs
440474
440637
  if (!(error4 instanceof Error) || error4.message !== "Timed out acquiring durable filesystem lock") {
440475
440638
  throw error4;
440476
440639
  }
440477
- await new Promise((resolve37) => setTimeout(resolve37, retryDelayMs));
440640
+ await new Promise((resolve38) => setTimeout(resolve38, retryDelayMs));
440478
440641
  }
440479
440642
  }
440480
440643
  }
@@ -441369,11 +441532,11 @@ async function retryApprovalRecoveryRead(read2, assertCurrent, signal) {
441369
441532
  detail
441370
441533
  }))
441371
441534
  throw error4;
441372
- await new Promise((resolve37) => {
441535
+ await new Promise((resolve38) => {
441373
441536
  const done = () => {
441374
441537
  clearTimeout(timer);
441375
441538
  signal.removeEventListener("abort", done);
441376
- resolve37();
441539
+ resolve38();
441377
441540
  };
441378
441541
  const timer = setTimeout(done, getRetryDelayMs2({
441379
441542
  category: "transient_provider",
@@ -441446,7 +441609,7 @@ async function sleepWithAbort3(delayMs, abortSignal) {
441446
441609
  if (delayMs <= 0) {
441447
441610
  return;
441448
441611
  }
441449
- await new Promise((resolve37, reject2) => {
441612
+ await new Promise((resolve38, reject2) => {
441450
441613
  let timeout = null;
441451
441614
  function cleanup() {
441452
441615
  if (timeout) {
@@ -441466,7 +441629,7 @@ async function sleepWithAbort3(delayMs, abortSignal) {
441466
441629
  abortSignal?.addEventListener("abort", onAbort, { once: true });
441467
441630
  timeout = setTimeout(() => {
441468
441631
  cleanup();
441469
- resolve37();
441632
+ resolve38();
441470
441633
  }, delayMs);
441471
441634
  });
441472
441635
  }
@@ -441815,7 +441978,7 @@ async function sendMessageStreamWithRetry(conversationId, messages, opts, socket
441815
441978
  conversationId
441816
441979
  });
441817
441980
  }
441818
- await new Promise((resolve37) => setTimeout(resolve37, delayMs));
441981
+ await new Promise((resolve38) => setTimeout(resolve38, delayMs));
441819
441982
  if (abortSignal?.aborted) {
441820
441983
  throw new Error("Cancelled by user");
441821
441984
  }
@@ -441963,7 +442126,7 @@ async function sendApprovalContinuationWithRetry(conversationId, messages, opts,
441963
442126
  conversationId
441964
442127
  });
441965
442128
  }
441966
- await new Promise((resolve37) => setTimeout(resolve37, delayMs));
442129
+ await new Promise((resolve38) => setTimeout(resolve38, delayMs));
441967
442130
  if (abortSignal?.aborted) {
441968
442131
  throw new Error("Cancelled by user");
441969
442132
  }
@@ -442975,7 +443138,7 @@ var init_diff2 = __esm(() => {
442975
443138
  });
442976
443139
 
442977
443140
  // src/cli/helpers/shell-semantic-display.ts
442978
- import { relative as relative7 } from "node:path";
443141
+ import { relative as relative8 } from "node:path";
442979
443142
  function quoteSummaryValue(value) {
442980
443143
  return JSON.stringify(value);
442981
443144
  }
@@ -443042,7 +443205,7 @@ function formatDisplayPath2(filePath) {
443042
443205
  return ".";
443043
443206
  }
443044
443207
  const cwd2 = process.cwd();
443045
- const relativePath = relative7(cwd2, filePath);
443208
+ const relativePath = relative8(cwd2, filePath);
443046
443209
  if (relativePath === "") {
443047
443210
  return ".";
443048
443211
  }
@@ -443667,13 +443830,13 @@ __export(exports_format_args_display, {
443667
443830
  parsePatchInput: () => parsePatchInput,
443668
443831
  formatArgsDisplay: () => formatArgsDisplay
443669
443832
  });
443670
- import { relative as relative8 } from "node:path";
443833
+ import { relative as relative9 } from "node:path";
443671
443834
  function formatItemCount(count) {
443672
443835
  return `${String(count)} item${count === 1 ? "" : "s"}`;
443673
443836
  }
443674
443837
  function formatDisplayPath3(filePath) {
443675
443838
  const cwd2 = process.cwd();
443676
- const relativePath = relative8(cwd2, filePath);
443839
+ const relativePath = relative9(cwd2, filePath);
443677
443840
  if (relativePath.startsWith("..")) {
443678
443841
  return filePath;
443679
443842
  }
@@ -444369,7 +444532,7 @@ async function waitForApprovalTransportOpen(isDeliveryReady, shouldInterrupt) {
444369
444532
  if (isDeliveryReady())
444370
444533
  return "open";
444371
444534
  while (!shouldInterrupt()) {
444372
- await new Promise((resolve37) => setTimeout(resolve37, APPROVAL_TRANSPORT_REOPEN_POLL_MS));
444535
+ await new Promise((resolve38) => setTimeout(resolve38, APPROVAL_TRANSPORT_REOPEN_POLL_MS));
444373
444536
  if (isDeliveryReady())
444374
444537
  return "open";
444375
444538
  }
@@ -444980,7 +445143,7 @@ var init_turn_approval = __esm(() => {
444980
445143
 
444981
445144
  // src/agent/attached-repository-git-sync.ts
444982
445145
  import { existsSync as existsSync59 } from "node:fs";
444983
- import { join as join84 } from "node:path";
445146
+ import { join as join85 } from "node:path";
444984
445147
  async function getPendingCommitCount(path41) {
444985
445148
  const divergence = await getMemoryAheadBehind(path41);
444986
445149
  if (divergence) {
@@ -445010,7 +445173,7 @@ async function syncPendingAttachedRepositoryCommitsUnlocked(params) {
445010
445173
  path: path41,
445011
445174
  permissions: params.repository.permissions ?? "unknown"
445012
445175
  };
445013
- if (!existsSync59(join84(path41, ".git"))) {
445176
+ if (!existsSync59(join85(path41, ".git"))) {
445014
445177
  return {
445015
445178
  ...resultBase,
445016
445179
  status: "skipped",
@@ -445143,7 +445306,7 @@ async function syncPendingAttachedRepositoryCommitsAfterTurn(agentId, dependenci
445143
445306
  return { results: [] };
445144
445307
  }
445145
445308
  const listRepositories = dependencies.listRepositories ?? listAttachedAgentRepositories;
445146
- const repositories = await listRepositories(agentId);
445309
+ const repositories = await listRepositories(resolveEffectiveAgentId(agentId));
445147
445310
  if (repositories.length === 0) {
445148
445311
  return { results: [] };
445149
445312
  }
@@ -445176,12 +445339,13 @@ var init_attached_repository_git_sync = __esm(() => {
445176
445339
  init_attached_repositories();
445177
445340
  init_memory_auth();
445178
445341
  init_memory_git();
445342
+ init_ephemeral_subagent();
445179
445343
  repositorySyncs = new Map;
445180
445344
  });
445181
445345
 
445182
445346
  // src/reminders/memory-git-sync.ts
445183
445347
  import { existsSync as existsSync60 } from "node:fs";
445184
- import { join as join85 } from "node:path";
445348
+ import { join as join86 } from "node:path";
445185
445349
  function formatMemoryRepairInProgressReminder(result3) {
445186
445350
  return `${SYSTEM_REMINDER_OPEN}
445187
445351
  MEMORY REPAIR RUNNING: A background worker is repairing the memory repository.
@@ -445291,7 +445455,7 @@ async function runPostTurnMemorySync(params, dependencies = {}) {
445291
445455
  if (memorySyncEnabled) {
445292
445456
  try {
445293
445457
  const memoryDir = getScopedMemoryFilesystemRoot(params.agentId);
445294
- const release = existsSync60(join85(memoryDir, ".git")) ? await (dependencies.claimOperation ?? claimMemoryOperation)(memoryDir) : undefined;
445458
+ const release = existsSync60(join86(memoryDir, ".git")) ? await (dependencies.claimOperation ?? claimMemoryOperation)(memoryDir) : undefined;
445295
445459
  if (release !== null) {
445296
445460
  try {
445297
445461
  const result3 = await syncMemory(params.agentId);
@@ -447526,7 +447690,7 @@ var init_core5 = __esm(() => {
447526
447690
  import { spawn as spawn12 } from "node:child_process";
447527
447691
  import { accessSync as accessSync2, constants as constants6 } from "node:fs";
447528
447692
  import { homedir as homedir23 } from "node:os";
447529
- import { join as join86 } from "node:path";
447693
+ import { join as join87 } from "node:path";
447530
447694
  import { fileURLToPath as fileURLToPath9 } from "node:url";
447531
447695
  async function normalizeCheckpoint(input) {
447532
447696
  const { decoded, bounds, filters } = await decodeCheckpoint(input);
@@ -447550,10 +447714,10 @@ async function decodeCheckpoint(input) {
447550
447714
  }
447551
447715
  async function loadDeepAgentsCheckpoint(checkpoint) {
447552
447716
  validateLocation(checkpoint);
447553
- const path41 = checkpoint.path ?? join86(homedir23(), ".deepagents", "sessions.db");
447717
+ const path41 = checkpoint.path ?? join87(homedir23(), ".deepagents", "sessions.db");
447554
447718
  const python = checkpoint.pythonExecutable ?? process.env.PYTHON ?? "python3";
447555
447719
  const helper = resolveHelperPath();
447556
- return await new Promise((resolve37, reject2) => {
447720
+ return await new Promise((resolve38, reject2) => {
447557
447721
  const child = spawn12(python, [helper], {
447558
447722
  stdio: ["pipe", "pipe", "pipe"],
447559
447723
  windowsHide: true
@@ -447610,7 +447774,7 @@ async function loadDeepAgentsCheckpoint(checkpoint) {
447610
447774
  reject2(new NormalizationError("invalid_checkpoint_state", "Deep Agents checkpoint helper returned an invalid message envelope."));
447611
447775
  return;
447612
447776
  }
447613
- resolve37({ ...response.data, threadId: checkpoint.threadId });
447777
+ resolve38({ ...response.data, threadId: checkpoint.threadId });
447614
447778
  });
447615
447779
  child.stdin.on("error", () => {});
447616
447780
  child.stdin.end(JSON.stringify({
@@ -447770,7 +447934,7 @@ var init_deepagents = __esm(() => {
447770
447934
 
447771
447935
  // node_modules/@letta-ai/trajectory/dist/adapters/listing-shared.js
447772
447936
  import { readdirSync as readdirSync24, statSync as statSync24 } from "node:fs";
447773
- import { join as join87 } from "node:path";
447937
+ import { join as join88 } from "node:path";
447774
447938
  function sortListings(items) {
447775
447939
  return items.sort((left, right) => {
447776
447940
  const l3 = left.updatedAt ?? "";
@@ -447815,7 +447979,7 @@ function collectFiles(root2, extension, depth) {
447815
447979
  return [];
447816
447980
  const collected = [];
447817
447981
  for (const entry of safeReadDir(root2)) {
447818
- const full = join87(root2, entry.name);
447982
+ const full = join88(root2, entry.name);
447819
447983
  if (entry.isFile && entry.name.endsWith(extension)) {
447820
447984
  collected.push(full);
447821
447985
  } else if (entry.isDirectory) {
@@ -447900,18 +448064,18 @@ var init_listing_shared = __esm(() => {
447900
448064
 
447901
448065
  // node_modules/@letta-ai/trajectory/dist/adapters/claude-code/list.js
447902
448066
  import { homedir as homedir24 } from "node:os";
447903
- import { basename as basename25, join as join88 } from "node:path";
448067
+ import { basename as basename25, join as join89 } from "node:path";
447904
448068
  async function listClaudeCodeTrajectories(root2) {
447905
- const base2 = root2 ?? join88(homedir24(), ".claude", "projects");
448069
+ const base2 = root2 ?? join89(homedir24(), ".claude", "projects");
447906
448070
  const items = [];
447907
448071
  for (const project of safeReadDir(base2)) {
447908
448072
  if (!project.isDirectory)
447909
448073
  continue;
447910
- const projectPath = join88(base2, project.name);
448074
+ const projectPath = join89(base2, project.name);
447911
448075
  for (const entry of safeReadDir(projectPath)) {
447912
448076
  if (!entry.isFile || !entry.name.endsWith(".jsonl"))
447913
448077
  continue;
447914
- const path41 = join88(projectPath, entry.name);
448078
+ const path41 = join89(projectPath, entry.name);
447915
448079
  const listing = listingFromFile(basename25(entry.name, ".jsonl"), path41);
447916
448080
  if (listing)
447917
448081
  items.push(listing);
@@ -447925,9 +448089,9 @@ var init_list = __esm(() => {
447925
448089
 
447926
448090
  // node_modules/@letta-ai/trajectory/dist/adapters/codex/list.js
447927
448091
  import { homedir as homedir25 } from "node:os";
447928
- import { basename as basename26, join as join89 } from "node:path";
448092
+ import { basename as basename26, join as join90 } from "node:path";
447929
448093
  async function listCodexTrajectories(root2) {
447930
- const base2 = root2 ?? join89(homedir25(), ".codex", "sessions");
448094
+ const base2 = root2 ?? join90(homedir25(), ".codex", "sessions");
447931
448095
  const items = [];
447932
448096
  for (const path41 of collectFiles(base2, ".jsonl", 4)) {
447933
448097
  const listing = listingFromFile(basename26(path41, ".jsonl"), path41);
@@ -447942,7 +448106,7 @@ var init_list2 = __esm(() => {
447942
448106
 
447943
448107
  // node_modules/@letta-ai/trajectory/dist/adapters/deepagents/list.js
447944
448108
  import { homedir as homedir26 } from "node:os";
447945
- import { join as join90 } from "node:path";
448109
+ import { join as join91 } from "node:path";
447946
448110
  async function listDeepAgentsTrajectories(root2) {
447947
448111
  const path41 = resolveStorePath(root2);
447948
448112
  if (!safeStat(path41))
@@ -447963,8 +448127,8 @@ async function listDeepAgentsTrajectories(root2) {
447963
448127
  }
447964
448128
  function resolveStorePath(root2) {
447965
448129
  if (root2 === undefined)
447966
- return join90(homedir26(), ".deepagents", "sessions.db");
447967
- return root2.endsWith(".db") ? root2 : join90(root2, "sessions.db");
448130
+ return join91(homedir26(), ".deepagents", "sessions.db");
448131
+ return root2.endsWith(".db") ? root2 : join91(root2, "sessions.db");
447968
448132
  }
447969
448133
  var init_list3 = __esm(() => {
447970
448134
  init_listing_shared();
@@ -447972,7 +448136,7 @@ var init_list3 = __esm(() => {
447972
448136
 
447973
448137
  // node_modules/@letta-ai/trajectory/dist/adapters/hermes/list.js
447974
448138
  import { homedir as homedir27 } from "node:os";
447975
- import { join as join91 } from "node:path";
448139
+ import { join as join92 } from "node:path";
447976
448140
  async function listHermesTrajectories(root2) {
447977
448141
  const path41 = resolveStorePath2(root2);
447978
448142
  if (!safeStat(path41))
@@ -447999,8 +448163,8 @@ async function listHermesTrajectories(root2) {
447999
448163
  }
448000
448164
  function resolveStorePath2(root2) {
448001
448165
  if (root2 === undefined)
448002
- return join91(homedir27(), ".hermes", "state.db");
448003
- return root2.endsWith(".db") ? root2 : join91(root2, "state.db");
448166
+ return join92(homedir27(), ".hermes", "state.db");
448167
+ return root2.endsWith(".db") ? root2 : join92(root2, "state.db");
448004
448168
  }
448005
448169
  function numeric2(value) {
448006
448170
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
@@ -448011,18 +448175,18 @@ var init_list4 = __esm(() => {
448011
448175
 
448012
448176
  // node_modules/@letta-ai/trajectory/dist/adapters/letta-code/list.js
448013
448177
  import { homedir as homedir28 } from "node:os";
448014
- import { join as join92 } from "node:path";
448178
+ import { join as join93 } from "node:path";
448015
448179
  async function listLettaCodeTrajectories(root2) {
448016
- const base2 = root2 ?? join92(homedir28(), ".letta", "transcripts");
448180
+ const base2 = root2 ?? join93(homedir28(), ".letta", "transcripts");
448017
448181
  const items = [];
448018
448182
  for (const agent of safeReadDir(base2)) {
448019
448183
  if (!agent.isDirectory)
448020
448184
  continue;
448021
- const agentPath2 = join92(base2, agent.name);
448185
+ const agentPath2 = join93(base2, agent.name);
448022
448186
  for (const conversation of safeReadDir(agentPath2)) {
448023
448187
  if (!conversation.isDirectory)
448024
448188
  continue;
448025
- const path41 = join92(agentPath2, conversation.name, "transcript.jsonl");
448189
+ const path41 = join93(agentPath2, conversation.name, "transcript.jsonl");
448026
448190
  const listing = listingFromFile(`${agent.name}/${conversation.name}`, path41);
448027
448191
  if (listing && (listing.sizeBytes ?? 0) > 0)
448028
448192
  items.push(listing);
@@ -448037,19 +448201,19 @@ var init_list5 = __esm(() => {
448037
448201
  // node_modules/@letta-ai/trajectory/dist/adapters/openclaw/list.js
448038
448202
  import { existsSync as existsSync61 } from "node:fs";
448039
448203
  import { homedir as homedir29 } from "node:os";
448040
- import { basename as basename27, join as join93 } from "node:path";
448204
+ import { basename as basename27, join as join94 } from "node:path";
448041
448205
  async function listOpenClawTrajectories(root2) {
448042
448206
  const base2 = root2 ?? defaultStateDir();
448043
448207
  const items = [];
448044
- const agentsPath = join93(base2, "agents");
448208
+ const agentsPath = join94(base2, "agents");
448045
448209
  for (const agent of safeReadDir(agentsPath)) {
448046
448210
  if (!agent.isDirectory)
448047
448211
  continue;
448048
- const sessionsPath = join93(agentsPath, agent.name, "sessions");
448212
+ const sessionsPath = join94(agentsPath, agent.name, "sessions");
448049
448213
  for (const entry of safeReadDir(sessionsPath)) {
448050
448214
  if (!entry.isFile || !entry.name.endsWith(".jsonl"))
448051
448215
  continue;
448052
- const path41 = join93(sessionsPath, entry.name);
448216
+ const path41 = join94(sessionsPath, entry.name);
448053
448217
  const listing = listingFromFile(basename27(entry.name, ".jsonl"), path41);
448054
448218
  if (listing)
448055
448219
  items.push(listing);
@@ -448061,10 +448225,10 @@ function defaultStateDir() {
448061
448225
  const override = process.env.OPENCLAW_STATE_DIR?.trim() || process.env.CLAWDBOT_STATE_DIR?.trim();
448062
448226
  if (override)
448063
448227
  return override;
448064
- const current = join93(homedir29(), ".openclaw");
448228
+ const current = join94(homedir29(), ".openclaw");
448065
448229
  if (existsSync61(current))
448066
448230
  return current;
448067
- return join93(homedir29(), ".clawdbot");
448231
+ return join94(homedir29(), ".clawdbot");
448068
448232
  }
448069
448233
  var init_list6 = __esm(() => {
448070
448234
  init_listing_shared();
@@ -448072,14 +448236,14 @@ var init_list6 = __esm(() => {
448072
448236
 
448073
448237
  // node_modules/@letta-ai/trajectory/dist/adapters/openhands/list.js
448074
448238
  import { homedir as homedir30 } from "node:os";
448075
- import { join as join94 } from "node:path";
448239
+ import { join as join95 } from "node:path";
448076
448240
  async function listOpenHandsTrajectories(root2) {
448077
- const base2 = root2 ?? join94(homedir30(), ".openhands", "sessions");
448241
+ const base2 = root2 ?? join95(homedir30(), ".openhands", "sessions");
448078
448242
  const items = [];
448079
448243
  for (const entry of safeReadDir(base2)) {
448080
448244
  if (!entry.isDirectory)
448081
448245
  continue;
448082
- const path41 = join94(base2, entry.name);
448246
+ const path41 = join95(base2, entry.name);
448083
448247
  const facts = safeStat(path41);
448084
448248
  items.push({
448085
448249
  id: entry.name,
@@ -448253,7 +448417,7 @@ __export(exports_memory_scanner, {
448253
448417
  getFileNodes: () => getFileNodes
448254
448418
  });
448255
448419
  import { readdirSync as readdirSync25, readFileSync as readFileSync50, statSync as statSync25 } from "node:fs";
448256
- import { join as join95, relative as relative9 } from "node:path";
448420
+ import { join as join96, relative as relative10 } from "node:path";
448257
448421
  function scanMemoryFilesystem(memoryRoot) {
448258
448422
  const nodes = [];
448259
448423
  const scanDir = (dir, depth, parentIsLast) => {
@@ -448265,8 +448429,8 @@ function scanMemoryFilesystem(memoryRoot) {
448265
448429
  }
448266
448430
  const filtered = entries2.filter((name) => !name.startsWith("."));
448267
448431
  const sorted = filtered.sort((a2, b3) => {
448268
- const aPath = join95(dir, a2);
448269
- const bPath = join95(dir, b3);
448432
+ const aPath = join96(dir, a2);
448433
+ const bPath = join96(dir, b3);
448270
448434
  let aIsDir = false;
448271
448435
  let bIsDir = false;
448272
448436
  try {
@@ -448286,14 +448450,14 @@ function scanMemoryFilesystem(memoryRoot) {
448286
448450
  return a2.localeCompare(b3);
448287
448451
  });
448288
448452
  sorted.forEach((name, index) => {
448289
- const fullPath = join95(dir, name);
448453
+ const fullPath = join96(dir, name);
448290
448454
  let isDir = false;
448291
448455
  try {
448292
448456
  isDir = statSync25(fullPath).isDirectory();
448293
448457
  } catch {
448294
448458
  return;
448295
448459
  }
448296
- const relativePath = relative9(memoryRoot, fullPath).replace(/\\/g, "/");
448460
+ const relativePath = relative10(memoryRoot, fullPath).replace(/\\/g, "/");
448297
448461
  const isLast = index === sorted.length - 1;
448298
448462
  nodes.push({
448299
448463
  name: isDir ? `${name}/` : name,
@@ -448404,7 +448568,7 @@ import {
448404
448568
  stat as stat12,
448405
448569
  writeFile as writeFile15
448406
448570
  } from "node:fs/promises";
448407
- import { join as join96 } from "node:path";
448571
+ import { join as join97 } from "node:path";
448408
448572
  function buildReflectionSelectorPrompt(options) {
448409
448573
  const lines = [
448410
448574
  'You are selecting conversation transcripts for memory reflection. The transcript candidates path is available as the `$TRANSCRIPT_PATH` env var — read it via Bash (e.g. `wc -c "$TRANSCRIPT_PATH"`). Note: `$TRANSCRIPT_PATH` only expands in shell commands; Edit file_path is literal and does NOT expand env vars.',
@@ -448438,7 +448602,7 @@ async function collectParentMemoryFiles(memoryDir) {
448438
448602
  return a2.name.localeCompare(b3.name);
448439
448603
  });
448440
448604
  for (const entry of sortedEntries) {
448441
- const entryPath = join96(currentDir, entry.name);
448605
+ const entryPath = join97(currentDir, entry.name);
448442
448606
  const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
448443
448607
  if (entry.isDirectory()) {
448444
448608
  await walk3(entryPath, relativePath);
@@ -448854,17 +449018,17 @@ async function writeState(paths, state2) {
448854
449018
  }
448855
449019
  function buildPayloadPath(rootDir, kind) {
448856
449020
  const nonce = Math.random().toString(36).slice(2, 8);
448857
- return join96(rootDir, `payload-${kind}-${nonce}.json`);
449021
+ return join97(rootDir, `payload-${kind}-${nonce}.json`);
448858
449022
  }
448859
449023
  function getAgentTranscriptRoot(agentId) {
448860
- return join96(getTranscriptRoot(), sanitizePathSegment2(agentId));
449024
+ return join97(getTranscriptRoot(), sanitizePathSegment2(agentId));
448861
449025
  }
448862
449026
  function getReflectionTranscriptPaths(agentId, conversationId) {
448863
- const rootDir = join96(getTranscriptRoot(), sanitizePathSegment2(agentId), sanitizePathSegment2(conversationId));
449027
+ const rootDir = join97(getTranscriptRoot(), sanitizePathSegment2(agentId), sanitizePathSegment2(conversationId));
448864
449028
  return {
448865
449029
  rootDir,
448866
- transcriptPath: join96(rootDir, "transcript.jsonl"),
448867
- statePath: join96(rootDir, "state.json")
449030
+ transcriptPath: join97(rootDir, "transcript.jsonl"),
449031
+ statePath: join97(rootDir, "state.json")
448868
449032
  };
448869
449033
  }
448870
449034
  async function appendTranscriptDeltaJsonl(agentId, conversationId, lines) {
@@ -448954,7 +449118,7 @@ async function getTranscriptLastUpdatedAt(paths) {
448954
449118
  }
448955
449119
  }
448956
449120
  async function ensureAgentPayloadRoot(agentId) {
448957
- const root2 = join96(getAgentTranscriptRoot(agentId), "multi-reflection-payloads");
449121
+ const root2 = join97(getAgentTranscriptRoot(agentId), "multi-reflection-payloads");
448958
449122
  await mkdir12(root2, { recursive: true });
448959
449123
  return root2;
448960
449124
  }
@@ -449518,7 +449682,7 @@ import { execFile as execFileCb3 } from "node:child_process";
449518
449682
  import { randomUUID as randomUUID54 } from "node:crypto";
449519
449683
  import { existsSync as existsSync62 } from "node:fs";
449520
449684
  import { mkdir as mkdir13 } from "node:fs/promises";
449521
- import { dirname as dirname37, isAbsolute as isAbsolute26, join as join97, resolve as resolve37 } from "node:path";
449685
+ import { dirname as dirname37, isAbsolute as isAbsolute27, join as join98, resolve as resolve38 } from "node:path";
449522
449686
  import { promisify as promisify18 } from "node:util";
449523
449687
  async function runGit4(cwd2, args) {
449524
449688
  try {
@@ -449555,7 +449719,7 @@ function normalizeGitPath(path41, cwd2) {
449555
449719
  const trimmed = path41.trim();
449556
449720
  if (!trimmed)
449557
449721
  return trimmed;
449558
- return isAbsolute26(trimmed) ? trimmed : resolve37(cwd2, trimmed);
449722
+ return isAbsolute27(trimmed) ? trimmed : resolve38(cwd2, trimmed);
449559
449723
  }
449560
449724
  function buildReflectionWorktreeId(now2 = new Date) {
449561
449725
  const timestamp = now2.toISOString().replace(/[^0-9]/g, "").slice(0, 14);
@@ -449576,11 +449740,11 @@ async function buildReflectionMergeMessage(parentMemoryDir, branchName) {
449576
449740
  return `merge(reflection): ${summary}`;
449577
449741
  }
449578
449742
  async function createReflectionMemoryWorktree(options) {
449579
- const parentMemoryDir = resolve37(options.parentMemoryDir);
449743
+ const parentMemoryDir = resolve38(options.parentMemoryDir);
449580
449744
  const id = buildReflectionWorktreeId(options.now);
449581
- const worktreeBaseDir = join97(dirname37(parentMemoryDir), "memory-worktrees");
449745
+ const worktreeBaseDir = join98(dirname37(parentMemoryDir), "memory-worktrees");
449582
449746
  const label = options.label ?? "reflection";
449583
- const worktreeDir = join97(worktreeBaseDir, `${label}-${id}`);
449747
+ const worktreeDir = join98(worktreeBaseDir, `${label}-${id}`);
449584
449748
  const branchName = `letta/${label}/${id}`;
449585
449749
  await mkdir13(worktreeBaseDir, { recursive: true });
449586
449750
  const { stdout: baseHeadOut } = await runGit4(parentMemoryDir, [
@@ -449645,7 +449809,7 @@ async function getStatusPorcelain(cwd2) {
449645
449809
  return stdout.trim();
449646
449810
  }
449647
449811
  async function reflectionMemoryParentHasChanges(parentMemoryDir) {
449648
- return (await getStatusPorcelain(resolve37(parentMemoryDir))).length > 0;
449812
+ return (await getStatusPorcelain(resolve38(parentMemoryDir))).length > 0;
449649
449813
  }
449650
449814
  async function getCommitCount(worktree) {
449651
449815
  const { stdout } = await runGit4(worktree.worktreeDir, [
@@ -450481,7 +450645,7 @@ async function runExplicitReflectionIntegration(params) {
450481
450645
  spawnBackgroundSubagentTask: spawnBackgroundSubagentTask2,
450482
450646
  waitForBackgroundSubagentConversationId: waitForBackgroundSubagentConversationId2
450483
450647
  } = await Promise.resolve().then(() => (init_task(), exports_task));
450484
- return await new Promise((resolve38) => {
450648
+ return await new Promise((resolve39) => {
450485
450649
  try {
450486
450650
  const { subagentId } = spawnBackgroundSubagentTask2({
450487
450651
  subagentType: "general-purpose",
@@ -450500,7 +450664,7 @@ async function runExplicitReflectionIntegration(params) {
450500
450664
  },
450501
450665
  silentCompletion: true,
450502
450666
  onComplete: (result3) => {
450503
- resolve38({
450667
+ resolve39({
450504
450668
  success: result3.success,
450505
450669
  error: result3.success ? undefined : result3.error ?? "Reflection integration did not complete",
450506
450670
  conversationId: result3.conversationId
@@ -450517,7 +450681,7 @@ async function runExplicitReflectionIntegration(params) {
450517
450681
  debugWarn("memory", `Failed to title reflection integration conversation: ${error4 instanceof Error ? error4.message : String(error4)}`);
450518
450682
  });
450519
450683
  } catch (error4) {
450520
- resolve38({
450684
+ resolve39({
450521
450685
  success: false,
450522
450686
  error: error4 instanceof Error ? error4.message : String(error4)
450523
450687
  });
@@ -451280,7 +451444,7 @@ async function prepareProviderRetryInput(params) {
451280
451444
  agentId: params.agentId,
451281
451445
  conversationId: params.conversationId
451282
451446
  });
451283
- await new Promise((resolve38) => setTimeout(resolve38, delayMs));
451447
+ await new Promise((resolve39) => setTimeout(resolve39, delayMs));
451284
451448
  if (params.turnLease.signal.aborted) {
451285
451449
  throw new Error("Cancelled by user");
451286
451450
  }
@@ -452244,7 +452408,7 @@ async function handleIncomingMessageInner(msg, socket, runtime, onStatusChange,
452244
452408
  agentId,
452245
452409
  conversationId
452246
452410
  });
452247
- await new Promise((resolve38) => setTimeout(resolve38, delayMs));
452411
+ await new Promise((resolve39) => setTimeout(resolve39, delayMs));
452248
452412
  if (turnAbortSignal.aborted) {
452249
452413
  throw new Error("Cancelled by user");
452250
452414
  }
@@ -453055,14 +453219,14 @@ function localSources() {
453055
453219
  cpu: cpus()[0]?.model,
453056
453220
  memoryBytes: Math.min(totalmem(), limit4 || Number.POSITIVE_INFINITY),
453057
453221
  read: (path41, signal) => readFile25(path41, { encoding: "utf8", signal }),
453058
- run: (command, args, signal) => new Promise((resolve38, reject2) => {
453222
+ run: (command, args, signal) => new Promise((resolve39, reject2) => {
453059
453223
  execFile19(command, args, {
453060
453224
  encoding: "utf8",
453061
453225
  signal,
453062
453226
  killSignal: "SIGKILL",
453063
453227
  windowsHide: true,
453064
453228
  maxBuffer: 512 * 1024
453065
- }, (error4, stdout) => error4 ? reject2(error4) : resolve38(stdout));
453229
+ }, (error4, stdout) => error4 ? reject2(error4) : resolve39(stdout));
453066
453230
  })
453067
453231
  };
453068
453232
  }
@@ -453179,10 +453343,10 @@ async function collectMachineMetadata(sources = localSources(), timeoutMs = COLL
453179
453343
  try {
453180
453344
  await Promise.race([
453181
453345
  probe2().catch(() => {}),
453182
- new Promise((resolve38) => {
453346
+ new Promise((resolve39) => {
453183
453347
  timer = setTimeout(() => {
453184
453348
  controller.abort();
453185
- resolve38();
453349
+ resolve39();
453186
453350
  }, timeoutMs);
453187
453351
  })
453188
453352
  ]);
@@ -453316,7 +453480,7 @@ async function registerWithCloud(opts, fetchImpl = fetch) {
453316
453480
  async function registerWithCloudRetry(opts, callbacks) {
453317
453481
  const startTime = Date.now();
453318
453482
  const maxDurationMs = callbacks?.maxDurationMs ?? REGISTER_MAX_DURATION_MS;
453319
- const sleep12 = callbacks?.sleep ?? ((delayMs) => new Promise((resolve38) => setTimeout(resolve38, delayMs)));
453483
+ const sleep12 = callbacks?.sleep ?? ((delayMs) => new Promise((resolve39) => setTimeout(resolve39, delayMs)));
453320
453484
  let attempt2 = 0;
453321
453485
  for (;; ) {
453322
453486
  try {
@@ -453758,7 +453922,7 @@ var init_connection_state_sync = __esm(() => {
453758
453922
  });
453759
453923
 
453760
453924
  // src/websocket/listener/control-inputs.ts
453761
- import { realpath as realpath6, stat as stat13 } from "node:fs/promises";
453925
+ import { realpath as realpath7, stat as stat13 } from "node:fs/promises";
453762
453926
  import path41 from "node:path";
453763
453927
  function trackListenerError(errorType, error4, context3) {
453764
453928
  trackBoundaryError({
@@ -454027,7 +454191,7 @@ async function handleAbortMessageInput(listener, params, deps = {}) {
454027
454191
  while (cancellation.lease && scopedRuntime.turnLifecycle.isCurrent(cancellation.lease)) {
454028
454192
  if (Date.now() >= deadline)
454029
454193
  throw new Error("The listener turn did not stop");
454030
- await new Promise((resolve38) => setTimeout(resolve38, 20));
454194
+ await new Promise((resolve39) => setTimeout(resolve39, 20));
454031
454195
  }
454032
454196
  } else {
454033
454197
  settlementPromise.catch(() => {
@@ -454049,7 +454213,7 @@ async function handleCwdChange(msg, socket, runtime) {
454049
454213
  throw new Error("Working directory cannot be empty");
454050
454214
  }
454051
454215
  const resolvedPath = path41.isAbsolute(requestedPath) ? requestedPath : path41.resolve(currentWorkingDirectory, requestedPath);
454052
- const normalizedPath = await realpath6(resolvedPath);
454216
+ const normalizedPath = await realpath7(resolvedPath);
454053
454217
  const stats = await stat13(normalizedPath);
454054
454218
  if (!stats.isDirectory()) {
454055
454219
  throw new Error(`Not a directory: ${normalizedPath}`);
@@ -454170,7 +454334,7 @@ async function runGrepInFiles(args) {
454170
454334
  });
454171
454335
  }
454172
454336
  function runRipgrep2(rgArgs) {
454173
- return new Promise((resolve38, reject2) => {
454337
+ return new Promise((resolve39, reject2) => {
454174
454338
  const child = execFile20(rgPath, rgArgs, {
454175
454339
  maxBuffer: 50 * 1024 * 1024,
454176
454340
  windowsHide: true
@@ -454179,7 +454343,7 @@ function runRipgrep2(rgArgs) {
454179
454343
  reject2(error4);
454180
454344
  return;
454181
454345
  }
454182
- resolve38(stdout);
454346
+ resolve39(stdout);
454183
454347
  });
454184
454348
  const timer = setTimeout(() => {
454185
454349
  child.kill("SIGTERM");
@@ -455545,8 +455709,8 @@ function normalizeAbsPath(value) {
455545
455709
  return path44.resolve(value);
455546
455710
  }
455547
455711
  function isWithinOrEqual(parent, child) {
455548
- const relative11 = path44.relative(parent, child);
455549
- return relative11 === "" || !relative11.startsWith("..") && !path44.isAbsolute(relative11);
455712
+ const relative12 = path44.relative(parent, child);
455713
+ return relative12 === "" || !relative12.startsWith("..") && !path44.isAbsolute(relative12);
455550
455714
  }
455551
455715
  function getHomeDirectory() {
455552
455716
  return normalizeAbsPath(process.env.HOME || homedir32());
@@ -455559,10 +455723,10 @@ function getProtectedHomeSegment(absPath) {
455559
455723
  const target = normalizeAbsPath(absPath);
455560
455724
  if (!isWithinOrEqual(home, target))
455561
455725
  return null;
455562
- const relative11 = path44.relative(home, target);
455563
- if (!relative11)
455726
+ const relative12 = path44.relative(home, target);
455727
+ if (!relative12)
455564
455728
  return null;
455565
- const [firstSegment] = relative11.split(path44.sep);
455729
+ const [firstSegment] = relative12.split(path44.sep);
455566
455730
  const normalized = firstSegment?.toLowerCase();
455567
455731
  return normalized && PROTECTED_HOME_NAMES.has(normalized) ? normalized : null;
455568
455732
  }
@@ -456680,9 +456844,9 @@ __export(exports_custom, {
456680
456844
  });
456681
456845
  import { existsSync as existsSync63 } from "node:fs";
456682
456846
  import { readdir as readdir11, readFile as readFile27 } from "node:fs/promises";
456683
- import { basename as basename29, dirname as dirname38, join as join98 } from "node:path";
456847
+ import { basename as basename29, dirname as dirname38, join as join99 } from "node:path";
456684
456848
  function getGlobalCommandsDir() {
456685
- return join98(resolveGlobalConfigDir(), "commands");
456849
+ return join99(resolveGlobalConfigDir(), "commands");
456686
456850
  }
456687
456851
  async function getCustomCommands() {
456688
456852
  if (cachedCommands !== null) {
@@ -456694,7 +456858,7 @@ async function getCustomCommands() {
456694
456858
  function refreshCustomCommands() {
456695
456859
  cachedCommands = null;
456696
456860
  }
456697
- async function discoverCustomCommands(projectPath = join98(process.cwd(), COMMANDS_DIR)) {
456861
+ async function discoverCustomCommands(projectPath = join99(process.cwd(), COMMANDS_DIR)) {
456698
456862
  const commandsById = new Map;
456699
456863
  const userCommands = await discoverFromDirectory(getGlobalCommandsDir(), "user");
456700
456864
  for (const cmd of userCommands) {
@@ -456726,7 +456890,7 @@ async function findCommandFiles(currentPath, rootPath, commands, source) {
456726
456890
  try {
456727
456891
  const entries2 = await readdir11(currentPath, { withFileTypes: true });
456728
456892
  for (const entry of entries2) {
456729
- const fullPath = join98(currentPath, entry.name);
456893
+ const fullPath = join99(currentPath, entry.name);
456730
456894
  if (entry.isDirectory()) {
456731
456895
  await findCommandFiles(fullPath, rootPath, commands, source);
456732
456896
  } else if (entry.isFile() && entry.name.endsWith(".md")) {
@@ -458122,7 +458286,7 @@ var init_app_server_info = __esm(() => {
458122
458286
  });
458123
458287
 
458124
458288
  // src/websocket/listener/commands/boot-working-directory.ts
458125
- import { realpath as realpath7, stat as stat14 } from "node:fs/promises";
458289
+ import { realpath as realpath8, stat as stat14 } from "node:fs/promises";
458126
458290
  import path45 from "node:path";
458127
458291
  async function resolveDirectory(requestedPath, currentBootWorkingDirectory) {
458128
458292
  const trimmedPath = requestedPath.trim();
@@ -458130,7 +458294,7 @@ async function resolveDirectory(requestedPath, currentBootWorkingDirectory) {
458130
458294
  throw new Error("Working directory cannot be empty");
458131
458295
  }
458132
458296
  const resolvedPath = path45.isAbsolute(trimmedPath) ? trimmedPath : path45.resolve(currentBootWorkingDirectory, trimmedPath);
458133
- const normalizedPath = await realpath7(resolvedPath);
458297
+ const normalizedPath = await realpath8(resolvedPath);
458134
458298
  const stats = await stat14(normalizedPath);
458135
458299
  if (!stats.isDirectory()) {
458136
458300
  throw new Error(`Not a directory: ${normalizedPath}`);
@@ -459437,8 +459601,8 @@ async function awaitMemoryPushBounded(commandName, agentId, memoryRoot) {
459437
459601
  }
459438
459602
  };
459439
459603
  let timer;
459440
- const capPromise = new Promise((resolve38) => {
459441
- timer = setTimeout(() => resolve38("timed_out"), MEMORY_PUSH_AWAIT_CAP_MS);
459604
+ const capPromise = new Promise((resolve39) => {
459605
+ timer = setTimeout(() => resolve39("timed_out"), MEMORY_PUSH_AWAIT_CAP_MS);
459442
459606
  });
459443
459607
  try {
459444
459608
  const result3 = await Promise.race([syncPromise, capPromise]);
@@ -459470,9 +459634,9 @@ async function handleListMemoryCommand(parsed, socket, safeSocketSend, overrides
459470
459634
  const { scanMemoryFilesystem: scanMemoryFilesystem2, getFileNodes: getFileNodes2, readFileContent: readFileContent2 } = await Promise.resolve().then(() => (init_memory_scanner(), exports_memory_scanner));
459471
459635
  const { parseFrontmatter: parseFrontmatter2 } = await Promise.resolve().then(() => exports_frontmatter);
459472
459636
  const { existsSync: existsSync64, statSync: statSync26 } = await import("node:fs");
459473
- const { join: join99, posix: posix4 } = await import("node:path");
459637
+ const { join: join100, posix: posix4 } = await import("node:path");
459474
459638
  const memoryRoot = getMemoryFilesystemRoot2(parsed.agent_id);
459475
- let memfsInitialized = existsSync64(join99(memoryRoot, ".git"));
459639
+ let memfsInitialized = existsSync64(join100(memoryRoot, ".git"));
459476
459640
  const memfsEnabled = memfsInitialized ? true : await isMemfsEnabledOnServer2(parsed.agent_id);
459477
459641
  if (!memfsEnabled) {
459478
459642
  safeSocketSend(socket, {
@@ -459490,7 +459654,7 @@ async function handleListMemoryCommand(parsed, socket, safeSocketSend, overrides
459490
459654
  await ensureLocalMemfsCheckout2(parsed.agent_id, {
459491
459655
  pullOnExistingRepo: true
459492
459656
  });
459493
- memfsInitialized = existsSync64(join99(memoryRoot, ".git"));
459657
+ memfsInitialized = existsSync64(join100(memoryRoot, ".git"));
459494
459658
  if (!memfsInitialized) {
459495
459659
  throw new Error("MemFS is enabled, but the local memory checkout could not be initialized.");
459496
459660
  }
@@ -459791,33 +459955,33 @@ function handleMemoryProtocolCommand(parsed, context3) {
459791
459955
  } = await Promise.resolve().then(() => (init_memory_filesystem2(), exports_memory_filesystem));
459792
459956
  const { readFile: readFile28 } = await import("node:fs/promises");
459793
459957
  const { existsSync: existsSync64 } = await import("node:fs");
459794
- const { isAbsolute: isAbsolute27, join: join99, normalize: normalize5, relative: relative11, sep: sep8 } = await import("node:path");
459795
- if (isAbsolute27(parsed.path) || parsed.path.length === 0) {
459958
+ const { isAbsolute: isAbsolute28, join: join100, normalize: normalize5, relative: relative12, sep: sep9 } = await import("node:path");
459959
+ if (isAbsolute28(parsed.path) || parsed.path.length === 0) {
459796
459960
  sendFailure("path must be a non-empty relative path");
459797
459961
  return;
459798
459962
  }
459799
459963
  const memoryRoot = getScopedMemoryFilesystemRoot2(parsed.agent_id);
459800
- const absolutePath = normalize5(join99(memoryRoot, parsed.path));
459801
- const rel = relative11(memoryRoot, absolutePath);
459802
- if (rel.startsWith("..") || rel === "" || isAbsolute27(rel) || rel.split(sep8).includes("..")) {
459964
+ const absolutePath = normalize5(join100(memoryRoot, parsed.path));
459965
+ const rel = relative12(memoryRoot, absolutePath);
459966
+ if (rel.startsWith("..") || rel === "" || isAbsolute28(rel) || rel.split(sep9).includes("..")) {
459803
459967
  sendFailure("path must resolve inside the memory root");
459804
459968
  return;
459805
459969
  }
459806
- if (!existsSync64(join99(memoryRoot, ".git"))) {
459970
+ if (!existsSync64(join100(memoryRoot, ".git"))) {
459807
459971
  const enabled = await isMemfsEnabledOnServer2(parsed.agent_id);
459808
459972
  if (!enabled) {
459809
459973
  sendFailure("memfs is not enabled for this agent");
459810
459974
  return;
459811
459975
  }
459812
459976
  await ensureLocalMemfsCheckout2(parsed.agent_id);
459813
- if (!existsSync64(join99(memoryRoot, ".git"))) {
459977
+ if (!existsSync64(join100(memoryRoot, ".git"))) {
459814
459978
  sendFailure("failed to initialize local memory checkout");
459815
459979
  return;
459816
459980
  }
459817
459981
  }
459818
459982
  const buffer = await readFile28(absolutePath);
459819
459983
  const content = encoding === "base64" ? buffer.toString("base64") : buffer.toString("utf-8");
459820
- const pathspec = rel.split(sep8).join("/");
459984
+ const pathspec = rel.split(sep9).join("/");
459821
459985
  safeSocketSend(socket, {
459822
459986
  type: "read_memory_file_response",
459823
459987
  request_id: parsed.request_id,
@@ -459857,26 +460021,26 @@ function handleMemoryProtocolCommand(parsed, context3) {
459857
460021
  const { commitMemoryWrite: commitMemoryWrite2 } = await Promise.resolve().then(() => (init_memory_git(), exports_memory_git));
459858
460022
  const { writeFile: writeFile17, mkdir: mkdir15 } = await import("node:fs/promises");
459859
460023
  const { existsSync: existsSync64 } = await import("node:fs");
459860
- const { dirname: dirname39, isAbsolute: isAbsolute27, join: join99, normalize: normalize5, relative: relative11, sep: sep8 } = await import("node:path");
459861
- if (isAbsolute27(parsed.path) || parsed.path.length === 0) {
460024
+ const { dirname: dirname39, isAbsolute: isAbsolute28, join: join100, normalize: normalize5, relative: relative12, sep: sep9 } = await import("node:path");
460025
+ if (isAbsolute28(parsed.path) || parsed.path.length === 0) {
459862
460026
  sendFailure("write_memory_file: path must be a non-empty relative path");
459863
460027
  return;
459864
460028
  }
459865
460029
  const memoryRoot = getScopedMemoryFilesystemRoot2(parsed.agent_id);
459866
- const absolutePath = normalize5(join99(memoryRoot, parsed.path));
459867
- const rel = relative11(memoryRoot, absolutePath);
459868
- if (rel.startsWith("..") || rel === "" || isAbsolute27(rel) || rel.split(sep8).includes("..")) {
460030
+ const absolutePath = normalize5(join100(memoryRoot, parsed.path));
460031
+ const rel = relative12(memoryRoot, absolutePath);
460032
+ if (rel.startsWith("..") || rel === "" || isAbsolute28(rel) || rel.split(sep9).includes("..")) {
459869
460033
  sendFailure("write_memory_file: path must resolve inside the memory root");
459870
460034
  return;
459871
460035
  }
459872
- if (!existsSync64(join99(memoryRoot, ".git"))) {
460036
+ if (!existsSync64(join100(memoryRoot, ".git"))) {
459873
460037
  const enabled = await isMemfsEnabledOnServer2(parsed.agent_id);
459874
460038
  if (!enabled) {
459875
460039
  sendFailure("write_memory_file: memfs is not enabled for this agent");
459876
460040
  return;
459877
460041
  }
459878
460042
  await ensureLocalMemfsCheckout2(parsed.agent_id);
459879
- if (!existsSync64(join99(memoryRoot, ".git"))) {
460043
+ if (!existsSync64(join100(memoryRoot, ".git"))) {
459880
460044
  sendFailure("write_memory_file: failed to initialize local memory checkout");
459881
460045
  return;
459882
460046
  }
@@ -459894,7 +460058,7 @@ function handleMemoryProtocolCommand(parsed, context3) {
459894
460058
  agentName = agent.name.trim();
459895
460059
  }
459896
460060
  } catch {}
459897
- const pathspec = rel.split(sep8).join("/");
460061
+ const pathspec = rel.split(sep9).join("/");
459898
460062
  const reason = parsed.commit_message?.trim() || `Update memory file ${pathspec}`;
459899
460063
  const commitResult = await commitMemoryWrite2({
459900
460064
  memoryDir: memoryRoot,
@@ -459955,31 +460119,31 @@ function handleMemoryProtocolCommand(parsed, context3) {
459955
460119
  const { commitMemoryWrite: commitMemoryWrite2 } = await Promise.resolve().then(() => (init_memory_git(), exports_memory_git));
459956
460120
  const { unlink: unlink3 } = await import("node:fs/promises");
459957
460121
  const { existsSync: existsSync64 } = await import("node:fs");
459958
- const { isAbsolute: isAbsolute27, join: join99, normalize: normalize5, relative: relative11, sep: sep8 } = await import("node:path");
459959
- if (isAbsolute27(parsed.path) || parsed.path.length === 0) {
460122
+ const { isAbsolute: isAbsolute28, join: join100, normalize: normalize5, relative: relative12, sep: sep9 } = await import("node:path");
460123
+ if (isAbsolute28(parsed.path) || parsed.path.length === 0) {
459960
460124
  sendFailure("delete_memory_file: path must be a non-empty relative path");
459961
460125
  return;
459962
460126
  }
459963
460127
  const memoryRoot = getScopedMemoryFilesystemRoot2(parsed.agent_id);
459964
- const absolutePath = normalize5(join99(memoryRoot, parsed.path));
459965
- const rel = relative11(memoryRoot, absolutePath);
459966
- if (rel.startsWith("..") || rel === "" || isAbsolute27(rel) || rel.split(sep8).includes("..")) {
460128
+ const absolutePath = normalize5(join100(memoryRoot, parsed.path));
460129
+ const rel = relative12(memoryRoot, absolutePath);
460130
+ if (rel.startsWith("..") || rel === "" || isAbsolute28(rel) || rel.split(sep9).includes("..")) {
459967
460131
  sendFailure("delete_memory_file: path must resolve inside the memory root");
459968
460132
  return;
459969
460133
  }
459970
- if (!existsSync64(join99(memoryRoot, ".git"))) {
460134
+ if (!existsSync64(join100(memoryRoot, ".git"))) {
459971
460135
  const enabled = await isMemfsEnabledOnServer2(parsed.agent_id);
459972
460136
  if (!enabled) {
459973
460137
  sendFailure("delete_memory_file: memfs is not enabled for this agent");
459974
460138
  return;
459975
460139
  }
459976
460140
  await ensureLocalMemfsCheckout2(parsed.agent_id);
459977
- if (!existsSync64(join99(memoryRoot, ".git"))) {
460141
+ if (!existsSync64(join100(memoryRoot, ".git"))) {
459978
460142
  sendFailure("delete_memory_file: failed to initialize local memory checkout");
459979
460143
  return;
459980
460144
  }
459981
460145
  }
459982
- const pathspec = rel.split(sep8).join("/");
460146
+ const pathspec = rel.split(sep9).join("/");
459983
460147
  const removeIfPresent = async () => {
459984
460148
  if (!existsSync64(absolutePath))
459985
460149
  return false;
@@ -460108,10 +460272,10 @@ __export(exports_remote_model_catalog, {
460108
460272
  __testResetRemoteModelCatalog: () => __testResetRemoteModelCatalog
460109
460273
  });
460110
460274
  import { existsSync as existsSync64, mkdirSync as mkdirSync50, readFileSync as readFileSync51, writeFileSync as writeFileSync43 } from "node:fs";
460111
- import { dirname as dirname39, join as join99 } from "node:path";
460275
+ import { dirname as dirname39, join as join100 } from "node:path";
460112
460276
  function catalogCachePath() {
460113
- const dir = process.env.LETTA_MODEL_CATALOG_CACHE_DIR || join99(resolveGlobalConfigDir(), "cache");
460114
- return join99(dir, "model-catalog.json");
460277
+ const dir = process.env.LETTA_MODEL_CATALOG_CACHE_DIR || join100(resolveGlobalConfigDir(), "cache");
460278
+ return join100(dir, "model-catalog.json");
460115
460279
  }
460116
460280
  function normalizeCatalogSource(source) {
460117
460281
  try {
@@ -461530,7 +461694,7 @@ async function handleSkillCommand(parsed, socket, safeSocketSend) {
461530
461694
  symlinkSync: symlinkSync2,
461531
461695
  unlinkSync: unlinkSync18
461532
461696
  } = await import("node:fs");
461533
- const { basename: basename30, join: join100 } = await import("node:path");
461697
+ const { basename: basename30, join: join101 } = await import("node:path");
461534
461698
  const globalSkillsDir = getGlobalSkillsDir();
461535
461699
  if (parsed.type === "skill_enable") {
461536
461700
  try {
@@ -461543,7 +461707,7 @@ async function handleSkillCommand(parsed, socket, safeSocketSend) {
461543
461707
  }, "listener_skill_send_failed", "listener_skill_command");
461544
461708
  return true;
461545
461709
  }
461546
- const skillMdPath = join100(parsed.skill_path, "SKILL.md");
461710
+ const skillMdPath = join101(parsed.skill_path, "SKILL.md");
461547
461711
  if (!existsSync65(skillMdPath)) {
461548
461712
  safeSocketSend(socket, {
461549
461713
  type: "skill_enable_response",
@@ -461554,7 +461718,7 @@ async function handleSkillCommand(parsed, socket, safeSocketSend) {
461554
461718
  return true;
461555
461719
  }
461556
461720
  const linkName = basename30(parsed.skill_path);
461557
- const linkPath = join100(globalSkillsDir, linkName);
461721
+ const linkPath = join101(globalSkillsDir, linkName);
461558
461722
  mkdirSync51(globalSkillsDir, { recursive: true });
461559
461723
  if (existsSync65(linkPath)) {
461560
461724
  const stat15 = lstatSync4(linkPath);
@@ -461597,7 +461761,7 @@ async function handleSkillCommand(parsed, socket, safeSocketSend) {
461597
461761
  }
461598
461762
  if (parsed.type === "skill_disable") {
461599
461763
  try {
461600
- const linkPath = join100(globalSkillsDir, parsed.name);
461764
+ const linkPath = join101(globalSkillsDir, parsed.name);
461601
461765
  if (!existsSync65(linkPath)) {
461602
461766
  safeSocketSend(socket, {
461603
461767
  type: "skill_disable_response",
@@ -462369,7 +462533,7 @@ async function waitForPairedSocketAcceptance(socket, identity3) {
462369
462533
  return { status: "closed" };
462370
462534
  }
462371
462535
  const timeoutMs = getStreamOpenTimeoutMs();
462372
- return await new Promise((resolve38) => {
462536
+ return await new Promise((resolve39) => {
462373
462537
  let settled = false;
462374
462538
  const timeout = setTimeout(() => settle3({ status: "timed_out", timeoutMs }), timeoutMs);
462375
462539
  timeout.unref?.();
@@ -462384,7 +462548,7 @@ async function waitForPairedSocketAcceptance(socket, identity3) {
462384
462548
  return;
462385
462549
  settled = true;
462386
462550
  cleanup();
462387
- resolve38(result3);
462551
+ resolve39(result3);
462388
462552
  }
462389
462553
  function handleFailure() {
462390
462554
  settle3({ status: "closed" });
@@ -462412,7 +462576,7 @@ async function waitForStreamSocketOpen(streamSocket) {
462412
462576
  return { status: "closed" };
462413
462577
  }
462414
462578
  const timeoutMs = getStreamOpenTimeoutMs();
462415
- return await new Promise((resolve38) => {
462579
+ return await new Promise((resolve39) => {
462416
462580
  let timeout = null;
462417
462581
  let settled = false;
462418
462582
  function cleanup() {
@@ -462430,7 +462594,7 @@ async function waitForStreamSocketOpen(streamSocket) {
462430
462594
  }
462431
462595
  settled = true;
462432
462596
  cleanup();
462433
- resolve38(result3);
462597
+ resolve39(result3);
462434
462598
  }
462435
462599
  function handleOpen() {
462436
462600
  settle3({ status: "open", transport: streamSocket });
@@ -463587,7 +463751,7 @@ var init_message_router = __esm(() => {
463587
463751
  });
463588
463752
 
463589
463753
  // src/websocket/listener/process-services.ts
463590
- import { join as join100 } from "node:path";
463754
+ import { join as join101 } from "node:path";
463591
463755
  function installProcessEventRouting(params) {
463592
463756
  const { runtime, processTransport, opts, processQueuedTurn } = params;
463593
463757
  runtime._unsubscribeSubagentState?.();
@@ -463599,16 +463763,33 @@ function installProcessEventRouting(params) {
463599
463763
  }
463600
463764
  emitSubagentStateUpdate(transport3, runtime, scope, TO_SUBSCRIBERS, options);
463601
463765
  };
463766
+ let previousOwnerScopes = new Map;
463602
463767
  runtime._unsubscribeSubagentState = subscribe2(() => {
463603
- if (runtime.conversationRuntimes.size === 0) {
463604
- emitSubagentState();
463605
- return;
463768
+ const ownerScopes = new Map;
463769
+ for (const subagent of getSubagents()) {
463770
+ if (!subagent.parentAgentId)
463771
+ continue;
463772
+ const scope = {
463773
+ agent_id: subagent.parentAgentId,
463774
+ conversation_id: subagent.parentConversationId ?? "default"
463775
+ };
463776
+ ownerScopes.set(JSON.stringify(scope), scope);
463606
463777
  }
463778
+ const scopes = new Map([...previousOwnerScopes, ...ownerScopes]);
463779
+ previousOwnerScopes = ownerScopes;
463607
463780
  for (const conversationRuntime of runtime.conversationRuntimes.values()) {
463608
- emitSubagentState({
463781
+ const scope = {
463609
463782
  agent_id: conversationRuntime.agentId,
463610
463783
  conversation_id: conversationRuntime.conversationId
463611
- }, { onlyIfChanged: true });
463784
+ };
463785
+ scopes.set(JSON.stringify(scope), scope);
463786
+ }
463787
+ if (scopes.size === 0) {
463788
+ emitSubagentState();
463789
+ return;
463790
+ }
463791
+ for (const scope of scopes.values()) {
463792
+ emitSubagentState(scope, { onlyIfChanged: true });
463612
463793
  }
463613
463794
  });
463614
463795
  runtime._unsubscribeSubagentStreamEvents?.();
@@ -463677,7 +463858,7 @@ function installProcessEventRouting(params) {
463677
463858
  scheduleQueuePump(targetRuntime, processTransport, opts, processQueuedTurn);
463678
463859
  });
463679
463860
  runtime._stopDiskSpaceWatch?.();
463680
- runtime._stopDiskSpaceWatch = watchSandboxDiskSpace(getCurrentWorkingDirectory, (text3) => deliverSandboxDiskAlert(runtime, text3), { reserveDirectory: join100(resolveGlobalConfigDir(), "state") });
463861
+ runtime._stopDiskSpaceWatch = watchSandboxDiskSpace(getCurrentWorkingDirectory, (text3) => deliverSandboxDiskAlert(runtime, text3), { reserveDirectory: join101(resolveGlobalConfigDir(), "state") });
463681
463862
  }
463682
463863
  function deliverSandboxDiskAlert(runtime, text3) {
463683
463864
  const target = getMostRecentlyActiveConversation(runtime);
@@ -464751,11 +464932,11 @@ async function replaySyncStateForRuntime(listenerRuntime, socket, scope, opts) {
464751
464932
  if (syncScopedRuntime.recoveredApprovalState && (syncScopedRuntime.recoveredApprovalState.autoDecisions?.length ?? 0) > 0) {
464752
464933
  let signalLeaseReady;
464753
464934
  let releaseLeaseBarrier;
464754
- const leaseReady = new Promise((resolve38) => {
464755
- signalLeaseReady = resolve38;
464935
+ const leaseReady = new Promise((resolve39) => {
464936
+ signalLeaseReady = resolve39;
464756
464937
  });
464757
- const leaseBarrier = new Promise((resolve38) => {
464758
- releaseLeaseBarrier = resolve38;
464938
+ const leaseBarrier = new Promise((resolve39) => {
464939
+ releaseLeaseBarrier = resolve39;
464759
464940
  });
464760
464941
  const recovery = startRecoveredApprovalContinuation(syncScopedRuntime, getOrCreateProcessTransport(listenerRuntime), opts?.processIncomingMessage ?? handleIncomingMessage, {
464761
464942
  onStatusChange: opts?.onStatusChange,
@@ -465159,8 +465340,8 @@ async function connectWithRetry(runtime, opts, attempt2 = 0, startTime = Date.no
465159
465340
  }
465160
465341
  const delay7 = Math.min(INITIAL_RETRY_DELAY_MS2 * 2 ** (attempt2 - 1), MAX_RETRY_DELAY_MS);
465161
465342
  opts.onRetrying?.(attempt2, MAX_RETRY_ATTEMPTS, delay7, opts.connectionId);
465162
- await new Promise((resolve38) => {
465163
- runtime.reconnectTimeout = setTimeout(resolve38, delay7);
465343
+ await new Promise((resolve39) => {
465344
+ runtime.reconnectTimeout = setTimeout(resolve39, delay7);
465164
465345
  });
465165
465346
  runtime.reconnectTimeout = null;
465166
465347
  if (runtime !== getActiveRuntime() || runtime.intentionallyClosed) {
@@ -465521,7 +465702,7 @@ async function runTurnViaListenerRuntime(params) {
465521
465702
  }
465522
465703
  };
465523
465704
  const processQueuedTurn = createConnectionTurnProcessor(listener);
465524
- return await new Promise((resolve38) => {
465705
+ return await new Promise((resolve39) => {
465525
465706
  let text3 = "";
465526
465707
  let reasoning = "";
465527
465708
  let usage = {
@@ -465548,7 +465729,7 @@ async function runTurnViaListenerRuntime(params) {
465548
465729
  observers.delete(observer);
465549
465730
  unregisterTurnObserver();
465550
465731
  toolTracker?.dispose();
465551
- resolve38({ text: text3, reasoning, usage, error: error4 });
465732
+ resolve39({ text: text3, reasoning, usage, error: error4 });
465552
465733
  };
465553
465734
  const observer = (message2) => {
465554
465735
  if (message2.type === "runtime_stopped") {
@@ -466688,14 +466869,14 @@ async function startAppServer(options = {}) {
466688
466869
  clearInterval(heartbeatInterval);
466689
466870
  });
466690
466871
  try {
466691
- await new Promise((resolve38, reject2) => {
466872
+ await new Promise((resolve39, reject2) => {
466692
466873
  const onError = (error4) => {
466693
466874
  server2.off("listening", onListening);
466694
466875
  reject2(error4);
466695
466876
  };
466696
466877
  const onListening = () => {
466697
466878
  server2.off("error", onError);
466698
- resolve38();
466879
+ resolve39();
466699
466880
  };
466700
466881
  server2.once("error", onError);
466701
466882
  server2.once("listening", onListening);
@@ -466716,7 +466897,7 @@ async function startAppServer(options = {}) {
466716
466897
  setActiveRuntime(runtime);
466717
466898
  } else if (getActiveRuntime() !== runtime) {
466718
466899
  clearInterval(heartbeatInterval);
466719
- await new Promise((resolve38) => server2.close(() => resolve38()));
466900
+ await new Promise((resolve39) => server2.close(() => resolve39()));
466720
466901
  throw new Error("Shared app-server runtime must be the active listener runtime");
466721
466902
  }
466722
466903
  if (ownsRuntime) {
@@ -466744,16 +466925,16 @@ async function startAppServer(options = {}) {
466744
466925
  stopRuntime(runtime, true);
466745
466926
  setActiveRuntime(null);
466746
466927
  }
466747
- await new Promise((resolve38, reject2) => {
466928
+ await new Promise((resolve39, reject2) => {
466748
466929
  wss.close();
466749
- const timeout = setTimeout(resolve38, 1000);
466930
+ const timeout = setTimeout(resolve39, 1000);
466750
466931
  server2.close((serverError) => {
466751
466932
  clearTimeout(timeout);
466752
466933
  if (serverError) {
466753
466934
  reject2(serverError);
466754
466935
  return;
466755
466936
  }
466756
- resolve38();
466937
+ resolve39();
466757
466938
  });
466758
466939
  });
466759
466940
  }
@@ -466801,7 +466982,7 @@ Examples:
466801
466982
  letta server --listen ws://127.0.0.1:4500 --openai-api`);
466802
466983
  }
466803
466984
  async function waitForShutdown(close) {
466804
- return await new Promise((resolve38) => {
466985
+ return await new Promise((resolve39) => {
466805
466986
  let shuttingDown = false;
466806
466987
  const shutdown = (signal) => {
466807
466988
  if (shuttingDown)
@@ -466810,10 +466991,10 @@ async function waitForShutdown(close) {
466810
466991
  close().then(() => {
466811
466992
  console.log(`
466812
466993
  Stopped App Server (${signal}).`);
466813
- resolve38(0);
466994
+ resolve39(0);
466814
466995
  }).catch((error4) => {
466815
466996
  console.error(error4 instanceof Error ? `Error: ${error4.message}` : String(error4));
466816
- resolve38(1);
466997
+ resolve39(1);
466817
466998
  });
466818
466999
  };
466819
467000
  process.once("SIGINT", shutdown);
@@ -467199,7 +467380,7 @@ import {
467199
467380
  readdirSync as readdirSync26,
467200
467381
  unlinkSync as unlinkSync18
467201
467382
  } from "node:fs";
467202
- import { join as join101 } from "node:path";
467383
+ import { join as join102 } from "node:path";
467203
467384
  function formatTimestamp2() {
467204
467385
  const now2 = new Date;
467205
467386
  const h3 = String(now2.getHours()).padStart(2, "0");
@@ -467220,7 +467401,7 @@ function pruneOldLogs(dir, maxFiles) {
467220
467401
  const toDelete = files.slice(0, files.length - maxFiles + 1);
467221
467402
  for (const file of toDelete) {
467222
467403
  try {
467223
- unlinkSync18(join101(dir, file));
467404
+ unlinkSync18(join102(dir, file));
467224
467405
  } catch {}
467225
467406
  }
467226
467407
  }
@@ -467259,7 +467440,7 @@ class RemoteSessionLog {
467259
467440
  freshPath() {
467260
467441
  const stamp = formatFileTimestamp(new Date);
467261
467442
  const suffix = this.rotation > 0 ? `.${this.rotation}` : "";
467262
- return join101(this.dir, `${stamp}${suffix}.log`);
467443
+ return join102(this.dir, `${stamp}${suffix}.log`);
467263
467444
  }
467264
467445
  rotate() {
467265
467446
  const previous = this.path;
@@ -467300,13 +467481,13 @@ var REMOTE_LOG_DIR, MAX_LOG_FILES = 10, MAX_LOG_BYTES2;
467300
467481
  var init_listen_log = __esm(() => {
467301
467482
  init_settings_path();
467302
467483
  init_ws_event_redaction();
467303
- REMOTE_LOG_DIR = join101(resolveGlobalConfigDir(), "logs", "remote");
467484
+ REMOTE_LOG_DIR = join102(resolveGlobalConfigDir(), "logs", "remote");
467304
467485
  MAX_LOG_BYTES2 = 10 * 1024 * 1024;
467305
467486
  });
467306
467487
 
467307
467488
  // src/websocket/listener/manual-instance-lock.ts
467308
467489
  import { createHash as createHash21, randomUUID as randomUUID60 } from "node:crypto";
467309
- import { link as link4, mkdir as mkdir15, readFile as readFile28, rm as rm11, unlink as unlink3, writeFile as writeFile17 } from "node:fs/promises";
467490
+ import { link as link4, mkdir as mkdir15, readFile as readFile28, rm as rm12, unlink as unlink3, writeFile as writeFile17 } from "node:fs/promises";
467310
467491
  import { uptime as uptime2 } from "node:os";
467311
467492
  import path46 from "node:path";
467312
467493
  function hasErrorCode3(error4, code) {
@@ -467380,7 +467561,7 @@ async function publishInitializedFile(targetPath, contents) {
467380
467561
  } catch (error4) {
467381
467562
  publicationError = error4;
467382
467563
  }
467383
- await rm11(candidatePath, { force: true }).catch(() => {});
467564
+ await rm12(candidatePath, { force: true }).catch(() => {});
467384
467565
  return publicationError;
467385
467566
  }
467386
467567
  function getRecoveryClaimPath2(lockPath, staleContents, depth) {
@@ -467389,7 +467570,7 @@ function getRecoveryClaimPath2(lockPath, staleContents, depth) {
467389
467570
  }
467390
467571
  async function cleanupRecoveryClaims2(lockPath, staleContents, deepestClaim) {
467391
467572
  for (let depth = deepestClaim;depth >= 0; depth--) {
467392
- await rm11(getRecoveryClaimPath2(lockPath, staleContents, depth), {
467573
+ await rm12(getRecoveryClaimPath2(lockPath, staleContents, depth), {
467393
467574
  force: true
467394
467575
  }).catch(() => {});
467395
467576
  }
@@ -468050,8 +468231,8 @@ async function startChannelGatewaySupervisor(options) {
468050
468231
  let resolveInitialReady = null;
468051
468232
  let rejectInitialReady = null;
468052
468233
  const pendingCommands = new Map;
468053
- const initialReady = new Promise((resolve38, reject2) => {
468054
- resolveInitialReady = resolve38;
468234
+ const initialReady = new Promise((resolve39, reject2) => {
468235
+ resolveInitialReady = resolve39;
468055
468236
  rejectInitialReady = reject2;
468056
468237
  });
468057
468238
  function clearStableTimer() {
@@ -468277,7 +468458,7 @@ async function startChannelGatewaySupervisor(options) {
468277
468458
  clearTimeout(startupTimeout);
468278
468459
  }
468279
468460
  return {
468280
- request: (command) => new Promise((resolve38, reject2) => {
468461
+ request: (command) => new Promise((resolve39, reject2) => {
468281
468462
  const activeChild = readyChild;
468282
468463
  if (!activeChild?.stdin?.writable) {
468283
468464
  reject2(new Error("ChannelGateway process is not available"));
@@ -468288,7 +468469,7 @@ async function startChannelGatewaySupervisor(options) {
468288
468469
  pendingCommands.delete(requestId);
468289
468470
  reject2(new Error(`ChannelGateway command timed out: ${command.kind}`));
468290
468471
  }, COMMAND_TIMEOUT_MS);
468291
- pendingCommands.set(requestId, { resolve: resolve38, reject: reject2, timeout });
468472
+ pendingCommands.set(requestId, { resolve: resolve39, reject: reject2, timeout });
468292
468473
  activeChild.stdin.write(`${JSON.stringify({ type: "command", requestId, command })}
468293
468474
  `, (error4) => {
468294
468475
  if (!error4)
@@ -468313,14 +468494,14 @@ async function startChannelGatewaySupervisor(options) {
468313
468494
  rejectPendingCommands(closeError);
468314
468495
  if (!activeChild || activeChild.exitCode !== null)
468315
468496
  return;
468316
- await new Promise((resolve38) => {
468497
+ await new Promise((resolve39) => {
468317
468498
  const timeout = setTimeout(() => {
468318
468499
  activeChild.kill("SIGKILL");
468319
- resolve38();
468500
+ resolve39();
468320
468501
  }, SHUTDOWN_TIMEOUT_MS);
468321
468502
  activeChild.once("exit", () => {
468322
468503
  clearTimeout(timeout);
468323
- resolve38();
468504
+ resolve39();
468324
468505
  });
468325
468506
  activeChild.kill("SIGTERM");
468326
468507
  });
@@ -469026,7 +469207,7 @@ import {
469026
469207
  readFileSync as readFileSync52,
469027
469208
  writeFileSync as writeFileSync44
469028
469209
  } from "node:fs";
469029
- import { join as join102 } from "node:path";
469210
+ import { join as join103 } from "node:path";
469030
469211
  function readJsonl(path47) {
469031
469212
  if (!existsSync66(path47))
469032
469213
  return [];
@@ -469309,7 +469490,7 @@ function convertMessages4(messages, mode, nextId2) {
469309
469490
  }
469310
469491
  function migrateLocalBackendTranscripts(input) {
469311
469492
  const storageDir = input.storageDir;
469312
- const conversationsDir = join102(storageDir, "conversations");
469493
+ const conversationsDir = join103(storageDir, "conversations");
469313
469494
  const result3 = {
469314
469495
  storageDir,
469315
469496
  converted: [],
@@ -469319,9 +469500,9 @@ function migrateLocalBackendTranscripts(input) {
469319
469500
  if (!existsSync66(conversationsDir))
469320
469501
  return result3;
469321
469502
  for (const name of readdirSync27(conversationsDir)) {
469322
- const conversationDir = join102(conversationsDir, name);
469323
- const messagesPath = join102(conversationDir, "messages.jsonl");
469324
- const manifestPath = join102(conversationDir, "manifest.json");
469503
+ const conversationDir = join103(conversationsDir, name);
469504
+ const messagesPath = join103(conversationDir, "messages.jsonl");
469505
+ const manifestPath = join103(conversationDir, "manifest.json");
469325
469506
  const hasManifest = existsSync66(manifestPath);
469326
469507
  const existingManifest = hasManifest ? (() => {
469327
469508
  try {
@@ -469364,7 +469545,7 @@ function migrateLocalBackendTranscripts(input) {
469364
469545
  const backupPath = `${messagesPath}.pre-pi-backup-${timestampSuffix()}`;
469365
469546
  if (!input.dryRun) {
469366
469547
  copyFileSync3(messagesPath, backupPath);
469367
- const conversationPath = join102(conversationDir, "conversation.json");
469548
+ const conversationPath = join103(conversationDir, "conversation.json");
469368
469549
  let conversation;
469369
469550
  if (existsSync66(conversationPath)) {
469370
469551
  try {
@@ -469562,7 +469743,7 @@ var init_memory_tokens = __esm(() => {
469562
469743
  // src/cli/subcommands/memory.ts
469563
469744
  import { cpSync, existsSync as existsSync67, mkdirSync as mkdirSync53, rmSync as rmSync24, statSync as statSync26 } from "node:fs";
469564
469745
  import { readdir as readdir12 } from "node:fs/promises";
469565
- import { dirname as dirname40, join as join103 } from "node:path";
469746
+ import { dirname as dirname40, join as join104 } from "node:path";
469566
469747
  import { parseArgs as parseArgs12 } from "node:util";
469567
469748
  function printUsage8() {
469568
469749
  console.log(`
@@ -469632,7 +469813,7 @@ async function listBackups(agentId) {
469632
469813
  continue;
469633
469814
  if (!entry.name.startsWith("memory-backup-"))
469634
469815
  continue;
469635
- const path47 = join103(agentRoot, entry.name);
469816
+ const path47 = join104(agentRoot, entry.name);
469636
469817
  let createdAt = null;
469637
469818
  try {
469638
469819
  const stat15 = statSync26(path47);
@@ -469649,7 +469830,7 @@ function resolveBackupPath(agentId, from) {
469649
469830
  if (from.startsWith("/") || /^[A-Za-z]:[/\\]/.test(from)) {
469650
469831
  return from;
469651
469832
  }
469652
- return join103(getAgentRoot(agentId), from);
469833
+ return join104(getAgentRoot(agentId), from);
469653
469834
  }
469654
469835
  async function runMemorySubcommand(argv, deps = {}) {
469655
469836
  let parsed;
@@ -469733,7 +469914,7 @@ async function runMemorySubcommand(argv, deps = {}) {
469733
469914
  }
469734
469915
  const agentRoot = getAgentRoot(agentId);
469735
469916
  const backupName = `memory-backup-${formatBackupTimestamp()}`;
469736
- const backupPath = join103(agentRoot, backupName);
469917
+ const backupPath = join104(agentRoot, backupName);
469737
469918
  if (existsSync67(backupPath)) {
469738
469919
  console.error(`Backup already exists at ${backupPath}`);
469739
469920
  return 1;
@@ -469834,7 +470015,7 @@ var init_memory6 = __esm(() => {
469834
470015
 
469835
470016
  // src/backend/local/transcript-search.ts
469836
470017
  import { existsSync as existsSync68, readdirSync as readdirSync28, readFileSync as readFileSync53, statSync as statSync27 } from "node:fs";
469837
- import { join as join104 } from "node:path";
470018
+ import { join as join105 } from "node:path";
469838
470019
  function readJsonFile3(path47) {
469839
470020
  if (!existsSync68(path47))
469840
470021
  return;
@@ -470079,7 +470260,7 @@ function collectConversationMessages(input) {
470079
470260
  return [];
470080
470261
  if (input.conversationId && conversation.id !== input.conversationId)
470081
470262
  return [];
470082
- const manifest2 = readJsonFile3(join104(conversationDir, "manifest.json"));
470263
+ const manifest2 = readJsonFile3(join105(conversationDir, "manifest.json"));
470083
470264
  let format3 = transcriptFormatFromManifest(manifest2);
470084
470265
  const records2 = [];
470085
470266
  const echoToolCallIds = [];
@@ -470139,7 +470320,7 @@ function collectConversationMessages(input) {
470139
470320
  }
470140
470321
  addRow(row, rowIndex);
470141
470322
  };
470142
- const messagesPath = join104(conversationDir, "messages.jsonl");
470323
+ const messagesPath = join105(conversationDir, "messages.jsonl");
470143
470324
  let rowError;
470144
470325
  try {
470145
470326
  forEachJsonlRow(messagesPath, (row) => {
@@ -470168,11 +470349,11 @@ function collectConversationMessages(input) {
470168
470349
  return records2;
470169
470350
  }
470170
470351
  function conversationDirectories(storageDir) {
470171
- const conversationsDir = join104(storageDir, "conversations");
470352
+ const conversationsDir = join105(storageDir, "conversations");
470172
470353
  if (!existsSync68(conversationsDir))
470173
470354
  return [];
470174
470355
  try {
470175
- return readdirSync28(conversationsDir).map((entry) => join104(conversationsDir, entry)).filter((entryPath) => statSync27(entryPath).isDirectory());
470356
+ return readdirSync28(conversationsDir).map((entry) => join105(conversationsDir, entry)).filter((entryPath) => statSync27(entryPath).isDirectory());
470176
470357
  } catch {
470177
470358
  return [];
470178
470359
  }
@@ -470199,7 +470380,7 @@ function searchLocalTranscriptMessages(storageDir, body3, options = {}) {
470199
470380
  const endDate = typeof body3.end_date === "string" ? body3.end_date : undefined;
470200
470381
  const includeHidden = body3.include_hidden === true;
470201
470382
  const records2 = conversationDirectories(storageDir).flatMap((conversationDir) => {
470202
- const conversation = conversationSearchRecord(readJsonFile3(join104(conversationDir, "conversation.json")));
470383
+ const conversation = conversationSearchRecord(readJsonFile3(join105(conversationDir, "conversation.json")));
470203
470384
  if (!conversation)
470204
470385
  return [];
470205
470386
  if (conversation.hidden && !includeHidden)
@@ -470303,7 +470484,7 @@ var init_message_status = __esm(() => {
470303
470484
 
470304
470485
  // src/cli/subcommands/messages.ts
470305
470486
  import { writeFile as writeFile18 } from "node:fs/promises";
470306
- import { resolve as resolve38 } from "node:path";
470487
+ import { resolve as resolve39 } from "node:path";
470307
470488
  import { parseArgs as parseArgs13 } from "node:util";
470308
470489
  function printUsage9() {
470309
470490
  console.log(`
@@ -470633,7 +470814,7 @@ async function runMessagesSubcommand(argv, deps = {}) {
470633
470814
  const pageLimit = Math.max(1, parseLimit3(parsed.values.limit, 100));
470634
470815
  const maxPages = Math.max(1, parseLimit3(parsed.values["max-pages"], 200));
470635
470816
  const outputPathRaw = parsed.values.out || parsed.values.output;
470636
- const outputPath = outputPathRaw ? resolve38(process.cwd(), outputPathRaw) : undefined;
470817
+ const outputPath = outputPathRaw ? resolve39(process.cwd(), outputPathRaw) : undefined;
470637
470818
  const { messages, truncated } = await fetchConversationMessages(conversationId, agentId || undefined, pageLimit, maxPages);
470638
470819
  const transcript2 = messages.flatMap((msg) => formatEntry(msg)).join(`
470639
470820
 
@@ -470871,9 +471052,9 @@ function filterStructuredOutputRows(rows) {
470871
471052
  return { supported, unknownCount };
470872
471053
  }
470873
471054
  async function printJson3(value) {
470874
- await new Promise((resolve39, reject2) => {
471055
+ await new Promise((resolve40, reject2) => {
470875
471056
  process.stdout.write(`${JSON.stringify(value, null, 2)}
470876
- `, (error4) => error4 ? reject2(error4) : resolve39());
471057
+ `, (error4) => error4 ? reject2(error4) : resolve40());
470877
471058
  });
470878
471059
  }
470879
471060
  async function runModelSubcommand(argv) {
@@ -471250,8 +471431,8 @@ function isRecord21(value) {
471250
471431
  function isPathInsideOrEqual2(childPath, parentPath) {
471251
471432
  const child = path47.resolve(childPath);
471252
471433
  const parent = path47.resolve(parentPath);
471253
- const relative11 = path47.relative(parent, child);
471254
- return relative11 === "" || !!relative11 && !relative11.startsWith("..") && !path47.isAbsolute(relative11);
471434
+ const relative12 = path47.relative(parent, child);
471435
+ return relative12 === "" || !!relative12 && !relative12.startsWith("..") && !path47.isAbsolute(relative12);
471255
471436
  }
471256
471437
  function readPackageJson(packageJsonPath) {
471257
471438
  let parsed;
@@ -471592,7 +471773,7 @@ function writeNpmInstallManifest(tempRoot) {
471592
471773
  `);
471593
471774
  }
471594
471775
  function runProcess2(params) {
471595
- return new Promise((resolve39, reject2) => {
471776
+ return new Promise((resolve40, reject2) => {
471596
471777
  const child = params.spawnImpl(params.command, params.args, {
471597
471778
  cwd: params.cwd,
471598
471779
  stdio: ["ignore", "pipe", "pipe"]
@@ -471608,7 +471789,7 @@ function runProcess2(params) {
471608
471789
  child.on("error", reject2);
471609
471790
  child.on("exit", (code) => {
471610
471791
  if (code === 0) {
471611
- resolve39({ stderr: stderr.join(""), stdout: stdout.join("") });
471792
+ resolve40({ stderr: stderr.join(""), stdout: stdout.join("") });
471612
471793
  return;
471613
471794
  }
471614
471795
  const details = stderr.join("").trim() || stdout.join("").trim();
@@ -472228,7 +472409,7 @@ var init_package_scaffolder = __esm(() => {
472228
472409
  });
472229
472410
 
472230
472411
  // src/cli/subcommands/mods.ts
472231
- import { dirname as dirname41, join as join105 } from "node:path";
472412
+ import { dirname as dirname41, join as join106 } from "node:path";
472232
472413
  import { parseArgs as parseArgs15 } from "node:util";
472233
472414
  function printUsage11() {
472234
472415
  console.log(`
@@ -472267,7 +472448,7 @@ function getExplicitAgentId(values4) {
472267
472448
  return typeof explicitAgent === "string" && explicitAgent.trim() ? explicitAgent.trim() : null;
472268
472449
  }
472269
472450
  function getAgentModsDirectory(agentId) {
472270
- return join105(getScopedMemoryFilesystemRoot(agentId), "mods");
472451
+ return join106(getScopedMemoryFilesystemRoot(agentId), "mods");
472271
472452
  }
472272
472453
  function directFilesForSource(source) {
472273
472454
  return source.files.filter((file) => dirname41(file) === source.root);
@@ -472754,7 +472935,7 @@ var init_sandbox_files = __esm(() => {
472754
472935
 
472755
472936
  // src/cli/subcommands/sandbox.ts
472756
472937
  import { readFile as readFile29, stat as stat15, writeFile as writeFile19 } from "node:fs/promises";
472757
- import { basename as basename30, resolve as resolve39 } from "node:path";
472938
+ import { basename as basename30, resolve as resolve40 } from "node:path";
472758
472939
  import { parseArgs as parseArgs17 } from "node:util";
472759
472940
  function printUsage13() {
472760
472941
  console.log(`
@@ -472977,7 +473158,7 @@ async function runSandboxSubcommand(argv, deps = {}) {
472977
473158
  if (path49 === undefined)
472978
473159
  throw new Error("Missing file path");
472979
473160
  if (action === "upload") {
472980
- const localPath3 = resolve39(path49);
473161
+ const localPath3 = resolve40(path49);
472981
473162
  const fileStat = await (deps.statLocalPath ?? stat15)(localPath3);
472982
473163
  if (!fileStat.isFile())
472983
473164
  throw new Error(`${localPath3} is not a file`);
@@ -472989,7 +473170,7 @@ async function runSandboxSubcommand(argv, deps = {}) {
472989
473170
  }
472990
473171
  const sandbox = await ensureSandbox();
472991
473172
  const data = await (deps.downloadFile ?? downloadFileFromSandbox)(sandbox.sandboxId, path49);
472992
- const localPath2 = resolve39(parsed.values.to ?? basename30(path49));
473173
+ const localPath2 = resolve40(parsed.values.to ?? basename30(path49));
472993
473174
  await (deps.writeLocalFile ?? writeFile19)(localPath2, data);
472994
473175
  console.log(JSON.stringify({
472995
473176
  path: localPath2,
@@ -473758,7 +473939,7 @@ __export(exports_setup, {
473758
473939
  runSetup: () => runSetup
473759
473940
  });
473760
473941
  async function runSetup(options = {}) {
473761
- return new Promise((resolve40) => {
473942
+ return new Promise((resolve41) => {
473762
473943
  let settled = false;
473763
473944
  let instance2;
473764
473945
  const settle3 = (result3) => {
@@ -473767,7 +473948,7 @@ async function runSetup(options = {}) {
473767
473948
  }
473768
473949
  settled = true;
473769
473950
  instance2.unmount();
473770
- resolve40(result3);
473951
+ resolve41(result3);
473771
473952
  };
473772
473953
  instance2 = render_default(import_react35.default.createElement(SetupUI, {
473773
473954
  initialMode: options.initialMode,
@@ -473822,7 +474003,7 @@ var init_setup7 = __esm(async () => {
473822
474003
 
473823
474004
  // src/cli/subcommands/shared-memory.ts
473824
474005
  import { existsSync as existsSync71 } from "node:fs";
473825
- import { join as join106 } from "node:path";
474006
+ import { join as join107 } from "node:path";
473826
474007
  import { parseArgs as parseArgs19 } from "node:util";
473827
474008
  function printUsage16() {
473828
474009
  console.log(`
@@ -474029,7 +474210,7 @@ async function runSharedMemorySubcommand(argv, deps = {}) {
474029
474210
  invalidateClientSkills(agentId);
474030
474211
  const recompileError = await recompileAndReportFailure(recompileAgent, agentId);
474031
474212
  const mountDir = getRepositoryMountDir(agentId, repository.name);
474032
- const mounted = existsSync71(join106(mountDir, ".git"));
474213
+ const mounted = existsSync71(join107(mountDir, ".git"));
474033
474214
  console.log(JSON.stringify({
474034
474215
  attached: true,
474035
474216
  repository: { id: repository.id, name: repository.name },
@@ -475621,7 +475802,7 @@ import {
475621
475802
  } from "node:fs";
475622
475803
  import { mkdir as mkdir16, readdir as readdir13 } from "node:fs/promises";
475623
475804
  import { tmpdir as tmpdir15 } from "node:os";
475624
- import { basename as basename31, dirname as dirname42, join as join107, normalize as normalize5, resolve as resolve40, sep as sep8 } from "node:path";
475805
+ import { basename as basename31, dirname as dirname42, join as join108, normalize as normalize5, resolve as resolve41, sep as sep9 } from "node:path";
475625
475806
  import { parseArgs as parseArgs20, TextDecoder as TextDecoder2, TextEncoder as TextEncoder2 } from "node:util";
475626
475807
  function printUsage17() {
475627
475808
  console.log(`
@@ -475892,14 +476073,14 @@ async function resolveBranchAndSubdir(location) {
475892
476073
  }
475893
476074
  async function cloneSkillSource(location) {
475894
476075
  const resolvedLocation = await resolveBranchAndSubdir(location);
475895
- const tmpDir = mkdtempSync6(join107(tmpdir15(), "letta-skill-install-"));
476076
+ const tmpDir = mkdtempSync6(join108(tmpdir15(), "letta-skill-install-"));
475896
476077
  const args = ["clone", "--depth", "1"];
475897
476078
  if (resolvedLocation.branch) {
475898
476079
  args.push("--branch", resolvedLocation.branch);
475899
476080
  }
475900
476081
  args.push(resolvedLocation.repoUrl, tmpDir);
475901
476082
  await execFile22("git", args, { timeout: 120000 });
475902
- const sourceDir = resolvedLocation.subdir ? join107(tmpDir, resolvedLocation.subdir) : tmpDir;
476083
+ const sourceDir = resolvedLocation.subdir ? join108(tmpDir, resolvedLocation.subdir) : tmpDir;
475903
476084
  return { tmpDir, sourceDir };
475904
476085
  }
475905
476086
  function assertDirectSkillFileSize(receivedBytes, maxBytes) {
@@ -475954,11 +476135,11 @@ async function downloadDirectSkillFileSource(location, options = {}) {
475954
476135
  throw new Error(`Direct skill file download failed for ${location.url}: ${response.status}`);
475955
476136
  }
475956
476137
  const skillText = await readResponseTextWithLimit(response, MAX_DIRECT_SKILL_FILE_BYTES);
475957
- const tmpDir = mkdtempSync6(join107(tmpdir15(), "letta-direct-skill-"));
476138
+ const tmpDir = mkdtempSync6(join108(tmpdir15(), "letta-direct-skill-"));
475958
476139
  try {
475959
- const sourceDir = join107(tmpDir, "skill");
476140
+ const sourceDir = join108(tmpDir, "skill");
475960
476141
  await mkdir16(sourceDir, { recursive: true });
475961
- writeFileSync47(join107(sourceDir, "SKILL.md"), skillText, "utf8");
476142
+ writeFileSync47(join108(sourceDir, "SKILL.md"), skillText, "utf8");
475962
476143
  return { tmpDir, sourceDir };
475963
476144
  } catch (error4) {
475964
476145
  rmSync27(tmpDir, { recursive: true, force: true });
@@ -475999,9 +476180,9 @@ function assertSafeZipMember(name) {
475999
476180
  }
476000
476181
  async function downloadClawHubSkillSource(location) {
476001
476182
  const version3 = await resolveClawHubVersion(location);
476002
- const tmpDir = mkdtempSync6(join107(tmpdir15(), "letta-clawhub-skill-"));
476003
- const zipPath = join107(tmpDir, "skill.zip");
476004
- const sourceDir = join107(tmpDir, "skill");
476183
+ const tmpDir = mkdtempSync6(join108(tmpdir15(), "letta-clawhub-skill-"));
476184
+ const zipPath = join108(tmpDir, "skill.zip");
476185
+ const sourceDir = join108(tmpDir, "skill");
476005
476186
  await mkdir16(sourceDir, { recursive: true });
476006
476187
  const url2 = new URL(`${CLAWHUB_API_BASE_URL}/download`);
476007
476188
  url2.searchParams.set("slug", location.slug);
@@ -476026,9 +476207,9 @@ async function downloadClawHubSkillSource(location) {
476026
476207
  return { tmpDir, sourceDir };
476027
476208
  }
476028
476209
  function assertInside(parent, child) {
476029
- const parentPath = resolve40(parent);
476030
- const childPath = resolve40(child);
476031
- if (childPath !== parentPath && !childPath.startsWith(`${parentPath}${sep8}`)) {
476210
+ const parentPath = resolve41(parent);
476211
+ const childPath = resolve41(child);
476212
+ if (childPath !== parentPath && !childPath.startsWith(`${parentPath}${sep9}`)) {
476032
476213
  throw new Error(`Resolved path is outside target directory: ${child}`);
476033
476214
  }
476034
476215
  }
@@ -476040,16 +476221,16 @@ function sanitizeSkillName(name) {
476040
476221
  return trimmed;
476041
476222
  }
476042
476223
  function getSkillName(sourceDir) {
476043
- const skillMd = readFileSync55(join107(sourceDir, "SKILL.md"), "utf8");
476224
+ const skillMd = readFileSync55(join108(sourceDir, "SKILL.md"), "utf8");
476044
476225
  const { frontmatter } = parseFrontmatter(skillMd);
476045
476226
  const frontmatterName = frontmatter.name;
476046
476227
  const name = typeof frontmatterName === "string" && frontmatterName.trim() ? frontmatterName : basename31(sourceDir);
476047
476228
  return sanitizeSkillName(name);
476048
476229
  }
476049
476230
  async function installSkillDirectory(params) {
476050
- const sourceDir = resolve40(params.sourceDir);
476051
- const memoryDir = resolve40(params.memoryDir);
476052
- const skillMdPath = join107(sourceDir, "SKILL.md");
476231
+ const sourceDir = resolve41(params.sourceDir);
476232
+ const memoryDir = resolve41(params.memoryDir);
476233
+ const skillMdPath = join108(sourceDir, "SKILL.md");
476053
476234
  if (!existsSync72(skillMdPath)) {
476054
476235
  throw new Error("No SKILL.md found in the skill directory.");
476055
476236
  }
@@ -476057,8 +476238,8 @@ async function installSkillDirectory(params) {
476057
476238
  throw new Error(`Skill source is not a directory: ${sourceDir}`);
476058
476239
  }
476059
476240
  const name = getSkillName(sourceDir);
476060
- const skillsDir = join107(memoryDir, "skills");
476061
- const targetPath = join107(skillsDir, name);
476241
+ const skillsDir = join108(memoryDir, "skills");
476242
+ const targetPath = join108(skillsDir, name);
476062
476243
  assertInside(skillsDir, targetPath);
476063
476244
  if (existsSync72(targetPath)) {
476064
476245
  if (!params.force) {
@@ -476074,8 +476255,8 @@ async function installSkillDirectory(params) {
476074
476255
  return { name, path: normalize5(targetPath) };
476075
476256
  }
476076
476257
  async function listSkillDirectories(params) {
476077
- const memoryDir = resolve40(params.memoryDir);
476078
- const skillsDir = join107(memoryDir, "skills");
476258
+ const memoryDir = resolve41(params.memoryDir);
476259
+ const skillsDir = join108(memoryDir, "skills");
476079
476260
  if (!existsSync72(skillsDir))
476080
476261
  return [];
476081
476262
  const entries2 = await readdir13(skillsDir, { withFileTypes: true });
@@ -476083,8 +476264,8 @@ async function listSkillDirectories(params) {
476083
476264
  for (const entry of entries2) {
476084
476265
  if (!entry.isDirectory())
476085
476266
  continue;
476086
- const skillDir = join107(skillsDir, entry.name);
476087
- const skillMdPath = join107(skillDir, "SKILL.md");
476267
+ const skillDir = join108(skillsDir, entry.name);
476268
+ const skillMdPath = join108(skillDir, "SKILL.md");
476088
476269
  if (!existsSync72(skillMdPath))
476089
476270
  continue;
476090
476271
  let name = entry.name;
@@ -476104,10 +476285,10 @@ async function listSkillDirectories(params) {
476104
476285
  return skills.sort((a2, b3) => a2.name.localeCompare(b3.name));
476105
476286
  }
476106
476287
  async function deleteSkillDirectory(params) {
476107
- const memoryDir = resolve40(params.memoryDir);
476108
- const skillsDir = join107(memoryDir, "skills");
476288
+ const memoryDir = resolve41(params.memoryDir);
476289
+ const skillsDir = join108(memoryDir, "skills");
476109
476290
  const name = sanitizeSkillName(params.name);
476110
- const targetPath = join107(skillsDir, name);
476291
+ const targetPath = join108(skillsDir, name);
476111
476292
  assertInside(skillsDir, targetPath);
476112
476293
  if (!existsSync72(targetPath)) {
476113
476294
  throw new Error(`Skill "${name}" is not installed at ${targetPath}.`);
@@ -476156,7 +476337,7 @@ async function installSkill(specifier, agentId, force) {
476156
476337
  downloaded = await downloadClawHubSkillSource(source.location);
476157
476338
  }
476158
476339
  tmpDir = downloaded.tmpDir;
476159
- const sourceDir = resolve40(downloaded.sourceDir);
476340
+ const sourceDir = resolve41(downloaded.sourceDir);
476160
476341
  assertInside(tmpDir, sourceDir);
476161
476342
  if (!existsSync72(sourceDir)) {
476162
476343
  const missingPath = source.type === "git" ? source.location.subdir ?? "." : source.type === "direct-file" ? source.location.url : source.location.slug;
@@ -476339,7 +476520,7 @@ async function runInstall(argv, options = {}) {
476339
476520
  return 1;
476340
476521
  }
476341
476522
  }
476342
- const maybeLocalPath = resolve40(specifier);
476523
+ const maybeLocalPath = resolve41(specifier);
476343
476524
  if (isLocalLettaModPackageDirectory(maybeLocalPath)) {
476344
476525
  if (hasInstallAgentScope(parsed.values)) {
476345
476526
  console.error("Agent-scoped mod package install is not supported yet.");
@@ -476654,20 +476835,20 @@ async function runTeleportSubcommand(argv, deps = {}) {
476654
476835
  throw new Error(channelError);
476655
476836
  let targetConnectionId;
476656
476837
  if (action === "cloud") {
476657
- const resolve41 = deps.resolveAgentSandboxConnectionId ?? resolveAgentSandboxConnectionId;
476658
- const result4 = await resolve41(session3.agentId, {
476838
+ const resolve42 = deps.resolveAgentSandboxConnectionId ?? resolveAgentSandboxConnectionId;
476839
+ const result4 = await resolve42(session3.agentId, {
476659
476840
  conversationId: session3.conversationId
476660
476841
  });
476661
476842
  targetConnectionId = result4.connectionId;
476662
476843
  } else if (action === "local") {
476663
- const resolve41 = deps.resolveDesktopEnvironmentConnectionId ?? resolveDesktopEnvironmentConnectionId;
476664
- const result4 = await resolve41();
476844
+ const resolve42 = deps.resolveDesktopEnvironmentConnectionId ?? resolveDesktopEnvironmentConnectionId;
476845
+ const result4 = await resolve42();
476665
476846
  targetConnectionId = result4.connectionId;
476666
476847
  } else if (action === "back") {
476667
476848
  throw new Error("Teleport back is not supported. Use `letta teleport local` or choose an explicit computer.");
476668
476849
  } else {
476669
- const resolve41 = deps.resolveEnvironmentConnectionId ?? resolveEnvironmentConnectionId;
476670
- const resolved = await resolve41(action);
476850
+ const resolve42 = deps.resolveEnvironmentConnectionId ?? resolveEnvironmentConnectionId;
476851
+ const resolved = await resolve42(action);
476671
476852
  assertTeleportableRemoteEnvironment(resolved.environment);
476672
476853
  targetConnectionId = resolved.connectionId;
476673
476854
  }
@@ -476693,7 +476874,7 @@ var init_teleport2 = __esm(() => {
476693
476874
 
476694
476875
  // src/cli/subcommands/trajectories/readers.ts
476695
476876
  import { readdir as readdir14, readFile as readFile30, stat as stat16 } from "node:fs/promises";
476696
- import { join as join108 } from "node:path";
476877
+ import { join as join109 } from "node:path";
476697
476878
  async function loadSessionTranscript(item) {
476698
476879
  const stats = await stat16(item.path);
476699
476880
  if (stats.isDirectory()) {
@@ -476705,13 +476886,13 @@ async function loadSessionTranscript(item) {
476705
476886
  return readFile30(item.path, "utf-8");
476706
476887
  }
476707
476888
  async function assembleEventDirectory(sessionDir) {
476708
- const eventsSubdir = join108(sessionDir, "events");
476889
+ const eventsSubdir = join109(sessionDir, "events");
476709
476890
  const eventsDir = (await stat16(eventsSubdir).catch(() => null))?.isDirectory() ? eventsSubdir : sessionDir;
476710
476891
  const names = (await readdir14(eventsDir, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => entry.name).sort((a2, b3) => Number.parseInt(a2, 10) - Number.parseInt(b3, 10) || a2.localeCompare(b3));
476711
476892
  if (names.length === 0) {
476712
476893
  throw new Error(`No event files found in ${eventsDir}`);
476713
476894
  }
476714
- const events = await Promise.all(names.map(async (name) => JSON.parse(await readFile30(join108(eventsDir, name), "utf-8"))));
476895
+ const events = await Promise.all(names.map(async (name) => JSON.parse(await readFile30(join109(eventsDir, name), "utf-8"))));
476715
476896
  return JSON.stringify(events);
476716
476897
  }
476717
476898
  async function openReadOnlyDatabase(path49) {
@@ -476785,11 +476966,11 @@ import {
476785
476966
  mkdir as mkdir17,
476786
476967
  readdir as readdir15,
476787
476968
  readFile as readFile31,
476788
- rm as rm12,
476969
+ rm as rm13,
476789
476970
  stat as stat17,
476790
476971
  writeFile as writeFile20
476791
476972
  } from "node:fs/promises";
476792
- import { basename as basename32, join as join109 } from "node:path";
476973
+ import { basename as basename32, join as join110 } from "node:path";
476793
476974
  function fileTimestamp(startedAt) {
476794
476975
  if (!startedAt)
476795
476976
  return "unknown-date";
@@ -476859,7 +477040,7 @@ async function prepareOutDir(outDir) {
476859
477040
  throw new Error(`--out ${outDir} is not empty and has no ${MANIFEST_NAME}; refusing to overwrite a directory this tool did not create`);
476860
477041
  }
476861
477042
  for (const entry of entries2) {
476862
- await rm12(join109(outDir, entry), { recursive: true, force: true });
477043
+ await rm13(join110(outDir, entry), { recursive: true, force: true });
476863
477044
  }
476864
477045
  } catch (error4) {
476865
477046
  if (error4.code !== "ENOENT")
@@ -476902,14 +477083,14 @@ async function runTrajectoryExport(options) {
476902
477083
  }
476903
477084
  const sessionId = sessionHash(source, id);
476904
477085
  const base2 = `${fileTimestamp(stats.startedAt)}_${sessionId}`;
476905
- let file = join109(source, `${base2}.json`);
477086
+ let file = join110(source, `${base2}.json`);
476906
477087
  for (let suffix = 2;usedFiles.has(file); suffix += 1) {
476907
- file = join109(source, `${base2}-${suffix}.json`);
477088
+ file = join110(source, `${base2}-${suffix}.json`);
476908
477089
  }
476909
477090
  usedFiles.add(file);
476910
477091
  const body3 = JSON.stringify(records2);
476911
- await mkdir17(join109(options.outDir, source), { recursive: true });
476912
- await writeFile20(join109(options.outDir, file), body3, "utf-8");
477092
+ await mkdir17(join110(options.outDir, source), { recursive: true });
477093
+ await writeFile20(join110(options.outDir, file), body3, "utf-8");
476913
477094
  counts.exported += 1;
476914
477095
  manifest2.sessions.push({
476915
477096
  source,
@@ -476963,7 +477144,7 @@ async function runTrajectoryExport(options) {
476963
477144
  await exportCheckpoint(checkpoint, `${basename32(checkpoint.path)}-${checkpoint.threadId}`);
476964
477145
  }
476965
477146
  manifest2.sessions.sort((a2, b3) => (a2.startedAt ?? "").localeCompare(b3.startedAt ?? ""));
476966
- await writeFile20(join109(options.outDir, MANIFEST_NAME), JSON.stringify(manifest2, null, 2), "utf-8");
477147
+ await writeFile20(join110(options.outDir, MANIFEST_NAME), JSON.stringify(manifest2, null, 2), "utf-8");
476967
477148
  return manifest2;
476968
477149
  }
476969
477150
  var MANIFEST_NAME = "manifest.json", FIRST_PROMPT_MAX_CHARS = 200, LIST_PAGE_LIMIT = 1000;
@@ -476975,13 +477156,13 @@ var init_export = __esm(() => {
476975
477156
 
476976
477157
  // src/cli/subcommands/trajectories/review.ts
476977
477158
  import { readFile as readFile32 } from "node:fs/promises";
476978
- import { isAbsolute as isAbsolute27, join as join110 } from "node:path";
477159
+ import { isAbsolute as isAbsolute28, join as join111 } from "node:path";
476979
477160
  async function readManifest(dir) {
476980
477161
  let raw2;
476981
477162
  try {
476982
- raw2 = await readFile32(join110(dir, "manifest.json"), "utf-8");
477163
+ raw2 = await readFile32(join111(dir, "manifest.json"), "utf-8");
476983
477164
  } catch {
476984
- throw new Error(`No manifest at ${join110(dir, "manifest.json")}. Run: letta trajectories export --out ${dir}`);
477165
+ throw new Error(`No manifest at ${join111(dir, "manifest.json")}. Run: letta trajectories export --out ${dir}`);
476985
477166
  }
476986
477167
  return JSON.parse(raw2);
476987
477168
  }
@@ -476990,7 +477171,7 @@ function filterSessions(sessions5, filter3) {
476990
477171
  }
476991
477172
  async function resolveSessionFile(dir, target) {
476992
477173
  if (target.endsWith(".json")) {
476993
- const direct = isAbsolute27(target) ? target : join110(dir, target);
477174
+ const direct = isAbsolute28(target) ? target : join111(dir, target);
476994
477175
  try {
476995
477176
  await readFile32(direct, "utf-8");
476996
477177
  return direct;
@@ -477001,7 +477182,7 @@ async function resolveSessionFile(dir, target) {
477001
477182
  if (!entry) {
477002
477183
  throw new Error(`No session "${target}" in ${dir} (pass a file path, a manifest-relative file, or a sessionId)`);
477003
477184
  }
477004
- return join110(dir, entry.file);
477185
+ return join111(dir, entry.file);
477005
477186
  }
477006
477187
  function stamp(timestamp) {
477007
477188
  return (timestamp ?? "").slice(0, 19);
@@ -477044,7 +477225,7 @@ async function searchSessions(dir, keyword, options = {}) {
477044
477225
  for (const session3 of filterSessions(manifest2.sessions, options)) {
477045
477226
  let records2;
477046
477227
  try {
477047
- records2 = JSON.parse(await readFile32(join110(dir, session3.file), "utf-8"));
477228
+ records2 = JSON.parse(await readFile32(join111(dir, session3.file), "utf-8"));
477048
477229
  } catch {
477049
477230
  continue;
477050
477231
  }
@@ -477380,8 +477561,8 @@ Current plan: ${balance.billing_tier}
477380
477561
  * Quota Window End: ${quota.quotaWindowEnd}
477381
477562
  * Daily Quota Window End: ${quota.dailyQuotaWindowEnd ?? "Unavailable"}
477382
477563
  `;
477383
- await new Promise((resolve41, reject2) => {
477384
- process.stdout.write(usage, (error4) => error4 ? reject2(error4) : resolve41());
477564
+ await new Promise((resolve42, reject2) => {
477565
+ process.stdout.write(usage, (error4) => error4 ? reject2(error4) : resolve42());
477385
477566
  });
477386
477567
  return 0;
477387
477568
  } catch (error4) {
@@ -481498,12 +481679,12 @@ function createRoutedRuntimeRegistrationRefresher(options) {
481498
481679
  });
481499
481680
  return run;
481500
481681
  };
481501
- const waitForRetry = () => new Promise((resolve41) => {
481502
- resolveRetry = resolve41;
481682
+ const waitForRetry = () => new Promise((resolve42) => {
481683
+ resolveRetry = resolve42;
481503
481684
  retryTimer = setTimeout(() => {
481504
481685
  retryTimer = null;
481505
481686
  resolveRetry = null;
481506
- resolve41();
481687
+ resolve42();
481507
481688
  }, retryDelayMs);
481508
481689
  retryTimer.unref?.();
481509
481690
  });
@@ -482139,7 +482320,7 @@ async function runChannelGatewaySubcommand(argv) {
482139
482320
  await ensureChannelRuntimeInstalled2(channelName);
482140
482321
  }
482141
482322
  }
482142
- return await new Promise((resolve41) => {
482323
+ return await new Promise((resolve42) => {
482143
482324
  let closing2 = false;
482144
482325
  let closeGateway = null;
482145
482326
  const finish2 = (code) => {
@@ -482147,10 +482328,10 @@ async function runChannelGatewaySubcommand(argv) {
482147
482328
  return;
482148
482329
  closing2 = true;
482149
482330
  if (!closeGateway) {
482150
- resolve41(code);
482331
+ resolve42(code);
482151
482332
  return;
482152
482333
  }
482153
- closeGateway().finally(() => resolve41(code));
482334
+ closeGateway().finally(() => resolve42(code));
482154
482335
  };
482155
482336
  startLocalChannelGateway({
482156
482337
  appServerUrl,
@@ -482198,7 +482379,7 @@ async function runChannelGatewaySubcommand(argv) {
482198
482379
  gateway.close();
482199
482380
  }).catch((error4) => {
482200
482381
  console.error(error4 instanceof Error ? error4.message : String(error4));
482201
- resolve41(1);
482382
+ resolve42(1);
482202
482383
  });
482203
482384
  });
482204
482385
  }
@@ -482445,10 +482626,10 @@ async function detectAndEnableKittyProtocol() {
482445
482626
  detectionComplete = true;
482446
482627
  return;
482447
482628
  }
482448
- return new Promise((resolve41) => {
482629
+ return new Promise((resolve42) => {
482449
482630
  if (!process.stdin.isTTY || !process.stdout.isTTY) {
482450
482631
  detectionComplete = true;
482451
- resolve41();
482632
+ resolve42();
482452
482633
  return;
482453
482634
  }
482454
482635
  const originalRawMode = process.stdin.isRaw;
@@ -482481,7 +482662,7 @@ async function detectAndEnableKittyProtocol() {
482481
482662
  console.error("[kitty] protocol query unsupported; enabled anyway (best-effort)");
482482
482663
  }
482483
482664
  detectionComplete = true;
482484
- resolve41();
482665
+ resolve42();
482485
482666
  };
482486
482667
  const handleData = (data) => {
482487
482668
  if (timeoutId === undefined) {
@@ -483000,8 +483181,8 @@ async function waitForEnqueuedReply(params) {
483000
483181
  let timer;
483001
483182
  const event = await Promise.race([
483002
483183
  next,
483003
- new Promise((resolve41) => {
483004
- timer = setTimeout(() => resolve41(null), params.pollMs ?? 1000);
483184
+ new Promise((resolve42) => {
483185
+ timer = setTimeout(() => resolve42(null), params.pollMs ?? 1000);
483005
483186
  })
483006
483187
  ]).finally(() => clearTimeout(timer));
483007
483188
  if (event) {
@@ -483378,7 +483559,7 @@ function resolveHeadlessMemfsPolicy(options) {
483378
483559
  var init_headless_memfs_policy = () => {};
483379
483560
 
483380
483561
  // src/headless-mod-adapter.ts
483381
- import { join as join111 } from "node:path";
483562
+ import { join as join112 } from "node:path";
483382
483563
  function isHeadlessMemfsEnabled(agentId) {
483383
483564
  try {
483384
483565
  return settingsManager.isMemfsEnabled(agentId);
@@ -483449,7 +483630,7 @@ function createHeadlessModContext(options) {
483449
483630
  };
483450
483631
  }
483451
483632
  function createHeadlessModAdapter(options) {
483452
- const agentModsDirectory = isHeadlessMemfsEnabled(options.agent.id) ? join111(getScopedMemoryFilesystemRoot(options.agent.id), "mods") : undefined;
483633
+ const agentModsDirectory = isHeadlessMemfsEnabled(options.agent.id) ? join112(getScopedMemoryFilesystemRoot(options.agent.id), "mods") : undefined;
483453
483634
  return createModAdapter({
483454
483635
  ...agentModsDirectory ? { agentModsDirectory } : {},
483455
483636
  ...options.cacheDirectory ? { cacheDirectory: options.cacheDirectory } : {},
@@ -483571,9 +483752,9 @@ function writeWireMessage(msg) {
483571
483752
  async function writeWireMessageAsync(msg) {
483572
483753
  const line = `${JSON.stringify(stampWireMessage(msg))}
483573
483754
  `;
483574
- return await new Promise((resolve41, reject2) => {
483755
+ return await new Promise((resolve42, reject2) => {
483575
483756
  if (process.stdout.destroyed || process.stdout.writableEnded) {
483576
- resolve41(false);
483757
+ resolve42(false);
483577
483758
  return;
483578
483759
  }
483579
483760
  process.stdout.write(line, (error4) => {
@@ -483581,7 +483762,7 @@ async function writeWireMessageAsync(msg) {
483581
483762
  reject2(error4);
483582
483763
  return;
483583
483764
  }
483584
- resolve41(true);
483765
+ resolve42(true);
483585
483766
  });
483586
483767
  });
483587
483768
  }
@@ -483972,10 +484153,10 @@ async function sendScopedApprovalMessages(params) {
483972
484153
  }
483973
484154
  async function flushAndExit(code) {
483974
484155
  await shutdownMonitors();
483975
- const flushWritable = (stream11) => new Promise((resolve41) => {
484156
+ const flushWritable = (stream11) => new Promise((resolve42) => {
483976
484157
  if (stream11.destroyed || stream11.writableEnded)
483977
- return resolve41();
483978
- stream11.write("", () => resolve41());
484158
+ return resolve42();
484159
+ stream11.write("", () => resolve42());
483979
484160
  });
483980
484161
  await closeClientMcpServers();
483981
484162
  await Promise.allSettled([
@@ -483985,12 +484166,12 @@ async function flushAndExit(code) {
483985
484166
  process.exit(code);
483986
484167
  }
483987
484168
  async function writeFinalHeadlessStdout(text3) {
483988
- await new Promise((resolve41) => {
484169
+ await new Promise((resolve42) => {
483989
484170
  if (process.stdout.destroyed || process.stdout.writableEnded) {
483990
- resolve41();
484171
+ resolve42();
483991
484172
  return;
483992
484173
  }
483993
- process.stdout.write(text3, () => resolve41());
484174
+ process.stdout.write(text3, () => resolve42());
483994
484175
  });
483995
484176
  }
483996
484177
  async function handleHeadlessCommand(parsedArgs, model2, skillsDirectoryOverride, skillSourcesOverride, systemInfoReminderEnabledOverride, startupOptions = {}) {
@@ -485105,7 +485286,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
485105
485286
  } else {
485106
485287
  console.error(`Conversation is busy, waiting ${Math.round(retryDelayMs / 1000)}s and retrying...`);
485107
485288
  }
485108
- await new Promise((resolve41) => setTimeout(resolve41, retryDelayMs));
485289
+ await new Promise((resolve42) => setTimeout(resolve42, retryDelayMs));
485109
485290
  continue;
485110
485291
  }
485111
485292
  }
@@ -485134,7 +485315,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
485134
485315
  const delaySeconds = Math.round(delayMs / 1000);
485135
485316
  console.error(`Transient API error before streaming (attempt ${attempt2} of ${LLM_API_ERROR_MAX_RETRIES2}), retrying in ${delaySeconds}s...`);
485136
485317
  }
485137
- await new Promise((resolve41) => setTimeout(resolve41, delayMs));
485318
+ await new Promise((resolve42) => setTimeout(resolve42, delayMs));
485138
485319
  conversationBusyRetries = 0;
485139
485320
  continue;
485140
485321
  }
@@ -485384,7 +485565,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
485384
485565
  const delaySeconds = Math.round(delayMs / 1000);
485385
485566
  console.error(`LLM API error encountered (attempt ${attempt2} of ${LLM_API_ERROR_MAX_RETRIES2}), retrying in ${delaySeconds}s...`);
485386
485567
  }
485387
- await new Promise((resolve41) => setTimeout(resolve41, delayMs));
485568
+ await new Promise((resolve42) => setTimeout(resolve42, delayMs));
485388
485569
  currentInput = refreshInputOtidsForNewRequest(currentInput);
485389
485570
  continue;
485390
485571
  }
@@ -485476,7 +485657,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
485476
485657
  } else {
485477
485658
  console.error(`Empty LLM response, retrying (attempt ${attempt2} of ${EMPTY_RESPONSE_MAX_RETRIES2})...`);
485478
485659
  }
485479
- await new Promise((resolve41) => setTimeout(resolve41, delayMs));
485660
+ await new Promise((resolve42) => setTimeout(resolve42, delayMs));
485480
485661
  currentInput = refreshInputOtidsForNewRequest(currentInput);
485481
485662
  continue;
485482
485663
  }
@@ -485504,7 +485685,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
485504
485685
  const delaySeconds = Math.round(delayMs / 1000);
485505
485686
  console.error(`LLM API error encountered (attempt ${attempt2} of ${LLM_API_ERROR_MAX_RETRIES2}), retrying in ${delaySeconds}s...`);
485506
485687
  }
485507
- await new Promise((resolve41) => setTimeout(resolve41, delayMs));
485688
+ await new Promise((resolve42) => setTimeout(resolve42, delayMs));
485508
485689
  currentInput = refreshInputOtidsForNewRequest(currentInput);
485509
485690
  continue;
485510
485691
  }
@@ -485534,7 +485715,7 @@ Current session AGENT_ID=${process.env.AGENT_ID}; --backend local switches to a
485534
485715
  const delaySeconds = Math.round(delayMs / 1000);
485535
485716
  console.error(`LLM API error encountered (attempt ${attempt2} of ${LLM_API_ERROR_MAX_RETRIES2}), retrying in ${delaySeconds}s...`);
485536
485717
  }
485537
- await new Promise((resolve41) => setTimeout(resolve41, delayMs));
485718
+ await new Promise((resolve42) => setTimeout(resolve42, delayMs));
485538
485719
  currentInput = refreshInputOtidsForNewRequest(currentInput);
485539
485720
  continue;
485540
485721
  }
@@ -485934,9 +486115,9 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
485934
486115
  const syntheticUserLine = serializeQueuedMessageAsUserLine(queuedMessage);
485935
486116
  maybeNotifyBlocked(syntheticUserLine);
485936
486117
  if (lineResolver) {
485937
- const resolve41 = lineResolver;
486118
+ const resolve42 = lineResolver;
485938
486119
  lineResolver = null;
485939
- resolve41(syntheticUserLine);
486120
+ resolve42(syntheticUserLine);
485940
486121
  return;
485941
486122
  }
485942
486123
  lineQueue.push(syntheticUserLine);
@@ -485956,9 +486137,9 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
485956
486137
  if (action === "abort-active") {
485957
486138
  currentAbortController.abort();
485958
486139
  if (lineResolver) {
485959
- const resolve41 = lineResolver;
486140
+ const resolve42 = lineResolver;
485960
486141
  lineResolver = null;
485961
- resolve41(null);
486142
+ resolve42(null);
485962
486143
  }
485963
486144
  } else if (action === "latch") {
485964
486145
  pendingInterrupt = true;
@@ -485978,9 +486159,9 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
485978
486159
  if (lineResolver) {
485979
486160
  if (parsedLine?.type === "user")
485980
486161
  turnStarting = true;
485981
- const resolve41 = lineResolver;
486162
+ const resolve42 = lineResolver;
485982
486163
  lineResolver = null;
485983
- resolve41(line);
486164
+ resolve42(line);
485984
486165
  } else {
485985
486166
  lineQueue.push(line);
485986
486167
  }
@@ -485989,17 +486170,17 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
485989
486170
  setMessageQueueAdder(null);
485990
486171
  msgQueueRuntime.clear("shutdown");
485991
486172
  if (lineResolver) {
485992
- const resolve41 = lineResolver;
486173
+ const resolve42 = lineResolver;
485993
486174
  lineResolver = null;
485994
- resolve41(null);
486175
+ resolve42(null);
485995
486176
  }
485996
486177
  });
485997
486178
  async function getNextLine() {
485998
486179
  if (lineQueue.length > 0) {
485999
486180
  return lineQueue.shift() ?? null;
486000
486181
  }
486001
- return new Promise((resolve41) => {
486002
- lineResolver = resolve41;
486182
+ return new Promise((resolve42) => {
486183
+ lineResolver = resolve42;
486003
486184
  });
486004
486185
  }
486005
486186
  const EXTERNAL_TOOL_WAIT_ABORTED = Symbol("externalToolWaitAborted");
@@ -486010,17 +486191,17 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
486010
486191
  return lineQueue.shift() ?? null;
486011
486192
  if (!signal)
486012
486193
  return getNextLine();
486013
- return new Promise((resolve41) => {
486194
+ return new Promise((resolve42) => {
486014
486195
  const cleanup = () => signal.removeEventListener("abort", onAbort);
486015
486196
  const onAbort = () => {
486016
486197
  cleanup();
486017
486198
  if (lineResolver === settle3)
486018
486199
  lineResolver = null;
486019
- resolve41(EXTERNAL_TOOL_WAIT_ABORTED);
486200
+ resolve42(EXTERNAL_TOOL_WAIT_ABORTED);
486020
486201
  };
486021
486202
  const settle3 = (line) => {
486022
486203
  cleanup();
486023
- resolve41(line);
486204
+ resolve42(line);
486024
486205
  };
486025
486206
  signal.addEventListener("abort", onAbort);
486026
486207
  lineResolver = settle3;
@@ -486548,7 +486729,7 @@ async function runBidirectionalMode(agent, conversationId, effectiveModel, _outp
486548
486729
  uuid: `retry-bidir-${randomUUID66()}`
486549
486730
  };
486550
486731
  writeWireMessage(retryMsg);
486551
- await new Promise((resolve41) => setTimeout(resolve41, delayMs));
486732
+ await new Promise((resolve42) => setTimeout(resolve42, delayMs));
486552
486733
  continue;
486553
486734
  }
486554
486735
  throw preStreamError;
@@ -487298,7 +487479,7 @@ var BYTES_PER_TOKEN = 4;
487298
487479
 
487299
487480
  // src/cli/helpers/window-title-config.ts
487300
487481
  import { homedir as homedir33 } from "node:os";
487301
- import { basename as basename33, resolve as resolve41 } from "node:path";
487482
+ import { basename as basename33, resolve as resolve42 } from "node:path";
487302
487483
  function isWindowTitleField(value) {
487303
487484
  return WINDOW_TITLE_FIELDS.includes(value);
487304
487485
  }
@@ -487456,7 +487637,7 @@ function terminalTitleProjectName(data) {
487456
487637
  const directory = titleDirectory(data);
487457
487638
  if (!directory)
487458
487639
  return null;
487459
- const resolved = resolve41(directory);
487640
+ const resolved = resolve42(directory);
487460
487641
  const name = basename33(resolved) || formatDirectoryDisplay(resolved) || resolved;
487461
487642
  return truncateTerminalTitlePart(name, 24);
487462
487643
  }
@@ -487466,7 +487647,7 @@ function titleDirectory(data) {
487466
487647
  function formatDirectoryDisplay(directory) {
487467
487648
  if (!directory)
487468
487649
  return null;
487469
- const resolved = resolve41(directory);
487650
+ const resolved = resolve42(directory);
487470
487651
  const home = homedir33();
487471
487652
  if (resolved === home)
487472
487653
  return "~";
@@ -488142,10 +488323,10 @@ import { execFile as execFileCb4 } from "node:child_process";
488142
488323
  import { existsSync as existsSync75 } from "node:fs";
488143
488324
  import { appendFile as appendFile3, chmod, mkdir as mkdir18, writeFile as writeFile21 } from "node:fs/promises";
488144
488325
  import { homedir as homedir34 } from "node:os";
488145
- import { join as join113 } from "node:path";
488326
+ import { join as join114 } from "node:path";
488146
488327
  import { promisify as promisify20 } from "node:util";
488147
488328
  function getReflectionArenaHfCacheRoot(env6 = process.env, fallbackHome = homedir34()) {
488148
- return join113(resolveGlobalConfigDir(env6, fallbackHome), "reflection-arena", "hf-upload");
488329
+ return join114(resolveGlobalConfigDir(env6, fallbackHome), "reflection-arena", "hf-upload");
488149
488330
  }
488150
488331
  function buildGitEnv(token2, askpassPath) {
488151
488332
  return {
@@ -488181,7 +488362,7 @@ async function runGit6(cwd2, args, env6) {
488181
488362
  }
488182
488363
  }
488183
488364
  async function writeGitAskpass(repoRoot) {
488184
- const askpassPath = join113(repoRoot, "hf-askpass.sh");
488365
+ const askpassPath = join114(repoRoot, "hf-askpass.sh");
488185
488366
  await writeFile21(askpassPath, [
488186
488367
  "#!/bin/sh",
488187
488368
  'case "$1" in',
@@ -488196,7 +488377,7 @@ async function writeGitAskpass(repoRoot) {
488196
488377
  }
488197
488378
  async function prepareHfRepo(env6) {
488198
488379
  await mkdir18(HF_CACHE_ROOT, { recursive: true });
488199
- if (!existsSync75(join113(HF_REPO_DIR, ".git"))) {
488380
+ if (!existsSync75(join114(HF_REPO_DIR, ".git"))) {
488200
488381
  await runGit6(HF_CACHE_ROOT, ["clone", "--depth", "1", HF_REPO_URL, HF_REPO_DIR], env6);
488201
488382
  return HF_REPO_DIR;
488202
488383
  }
@@ -488231,8 +488412,8 @@ async function maybeUploadReflectionArenaChoiceToHf(row) {
488231
488412
  const env6 = buildGitEnv(token2, askpassPath);
488232
488413
  try {
488233
488414
  const repoDir = await prepareHfRepo(env6);
488234
- await mkdir18(join113(repoDir, "data"), { recursive: true });
488235
- await appendFile3(join113(repoDir, HF_DATASET_PATH), `${JSON.stringify(row)}
488415
+ await mkdir18(join114(repoDir, "data"), { recursive: true });
488416
+ await appendFile3(join114(repoDir, HF_DATASET_PATH), `${JSON.stringify(row)}
488236
488417
  `, {
488237
488418
  encoding: "utf-8"
488238
488419
  });
@@ -488262,14 +488443,14 @@ var init_reflection_arena_hf_upload = __esm(() => {
488262
488443
  execFile23 = promisify20(execFileCb4);
488263
488444
  HF_REPO_URL = `https://huggingface.co/datasets/${HF_REPO_ID}`;
488264
488445
  HF_CACHE_ROOT = getReflectionArenaHfCacheRoot();
488265
- HF_REPO_DIR = join113(HF_CACHE_ROOT, "repo");
488446
+ HF_REPO_DIR = join114(HF_CACHE_ROOT, "repo");
488266
488447
  });
488267
488448
 
488268
488449
  // src/cli/helpers/reflection-arena.ts
488269
488450
  import { execFile as execFileCb5 } from "node:child_process";
488270
488451
  import { randomInt as randomInt2, randomUUID as randomUUID67 } from "node:crypto";
488271
488452
  import { appendFile as appendFile4, mkdir as mkdir19, readFile as readFile34, writeFile as writeFile22 } from "node:fs/promises";
488272
- import { join as join114 } from "node:path";
488453
+ import { join as join115 } from "node:path";
488273
488454
  import { promisify as promisify21 } from "node:util";
488274
488455
  function sampleReflectionArenaComparisonModel(excludedModels = []) {
488275
488456
  const excluded = new Set(excludedModels);
@@ -488318,16 +488499,16 @@ function candidateIsConfirmedNoOp(candidate) {
488318
488499
  return candidate.result?.success === true && candidate.result.memoryNoChanges === true && candidate.result.memoryHead === candidate.worktree.baseHead;
488319
488500
  }
488320
488501
  function getReflectionArenaRoot() {
488321
- return join114(resolveGlobalConfigDir(), "reflection-arena");
488502
+ return join115(resolveGlobalConfigDir(), "reflection-arena");
488322
488503
  }
488323
488504
  function getReflectionArenaRunsDir() {
488324
- return join114(getReflectionArenaRoot(), "runs");
488505
+ return join115(getReflectionArenaRoot(), "runs");
488325
488506
  }
488326
488507
  function getReflectionArenaChoiceLogPath() {
488327
- return join114(getReflectionArenaRoot(), "choices.jsonl");
488508
+ return join115(getReflectionArenaRoot(), "choices.jsonl");
488328
488509
  }
488329
488510
  function getReflectionArenaRunPath(runId) {
488330
- return join114(getReflectionArenaRunsDir(), `${runId}.json`);
488511
+ return join115(getReflectionArenaRunsDir(), `${runId}.json`);
488331
488512
  }
488332
488513
  async function saveReflectionArenaRun(run) {
488333
488514
  await mkdir19(getReflectionArenaRunsDir(), { recursive: true });
@@ -489387,8 +489568,8 @@ async function pushToMemoryRepositoryWithTimeout(agentId) {
489387
489568
  try {
489388
489569
  return await Promise.race([
489389
489570
  pushToMemoryRepository(agentId),
489390
- new Promise((resolve42) => {
489391
- timeout = setTimeout(() => resolve42("timeout"), INITIAL_PUSH_TIMEOUT_MS);
489571
+ new Promise((resolve43) => {
489572
+ timeout = setTimeout(() => resolve43("timeout"), INITIAL_PUSH_TIMEOUT_MS);
489392
489573
  })
489393
489574
  ]);
489394
489575
  } finally {
@@ -489868,7 +490049,7 @@ import {
489868
490049
  writeFileSync as writeFileSync50
489869
490050
  } from "node:fs";
489870
490051
  import { homedir as homedir35, platform as platform10 } from "node:os";
489871
- import { dirname as dirname43, join as join115 } from "node:path";
490052
+ import { dirname as dirname43, join as join116 } from "node:path";
489872
490053
  function detectTerminalType() {
489873
490054
  if (process.env.CURSOR_TRACE_ID || process.env.CURSOR_CHANNEL) {
489874
490055
  return "cursor";
@@ -489900,16 +490081,16 @@ function getKeybindingsPath(terminal) {
489900
490081
  }[terminal];
489901
490082
  const os7 = platform10();
489902
490083
  if (os7 === "darwin") {
489903
- return join115(homedir35(), "Library", "Application Support", appName, "User", "keybindings.json");
490084
+ return join116(homedir35(), "Library", "Application Support", appName, "User", "keybindings.json");
489904
490085
  }
489905
490086
  if (os7 === "win32") {
489906
490087
  const appData = process.env.APPDATA;
489907
490088
  if (!appData)
489908
490089
  return null;
489909
- return join115(appData, appName, "User", "keybindings.json");
490090
+ return join116(appData, appName, "User", "keybindings.json");
489910
490091
  }
489911
490092
  if (os7 === "linux") {
489912
- return join115(homedir35(), ".config", appName, "User", "keybindings.json");
490093
+ return join116(homedir35(), ".config", appName, "User", "keybindings.json");
489913
490094
  }
489914
490095
  return null;
489915
490096
  }
@@ -490062,14 +490243,14 @@ function getWezTermConfigPath() {
490062
490243
  }
490063
490244
  const xdgConfig = process.env.XDG_CONFIG_HOME;
490064
490245
  if (xdgConfig) {
490065
- const xdgPath = join115(xdgConfig, "wezterm", "wezterm.lua");
490246
+ const xdgPath = join116(xdgConfig, "wezterm", "wezterm.lua");
490066
490247
  if (existsSync76(xdgPath))
490067
490248
  return xdgPath;
490068
490249
  }
490069
- const configPath = join115(homedir35(), ".config", "wezterm", "wezterm.lua");
490250
+ const configPath = join116(homedir35(), ".config", "wezterm", "wezterm.lua");
490070
490251
  if (existsSync76(configPath))
490071
490252
  return configPath;
490072
- return join115(homedir35(), ".wezterm.lua");
490253
+ return join116(homedir35(), ".wezterm.lua");
490073
490254
  }
490074
490255
  function stripLuaCommentsFromLine(line, blockCommentEnd) {
490075
490256
  let code = "";
@@ -490247,7 +490428,7 @@ __export(exports_settings, {
490247
490428
  loadProjectSettings: () => loadProjectSettings,
490248
490429
  getSetting: () => getSetting
490249
490430
  });
490250
- import { join as join116 } from "node:path";
490431
+ import { join as join117 } from "node:path";
490251
490432
  function getSettingsPath() {
490252
490433
  return resolveGlobalSettingsPath();
490253
490434
  }
@@ -490289,7 +490470,7 @@ async function getSetting(key4) {
490289
490470
  return settings[key4];
490290
490471
  }
490291
490472
  function getProjectSettingsPath() {
490292
- return join116(process.cwd(), ".letta", "settings.local.json");
490473
+ return join117(process.cwd(), ".letta", "settings.local.json");
490293
490474
  }
490294
490475
  async function loadProjectSettings() {
490295
490476
  if (shouldIsolateHomeProjectConfig(process.cwd()))
@@ -490311,7 +490492,7 @@ async function saveProjectSettings(settings) {
490311
490492
  if (shouldIsolateHomeProjectConfig(process.cwd()))
490312
490493
  return;
490313
490494
  const settingsPath = getProjectSettingsPath();
490314
- const dirPath = join116(process.cwd(), ".letta");
490495
+ const dirPath = join117(process.cwd(), ".letta");
490315
490496
  try {
490316
490497
  if (!exists(dirPath)) {
490317
490498
  await mkdir(dirPath, { recursive: true });
@@ -491376,10 +491557,10 @@ var init_InlineBashApproval = __esm(async () => {
491376
491557
  });
491377
491558
 
491378
491559
  // src/cli/components/DiffRenderer.tsx
491379
- import { relative as relative11 } from "node:path";
491560
+ import { relative as relative12 } from "node:path";
491380
491561
  function formatDisplayPath4(filePath) {
491381
491562
  const cwd2 = process.cwd();
491382
- const relativePath = relative11(cwd2, filePath);
491563
+ const relativePath = relative12(cwd2, filePath);
491383
491564
  if (relativePath.startsWith("..")) {
491384
491565
  return filePath;
491385
491566
  }
@@ -491738,10 +491919,10 @@ var init_DiffRenderer = __esm(async () => {
491738
491919
  });
491739
491920
 
491740
491921
  // src/cli/components/AdvancedDiffRenderer.tsx
491741
- import { relative as relative12 } from "node:path";
491922
+ import { relative as relative13 } from "node:path";
491742
491923
  function formatRelativePath(filePath) {
491743
491924
  const cwd2 = process.cwd();
491744
- const relativePath = relative12(cwd2, filePath);
491925
+ const relativePath = relative13(cwd2, filePath);
491745
491926
  return relativePath.startsWith("..") ? relativePath : `./${relativePath}`;
491746
491927
  }
491747
491928
  function padLeft(n, width) {
@@ -492004,7 +492185,7 @@ function AdvancedDiffRenderer(props) {
492004
492185
  }
492005
492186
  const { hunks } = result3;
492006
492187
  const filePath = props.filePath;
492007
- const relative13 = formatRelativePath(filePath);
492188
+ const relative14 = formatRelativePath(filePath);
492008
492189
  const lang = languageFromPath(filePath);
492009
492190
  const shouldHighlight = lang && !exceedsAdvancedDiffHighlightLimits(hunks);
492010
492191
  const hunkSyntaxLines = [];
@@ -492027,7 +492208,7 @@ function AdvancedDiffRenderer(props) {
492027
492208
  const rows = buildAdvancedDiffRows(hunks, hunkSyntaxLines);
492028
492209
  const maxDisplayNo = rows.reduce((m4, r5) => Math.max(m4, r5.displayNo), 1);
492029
492210
  const gutterWidth = String(maxDisplayNo).length;
492030
- const header = props.kind === "write" ? `Wrote changes to ${relative13}` : `Updated ${relative13}`;
492211
+ const header = props.kind === "write" ? `Wrote changes to ${relative14}` : `Updated ${relative14}`;
492031
492212
  if (rows.length === 0) {
492032
492213
  const noChangesGutter = 4;
492033
492214
  return /* @__PURE__ */ jsx_dev_runtime24.jsxDEV(Box_default, {
@@ -492078,7 +492259,7 @@ function AdvancedDiffRenderer(props) {
492078
492259
  "No changes to ",
492079
492260
  /* @__PURE__ */ jsx_dev_runtime24.jsxDEV(Text2, {
492080
492261
  bold: true,
492081
- children: relative13
492262
+ children: relative14
492082
492263
  }, undefined, false, undefined, this),
492083
492264
  " (file content identical)"
492084
492265
  ]
@@ -492184,9 +492365,9 @@ function getHeaderText(fileEdit) {
492184
492365
  } else if (operations2.length === 1) {
492185
492366
  const op = operations2[0];
492186
492367
  if (op) {
492187
- const { relative: relative14 } = __require("node:path");
492368
+ const { relative: relative15 } = __require("node:path");
492188
492369
  const cwd3 = process.cwd();
492189
- const relPath2 = relative14(cwd3, op.path);
492370
+ const relPath2 = relative15(cwd3, op.path);
492190
492371
  const displayPath2 = relPath2.startsWith("..") ? op.path : relPath2;
492191
492372
  if (op.kind === "add") {
492192
492373
  return `Write to ${displayPath2}?`;
@@ -492200,9 +492381,9 @@ function getHeaderText(fileEdit) {
492200
492381
  }
492201
492382
  return "Apply patch?";
492202
492383
  }
492203
- const { relative: relative13 } = __require("node:path");
492384
+ const { relative: relative14 } = __require("node:path");
492204
492385
  const cwd2 = process.cwd();
492205
- const relPath = relative13(cwd2, fileEdit.filePath);
492386
+ const relPath = relative14(cwd2, fileEdit.filePath);
492206
492387
  const displayPath = relPath.startsWith("..") ? fileEdit.filePath : relPath;
492207
492388
  if (t2 === "write") {
492208
492389
  const { existsSync: existsSync77 } = __require("node:fs");
@@ -492375,9 +492556,9 @@ var init_InlineFileEditApproval = __esm(async () => {
492375
492556
  children: fileEdit.patchInput ? /* @__PURE__ */ jsx_dev_runtime25.jsxDEV(Box_default, {
492376
492557
  flexDirection: "column",
492377
492558
  children: parsePatchOperations(fileEdit.patchInput).map((op, idx) => {
492378
- const { relative: relative13 } = __require("node:path");
492559
+ const { relative: relative14 } = __require("node:path");
492379
492560
  const cwd2 = process.cwd();
492380
- const relPath = relative13(cwd2, op.path);
492561
+ const relPath = relative14(cwd2, op.path);
492381
492562
  const displayPath = relPath.startsWith("..") ? op.path : relPath;
492382
492563
  const diffKey = fileEdit.toolCallId ? `${fileEdit.toolCallId}:${op.path}` : undefined;
492383
492564
  const opDiff = diffKey && allDiffs ? allDiffs.get(diffKey) : undefined;
@@ -501121,7 +501302,7 @@ var init_InputRich = __esm(async () => {
501121
501302
  });
501122
501303
 
501123
501304
  // src/cli/commands/install-github-app.ts
501124
- import { execFileSync as execFileSync11 } from "node:child_process";
501305
+ import { execFileSync as execFileSync12 } from "node:child_process";
501125
501306
  import {
501126
501307
  existsSync as existsSync77,
501127
501308
  mkdirSync as mkdirSync59,
@@ -501131,10 +501312,10 @@ import {
501131
501312
  writeFileSync as writeFileSync51
501132
501313
  } from "node:fs";
501133
501314
  import { tmpdir as tmpdir16 } from "node:os";
501134
- import { dirname as dirname44, join as join117 } from "node:path";
501315
+ import { dirname as dirname44, join as join118 } from "node:path";
501135
501316
  function runCommand(command, args, cwd2, input) {
501136
501317
  try {
501137
- return execFileSync11(command, args, {
501318
+ return execFileSync12(command, args, {
501138
501319
  cwd: cwd2,
501139
501320
  encoding: "utf8",
501140
501321
  stdio: [input ? "pipe" : "ignore", "pipe", "pipe"],
@@ -501352,8 +501533,8 @@ async function createLettaAgent(apiKey, name) {
501352
501533
  return createMinimalAgent(apiKey, name);
501353
501534
  }
501354
501535
  function cloneRepoToTemp(repo) {
501355
- const tempDir = mkdtempSync7(join117(tmpdir16(), "letta-install-github-app-"));
501356
- const repoDir = join117(tempDir, "repo");
501536
+ const tempDir = mkdtempSync7(join118(tmpdir16(), "letta-install-github-app-"));
501537
+ const repoDir = join118(tempDir, "repo");
501357
501538
  runCommand("gh", ["repo", "clone", repo, repoDir, "--", "--depth=1"]);
501358
501539
  return { tempDir, repoDir };
501359
501540
  }
@@ -501364,7 +501545,7 @@ function runGit7(args, cwd2) {
501364
501545
  return runCommand("git", args, cwd2);
501365
501546
  }
501366
501547
  function writeWorkflow(repoDir, workflowPath, content) {
501367
- const absolutePath = join117(repoDir, workflowPath);
501548
+ const absolutePath = join118(repoDir, workflowPath);
501368
501549
  if (!existsSync77(dirname44(absolutePath))) {
501369
501550
  mkdirSync59(dirname44(absolutePath), { recursive: true });
501370
501551
  }
@@ -505254,7 +505435,7 @@ __export(exports_generate_memory_viewer, {
505254
505435
  });
505255
505436
  import { execFile as execFileCb6 } from "node:child_process";
505256
505437
  import { chmodSync as chmodSync11, existsSync as existsSync78, mkdirSync as mkdirSync60, writeFileSync as writeFileSync52 } from "node:fs";
505257
- import { join as join118 } from "node:path";
505438
+ import { join as join119 } from "node:path";
505258
505439
  import { promisify as promisify22 } from "node:util";
505259
505440
  function messagesFromOverview(overview) {
505260
505441
  return overview.messages?.map((message2) => ({
@@ -505564,7 +505745,7 @@ ${m4.body}` : m4.subject;
505564
505745
  async function generateAndOpenMemoryViewer(agentId, options) {
505565
505746
  const memoryRoot = getScopedMemoryFilesystemRoot(agentId);
505566
505747
  const repoDir = memoryRoot;
505567
- if (!existsSync78(join118(repoDir, ".git"))) {
505748
+ if (!existsSync78(join119(repoDir, ".git"))) {
505568
505749
  throw new Error("Memory viewer requires memfs. Run /memfs enable first.");
505569
505750
  }
505570
505751
  const data = await collectMemoryData(agentId, repoDir, memoryRoot, options?.conversationId);
@@ -505580,7 +505761,7 @@ async function generateAndOpenMemoryViewer(agentId, options) {
505580
505761
  try {
505581
505762
  chmodSync11(VIEWERS_DIR, 448);
505582
505763
  } catch {}
505583
- const filePath = join118(VIEWERS_DIR, `memory-${encodeURIComponent(agentId)}.html`);
505764
+ const filePath = join119(VIEWERS_DIR, `memory-${encodeURIComponent(agentId)}.html`);
505584
505765
  writeFileSync52(filePath, html5);
505585
505766
  chmodSync11(filePath, 384);
505586
505767
  const skipOpen = Boolean(process.env.TMUX) || Boolean(process.env.SSH_CONNECTION) || Boolean(process.env.SSH_TTY);
@@ -505608,13 +505789,13 @@ var init_generate_memory_viewer = __esm(() => {
505608
505789
  init_local_memory_context();
505609
505790
  init_memory_viewer_template();
505610
505791
  execFile25 = promisify22(execFileCb6);
505611
- VIEWERS_DIR = join118(resolveGlobalConfigDir(), "viewers");
505792
+ VIEWERS_DIR = join119(resolveGlobalConfigDir(), "viewers");
505612
505793
  REFLECTION_PATTERN = /\(reflection\)|🔮|reflection:/i;
505613
505794
  });
505614
505795
 
505615
505796
  // src/cli/components/MemfsTreeViewer.tsx
505616
505797
  import { existsSync as existsSync79 } from "node:fs";
505617
- import { join as join119 } from "node:path";
505798
+ import { join as join120 } from "node:path";
505618
505799
  function renderTreePrefix(node) {
505619
505800
  let prefix = "";
505620
505801
  for (let i4 = 0;i4 < node.depth; i4++) {
@@ -505643,7 +505824,7 @@ function MemfsTreeViewer({
505643
505824
  const statusTimerRef = import_react88.useRef(null);
505644
505825
  const memoryRoot = getScopedMemoryFilesystemRoot(agentId);
505645
505826
  const memoryExists = existsSync79(memoryRoot);
505646
- const hasGitRepo = import_react88.useMemo(() => existsSync79(join119(memoryRoot, ".git")), [memoryRoot]);
505827
+ const hasGitRepo = import_react88.useMemo(() => existsSync79(join120(memoryRoot, ".git")), [memoryRoot]);
505647
505828
  function showStatus(msg, durationMs) {
505648
505829
  if (statusTimerRef.current)
505649
505830
  clearTimeout(statusTimerRef.current);
@@ -508375,10 +508556,10 @@ var init_use_chatgpt_rate_limit_state = __esm(() => {
508375
508556
  // src/utils/aws-credentials.ts
508376
508557
  import { readFile as readFile35 } from "node:fs/promises";
508377
508558
  import { homedir as homedir36 } from "node:os";
508378
- import { join as join120 } from "node:path";
508559
+ import { join as join121 } from "node:path";
508379
508560
  async function parseAwsCredentials() {
508380
- const credentialsPath = join120(homedir36(), ".aws", "credentials");
508381
- const configPath = join120(homedir36(), ".aws", "config");
508561
+ const credentialsPath = join121(homedir36(), ".aws", "credentials");
508562
+ const configPath = join121(homedir36(), ".aws", "config");
508382
508563
  const profiles = new Map;
508383
508564
  try {
508384
508565
  const content = await readFile35(credentialsPath, "utf-8");
@@ -510141,7 +510322,7 @@ var init_ReasoningMessageRich = __esm(async () => {
510141
510322
  });
510142
510323
 
510143
510324
  // src/cli/components/skills-dialog-paths.ts
510144
- import { join as join121 } from "node:path";
510325
+ import { join as join122 } from "node:path";
510145
510326
  function displayDirectory(path50) {
510146
510327
  return `${path50.replace(/\\/g, "/").replace(/\/$/, "")}/`;
510147
510328
  }
@@ -510151,7 +510332,7 @@ function getSkillsTabDescription(tab2, agentId, env6 = process.env) {
510151
510332
  return ".agents/skills/";
510152
510333
  case "agent": {
510153
510334
  const memoryDir = resolveScopedMemoryDir({ agentId, env: env6 });
510154
- return memoryDir ? displayDirectory(join121(memoryDir, "skills")) : "$MEMORY_DIR/skills/";
510335
+ return memoryDir ? displayDirectory(join122(memoryDir, "skills")) : "$MEMORY_DIR/skills/";
510155
510336
  }
510156
510337
  case "global":
510157
510338
  return displayDirectory(getGlobalSkillsDir(env6));
@@ -510179,8 +510360,8 @@ function SkillsDialog({ onClose, agentId }) {
510179
510360
  try {
510180
510361
  const { discoverSkills: discoverSkills2, SKILLS_DIR: SKILLS_DIR2 } = await Promise.resolve().then(() => (init_skills5(), exports_skills2));
510181
510362
  const { getSkillsDirectory: getSkillsDirectory2, getSkillSources: getSkillSources2 } = await Promise.resolve().then(() => (init_context(), exports_context));
510182
- const { join: join122 } = await import("node:path");
510183
- const skillsDir = getSkillsDirectory2() || join122(process.cwd(), SKILLS_DIR2);
510363
+ const { join: join123 } = await import("node:path");
510364
+ const skillsDir = getSkillsDirectory2() || join123(process.cwd(), SKILLS_DIR2);
510184
510365
  const result3 = await discoverSkills2(skillsDir, agentId, {
510185
510366
  sources: getSkillSources2()
510186
510367
  });
@@ -514486,9 +514667,9 @@ function getFileEditHeader(toolName2, toolArgs) {
514486
514667
  } else if (operations2.length === 1) {
514487
514668
  const op = operations2[0];
514488
514669
  if (op) {
514489
- const { relative: relative14 } = __require("node:path");
514670
+ const { relative: relative15 } = __require("node:path");
514490
514671
  const cwd3 = process.cwd();
514491
- const relPath2 = relative14(cwd3, op.path);
514672
+ const relPath2 = relative15(cwd3, op.path);
514492
514673
  const displayPath2 = relPath2.startsWith("..") ? op.path : relPath2;
514493
514674
  if (op.kind === "add")
514494
514675
  return `Write to ${displayPath2}?`;
@@ -514502,9 +514683,9 @@ function getFileEditHeader(toolName2, toolArgs) {
514502
514683
  return "Apply patch?";
514503
514684
  }
514504
514685
  const filePath = args.file_path || "";
514505
- const { relative: relative13 } = __require("node:path");
514686
+ const { relative: relative14 } = __require("node:path");
514506
514687
  const cwd2 = process.cwd();
514507
- const relPath = relative13(cwd2, filePath);
514688
+ const relPath = relative14(cwd2, filePath);
514508
514689
  const displayPath = relPath.startsWith("..") ? filePath : relPath;
514509
514690
  if (t2 === "write") {
514510
514691
  const { existsSync: existsSync80 } = __require("node:fs");
@@ -514589,9 +514770,9 @@ var init_ApprovalPreview = __esm(async () => {
514589
514770
  /* @__PURE__ */ jsx_dev_runtime96.jsxDEV(Box_default, {
514590
514771
  flexDirection: "column",
514591
514772
  children: operations2.map((op, idx) => {
514592
- const { relative: relative13 } = __require("node:path");
514773
+ const { relative: relative14 } = __require("node:path");
514593
514774
  const cwd2 = process.cwd();
514594
- const relPath = relative13(cwd2, op.path);
514775
+ const relPath = relative14(cwd2, op.path);
514595
514776
  const displayPath = relPath.startsWith("..") ? op.path : relPath;
514596
514777
  const diffKey = toolCallId ? `${toolCallId}:${op.path}` : undefined;
514597
514778
  const opDiff = diffKey && allDiffs ? allDiffs.get(diffKey) : undefined;
@@ -516278,7 +516459,7 @@ __export(exports_generate_diff_viewer, {
516278
516459
  });
516279
516460
  import { execFile as execFileCb7 } from "node:child_process";
516280
516461
  import { chmodSync as chmodSync12, existsSync as existsSync80, mkdirSync as mkdirSync61, writeFileSync as writeFileSync53 } from "node:fs";
516281
- import { isAbsolute as isAbsolute28, join as join122, resolve as resolve42 } from "node:path";
516462
+ import { isAbsolute as isAbsolute29, join as join123, resolve as resolve43 } from "node:path";
516282
516463
  import { promisify as promisify23 } from "node:util";
516283
516464
  async function runGit8(cwd2, args) {
516284
516465
  try {
@@ -516480,7 +516661,7 @@ function escapeHtml3(value) {
516480
516661
  function resolveTargetPath(targetPath) {
516481
516662
  if (!targetPath?.trim())
516482
516663
  return process.cwd();
516483
- return isAbsolute28(targetPath) ? targetPath : resolve42(process.cwd(), targetPath);
516664
+ return isAbsolute29(targetPath) ? targetPath : resolve43(process.cwd(), targetPath);
516484
516665
  }
516485
516666
  function shouldSkipOpen() {
516486
516667
  return Boolean(process.env.TMUX) || Boolean(process.env.SSH_CONNECTION) || Boolean(process.env.SSH_TTY);
@@ -516507,7 +516688,7 @@ async function generateAndOpenDiffViewer(targetPath) {
516507
516688
  try {
516508
516689
  chmodSync12(VIEWERS_DIR2, 448);
516509
516690
  } catch {}
516510
- const filePath = join122(VIEWERS_DIR2, `diff-${encodeURIComponent(worktreePath)}.html`);
516691
+ const filePath = join123(VIEWERS_DIR2, `diff-${encodeURIComponent(worktreePath)}.html`);
516511
516692
  writeFileSync53(filePath, html5);
516512
516693
  chmodSync12(filePath, 384);
516513
516694
  const skipOpen = shouldSkipOpen();
@@ -516577,7 +516758,7 @@ var init_generate_diff_viewer = __esm(() => {
516577
516758
  init_settings_path();
516578
516759
  init_diff_viewer_template();
516579
516760
  execFile26 = promisify23(execFileCb7);
516580
- VIEWERS_DIR2 = join122(resolveGlobalConfigDir(), "viewers");
516761
+ VIEWERS_DIR2 = join123(resolveGlobalConfigDir(), "viewers");
516581
516762
  GIT_MAX_BUFFER = 50 * 1024 * 1024;
516582
516763
  });
516583
516764
 
@@ -518540,7 +518721,7 @@ __export(exports_shell_aliases, {
518540
518721
  });
518541
518722
  import { existsSync as existsSync81, readFileSync as readFileSync59 } from "node:fs";
518542
518723
  import { homedir as homedir37 } from "node:os";
518543
- import { join as join123 } from "node:path";
518724
+ import { join as join124 } from "node:path";
518544
518725
  function parseAliasesFromFile(filePath) {
518545
518726
  const aliases = new Map;
518546
518727
  if (!existsSync81(filePath)) {
@@ -518612,7 +518793,7 @@ function loadAliases(forceReload = false) {
518612
518793
  const home = homedir37();
518613
518794
  const allAliases = new Map;
518614
518795
  for (const file of ALIAS_FILES) {
518615
- const filePath = join123(home, file);
518796
+ const filePath = join124(home, file);
518616
518797
  const fileAliases = parseAliasesFromFile(filePath);
518617
518798
  for (const [name, value] of fileAliases) {
518618
518799
  allAliases.set(name, value);
@@ -519773,7 +519954,7 @@ var init_system_reminders2 = __esm(() => {
519773
519954
  // src/cli/app/use-conversation-loop.ts
519774
519955
  import { randomUUID as randomUUID71 } from "node:crypto";
519775
519956
  function sleep12(ms) {
519776
- return new Promise((resolve43) => setTimeout(resolve43, ms));
519957
+ return new Promise((resolve44) => setTimeout(resolve44, ms));
519777
519958
  }
519778
519959
  function makeExecutionPhaseHook(setExecutionPhase) {
519779
519960
  return ({ chunk: chunk2 }) => {
@@ -520227,7 +520408,7 @@ function useConversationLoop(ctx) {
520227
520408
  cancelled = true;
520228
520409
  break;
520229
520410
  }
520230
- await new Promise((resolve43) => setTimeout(resolve43, 100));
520411
+ await new Promise((resolve44) => setTimeout(resolve44, 100));
520231
520412
  }
520232
520413
  if (!blockingRunId) {
520233
520414
  buffersRef.current.byId.delete(statusId);
@@ -520274,7 +520455,7 @@ function useConversationLoop(ctx) {
520274
520455
  cancelled = true;
520275
520456
  break;
520276
520457
  }
520277
- await new Promise((resolve43) => setTimeout(resolve43, 100));
520458
+ await new Promise((resolve44) => setTimeout(resolve44, 100));
520278
520459
  }
520279
520460
  if (retryStatusId) {
520280
520461
  buffersRef.current.byId.delete(retryStatusId);
@@ -521030,7 +521211,7 @@ ${feedback}
521030
521211
  });
521031
521212
  buffersRef.current.order.push(statusId);
521032
521213
  refreshDerived();
521033
- await new Promise((resolve43) => setTimeout(resolve43, delayMs));
521214
+ await new Promise((resolve44) => setTimeout(resolve44, delayMs));
521034
521215
  buffersRef.current.byId.delete(statusId);
521035
521216
  buffersRef.current.order = buffersRef.current.order.filter((id) => id !== statusId);
521036
521217
  refreshDerived();
@@ -521070,7 +521251,7 @@ ${feedback}
521070
521251
  cancelled = true;
521071
521252
  break;
521072
521253
  }
521073
- await new Promise((resolve43) => setTimeout(resolve43, 100));
521254
+ await new Promise((resolve44) => setTimeout(resolve44, 100));
521074
521255
  }
521075
521256
  if (retryStatusId) {
521076
521257
  buffersRef.current.byId.delete(retryStatusId);
@@ -523796,7 +523977,7 @@ async function writeHistoryArtifacts(params) {
523796
523977
  }
523797
523978
  async function defaultCommandRunner(command, args, options) {
523798
523979
  const startedAt = Date.now();
523799
- return new Promise((resolve43) => {
523980
+ return new Promise((resolve44) => {
523800
523981
  const child = spawn16(command, args, {
523801
523982
  cwd: options.cwd,
523802
523983
  env: options.env,
@@ -523823,7 +524004,7 @@ async function defaultCommandRunner(command, args, options) {
523823
524004
  });
523824
524005
  child.on("close", (exitCode) => {
523825
524006
  clearTimeout(timeout);
523826
- resolve43({
524007
+ resolve44({
523827
524008
  args,
523828
524009
  command,
523829
524010
  cwd: options.cwd,
@@ -526848,7 +527029,7 @@ var init_conversation_switch_alert = __esm(() => {
526848
527029
  import { randomUUID as randomUUID73 } from "node:crypto";
526849
527030
  import { existsSync as existsSync82, readFileSync as readFileSync60, renameSync as renameSync14 } from "node:fs";
526850
527031
  import { tmpdir as tmpdir17 } from "node:os";
526851
- import { join as join124 } from "node:path";
527032
+ import { join as join125 } from "node:path";
526852
527033
  async function findCustomCommandByName(commandName) {
526853
527034
  const { findCustomCommand: findCustomCommand2 } = await Promise.resolve().then(() => (init_custom(), exports_custom));
526854
527035
  return findCustomCommand2(commandName);
@@ -527456,8 +527637,8 @@ ${SYSTEM_REMINDER_CLOSE}`),
527456
527637
  try {
527457
527638
  const memoryRoot = getScopedMemoryFilesystemRoot(agentId);
527458
527639
  const personaCandidates = [
527459
- join124(memoryRoot, "system", "persona.md"),
527460
- join124(memoryRoot, "memory", "system", "persona.md")
527640
+ join125(memoryRoot, "system", "persona.md"),
527641
+ join125(memoryRoot, "memory", "system", "persona.md")
527461
527642
  ];
527462
527643
  const personaPath = personaCandidates.find((candidate) => existsSync82(candidate));
527463
527644
  if (personaPath) {
@@ -528305,7 +528486,7 @@ Path: ${memoryDir}`, true);
528305
528486
  updateMemorySyncCommand(cmdId, "No local memory filesystem found to reset.", true, msg);
528306
528487
  return { submitted: true };
528307
528488
  }
528308
- const backupDir = join124(tmpdir17(), `letta-memfs-reset-${agentId}-${Date.now()}`);
528489
+ const backupDir = join125(tmpdir17(), `letta-memfs-reset-${agentId}-${Date.now()}`);
528309
528490
  renameSync14(memoryDir, backupDir);
528310
528491
  if (getBackend().capabilities.localMemfs) {
528311
528492
  const { initializeLocalMemoryRepo: initializeLocalMemoryRepo2 } = await Promise.resolve().then(() => (init_memory_git(), exports_memory_git));
@@ -529214,7 +529395,7 @@ var init_use_submit_handler = __esm(async () => {
529214
529395
  });
529215
529396
 
529216
529397
  // src/cli/app/AppCoordinator.tsx
529217
- import { join as join125 } from "node:path";
529398
+ import { join as join126 } from "node:path";
529218
529399
  function buildStartupCommandHints(options) {
529219
529400
  const {
529220
529401
  isResumingConversation,
@@ -530495,7 +530676,7 @@ function App2({
530495
530676
  agentId: a2.agentId ?? null
530496
530677
  }))
530497
530678
  });
530498
- const agentModsDirectory = modContext.memfs.enabled && modContext.memfs.memoryDir ? join125(modContext.memfs.memoryDir, "mods") : null;
530679
+ const agentModsDirectory = modContext.memfs.enabled && modContext.memfs.memoryDir ? join126(modContext.memfs.memoryDir, "mods") : null;
530499
530680
  const modAdapter = useLocalModAdapter(modContext, {
530500
530681
  agentModsDirectory,
530501
530682
  disabled: modsDisabled,
@@ -532836,12 +533017,12 @@ EXAMPLES
532836
533017
  console.log(usage);
532837
533018
  }
532838
533019
  async function printInfo() {
532839
- const { join: join126 } = await import("node:path");
533020
+ const { join: join127 } = await import("node:path");
532840
533021
  const { getVersion: getVersion2 } = await Promise.resolve().then(() => (init_version(), exports_version));
532841
533022
  const { SKILLS_DIR: SKILLS_DIR2 } = await Promise.resolve().then(() => (init_skills5(), exports_skills2));
532842
533023
  const { exists: exists2 } = await Promise.resolve().then(() => (init_fs(), exports_fs));
532843
533024
  const cwd2 = process.cwd();
532844
- const skillsDir = join126(cwd2, SKILLS_DIR2);
533025
+ const skillsDir = join127(cwd2, SKILLS_DIR2);
532845
533026
  const skillsExist = exists2(skillsDir);
532846
533027
  await settingsManager.loadLocalProjectSettings(cwd2);
532847
533028
  const pinned = settingsManager.getPinnedAgents();
@@ -536703,4 +536884,4 @@ function registerBunOAuthFlows() {
536703
536884
  registerBunOAuthFlows();
536704
536885
  await init_src5().then(() => exports_src2);
536705
536886
 
536706
- //# debugId=F2C2B5566F98148D64756E2164756E21
536887
+ //# debugId=A36F7BFC09468D8164756E2164756E21