@0perator/operator 0.1.351 → 0.1.353

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 (92) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1073 -177
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +66 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +362 -33
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/toolchain/toolchain.py +528 -112
  46. package/dist/tools/deferred.js +28 -18
  47. package/dist/tools/executor.js +7 -3
  48. package/dist/tools/registry.js +68 -7
  49. package/dist/tools/result-cap.js +1 -1
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -6,19 +6,32 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
6
6
  // makes the scroll/echo/overwrite bug class of the ANSI-cursor Python core structurally impossible.
7
7
  import "./boot.js";
8
8
  import { parseAgentCommand } from "./background/commands.js";
9
- import { useCallback, useEffect, useRef, useState } from "react";
9
+ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
10
10
  import { render, Box, Text, useApp } from "ink";
11
11
  import { App } from "./ui/index.js";
12
12
  import { mastheadLines } from "./ui/Masthead.js";
13
13
  import { shouldPromptPlanExit, resolvePlanExit, PLAN_EXIT_OPTIONS } from "./ui/planExit.js";
14
- import { FREE_ROW_PRESETS, connectedAccounts, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, wantsContextStep } from "./ui/modelPicker.js";
14
+ import { initialMode, modePolicy, nextMode, parseMode, planToggleTarget } from "./permissions/modes.js";
15
+ import { FREE_ROW_PRESETS, connectedAccounts, looksLikeSecret, contextLine, contextPickerView, keyStoredLine, markModelRows, modelLine, modelPickerView, onceEach, pickerAnswer, providerPickerView, rereadConfirmView, wantsContextStep, wantsRereadConfirm } from "./ui/modelPicker.js";
15
16
  import { RemoteHost } from "./remote/host.js";
16
17
  import { REMOTE_SAFE_COMMANDS, REMOTE_SAFE_COMMAND_NAMES } from "./remote/safe-commands.js";
17
18
  import { newCode, pairURL } from "./remote/pairing.js";
18
19
  import { qrToTerminal } from "./ui/qr.js";
20
+ import { onDelegateProgress } from "./autonomy/delegate.js";
21
+ import { phaseVerb, phaseWord, holdReceipt, compactReceipt } from "./ui/phase.js";
22
+ import { pushSample, readStats, readReceipt, RECEIPT_MIN_MS } from "./ui/readProgress.js";
23
+ import { routeLabel } from "./ui/StatusRule.js";
24
+ import { planReceipt, planVerb } from "./ui/PlanPane.js";
25
+ import { expectSegs, forecast, forecastTail, noteColdRead } from "./ui/readForecast.js";
26
+ import { createDecode, decodeRate, decodeRound, deltasApprox, dueCheck, noteDecode, noteRoundRate, shallower, CHECK_TAIL } from "./ui/decodeHealth.js";
27
+ import { isRunawayRepetition } from "./engine/repetition-guard.js";
28
+ import { createLedger, interruptedLine, ledgerParts, noteCompaction, noteGenEnd, noteGenStart, noteRead, noteRound, noteTools, noteWait } from "./ui/turnLedger.js";
29
+ import { termCols } from "./ui/term.js";
19
30
  import { pollBus, pollSent, selfAgent, buildMentorWake, selectReadyWakes } from "./bus/inbox.js";
20
- import { isErrorResult, resultPreview } from "./ui/format.js";
21
- import { seedLiveTools, settleLiveTool } from "./ui/liveTools.js";
31
+ import { isErrorResult } from "./ui/format.js";
32
+ import { feedFold, foldStep, settleFold, settledFields } from "./ui/fold.js";
33
+ import { turnScoped } from "./ui/turnScope.js";
34
+ import { applyDrafts, bufferDraft, seedLiveTools, settleLiveTool, startLiveTool } from "./ui/liveTools.js";
22
35
  import { Session } from "./session.js";
23
36
  import { buildMemory } from "./memory/providers.js";
24
37
  import { cacheBustNotice } from "./engine/aurora.js";
@@ -42,7 +55,9 @@ import { hasByoToken, setByoToken } from "./auth/byo.js";
42
55
  import { getDiscoveredModels } from "./router/discovery.js";
43
56
  import { disposeShellSession, getAgentTasks, registry } from "./tools/registry.js";
44
57
  import { drainJobNotices, getJobNoticeMode, listShellJobs, onJobEvent, parseJobsArgs, pendingJobNotices, renderJobsList, runningJobCount, setJobNoticeMode, stopShellJob } from "./tools/shell-jobs.js";
45
- import { drainAgentReports, onAgentReport, pendingAgentReports, queueAgentReport, queueAgentNotice, formatStuckNotice } from "./background/notices.js";
58
+ import { drainAgentNotices, onAgentReport, pendingAgentReports, queueAgentReport, queueAgentNotice, formatStuckNotice } from "./background/notices.js";
59
+ import { reportLine, deliveredLine } from "./ui/reportLine.js";
60
+ import { pushCollapsed, popCollapsed, dropCollapsed } from "./ui/expand.js";
46
61
  import { ensureScratchDir } from "./config/scratch.js";
47
62
  import { caffeinateEnabled, startCaffeinate } from "./util/caffeinate.js";
48
63
  import { recordLiveProgress, roundProgressed, settleLiveProgress, touchedPaths } from "./memory/live-progress.js";
@@ -64,7 +79,16 @@ import { resolveMode } from "./classifier/modes.js";
64
79
  import { subagentModelFor, servingModelFor } from "./autonomy/subagent-model.js";
65
80
  import { classifierConfig } from "./classifier/config.js";
66
81
  import { throttle } from "./util/throttle.js";
67
- import { isSlashCommand } from "./util/slash.js";
82
+ import { isSlashCommand, midTurnClass } from "./util/slash.js";
83
+ import { RateFeed, readRates, rereadCost } from "./router/read-rates.js";
84
+ import { popLatest, takeSteers } from "./ui/pending.js";
85
+ import { createTurnFlow } from "./ui/turnFlow.js";
86
+ import { engineStopSteps, interruptSteps, settledPartial } from "./ui/nextStep.js";
87
+ import { MAIN, agentMention, conversationList, switcherKey, transcriptHeader, transcriptLines } from "./ui/conversations.js";
88
+ import { termRows } from "./ui/term.js";
89
+ import { actNowOffer, guardDetail } from "./ui/actNow.js";
90
+ import { OWNER_ACT_MESSAGE } from "./engine/owner-act.js";
91
+ import { HubUnreadable, SOURCE_LIMITS, defaultSources, draftSkillPrompt, quotedReference, skillSkeleton, skillSlug, trustedInstructions } from "./skills/finder.js";
68
92
  import * as compose from "./compose/client.js";
69
93
  import { catalogEntry, continuationContext, folderExists, indexCatalog, searchCatalog, sessionSearchConfig } from "./memory/session-catalog.js";
70
94
  import { titleFrom } from "./memory/session-sources.js";
@@ -116,9 +140,16 @@ if (process.argv.includes("--version") || process.argv.includes("-V")) {
116
140
  }
117
141
  if (process.argv.includes("--help")) {
118
142
  process.stdout.write(mastheadLines(`v${VERSION}`).join("\n") +
119
- "\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator gateway the local model runtime: start | stop | status | health | logs\n operator toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator --version print the version\n");
143
+ "\n\nUsage:\n operator start the interactive session\n 0p short for operator (every subcommand works)\n operator --resume resume the last session in this directory\n operator update update to the latest release\n operator --fullscreen fullscreen layout: composer pinned to the bottom (or settings.ui.fullscreen)\n operator auth sign in / manage your AXE account\n operator gateway the local model runtime: start | stop | status | health | logs\n operator toolchain the llama-server store: status | verify | install | activate | rollback | migrate | which\n operator run <task>|- run one task headless (--model, --permissions, --output json, --cwd)\n operator selfimprove backfill [--since YYYY-MM-DD] [--dry-run]\n turn looped turns and mentor pairs into lessons\n operator --version print the version\n");
120
144
  process.exit(0);
121
145
  }
146
+ // `operator selfimprove backfill …` — offline: folds the flywheel's looped turns and the mentor pairs into the global
147
+ // memories.md (the fold sleep consolidation runs too). It runs before the boot below, like the fast paths, so it touches
148
+ // no keychain, seat or audit trail; it only reads settings for the lessons cap.
149
+ if (process.argv[2] === "selfimprove") {
150
+ const { runSelfImproveCli } = await import("./selfimprove/backfill.js");
151
+ process.exit(await runSelfImproveCli(process.argv.slice(3)));
152
+ }
122
153
  // operator/settings.json (override path via KODE_TSI_SETTINGS), env vars still win — see config/settings.ts.
123
154
  const settings = loadSettings();
124
155
  // Enterprise first-run: make the operator home's contract explicit BEFORE any module writes into it (0700
@@ -150,7 +181,7 @@ if (settings.search?.autopilotUrl)
150
181
  if (settings.selfImprove?.flywheel === false)
151
182
  process.env.KODE_SELFIMPROVE = "0"; // opt out of turn-capture
152
183
  if (settings.selfImprove?.memory === false)
153
- process.env.KODE_SELFIMPROVE_MEMORY = "0"; // opt out of the closed loop (a stuck session leaves a durable lesson in .operator/memories.md) — ON by default
184
+ process.env.KODE_SELFIMPROVE_MEMORY = "0"; // opt out of the closed loop (a looped or stuck turn leaves a lesson in the global memories.md) — ON by default
154
185
  if (settings.verifyGate?.enabled === false)
155
186
  process.env.KODE_VERIFY_GATE = "0"; // opt out of verify-before-done
156
187
  if (settings.verifyGate?.maxNudges != null)
@@ -257,10 +288,20 @@ if (!settings.mcp) {
257
288
  if (servers.length)
258
289
  embodimentHub = new McpHub(servers);
259
290
  }
260
- // Foreground policy = the owner's settings with computer tools forced to "ask". When computer control is
261
- // off, computerAskRules is empty, so this is behaviorally identical to settings.permissions (an empty
262
- // rules object keeps a "bypass" policy inert — zero overhead).
263
- const fgPermissions = { ...settings.permissions, rules: { ...settings.permissions.rules, ...computerAskRules } };
291
+ // Foreground policy per operating mode (permissions/modes.ts): the owner's settings, plus computer tools forced to "ask"
292
+ // in Manual and Gated. Autonomous drops that rule and puts plan review in its place. When computer control is off,
293
+ // computerAskRules is empty, so Manual is a plain bypass policy (inert — zero overhead).
294
+ const modePolicyFor = (mode) => modePolicy(mode, settings.permissions, computerAskRules);
295
+ const START_MODE = initialMode(settings.permissions.mode);
296
+ const START_POLICY = modePolicyFor(START_MODE);
297
+ const MODE_LINE = {
298
+ auto: "◆ mode → AUTONOMOUS — no approval prompts: I put multi-step work in the task list for you to review, and a money / prod / destructive step runs only if the approved plan lists it (shift+tab to cycle)",
299
+ manual: Object.keys(computerAskRules).length
300
+ ? "◈ mode → MANUAL — I execute without asking, except computer-control actions and money / prod / destructive steps (shift+tab to cycle)"
301
+ : "◈ mode → MANUAL — I execute without asking (shift+tab to cycle)",
302
+ plan: "◔ mode → PLAN — read-only research + a proposed plan; nothing runs (shift+tab to cycle)",
303
+ gated: "⊘ mode → GATED — I ask before every change (writes/edits/shell); shift+tab leaves gated for plan",
304
+ };
264
305
  // Session persistence: the conversation is auto-saved every turn and reloaded by `operator --resume`.
265
306
  // It lives in a central per-workspace state dir — NEVER in the working directory, where it would be
266
307
  // grepped back into the model's own context (self-poisoning → runaway ctx growth), committed by
@@ -415,7 +456,7 @@ function formatAgentLine(a) {
415
456
  }
416
457
  const DISPLAY_STATUS = { queued: "queued", working: "running", idle: "done", stopped: "errored" };
