@0perator/operator 0.1.352 → 0.1.354

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