@0perator/operator 0.1.351 → 0.1.353

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/acp/agent.js +2 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +54 -1
  4. package/dist/autonomy/headless.js +2 -0
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1073 -177
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +444 -76
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +66 -19
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +14 -12
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/owner-act.js +52 -0
  27. package/dist/engine/verify-gate.js +52 -0
  28. package/dist/flywheel/processor.js +3 -1
  29. package/dist/flywheel/srft.js +8 -4
  30. package/dist/hooks/index.js +12 -8
  31. package/dist/mcp/index.js +9 -4
  32. package/dist/permissions/index.js +32 -11
  33. package/dist/permissions/modes.js +42 -0
  34. package/dist/permissions/plan-review.js +100 -0
  35. package/dist/permissions/policy.js +16 -5
  36. package/dist/permissions/signature.js +8 -3
  37. package/dist/remote/safe-commands.js +1 -1
  38. package/dist/router/read-rates.js +152 -0
  39. package/dist/selfimprove/backfill.js +174 -0
  40. package/dist/selfimprove/index.js +146 -57
  41. package/dist/selfimprove/lessons.js +429 -0
  42. package/dist/selfimprove/sync.js +58 -0
  43. package/dist/session.js +362 -33
  44. package/dist/skills/finder.js +219 -0
  45. package/dist/toolchain/toolchain.py +528 -112
  46. package/dist/tools/deferred.js +28 -18
  47. package/dist/tools/executor.js +7 -3
  48. package/dist/tools/registry.js +68 -7
  49. package/dist/tools/result-cap.js +1 -1
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
@@ -0,0 +1,44 @@
1
+ // The cold-read forecast (TUI plan #10): at the moment of choice — /model, a finished compaction, a gateway fallback,
2
+ // a route change — say what the next request may have to read, while the owner can still change course. "May … up
3
+ // to": a model switched back to can still hold the prefix, and so can llama.cpp's host-RAM cache. The time is shown
4
+ // only from THIS process's own measured cold read on that model, at half the forecast depth or deeper (prefill slows
5
+ // with depth), and it is never drawn as a bar. Otherwise the line gives the size alone.
6
+ import { fitSegments, seg } from "./fit.js";
7
+ import { fmtElapsed, fmtTok } from "./format.js";
8
+ /** A cold read this small says little about a deep one. */
9
+ export const COLD_SAMPLE_MIN = 4096;
10
+ const KEEP = 8;
11
+ /** Record one measured read: only a cold one (nothing cached) of COLD_SAMPLE_MIN fresh tokens or more counts. */
12
+ export function noteColdRead(store, model, r, at = Date.now()) {
13
+ if (r.cache !== 0 || r.fresh < COLD_SAMPLE_MIN || r.elapsedMs <= 0)
14
+ return;
15
+ const list = [...(store.get(model) ?? []), { depth: r.fresh, rate: r.fresh / (r.elapsedMs / 1000), at }];
16
+ store.set(model, list.slice(-KEEP));
17
+ }
18
+ /** The rate to forecast `tokens` with: the newest measured cold read at half that depth or deeper, else none. */
19
+ export function forecastRate(store, model, tokens) {
20
+ return [...(store.get(model) ?? [])].reverse().find((s) => s.depth >= tokens / 2);
21
+ }
22
+ export function forecast(store, model, tokens) {
23
+ const s = forecastRate(store, model, tokens);
24
+ return s ? { model, tokens, ms: (tokens / s.rate) * 1000, rate: Math.round(s.rate) } : { model, tokens };
25
+ }
26
+ /** The Static line under /model: "the next message may re-read up to ~60.1k tokens on cortana (~3m 50s at its last
27
+ * measured 261 tok/s)". The parenthetical shortens below 100 cols and leaves below 60. */
28
+ export function forecastLine(f, cols) {
29
+ const head = `the next message may re-read up to ~${fmtTok(f.tokens)} tokens on ${f.model}`;
30
+ if (f.ms === undefined)
31
+ return fitSegments([seg(head)], cols);
32
+ const at = `~${fmtElapsed(f.ms)}`;
33
+ return fitSegments([seg(head), seg([`(${at} at its last measured ${f.rate} tok/s)`, `(${at})`], 2)], cols, { sep: " " });
34
+ }
35
+ /** The tail on the compaction receipt: "the next round reads up to ~42.4k fresh (~2m 40s at 261 tok/s)". */
36
+ export function forecastTail(f) {
37
+ return `the next round reads up to ~${fmtTok(f.tokens)} fresh${f.ms !== undefined ? ` (~${fmtElapsed(f.ms)} at ${f.rate} tok/s)` : ""}`;
38
+ }
39
+ /** The phase line's segments between Enter and the server's first progress chunk; the measured read line replaces them. */
40
+ export function expectSegs(f) {
41
+ return f.ms !== undefined
42
+ ? [`expect up to ~${fmtTok(f.tokens)} new · ~${fmtElapsed(f.ms)} at ${f.model}'s last measured ${f.rate} tok/s`, `expect up to ~${fmtTok(f.tokens)} new · ~${fmtElapsed(f.ms)}`, `expect ~${fmtTok(f.tokens)} new`]
43
+ : [`expect up to ~${fmtTok(f.tokens)} new to read on ${f.model}`, `expect ~${fmtTok(f.tokens)} new`];
44
+ }
@@ -0,0 +1,119 @@
1
+ // The measured read line (TUI plan #1). While llama.cpp reads the prompt it sends prompt_progress {total, cache,
2
+ // processed, time_ms} after every batch; the shell used to keep only processed/total — and processed INCLUDES the cached
3
+ // prefix, so a warm read jumped to ~97% and a cold one gave no sense of speed. Every number here is the server's own:
4
+ // new = total − cache, done = processed − cache, the rate is Δdone over the server's clock (time_ms; the shell's clock
5
+ // only when a server omits it), and the ETA is recomputed per chunk, coarsened, and hidden before a rate exists.
6
+ import { cellWidth } from "./StatusRule.js";
7
+ import { fitSegments, seg } from "./fit.js";
8
+ import { fmtElapsed, fmtTok } from "./format.js";
9
+ const RING_MAX = 64;
10
+ const RATE_WINDOW_MS = 3000;
11
+ /** Add one chunk. A chunk whose total changed, or whose processed count went back, is a new request: the ring restarts. */
12
+ export function pushSample(ring, s) {
13
+ const last = ring[ring.length - 1];
14
+ if (!last || last.total !== s.total || s.processed < last.processed)
15
+ return [s];
16
+ const next = [...ring, s];
17
+ return next.length > RING_MAX ? next.slice(next.length - RING_MAX) : next;
18
+ }
19
+ function clock(a, b) {
20
+ return a.timeMs !== undefined && b.timeMs !== undefined ? [a.timeMs, b.timeMs] : [a.at, b.at];
21
+ }
22
+ const ETA_MIN_MS = 2500; // under this the read is all but done, and a floored "~5s left" would contradict its own count
23
+ function coarsen(ms) {
24
+ const s = ms / 1000;
25
+ const step = s < 60 ? 5 : 10;
26
+ return Math.max(step, Math.ceil(s / step) * step) * 1000;
27
+ }
28
+ /** Stats for the current request's ring. `origin` is when the request started, for a server that sends no time_ms. */
29
+ export function readStats(ring, origin) {
30
+ const last = ring[ring.length - 1];
31
+ if (!last || last.total <= 0)
32
+ return undefined;
33
+ const cache = Math.min(last.cache, last.total);
34
+ const fresh = last.total - cache;
35
+ const done = Math.max(0, Math.min(fresh, last.processed - cache));
36
+ let rate;
37
+ for (let i = ring.length - 2; i >= 0; i--) {
38
+ const [t0, t1] = clock(ring[i], last);
39
+ if (t1 - t0 < RATE_WINDOW_MS)
40
+ continue;
41
+ const gained = (last.processed - ring[i].processed);
42
+ if (gained > 0)
43
+ rate = gained / ((t1 - t0) / 1000);
44
+ break;
45
+ }
46
+ const left = Math.max(0, last.total - last.processed);
47
+ const leftMs = rate && left > 0 ? (left / rate) * 1000 : undefined;
48
+ const etaMs = leftMs !== undefined && leftMs >= ETA_MIN_MS ? coarsen(leftMs) : undefined;
49
+ const elapsedMs = last.timeMs ?? Math.max(0, last.at - (origin ?? ring[0].at));
50
+ return { total: last.total, cache, fresh, done, fraction: fresh > 0 ? done / fresh : 1, rate, etaMs, elapsedMs, complete: last.processed >= last.total };
51
+ }
52
+ function fmtEta(ms) {
53
+ const s = Math.round(ms / 1000);
54
+ if (s < 60)
55
+ return `${s}s`;
56
+ const r = s % 60;
57
+ return `${Math.floor(s / 60)}m${r ? ` ${r}s` : ""}`;
58
+ }
59
+ // The read meter has its own motion, unlike the compaction bar's ▰▱ (James, 11/04: "different than our compacting
60
+ // animation and unique"): braille cells fill like lines on a page — the same language as the read tool's glyph — and the
61
+ // cell at the head of the measured fill slowly writes itself in. The fill is measured; only the head cell moves.
62
+ const FULL = "⣿";
63
+ const EMPTY = "⣀";
64
+ const HEAD = ["⣀", "⣄", "⣤", "⣦", "⣶", "⣷"];
65
+ const HEAD_TICKS = 3; // shared-clock ticks per head step (~360 ms): calm, not a spinner
66
+ export function readMeter(fraction, width = 8, frame = 0) {
67
+ const f = Math.max(0, Math.min(1, fraction));
68
+ const full = Math.floor(f * width);
69
+ if (full >= width)
70
+ return FULL.repeat(width);
71
+ return FULL.repeat(full) + HEAD[Math.floor(frame / HEAD_TICKS) % HEAD.length] + EMPTY.repeat(width - full - 1);
72
+ }
73
+ const METER_MIN_COLS = 100;
74
+ /** The line under the spinner while the server reads: the meter (≥100 cols, and only when everything else fits) and
75
+ * the fitted text. Drop order as cols shrink: meter → the cache note → the rate → "of N new" → "esc to interrupt". */
76
+ export function readLine(st, cols, opts = {}) {
77
+ const segs = [];
78
+ if (st.cache > 0)
79
+ segs.push(seg(`reused ${fmtTok(st.cache)} cached`, 4));
80
+ if (st.complete) { // the whole prompt is read: say so, not "reading 30.5k of 30.5k" (review F8)
81
+ const read = `read ${fmtTok(st.fresh)} new`;
82
+ segs.push(seg(st.fresh > 0 ? [`${read} in ${fmtElapsed(st.elapsedMs)}`, read] : "nothing new to read", 2, true));
83
+ segs.push(seg(["waiting for the first token", "waiting"], 3, true));
84
+ }
85
+ else {
86
+ segs.push(seg([`reading ${fmtTok(st.done)} of ${fmtTok(st.fresh)} new`, `reading ${fmtTok(st.done)}/${fmtTok(st.fresh)}`], 2, true));
87
+ if (st.rate)
88
+ segs.push(seg(`${Math.round(st.rate)} tok/s`, 3));
89
+ if (st.etaMs !== undefined)
90
+ segs.push(seg(`~${fmtEta(st.etaMs)} left`));
91
+ }
92
+ if (st.cache === 0 && opts.model)
93
+ segs.push(seg(`nothing cached on ${opts.model}`, 4));
94
+ segs.push(...(opts.tail ?? [seg(["esc to interrupt", "esc"], 1, true)]));
95
+ if (cols >= METER_MIN_COLS) {
96
+ const meter = readMeter(st.fraction, 8, opts.frame ?? 0);
97
+ const lead = ` ${meter} `;
98
+ const unfitted = lead + segs.map((s) => s.forms[0]).join(" · ");
99
+ if (cellWidth(unfitted) <= cols - 1)
100
+ return { meter, text: fitSegments(segs, cols, { lead }).slice(lead.length) };
101
+ }
102
+ return { text: fitSegments(segs, cols, { lead: " " }).slice(2) };
103
+ }
104
+ const RATE_MIN_FRESH = 2048; // one llama.cpp batch
105
+ /** Reads shorter than this settle no receipt: the live line already said everything worth saying. */
106
+ export const RECEIPT_MIN_MS = 10_000;
107
+ /** The one dim line that settles into scrollback at the first token after a long read. */
108
+ export function readReceipt(st, cols, opts) {
109
+ const secs = st.elapsedMs / 1000;
110
+ // Under one batch of fresh tokens the server's clock is mostly restoring the cached prefix (live 11/04: "148 new
111
+ // tokens in 12s"), so an average over them would read as a 12 tok/s server. The time and the cache note say it.
112
+ const avg = secs > 0 && st.fresh >= RATE_MIN_FRESH ? Math.round(st.fresh / secs) : 0;
113
+ const head = `read ${fmtTok(st.fresh)} new tokens in ${fmtElapsed(st.elapsedMs)}`;
114
+ return fitSegments([
115
+ seg(avg ? [`${head} (${avg} tok/s)`, head] : head, 1, true),
116
+ seg(st.cache > 0 ? `${fmtTok(st.cache)} reused from cache` : opts.model ? `nothing was cached on ${opts.model}` : "nothing was cached", 3),
117
+ seg(`first token at ${fmtElapsed(opts.firstTokenMs)}`, 2),
118
+ ], cols, { lead: " ▸ " });
119
+ }
@@ -0,0 +1,62 @@
1
+ // A finished sub-agent as ONE line (TUI plan #4). The old "done" path printed a 500-char dump — often the raw partial-
2
+ // report header written for the model — and the wake turn then printed every paragraph of every queued report as its
3
+ // own "⤷" line. Now: who, how it ended (and who stopped it), verify badge, what it wrote or gathered, and the first
4
+ // sentence of its report; the full text is one command away (/agents <name> report, or ctrl+o while it is the newest
5
+ // collapsed item). Static, but still fitted: the headline drops first, then the ledger, the verify badge and the
6
+ // duration; glyph · name · outcome · hint stay.
7
+ import { fitSegments, seg } from "./fit.js";
8
+ import { fmtElapsed } from "./format.js";
9
+ export function reportTone(a) {
10
+ if (a.endKind === "failed" || a.endKind === "error")
11
+ return "error";
12
+ if (a.endKind === "done" || (!a.endKind && a.status === "idle"))
13
+ return "done";
14
+ return "stopped";
15
+ }
16
+ const GLYPH = { done: "⤷", stopped: "■", error: "✗" };
17
+ /** The command that appends this agent's full report. */
18
+ export function reportCommand(a) {
19
+ return `/agents ${(a.name ?? a.id).toLowerCase()} report`;
20
+ }
21
+ function outcome(a) {
22
+ const dur = a.durationMs != null ? fmtElapsed(a.durationMs) : undefined;
23
+ const rounds = a.round ? ` after ${a.round} round${a.round === 1 ? "" : "s"}` : "";
24
+ switch (a.endKind) {
25
+ case "stopped": {
26
+ const why = a.endReason ?? "stopped";
27
+ return [...new Set([`${why}${rounds}`, why, why.replace(/ \(stop_agent\)$/, ""), "stopped"])];
28
+ }
29
+ case "stalled": return [`${a.endReason ?? "stalled"}${rounds}`, "stalled"];
30
+ case "engine": return [`stopped by the engine: ${a.endReason ?? "no progress"}`, "stopped by the engine"];
31
+ case "failed":
32
+ case "error": return [a.endReason ?? "errored", "errored"];
33
+ default: return dur ? [`done in ${dur}`, "done"] : ["done"];
34
+ }
35
+ }
36
+ function ledger(a) {
37
+ if (a.written?.length)
38
+ return `wrote ${a.written.slice(-2).map((p) => p.split("/").pop()).join(", ")}${a.written.length > 2 ? ` +${a.written.length - 2}` : ""}`;
39
+ return a.endKind !== "done" && a.headline?.startsWith("partial:") ? a.headline : undefined;
40
+ }
41
+ /** The fitted line and where its parts sit, so the renderer can color the glyph, the name and the hint. */
42
+ export function reportLine(a, cols) {
43
+ const tone = reportTone(a);
44
+ const name = a.name ?? a.id;
45
+ // The exact command, never a bare "ctrl+o": ctrl+o walks newest first, so on an older line it reaches a newer item.
46
+ const hint = reportCommand(a);
47
+ const segs = [
48
+ seg([`${name.padEnd(6)} ${a.title ?? "sub-agent"}`, name], 2.5, true),
49
+ seg(outcome(a), 1, true),
50
+ ...(a.verified === true ? [seg("✓ verified", 3)] : a.verified === false ? [seg("✗ unverified", 3)] : []),
51
+ ...(ledger(a) ? [seg(ledger(a), 4)] : []),
52
+ ...(tone === "done" && a.headline ? [seg(`"${a.headline}"`, 5)] : []),
53
+ seg([hint, "ctrl+o"], 0.5, true), // the outcome's detail gives way before the command does
54
+ ];
55
+ const line = fitSegments(segs, cols, { lead: `${GLYPH[tone]} ` });
56
+ const shown = line.endsWith(hint) ? hint : line.endsWith("ctrl+o") ? "ctrl+o" : "";
57
+ return { tone, line, hint: shown };
58
+ }
59
+ /** The wake turn's one hand-off line, instead of one line per paragraph of every report. */
60
+ export function deliveredLine(owners, model, cols) {
61
+ return fitSegments([seg(`delivered to ${model}: ${owners.join(" · ")}`)], cols, { lead: "⤷ " });
62
+ }
@@ -16,7 +16,7 @@ export const SLASH_COMMANDS = [
16
16
  { name: "remote", description: "remote control: let a follower attach and drive this session", args: "[on|off]" },
17
17
  { name: "pair", description: "pair a phone to drive this session — shows a QR for the Operator app (end-to-end encrypted)" },
18
18
  { name: "plan", description: "plan mode: read-only research + propose a plan (/plan again executes)" },
19
- { name: "mode", description: "set operating mode: plan · manual · autonomous", args: "[plan|manual|auto]" },
19
+ { name: "mode", description: "set operating mode: autonomous · manual · plan · gated", args: "[auto|manual|plan|gated]" },
20
20
  { name: "think", description: "toggle extended reasoning (think before answering)" },
21
21
  { name: "ultrathink", description: "toggle deep, exhaustive reasoning for hard problems" },
22
22
  { name: "agents", description: "detailed sub-agent status: running/queued/done/errored + metrics" },
package/dist/ui/theme.js CHANGED
@@ -19,6 +19,7 @@ const PALETTE = {
19
19
  success: { hex: "#5fd38a", ansi: "green", hc: "greenBright" }, // done / verified
20
20
  error: { hex: "#ff6b6b", ansi: "red", hc: "redBright" }, // failed / unverified
21
21
  warn: { hex: "#e8c14d", ansi: "yellow", hc: "yellowBright" }, // malformed / caution
22
+ blocked: { hex: "#c9a25a", ansi: "yellow", hc: "yellowBright" }, // muted amber: a call the engine refused (⊘) — not a failure, not a success
22
23
  running: { hex: "#e8a33d", ansi: "yellow", hc: "yellowBright" }, // in-flight amber (tool running, star heartbeat)
23
24
  starBright: { hex: "#ffe2a0", ansi: "yellowBright", hc: "whiteBright" }, // the star's bright burst
24
25
  textBright: { hex: "#ffffff", ansi: "whiteBright", hc: "whiteBright" }, // emphasized foreground
@@ -0,0 +1,72 @@
1
+ // The shell's turn order (cli.tsx). One turn at a time: a turn asked for while a turn or a compaction runs waits in the
2
+ // pending list as an after-turn message — never a second Session.send, which threw "in flight", lost the text and marked
3
+ // the shell idle under the running turn (review F2). When a turn or a compaction ends the drain runs what waited:
4
+ // staged commands one by one, each on its own, then one text turn with the steers the turn never reached and the
5
+ // after-turn messages. A sub-agent report, or a job notice in wake mode, starts a turn only when nothing waits;
6
+ // otherwise it rides on the next. What a compaction was started FOR ("compact, then continue", /model's compact-first)
7
+ // is its follow-up: it runs when the compaction ends, before the drain can start anything — never chained on the
8
+ // promise. Free of React and I/O: the shell's refs come in as `fx`, so the order is tested without a TTY.
9
+ import { drainPlan } from "./pending.js";
10
+ export function createTurnFlow(fx) {
11
+ let draining = false; // a staged /compact ends in its own drain call: that one must not run anything
12
+ let followUp;
13
+ const flow = {
14
+ send: (text, opts = {}) => {
15
+ if (fx.idle()) {
16
+ fx.start(text, opts);
17
+ return;
18
+ }
19
+ if (!opts.wake && text)
20
+ fx.setPending([...fx.pending(), { kind: "after", text }]);
21
+ },
22
+ drain: () => {
23
+ if (draining)
24
+ return;
25
+ const { commands, text } = drainPlan(fx.pending());
26
+ if (!commands.length && !text) {
27
+ flow.wake();
28
+ return;
29
+ }
30
+ fx.setPending([]);
31
+ draining = true;
32
+ void (async () => {
33
+ try {
34
+ for (const c of commands)
35
+ await fx.command(c);
36
+ }
37
+ finally {
38
+ draining = false;
39
+ }
40
+ // What was typed while the commands ran waits behind the text the turn left, and is drained with it — it used to
41
+ // sit on screen unsent, blocking every wake (review F4). A command that started a turn of its own
42
+ // (/deep-research) keeps both for after that turn, whose drain sends them; never a steer into it.
43
+ const typed = fx.pending();
44
+ if (typed.length || !fx.idle()) {
45
+ fx.setPending([...(text ? [{ kind: "after", text }] : []), ...typed]);
46
+ if (fx.idle())
47
+ flow.drain();
48
+ return;
49
+ }
50
+ if (text)
51
+ fx.submit(text);
52
+ else
53
+ flow.wake();
54
+ })();
55
+ },
56
+ wake: () => {
57
+ if (!fx.wakeDue())
58
+ return;
59
+ if (!fx.idle() || fx.pending().length)
60
+ return;
61
+ flow.send("", { wake: true });
62
+ },
63
+ afterCompaction: (then) => { followUp = then; },
64
+ compacted: () => {
65
+ const then = followUp;
66
+ followUp = undefined;
67
+ then?.();
68
+ flow.drain();
69
+ },
70
+ };
71
+ return flow;
72
+ }
@@ -0,0 +1,121 @@
1
+ // Where a turn's time went (TUI plan #6). An interrupted turn used to end on "⎋ interrupted — output above kept" with
2
+ // its numbers thrown away, and a 33-minute turn closed on one line with nothing about whether the half hour went to
3
+ // reading, generating, tools or a loop. Every part is measured: reading from each round's last prompt_progress time_ms
4
+ // (the summed onCacheStats promptMs is sparse — llama.cpp omits timings on many tool rounds), tools from onToolBatch's
5
+ // duration, generating in the shell from a round's first chunk to its end; "other" is the named remainder, so the parts
6
+ // always sum to the wall time. Pure: cli.tsx feeds it from the handlers it already has.
7
+ import { fitSegments, seg } from "./fit.js";
8
+ import { cellWidth } from "./StatusRule.js";
9
+ import { fmtElapsed, fmtTok } from "./format.js";
10
+ /** A read of this many fresh tokens with nothing cached counts as a cold read (the cacheBustNotice rule). */
11
+ export const COLD_READ_MIN = 8000;
12
+ export function createLedger() {
13
+ return { readMs: 0, genMs: 0, toolMs: 0, waitMs: 0, compactMs: 0, fresh: 0, cached: 0, coldReads: 0, coldTokens: 0, wrote: false, roundRead: false };
14
+ }
15
+ /** A round's read finished (its first token, or the end of a round that streamed nothing): count it once. `cache` is
16
+ * NaN when the server reported no cache numbers at all — never counted as a cold read (unknown is not zero). */
17
+ export function noteRead(l, r) {
18
+ if (l.roundRead)
19
+ return;
20
+ l.roundRead = true;
21
+ l.readMs += Math.max(0, r.ms);
22
+ l.fresh += r.fresh;
23
+ l.cached += Number.isFinite(r.cache) ? r.cache : 0;
24
+ if (r.cache === 0 && r.fresh >= COLD_READ_MIN) {
25
+ l.coldReads += 1;
26
+ l.coldTokens += r.fresh;
27
+ }
28
+ }
29
+ export function noteGenStart(l, now, content) {
30
+ if (content)
31
+ l.wrote = true;
32
+ if (l.genStart === undefined)
33
+ l.genStart = now;
34
+ }
35
+ /** The round's stream ended (tools start, the batch settles, or the turn ends). */
36
+ export function noteGenEnd(l, now) {
37
+ if (l.genStart !== undefined) {
38
+ l.genMs += Math.max(0, now - l.genStart);
39
+ l.genStart = undefined;
40
+ }
41
+ }
42
+ /** A new round: its read has not been counted yet. */
43
+ export function noteRound(l) {
44
+ l.roundRead = false;
45
+ }
46
+ export function noteTools(l, ms) {
47
+ l.toolMs += Math.max(0, ms);
48
+ }
49
+ export function noteWait(l, ms) {
50
+ l.waitMs += Math.max(0, ms);
51
+ }
52
+ export function noteCompaction(l, ms) {
53
+ l.compactMs += Math.max(0, ms);
54
+ }
55
+ /** The parts, summing exactly to `wallMs`: when the measured parts overrun the wall (clocks from two machines), the
56
+ * shell-measured generating time gives way first; "other" is never negative. */
57
+ export function ledgerParts(l, wallMs) {
58
+ let left = wallMs;
59
+ const take = (ms) => { const v = Math.max(0, Math.min(ms, left)); left -= v; return v; };
60
+ const readMs = take(l.readMs), toolMs = take(l.toolMs), compactMs = take(l.compactMs), waitMs = take(l.waitMs), genMs = take(l.genMs);
61
+ return { readMs, genMs, toolMs, waitMs, compactMs, otherMs: left };
62
+ }
63
+ function readNote(l) {
64
+ if (l.coldReads)
65
+ return `${l.coldReads} cold read${l.coldReads === 1 ? "" : "s"}: ${fmtTok(l.coldTokens)}`;
66
+ return l.cached > 0 ? `${fmtTok(l.fresh)} new, ${fmtTok(l.cached)} reused` : `${fmtTok(l.fresh)} new, nothing cached`;
67
+ }
68
+ const SPLIT_COLS = 60;
69
+ /** The card's "time" rows: parts largest first (anything under a second left out), the parentheticals drop below 100
70
+ * cols, and below 60 cols the ledger splits over two lines. `inner` is the width inside the card's border. */
71
+ export function ledgerLines(p, l, inner) {
72
+ const parts = [];
73
+ const gen = l.wrote ? "generating" : "thinking";
74
+ if (p.genMs >= 1000)
75
+ parts.push([p.genMs, seg(`${gen} ${fmtElapsed(p.genMs)}`)]);
76
+ if (p.readMs >= 1000)
77
+ parts.push([p.readMs, seg(inner >= 100 && (l.fresh || l.coldReads) ? [`reading ${fmtElapsed(p.readMs)} (${readNote(l)})`, `reading ${fmtElapsed(p.readMs)}`] : `reading ${fmtElapsed(p.readMs)}`, 2, true)]);
78
+ if (p.toolMs >= 1000)
79
+ parts.push([p.toolMs, seg(`tools ${fmtElapsed(p.toolMs)}`)]);
80
+ if (p.compactMs >= 1000)
81
+ parts.push([p.compactMs, seg(`compacting ${fmtElapsed(p.compactMs)}`)]);
82
+ if (p.waitMs >= 1000)
83
+ parts.push([p.waitMs, seg(`waiting ${fmtElapsed(p.waitMs)}`)]);
84
+ if (p.otherMs >= 1000)
85
+ parts.push([p.otherMs, seg(`other ${fmtElapsed(p.otherMs)}`)]);
86
+ const segs = parts.sort((a, b) => b[0] - a[0]).map(([, s]) => s);
87
+ if (!segs.length)
88
+ return [];
89
+ if (inner < SPLIT_COLS && segs.length > 2) {
90
+ return [fitSegments(segs.slice(0, 2), inner, { lead: "time " }), fitSegments(segs.slice(2), inner, { lead: " " })];
91
+ }
92
+ return [fitSegments(segs, inner, { lead: "time " })];
93
+ }
94
+ /** The interrupted receipt: when, where the time went (the read in flight included), and that the output stayed.
95
+ * Narrowing is two-phase: every parenthetical goes first, then the smallest parts; the floor is
96
+ * "interrupted at 7m 43s · output above kept". */
97
+ export function interruptedLine(wallMs, p, l, tokens, cols) {
98
+ const gen = l.wrote ? "generating" : "thinking";
99
+ const parts = [];
100
+ if (p.readMs >= 1000)
101
+ parts.push({ ms: p.readMs, full: l.fresh ? `reading ${fmtElapsed(p.readMs)} (${readNote({ ...l, coldReads: 0, coldTokens: 0 })})` : `reading ${fmtElapsed(p.readMs)}`, short: `reading ${fmtElapsed(p.readMs)}` });
102
+ if (p.genMs >= 1000)
103
+ parts.push({ ms: p.genMs, full: tokens ? `${gen} ${fmtElapsed(p.genMs)} (${fmtTok(tokens)} tok)` : `${gen} ${fmtElapsed(p.genMs)}`, short: `${gen} ${fmtElapsed(p.genMs)}` });
104
+ if (p.toolMs >= 1000)
105
+ parts.push({ ms: p.toolMs, full: `tools ${fmtElapsed(p.toolMs)}`, short: `tools ${fmtElapsed(p.toolMs)}` });
106
+ if (p.compactMs >= 1000)
107
+ parts.push({ ms: p.compactMs, full: `compacting ${fmtElapsed(p.compactMs)}`, short: `compacting ${fmtElapsed(p.compactMs)}` });
108
+ if (p.waitMs >= 1000)
109
+ parts.push({ ms: p.waitMs, full: `waiting ${fmtElapsed(p.waitMs)}`, short: `waiting ${fmtElapsed(p.waitMs)}` });
110
+ parts.sort((a, b) => b.ms - a.ms);
111
+ const head = seg(`interrupted at ${fmtElapsed(wallMs)}`);
112
+ const tail = seg("output above kept");
113
+ const full = `⎋ ${[head.forms[0], ...parts.map((x) => x.full), tail.forms[0]].join(" · ")}`;
114
+ if (cellWidth(full) <= cols - 1)
115
+ return full;
116
+ return fitSegments([head, ...parts.map((x, i) => seg(x.short, 10 + i)), tail], cols, { lead: "⎋ " });
117
+ }
118
+ /** The 'repetition' stop's line: how much the last round streamed, and for how long, before the check cut it. */
119
+ export function repetitionLine(chars, ms, inner) {
120
+ return fitSegments([seg(`the last round streamed ${fmtTok(chars)} chars over ${fmtElapsed(ms)}`), seg("before the repetition check stopped it", 2)], inner, { sep: " " });
121
+ }
@@ -0,0 +1,11 @@
1
+ // A turn's handlers stop at its end (review F14). esc ends the turn at once, but the tool in flight keeps running and the
2
+ // engine still reports its batch when it returns — seconds later, into an idle TUI (left stuck in "thinking") or into
3
+ // the next turn, whose live rows, read ring, ledger and fold it would reset. Each turn's handlers carry its id.
4
+ /** `handlers` with every function made a no-op (returning undefined) unless `current()` is still `turn`. */
5
+ export function turnScoped(handlers, turn, current) {
6
+ const out = {};
7
+ for (const [k, v] of Object.entries(handlers)) {
8
+ out[k] = typeof v === "function" ? (...a) => (current() === turn ? v(...a) : undefined) : v;
9
+ }
10
+ return out;
11
+ }
@@ -8,6 +8,7 @@ const KNOWN = new Set([
8
8
  "artifacts", "sessions", "skills", "skill", "allow", "caffeinate", "caffeine", "deep-research", "deepresearch",
9
9
  "research", "pair",
10
10
  ]);
11
+ export const KNOWN_COMMANDS = KNOWN;
11
12
  export function isSlashCommand(text) {
12
13
  const t = text.trim();
13
14
  if (!t.startsWith("/") || t.includes("\n"))
@@ -15,3 +16,20 @@ export function isSlashCommand(text) {
15
16
  const cmd = t.slice(1).split(/\s+/)[0];
16
17
  return KNOWN.has(cmd);
17
18
  }
19
+ /** When a command typed mid-turn applies (TUI A3.2). "now": read-only or self-contained — it runs at once and the turn
20
+ * keeps going. "next": a setting the engine reads per request or per tool call — it applies at once, from the turn's
21
+ * next step. "after": it would swap the model, the conversation, the tool surface or the session under a running turn
22
+ * — it is staged and runs on its own when the turn ends. Every KNOWN command has a class; a new command must pick one. */
23
+ export const MIDTURN = {
24
+ help: "now", agents: "now", jobs: "now", stats: "now", endpoints: "now", audit: "now", memory: "now", skills: "now",
25
+ skill: "now", whoami: "now", monitor: "now", remember: "now", caffeinate: "now", caffeine: "now", bg: "now", dashboard: "now",
26
+ think: "next", ultrathink: "next", context: "next", ctx: "next", mode: "next", plan: "next", allow: "next",
27
+ model: "after", new: "after", compact: "after", clear: "after", route: "after", mcp: "after", login: "after", logout: "after",
28
+ remote: "after", remotecontrol: "after", rc: "after", pair: "after", sessions: "after", artifacts: "after", services: "after",
29
+ "deep-research": "after", deepresearch: "after", research: "after", exit: "after", quit: "after",
30
+ };
31
+ /** The mid-turn class of a slash command line (its first token); "after" for anything unclassified — the safe side. */
32
+ export function midTurnClass(text) {
33
+ const cmd = text.trim().slice(1).split(/\s+/)[0] ?? "";
34
+ return MIDTURN[cmd] ?? "after";
35
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@0perator/operator",
3
- "version": "0.1.351",
3
+ "version": "0.1.353",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "operator": "dist/cli.js",