417
458
  function formatAgentDetail(a) {
418
- const ds = DISPLAY_STATUS[a.status] ?? a.status;
459
+ const ds = a.status === "stopped" && a.endReason ? a.endReason : DISPLAY_STATUS[a.status] ?? a.status;
419
460
  const parts = [`${a.id} [${ds}]`];
420
461
  if (a.round)
421
462
  parts.push(`round ${a.round}`);
@@ -507,7 +548,7 @@ const HELP = [
507
548
  " /artifacts browse + attach your Compose (compose.casa) artifacts: search · attach · copy url · delete",
508
549
  " /sessions [query] search Operator's and other agents' sessions (providers in agents.md) and pick one up",
509
550
  " /plan plan mode: read-only research + propose a plan (/plan again to execute)",
510
- " /mode [plan|manual|auto] set operating mode (plan · manual · autonomous); also Shift+Tab to cycle",
551
+ " /mode [auto|manual|plan|gated] set operating mode (autonomous · manual · plan · gated); Shift+Tab cycles the first three",
511
552
  " /think extended reasoning: Operator thinks before answering (/think again = off)",
512
553
  " /ultrathink deep, exhaustive reasoning for hard problems (/ultrathink again = off)",
513
554
  " /compact force-compact the conversation now",
@@ -517,13 +558,18 @@ const HELP = [
517
558
  " /skill <name|off> activate a skill as a system-prompt directive (/skill off to deactivate)",
518
559
  " /mcp [on|off] fleet MCP: status · on/off (saved) · /mcp reload (from disk) · /mcp add powertools <root>",
519
560
  " /login · /logout · /whoami /login opens the browser to approve; or /login <email> for a 6-digit code (then /login <code>); /login <token>",
520
- " /agents [id] detailed sub-agent status, or /agents <id> for a deep view + controls (msg/stop)",
561
+ " /agents [id] detailed sub-agent status, or /agents <id> for a deep view + controls (msg/stop/report)",
562
+ " @Name <text> message a running sub-agent directly — no main-model turn (@Name stop · @all stop)",
521
563
  " /bg <task|stop id> spawn a background sub-agent, list, or stop one",
522
564
  " /new start a fresh conversation",
523
565
  " /clear clear the screen (keeps the conversation)",
524
566
  " /exit /quit leave operator",
525
- "esc — interrupt a running turn (or quit when idle)",
526
- "while a turn runs: enter queues a message · esc sends it now · ↑ on an empty input edits the last queued · backspace on an empty input cancels it",
567
+ "esc — interrupt a running turn (or quit when idle); after a stop, 1-4 pick the next step",
568
+ "ctrl+y — use what you have: cut a long reasoning stream (or a loop) short and answer from what it has (think-off)",
569
+ "ctrl+g — find a skill or tool: search the AXE hub (65K+ skills), your profile and the catalogue · use · run · create a skill",
570
+ "ctrl+o — expand the latest collapsed batch or sub-agent report; press again for the one before it",
571
+ "↓ on an empty input: the conversation switcher (main + each sub-agent) · ←/→ pick · enter opens it · type to talk to it",
572
+ "while a turn runs: enter steers it (goes in before the next model call) · tab queues for after the turn · esc stops it (a typed draft goes right after) · ↑ on an empty input edits the last pending message · backspace on an empty input cancels it",
527
573
  ].join("\n");
528
574
  // Slash commands a remote-control FOLLOWER is allowed to drive (RemoteHost `command` frame →
529
575
  // SPEC/remote-session.md extension; see REMOTE_RICH_HEAD_AUDIT.md). This is BOTH the allowlist enforced
@@ -535,6 +581,8 @@ const nextId = () => `e${++ID}`;
535
581
  const fmtDuration = (sec) => (sec < 60 ? `${sec < 10 ? sec.toFixed(1) : Math.round(sec)}s` : `${Math.floor(sec / 60)}m ${Math.round(sec % 60)}s`);
536
582
  const fmtTokens = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k tokens` : `${n} token${n === 1 ? "" : "s"}`);
537
583
  const fmtMeta = (sec, tokens) => `(${fmtDuration(sec)} · ${fmtTokens(tokens)})`;
584
+ const LEDGER_MIN_MS = 30_000; // a turn this long gets a card and a time ledger, tools or not (TUI plan #6)
585
+ const HOLD_RECEIPT_MS = 5_000; // a server that held a request this long before reading says so (TUI plan #7)
538
586
  function Root() {
539
587
  const { exit } = useApp();
540
588
  const [boot, setBoot] = useState("checking");
@@ -542,9 +590,41 @@ function Root() {
542
590
  const [entries, setEntries] = useState([]);
543
591
  const [live, setLive] = useState(null);
544
592
  const [status, setStatus] = useState("idle");
545
- const [prefill, setPrefill] = useState(""); // "reading context N%" during a long prefill
546
- const prefillRef = useRef("");
593
+ const [triage, setTriage] = useState(undefined); // the front door's status line for a full turn (onTriage)
594
+ // What the turn is measurably doing (ui/phase.ts): each value set by a real engine signal in the handlers below,
595
+ // never guessed. The ref mirrors it so a handler can skip a no-op render.
596
+ const [phase, setPhaseState] = useState(null);
597
+ const phaseRef = useRef(null);
598
+ const setPhase = (p) => { if (phaseRef.current !== p) {
599
+ phaseRef.current = p;
600
+ setPhaseState(p);
601
+ } };
602
+ // The current request's prompt_progress chunks (ui/readProgress.ts) and when the request went out (the read clock's
603
+ // fallback origin when a server sends no time_ms). readTick re-renders the read line per chunk.
604
+ const readRingRef = useRef([]);
605
+ const [, setReadTick] = useState(0);
606
+ const roundStartRef = useRef(0);
607
+ const firstTokenRef = useRef(false); // this round's first reasoning/content chunk has been seen
608
+ const readReceiptRef = useRef(false); // this round settled a read receipt — its cache-bust line would say it twice
609
+ const ledgerRef = useRef(createLedger()); // where this turn's time went (ui/turnLedger.ts)
610
+ // The endpoint gate and the server (TUI plan #7): who holds the slot while this request waits, when it went out (the
611
+ // first progress chunk then says how long the server held it before reading), and a mid-turn compaction in flight.
612
+ const gateQueueRef = useRef(null);
613
+ const sentAtRef = useRef(null);
614
+ const queuedAtRef = useRef(null);
615
+ const compactRef = useRef(null);
616
+ // The cold-read forecast (TUI plan #10): each model's measured cold reads in THIS process, and the forecast armed by
617
+ // /model, a compaction or a route change — shown on the phase line until the server's first progress chunk.
618
+ const coldReadsRef = useRef(new Map());
619
+ const expectRef = useRef(null);
620
+ const lastRouteRef = useRef(null);
547
621
  const [stepLabel, setStepLabel] = useState(""); // tool(s) currently executing, for the step animation
622
+ // Repeats of the previous round fold into one counting line (ui/fold.ts) instead of a settled block per round.
623
+ const foldRef = useRef({});
624
+ // The running delegate_task's child (TUI plan #9): its events arrive through onDelegateProgress, throttled like the panel.
625
+ const delegateRef = useRef(null);
626
+ const [delegate, setDelegate] = useState(null);
627
+ const [liveFold, setLiveFold] = useState(null);
548
628
  const [liveTools, setLiveTools] = useState([]); // one row per call in the CURRENT batch,
549
629
  // live: seeded "running" by onToolStart, each flips to done/error independently as onToolResult fires
550
630
  // for it — see ui/liveTools.ts. Cleared once the batch settles (onToolBatch).
@@ -560,18 +640,37 @@ function Root() {
560
640
  const [bgAgents, setBgAgents] = useState([]);
561
641
  const [shellJobs, setShellJobs] = useState([]); // background SHELL jobs (shN), shown beside the sub-agents but never mixed with their ids
562
642
  const [tasks, setTasks] = useState([]); // session TODO list for the plan pane, refreshed after task_* tools
643
+ // The plan rail (TUI plan #5): when the last open step lands, one receipt line settles; an idle plan's clock stops at
644
+ // the end of the last turn instead of counting time nobody worked.
645
+ const planOpenRef = useRef(false);
646
+ const lastTurnEndRef = useRef(0);
647
+ const wakeTurnRef = useRef(false);
648
+ const refreshTasks = () => {
649
+ const next = getAgentTasks();
650
+ const open = next.some((t) => t.status === "pending" || t.status === "in_progress");
651
+ if (planOpenRef.current && !open && next.length)
652
+ sys(planReceipt(next, termCols()));
653
+ planOpenRef.current = open;
654
+ setTasks(next);
655
+ };
563
656
  const [authUser, setAuthUser] = useState(""); // signed-in identity for the status rule
564
657
  const [planMode, setPlanMode] = useState(false); // /plan: read-only research + propose, shown as a status badge
565
- // Operating mode, cycled with Shift+Tab (like Claude Code): auto (no gate) → manual (approve mutations)
566
- // → plan (read-only + propose) → auto. Auto=bypass policy, Manual=gated policy, Plan=session plan mode.
567
- const [opMode, setOpMode] = useState(settings.permissions.mode === "gated" ? "manual" : "auto");
658
+ // Operating mode (permissions/modes.ts), cycled with Shift+Tab: auto (plan review, no prompts) → manual (commands
659
+ // run; computer control asks) → plan (read-only + propose) → auto. Gated (every mutation asks) is outside the cycle:
660
+ // the session starts there when settings.permissions.mode is "gated", or /mode gated selects it.
661
+ const [opMode, setOpMode] = useState(START_MODE);
568
662
  // Ref mirror of opMode so buildCapabilities() reflects the LIVE mode synchronously (a follower's mode
569
663
  // selector must light up the instant it changes, before React flushes the setOpMode state update).
570
664
  const opModeRef = useRef(opMode);
665
+ const beforePlanRef = useRef(opMode === "plan" ? "gated" : opMode); // the mode /plan off returns to
571
666
  const [thinkMode, setThinkMode] = useState(settings.ui?.reasoning ?? "think"); // /think, /ultrathink badge; default "think" so the model's thoughts stream dim above the answer (settings.ui.reasoning / /think to change)
572
667
  const [elapsed, setElapsed] = useState(0); // live seconds since the current turn started (ticked by a
573
668
  const turnStartRef = useRef(0); // timer, so the clock advances even during a long reasoning
574
669
  // phase where no content tokens stream — that was the "timer stuck" bug (Ink only re-renders on deltas).
670
+ // The turn in flight (0: none). Its handlers act only while it is current (ui/turnScope.ts): after esc the tool in
671
+ // flight keeps running, and its batch report must not reach an idle shell or the next turn.
672
+ const turnSeqRef = useRef(0);
673
+ const turnIdRef = useRef(0);
575
674
  // Tool-approval bridge: when the permission policy returns "ask", session.approve(name,args) parks the
576
675
  // decision here and <ApprovalPrompt> renders it; the keystroke resolves the promise. "allow always"
577
676
  // adds the tool to a per-session set so it stops prompting. (No approver ⇒ policy fail-safe denies.)
@@ -607,6 +706,7 @@ function Root() {
607
706
  const [planExitPicker, setPlanExitPicker] = useState(null);
608
707
  const [artifactsPicker, setArtifactsPicker] = useState(null);
609
708
  const [sessionsPicker, setSessionsPicker] = useState(null);
709
+ const [finder, setFinder] = useState(null); // ctrl+g — the skills and tools finder
610
710
  const alwaysAllowRef = useRef(new Set());
611
711
  // Remembers the email a `/login <email>` sent a 6-digit code to, so the follow-up `/login <code>`
612
712
  // knows which address to verify against — the in-session twin of the shell's email-code login.
@@ -652,6 +752,7 @@ function Root() {
652
752
  const { auroraOnDemand } = await import("./services/preflight.js");
653
753
  auroraHookRef.current = auroraOnDemand(settings.endpoints.aurora, settings.services?.aurora, buildRouter, () => {
654
754
  push({ kind: "message", message: { id: nextId(), role: "system", content: "aurora is not loaded — loading it for this turn…" } });
755
+ setPhase("loading");
655
756
  });
656
757
  }
657
758
  return auroraHookRef.current(signal);
@@ -683,10 +784,12 @@ function Root() {
683
784
  moa: settings.moa,
684
785
  classifier: { mode: resolveMode(settings), endpoint: classifierConfig(settings).endpoint }, // the turn router (classifier/route.ts) // MOA proposers/aggregator config (MOA-DESIGN.md); absent = "/model moa" explains
685
786
  fastStart: settings.fastStart, // fast-model-vs-real-turn race (feature: fastStart, default OFF)
787
+ frontDoor: settings.frontDoor, // the gateway answers a message that needs no tools in the session's voice (engine/front-door.ts)
686
788
  features: settings.features, // feature flags — registers flag-gated tools (e.g. cloudAgents) only when on
687
789
  activeModel: settings.activeModel, // persisted /model choice, applied at startup
688
790
  contextPin: settings.contextPin, // persisted /context · ctrl+x choice (KODE_CONTEXT wins); unset = the served window
689
- permissions: fgPermissions, // owner's policy + computer tools forced to "ask" when enabled (else bypass)
791
+ permissions: START_POLICY.permissions, // the starting mode's policy (Autonomous, or Gated when the settings say so)
792
+ planReview: START_POLICY.planReview, // Autonomous: the owner reviews plans; risky steps run only if the approved plan lists them
690
793
  approve: approveFn, // renders the in-TUI approval prompt for any "ask" decision
691
794
  askUser, // registers the ask_user tool so the model can put a clarifying question to the owner
692
795
  decisionPoints: settings.decisionPoints, // a build turn's first change waits for the owner's choice (ask_user); false / KODE_DECISION_POINTS=0 = off
@@ -770,11 +873,12 @@ function Root() {
770
873
  const mgr = bgRef.current;
771
874
  if (!mgr)
772
875
  return "background manager not ready yet — retry in a moment";
876
+ const by = routeLabel(sessionRef.current?.currentModel() ?? ""); // the orchestrator stopped it — the owner's line says which model
773
877
  if (!id) {
774
- const stopped = mgr.requestStopAll();
878
+ const stopped = mgr.requestStopAll("orchestrator", by);
775
879
  return stopped.length ? `stopped ${stopped.length} sub-agent(s): ${stopped.join(", ")}.` : "no running or queued sub-agents to stop.";
776
880
  }
777
- return mgr.requestStop(id)
881
+ return mgr.requestStop(id, "orchestrator", by)
778
882
  ? `stopped ${id} — its partial findings (notes, sources read) arrive as its report at the start of your next turn.`
779
883
  : `${id} isn't a running or queued sub-agent (already finished, unknown, or never existed) — nothing to stop.`;
780
884
  },
@@ -789,11 +893,17 @@ function Root() {
789
893
  // background agent on aurora-code-1 looped 51 rounds while Cortana was the selected model).
790
894
  const subagentModel = () => subagentModelFor(settings, sessionRef.current?.currentModel());
791
895
  const bgRef = useRef(null);
896
+ // Every finished sub-agent's full report, by id (live or retired), for ctrl+o and `/agents <name> report` — the
897
+ // transcript shows one line per agent (ui/reportLine.ts). collapsedRef is ctrl+o's newest-first stack.
898
+ const reportsRef = useRef(new Map());
899
+ const collapsedRef = useRef([]);
900
+ const batchesRef = useRef(new Map()); // settled batches by entry id, for ctrl+o
792
901
  if (!bgRef.current) {
793
- bgRef.current = new BackgroundAgents((cwd, type, selectedModel) => {
902
+ bgRef.current = new BackgroundAgents((cwd, type, selectedModel, owner) => {
794
903
  const role = type ?? "generic";
795
904
  const model = selectedModel ?? subagentModel();
796
905
  const child = new Session({
906
+ owner, // its name labels the endpoint slot it holds, so a waiting lane can say who holds it
797
907
  systemPrompt: subagentSystemPrompt({ cwd: cwd ?? process.cwd(), ctxTokens: modelCtxFor(model, settings.models), type: role }),
798
908
  toolAllow: SUBAGENT_ROLES[role]?.tools,
799
909
  toolDeny: SUBAGENT_TOOL_DENY,
@@ -824,19 +934,38 @@ function Root() {
824
934
  return child;
825
935
  }, throttle(() => setBgAgents(bgRef.current.list()), 90), // coalesce per-update churn: a 3+ agent swarm streaming at once would otherwise redraw the whole frame dozens×/s (flicker). Final state lands via the immediate setBgAgents on the done path below.
826
936
  (agent, result) => {
827
- queueAgentReport(agent, result); // the MODEL gets the report at the start of the next turn (an idle session wakes for it); the screen line below is for the owner
828
- const changed = agent.written?.length ? `wrote ${agent.written.join(", ")}` : "no file writes recorded";
829
- setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⤷ ${agent.name ?? agent.id} (${agent.title ?? "sub-agent"}, ${agent.id}) done — ${changed}:\n${result.slice(0, 500)}` } }]);
937
+ queueAgentReport(agent, result); // the MODEL gets the report at the start of the next turn (an idle session wakes for it); the line below is for the owner
938
+ // One line per finished agent (TUI plan #4): who, how it ended and who stopped it, what it wrote — the full
939
+ // report is one key away (ctrl+o / `/agents <name> report`), never a 500-char dump of text written for the model.
940
+ const snap = { ...agent };
941
+ reportsRef.current.set(agent.id, { agent: snap, text: result });
942
+ collapsedRef.current = pushCollapsed(collapsedRef.current, { kind: "report", id: agent.id });
943
+ setEntries((prev) => [...prev, { kind: "report", id: nextId(), agent: snap }]);
944
+ remoteRef.current?.system(reportLine(snap, termCols()).line);
830
945
  setBgAgents(bgRef.current.list());
831
946
  }, subagentModel, // the model each child runs on, recorded at spawn for the panel (grandmaster §5)
832
- () => setTasks(getAgentTasks()), // a child's task_* call mutates the same session-wide task list this reads — refresh the plan pane live instead of leaving it frozen until the foreground itself touches a task_* tool
947
+ () => refreshTasks(), // a child's task_* call mutates the same session-wide task list this reads — refresh the plan pane live instead of leaving it frozen until the foreground itself touches a task_* tool
833
948
  (agent) => {
834
- queueAgentNotice(formatStuckNotice(agent));
949
+ queueAgentNotice(formatStuckNotice(agent), `${agent.name ?? agent.id}'s stuck notice`);
835
950
  setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `⚠ ${agent.name ?? agent.id} looks stuck: ${agent.stuck} — /agents ${agent.id} msg <steer> · /agents ${agent.id} stop` } }]);
951
+ }, (agent, round, how) => {
952
+ setEntries((prev) => [...prev, { kind: "message", message: { id: nextId(), role: "system", content: `→ ${agent.name ?? agent.id} took it ${how === "round" ? `at round ${round}` : "as a follow-up turn"}` } }]);
836
953
  });
837
954
  }
838
955
  const bg = bgRef.current;
956
+ // Talking to sub-agents (A3.4): "@Nova <text>" and the conversation switcher on the mode line. `openConv` is the
957
+ // conversation the composer types into — "main", or a sub-agent's id whose transcript pane is open above it.
958
+ const [openConv, setOpenConv] = useState(MAIN);
959
+ const [switcher, setSwitcher] = useState({ focused: false, sel: MAIN }); // sel: a conversation id (switcherKey)
960
+ const switcherRef = useRef(switcher);
961
+ switcherRef.current = switcher;
962
+ const openConvRef = useRef(openConv);
963
+ openConvRef.current = openConv;
964
+ const convsRef = useRef([]);
839
965
  const lastFallbackRef = useRef(undefined); // last gateway-fallback notice shown (once per change)
966
+ // Read-rate attribution (router/read-rates.ts): each round's read is credited to the model active at its onRoute, and a
967
+ // round another box served (gateway fallback) is never credited to the model that was asked for.
968
+ const rateFeed = useRef(new RateFeed()).current;
840
969
  const compactionWarnedRef = useRef(false); // a failed auto-compaction is said once, until one succeeds again
841
970
  const tokHist = useRef([]); // per-turn decode tok/s, for the /stats throughput sparkline
842
971
  const toolTotal = useRef(0); // cumulative tool calls this session, for /stats
@@ -845,6 +974,15 @@ function Root() {
845
974
  const lastNarrationRef = useRef(""); // the narration that preceded the current tool batch (liveText is cleared when the batch starts)
846
975
  const liveReasoning = useRef(""); // current completion's reasoning ("thinking"), shown dim + above the answer
847
976
  const liveTokRef = useRef(0); // per-token count accumulated by the stream; flushed to liveTok on the throttled tick
977
+ // Draft rows (TUI plan #8): tool calls the model is still writing, applied on the same throttled flush as the stream.
978
+ const draftRowsRef = useRef([]);
979
+ const draftPendingRef = useRef(new Map()); // raw drafts since the last frame, parsed once by the flush
980
+ const draftDirtyRef = useRef(false);
981
+ // The decode readout (TUI plan #13): the round's rate window, this session's per-model (depth, rate) history, the
982
+ // context depth this round pays for, and the early repetition check (the guard's own detector, run on the flush tick).
983
+ const decodeRef = useRef(createDecode());
984
+ const depthRef = useRef(undefined);
985
+ const transportRef = useRef(undefined);
848
986
  // Coalesced live-frame update: applies the accumulated stream refs in ONE render, rate-limited to ~15fps,
849
987
  // so a fast reply or a multi-agent swarm can't flicker the frame with a per-token redraw storm. Resolves
850
988
  // to setLive(null) when the refs are empty (turn/tool-batch end clears them), so a trailing tick after a
@@ -853,9 +991,32 @@ function Root() {
853
991
  const has = liveText.current.length > 0 || liveReasoning.current.length > 0;
854
992
  setLive(has ? { kind: "message", message: { id: "live", role: "assistant", content: liveText.current, reasoning: liveReasoning.current || undefined } } : null);
855
993
  setLiveTok(liveTokRef.current);
994
+ if (draftDirtyRef.current) {
995
+ draftDirtyRef.current = false;
996
+ draftRowsRef.current = applyDrafts(draftRowsRef.current, draftPendingRef.current);
997
+ setLiveTools(draftRowsRef.current);
998
+ }
999
+ // Every 2k new characters, never inside the SSE loop: does the stream's tail measurably repeat? A calm note while it
1000
+ // does — nothing is stopped here; the engine's own hard stop is untouched.
1001
+ const d = decodeRef.current;
1002
+ if (dueCheck(d, liveText.current.length + liveReasoning.current.length)) {
1003
+ const tails = [liveReasoning.current, liveText.current].map((t) => t.slice(-CHECK_TAIL));
1004
+ const hit = tails.find((t) => isRunawayRepetition(t));
1005
+ d.repeatingChars = hit ? hit.length : 0;
1006
+ }
856
1007
  }, 64)).current;
857
- const queued = useRef([]); // type-while-thinking messages, oldest first; drained as one turn when the turn ends
858
- const [queuedPreview, setQueuedPreview] = useState([]); // reactive mirror of the queue, shown above the composer so a type-while-thinking message is VISIBLE
1008
+ // What the owner typed while a turn runs, oldest first (ui/pending.ts): steers the engine takes at its next round
1009
+ // boundary, after-turn messages and staged commands the drain runs when the turn ends. The state mirror is shown above
1010
+ // the composer, so nothing typed mid-turn is invisible.
1011
+ const pendingRef = useRef([]);
1012
+ // After a stop (A3.5): the one-key next steps shown above the status rule while idle, and a cut reply kept for "show".
1013
+ const [nextSteps, setNextSteps] = useState(null);
1014
+ const stashedPartialRef = useRef("");
1015
+ // ctrl+y — "use what you have" (A3.3): what the phase line's offer is measured from. Plain refs, read on the existing
1016
+ // 500 ms clock; reset at every turn and round.
1017
+ const actRef = useRef({});
1018
+ const [pending, setPending] = useState([]);
1019
+ const setPendingItems = (items) => { pendingRef.current = items; setPending(items); };
859
1020
  const statusRef = useRef("idle");
860
1021
  // Remote-control host (SPEC/remote-session.md): non-null only while /remotecontrol is active. Every
861
1022
  // state mutation below also mirrors to it so attached followers see identical transcript/tool/activity.
@@ -864,10 +1025,13 @@ function Root() {
864
1025
  const rcConnectedRef = useRef(false);
865
1026
  rcConnectedRef.current = rcConnected; // a follower attached = someone is watching: the idle monitor reads this
866
1027
  const [rcActive, setRcActive] = useState(false); // remote-control ENABLED/listening (host up) — distinct from rcConnected (a follower is attached); the footer shows OFF(gray) vs ON-waiting(amber) vs LIVE(green)
867
- const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); if (s === "idle")
868
- touchWork(); };
1028
+ const setStat = (s) => { statusRef.current = s; setStatus(s); remoteRef.current?.setActivity(s); if (s === "idle") {
1029
+ touchWork();
1030
+ setTriage(undefined);
1031
+ } };
869
1032
  const push = (e) => setEntries((prev) => [...prev, e]);
870
1033
  const submitRef = useRef(() => { });
1034
+ const slashRef = useRef(async () => { }); // handleSlash, awaitable (the drain runs staged commands in order)
871
1035
  // AXE skills fetched/saved THIS session (name -> a best-effort description) — there's no persistent
872
1036
  // skill-loader/registry in this codebase to read from (skills are hub-fetched on demand by the
873
1037
  // skill_fetch/skill_save tools, see tools/registry.ts), so this is the closest real signal for
@@ -890,16 +1054,19 @@ function Root() {
890
1054
  skills: [...skillsRef.current.entries()].map(([name, description]) => ({ name, description })),
891
1055
  mcpServers: session.mcpServers().map((s) => ({ name: s.name, toolCount: s.tools.length, tools: s.tools })),
892
1056
  models: session.modelRegistry().map((m) => ({ id: m.id, label: shortName(m), ctx: m.ctx ?? 0, kind: m.kind })),
893
- mode: opModeRef.current, // live operating mode (Plan/Manual/Autonomous) — a follower can read + drive it via /mode
1057
+ mode: opModeRef.current, // live operating mode — a follower reads it; only /plan is follower-drivable (/mode stays owner-local)
894
1058
  cwd: process.cwd(),
895
1059
  model: session.currentModel(),
896
1060
  });
