@cydm/pie 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -155,6 +155,8 @@ import {
155
155
  streamSimple,
156
156
  type_exports
157
157
  } from "./chunks/chunk-3W3SXVPB.js";
158
+ import "./chunks/chunk-F7EBZTZO.js";
159
+ import "./chunks/chunk-ZPJ3BNQB.js";
158
160
  import {
159
161
  IsArray,
160
162
  IsBigInt,
@@ -169,8 +171,6 @@ import {
169
171
  TypeBoxError,
170
172
  TypeSystemPolicy
171
173
  } from "./chunks/chunk-XXGYUYXI.js";
172
- import "./chunks/chunk-F7EBZTZO.js";
173
- import "./chunks/chunk-ZPJ3BNQB.js";
174
174
  import {
175
175
  resolveCliProjectRoot
176
176
  } from "./chunks/chunk-WLFOBECN.js";
@@ -72399,7 +72399,7 @@ function handleContextReportCommand(host) {
72399
72399
  const contextWindow = host.options.model?.contextWindow ?? 0;
72400
72400
  const reserveTokens = host.options.settingsManager.getAutoCompactReserveTokens();
72401
72401
  const autoCompactEnabled = host.options.settingsManager.getAutoCompactEnabled();
72402
- const autoCompactLimit = contextWindow > 0 ? getAutoCompactTokenLimit(contextWindow, reserveTokens) ?? null : null;
72402
+ const autoCompactLimit2 = contextWindow > 0 ? getAutoCompactTokenLimit(contextWindow, reserveTokens) ?? null : null;
72403
72403
  const state = host.agent.state;
72404
72404
  const prefixHash = computePromptPrefixHash(
72405
72405
  systemPrompt,
@@ -72440,7 +72440,7 @@ function handleContextReportCommand(host) {
72440
72440
  providerMeasuredAt: usage2.providerMeasuredAt,
72441
72441
  measurementMatchesCurrentContext: usage2.measurementMatchesCurrentContext,
72442
72442
  autoCompactEnabled,
72443
- autoCompactLimitTokens: autoCompactLimit,
72443
+ autoCompactLimitTokens: autoCompactLimit2,
72444
72444
  reserveTokens,
72445
72445
  promptPrefixHash: prefixHash,
72446
72446
  promptPrefixChanged
@@ -73394,6 +73394,76 @@ function handleSessionCommand(host) {
73394
73394
  host.ui.requestRender();
73395
73395
  }
73396
73396
 
73397
+ // src/commands/builtin-command-catalog.ts
73398
+ var BUILTIN_COMMAND_CATALOG = [
73399
+ { path: ["sessions"], description: "Manage sessions: resume, new, tree, fork, compact, info", headless: "category" },
73400
+ { path: ["sessions", "compact"], description: "Summarize history and replace it with a compact checkpoint", headless: "supported" },
73401
+ { path: ["sessions", "new"], description: "Start a new session", headless: "requires-ui" },
73402
+ { path: ["sessions", "resume"], description: "Resume a different session", headless: "requires-ui" },
73403
+ { path: ["sessions", "tree"], description: "Navigate session tree", headless: "requires-ui" },
73404
+ { path: ["sessions", "info"], description: "Show session info", headless: "requires-ui" },
73405
+ { path: ["sessions", "fork"], description: "Fork from a message", headless: "requires-ui" },
73406
+ // Multi-agent IM design (2026-11-09): the one user-facing naming entry
73407
+ // inside the TUI. Before this, renaming needed the CLI subcommand
73408
+ // (`pie sessions rename <id> <name>`), which nobody meets in daily use —
73409
+ // so sessions stayed nameless and every surface fell back to id tails.
73410
+ { path: ["sessions", "name"], description: "Name this session \u2014 /sessions/name <name> (manual name: wins everywhere, never auto-replaced)", headless: "requires-ui" },
73411
+ { path: ["settings", "help"], description: "Show help information (keyboard shortcuts and commands)", headless: "requires-ui" },
73412
+ { path: ["settings"], description: "Open settings menu", headless: "requires-ui" },
73413
+ { path: ["settings", "model"], description: "Select AI model", headless: "requires-ui" },
73414
+ { path: ["settings", "hotkeys"], description: "Show keyboard shortcuts", headless: "requires-ui" },
73415
+ { path: ["settings", "theme"], description: "Change theme", headless: "requires-ui" },
73416
+ { path: ["settings", "thinking"], description: "Set thinking level (off/minimal/low/medium/high/xhigh)", headless: "requires-ui" },
73417
+ { path: ["settings", "yolo"], description: "Toggle or set YOLO mode (on/off/status)", headless: "requires-ui" },
73418
+ { path: ["settings", "calm"], description: "Toggle calm mode: show only questions and answers (on/off/status)", headless: "requires-ui" },
73419
+ { path: ["extensions"], description: "List extensions and manage enable/disable toggles", headless: "requires-ui" },
73420
+ { path: ["extensions", "list"], description: "List discovered extensions (including disabled)", headless: "requires-ui" },
73421
+ { path: ["extensions", "enable"], description: "Enable an extension by identity (writes settings)", headless: "requires-ui" },
73422
+ { path: ["extensions", "disable"], description: "Disable an extension by identity (writes settings)", headless: "requires-ui" },
73423
+ { path: ["skills"], description: "Manage skills: list, toggle enable/disable, invoke", headless: "requires-ui" },
73424
+ { path: ["skills", "list"], description: "List available skills (plain text)", headless: "requires-ui" },
73425
+ { path: ["skills", "use"], description: "Use a skill", headless: "requires-ui" },
73426
+ { path: ["skills", "create"], description: "Create a new skill from a template", headless: "requires-ui" },
73427
+ { path: ["skills", "reload"], description: "Reload skills from disk", headless: "requires-ui" },
73428
+ { path: ["skills", "enable"], description: "Enable a skill by name (writes settings, reloads immediately)", headless: "requires-ui" },
73429
+ { path: ["skills", "disable"], description: "Disable a skill by name (writes settings, reloads immediately)", headless: "requires-ui" },
73430
+ { path: ["tools", "subagent"], description: "Spawn subagents in parallel to handle tasks", headless: "requires-ui" },
73431
+ { path: ["tools"], description: "List runtime tools and manage enable/disable toggles", headless: "requires-ui" },
73432
+ { path: ["tools", "list"], description: "List runtime tools and their state (plain text)", headless: "requires-ui" },
73433
+ { path: ["tools", "enable"], description: "Enable a tool by name (writes settings; live tools apply now)", headless: "requires-ui" },
73434
+ { path: ["tools", "disable"], description: "Disable a tool by name (writes settings; applies now)", headless: "requires-ui" },
73435
+ { path: ["debugs", "cache-test"], description: "Run provider cache diagnostics with a dedicated 2-request probe", headless: "requires-ui" },
73436
+ { path: ["debugs", "context"], description: "Context composition report: sections, tokens, drill-down", headless: "supported" },
73437
+ { path: ["debugs", "trace"], description: "Session trace: timeline, tool stats, runtime events", headless: "requires-ui" },
73438
+ { path: ["debugs", "boot"], description: "Boot composition pipeline: how the runtime was assembled", headless: "requires-ui" },
73439
+ { path: ["settings", "quit"], description: "Exit Pie", headless: "requires-ui" }
73440
+ ];
73441
+ function findBuiltinCommand(path26) {
73442
+ return BUILTIN_COMMAND_CATALOG.find((entry) => entry.path.join("/") === path26);
73443
+ }
73444
+ function headlessRefusalFor(path26) {
73445
+ const entry = findBuiltinCommand(path26);
73446
+ if (!entry) return `unknown command: ${path26}`;
73447
+ if (entry.headless === "category") return `"${path26}" is a command category; pick a sub-command`;
73448
+ if (entry.headless === "requires-ui") return `"${path26}" needs an interactive terminal; not available on a background worker`;
73449
+ return void 0;
73450
+ }
73451
+ function registerHeadlessBuiltinCommands(tree, executors) {
73452
+ for (const entry of BUILTIN_COMMAND_CATALOG) {
73453
+ const key = entry.path.join("/");
73454
+ let handler;
73455
+ if (entry.headless === "supported") {
73456
+ const executor = executors[key];
73457
+ if (!executor) throw new Error(`headless host mounted builtin command "${key}" without an executor`);
73458
+ handler = executor;
73459
+ } else {
73460
+ const refusal = headlessRefusalFor(key);
73461
+ handler = () => refusal;
73462
+ }
73463
+ tree.register(entry.path, { description: entry.description, handler });
73464
+ }
73465
+ }
73466
+
73397
73467
  // src/commands/interactive-command-registration.ts
73398
73468
  function createExtensionContextForCommands(host) {
73399
73469
  return {
@@ -73489,161 +73559,60 @@ function createExtensionContextForCommands(host) {
73489
73559
  };
73490
73560
  }
73491
73561
  function registerBuiltinCommands(host) {
73492
- commandTree.register(["sessions"], {
73493
- description: "Manage sessions: resume, new, tree, fork, compact, info"
73494
- });
73495
- commandTree.register(["sessions", "compact"], {
73496
- description: "Summarize history and replace it with a compact checkpoint",
73497
- handler: () => host.handleCompactCommand()
73498
- });
73499
- commandTree.register(["sessions", "new"], {
73500
- description: "Start a new session",
73501
- handler: () => host.handleClearCommand()
73502
- });
73503
- commandTree.register(["sessions", "resume"], {
73504
- description: "Resume a different session",
73505
- handler: () => host.handleResumeCommand()
73506
- });
73507
- commandTree.register(["sessions", "tree"], {
73508
- description: "Navigate session tree",
73509
- handler: () => host.handleTreeCommand()
73510
- });
73511
- commandTree.register(["sessions", "info"], {
73512
- description: "Show session info",
73513
- handler: () => host.handleSessionCommand()
73514
- });
73515
- commandTree.register(["sessions", "fork"], {
73516
- description: "Fork from a message",
73517
- handler: () => host.handleForkCommand()
73518
- });
73519
- commandTree.register(["sessions", "name"], {
73520
- description: "Name this session \u2014 /sessions/name <name> (manual name: wins everywhere, never auto-replaced)",
73521
- handler: (_ctx, args) => host.handleNameCommand(args?.trim() ?? "")
73522
- });
73523
- commandTree.register(["settings", "help"], {
73524
- description: "Show help information (keyboard shortcuts and commands)",
73525
- handler: () => host.handleHotkeysCommand()
73526
- });
73527
- commandTree.register(["settings"], {
73528
- description: "Open settings menu",
73529
- handler: () => host.showSettingsSelector()
73530
- });
73531
- commandTree.register(["settings", "model"], {
73532
- description: "Select AI model",
73533
- handler: (_2, args) => host.handleModelCommand(args)
73534
- });
73535
- commandTree.register(["settings", "hotkeys"], {
73536
- description: "Show keyboard shortcuts",
73537
- handler: () => host.handleHotkeysCommand()
73538
- });
73539
- commandTree.register(["settings", "theme"], {
73540
- description: "Change theme",
73541
- handler: () => host.showSettingsSelector("theme")
73542
- });
73543
- commandTree.register(["settings", "thinking"], {
73544
- description: "Set thinking level (off/minimal/low/medium/high/xhigh)",
73545
- handler: (_2, args) => host.handleThinkingCommand(args)
73546
- });
73547
- commandTree.register(["settings", "yolo"], {
73548
- description: "Toggle or set YOLO mode (on/off/status)",
73549
- handler: (_2, args) => host.handleYoloCommand(args)
73550
- });
73551
- commandTree.register(["settings", "calm"], {
73552
- description: "Toggle calm mode: show only questions and answers (on/off/status)",
73553
- handler: (_2, args) => host.handleCalmCommand(args)
73554
- });
73555
- commandTree.register(["extensions"], {
73556
- description: "List extensions and manage enable/disable toggles",
73557
- handler: (_2, args) => host.handleExtensionsCommand(args)
73558
- });
73559
- commandTree.register(["extensions", "list"], {
73560
- description: "List discovered extensions (including disabled)",
73561
- handler: (_2, args) => host.handleExtensionsCommand(args ? `list ${args}` : "list")
73562
- });
73563
- commandTree.register(["extensions", "enable"], {
73564
- description: "Enable an extension by identity (writes settings)",
73565
- handler: (_2, args) => host.handleExtensionsCommand(`enable ${args || ""}`)
73566
- });
73567
- commandTree.register(["extensions", "disable"], {
73568
- description: "Disable an extension by identity (writes settings)",
73569
- handler: (_2, args) => host.handleExtensionsCommand(`disable ${args || ""}`)
73570
- });
73571
- commandTree.register(["skills"], {
73572
- description: "Manage skills: list, toggle enable/disable, invoke",
73573
- handler: () => host.handleSkillsCommand()
73574
- });
73575
- commandTree.register(["skills", "list"], {
73576
- description: "List available skills (plain text)",
73577
- handler: () => host.handleSkillsListCommand()
73578
- });
73579
- commandTree.register(["skills", "use"], {
73580
- description: "Use a skill",
73581
- handler: (_2, args) => host.handleSkillCommand(args || "")
73582
- });
73583
- commandTree.register(["skills", "create"], {
73584
- description: "Create a new skill from a template",
73585
- handler: (_2, args) => host.handleSkillsCreate(args || "")
73586
- });
73587
- commandTree.register(["skills", "reload"], {
73588
- description: "Reload skills from disk",
73589
- handler: async () => {
73562
+ const handlers = {
73563
+ "sessions/compact": () => host.handleCompactCommand(),
73564
+ "sessions/new": () => host.handleClearCommand(),
73565
+ "sessions/resume": () => host.handleResumeCommand(),
73566
+ "sessions/tree": () => host.handleTreeCommand(),
73567
+ "sessions/info": () => host.handleSessionCommand(),
73568
+ "sessions/fork": () => host.handleForkCommand(),
73569
+ "sessions/name": (_ctx, args) => host.handleNameCommand(args?.trim() ?? ""),
73570
+ "settings/help": () => host.handleHotkeysCommand(),
73571
+ "settings": () => host.showSettingsSelector(),
73572
+ "settings/model": (_2, args) => host.handleModelCommand(args),
73573
+ "settings/hotkeys": () => host.handleHotkeysCommand(),
73574
+ "settings/theme": () => host.showSettingsSelector("theme"),
73575
+ "settings/thinking": (_2, args) => host.handleThinkingCommand(args),
73576
+ "settings/yolo": (_2, args) => host.handleYoloCommand(args),
73577
+ "settings/calm": (_2, args) => host.handleCalmCommand(args),
73578
+ "extensions": (_2, args) => host.handleExtensionsCommand(args),
73579
+ "extensions/list": (_2, args) => host.handleExtensionsCommand(args ? `list ${args}` : "list"),
73580
+ "extensions/enable": (_2, args) => host.handleExtensionsCommand(`enable ${args || ""}`),
73581
+ "extensions/disable": (_2, args) => host.handleExtensionsCommand(`disable ${args || ""}`),
73582
+ "skills": () => host.handleSkillsCommand(),
73583
+ "skills/list": () => host.handleSkillsListCommand(),
73584
+ "skills/use": (_2, args) => host.handleSkillCommand(args || ""),
73585
+ "skills/create": (_2, args) => host.handleSkillsCreate(args || ""),
73586
+ "skills/reload": async () => {
73590
73587
  await host.handleSkillsReload();
73588
+ },
73589
+ "skills/enable": (_2, args) => host.handleSkillToggleCommand(args || "", true),
73590
+ "skills/disable": (_2, args) => host.handleSkillToggleCommand(args || "", false),
73591
+ "tools/subagent": (_2, args) => host.handleSubagentCommand(args || ""),
73592
+ "tools": (_2, args) => host.handleToolsCommand(args || ""),
73593
+ "tools/list": (_2, args) => host.handleToolsCommand(args ? `list ${args}` : "list"),
73594
+ "tools/enable": (_2, args) => host.handleToolsCommand(`enable ${args || ""}`),
73595
+ "tools/disable": (_2, args) => host.handleToolsCommand(`disable ${args || ""}`),
73596
+ "debugs/cache-test": () => host.handleCacheTest(),
73597
+ "debugs/context": () => host.handleDebugReportCommand("context"),
73598
+ "debugs/trace": () => host.handleDebugReportCommand("trace"),
73599
+ "debugs/boot": () => host.handleDebugReportCommand("boot"),
73600
+ "settings/quit": () => host.cleanupAndExit()
73601
+ };
73602
+ for (const entry of BUILTIN_COMMAND_CATALOG) {
73603
+ const key = entry.path.join("/");
73604
+ const handler = entry.headless === "category" ? void 0 : handlers[key];
73605
+ if (entry.headless !== "category" && !handler) {
73606
+ throw new Error(`builtin command "${key}" has no interactive handler`);
73591
73607
  }
73592
- });
73593
- commandTree.register(["skills", "enable"], {
73594
- description: "Enable a skill by name (writes settings, reloads immediately)",
73595
- handler: (_2, args) => host.handleSkillToggleCommand(args || "", true)
73596
- });
73597
- commandTree.register(["skills", "disable"], {
73598
- description: "Disable a skill by name (writes settings, reloads immediately)",
73599
- handler: (_2, args) => host.handleSkillToggleCommand(args || "", false)
73600
- });
73608
+ commandTree.register(entry.path, { description: entry.description, handler });
73609
+ }
73601
73610
  for (const skill of host.skills) {
73602
73611
  commandTree.register(["skills", `skill:${skill.name}`], {
73603
73612
  description: skill.description,
73604
73613
  handler: (_2, args) => host.handleSkillInvoke(skill.name, args || "")
73605
73614
  });
73606
73615
  }
73607
- commandTree.register(["tools", "subagent"], {
73608
- description: "Spawn subagents in parallel to handle tasks",
73609
- handler: (_2, args) => host.handleSubagentCommand(args || "")
73610
- });
73611
- commandTree.register(["tools"], {
73612
- description: "List runtime tools and manage enable/disable toggles",
73613
- handler: (_2, args) => host.handleToolsCommand(args || "")
73614
- });
73615
- commandTree.register(["tools", "list"], {
73616
- description: "List runtime tools and their state (plain text)",
73617
- handler: (_2, args) => host.handleToolsCommand(args ? `list ${args}` : "list")
73618
- });
73619
- commandTree.register(["tools", "enable"], {
73620
- description: "Enable a tool by name (writes settings; live tools apply now)",
73621
- handler: (_2, args) => host.handleToolsCommand(`enable ${args || ""}`)
73622
- });
73623
- commandTree.register(["tools", "disable"], {
73624
- description: "Disable a tool by name (writes settings; applies now)",
73625
- handler: (_2, args) => host.handleToolsCommand(`disable ${args || ""}`)
73626
- });
73627
- commandTree.register(["debugs", "cache-test"], {
73628
- description: "Run provider cache diagnostics with a dedicated 2-request probe",
73629
- handler: () => host.handleCacheTest()
73630
- });
73631
- commandTree.register(["debugs", "context"], {
73632
- description: "Context composition report: sections, tokens, drill-down",
73633
- handler: () => host.handleDebugReportCommand("context")
73634
- });
73635
- commandTree.register(["debugs", "trace"], {
73636
- description: "Session trace: timeline, tool stats, runtime events",
73637
- handler: () => host.handleDebugReportCommand("trace")
73638
- });
73639
- commandTree.register(["debugs", "boot"], {
73640
- description: "Boot composition pipeline: how the runtime was assembled",
73641
- handler: () => host.handleDebugReportCommand("boot")
73642
- });
73643
- commandTree.register(["settings", "quit"], {
73644
- description: "Exit Pie",
73645
- handler: () => host.cleanupAndExit()
73646
- });
73647
73616
  }
73648
73617
 
73649
73618
  // src/runtime/compaction-diff.ts
@@ -78304,7 +78273,10 @@ function createInteractiveAgentSessionController(host) {
78304
78273
  compact: async (context) => {
78305
78274
  const beforeCompact = await host.extensionRunner?.emitSessionBeforeCompact({
78306
78275
  type: "session:before_compact",
78307
- reason: context.reason === "overflow" ? "overflow" : "threshold",
78276
+ // The event's grammar already carries "manual" — pass the controller
78277
+ // reason through instead of flattening it to threshold (a manual
78278
+ // host-requested compaction via the IM panel reads as manual).
78279
+ reason: context.reason,
78308
78280
  messageCount: context.messages.length
78309
78281
  });
78310
78282
  if (beforeCompact?.cancel) {
@@ -78494,7 +78466,7 @@ function createInteractiveAgentSessionController(host) {
78494
78466
  host.setSubmitLock(true);
78495
78467
  host.isProcessing = true;
78496
78468
  host.footer.setState({ status: "processing", lifecycleEvent: "auto_compact" });
78497
- host.showStatus(event.reason === "overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context...");
78469
+ host.showStatus(event.reason === "overflow" ? "Context overflow detected, compacting..." : event.reason === "manual" ? "Compacting context..." : "Auto-compacting context...");
78498
78470
  } else if (event.type === "compaction_committed") {
78499
78471
  host.resetFileObservationState(`auto compaction (${event.reason})`);
78500
78472
  host.resetRuntimeModeBlocks?.();
@@ -78509,7 +78481,7 @@ function createInteractiveAgentSessionController(host) {
78509
78481
  if (stillRunning) host.setControllerBusy(true);
78510
78482
  host.setSubmitLock(false);
78511
78483
  if (event.errorMessage) {
78512
- const prefix = event.reason === "overflow" ? "Context overflow recovery failed" : "Auto-compaction failed";
78484
+ const prefix = event.reason === "overflow" ? "Context overflow recovery failed" : event.reason === "manual" ? "Compaction failed" : "Auto-compaction failed";
78513
78485
  host.showError(`${prefix}: ${event.errorMessage}`);
78514
78486
  lastShownCompactionError = event.willRetry || stillRunning ? event.errorMessage : null;
78515
78487
  host.footer.setState({ status: stillRunning ? "processing" : "ready" });
@@ -80955,7 +80927,9 @@ function createPrintModeCompactionHandler(params) {
80955
80927
  compact: async (context) => {
80956
80928
  const beforeCompact = await params.runner.emitSessionBeforeCompact({
80957
80929
  type: "session:before_compact",
80958
- reason: context.reason === "overflow" ? "overflow" : "threshold",
80930
+ // Pass the controller reason through (manual host-requested
80931
+ // compactions keep their identity; the event grammar carries it).
80932
+ reason: context.reason,
80959
80933
  messageCount: context.messages.length
80960
80934
  });
80961
80935
  if (beforeCompact.cancel) return { aborted: true };
@@ -81260,7 +81234,7 @@ async function runPrintMode(params) {
81260
81234
  if (event.type === "turn_recovery_pending" && event.recovery === "compaction") {
81261
81235
  console.error(event.failure.kind === "context_overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context before retry...");
81262
81236
  } else if (event.type === "auto_compaction_start") {
81263
- console.error(event.reason === "overflow" ? "Context overflow detected, compacting..." : "Auto-compacting context...");
81237
+ console.error(event.reason === "overflow" ? "Context overflow detected, compacting..." : event.reason === "manual" ? "Compacting context..." : "Auto-compacting context...");
81264
81238
  } else if (event.type === "compaction_committed") {
81265
81239
  runtime.fileObservationState.clear(`auto compaction (${event.reason})`);
81266
81240
  } else {
@@ -81399,6 +81373,88 @@ function createJsonlWriter(io) {
81399
81373
  // src/app/json-events-mode.ts
81400
81374
  import * as os9 from "node:os";
81401
81375
 
81376
+ // src/runtime/headless-session-commands.ts
81377
+ function buildHeadlessContextReport(params) {
81378
+ const usage2 = calculateCliContextUsage({
81379
+ messages: params.messages,
81380
+ latestCompactionTimestamp: params.latestCompactionTimestamp ?? null
81381
+ });
81382
+ const limit = params.contextWindow && params.contextWindow > 0 ? autoCompactLimit(params.contextWindow, params.reserveTokens) : null;
81383
+ return {
81384
+ estimatedTokens: usage2.tokens,
81385
+ contextWindow: params.contextWindow ?? 0,
81386
+ percent: usage2.tokens !== null && params.contextWindow && params.contextWindow > 0 ? Math.round(usage2.tokens / params.contextWindow * 1e3) / 10 : null,
81387
+ providerMeasuredTokens: usage2.providerMeasuredTokens,
81388
+ providerMeasuredAt: usage2.providerMeasuredAt,
81389
+ measurementMatchesCurrentContext: usage2.measurementMatchesCurrentContext,
81390
+ autoCompactEnabled: params.autoCompactEnabled,
81391
+ autoCompactLimitTokens: limit,
81392
+ pendingQueuedInputs: params.controller.pendingMessageCount,
81393
+ isStreaming: params.controller.isStreaming,
81394
+ basis: "estimate",
81395
+ generatedAt: Date.now()
81396
+ };
81397
+ }
81398
+ function autoCompactLimit(contextWindow, reserveTokens) {
81399
+ const limit = getAutoCompactTokenLimit(contextWindow, reserveTokens);
81400
+ return typeof limit === "number" ? limit : null;
81401
+ }
81402
+ async function runHeadlessManualCompact(params) {
81403
+ const { controller } = params;
81404
+ if (manualCompactInFlight.has(controller)) {
81405
+ return { status: "refused", reason: "a manual compaction is already running; wait for it to finish" };
81406
+ }
81407
+ const gate = () => {
81408
+ if (controller.isStreaming) return "a turn is streaming; retry when idle";
81409
+ if (controller.hasQueuedMessages) return `${controller.pendingMessageCount} input(s) still queued; retry when idle`;
81410
+ return void 0;
81411
+ };
81412
+ const firstGate = gate();
81413
+ if (firstGate) return { status: "refused", reason: firstGate };
81414
+ const sessionId = controller.sessionManager.getActiveSession()?.id ?? "";
81415
+ const messageCount = controller.agent.state.messages.length;
81416
+ if (messageCount === 0) {
81417
+ return { status: "refused", reason: "nothing to compact yet" };
81418
+ }
81419
+ const before = await params.emitBeforeCompact({ reason: "manual", messageCount });
81420
+ if (before?.cancel) {
81421
+ return { status: "refused", reason: "cancelled by an extension (session:before_compact)" };
81422
+ }
81423
+ const afterSession = controller.sessionManager.getActiveSession()?.id ?? "";
81424
+ if (afterSession !== sessionId) {
81425
+ return { status: "refused", reason: "session changed during the pre-compact hook; nothing started" };
81426
+ }
81427
+ const secondGate = gate();
81428
+ if (secondGate) return { status: "refused", reason: secondGate };
81429
+ if (manualCompactInFlight.has(controller)) {
81430
+ return { status: "refused", reason: "a manual compaction is already running; wait for it to finish" };
81431
+ }
81432
+ manualCompactInFlight.add(controller);
81433
+ void (async () => {
81434
+ let outcome;
81435
+ try {
81436
+ const result = await controller.runAutoCompact("manual", false);
81437
+ outcome = {
81438
+ ok: !result?.aborted,
81439
+ detail: result?.aborted ? "compaction aborted (extension cancel or session change)" : `compaction committed (tokensBefore=${result?.tokensBefore ?? "?"}, savings=${result?.tokenSavings ?? "?"})`
81440
+ };
81441
+ } catch (error) {
81442
+ outcome = {
81443
+ ok: false,
81444
+ detail: `compaction failed: ${error instanceof Error ? error.message : String(error)}`
81445
+ };
81446
+ } finally {
81447
+ manualCompactInFlight.delete(controller);
81448
+ }
81449
+ params.onSettled?.(outcome);
81450
+ })();
81451
+ return { status: "accepted", sessionId };
81452
+ }
81453
+ var manualCompactInFlight = /* @__PURE__ */ new WeakSet();
81454
+ function isManualCompactionInFlight(controller) {
81455
+ return manualCompactInFlight.has(controller);
81456
+ }
81457
+
81402
81458
  // src/app/host-idle.ts
81403
81459
  var PENDING_RECOVERY = /* @__PURE__ */ new Set([
81404
81460
  "retry_pending",
@@ -81678,6 +81734,11 @@ function makeQueueExternalUserInput(context) {
81678
81734
  });
81679
81735
  };
81680
81736
  }
81737
+ function isJournalOnlyControlAudit(customType, data) {
81738
+ if (customType !== "pie.ipc.control") return false;
81739
+ const control = data?.control;
81740
+ return control === "session.context" || control === "session.compact";
81741
+ }
81681
81742
  async function loadJsonModeExtensions(params) {
81682
81743
  const uiContext = createNoOpExtensionUIContext2();
81683
81744
  const executionState = new ExecutionStateManager();
@@ -81691,6 +81752,8 @@ async function loadJsonModeExtensions(params) {
81691
81752
  trackUnregisterHandle: (unregister) => runnerCell.current.trackUnregisterHandle(unregister),
81692
81753
  emitTerminalInput: (event) => runnerCell.current.emitTerminalInput(event)
81693
81754
  };
81755
+ let manualCompactRunning = false;
81756
+ let manualCompactOutcome;
81694
81757
  const actions = {
81695
81758
  setActiveTools: (toolNames) => {
81696
81759
  const agent = params.getAgent();
@@ -81862,7 +81925,24 @@ async function loadJsonModeExtensions(params) {
81862
81925
  // best-effort catch silently ate it — the audit promised in the docs
81863
81926
  // never landed (dogfood-verified). Wire it to the session store like
81864
81927
  // print-mode does; the extension's catch keeps ack delivery unaffected.
81865
- appendEntry: (customType, data) => params.runtime.sessionManager.appendCustomEntry(customType, data).id,
81928
+ //
81929
+ // panel v3 (review r1 P1-2): the two headless session controls must NOT
81930
+ // write session history — appendCustomEntry changes the active leaf,
81931
+ // which would make the very compaction the audit records go stale at its
81932
+ // own commit verification (prepare snapshots the leaf; the audit entry
81933
+ // replaces it before the summary lands). Context reads stay history-free
81934
+ // too (boundary: zero session history). Their audit rides the stdout
81935
+ // event log instead (extension.log), which the worker journal persists.
81936
+ appendEntry: (customType, data) => {
81937
+ if (isJournalOnlyControlAudit(customType, data)) {
81938
+ writeEvent({
81939
+ type: "extension.log",
81940
+ message: `pie.ipc.control audit (journal-only): ${JSON.stringify(data)}`
81941
+ });
81942
+ return "";
81943
+ }
81944
+ return params.runtime.sessionManager.appendCustomEntry(customType, data).id;
81945
+ },
81866
81946
  // MULTI-AGENT IM v2 Phase 2.3 — machine-remote control frames
81867
81947
  // (ipc_control_notify). Distinct from queueExternalInput: a control
81868
81948
  // mutates host state directly; it NEVER enters the turn pipeline or the
@@ -81909,6 +81989,61 @@ async function loadJsonModeExtensions(params) {
81909
81989
  });
81910
81990
  return { ok: true, message: `thinking level set to ${level} (applies from the next agent execution)` };
81911
81991
  }
81992
+ if (control === "session.context") {
81993
+ const controller = params.getController();
81994
+ const agent = params.getAgent();
81995
+ if (!controller || !agent) return { ok: false, message: "runtime not composed" };
81996
+ const report = buildHeadlessContextReport({
81997
+ controller,
81998
+ messages: agent.state.messages,
81999
+ latestCompactionTimestamp: params.runtime.sessionManager.getLatestCompactionTimestamp(),
82000
+ contextWindow: params.runtime.model?.contextWindow,
82001
+ reserveTokens: params.runtime.settingsManager.getAutoCompactReserveTokens(),
82002
+ autoCompactEnabled: params.runtime.settingsManager.getAutoCompactEnabled()
82003
+ });
82004
+ return {
82005
+ ok: true,
82006
+ message: JSON.stringify({
82007
+ estimatedTokens: report.estimatedTokens,
82008
+ contextWindow: report.contextWindow,
82009
+ percent: report.percent,
82010
+ providerMeasuredTokens: report.providerMeasuredTokens,
82011
+ autoCompactEnabled: report.autoCompactEnabled,
82012
+ autoCompactLimitTokens: report.autoCompactLimitTokens,
82013
+ pendingQueuedInputs: report.pendingQueuedInputs,
82014
+ isStreaming: report.isStreaming,
82015
+ compactionRunning: manualCompactRunning,
82016
+ ...manualCompactOutcome ? { lastCompactOutcome: manualCompactOutcome } : {},
82017
+ basis: report.basis,
82018
+ generatedAt: report.generatedAt
82019
+ })
82020
+ };
82021
+ }
82022
+ if (control === "session.compact") {
82023
+ const controller = params.getController();
82024
+ if (!controller) return { ok: false, message: "runtime not composed" };
82025
+ const receipt = await runHeadlessManualCompact({
82026
+ controller,
82027
+ emitBeforeCompact: (event) => runnerCell.current.emitSessionBeforeCompact({
82028
+ type: "session:before_compact",
82029
+ reason: event.reason,
82030
+ messageCount: event.messageCount
82031
+ }),
82032
+ onSettled: (outcome) => {
82033
+ manualCompactRunning = false;
82034
+ manualCompactOutcome = outcome.detail;
82035
+ writeEvent({
82036
+ type: "extension.log",
82037
+ message: `im/session.compact: ${outcome.detail}`
82038
+ });
82039
+ }
82040
+ });
82041
+ if (receipt.status === "accepted") {
82042
+ manualCompactRunning = isManualCompactionInFlight(controller);
82043
+ }
82044
+ if (receipt.status === "refused") return { ok: false, message: receipt.reason };
82045
+ return { ok: true, message: `manual compaction submitted for ${receipt.sessionId || "session"}; the outcome is observable via session.context (lastCompactOutcome) \u2014 a controller-side refusal (busy/transitioning) also lands there` };
82046
+ }
81912
82047
  return { ok: false, message: `unknown control: ${control}` };
81913
82048
  },
81914
82049
  yoloMode: false
@@ -81958,6 +82093,41 @@ async function loadJsonModeExtensions(params) {
81958
82093
  errors.map(({ path: path26, error }) => `${path26}: ${error}`).join("\n")
81959
82094
  );
81960
82095
  }
82096
+ registerHeadlessBuiltinCommands(commandTree, {
82097
+ "sessions/compact": async () => {
82098
+ const controller = params.getController();
82099
+ if (!controller) return "runtime not composed";
82100
+ const receipt = await runHeadlessManualCompact({
82101
+ controller,
82102
+ emitBeforeCompact: (event) => runnerCell.current.emitSessionBeforeCompact({
82103
+ type: "session:before_compact",
82104
+ reason: event.reason,
82105
+ messageCount: event.messageCount
82106
+ }),
82107
+ onSettled: (outcome) => {
82108
+ writeEvent({
82109
+ type: "extension.log",
82110
+ message: `sessions/compact: ${outcome.detail}`
82111
+ });
82112
+ }
82113
+ });
82114
+ return receipt.status === "refused" ? receipt.reason : "manual compaction accepted; run /debugs/context to observe the result";
82115
+ },
82116
+ "debugs/context": async () => {
82117
+ const controller = params.getController();
82118
+ const agent = params.getAgent();
82119
+ if (!controller || !agent) return "runtime not composed";
82120
+ const report = buildHeadlessContextReport({
82121
+ controller,
82122
+ messages: agent.state.messages,
82123
+ latestCompactionTimestamp: params.runtime.sessionManager.getLatestCompactionTimestamp(),
82124
+ contextWindow: params.runtime.model?.contextWindow,
82125
+ reserveTokens: params.runtime.settingsManager.getAutoCompactReserveTokens(),
82126
+ autoCompactEnabled: params.runtime.settingsManager.getAutoCompactEnabled()
82127
+ });
82128
+ return `context estimate: ${report.estimatedTokens ?? "?"} tokens \xB7 window ${report.contextWindow || "unknown"}${report.percent !== null ? ` (${report.percent}%)` : ""} \xB7 auto-compact ${report.autoCompactEnabled ? `at ${report.autoCompactLimitTokens ?? "?"}` : "off"} \xB7 queued ${report.pendingQueuedInputs}`;
82129
+ }
82130
+ });
81961
82131
  try {
81962
82132
  await restoreExtensionProviderCredentials(params.runtime.modelRegistry);
81963
82133
  const extensionTools = filterEnabledTools(convertExtensionTools(extensions), params.runtime.settingsManager);
@@ -84245,7 +84415,7 @@ async function main() {
84245
84415
  return;
84246
84416
  }
84247
84417
  if (args[0] === STABLE_CLI_COMMANDS.manager) {
84248
- const { runManagerCommand } = await import("./chunks/manager-cli-7ZIDGDMI.js");
84418
+ const { runManagerCommand } = await import("./chunks/manager-cli-NEZA46M5.js");
84249
84419
  try {
84250
84420
  await runManagerCommand(args.slice(1));
84251
84421
  } catch (error) {