@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,154 @@
1
+ import { fitSegments, seg } from "./fit.js";
2
+ import { cellWidth } from "./StatusRule.js";
3
+ import { ENGINE_NOTE_PREFIX } from "../engine/continuation.js";
4
+ const live = (a) => a.status === "working" || a.status === "queued";
5
+ const nameOf = (a) => a.name ?? a.id;
6
+ /** "@Nova <text>" → the sub-agent it names and the message, as typed; "@all stop" → every one. Names match whole
7
+ * (multiword ones too, longest first — parseAgentCommand's rule). An agent that already finished still matches, so the
8
+ * shell answers "Vega already finished" instead of handing "@Vega …" to the main model (review F5); a live agent wins a
9
+ * name a finished one had. Null when the @token names no agent at all, so "@src/x.ts" stays a file mention. */
10
+ export function agentMention(text, agents) {
11
+ const t = text.trim();
12
+ if (!t.startsWith("@") || t.includes("\n"))
13
+ return null;
14
+ const body = t.slice(1);
15
+ if (/^all\s+stop$/i.test(body))
16
+ return { target: "all", message: "stop" };
17
+ const lower = body.toLowerCase();
18
+ const names = [...agents.filter(live), ...agents.filter((a) => !live(a))]
19
+ .flatMap((a) => [a.id, a.name].filter((n) => !!n).map((n) => ({ a, n })))
20
+ .sort((x, y) => y.n.length - x.n.length); // stable: same length keeps the live agent first
21
+ const hit = names.find(({ n }) => lower === n.toLowerCase() || lower.startsWith(`${n.toLowerCase()} `));
22
+ return hit ? { target: hit.a, message: body.slice(hit.n.length).trim() } : null;
23
+ }
24
+ /** The @ menu while the draft is a bare "@token" being typed: the live agents whose name or id starts with it, then the
25
+ * "@all stop" row. Null when the draft is not a bare @token, or no live agent exists. */
26
+ export function matchAgentMentions(draft, agents) {
27
+ const m = /^@([\w.-]*)$/.exec(draft);
28
+ if (!m)
29
+ return null;
30
+ const running = agents.filter(live);
31
+ if (!running.length)
32
+ return null;
33
+ const q = m[1].toLowerCase();
34
+ const hits = running.filter((a) => nameOf(a).toLowerCase().startsWith(q) || a.id.toLowerCase().startsWith(q));
35
+ if ("all".startsWith(q))
36
+ hits.push("all");
37
+ return hits.length ? hits : null;
38
+ }
39
+ /** What Tab completes the highlighted @ row to. */
40
+ export function mentionCompletion(m) {
41
+ return m === "all" ? "@all stop" : `@${nameOf(m)} `;
42
+ }
43
+ /** The one-line @ menu, fitted to cols−1: " @ Nova (researcher · round 6) · Atlas (builder · round 3) · @all stop ·
44
+ * ⏎ sends to Nova, no main turn". Narrow: names only, then only the highlighted one. */
45
+ export function mentionMenuLine(matches, sel, cols) {
46
+ const hi = matches[Math.min(Math.max(sel, 0), matches.length - 1)];
47
+ const label = (m, full) => m === "all" ? "@all stop" : `${nameOf(m)}${full ? ` (${[m.title, m.status === "queued" ? "queued" : m.round ? `round ${m.round}` : ""].filter(Boolean).join(" · ")})` : ""}`;
48
+ const mark = (m) => (m === hi ? "▸" : "");
49
+ if (cols < 40)
50
+ return fitSegments([seg(`${mark(hi)}${label(hi, false)}`)], cols, { lead: " @ " });
51
+ const full = matches.map((m) => `${mark(m)}${label(m, true)}`).join(" · ");
52
+ const names = matches.map((m) => `${mark(m)}${label(m, false)}`).join(" · ");
53
+ const list = cols >= 80 && cellWidth(` @ ${full}`) <= cols - 1 ? full : names; // role and round only when they all fit
54
+ return fitSegments([seg(list), ...(hi !== "all" ? [seg(` · ⏎ sends to ${nameOf(hi)}, no main turn`, 1)] : [])], cols, { lead: " @ ", sep: "" });
55
+ }
56
+ export const MAIN = "main";
57
+ /** main first, then every sub-agent with a conversation to show: the live ones, then the finished ones still retained. */
58
+ export function conversationList(agents, retired, hasTranscript) {
59
+ const seen = new Set();
60
+ const out = [{ id: MAIN, label: "main" }];
61
+ for (const a of [...agents, ...[...retired].reverse()]) {
62
+ if (seen.has(a.id) || !hasTranscript(a.id))
63
+ continue;
64
+ seen.add(a.id);
65
+ out.push({ id: a.id, label: a.name ?? a.id, status: a.status });
66
+ }
67
+ return out;
68
+ }
69
+ /** The centre of the mode line. Unfocused: "↓ main · Nova · Atlas" (the open one marked ●). Focused: the highlighted one
70
+ * in brackets and the keys. Fitted to `width`; "" when main is the only conversation. */
71
+ /** A key while the switcher has focus. The selection is a conversation id, never a position: an agent spawned or finished
72
+ * while it has focus moves the list, not the selection (review F13). A selected conversation that left the list counts
73
+ * as main. */
74
+ export function switcherKey(convs, sel, k) {
75
+ if (k === "back")
76
+ return { back: true };
77
+ const at = Math.max(0, convs.findIndex((c) => c.id === sel));
78
+ if (k === "open")
79
+ return { open: convs[at]?.id ?? MAIN };
80
+ const n = Math.max(1, convs.length);
81
+ return { sel: convs[(at + (k === "left" ? n - 1 : 1)) % n]?.id ?? MAIN };
82
+ }
83
+ export function switcherLine(convs, o, width) {
84
+ if (convs.length < 2 || width < 8)
85
+ return "";
86
+ const names = convs.map((c, i) => {
87
+ const open = c.id === o.open ? "●" : "";
88
+ return o.focused && i === o.sel ? `[${open}${c.label}]` : `${open}${c.label}`;
89
+ });
90
+ const segs = o.focused
91
+ ? [seg("◂ "), seg(names.join(" · ")), seg(" ▸"), seg(" · ⏎ open · ↑ back", 1)]
92
+ : [seg("↓ ", 2), seg(names.join(" · "))];
93
+ return fitSegments(segs, width + 1, { sep: "" });
94
+ }
95
+ const oneLine = (s) => s.replace(/\s+/g, " ").trim();
96
+ const argsPreview = (args) => {
97
+ try {
98
+ const o = JSON.parse(args);
99
+ const v = o.path ?? o.file_path ?? o.command ?? o.query ?? o.url ?? o.pattern ?? Object.values(o)[0];
100
+ return typeof v === "string" ? v : JSON.stringify(v ?? "");
101
+ }
102
+ catch {
103
+ return args;
104
+ }
105
+ };
106
+ /** The open conversation's body: exactly `rows` lines (padded), each fitted to cols−1 — the pane keeps one height for
107
+ * as long as it is open (plan ground rule 3), and new lines push old ones off the top. */
108
+ export function transcriptLines(msgs, cols, rows) {
109
+ const lines = [];
110
+ let first = true;
111
+ for (const m of msgs) {
112
+ const text = typeof m.content === "string" ? m.content : "";
113
+ if (m.role === "system")
114
+ continue;
115
+ if (m.role === "user") {
116
+ if (text.startsWith(ENGINE_NOTE_PREFIX))
117
+ lines.push(` · ${oneLine(text.slice(ENGINE_NOTE_PREFIX.length))}`);
118
+ else {
119
+ lines.push(`${first ? "▸ brief" : "❯"} ${oneLine(text)}`);
120
+ first = false;
121
+ }
122
+ }
123
+ else if (m.role === "assistant") {
124
+ if (text.trim())
125
+ lines.push(`⏺ ${oneLine(text)}`);
126
+ for (const c of m.tool_calls ?? [])
127
+ lines.push(`▶ ${c.function?.name ?? "tool"}(${oneLine(argsPreview(c.function?.arguments ?? ""))})`);
128
+ }
129
+ else if (m.role === "tool") {
130
+ const head = text.split("\n").find((l) => l.trim()) ?? "";
131
+ lines.push(` ⤷ ${oneLine(head)}`);
132
+ }
133
+ }
134
+ const tail = lines.slice(-rows).map((l) => fitSegments([seg(l)], cols));
135
+ while (tail.length < rows)
136
+ tail.unshift("");
137
+ return tail;
138
+ }
139
+ /** The pane's header line: who it is, what it is doing, and the keys. */
140
+ export function transcriptHeader(a, cols) {
141
+ const state = a.status === "working" ? "running" : a.status === "queued" ? "queued" : a.status === "idle" ? "done" : "stopped";
142
+ const who = [a.name ?? a.id, a.title, a.model, a.round ? `round ${a.round}` : "", state].filter(Boolean).join(" · ");
143
+ const keys = a.status === "working" || a.status === "queued" ? " · type to message it · ↓ switch" : " · finished, read-only · ↓ switch";
144
+ return fitSegments([seg(`── ${who} ──`), seg(keys, 1)], cols, { sep: "" });
145
+ }
146
+ /** Padding that puts the switcher at the true centre of the mode line when the left side allows it (else right after
147
+ * it), keeping the whole row at cols−1: left · pad · centre · pad · right. */
148
+ export function centreLayout(leftW, centreW, rightW, cols) {
149
+ const total = Math.max(0, cols - 1);
150
+ const ideal = Math.floor((total - centreW) / 2);
151
+ const before = Math.max(1, Math.min(ideal - leftW, total - leftW - centreW - rightW - 1));
152
+ const after = Math.max(1, total - leftW - before - centreW - rightW);
153
+ return { before, after };
154
+ }
@@ -0,0 +1,77 @@
1
+ // The decode readout (TUI plan #13): while the model generates, the phase line says how fast, at what context depth,
2
+ // and — when this session measured the same model shallower — how fast it was there, which names both the cause of a
3
+ // slow stretch (depth) and its lever (/compact). Early repetition gets a calm, informative note (James, 11/04: "make
4
+ // this look less like an error"): no ⚠, no error color, and it never stops anything — the engine's own hard stop and
5
+ // its 16k threshold are untouched. Pure bookkeeping; the shell feeds it, and runs the guard's detector on its tick.
6
+ import { seg } from "./fit.js";
7
+ /** A depth or a length, rounded the way the readout says it: "84k context", "the last 8k chars". */
8
+ const k = (n) => (n < 1000 ? String(Math.round(n)) : `${Math.round(n / 1000)}k`);
9
+ const WINDOW_MS = 5000;
10
+ const MIN_SPAN_MS = 1500;
11
+ export function createDecode() {
12
+ return { samples: [], roundStartTok: 0, history: new Map(), checkedChars: 0, repeatingChars: 0 };
13
+ }
14
+ /** A new round: the window restarts (the previous round's rate is history now). */
15
+ export function decodeRound(d, tok) {
16
+ d.samples = [];
17
+ d.roundStartTok = tok;
18
+ d.roundStartAt = undefined;
19
+ d.checkedChars = 0;
20
+ d.repeatingChars = 0;
21
+ }
22
+ /** The live token count at `now` (≈1 per streamed delta; onTokens corrects it at the round's end). */
23
+ export function noteDecode(d, tok, now) {
24
+ d.roundStartAt ??= now;
25
+ d.samples.push({ t: now, tok });
26
+ while (d.samples.length > 2 && d.samples[1].t <= now - WINDOW_MS)
27
+ d.samples.shift();
28
+ }
29
+ /** Tokens per second over the last ~5 s; undefined until the window spans 1.5 s. */
30
+ export function decodeRate(d) {
31
+ const a = d.samples[0], b = d.samples[d.samples.length - 1];
32
+ if (!a || !b || b.t - a.t < MIN_SPAN_MS)
33
+ return undefined;
34
+ return ((b.tok - a.tok) / (b.t - a.t)) * 1000;
35
+ }
36
+ /** The round ended: keep its average rate against its depth, for this model's comparisons. */
37
+ export function noteRoundRate(d, model, depth, tok, now) {
38
+ if (!depth || d.roundStartAt === undefined)
39
+ return;
40
+ const ms = now - d.roundStartAt, made = tok - d.roundStartTok;
41
+ if (ms < 2000 || made < 20)
42
+ return;
43
+ const list = [...(d.history.get(model) ?? []), { depth, rate: (made / ms) * 1000 }];
44
+ d.history.set(model, list.slice(-16));
45
+ }
46
+ /** The newest finished round of this model at under half the current depth, if this session has one. */
47
+ export function shallower(d, model, depth) {
48
+ return [...(d.history.get(model) ?? [])].reverse().find((h) => h.depth < depth / 2);
49
+ }
50
+ /** Whether to run the repetition check now: every 2k new streamed characters. */
51
+ export function dueCheck(d, chars) {
52
+ if (chars - d.checkedChars < 2000)
53
+ return false;
54
+ d.checkedChars = chars;
55
+ return true;
56
+ }
57
+ /** How much of the tail the check reads — the guard's detector, run early, on at most this much. */
58
+ export const CHECK_TAIL = 8000;
59
+ /** Whether a stream's deltas only approximate its tokens: llama.cpp (the default transport) sends one token per delta;
60
+ * a vendor on the OpenAI or Anthropic wire packs several into one event, so a rate or count from deltas is "≈". */
61
+ export function deltasApprox(transport) {
62
+ return transport !== undefined && transport !== "llama";
63
+ }
64
+ /** The phase line's decode segments, in give-way order: the comparison first, then the depth, then the rate; the
65
+ * repetition note outranks them all and only shortens. `approx` marks a transport whose deltas carry several tokens. */
66
+ export function decodeSegs(v) {
67
+ const out = [];
68
+ if (v.rate !== undefined) {
69
+ const r = `${v.approx ? "≈" : ""}${Math.max(0, Math.round(v.rate))} tok/s`;
70
+ const deep = v.depth ? `${r} at ${k(v.depth)} context` : r;
71
+ const cmp = v.compare && !v.repeatingChars ? `${deep} (${Math.round(v.compare.rate)} tok/s at ${k(v.compare.depth)} earlier this session)` : deep;
72
+ out.push(seg([...new Set([cmp, deep, r])], 4));
73
+ }
74
+ if (v.repeatingChars)
75
+ out.push(seg([`↻ the last ${k(v.repeatingChars)} chars mostly repeat one passage`, "↻ repeating"], 1.5, true));
76
+ return out;
77
+ }
@@ -0,0 +1,17 @@
1
+ /** ctrl+o, the same pure-helper shape as Composer's isBackgroundKey / isContextCycleKey. */
2
+ export function isExpandKey(ch, key) {
3
+ return !!key.ctrl && ch === "o";
4
+ }
5
+ const MAX_COLLAPSED = 50;
6
+ export function pushCollapsed(stack, item) {
7
+ const next = [...stack.filter((c) => !(c.kind === item.kind && c.id === item.id)), item];
8
+ return next.length > MAX_COLLAPSED ? next.slice(next.length - MAX_COLLAPSED) : next;
9
+ }
10
+ /** The newest collapsed item and the stack without it (nothing when the stack is empty). */
11
+ export function popCollapsed(stack) {
12
+ return stack.length ? { item: stack[stack.length - 1], rest: stack.slice(0, -1) } : { rest: stack };
13
+ }
14
+ /** Drop an item expanded some other way (`/agents <name> report`), so ctrl+o does not repeat it. */
15
+ export function dropCollapsed(stack, item) {
16
+ return stack.filter((c) => !(c.kind === item.kind && c.id === item.id));
17
+ }
package/dist/ui/fit.js ADDED
@@ -0,0 +1,40 @@
1
+ // One fitter for every live line (TUI plan, ground rule 2). A line is a list of segments; each segment has a rank and
2
+ // one or more forms (full first, then shorter). While the line is wider than cols−1 cells, the highest-ranked segment
3
+ // that can still give something up steps to its next form, or leaves when it has none left; truncateToWidth(cols−1) is
4
+ // the last guard. cols−1, never cols: a line exactly as wide as the terminal wraps to a second row Ink's height
5
+ // accounting misses, and the whole frame creeps up the screen (StatusRule.ruleFill). Clip a label BEFORE fileLink adds
6
+ // OSC-8 escapes: truncating an escaped string cuts the escape.
7
+ import { cellWidth, truncateToWidth } from "./StatusRule.js";
8
+ /** A segment: one text, or its forms from full to shortest. */
9
+ export function seg(text, rank, keep = false) {
10
+ return { forms: (Array.isArray(text) ? text : [text]).filter((f) => f !== ""), rank, keep };
11
+ }
12
+ export function fitSegments(segs, cols, opts = {}) {
13
+ const lead = opts.lead ?? "";
14
+ const sep = opts.sep ?? " · ";
15
+ const state = segs.filter((s) => s.forms.length).map((s) => ({ s, i: 0, gone: false }));
16
+ const render = () => lead + state.filter((x) => !x.gone).map((x) => x.s.forms[x.i]).join(sep);
17
+ const max = cols - 1;
18
+ let line = render();
19
+ while (cellWidth(line) > max) {
20
+ let pick = -1;
21
+ for (let k = 0; k < state.length; k++) {
22
+ const x = state[k];
23
+ if (x.gone || x.s.rank === undefined)
24
+ continue;
25
+ if (x.i >= x.s.forms.length - 1 && x.s.keep)
26
+ continue;
27
+ if (pick < 0 || x.s.rank >= (state[pick].s.rank ?? 0))
28
+ pick = k;
29
+ }
30
+ if (pick < 0)
31
+ break;
32
+ const x = state[pick];
33
+ if (x.i < x.s.forms.length - 1)
34
+ x.i++;
35
+ else
36
+ x.gone = true;
37
+ line = render();
38
+ }
39
+ return truncateToWidth(line, max);
40
+ }
@@ -0,0 +1,14 @@
1
+ // A line that ends in free text — a message preview, a description — on top of the one fitter (fit.ts): the segments
2
+ // are fitted with the tail's first `tailMin` cells reserved, then the tail is cut at the window. Without it a long
3
+ // preview makes every key hint give way first, even on a wide terminal, before the preview itself is cut.
4
+ import { fitSegments } from "./fit.js";
5
+ import { cellWidth, truncateToWidth } from "./StatusRule.js";
6
+ export function fitWithTail(segs, tail, cols, o = {}) {
7
+ const join = tail ? o.join ?? "" : "";
8
+ const reserve = Math.min(cellWidth(tail), o.tailMin ?? 24) + cellWidth(join);
9
+ const head = fitSegments(segs, Math.max(2, cols - reserve), { lead: o.lead, sep: o.sep });
10
+ if (!tail)
11
+ return truncateToWidth(head, Math.max(0, cols - 1));
12
+ const room = cols - 1 - cellWidth(head) - cellWidth(join);
13
+ return room > 0 ? head + join + truncateToWidth(tail, room) : truncateToWidth(head, Math.max(0, cols - 1));
14
+ }
@@ -0,0 +1,149 @@
1
+ // Folded repeats (TUI plan #3). A model going in circles used to print one settled block per round: the same
2
+ // `✗ $ cmd` and the same three lines of loop-guard text five times over. Here a round that repeats the previous one
3
+ // folds into a single counting line instead — live while it keeps happening, settled once something else happens.
4
+ // • Rounds that were BLOCKED (nothing ran: the engine's report says so) fold on signature — names + stable args.
5
+ // • Rounds that RAN fold on signature (names + stable args, in order) AND result. Results reach onToolBatch after the
6
+ // engine's result guard, which appends `[note: …]` lines carrying counts and swaps a large duplicate for a
7
+ // "byte-identical" stub (engine/loop-guard.ts) — so those notes are stripped first, and the stub counts as a match.
8
+ // Without that rule two identical runs are never byte-identical as received and nothing would ever fold.
9
+ // Pure: cli.tsx owns the tracker in a ref and pushes what this decides. Settled folds are ordinary ToolSteps with
10
+ // `repeat` set, so remote followers parse them as tool steps.
11
+ import { fitSegments, seg } from "./fit.js";
12
+ import { exitCode, fmtElapsed, resultPreview, toolOutcome } from "./format.js";
13
+ const STUB = /^\[note: this result is byte-identical to /;
14
+ /** The result as the tool returned it: the guard's trailing `[note: …]` lines removed. */
15
+ export function stripGuardNotes(result) {
16
+ return result.replace(/\n\n\[note: [^\n]*\](\n\[note: [^\n]*\])*\s*$/, "");
17
+ }
18
+ function stable(v) {
19
+ if (Array.isArray(v))
20
+ return `[${v.map(stable).join(",")}]`;
21
+ if (v && typeof v === "object")
22
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${stable(v[k])}`).join(",")}}`;
23
+ return JSON.stringify(v) ?? "null";
24
+ }
25
+ /** One settled round's fold key, or null when it can't fold (empty, or blocked calls mixed with calls that ran). */
26
+ export function foldKey(events) {
27
+ if (!events.length)
28
+ return null;
29
+ const outcomes = events.map((e) => toolOutcome(e.result, e.refused));
30
+ const sig = events.map((e) => `${e.name}(${stable(e.args)})`).join("|");
31
+ if (outcomes.every((o) => o === "blocked"))
32
+ return { kind: "blocked", sig, results: [], outcome: "blocked" };
33
+ if (outcomes.some((o) => o === "blocked" || o === "cancelled"))
34
+ return null;
35
+ return {
36
+ kind: "ran",
37
+ sig,
38
+ results: events.map((e) => stripGuardNotes(e.result)),
39
+ outcome: outcomes.find((o) => o !== "ok") ?? "ok",
40
+ };
41
+ }
42
+ /** Does `next` repeat `first`? `first` stays the reference for the whole fold, so a later stub still matches it. */
43
+ export function sameRound(first, next) {
44
+ if (first.kind !== next.kind || first.sig !== next.sig)
45
+ return false;
46
+ if (first.kind === "blocked")
47
+ return true;
48
+ return next.results.every((r, i) => r === first.results[i] || STUB.test(r));
49
+ }
50
+ /** Feed one settled round. "fold": it repeated and was absorbed (redraw the live fold line). "push": show it as usual,
51
+ * after pushing `settled` (the fold it ended) when there is one. */
52
+ export function feedFold(t, events, now) {
53
+ const key = foldKey(events);
54
+ if (key && t.fold && sameRound(t.fold.key, key)) {
55
+ t.fold.count++;
56
+ t.fold.lastAt = now;
57
+ return { action: "fold" };
58
+ }
59
+ if (key && !t.fold && t.last && sameRound(t.last.key, key)) {
60
+ t.fold = { key: t.last.key, events: t.last.events, count: 1, firstAt: t.last.at, lastAt: now };
61
+ return { action: "fold" };
62
+ }
63
+ const settled = t.fold;
64
+ t.fold = undefined;
65
+ t.last = key ? { key, events, at: now } : undefined;
66
+ return { action: "push", settled };
67
+ }
68
+ /** End the fold in progress (the turn ended, errored or was interrupted); returns it for pushing. */
69
+ export function settleFold(t) {
70
+ const f = t.fold;
71
+ t.fold = undefined;
72
+ t.last = undefined;
73
+ return f;
74
+ }
75
+ /** The settled fold as one ToolStep: the repeated call, `repeat` times more, over `durationMs`. */
76
+ export function foldStep(f, id) {
77
+ const first = f.events[0];
78
+ const code = first ? exitCode(first.result) : undefined;
79
+ return {
80
+ id, name: first?.name ?? "tool", args: first?.args, status: f.key.outcome === "ok" ? "done" : "error",
81
+ ...(f.key.kind === "blocked" ? { outcome: "blocked" } : {}),
82
+ ...(code !== undefined && code !== 0 ? { exitCode: code } : {}),
83
+ repeat: f.count, durationMs: f.lastAt - f.firstAt,
84
+ ...(f.events.length > 1 ? { summary: `${f.events.length} calls` } : {}),
85
+ };
86
+ }
87
+ /** The fold line, live (`live`: the count changes in place) or settled. One row at cols−1; the time span drops first,
88
+ * then the reason shortens — "↻ blocked 4 more times · loop guard" at 40 cols. */
89
+ export function foldLine(step, cols, live = false) {
90
+ const n = step.repeat ?? 0;
91
+ const calls = step.summary ?? "call"; // "3 calls" for a repeated multi-call round
92
+ const times = `${n} more time${n === 1 ? "" : "s"}`;
93
+ const span = step.durationMs && step.durationMs >= 1000 ? ` over ${fmtElapsed(step.durationMs)}` : "";
94
+ const again = seg(`same ${calls} again ×${n}`);
95
+ if (step.outcome === "blocked") {
96
+ return live
97
+ ? fitSegments([again, seg(["blocked by the loop guard", "loop guard"], 2, true), seg("nothing is running", 3)], cols, { lead: "↻ " })
98
+ : fitSegments([seg([`blocked ${times}${span}`, `blocked ${times}`], 3, true), seg(["the model was told to change approach", "loop guard"], 2, true)], cols, { lead: "↻ " });
99
+ }
100
+ const same = seg([`identical output each time${step.exitCode !== undefined ? ` (exit ${step.exitCode})` : ""}`, "identical"], 2, true);
101
+ return live
102
+ ? fitSegments([again, same], cols, { lead: "↻ " })
103
+ : fitSegments([seg([`ran the same ${calls} ${times}${span}`, `ran the same ${calls} ${times}`], 3, true), same], cols, { lead: "↻ " });
104
+ }
105
+ /** How a settled call's row reads, from its result and the engine's refusal: status, why it never ran, its exit code,
106
+ * and the summary under it (the refusal reason inline for a blocked call; the output preview otherwise). One place, so
107
+ * the live row, the settled transcript and the fold agree. */
108
+ export function settledFields(result, refused) {
109
+ const o = toolOutcome(result, refused);
110
+ if (o === "blocked")
111
+ return { status: "error", outcome: "blocked", summary: blockedReason(result) };
112
+ if (o === "cancelled")
113
+ return { status: "error", outcome: "cancelled" };
114
+ const code = exitCode(result);
115
+ return { status: o === "ok" ? "done" : "error", ...(code ? { exitCode: code } : {}), summary: resultPreview(result), lines: resultLines(result) };
116
+ }
117
+ /** A result's meaningful line count, for a row's tail or a chip ("195 lines"): blank lines and the shell's own
118
+ * bracketed trailers ([exit N], [note: …], [hint: …]) are not the tool's output. */
119
+ export function resultLines(result) {
120
+ return result.replace(/\s+$/, "").split("\n").filter((l) => l.trim() && !/^\[(exit \d+|note: |hint: )/.test(l.trim())).length;
121
+ }
122
+ const ORD = (n) => `${n}${n % 100 >= 11 && n % 100 <= 13 ? "th" : ["th", "st", "nd", "rd"][n % 10] ?? "th"}`;
123
+ /** Why a call never ran, in a few words, from the refusal's text (whether it was refused is the engine's report, not
124
+ * this): "5th identical call (loop guard)". */
125
+ export function blockedReason(result) {
126
+ const s = result.trim();
127
+ const called = /^loop guard: .*?(?:has been )?called (\d+)(?: times|x)/i.exec(s);
128
+ if (called)
129
+ return `${ORD(Number(called[1]))} identical call (loop guard)`;
130
+ if (/^loop guard: .*already returned your status/i.test(s))
131
+ return "status unchanged (loop guard)";
132
+ if (/^repeated action:/i.test(s))
133
+ return "already completed this turn";
134
+ if (/^permission denied: .* by the user/i.test(s))
135
+ return "you declined it";
136
+ if (/^permission denied: .* tier/i.test(s))
137
+ return "not available on this seat's tier";
138
+ if (/^permission denied:/i.test(s))
139
+ return "denied by policy";
140
+ const hook = /^blocked by a pretooluse hook: [^\n]*(?:\nreason: ([^\n]+))?/i.exec(s);
141
+ if (hook)
142
+ return hook[1] ? `hook: ${hook[1].slice(0, 74)}` : "a PreToolUse hook blocked it";
143
+ const blocked = /^blocked [^:]+: ([^.\n]+)/i.exec(s);
144
+ if (blocked)
145
+ return blocked[1].slice(0, 80);
146
+ if (/^cancelled:/i.test(s))
147
+ return "the turn was interrupted first";
148
+ return s.split("\n")[0].replace(/^loop guard:\s*/i, "").slice(0, 80);
149
+ }
package/dist/ui/format.js CHANGED
@@ -4,11 +4,55 @@ export function formatDuration(ms) {
4
4
  return `${Math.round(ms)}ms`;
5
5
  return `${(ms / 1000).toFixed(1)}s`;
6
6
  }
7
+ /** A wall-clock span the way the live line reads it: "6.2s", "41s", "3m 24s", "1h 2m". Whole seconds past ten, so a
8
+ * ticking clock never shows "1m 60s". */
9
+ export function fmtElapsed(ms) {
10
+ const sec = Math.max(0, ms) / 1000;
11
+ if (sec < 10)
12
+ return `${sec.toFixed(1)}s`;
13
+ const total = Math.round(sec);
14
+ if (total < 60)
15
+ return `${total}s`;
16
+ if (total < 3600)
17
+ return `${Math.floor(total / 60)}m ${total % 60}s`;
18
+ return `${Math.floor(total / 3600)}h ${Math.floor((total % 3600) / 60)}m`;
19
+ }
20
+ /** A token count as the live lines read it: "844", "52.8k", "158k", "1.2M". */
21
+ export function fmtTok(n) {
22
+ const v = Math.max(0, Math.round(n));
23
+ if (v < 1000)
24
+ return String(v);
25
+ if (v < 100_000)
26
+ return `${(v / 1000).toFixed(1)}k`;
27
+ if (v < 1_000_000)
28
+ return `${Math.round(v / 1000)}k`;
29
+ return `${(v / 1_000_000).toFixed(1)}M`;
30
+ }
31
+ export function toolOutcome(result, refused) {
32
+ if (refused)
33
+ return refused;
34
+ const s = result.trim();
35
+ if (/^(error|loop guard|\[interrupted|\[timed out)/i.test(s))
36
+ return "fail";
37
+ const exit = exitCode(s);
38
+ if ((exit !== undefined && exit !== 0) || /^\(no output; exit \?\)/.test(s))
39
+ return "fail";
40
+ if (/\n\[timed out after [^\n]*\]$/.test(s))
41
+ return "fail";
42
+ return "ok";
43
+ }
44
+ /** A shell call's exit code from its result (registry.ts shellExec), or undefined: output then an `[exit N]` line —
45
+ * which shellResultNotes' `[note: …]`/`[hint: …]` lines and the result guard's notes may follow — or, for a command
46
+ * that printed nothing, `(no output; exit N)`. */
47
+ export function exitCode(result) {
48
+ const m = /(?:^|\n)\[exit (\d+)\](?:\n+\[[^\n]*\])*\s*$/.exec(result) ?? /^\s*\(no output; exit (\d+)\)/.exec(result);
49
+ return m ? Number(m[1]) : undefined;
50
+ }
7
51
  // A tool result reads as an error/loop-guard/interrupt sentinel rather than real output — shared by the
8
52
  // settled-transcript push (cli.tsx) and the live per-call row update (ui/liveTools.ts) so both classify
9
53
  // a result the same way.
10
- export function isErrorResult(s) {
11
- return /^(error|loop guard|\[interrupted)/i.test(s.trim());
54
+ export function isErrorResult(s, refused) {
55
+ return toolOutcome(s, refused) !== "ok";
12
56
  }
13
57
  // The at-a-glance preview of a tool's output, under its row. The old behaviour showed ONLY the first
14
58
  // physical line, which for `ls -la`/`du`/`git status` is a header (`total 1672`, a blank line, a banner)