897
1061
  // The app-level teardown steps (they need these refs). Added once; the process-level ones (session end, shells, owned children,
898
1062
  // telemetry flush) are installed above. Order: stop sub-agents (aborts their in-flight requests — a child mid-send used to keep the
899
1063
  // event loop alive and freeze `operator` after /exit), drop the remote-control socket, then the Session (MCP servers, shell).
1064
+ // First of them: a turn still running when a signal ends the process (a closed terminal, a kill) is recorded — its flywheel
1065
+ // row and, when it looped, its lesson — synchronously, since a signal handler awaits nothing.
900
1066
  useEffect(() => {
901
1067
  if (teardown.names().includes("session"))
902
1068
  return;
1069
+ teardown.add("interrupted-turn", () => session.recordInterruptedTurnSync(), { order: 15 });
903
1070
  teardown.add("background-agents", () => bgRef.current?.dispose(), { order: 30 });
904
1071
  teardown.add("remote-control", () => { remoteRef.current?.stop(); remoteRef.current = null; }, { order: 40 });
905
1072
  teardown.add("session", () => session.shutdown(), { order: 50 });
@@ -948,7 +1115,10 @@ function Root() {
948
1115
  setBoot(ok ? "ready" : "down");
949
1116
  if (!ok) {
950
1117
  const a = reports.find((r) => r.name === "aurora");
951
- setBootDetail(a?.detail ?? `no response from ${settings.endpoints.aurora.base}`);
1118
+ // Another model (moa, cortana) failed on its own endpoint: name that one, not Aurora's.
1119
+ setBootDetail(session.currentModel() === DEFAULT_MODEL_ID
1120
+ ? a?.detail ?? `no response from ${session.healthTarget()}`
1121
+ : `${session.currentModel()}: no response from ${session.healthTarget()}`);
952
1122
  return;
953
1123
  }
954
1124
  // The primary's served window, learned now rather than after the first overflow — AFTER the lever, so the gateway's
@@ -1037,14 +1207,121 @@ function Root() {
1037
1207
  catch { /* auth is optional — never block the REPL */ }
1038
1208
  })();
1039
1209
  }, []);
1040
- const sendTurn = useCallback(async (text, opts) => {
1210
+ // ctrl+o / `/agents <name> report`: append the full report as a new entry (Static output is never rewritten).
1211
+ const expandReport = (id) => {
1212
+ const r = reportsRef.current.get(id);
1213
+ if (!r)
1214
+ return false;
1215
+ collapsedRef.current = dropCollapsed(collapsedRef.current, { kind: "report", id });
1216
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: `▾ ${r.agent.name ?? r.agent.id} · report\n\n${r.text.trim() || "(no output)"}` } });
1217
+ return true;
1218
+ };
1219
+ const onExpand = () => {
1220
+ const { item, rest } = popCollapsed(collapsedRef.current);
1221
+ if (!item) {
1222
+ sys("nothing to expand — ctrl+o appends the latest collapsed batch or sub-agent report");
1223
+ return;
1224
+ }
1225
+ collapsedRef.current = rest;
1226
+ if (item?.kind === "report")
1227
+ expandReport(item.id);
1228
+ else if (item?.kind === "batch") {
1229
+ const b = batchesRef.current.get(item.id);
1230
+ if (b)
1231
+ push({ kind: "toolBatch", id: nextId(), steps: b.steps, durationMs: b.durationMs, expanded: true });
1232
+ }
1233
+ };
1234
+ // A settled fold is one ToolStep row (repeat = N), pushed once — followers receive it once, as a tool step.
1235
+ const pushFold = (f) => {
1236
+ const step = foldStep(f, nextId());
1237
+ push({ kind: "tool", step });
1238
+ remoteRef.current?.toolStep(step);
1239
+ };
1240
+ const settleFoldNow = () => {
1241
+ const f = settleFold(foldRef.current);
1242
+ if (f)
1243
+ pushFold(f);
1244
+ setLiveFold(null);
1245
+ };
1246
+ // Clear the just-streamed interstitial narration BEFORE the batch runs. Keeping it in the live frame while N parallel
1247
+ // tools settle one-by-one re-renders a tall frame (narration + the N-row tool box) that Ink can mis-erase, stamping the
1248
+ // same "let me check…" line once per tool — the redundancy. The prose already showed while it streamed; during
1249
+ // execution we show the tool rows, not a re-rendered copy of it. (onToolBatch also clears these once the batch fully
1250
+ // settles.) BUT the model's THINKING before this batch ("why I'm running these tools") is worth keeping — so persist it
1251
+ // as a dim, SETTLED thought ABOVE the tool rows before clearing. Settled entries render once into static scrollback (no
1252
+ // live re-render), so this dodges the tall-live-frame mis-erase the clear guards against while surfacing the
1253
+ // inter-batch reasoning the owner would otherwise lose. Runs at the first draft and again when the batch starts.
1254
+ const settleNarration = () => {
1255
+ const preThought = liveReasoning.current.trim();
1256
+ if (preThought)
1257
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: "", reasoning: preThought } });
1258
+ // The model's words to the owner beside this batch ("sending Iris and Orion to…") settle the same way: they are the
1259
+ // before/during update, and clearing them left the owner with only the turn's last reply (10/31).
1260
+ const said = liveText.current.trim();
1261
+ if (said) {
1262
+ lastNarrationRef.current = said;
1263
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: said } });
1264
+ }
1265
+ liveText.current = "";
1266
+ liveReasoning.current = "";
1267
+ setLive(null);
1268
+ };
1269
+ // A new request is about to go out (the turn start, or the next round after a tool batch): its read starts fresh, and
1270
+ // so does the receipt flag — a tool round with no timings never reaches onCacheStats to clear it (review F13).
1271
+ const newRound = () => { roundStartRef.current = Date.now(); readRingRef.current = []; firstTokenRef.current = false; readReceiptRef.current = false; sentAtRef.current = null; gateQueueRef.current = null; noteRound(ledgerRef.current); decodeRound(decodeRef.current, liveTokRef.current); };
1272
+ // A round's stream ended: its average rate at its depth joins this model's history (the "earlier this session" figure).
1273
+ const endRoundDecode = () => {
1274
+ noteRoundRate(decodeRef.current, routeLabel(session.currentModel()), depthRef.current, liveTokRef.current, Date.now());
1275
+ decodeRef.current.roundStartAt = undefined;
1276
+ };
1277
+ // The request's first progress chunk: the server's own time_ms says how long it has been reading, so the rest of the
1278
+ // time since the request went out is time the server held it (busy, or loading the model) — settled as one receipt
1279
+ // when it is HOLD_RECEIPT_MS or more. A server that sends no time_ms can't be split, so it settles nothing.
1280
+ const serverHeld = (sample) => {
1281
+ const sent = sentAtRef.current;
1282
+ if (sent === null || sample.timeMs === undefined)
1283
+ return;
1284
+ sentAtRef.current = null; // once per request
1285
+ const held = sample.at - sent - sample.timeMs;
1286
+ noteWait(ledgerRef.current, Math.max(0, held));
1287
+ if (held < HOLD_RECEIPT_MS)
1288
+ return;
1289
+ sys(holdReceipt(routeLabel(session.currentModel()), held, termCols()));
1290
+ };
1291
+ // The round's first reasoning/content chunk: a read of RECEIPT_MIN_MS or more settles one dim receipt into scrollback
1292
+ // (and to followers) — what was read, how fast, what was cached, when the first token came.
1293
+ const firstToken = () => {
1294
+ if (firstTokenRef.current)
1295
+ return;
1296
+ firstTokenRef.current = true;
1297
+ const st = readStats(readRingRef.current, roundStartRef.current);
1298
+ expectRef.current = null;
1299
+ if (st) {
1300
+ noteRead(ledgerRef.current, { ms: st.elapsedMs, fresh: st.fresh, cache: st.cache });
1301
+ noteColdRead(coldReadsRef.current, routeLabel(session.currentModel()), st);
1302
+ depthRef.current = st.total;
1303
+ }
1304
+ if (!st || st.elapsedMs < RECEIPT_MIN_MS)
1305
+ return;
1306
+ readReceiptRef.current = true;
1307
+ sys(readReceipt(st, termCols(), { model: routeLabel(session.currentModel()), firstTokenMs: Date.now() - turnStartRef.current }));
1308
+ };
1309
+ const startTurn = useCallback(async (text, opts) => {
1310
+ setNextSteps(null); // a new turn retires the last stop's one-key strip
1311
+ const turn = ++turnSeqRef.current;
1312
+ turnIdRef.current = turn;
1041
1313
  // Finished background shell jobs and finished sub-agents are announced at the start of the next turn (job notices
1042
1314
  // are capped, never the full output; a sub-agent's report goes in full — it IS the deliverable). A wake turn has
1043
1315
  // no user text: the notices are the whole prompt.
1044
- const reports = drainAgentReports();
1045
- const notices = [drainJobNotices(), reports].filter(Boolean).join("\n\n");
1316
+ const { text: reports, owners } = drainAgentNotices();
1317
+ const jobs = drainJobNotices();
1318
+ const notices = [jobs, reports].filter(Boolean).join("\n\n");
1046
1319
  if (notices) {
1047
- const heads = notices.split("\n\n").map((n) => "⤷ " + n.split("\n")[0].replace(/^\[system notice\] /, "")).join("\n");
1320
+ // Sub-agent reports read as ONE hand-off line for the owner; the model still gets every report in full, unchanged.
1321
+ const heads = [
1322
+ ...(jobs ? jobs.split("\n\n").map((n) => "⤷ " + n.split("\n")[0].replace(/^\[system notice\] /, "")) : []),
1323
+ ...(owners.length ? [deliveredLine(owners, routeLabel(session.currentModel()), termCols())] : []),
1324
+ ].join("\n");
1048
1325
  push({ kind: "message", message: { id: nextId(), role: "system", content: heads } });
1049
1326
  remoteRef.current?.system(heads);
1050
1327
  }
@@ -1053,8 +1330,8 @@ function Root() {
1053
1330
  : "A background job finished (notice above). Continue the task if it matters; otherwise reply in one line.";
1054
1331
  const toSend = (notices ? notices + "\n\n" : "") + (opts?.wake ? wakePrompt : text);
1055
1332
  if (!opts?.wake) {
1056
- push({ kind: "message", message: { id: nextId(), role: "user", content: text } });
1057
- remoteRef.current?.userPrompt(text); // mirror to followers
1333
+ push({ kind: "message", message: { id: nextId(), role: "user", content: opts?.display ?? text } }); // a strip pick shows its label; the model gets the full text
1334
+ remoteRef.current?.userPrompt(opts?.display ?? text); // mirror to followers
1058
1335
  }
1059
1336
  remoteRef.current?.turnStart(); // allocate this turn's assistant id (stable stream→final)
1060
1337
  liveText.current = "";
@@ -1063,9 +1340,15 @@ function Root() {
1063
1340
  setLive(null);
1064
1341
  setLiveTok(0); // reset the live counter at the start of the turn
1065
1342
  turnStartRef.current = Date.now();
1343
+ wakeTurnRef.current = opts?.wake === true;
1066
1344
  touchedThisTurn.current = [];
1067
1345
  turnCachedRef.current = 0;
1346
+ rateFeed.startTurn();
1347
+ actRef.current = {};
1348
+ ledgerRef.current = createLedger();
1349
+ newRound();
1068
1350
  setElapsed(0);
1351
+ setPhase("waiting");
1069
1352
  setStat("thinking");
1070
1353
  try {
1071
1354
  // Options-vs-act gate (feature classifierGate, default OFF). When enabled, classify the turn via the
@@ -1080,14 +1363,22 @@ function Root() {
1080
1363
  });
1081
1364
  turnDirective = actAskGateDirective(true, gate) ?? undefined;
1082
1365
  }
1083
- const outcome = await session.send(expandFileMentions(snapshotEphemeralImages(toSend)), {
1366
+ const outcome = await session.send(expandFileMentions(snapshotEphemeralImages(toSend)), turnScoped({
1367
+ onTriage: setTriage,
1084
1368
  onRoute: (label, pct) => {
1369
+ // A different leg answers from here (a failover): its cache holds none of this conversation — arm the forecast.
1370
+ if (lastRouteRef.current !== null && lastRouteRef.current !== label)
1371
+ expectRef.current = forecast(coldReadsRef.current, label, session.requestTokens());
1372
+ lastRouteRef.current = label;
1373
+ transportRef.current = session.modelRegistry().find((m) => m.id === session.currentModel())?.transport;
1085
1374
  // The owner reads the model, not the leg that answered ("cortana", never "cortana@192.168.1.103:8112");
1086
1375
  // /endpoints still lists the legs and their health.
1087
1376
  const model = session.currentModel();
1088
1377
  setRoute(model);
1089
1378
  setCtxPct(pct);
1090
1379
  remoteRef.current?.setStatus(pct, model, session.sessionTokens());
1380
+ rateFeed.route(model === "moa" ? label : model); // a MoA round runs on the planner or the specialist: label names it
1381
+ actRef.current = { guard: actRef.current.guard }; // a new request: its stream and its read start over
1091
1382
  // GW-06 oracle seed (once, fire-and-forget): a fresh meter cold-starts at chars/4 (4.0) — measured
1092
1383
  // truth on agent traffic is ~2.15 (aurora-tier0/calibrate-token-meter.py), i.e. the gate fires LATE
1093
1384
  // for the first rounds. Seed ONE weight-1 observation from the endpoint's own tokenizer
@@ -1104,18 +1395,60 @@ function Root() {
1104
1395
  }
1105
1396
  }
1106
1397
  },
1107
- onPromptProgress: ({ processed, total }) => {
1108
- const label = `reading context ${Math.min(100, Math.round((processed / total) * 100))}%`;
1109
- if (label !== prefillRef.current) {
1110
- prefillRef.current = label;
1111
- setPrefill(label);
1398
+ onPromptProgress: ({ processed, total, cached, timeMs }) => {
1399
+ const sample = { processed, total, cache: cached, timeMs, at: Date.now() };
1400
+ if (compactRef.current) { // the summarizer's own read, while a compaction runs
1401
+ compactRef.current.ring = pushSample(compactRef.current.ring, sample);
1402
+ setReadTick((n) => n + 1);
1403
+ return;
1112
1404
  }
1405
+ actRef.current.readingSince ??= Date.now();
1406
+ readRingRef.current = pushSample(readRingRef.current, sample);
1407
+ expectRef.current = null; // the measured read line replaces the forecast
1408
+ serverHeld(sample);
1409
+ setPhase("reading");
1410
+ setReadTick((n) => n + 1);
1113
1411
  },
1114
- onDelta: (chunk) => {
1115
- if (prefillRef.current) {
1116
- prefillRef.current = "";
1117
- setPrefill("");
1412
+ onQueued: (q) => { gateQueueRef.current = q; queuedAtRef.current = Date.now(); setPhase("queued"); },
1413
+ onSent: () => {
1414
+ if (queuedAtRef.current !== null) {
1415
+ noteWait(ledgerRef.current, Date.now() - queuedAtRef.current);
1416
+ queuedAtRef.current = null;
1118
1417
  }
1418
+ gateQueueRef.current = null;
1419
+ sentAtRef.current = Date.now();
1420
+ if (!compactRef.current)
1421
+ setPhase("sent");
1422
+ },
1423
+ onCompactionStart: ({ before }) => {
1424
+ compactRef.current = { before, startedAt: Date.now(), ring: [], wrote: 0 };
1425
+ setStepLabel("compacting context");
1426
+ setPhase("compacting");
1427
+ setStat("compacting");
1428
+ },
1429
+ onCompactionWrite: (n) => { if (compactRef.current)
1430
+ compactRef.current.wrote = n; }, // drawn on the 500 ms clock, not per delta
1431
+ onCompactionEnd: ({ before, after }) => {
1432
+ const c = compactRef.current;
1433
+ compactRef.current = null;
1434
+ if (c)
1435
+ noteCompaction(ledgerRef.current, Date.now() - c.startedAt);
1436
+ if (c && after < before) {
1437
+ const f = forecast(coldReadsRef.current, routeLabel(session.currentModel()), after); // after a compaction the summary is a new prefix
1438
+ expectRef.current = f;
1439
+ sys(compactReceipt(before, after, Date.now() - c.startedAt, termCols(), forecastTail(f)));
1440
+ }
1441
+ newRound();
1442
+ setPhase("waiting");
1443
+ setStat("thinking");
1444
+ },
1445
+ onDelta: (chunk) => {
1446
+ firstToken();
1447
+ noteGenStart(ledgerRef.current, Date.now(), true);
1448
+ noteDecode(decodeRef.current, liveTokRef.current + 1, Date.now());
1449
+ setPhase("writing");
1450
+ if (actRef.current.readingSince !== undefined || actRef.current.reasoningSince !== undefined)
1451
+ actRef.current = { guard: actRef.current.guard }; // an answer is coming
1119
1452
  liveText.current += chunk;
1120
1453
  liveTokRef.current += 1; // ≈1 token per streamed delta; flushed to the counter on the throttled tick
1121
1454
  setStat("streaming");
@@ -1126,10 +1459,12 @@ function Root() {
1126
1459
  // Thinking streams before/between content — accumulate it and show it dimmed in the live entry
1127
1460
  // (renderEntry renders `reasoning` above the answer, dimColor). Distinct from onDelta so the
1128
1461
  // thought process reads at lower opacity than the real answer, per the requested look.
1129
- if (prefillRef.current) {
1130
- prefillRef.current = "";
1131
- setPrefill("");
1132
- }
1462
+ firstToken();
1463
+ noteGenStart(ledgerRef.current, Date.now(), false);
1464
+ noteDecode(decodeRef.current, liveTokRef.current + 1, Date.now());
1465
+ setPhase("thinking");
1466
+ if (actRef.current.reasoningSince === undefined)
1467
+ actRef.current = { guard: actRef.current.guard, reasoningSince: Date.now() }; // the read ended
1133
1468
  liveReasoning.current += chunk;
1134
1469
  liveTokRef.current += 1; // reasoning tokens ARE generated tokens — count them so the live
1135
1470
  // counter + tok/s keep moving during a long thinking phase (they were frozen before content).
@@ -1137,6 +1472,38 @@ function Root() {
1137
1472
  flushLive(); // coalesced (~15fps) — throttled so a long thinking stream doesn't flicker the frame
1138
1473
  remoteRef.current?.streamAssistant(liveText.current, liveReasoning.current || undefined);
1139
1474
  },
1475
+ // Enter mid-turn: every steer typed so far goes in as ONE owner message before the next model call. Each settles
1476
+ // as the owner's row at the moment the engine took it, tagged with the round it reached — measured, not guessed.
1477
+ ownerSteer: (round) => {
1478
+ const { steers, rest } = takeSteers(pendingRef.current);
1479
+ if (!steers.length)
1480
+ return undefined;
1481
+ setPendingItems(rest);
1482
+ for (const t of steers) {
1483
+ push({ kind: "message", message: { id: nextId(), role: "user", content: t, tag: `↳ steered in · before round ${round}` } });
1484
+ remoteRef.current?.userPrompt(t);
1485
+ }
1486
+ return expandFileMentions(snapshotEphemeralImages(steers.join("\n\n")));
1487
+ },
1488
+ // ctrl+y took effect: what was streaming settles (dim — it is in the model's context now), then the owner's ask with
1489
+ // the moment it was pressed. A typed steer that became the ask already settled as its own row.
1490
+ onOwnerAct: ({ steered }) => {
1491
+ const kept = liveReasoning.current.trim();
1492
+ if (kept || liveText.current.trim())
1493
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: liveText.current.trim(), reasoning: kept || undefined } });
1494
+ liveText.current = "";
1495
+ liveReasoning.current = "";
1496
+ setLive(null);
1497
+ actRef.current = {};
1498
+ const at = `↳ ctrl+y at ${fmtDuration((Date.now() - turnStartRef.current) / 1000)}`;
1499
+ if (!steered) {
1500
+ push({ kind: "message", message: { id: nextId(), role: "user", content: OWNER_ACT_MESSAGE, tag: at } });
1501
+ remoteRef.current?.userPrompt(OWNER_ACT_MESSAGE);
1502
+ }
1503
+ else
1504
+ sys(`${at} · it answers from what it has, think-off`);
1505
+ setStat("thinking");
1506
+ },
1140
1507
  onTokens: (t) => { liveTokRef.current = t; setLiveTok(t); }, // authoritative per-round count — corrects the ≈1/delta animation to
1141
1508
  // the real llama.cpp total (which includes tool-call-arg + reasoning tokens the delta stream misses)
1142
1509
  onCacheStats: ({ promptTokens, cached, promptMs }) => {
@@ -1144,14 +1511,20 @@ function Root() {
1144
1511
  // tokens with ZERO reuse is a cache bust — name it, with its measured cost, instead of letting
1145
1512
  // the user watch "0 tokens for N seconds" and guess (the v0.1.140-143 mystery, now answerable).
1146
1513
  cacheReqsRef.current += 1;
1514
+ noteRead(ledgerRef.current, { ms: promptMs ?? 0, fresh: promptTokens, cache: cached ?? NaN }); // a round with no progress chunks still counts its read (a no-op when they were counted)
1515
+ if (!readRingRef.current.length)
1516
+ depthRef.current = promptTokens + (cached ?? 0); // the context this round paid for
1147
1517
  turnCachedRef.current += cached ?? 0; // gateway rounds report unknown (undefined) reuse — contribute 0, never NaN the turn tally
1148
1518
  const notice = cacheBustNotice({ requestIndex: cacheReqsRef.current, promptTokens, cached, promptMs });
1149
- if (notice)
1150
- sys("⚠ " + notice);
1519
+ if (notice && !readReceiptRef.current)
1520
+ sys("⚠ " + notice); // a read receipt already said this round's cost
1521
+ readReceiptRef.current = false;
1522
+ rateFeed.read(promptTokens, promptMs); // ≥2K-token reads only, never a fallback-served round (read-rates.ts)
1151
1523
  },
1152
1524
  onServed: ({ backend, fallbackFrom }) => {
1153
1525
  // The gateway answered from a fallback box: the selected model is down and another model is replying under
1154
1526
  // its name (10/30: a parked Cortana answered by Aurora fooled every check). Say so once per change.
1527
+ rateFeed.servedByFallback(); // another box served this round: no rate sample from it
1155
1528
  const key = `${fallbackFrom}->${backend ?? "?"}`;
1156
1529
  if (lastFallbackRef.current === key)
1157
1530
  return;
@@ -1168,6 +1541,16 @@ function Root() {
1168
1541
  compactionWarnedRef.current = true;
1169
1542
  sys(`⚠ auto-compaction failed (${e.skipped === "empty_summary" ? "the summarizer returned nothing" : "the summarizer errored"}) — context stays at ~${Math.round(e.after / 1000)}K tokens; /compact retries, /new starts fresh`);
1170
1543
  },
1544
+ onLoopCompaction: (e) => {
1545
+ sys(`↻ loop reset ${e.attempt}: ${e.nudges} loop warnings went unheeded — ` +
1546
+ (e.replaced ? `this turn's ${e.replaced} messages became one digest, ~${Math.round(e.before / 1000)}K → ~${Math.round(e.after / 1000)}K tokens` : "nothing to replace") +
1547
+ `; continuing from it (${e.files} files, each with its latest output — not to be re-read)`);
1548
+ },
1549
+ onLoopRecovery: (e) => {
1550
+ const calls = e.repeated.map((c) => c.call).slice(0, 2).join(", ") + (e.repeated.length > 2 ? ", …" : "");
1551
+ sys(`↻ loop recovery ${e.attempt}/${e.max}: ${calls} came back refused as repeats — ` +
1552
+ `${e.rounds === 1 ? "that round" : `those ${e.rounds} rounds`} became one note of their results; reviewing and continuing`);
1553
+ },
1171
1554
  onAutoContinue: (round) => {
1172
1555
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: `↻ still working — auto-continuing past ${round} tool rounds`, reasoning: "" } });
1173
1556
  },
@@ -1175,39 +1558,50 @@ function Root() {
1175
1558
  // A recovery reads as the agent working it out, NOT an error — show the calm "adjusting"
1176
1559
  // animation instead of surfacing a raw http 400/5xx. The next delta/tool flips status back.
1177
1560
  setStepLabel(kind === "context_exceeded" ? "adjusting context" : kind === "unavailable" ? "reconnecting" : "recovering");
1561
+ if (draftRowsRef.current.length || draftPendingRef.current.size) {
1562
+ draftRowsRef.current = [];
1563
+ draftPendingRef.current.clear();
1564
+ draftDirtyRef.current = false;
1565
+ setLiveTools([]);
1566
+ } // drafts that will never dispatch
1567
+ setPhase("recovering");
1178
1568
  setStat("recovering");
1179
1569
  },
1570
+ onToolDraft: (d) => {
1571
+ // A tool call's arguments are streaming: its row appears now and its size climbs (TUI plan #8). The narration
1572
+ // above it settles at the FIRST draft, the same way it used to settle when the batch started.
1573
+ if (!draftRowsRef.current.length && !draftPendingRef.current.size)
1574
+ settleNarration();
1575
+ firstToken();
1576
+ noteGenStart(ledgerRef.current, Date.now(), true);
1577
+ bufferDraft(draftPendingRef.current, d, Date.now()); // parsed on the next frame, not on every piece (review F4)
1578
+ draftDirtyRef.current = true;
1579
+ liveTokRef.current += 1; // ≈1 token per streamed argument delta; onTokens corrects it at the round's end
1580
+ noteDecode(decodeRef.current, liveTokRef.current, Date.now());
1581
+ setPhase("drafting");
1582
+ flushLive();
1583
+ },
1180
1584
  onToolStart: (calls) => {
1181
- // Clear the just-streamed interstitial narration BEFORE the batch runs. Keeping it in the live
1182
- // frame while N parallel tools settle one-by-one re-renders a tall frame (narration + the N-row
1183
- // tool box) that Ink can mis-erase, stamping the same "let me check…" line once per tool — the
1184
- // redundancy. The prose already showed while it streamed; during execution we show the tool rows,
1185
- // not a re-rendered copy of it. (onToolBatch also clears these once the batch fully settles.)
1186
- // BUT the model's THINKING before this batch ("why I'm running these tools") is worth keeping — so
1187
- // persist it as a dim, SETTLED thought ABOVE the tool rows before clearing. Settled entries render
1188
- // once into static scrollback (no live re-render), so this dodges the tall-live-frame mis-erase the
1189
- // clear guards against while surfacing the inter-batch reasoning the owner would otherwise lose.
1190
- const preThought = liveReasoning.current.trim();
1191
- if (preThought)
1192
- push({ kind: "message", message: { id: nextId(), role: "assistant", content: "", reasoning: preThought } });
1193
- // The model's words to the owner beside this batch ("sending Iris and Orion to…") settle the same way: they
1194
- // are the before/during update, and clearing them left the owner with only the turn's last reply (10/31).
1195
- const said = liveText.current.trim();
1196
- if (said) {
1197
- lastNarrationRef.current = said;
1198
- push({ kind: "message", message: { id: nextId(), role: "assistant", content: said } });
1199
- }
1200
- liveText.current = "";
1201
- liveReasoning.current = "";
1202
- setLive(null);
1585
+ settleNarration();
1586
+ actRef.current = { guard: actRef.current.guard }; // it acted: no long stream to cut
1203
1587
  setStepLabel(calls.map((c) => c.name).join(", "));
1588
+ noteGenEnd(ledgerRef.current, Date.now());
1589
+ endRoundDecode();
1204
1590
  setStat("executing");
1205
- setLiveTools(seedLiveTools(calls));
1591
+ setPhase("tools");
1592
+ // Same ids as the drafts, so each row flips in place to waiting its turn; onToolCallStart starts its clock.
1593
+ setLiveTools(seedLiveTools(calls, applyDrafts(draftRowsRef.current, draftPendingRef.current)));
1594
+ draftRowsRef.current = [];
1595
+ draftDirtyRef.current = false;
1206
1596
  },
1207
- onToolResult: (id, result) => {
1208
- setLiveTools((rows) => settleLiveTool(rows, id, result));
1597
+ onToolCallStart: (id) => {
1598
+ setLiveTools((rows) => startLiveTool(rows, id));
1599
+ },
1600
+ onToolResult: (id, result, _batchId, refused) => {
1601
+ setLiveTools((rows) => settleLiveTool(rows, id, result, Date.now(), refused));
1209
1602
  },
1210
1603
  onToolBatch: (events, durationMs) => {
1604
+ actRef.current = { guard: guardDetail(events) }; // the loop guard refusing a repeat offers ctrl+y until a batch runs clean
1211
1605
  // Live progress journal: after every round that changed something, the request, the task list, the files
1212
1606
  // touched and the last narration are rewritten at the end of this directory's handoff file — a cutoff
1213
1607
  // (killed session, wedged model, empty reply) loses nothing the next session cannot resume from.
@@ -1215,19 +1609,21 @@ function Root() {
1215
1609
  touchedThisTurn.current.push(...touchedPaths(events));
1216
1610
  recordLiveProgress(process.env.KODE_HANDOFF_FILE, { session: SESSION_ID, cwd: process.cwd(), request: text, tasks: getAgentTasks(), touched: touchedThisTurn.current, narration: lastNarrationRef.current });
1217
1611
  }
1612
+ // A round that repeats the last one folds into the live counting line; anything else first settles the fold it ends.
1613
+ const fed = feedFold(foldRef.current, events.map((ev) => ({ name: ev.name, args: ev.args, result: ev.result, refused: ev.refused })), Date.now());
1614
+ if (fed.action === "push" && fed.settled)
1615
+ pushFold(fed.settled);
1616
+ setLiveFold(fed.action === "fold" && foldRef.current.fold ? foldStep(foldRef.current.fold, "fold-live") : null);
1218
1617
  const steps = [];
1219
1618
  for (const ev of events) {
1220
- const step = {
1221
- id: nextId(), name: ev.name, args: ev.args,
1222
- status: isErrorResult(ev.result) ? "error" : "done",
1223
- durationMs, summary: resultPreview(ev.result),
1224
- };
1619
+ const step = { id: nextId(), name: ev.name, args: ev.args, durationMs, ...settledFields(ev.result, ev.refused) };
1225
1620
  steps.push(step);
1226
- remoteRef.current?.toolStep(step);
1621
+ if (fed.action === "push")
1622
+ remoteRef.current?.toolStep(step);
1227
1623
  // Track skills this session has actually pulled in, for RemoteCapabilities.skills (see
1228
1624
  // skillsRef above) — the description is synthetic (this codebase has no skill metadata to
1229
1625
  // read a real one from), not sourced from the fetched skillmd content.
1230
- if (!isErrorResult(ev.result)) {
1626
+ if (!isErrorResult(ev.result, ev.refused)) {
1231
1627
  if (ev.name === "skill_fetch") {
1232
1628
  const slug = String(ev.args?.slug ?? "").trim();
1233
1629
  if (slug)
@@ -1242,20 +1638,53 @@ function Root() {
1242
1638
  }
1243
1639
  // >1 tool in one round ran CONCURRENTLY (executeParallel) — box them so the parallelism reads at
1244
1640
  // a glance instead of as a flat sequential list; a lone call stays a plain row.
1245
- if (steps.length > 1)
1246
- push({ kind: "toolBatch", id: nextId(), steps, durationMs });
1641
+ if (fed.action === "fold") { /* counted on the live fold line; settles as one row */ }
1642
+ else if (steps.length > 1) {
1643
+ // One chip line (TUI plan #12); ctrl+o appends the full box from here.
1644
+ const id = nextId();
1645
+ batchesRef.current.set(id, { steps, durationMs });
1646
+ if (batchesRef.current.size > 50)
1647
+ batchesRef.current.delete(batchesRef.current.keys().next().value);
1648
+ collapsedRef.current = pushCollapsed(collapsedRef.current, { kind: "batch", id });
1649
+ push({ kind: "toolBatch", id, steps, durationMs });
1650
+ }
1247
1651
  else if (steps.length === 1)
1248
1652
  push({ kind: "tool", step: steps[0] });
1249
1653
  liveText.current = "";
1250
1654
  liveReasoning.current = "";
1251
1655
  setLive(null);
1656
+ // The status leaves "executing" BEFORE the rows clear: Ink renders each setState on its own here, and the other
1657
+ // order drew one frame of the bare "⠙ name…" spinner between the settled rows and the next request (live 11/04).
1658
+ setStat("thinking");
1252
1659
  setLiveTools([]); // batch settled — the per-call rows are now in the settled transcript above
1660
+ delegateRef.current = null;
1661
+ setDelegate(null);
1662
+ draftRowsRef.current = [];
1663
+ draftPendingRef.current.clear();
1664
+ draftDirtyRef.current = false; // a round whose calls were all refused never reached onToolStart
1253
1665
  toolTotal.current += events.length; // session tool-call tally for /stats
1254
1666
  if (events.some((ev) => ev.name.startsWith("task_")))
1255
- setTasks(getAgentTasks()); // refresh the plan pane
1256
- setStat("thinking");
1667
+ refreshTasks(); // refresh the plan pane (and settle its receipt)
1668
+ noteGenEnd(ledgerRef.current, Date.now()); // a fully blocked round never reached onToolStart
1669
+ endRoundDecode();
1670
+ noteTools(ledgerRef.current, durationMs);
1671
+ newRound();
1672
+ setPhase("waiting");
1257
1673
  },
1258
- }, turnDirective, { wake: opts?.wake === true });
1674
+ }, turn, () => turnIdRef.current), turnDirective, { wake: opts?.wake === true, thinkOff: opts?.thinkOff === true });
1675
+ settleFoldNow(); // a fold still counting ends with the turn, above the answer
1676
+ // Close the ledger: the round in flight stops generating; an interrupted read counts up to now.
1677
+ const ledger = ledgerRef.current;
1678
+ noteGenEnd(ledger, Date.now());
1679
+ endRoundDecode();
1680
+ if (outcome.interrupted && phaseRef.current === "reading") {
1681
+ const st = readStats(readRingRef.current, roundStartRef.current);
1682
+ if (st)
1683
+ noteRead(ledger, { ms: st.elapsedMs, fresh: st.done, cache: st.cache });
1684
+ }
1685
+ const wall = outcome.durationMs ?? Date.now() - turnStartRef.current;
1686
+ const timeParts = ledgerParts(ledger, wall);
1687
+ const lastRound = outcome.stopReason === "repetition" ? { chars: liveText.current.length + liveReasoning.current.length, ms: Date.now() - roundStartRef.current } : undefined;
1259
1688
  // A completed (not interrupted) turn while still in plan mode counts as "a plan was proposed" —
1260
1689
  // arms the exit-time Approve & run picker (see applyMode).
1261
1690
  // The turn ended normally: settle the live progress block so the next session is not told to resume a finished turn.
@@ -1264,8 +1693,18 @@ function Root() {
1264
1693
  if (!outcome.interrupted && session.inPlanMode())
1265
1694
  planProposedRef.current = true;
1266
1695
  if (outcome.interrupted) {
1267
- push({ kind: "message", message: { id: nextId(), role: "assistant", content: "⎋ interrupted — output above kept" } });
1268
- remoteRef.current?.system("⎋ interrupted — output above kept");
1696
+ // What the owner was watching settles (dim) BEFORE the finally clears the stream refs — the round it belonged to
1697
+ // is dropped by the engine, so it is screen-only, and says so. Then one line of next steps, one key each (A3.5).
1698
+ const partial = settledPartial(liveText.current, liveReasoning.current);
1699
+ if (partial) {
1700
+ push({ kind: "message", message: { id: nextId(), role: "assistant", ...partial.entry } });
1701
+ push({ kind: "message", message: { id: nextId(), role: "system", content: partial.note } });
1702
+ }
1703
+ // Where the time went, the read in flight included — an esc no longer throws the numbers away.
1704
+ const line = interruptedLine(wall, timeParts, ledger, liveTokRef.current, termCols());
1705
+ push({ kind: "message", message: { id: nextId(), role: "assistant", content: line } });
1706
+ remoteRef.current?.system(line);
1707
+ setNextSteps(interruptSteps({ reasoning: liveReasoning.current, compact: session.compactionEstimate() }));
1269
1708
  }
1270
1709
  else if (outcome.content.trim()) {
1271
1710
  // Keep the final answer's thinking (dim, above the answer), plus a dim note when generation was
@@ -1278,6 +1717,12 @@ function Root() {
1278
1717
  const shown = outcome.display ?? outcome.content; // an engine stop reads as a question, not a bracketed note
1279
1718
  push({ kind: "message", message: { id: nextId(), role: "assistant", content: shown, reasoning } });
1280
1719
  remoteRef.current?.finalAssistant(shown, reasoning);
1720
+ // An engine stop's question is answered with one key: its own options, verbatim. A reply cut by the repetition
1721
+ // check is stashed for "show what it had" — on screen only; the engine keeps it out of history by design.
1722
+ if (outcome.stopKind) {
1723
+ stashedPartialRef.current = outcome.stopKind === "repetition" ? liveText.current.trim() : "";
1724
+ setNextSteps(engineStopSteps(outcome.stopKind, { partialChars: stashedPartialRef.current.length, compact: session.compactionEstimate() }));
1725
+ }
1281
1726
  }
1282
1727
  // Surface the turn's real metrics: wall time · output tokens @ decode tok/s · prefill size. The
1283
1728
  // prefill number is the key one on a local model — it's where "0 tokens for N seconds" goes (the
@@ -1289,15 +1734,21 @@ function Root() {
1289
1734
  const tps = outcome.genMs && outcome.genMs > 0 ? Math.round(tok / (outcome.genMs / 1000)) : 0;
1290
1735
  if (tps > 0)
1291
1736
  tokHist.current = [...tokHist.current, tps].slice(-40); // keep the last 40 turns' throughput
1737
+ if (session.currentModel() !== "moa")
1738
+ rateFeed.decode(session.currentModel(), outcome.tokens, outcome.genMs);
1292
1739
  const prefill = outcome.promptTokens ?? 0;
1293
1740
  const parts = [fmtDuration(secs), `${fmtTokens(tok).replace(/ tokens?$/, " tok")}${tps ? ` @ ${tps} tok/s` : ""}`];
1294
1741
  if (prefill)
1295
1742
  parts.push(`${fmtTokens(prefill).replace(/ tokens?$/, "")} prefill`);
1296
1743
  setMetrics(`(${parts.join(" · ")})`);
1297
- // Enterprise summary card (SPEC §6) — a compact end-of-turn card in the transcript, but only for a
1298
- // turn that actually did work (used tools). A pure Q&A turn just shows its answer, no card noise.
1299
- if (outcome.toolCalls > 0) {
1300
- push({ kind: "summary", summary: { id: nextId(), durationMs, tokens: tok, tps: tps || undefined, prefill: prefill || undefined, rounds: outcome.rounds, tools: outcome.toolCalls, unverified: outcome.unverified } });
1744
+ // Enterprise summary card (SPEC §6) — a compact end-of-turn card for a turn that did work (used tools) or ran 30 s
1745
+ // or more, tools or not; a turn that long also gets its measured time ledger (TUI plan #6). A short pure Q&A turn
1746
+ // just shows its answer, no card noise.
1747
+ const long = durationMs >= LEDGER_MIN_MS;
1748
+ if (outcome.toolCalls > 0 || long) {
1749
+ push({ kind: "summary", summary: { id: nextId(), durationMs, tokens: tok, tps: tps || undefined, prefill: prefill || undefined, rounds: outcome.rounds, tools: outcome.toolCalls, unverified: outcome.unverified,
1750
+ ...(long ? { time: { ...timeParts, fresh: ledger.fresh, cached: ledger.cached, coldReads: ledger.coldReads, coldTokens: ledger.coldTokens, wrote: ledger.wrote } } : {}),
1751
+ ...(lastRound ? { lastRound } : {}) } });
1301
1752
  }
1302
1753
  // Feed the same numbers to the frozen event stream (dashboard + mobile). Gated on telemetry.enabled.
1303
1754
  if (emitTelemetry) {
@@ -1314,15 +1765,26 @@ function Root() {
1314
1765
  }
1315
1766
  finally {
1316
1767
  tracker.noteTurn();
1768
+ turnIdRef.current = 0; // a report of this turn that lands from here on (a tool still running after esc) is dropped
1317
1769
  // Clear BOTH stream refs: flushLive's trailing (throttled) tick fires after this setLive(null) and re-shows
1318
1770
  // whatever is left — a reasoning ref left full put the whole thought back under the settled answer (10/30, MoA).
1319
1771
  liveText.current = "";
1320
1772
  liveReasoning.current = "";
1321
1773
  setLive(null);
1322
1774
  setLiveTools([]); // an interrupt/error mid-batch must not leave stale "running" rows on screen
1775
+ delegateRef.current = null;
1776
+ setDelegate(null);
1777
+ draftRowsRef.current = [];
1778
+ draftPendingRef.current.clear();
1779
+ draftDirtyRef.current = false;
1780
+ settleFoldNow();
1781
+ compactRef.current = null;
1782
+ gateQueueRef.current = null;
1783
+ queuedAtRef.current = null;
1784
+ sentAtRef.current = null;
1785
+ lastTurnEndRef.current = Date.now();
1323
1786
  setCtxPct(session.ctxPct());
1324
- prefillRef.current = "";
1325
- setPrefill("");
1787
+ setPhase(null);
1326
1788
  setStat("idle");
1327
1789
  const live = bg.list().filter((a) => a.status === "working" || a.status === "queued");
1328
1790
  if (live.length)
@@ -1336,28 +1798,30 @@ function Root() {
1336
1798
  // Re-check capabilities after every turn: MCP discovery (first-turn only) may have just landed,
1337
1799
  // and any skill_fetch/skill_save this turn updated skillsRef above. A no-op diff never hits the wire.
1338
1800
  remoteRef.current?.setCapabilities(buildCapabilities());
1339
- const q = queued.current.join("\n");
1340
- queued.current = [];
1341
- setQueuedPreview([]);
1342
- if (q)
1343
- submitRef.current(q);
1344
- else
1345
- wakeIfIdleRef.current();
1801
+ drainRef.current();
1346
1802
  }
1347
1803
  }, []);
1348
- // A background shell job finished (wake mode) or a sub-agent reported: start a turn so Operator reacts without
1349
- // being polled. Only when idle with nothing typed-ahead; otherwise the notice rides along on the next turn. Jobs
1350
- // or reports ending together coalesce. A sub-agent report ALWAYS wakes — delivering it is the spawn contract
1351
- // ("its report resumes this conversation"); only shell jobs honor settings.background.jobNotices.
1804
+ // The turn ended (or a manual /compact did): run what waited for it (ui/turnFlow.ts) — staged commands one by one,
1805
+ // each on its own, then one text turn with the steers the turn never reached and the after-turn messages. Nothing typed
1806
+ // is lost, and a command is never joined into text (isSlashCommand refuses a multi-line input, so it used to reach the
1807
+ // model). A background shell job finished (wake mode) or a sub-agent reported: a turn starts so Operator reacts without
1808
+ // being polled — only when idle with nothing typed-ahead; otherwise the notice rides along on the next turn. Jobs or
1809
+ // reports ending together coalesce. A sub-agent report ALWAYS wakes — delivering it is the spawn contract ("its report
1810
+ // resumes this conversation"); only shell jobs honor settings.background.jobNotices.
1811
+ const flow = useMemo(() => createTurnFlow({
1812
+ idle: () => statusRef.current === "idle",
1813
+ pending: () => pendingRef.current,
1814
+ setPending: (items) => setPendingItems(items),
1815
+ command: (cmd) => slashRef.current(cmd),
1816
+ submit: (text) => submitRef.current(text),
1817
+ start: (text, opts) => { void startTurn(text, opts); },
1818
+ wakeDue: () => (getJobNoticeMode() === "wake" && pendingJobNotices() > 0) || pendingAgentReports() > 0,
1819
+ }), []);
1820
+ const sendTurn = useCallback((text, opts) => flow.send(text, opts), [flow]);
1821
+ const drainRef = useRef(() => { });
1822
+ drainRef.current = flow.drain;
1352
1823
  const wakeIfIdleRef = useRef(() => { });
1353
- wakeIfIdleRef.current = () => {
1354
- const jobs = getJobNoticeMode() === "wake" && pendingJobNotices() > 0;
1355
- if (!jobs && pendingAgentReports() === 0)
1356
- return;
1357
- if (statusRef.current !== "idle" || queued.current.length)
1358
- return;
1359
- void sendTurn("", { wake: true });
1360
- };
1824
+ wakeIfIdleRef.current = flow.wake;
1361
1825
  useEffect(() => {
1362
1826
  let timer;
1363
1827
  const wakeSoon = () => { if (timer)
@@ -1369,13 +1833,33 @@ function Root() {
1369
1833
  wakeSoon();
1370
1834
  });
1371
1835
  const offReports = onAgentReport(wakeSoon);
1372
- return () => { off(); offReports(); if (timer)
1836
+ const showDelegate = throttle(() => setDelegate(delegateRef.current), 90);
1837
+ const offDelegate = onDelegateProgress((p) => { delegateRef.current = p.done ? null : p; showDelegate(); });
1838
+ return () => { off(); offReports(); offDelegate(); if (timer)
1373
1839
  clearTimeout(timer); };
1374
1840
  }, []);
1375
1841
  const sys = useCallback((text) => {
1376
1842
  push({ kind: "message", message: { id: nextId(), role: "system", content: text } });
1377
1843
  remoteRef.current?.system(text);
1378
1844
  }, []);
1845
+ // A model turn is running (compacting is the one non-idle state with no next round to apply a setting to).
1846
+ const turnRunning = () => statusRef.current !== "idle" && statusRef.current !== "compacting";
1847
+ // /think rides in the system prompt (session.ts sysWithThink), so the turn after a toggle re-reads everything past the
1848
+ // base system text. Say so with the measured price; mid-turn the running turn changes per request only (the
1849
+ // enable_thinking getter), its prompt untouched. No measured read rate → the token count alone. Under 80 columns
1850
+ // the time goes and the size stays.
1851
+ const thinkCostTail = () => {
1852
+ const tokens = session.thinkRereadTokens();
1853
+ const mid = turnRunning();
1854
+ const lead = mid ? " · from the next step (per request; this turn's prompt is untouched)" : "";
1855
+ if (tokens < 2048)
1856
+ return lead;
1857
+ const model = session.currentModel();
1858
+ const rate = model === "moa" ? undefined : readRates.readRate(model, tokens);
1859
+ const cols = termCols();
1860
+ const cost = cols < 80 ? rereadCost(tokens, undefined) : rereadCost(tokens, rate, { source: cols >= 100 });
1861
+ return `${lead} · ${mid ? "the next turn" : "your next message"} re-reads ${cost}`;
1862
+ };
1379
1863
  // A follower drove a slash command. Reuse the EXACT same path a local `/name args` line takes (submitRef → onSubmit →
1380
1864
  // handleSlash) — never a second implementation of the switch — but only for names on the remote-safe allowlist;
1381
1865
  // anything else is refused locally-visibly (sys + an audit event) rather than silently dropped or silently run.
@@ -1454,29 +1938,26 @@ function Root() {
1454
1938
  // lockstep. Factored out of applyMode so the plan-exit picker below can perform it from a resolve
1455
1939
  // callback without re-entering (and re-gating) applyMode itself.
1456
1940
  const performModeSwitch = useCallback((next, quiet) => {
1941
+ if (next === "plan" && opModeRef.current !== "plan")
1942
+ beforePlanRef.current = opModeRef.current;
1457
1943
  if (next === "plan") {
1458
1944
  session.setPlanMode(true);
1459
1945
  planProposedRef.current = false;
1460
1946
  } // fresh plan-mode session
1461
1947
  else {
1462
1948
  session.setPlanMode(false);
1463
- session.setPermissionMode(next === "auto" ? "bypass" : "gated");
1949
+ session.setOperatingMode(modePolicyFor(next));
1464
1950
  }
1465
1951
  opModeRef.current = next;
1466
1952
  setPlanMode(next === "plan");
1467
1953
  setOpMode(next);
1468
1954
  if (!quiet)
1469
- sys(next === "auto"
1470
- ? "◆ mode → AUTONOMOUS — I execute without asking (shift+tab to cycle)"
1471
- : next === "manual"
1472
- ? "◈ mode → MANUAL — I ask before mutating (writes/edits/shell) (shift+tab to cycle)"
1473
- : "◔ mode → PLAN — read-only research + a proposed plan; nothing runs (shift+tab to cycle)");
1955
+ sys(MODE_LINE[next] + (turnRunning() ? " · from the next tool call; the running batch finishes first" : ""));
1474
1956
  remoteRef.current?.setCapabilities(buildCapabilities()); // re-sync attached followers' mode selector
1475
1957
  }, [sys]);
1476
- // Single code path for a mode change — Shift+Tab (onCycleMode), the /mode slash command (local or
1477
- // driven by a remote follower), and /plan all funnel here so the policy, the plan flag, the status
1478
- // badge, and the follower-facing capabilities stay in lockstep. auto=Autonomous (bypass policy, no
1479
- // approvals), manual=gated (mutations ask), plan=read-only research (session plan mode).
1958
+ // Single code path for a mode change — Shift+Tab (onCycleMode), the /mode slash command (owner-local),
1959
+ // and /plan (local or driven by a remote follower) all funnel here so the policy, the plan flag, the status
1960
+ // badge, and the follower-facing capabilities stay in lockstep. What each mode runs as: permissions/modes.ts.
1480
1961
  //
1481
1962
  // Leaving plan mode after the model actually proposed a plan doesn't switch silently — it parks an
1482
1963
  // Approve & run / Keep planning / Cancel picker (reusing QuestionPrompt) and defers the real switch
@@ -1510,7 +1991,7 @@ function Root() {
1510
1991
  saveSettings({ contextPin: session.contextPin() });
1511
1992
  setCtxPin(session.contextPin());
1512
1993
  setCtxPct(session.ctxPct());
1513
- sys(contextLine(session.contextPin(), session.servedContext(), session.ctxPct()));
1994
+ sys(contextLine(session.contextPin(), session.servedContext(), session.ctxPct()) + (turnRunning() ? " · from the next round" : ""));
1514
1995
  }, [sys]);
1515
1996
  // The /model, context and provider pickers share the one local QuestionPrompt slot. A row resolves by INDEX into the
1516
1997
  // entries it was drawn from (row text can repeat); the empty reply / ctrl+c (DISCUSS) closes the picker without
@@ -1590,10 +2071,21 @@ function Root() {
1590
2071
  setEntries([]);
1591
2072
  setLive(null);
1592
2073
  setCtxPct(0);
2074
+ collapsedRef.current = [];
2075
+ batchesRef.current.clear();
2076
+ expectRef.current = null;
1593
2077
  newArchive();
1594
2078
  sys("started a fresh conversation");
1595
2079
  break;
1596
2080
  case "model": {
2081
+ // What a switch to `id` costs (TUI A3.6): this conversation's request at that endpoint's learned chars/token (its
2082
+ // server holds none of it in its prefix cache) and that model's measured read rate. The active model costs nothing.
2083
+ const costOf = (id) => {
2084
+ if (id === s.currentModel())
2085
+ return undefined;
2086
+ const est = s.rereadEstimate(id);
2087
+ return est ? { tokens: est.tokens, window: est.window, rate: readRates.readRate(id, est.tokens) } : undefined;
2088
+ };
1597
2089
  // Apply a selection (picker choice or `/model <id>`), persist it, and reflect it on the
1598
2090
  // status rule right away — the router only updates its label mid-turn (onRoute), and MOA has
1599
2091
  // no router of its own at all, so this is the one place that's always accurate immediately.
@@ -1602,6 +2094,7 @@ function Root() {
1602
2094
  sys("that looks like an API key — use “+ Connect a provider key” in /model; nothing was stored or shown");
1603
2095
  return undefined;
1604
2096
  }
2097
+ const cost = costOf(id); // priced before the switch, against the model being left
1605
2098
  const r = s.setModel(id);
1606
2099
  if (!r.ok) {
1607
2100
  sys(`${r.error} — run /model for the list`);
@@ -1610,7 +2103,10 @@ function Root() {
1610
2103
  setRoute(s.currentModel());
1611
2104
  saveSettings({ activeModel: s.currentModel() });
1612
2105
  const chosen = s.modelRegistry().find((m) => m.id === s.currentModel());
1613
- sys(modelLine(s.currentModel(), chosen, s.ctxPct(), s.turnCount())); // a free row repeats its caveat here
2106
+ sys(modelLine(s.currentModel(), chosen, s.ctxPct(), s.turnCount(), cost)); // a free row repeats its caveat here
2107
+ // Arm the phase line's forecast of what the next message may re-read on this model (the line above names the cost).
2108
+ const f = forecast(coldReadsRef.current, routeLabel(s.currentModel()), s.requestTokens());
2109
+ expectRef.current = f;
1614
2110
  remoteRef.current?.setCapabilities(buildCapabilities()); // active model changed — re-sync attached followers
1615
2111
  // One honest line when the portal reports the chosen model down. Non-blocking (cache or ≤3s), silent when
1616
2112
  // the portal is unreachable or doesn't know the model — selection is never refused on portal state.
@@ -1655,7 +2151,7 @@ function Root() {
1655
2151
  askKey(a.entry); });
1656
2152
  };
1657
2153
  const active = s.currentModel();
1658
- const view = () => modelPickerView(s.modelRegistry(), { active, servedCtx: s.servedContext(), staleFree: freeStaleRef.current });
2154
+ const view = () => modelPickerView(s.modelRegistry(), { active, servedCtx: s.servedContext(), staleFree: freeStaleRef.current, cost: (m) => costOf(m.id), cols: termCols() });
1659
2155
  const first = view();
1660
2156
  let onScreen = first.rows;
1661
2157
  let cat;
@@ -1668,9 +2164,33 @@ function Root() {
1668
2164
  connectProvider();
1669
2165
  return;
1670
2166
  }
1671
- const chosen = apply(a.entry.profile.id);
1672
- if (chosen && wantsContextStep(chosen, s.servedContext()))
1673
- openContextPicker();
2167
+ const id = a.entry.profile.id;
2168
+ const go = () => { const chosen = apply(id); if (chosen && wantsContextStep(chosen, s.servedContext()))
2169
+ openContextPicker(); };
2170
+ // A pick that costs a long re-read asks once, with the price: switch now, compact here first, or stay.
2171
+ const cost = costOf(id);
2172
+ if (!cost || !wantsRereadConfirm(cost)) {
2173
+ go();
2174
+ return;
2175
+ }
2176
+ const here = s.currentModel() === DEFAULT_MODEL_ID ? "aurora" : s.currentModel();
2177
+ const est = s.compactionEstimate();
2178
+ const v = rereadConfirmView({
2179
+ target: a.entry.profile.label, current: here, cost,
2180
+ compact: est ? { afterMax: est.afterMax, summaryMax: est.summaryMax, decode: readRates.decodeRate(s.currentModel()) } : undefined,
2181
+ });
2182
+ openPicker(v.question, v.rows, v.choices, (c) => {
2183
+ if (!("entry" in c))
2184
+ return; // Esc / "chat about it": nothing changes
2185
+ if (c.entry === "switch")
2186
+ go();
2187
+ else if (c.entry === "compact") {
2188
+ flow.afterCompaction(go);
2189
+ void slashRef.current("/compact");
2190
+ } // compacts on the cache-warm model, then switches — before anything waiting can start a turn
2191
+ else
2192
+ sys(`stayed on ${here}`);
2193
+ });
1674
2194
  });
1675
2195
  // Live state markers from the portal and the free rows: the picker opens instantly; whichever lands re-renders
1676
2196
  // the SAME picker (markers on the same rows, free rows in their place before MOA) — only when something changed.
@@ -1873,19 +2393,43 @@ function Root() {
1873
2393
  sys("compaction already in progress…");
1874
2394
  break;
1875
2395
  }
2396
+ // A follower's /compact (remote-safe, no busy gate) mid-turn compacted the conversation the live turn was using
2397
+ // and took over its read line and handlers (review F11). The turn compacts on its own when it must.
2398
+ if (statusRef.current !== "idle") {
2399
+ sys("a turn is running — /compact when it ends (a turn compacts on its own when it must)");
2400
+ break;
2401
+ }
2402
+ // The 500 ms clock and the main lane measure from here, not from the last turn's start (review F12).
2403
+ turnStartRef.current = Date.now();
2404
+ setElapsed(0);
1876
2405
  const beforePct = s.ctxPct();
1877
2406
  setStepLabel("compacting context");
2407
+ // The same measured line as a mid-turn compaction: the summarizer's own read progress, when it reports one.
2408
+ compactRef.current = { before: s.requestTokens(), startedAt: Date.now(), ring: [], wrote: 0 };
2409
+ setPhase("compacting");
1878
2410
  setStat("compacting");
1879
2411
  try {
1880
- const n = await s.compactNow();
2412
+ const n = await s.compactNow({
2413
+ onPromptProgress: ({ processed, total, cached, timeMs }) => {
2414
+ if (!compactRef.current)
2415
+ return;
2416
+ compactRef.current.ring = pushSample(compactRef.current.ring, { processed, total, cache: cached, timeMs, at: Date.now() });
2417
+ setReadTick((k) => k + 1);
2418
+ },
2419
+ onCompactionWrite: (w) => { if (compactRef.current)
2420
+ compactRef.current.wrote = w; },
2421
+ });
1881
2422
  sys(n > 0
1882
2423
  ? `compacted · freed ~${n.toLocaleString()} tokens · ctx ${beforePct}%→${s.ctxPct()}%`
1883
2424
  : "already minimal — nothing to shed");
1884
2425
  }
1885
2426
  finally {
2427
+ compactRef.current = null;
2428
+ setPhase(null);
1886
2429
  setStepLabel("");
1887
2430
  setStat("idle");
1888
2431
  setCtxPct(s.ctxPct());
2432
+ flow.compacted(); // what it was started for, then what was typed during it — like after a turn
1889
2433
  }
1890
2434
  break;
1891
2435
  }
@@ -2132,11 +2676,11 @@ function Root() {
2132
2676
  if (q)
2133
2677
  skills = skills.filter((sk) => sk.name.toLowerCase().includes(q) || (sk.description ?? "").toLowerCase().includes(q));
2134
2678
  if (!skills.length) {
2135
- sys(q ? `no installed skills match "${arg}" — the fleet catalogue is still searchable mid-task via the skill_list tool` : "no skills installed locally — the fleet's 60k+ catalogue is searchable mid-task via the skill_list tool");
2679
+ sys(q ? `no installed skills match "${arg}" — ctrl+g searches the AXE hub's 65K+ skills (the model reaches them with skill_list)` : "no skills installed locally — ctrl+g searches the AXE hub's 65K+ skills (the model reaches them with skill_list)");
2136
2680
  break;
2137
2681
  }
2138
2682
  const rows = skills.slice(0, 40).map((sk) => ` ◆ ${sk.name}${sk.description ? ` — ${sk.description.length > 80 ? sk.description.slice(0, 79) + "…" : sk.description}` : ""}`);
2139
- sys(`skills (${skills.length}${q ? ` matching "${arg}"` : ""}):\n` + rows.join("\n") + (skills.length > 40 ? `\n … +${skills.length - 40} more` : "") + "\n(the fleet's 60k+ catalogue is also searchable mid-task via the skill_list tool)");
2683
+ sys(`skills (${skills.length}${q ? ` matching "${arg}"` : ""}):\n` + rows.join("\n") + (skills.length > 40 ? `\n … +${skills.length - 40} more` : "") + "\n(ctrl+g searches the AXE hub's 65K+ skills too: preview, use, run, or create one)");
2140
2684
  break;
2141
2685
  }
2142
2686
  case "deep-research":
@@ -2174,7 +2718,7 @@ function Root() {
2174
2718
  }
2175
2719
  case "plan": {
2176
2720
  const on = !s.inPlanMode();
2177
- const next = on ? "plan" : "auto";
2721
+ const next = planToggleTarget(on ? opModeRef.current : "plan", beforePlanRef.current);
2178
2722
  // A plan was proposed → applyMode parks the Approve & run picker instead of switching, and its
2179
2723
  // own resolve() gives the exit message — this command's custom line would be premature/wrong.
2180
2724
  const gated = shouldPromptPlanExit(opModeRef.current, next, planProposedRef.current);
@@ -2182,19 +2726,15 @@ function Root() {
2182
2726
  if (!gated)
2183
2727
  sys(on
2184
2728
  ? "◔ plan mode ON — I'll research read-only and propose a plan; writes/edits/shell mutations are blocked. /plan again to approve + execute."
2185
- : "plan mode OFF — back to normal execution.");
2729
+ : `plan mode OFF — back to ${next === "auto" ? "Autonomous" : next === "manual" ? "Manual" : "Gated"}.`);
2186
2730
  break;
2187
2731
  }
2188
2732
  case "mode": {
2189
- // Set the operating mode by name (owner OR a remote follower via a `command` frame). Mirrors
2190
- // Shift+Tab's cycle but addressable: /mode plan | manual | autonomous. No arg → report current.
2191
- const a = arg.toLowerCase();
2192
- const target = a === "plan" ? "plan"
2193
- : (a === "manual" || a === "gated") ? "manual"
2194
- : (a === "auto" || a === "autonomous" || a === "bypass") ? "auto"
2195
- : null;
2733
+ // Set the operating mode by name (owner-local: /mode is not in the follower allowlist). Shift+Tab's cycle,
2734
+ // addressable, plus gated, which is outside the cycle. No arg → report current.
2735
+ const target = parseMode(arg);
2196
2736
  if (!target) {
2197
- sys(`mode is ${opModeRef.current === "auto" ? "AUTONOMOUS" : opModeRef.current.toUpperCase()} — usage: /mode plan | manual | autonomous`);
2737
+ sys(`mode is ${opModeRef.current === "auto" ? "AUTONOMOUS" : opModeRef.current.toUpperCase()} — usage: /mode autonomous | manual | plan | gated`);
2198
2738
  break;
2199
2739
  }
2200
2740
  applyMode(target);
@@ -2204,16 +2744,16 @@ function Root() {
2204
2744
  const on = s.currentThinkMode() !== "think";
2205
2745
  s.setThinkMode(on ? "think" : "off");
2206
2746
  setThinkMode(on ? "think" : "off");
2207
- sys(on ? "✲ think ON — Operator reasons (shown dimmed) before answering. /think again to turn off."
2208
- : "think off — back to fast direct answers.");
2747
+ sys((on ? "✲ think ON — Operator reasons (shown dimmed) before answering. /think again to turn off."
2748
+ : "think off — back to fast direct answers.") + thinkCostTail());
2209
2749
  break;
2210
2750
  }
2211
2751
  case "ultrathink": {
2212
2752
  const on = s.currentThinkMode() !== "ultrathink";
2213
2753
  s.setThinkMode(on ? "ultrathink" : "off");
2214
2754
  setThinkMode(on ? "ultrathink" : "off");
2215
- sys(on ? "✲✲ ultrathink ON — Operator reasons deeply + exhaustively before answering (slower, deeper). /ultrathink again to turn off."
2216
- : "ultrathink off — back to fast direct answers.");
2755
+ sys((on ? "✲✲ ultrathink ON — Operator reasons deeply + exhaustively before answering (slower, deeper). /ultrathink again to turn off."
2756
+ : "ultrathink off — back to fast direct answers.") + thinkCostTail());
2217
2757
  break;
2218
2758
  }
2219
2759
  case "audit": {
@@ -2385,6 +2925,10 @@ function Root() {
2385
2925
  const ok = bg.sendToAgent(targetId, subArg);
2386
2926
  sys(ok ? `message sent to ${targetId}` : `${targetId} is not running — can only message working/queued agents`);
2387
2927
  }
2928
+ else if (subCmd === "report") {
2929
+ if (!expandReport(target.id))
2930
+ sys(`${target.name ?? target.id} has no report yet — ${target.status === "working" || target.status === "queued" ? "it is still running" : "it ended without one"}`);
2931
+ }
2388
2932
  else if (subCmd === "stop" || subCmd === "kill") {
2389
2933
  // requestStop, not stop: the partial report wakes the orchestrator so it can take the step over.
2390
2934
  sys(bg.requestStop(targetId) ? `stopped ${targetId} — its partial work goes to the orchestrator` : `${targetId} already finished`);
@@ -2557,6 +3101,12 @@ function Root() {
2557
3101
  }
2558
3102
  }, [exit, sys, bg, authUser, approval, settleApproval, settleQuestion, applyMode, applyContext, openPicker, openContextPicker, refreshFreeRows, remoteCommand, remotePrompt]);
2559
3103
  const onSubmit = useCallback((text) => {
3104
+ // A submit that arrives while a turn runs (a remote follower's prompt or command, a wake) takes the same path the
3105
+ // keyboard does: a command by its mid-turn class, text as a steer — a second Session.send would throw mid-turn.
3106
+ if (statusRef.current !== "idle") {
3107
+ (isSlashCommand(text) ? queueRef : steerRef).current(text);
3108
+ return;
3109
+ }
2560
3110
  if (isSlashCommand(text)) {
2561
3111
  void handleSlash(text.trim());
2562
3112
  return;
@@ -2564,25 +3114,325 @@ function Root() {
2564
3114
  void sendTurn(text);
2565
3115
  }, [sendTurn, handleSlash]);
2566
3116
  submitRef.current = onSubmit;
2567
- const onQueue = useCallback((text) => { queued.current = [...queued.current, text]; setQueuedPreview(queued.current); }, []);
2568
- // ↑ / Backspace on an empty draft act on the most recent queued message: edit pops it back into the draft (Enter
2569
- // re-queues it, or sends it if the turn has ended); drop discards it and echoes the full text so nothing vanishes silently.
3117
+ slashRef.current = handleSlash;
3118
+ const queueRef = useRef(() => { });
3119
+ const steerRef = useRef(() => { });
3120
+ // Tab, Esc-with-a-draft and Enter on a /command land here while a turn runs. A command never waits blindly (A3.2,
3121
+ // util/slash.ts MIDTURN): read-only ones run now and the turn keeps going; settings the engine reads per request or
3122
+ // per tool call apply now, from the next step; the rest are staged and run on their own when the turn ends.
3123
+ const onQueue = useCallback((text) => {
3124
+ const cmd = text.trim();
3125
+ if (isSlashCommand(cmd) && statusRef.current !== "idle") {
3126
+ const cls = midTurnClass(cmd);
3127
+ if (cls !== "after") {
3128
+ // a "next" command's own line says when it applies ("from the next tool call", "from the next step")
3129
+ push({ kind: "message", message: { id: nextId(), role: "user", content: cmd, tag: cls === "now" ? "↳ ran now · the turn keeps going" : undefined } });
3130
+ void slashRef.current(cmd);
3131
+ return;
3132
+ }
3133
+ setPendingItems([...pendingRef.current, { kind: "command", text: cmd }]);
3134
+ stagedNoteRef.current(cmd);
3135
+ return;
3136
+ }
3137
+ setPendingItems([...pendingRef.current, { kind: "after", text }]);
3138
+ }, []);
3139
+ // A staged /model <id> says what the switch will cost before the turn even ends, and that Esc gets there sooner.
3140
+ const stagedNoteRef = useRef(() => { });
3141
+ stagedNoteRef.current = (cmd) => {
3142
+ const [name, ...rest] = cmd.slice(1).split(/\s+/);
3143
+ const id = rest.join(" ").trim();
3144
+ if (name !== "model" || !id || looksLikeSecret(id))
3145
+ return;
3146
+ const est = session.rereadEstimate(id);
3147
+ if (!est)
3148
+ return;
3149
+ const cols = termCols(); // under 80 columns the time goes and the size stays (the /think rule)
3150
+ const cost = rereadCost(est.tokens, cols < 80 ? undefined : readRates.readRate(id, est.tokens), { source: cols >= 100 });
3151
+ sys(`after this turn · ${id} re-reads up to ${cost} · esc stops now and switches`);
3152
+ };
3153
+ // Enter mid-turn steers the running turn. Only a model turn has a next round: during a manual /compact the message
3154
+ // waits for after it, and a turn that ended in the meantime simply takes it as the next turn.
3155
+ const onSteer = useCallback((text) => {
3156
+ if (statusRef.current === "idle") {
3157
+ submitRef.current(text);
3158
+ return;
3159
+ }
3160
+ setPendingItems([...pendingRef.current, { kind: statusRef.current === "compacting" ? "after" : "steer", text }]);
3161
+ }, []);
3162
+ // ↑ / Backspace on an empty draft act on the most recent pending message, steer or queued: edit pops it back into the
3163
+ // draft (Enter steers or queues it again, or sends it if the turn has ended); drop discards it and echoes the full text
3164
+ // so nothing vanishes silently.
2570
3165
  const popQueued = useCallback(() => {
2571
- const text = queued.current.at(-1);
2572
- if (text === undefined)
3166
+ const { item, rest } = popLatest(pendingRef.current);
3167
+ if (!item)
2573
3168
  return undefined;
2574
- queued.current = queued.current.slice(0, -1);
2575
- setQueuedPreview(queued.current);
2576
- return text;
3169
+ setPendingItems(rest);
3170
+ return item.text;
3171
+ }, []);
3172
+ queueRef.current = onQueue;
3173
+ steerRef.current = onSteer;
3174
+ const onDropQueued = useCallback(() => {
3175
+ const { item, rest } = popLatest(pendingRef.current);
3176
+ if (!item)
3177
+ return;
3178
+ setPendingItems(rest);
3179
+ sys(`${item.kind === "steer" ? "steer" : "queued message"} cancelled (not sent): ${item.text}`);
3180
+ }, [sys]);
3181
+ // "@Nova <text>" (A3.4): straight to that sub-agent's next round — no main-model turn, idle or mid-turn, the main
3182
+ // context and cache untouched. "@Nova stop" stops it (its partial report goes to the orchestrator, as /agents stop
3183
+ // does); "@all stop" stops every running or queued one.
3184
+ const sendToAgentLine = useCallback((id, message) => {
3185
+ const a = bg.list().find((x) => x.id === id);
3186
+ const who = a?.name ?? id;
3187
+ if (!message) {
3188
+ sys(`type a message after @${who} — it goes to ${who}'s next round`);
3189
+ return;
3190
+ }
3191
+ if (/^stop$/i.test(message)) {
3192
+ sys(bg.requestStop(id) ? `→ ${who}: stop · its partial findings go to the orchestrator` : `${who} already finished`);
3193
+ return;
3194
+ }
3195
+ if (!bg.sendToAgent(id, message)) {
3196
+ sys(`${who} isn't running — /agents ${who} shows what it reported`);
3197
+ return;
3198
+ }
3199
+ sys(`→ ${who}: ${message} ✉ waits for its next round · ${statusRef.current === "idle" ? "no main turn" : "main turn untouched"}`);
3200
+ setBgAgents(bg.list()); // the panel's "✉ 1 message waiting" now, not at the next throttled tick
3201
+ }, [bg, sys]);
3202
+ const onAgentMessage = useCallback((text) => {
3203
+ const m = agentMention(text, bg.list());
3204
+ if (!m) {
3205
+ submitRef.current(text);
3206
+ return;
3207
+ }
3208
+ if (m.target === "all") {
3209
+ const ids = bg.requestStopAll();
3210
+ sys(ids.length ? `@all stop → stopped ${ids.join(", ")} · their partial findings go to the orchestrator` : "no running or queued sub-agents to stop");
3211
+ return;
3212
+ }
3213
+ sendToAgentLine(m.target.id, m.message);
3214
+ }, [bg, sys, sendToAgentLine]);
3215
+ // Typing while a sub-agent's conversation is open goes to that sub-agent, the same way @Name does.
3216
+ const onSendTo = useCallback((text) => {
3217
+ const id = openConvRef.current;
3218
+ if (id === MAIN) {
3219
+ submitRef.current(text);
3220
+ return;
3221
+ }
3222
+ const a = bg.list().find((x) => x.id === id);
3223
+ if (!a || (a.status !== "working" && a.status !== "queued")) {
3224
+ sys(`${a?.name ?? id} finished — its conversation is read-only · ↓ then main to go back`);
3225
+ return;
3226
+ }
3227
+ sendToAgentLine(id, text.trim());
3228
+ }, [bg, sys, sendToAgentLine]);
3229
+ // The switcher (mode line centre): ↓ from the composer focuses it, ←/→ pick, Enter opens, ↑ / Esc go back.
3230
+ const onFocusSwitcher = useCallback(() => {
3231
+ const convs = convsRef.current;
3232
+ if (convs.length < 2)
3233
+ return false;
3234
+ setSwitcher({ focused: true, sel: openConvRef.current });
3235
+ return true;
2577
3236
  }, []);
2578
- const onDropQueued = useCallback(() => { const text = popQueued(); if (text !== undefined)
2579
- sys(`queued message cancelled (not sent): ${text}`); }, [popQueued, sys]);
2580
- // Shift+Tab cycles the operating mode (matches Claude Code). auto→manual→plan→auto. Auto drives with
2581
- // no approval gate; Manual gates mutating tools through the approve() bridge; Plan is read-only research.
3237
+ const onSwitcher = useCallback((k) => {
3238
+ const sw = switcherRef.current;
3239
+ const r = switcherKey(convsRef.current, sw.sel, k);
3240
+ if (r.sel)
3241
+ setSwitcher({ ...sw, sel: r.sel });
3242
+ else {
3243
+ if (r.open)
3244
+ setOpenConv(r.open);
3245
+ setSwitcher({ ...sw, focused: false });
3246
+ }
3247
+ }, []);
3248
+ // ctrl+y: ask the running turn for its answer now. During the read it arms (the phase line says so); a live stream is
3249
+ // cut at once; during tools it applies before the next request. Idle: nothing to cut.
3250
+ const onActNow = useCallback(() => {
3251
+ if (statusRef.current === "idle" || !session.actNow())
3252
+ return;
3253
+ const st = actRef.current;
3254
+ // A live stream is cut at once (onOwnerAct settles it). Before the first token — queued at the server or still
3255
+ // reading — it is armed; during tools it applies once they finish. Either way the phase line says so now.
3256
+ if (statusRef.current === "executing")
3257
+ actRef.current = { ...st, armedTools: true };
3258
+ else if (st.reasoningSince === undefined)
3259
+ actRef.current = { ...st, armed: true };
3260
+ }, []);
3261
+ // ctrl+g — the skills and tools finder (A3.3, James's change; skills/finder.ts). Local sources answer as you type; the
3262
+ // AXE hub's ranked search is debounced, and a newer keystroke cancels an older search. Use = activate a skill (its
3263
+ // instructions ride with your next message) or ask for a tool; run = that, with your search words as the task;
3264
+ // create = the model drafts a new skill into your profile (skill_save), or the skeleton is saved now.
3265
+ const finderSourcesRef = useRef(null);
3266
+ const onOpenFinder = useCallback(() => {
3267
+ if (finderOpenRef.current)
3268
+ return;
3269
+ const sources = (finderSourcesRef.current ??= defaultSources());
3270
+ const patch = (p) => setFinder((f) => (f ? { ...f, ...p } : f));
3271
+ const results = new Map();
3272
+ const ORDER = ["profile", "catalogue", "hub", "tool"];
3273
+ const merged = () => ORDER.flatMap((id) => results.get(id) ?? []);
3274
+ let seq = 0;
3275
+ let ctl;
3276
+ let timer;
3277
+ const search = (query) => {
3278
+ const mine = ++seq;
3279
+ ctl?.abort();
3280
+ ctl = new AbortController();
3281
+ if (timer)
3282
+ clearTimeout(timer);
3283
+ results.clear();
3284
+ for (const src of sources.filter((x) => x.id !== "hub")) {
3285
+ void src.search(query, { limit: SOURCE_LIMITS[src.id] }).then((items) => { if (mine !== seq)
3286
+ return; results.set(src.id, items); patch({ items: merged() }); }).catch(() => { });
3287
+ }
3288
+ const hub = sources.find((x) => x.id === "hub");
3289
+ if (!hub)
3290
+ return;
3291
+ patch({ status: query.trim() ? "searching the AXE hub…" : "loading the AXE hub…" });
3292
+ const signal = ctl.signal;
3293
+ timer = setTimeout(() => {
3294
+ const t0 = Date.now();
3295
+ hub.search(query, { limit: SOURCE_LIMITS.hub, signal }).then((items) => {
3296
+ if (mine !== seq)
3297
+ return;
3298
+ results.set("hub", items);
3299
+ patch({ items: merged(), status: `hub: ${items.length} ${query.trim() ? `ranked for "${query.trim()}"` : "listed (type to search)"} · ${((Date.now() - t0) / 1000).toFixed(1)}s` });
3300
+ }).catch((e) => {
3301
+ if (mine !== seq || signal.aborted)
3302
+ return;
3303
+ const why = e instanceof HubUnreadable ? "answered something unreadable" : `is not answering (${e.message})`;
3304
+ patch({ status: `the AXE hub ${why} — your profile, the catalogue and tools still search` });
3305
+ });
3306
+ }, query.trim() ? 250 : 0);
3307
+ };
3308
+ let useCtl; // the ⏎ / ctrl+r load in flight: Esc, a newer ⏎ or closing drops it
3309
+ const close = () => { ctl?.abort(); useCtl?.abort(); if (timer)
3310
+ clearTimeout(timer); finderOpenRef.current = false; setFinder(null); };
3311
+ const fetchOf = (it, signal) => sources.find((x) => x.id === it.source).fetch(it, signal);
3312
+ const turnOrQueue = (text, display) => { if (statusRef.current === "idle")
3313
+ void sendTurn(text, { display });
3314
+ else
3315
+ queueRef.current(text); };
3316
+ const onIntent = async (i) => {
3317
+ switch (i.kind) {
3318
+ case "query":
3319
+ search(i.query);
3320
+ break;
3321
+ case "close":
3322
+ close();
3323
+ break;
3324
+ case "cancel":
3325
+ useCtl?.abort();
3326
+ patch({ loading: false, note: "cancelled — nothing was loaded" });
3327
+ break;
3328
+ case "preview":
3329
+ patch({ preview: { source: i.item.source, id: i.item.id, loading: true } });
3330
+ try {
3331
+ const text = await fetchOf(i.item);
3332
+ patch({ preview: { source: i.item.source, id: i.item.id, text: text || "(empty)" } });
3333
+ }
3334
+ catch (e) {
3335
+ patch({ preview: { source: i.item.source, id: i.item.id, error: `could not load it: ${e.message}` } });
3336
+ }
3337
+ break;
3338
+ case "use":
3339
+ case "run": {
3340
+ const it = i.item;
3341
+ if (it.source === "tool") {
3342
+ close();
3343
+ turnOrQueue(`Use the ${it.id} tool${i.query.trim() ? ` for: ${i.query.trim()}` : "."}`);
3344
+ break;
3345
+ }
3346
+ useCtl?.abort();
3347
+ const loading = (useCtl = new AbortController());
3348
+ patch({ loading: true, note: `loading ${it.name}… · esc cancels` });
3349
+ let content = "";
3350
+ try {
3351
+ content = await fetchOf(it, loading.signal);
3352
+ }
3353
+ catch (e) {
3354
+ if (!loading.signal.aborted)
3355
+ patch({ loading: false, note: `could not load ${it.name}: ${e.message}` });
3356
+ break;
3357
+ }
3358
+ // Esc, a newer ⏎ or closing the finder while it loaded: this one does nothing (review F8)
3359
+ if (loading.signal.aborted || !finderOpenRef.current)
3360
+ break;
3361
+ patch({ loading: false });
3362
+ if (!content.trim()) {
3363
+ patch({ note: `${it.name} has no instructions to load` });
3364
+ break;
3365
+ }
3366
+ close();
3367
+ const when = statusRef.current === "idle" ? "your next message" : "your next message after this turn";
3368
+ const from = it.source === "hub" ? `AXE hub${it.origin ? ` · ${it.origin}` : ""}` : it.source;
3369
+ if (trustedInstructions(it, content)) {
3370
+ session.activateSkill(it.id, content);
3371
+ sys(`skill '${it.name}' (${from}) activated — its instructions ride with ${when} · /skill off to drop it`);
3372
+ }
3373
+ else {
3374
+ // An unverified entry is never an instruction (review F3): quoted, once, as data.
3375
+ session.referenceOnce(quotedReference(it, content));
3376
+ sys(`'${it.name}' (${from}) is unverified — not activated: ${when} carries it once, quoted as reference data, not instructions`);
3377
+ }
3378
+ if (i.kind === "run")
3379
+ turnOrQueue(i.query.trim() || `Use the ${it.name} skill now.`, i.query.trim() ? undefined : `use ${it.name}`);
3380
+ break;
3381
+ }
3382
+ case "create": {
3383
+ const slug = skillSlug(i.name);
3384
+ if (i.draft) {
3385
+ close();
3386
+ turnOrQueue(draftSkillPrompt(slug, i.description), `new skill: ${slug}${i.description.trim() ? ` — ${i.description.trim()}` : ""}`);
3387
+ break;
3388
+ }
3389
+ const save = registry.get("skill_save");
3390
+ const out = save ? await save.run({ name: slug, content: skillSkeleton(slug, i.description) }) : "error: skill_save is not available";
3391
+ patch({ note: out.startsWith("error") ? out : `saved '${slug}' to your profile — edit it, then ⏎ on it here to use it` });
3392
+ search(slug);
3393
+ break;
3394
+ }
3395
+ }
3396
+ };
3397
+ finderOpenRef.current = true;
3398
+ setFinder({ items: [], onIntent, status: "loading…" });
3399
+ void Promise.all(sources.map((x) => x.size().catch(() => undefined))).then((sizes) => {
3400
+ const by = Object.fromEntries(sources.map((x, k) => [x.id, sizes[k]]));
3401
+ const n = (v) => v?.toLocaleString("en-US");
3402
+ patch({ sizes: [by.hub !== undefined ? `${n(by.hub)} in the AXE hub` : "", by.catalogue ? `${n(by.catalogue)} in the catalogue` : "", by.profile ? `${n(by.profile)} in your profile` : "", by.tool ? `${n(by.tool)} tools` : ""].filter(Boolean).join(" · ") });
3403
+ });
3404
+ search("");
3405
+ }, [sendTurn, sys]);
3406
+ const finderOpenRef = useRef(false);
3407
+ // A picked next step (A3.5). "think off" is a per-turn flag (enable_thinking only — the system prompt, and the server's
3408
+ // cached prefix, stay as they are); "compact" runs /compact on the current, cache-warm model first.
3409
+ const nextStepsRef = useRef(null);
3410
+ nextStepsRef.current = nextSteps;
3411
+ const onPickNext = useCallback((n) => {
3412
+ const step = nextStepsRef.current?.[n - 1];
3413
+ if (!step || statusRef.current !== "idle")
3414
+ return;
3415
+ setNextSteps(null);
3416
+ const a = step.action;
3417
+ if (a.kind === "send")
3418
+ void sendTurn(a.text, { display: a.display, thinkOff: a.thinkOff });
3419
+ else if (a.kind === "compact-send") {
3420
+ flow.afterCompaction(() => sendTurn(a.text, { display: a.display }));
3421
+ void slashRef.current("/compact");
3422
+ }
3423
+ else if (a.kind === "model")
3424
+ void slashRef.current("/model");
3425
+ else if (a.kind === "show") {
3426
+ const t = stashedPartialRef.current;
3427
+ sys(t ? `what the stopped reply had (cut by the repetition check, kept out of history):\n${t.length > 8000 ? `${t.slice(0, 8000)}\n… (${t.length - 8000} more chars)` : t}` : "nothing was kept from that reply");
3428
+ }
3429
+ }, [sendTurn, sys]);
3430
+ const onDismissNext = useCallback(() => { if (nextStepsRef.current)
3431
+ setNextSteps(null); }, []);
3432
+ // Shift+Tab cycles the operating mode (matches Claude Code): auto → manual → plan → auto; from gated it goes to plan
3433
+ // and never back (permissions/modes.ts nextMode).
2582
3434
  const onCycleMode = useCallback(() => {
2583
- const cur = opModeRef.current;
2584
- const next = cur === "auto" ? "manual" : cur === "manual" ? "plan" : "auto";
2585
- applyMode(next);
3435
+ applyMode(nextMode(opModeRef.current));
2586
3436
  }, [applyMode]);
2587
3437
  // ctrl+b: move the running shell command to the background so the turn continues. Nothing running → nothing happens.
2588
3438
  const onBackground = useCallback(() => { session.detachShell(); }, []);
@@ -2590,7 +3440,7 @@ function Root() {
2590
3440
  if (statusRef.current === "idle") {
2591
3441
  void teardown.run("quit");
2592
3442
  return exit();
2593
- } // Ctrl-C / ESC at rest quits
3443
+ } // Ctrl-C / ESC at rest quits (the Composer closes a strip on Esc itself)
2594
3444
  session.interrupt();
2595
3445
  }, [exit]);
2596
3446
  // Live clock: a lightweight interval ticks `elapsed` while a turn is active, so the timer advances
@@ -2599,7 +3449,7 @@ function Root() {
2599
3449
  // other hooks, ABOVE the boot early-returns below — otherwise it's skipped on the first render and the
2600
3450
  // hook count changes when boot flips to "ready" ("Rendered more hooks than during the previous render").
2601
3451
  useEffect(() => {
2602
- const active = status === "thinking" || status === "streaming" || status === "executing" || status === "recovering";
3452
+ const active = status === "thinking" || status === "streaming" || status === "executing" || status === "recovering" || status === "compacting";
2603
3453
  if (!active)
2604
3454
  return;
2605
3455
  const id = setInterval(() => setElapsed((Date.now() - turnStartRef.current) / 1000), 500); // 500ms: the elapsed readout shows whole/half seconds; 250ms doubled the whole-frame re-render rate (flashing)
@@ -2683,7 +3533,9 @@ function Root() {
2683
3533
  if (boot === "checking")
2684
3534
  return _jsx(Text, { dimColor: true, children: bootDetail || "connecting to Operator…" });
2685
3535
  if (boot === "down") {
2686
- return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, _jsxs(Text, { dimColor: true, children: ["The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/", settings.services?.aurora?.launchdLabel ?? "co.0perator.gateway"] })] }));
3536
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsx(Text, { color: "red", children: "Can't reach Operator on the configured endpoint." }), bootDetail ? _jsx(Text, { dimColor: true, children: bootDetail }) : null, session.currentModel() === DEFAULT_MODEL_ID
3537
+ ? _jsxs(Text, { dimColor: true, children: ["The Operator model is launchd-owned. Recover it with: launchctl kickstart -k gui/$(id -u)/", settings.services?.aurora?.launchdLabel ?? "co.0perator.gateway"] })
3538
+ : _jsxs(Text, { dimColor: true, children: ["Start on Aurora instead: set \"activeModel\": \"", DEFAULT_MODEL_ID, "\" in settings.json, then /model ", session.currentModel(), " once it is reachable."] })] }));
2687
3539
  }
2688
3540
  // While a turn runs, show a LIVE line: braille spinner + climbing token count + live tok/s + elapsed
2689
3541
  // seconds. When idle, show the last turn's final "N tok · X tok/s · Ys". Never freeze on the previous
@@ -2694,12 +3546,56 @@ function Root() {
2694
3546
  // Before the first token streams, the model is PREFILLING (reading the prompt) — that's the "0 tokens
2695
3547
  // for N seconds" the user sees. Label it honestly instead of showing a frozen "0 tokens", so a slow
2696
3548
  // local prefill reads as work in progress, not a hang. Once tokens flow, show the live count + elapsed.
3549
+ // The conversations the switcher offers, and the open sub-agent's pane: a fixed height (a third of the window, 4–12 rows)
3550
+ // for as long as it is open, so its live lines push old ones off the top instead of growing the frame.
3551
+ const convs = conversationList(bgAgents, bg.retiredList(), (id) => bg.hasTranscript(id));
3552
+ convsRef.current = convs;
3553
+ const openAgent = openConv === MAIN ? undefined : bgAgents.find((x) => x.id === openConv) ?? bg.retiredList().find((x) => x.id === openConv);
3554
+ const paneRows = Math.max(4, Math.min(12, Math.floor(termRows() / 3)));
3555
+ const conversationPane = openAgent
3556
+ ? { header: transcriptHeader(openAgent, termCols()), lines: transcriptLines(bg.transcript(openAgent.id) ?? [], termCols(), paneRows), target: openAgent.name ?? openAgent.id }
3557
+ : null;
3558
+ // The verb above names the phase now (Reading, Waiting, Loading…), so before the first token the metrics are just
3559
+ // the clock: "(3m 24s)", never "reading your prompt…" under a server that has not started reading.
2697
3560
  const liveMetrics = active
2698
3561
  ? liveTok === 0
2699
- ? `${spin} reading your prompt… (${fmtDuration(elapsed)})`
3562
+ ? `${spin} (${fmtDuration(elapsed)})`
2700
3563
  : `${spin} ${fmtMeta(elapsed, liveTok)}`
2701
3564
  : metrics;
2702
- return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, prefill: prefill, liveTools: liveTools, route: route, ctxPct: ctxPct, ctxWindow: session.currentModel() === "moa" ? (ctxPin ? fmtCtx(ctxPin) : undefined) : fmtCtx(ctxPin ? Math.min(ctxPin, session.servedContext()) : session.servedContext()), version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, onBackground: onBackground, tasks: tasks, onSubmit: onSubmit, onQueue: onQueue, queuedPreview: queuedPreview, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
3565
+ const vendorStream = deltasApprox(transportRef.current);
3566
+ // The decode readout for the phase line: the live rate, the depth, a shallower comparison from this session, and the
3567
+ // calm repetition note. "≈" on a transport whose deltas carry several tokens each (every vendor wire, review F7).
3568
+ const decodeView = () => {
3569
+ const d = decodeRef.current;
3570
+ const depth = depthRef.current;
3571
+ const model = routeLabel(route);
3572
+ return { rate: decodeRate(d), depth, compare: depth ? shallower(d, model, depth) : undefined, repeatingChars: d.repeatingChars || undefined, approx: vendorStream };
3573
+ };
3574
+ // The plan step names the spinner only when it started in THIS turn (or the turn is a wake turn), so a stale step
3575
+ // from an earlier turn never labels an unrelated question. Ground rule 6: plan step > measured phase > the pool.
3576
+ const curStep = tasks.find((t) => t.status === "in_progress");
3577
+ const stepVerb = curStep && (wakeTurnRef.current || (curStep.startedAt ?? 0) >= turnStartRef.current) ? planVerb(tasks) : undefined;
3578
+ const planLive = status !== "idle" || bgAgents.some((a) => a.status === "working");
3579
+ // Ink renders each setState on its own outside React events, so the phase and the status can disagree for one render
3580
+ // (a tool batch starting, or settling). The status decides which animation shows; keep the phase line consistent with it.
3581
+ const shownPhase = status === "executing" ? "tools" : phase === "tools" ? "waiting" : phase;
3582
+ // The main turn as a lane (TUI plan #11): its model, its plan step and phase, its clock and tokens.
3583
+ const stepAt = tasks.findIndex((t) => t.status === "in_progress");
3584
+ const mainLane = status !== "idle" && shownPhase
3585
+ ? { model: routeLabel(route), activity: `${stepVerb && stepAt >= 0 ? `step ${stepAt + 1}/${tasks.length} · ` : ""}${phaseWord(shownPhase)}`, elapsedMs: elapsed * 1000, tokens: liveTok }
3586
+ : null;
3587
+ const compactRead = compactRef.current ? readStats(compactRef.current.ring) : undefined;
3588
+ const phaseView = shownPhase
3589
+ ? {
3590
+ phase: shownPhase, model: routeLabel(route), tokens: liveTok, label: stepLabel,
3591
+ read: shownPhase === "reading" ? readStats(readRingRef.current, roundStartRef.current) : undefined,
3592
+ queue: shownPhase === "queued" ? gateQueueRef.current ?? undefined : undefined,
3593
+ compaction: shownPhase === "compacting" && compactRef.current ? { before: compactRef.current.before, read: compactRead, wrote: compactRef.current.wrote, approx: vendorStream } : undefined,
3594
+ expect: expectRef.current && (shownPhase === "waiting" || shownPhase === "sent") ? expectSegs(expectRef.current) : undefined,
3595
+ decode: shownPhase === "thinking" || shownPhase === "writing" || shownPhase === "drafting" ? decodeView() : undefined,
3596
+ }
3597
+ : null;
3598
+ return (_jsx(App, { messages: entries, live: live, status: status, stepLabel: stepLabel, phase: phaseView, fold: liveFold, delegate: delegate, thinkingVerb: stepVerb ?? triage ?? phaseVerb(shownPhase ?? undefined, phaseView?.read), liveTools: liveTools, route: route, ctxPct: ctxPct, ctxWindow: session.currentModel() === "moa" ? (ctxPin ? fmtCtx(ctxPin) : undefined) : fmtCtx(ctxPin ? Math.min(ctxPin, session.servedContext()) : session.servedContext()), version: VERSION, fullscreen: FULLSCREEN, metrics: liveMetrics, sessionTokens: session.sessionTokens() + liveTok, authUser: authUser, tier: EVENT_ACTOR.tier, planMode: planMode, thinkMode: thinkMode, verbs: settings.verbs, bgAgents: bgAgents, shellJobs: shellJobs, mainLane: mainLane, mainServing: servingModelFor(settings, session.currentModel()), maxRunning: bg.limits().running, onBackground: onBackground, tasks: tasks, planNow: planLive ? Date.now() : lastTurnEndRef.current, onSubmit: onSubmit, onQueue: onQueue, onSteer: onSteer, pending: pending, nextSteps: nextSteps ?? undefined, onPickNext: onPickNext, onDismissNext: onDismissNext, agents: bgAgents, onAgentMessage: onAgentMessage, conversations: convs, switcher: { focused: switcher.focused, sel: Math.max(0, convs.findIndex((c) => c.id === switcher.sel)), open: openConv }, onSwitcher: onSwitcher, onFocusSwitcher: onFocusSwitcher, conversationPane: conversationPane, onSendTo: onSendTo, actOffer: active ? actNowOffer(actRef.current, Date.now(), { thinking: thinkMode !== "off" }) : null, onActNow: onActNow, finder: finder, onOpenFinder: onOpenFinder, onEditQueued: popQueued, onDropQueued: onDropQueued, onInterrupt: onInterrupt, onExpand: onExpand, onCycleMode: onCycleMode, onCycleContext: onCycleContext, opMode: opMode, rcConnected: rcConnected, rcActive: rcActive, caffeinated: caffeinated, approval: approval, question: question, modelPicker: modelPicker, secretPrompt: secretPrompt, planExitPicker: planExitPicker, artifactsPicker: artifactsPicker, sessionsPicker: sessionsPicker, onApprovalDecide: (allow, always) => {
2703
3599
  const cur = approval;
2704
3600
  if (cur)
2705
3601
  settleApproval(cur.id, allow, always); // first-wins with any remote follower answer