@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,153 @@
1
+ import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
2
+ // ctrl+g — the skills and tools finder (TUI A3.3, James's change): search as you type across your profile, the Operator
3
+ // catalogue, Operator's tools and the AXE skills hub (65K+ skills), preview the highlighted one, use it (activate a
4
+ // skill, or ask for a tool), run it with your words as the task, or create a new skill. Same shape as SessionPicker: a
5
+ // pure keystroke reducer (tested without a TTY) + useInput gated while open, a bordered box above the composer, one
6
+ // fixed height for as long as it is open.
7
+ import { useEffect, useRef, useState } from "react";
8
+ import { Box, Text, useInput } from "ink";
9
+ import { skillSlug } from "../skills/finder.js";
10
+ import { fitSegments, seg } from "./fit.js";
11
+ import { fitWithTail } from "./fitTail.js";
12
+ import { termCols } from "./term.js";
13
+ import { typedText } from "./SecretPrompt.js";
14
+ export const FINDER_ROWS = 7;
15
+ const PREVIEW_ROWS = 4;
16
+ /** A typed or pasted chunk as one-line field text: the paste markers and terminal reports out (review F9), line breaks
17
+ * and other control characters as spaces. */
18
+ const fieldText = (input) => typedText(input).replace(/[\x00-\x1f\x7f]+/g, " ");
19
+ /** Pure keystroke reducer: the next state and/or an intent. Any query change searches again. `busy`: a ⏎ is loading —
20
+ * Esc cancels it before anything else (review F8). */
21
+ export function finderKey(st, raw, key, items, busy = false) {
22
+ if (busy && key.escape)
23
+ return { intent: { kind: "cancel" } };
24
+ const input = key.ctrl || key.meta ? raw : fieldText(raw);
25
+ const n = items.length;
26
+ const hi = Math.min(Math.max(st.highlight, 0), Math.max(0, n - 1));
27
+ const item = items[hi];
28
+ if (st.mode === "name" || st.mode === "desc") {
29
+ const field = st.mode === "name" ? "name" : "desc";
30
+ if (key.escape)
31
+ return { state: { ...st, mode: st.mode === "desc" ? "name" : "search" } };
32
+ if (key.return) {
33
+ if (st.mode === "name")
34
+ return st.name.trim() ? { state: { ...st, mode: "desc" } } : {};
35
+ return { state: { ...st, mode: "search" }, intent: { kind: "create", name: st.name, description: st.desc, draft: true } };
36
+ }
37
+ if (key.tab && st.mode === "desc")
38
+ return { state: { ...st, mode: "search" }, intent: { kind: "create", name: st.name, description: st.desc, draft: false } };
39
+ if (key.backspace || key.delete)
40
+ return { state: { ...st, [field]: st[field].slice(0, -1) } };
41
+ if (input && !key.ctrl && !key.meta)
42
+ return { state: { ...st, [field]: st[field] + input } };
43
+ return {};
44
+ }
45
+ if (key.escape) {
46
+ if (st.query) {
47
+ const next = { ...st, query: "", highlight: 0, expanded: false };
48
+ return { state: next, intent: { kind: "query", query: "" } };
49
+ }
50
+ return { intent: { kind: "close" } };
51
+ }
52
+ if (key.upArrow)
53
+ return { state: { ...st, highlight: n ? (hi <= 0 ? n - 1 : hi - 1) : 0, expanded: false } };
54
+ if (key.downArrow)
55
+ return { state: { ...st, highlight: n ? (hi >= n - 1 ? 0 : hi + 1) : 0, expanded: false } };
56
+ if (key.rightArrow)
57
+ return item ? { state: { ...st, expanded: true }, intent: { kind: "preview", item } } : {};
58
+ if (key.leftArrow)
59
+ return { state: { ...st, expanded: false } };
60
+ if (key.return)
61
+ return item ? { intent: { kind: "use", item, query: st.query } } : {};
62
+ if (key.ctrl && input === "r")
63
+ return item ? { intent: { kind: "run", item, query: st.query } } : {};
64
+ if (key.ctrl && input === "n")
65
+ return { state: { ...st, mode: "name", name: skillSlug(st.query || "new-skill"), desc: st.query } };
66
+ if (key.backspace || key.delete) {
67
+ if (!st.query)
68
+ return {};
69
+ const query = st.query.slice(0, -1);
70
+ return { state: { ...st, query, highlight: 0, expanded: false }, intent: { kind: "query", query } };
71
+ }
72
+ if (input && !key.ctrl && !key.meta) {
73
+ const query = st.query + input;
74
+ return { state: { ...st, query, highlight: 0, expanded: false }, intent: { kind: "query", query } };
75
+ }
76
+ return {};
77
+ }
78
+ const SOURCE_TAG = { profile: "profile", catalogue: "catalogue", tool: "tool", hub: "hub" };
79
+ /** One result row, fitted to `width`: name, where it is from, then as much of the description as fits. */
80
+ export function finderRow(it, selected, width) {
81
+ const tag = [SOURCE_TAG[it.source], it.origin && it.origin !== "profile" ? it.origin : "", it.verified ? "✓" : ""].filter(Boolean).join(" · ");
82
+ return fitWithTail([seg(selected ? "❯ " : " "), seg(it.name), seg(` [${tag}]`, 2)], it.description ? ` — ${it.description}` : "", width + 1, { sep: "", tailMin: 0 });
83
+ }
84
+ /** The preview block: the highlighted item's description (wrapped), or its full text after →, in PREVIEW_ROWS lines. */
85
+ export function previewLines(it, p, expanded, width) {
86
+ if (!it)
87
+ return Array.from({ length: PREVIEW_ROWS }, () => "");
88
+ let body;
89
+ if (expanded && p && p.source === it.source && p.id === it.id) {
90
+ if (p.loading)
91
+ body = ["loading the full text…"];
92
+ else if (p.error)
93
+ body = [p.error];
94
+ else
95
+ body = (p.text ?? "").replace(/^---\n[\s\S]*?\n---\n?/, "").split("\n").map((l) => l.trimEnd()).filter((l) => l.trim()).slice(0, PREVIEW_ROWS);
96
+ }
97
+ else {
98
+ const words = (it.description || "(no description)").split(/\s+/);
99
+ body = [];
100
+ let line = "";
101
+ for (const w of words) {
102
+ if ((line ? `${line} ${w}` : w).length > width - 2) {
103
+ body.push(line);
104
+ line = w;
105
+ if (body.length === PREVIEW_ROWS)
106
+ break;
107
+ }
108
+ else
109
+ line = line ? `${line} ${w}` : w;
110
+ }
111
+ if (line && body.length < PREVIEW_ROWS)
112
+ body.push(line);
113
+ }
114
+ const out = body.slice(0, PREVIEW_ROWS).map((l) => fitSegments([seg(l)], width + 1, { lead: " " }));
115
+ while (out.length < PREVIEW_ROWS)
116
+ out.push("");
117
+ return out;
118
+ }
119
+ export function SkillFinder({ pending }) {
120
+ const [st, setSt] = useState({ mode: "search", query: "", highlight: 0, name: "", desc: "", expanded: false });
121
+ const wasOpen = useRef(false);
122
+ useEffect(() => {
123
+ const open = !!pending;
124
+ if (open && !wasOpen.current)
125
+ setSt({ mode: "search", query: pending.initialQuery ?? "", highlight: 0, name: "", desc: "", expanded: false });
126
+ wasOpen.current = open;
127
+ }, [pending]);
128
+ const items = pending?.items ?? [];
129
+ const n = items.length;
130
+ const hi = Math.min(Math.max(st.highlight, 0), Math.max(0, n - 1));
131
+ useInput((input, key) => {
132
+ if (!pending)
133
+ return;
134
+ const a = finderKey(st, input, key, items, !!pending.loading);
135
+ if (a.state)
136
+ setSt(a.state);
137
+ if (a.intent)
138
+ pending.onIntent(a.intent);
139
+ }, { isActive: !!pending });
140
+ if (!pending)
141
+ return null;
142
+ const width = Math.max(30, termCols() - 4); // inside the border and padding
143
+ const start = n <= FINDER_ROWS ? 0 : Math.max(0, Math.min(hi - Math.floor(FINDER_ROWS / 2), n - FINDER_ROWS));
144
+ const shown = items.slice(start, start + FINDER_ROWS);
145
+ const pad = FINDER_ROWS - shown.length;
146
+ const creating = st.mode !== "search";
147
+ return (_jsxs(Box, { flexDirection: "column", marginTop: 1, marginBottom: 1, borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Text, { color: "cyan", bold: true, children: fitSegments([seg("◆ Skills & tools"), seg(pending.sizes ? ` ${pending.sizes}` : "", 1)], width + 1, { sep: "" }) }), creating ? (_jsxs(_Fragment, { children: [_jsxs(Text, { children: [_jsx(Text, { color: "magenta", children: "new skill› " }), st.mode === "name" ? _jsxs(_Fragment, { children: [st.name, _jsx(Text, { color: "cyan", children: "\u258C" })] }) : st.name] }), _jsxs(Text, { children: [_jsx(Text, { color: "magenta", children: " what for› " }), st.mode === "desc" ? _jsxs(_Fragment, { children: [st.desc, _jsx(Text, { color: "cyan", children: "\u258C" })] }) : _jsx(Text, { dimColor: true, children: st.desc || "(Enter to write what it is for)" })] })] })) : (_jsxs(Text, { children: [_jsx(Text, { color: "magenta", children: "search› " }), st.query, _jsx(Text, { color: "cyan", children: "\u258C" })] })), shown.map((it, i) => {
148
+ const sel = start + i === hi && !creating;
149
+ return _jsx(Text, { bold: sel, color: sel ? "cyan" : undefined, dimColor: !sel && it.source === "tool", children: finderRow(it, sel, width) }, `${it.source}:${it.id}`);
150
+ }), Array.from({ length: pad }, (_, i) => _jsx(Text, { children: i === 0 && n === 0 ? (st.query ? ` nothing matches "${st.query}" yet` : " type to search") : " " }, `pad${i}`)), _jsx(Text, { dimColor: true, children: fitSegments([seg(pending.status ? ` ${pending.status}` : " "), seg(n > FINDER_ROWS ? ` · ${hi + 1}/${n}` : "")], width + 1, { sep: "" }) }), previewLines(creating ? undefined : items[hi], pending.preview, st.expanded, width).map((l, i) => _jsx(Text, { dimColor: !st.expanded, children: l || " " }, `pv${i}`)), pending.note ? _jsx(Text, { color: "green", children: fitSegments([seg(pending.note)], width + 1, { lead: " " }) }) : _jsx(Text, { children: " " }), _jsx(Text, { dimColor: true, children: fitSegments([seg(creating
151
+ ? (st.mode === "name" ? "name it · Enter next · Esc back" : "what it is for · Enter: I draft it with the model · Tab: save the skeleton now · Esc back")
152
+ : "type to search · ↑/↓ move · → preview · ⏎ use · ctrl+r run with your words · ctrl+n new skill · esc close")], width + 1, { lead: " " }) })] }));
153
+ }
@@ -45,6 +45,10 @@ export function truncateToWidth(s, max) {
45
45
  // which keeps the leading fill ≥ 1 and the whole line at cols-1, so the rule never becomes the line that
46
46
  // wraps (the creep bug) no matter how many badges are lit or how narrow the window.
47
47
  const ROUTE_LABELS = { "operator-1m": "aurora" };
48
+ /** The model as the owner reads it everywhere ("cortana"; the default operator-1m reads "aurora"). */
49
+ export function routeLabel(route) {
50
+ return ROUTE_LABELS[route] ?? route;
51
+ }
48
52
  export function statusRight(p, cols) {
49
53
  const who = p.user ? `◆ ${p.user} · ` : "";
50
54
  const seat = p.tier && p.tier !== "admin" ? `⛨ ${p.tier} · ` : ""; // a narrowed seat shows; owner's admin doesn't
@@ -55,9 +59,8 @@ export function statusRight(p, cols) {
55
59
  // Show the active model (cortana, claude-opus, moa, custom …) and the window it runs on, never the leg that answered
56
60
  // ("cortana@192.168.1.103:8112" read as noise; /endpoints lists the legs). The default model reads as "aurora", not
57
61
  // its id operator-1m (owner, 11/03: "just aurora 300k"), and the window is the one served, not a pin above it.
58
- const routeLabel = ROUTE_LABELS[p.route] ?? p.route;
59
62
  const window = p.ctxWindow ? ` ${p.ctxWindow}` : "";
60
- let info = `${think}${plan}${seat}${who}${routeLabel}${window} ${ring(p.ctxPct)} ${Math.round(p.ctxPct)}% · ${tok}v${p.version}${p.build ? ` ·${p.build}` : ""}`;
63
+ let info = `${think}${plan}${seat}${who}${routeLabel(p.route)}${window} ${ring(p.ctxPct)} ${Math.round(p.ctxPct)}% · ${tok}v${p.version}${p.build ? ` ·${p.build}` : ""}`;
61
64
  let right = `✷ OPERATOR · ${info} ─`;
62
65
  const maxRight = cols - 3; // leaves fill ≥ 1 and total = cols-1
63
66
  if (cellWidth(right) > maxRight) {
@@ -1,6 +1,8 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
3
  import { theme } from "./theme.js";
4
+ import { termCols } from "./term.js";
5
+ import { ledgerLines, repetitionLine } from "./turnLedger.js";
4
6
  const fmtDur = (ms) => (ms < 1000 ? `${Math.round(ms)}ms` : ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`);
5
7
  const fmtTok = (n) => (n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`);
6
8
  /** The metrics line (pure) — kept separate so the exact layout is unit-testable without a render. */
@@ -14,5 +16,5 @@ export function summaryLine(s) {
14
16
  return parts.join(" · ");
15
17
  }
16
18
  export function SummaryCard({ summary }) {
17
- return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.accent, children: "\u2726 " }), _jsx(Text, { bold: true, children: "turn complete" }), _jsx(Text, { dimColor: true, children: ` ${summaryLine(summary)}` })] }), summary.unverified ? (_jsx(Text, { color: theme.warn, children: "\u26A0 changed files \u00B7 not verified (no passing check ran)" })) : null] }));
19
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.accent, children: "\u2726 " }), _jsx(Text, { bold: true, children: "turn complete" }), _jsx(Text, { dimColor: true, children: ` ${summaryLine(summary)}` })] }), summary.time ? ledgerLines(summary.time, summary.time, termCols() - 5).map((l, i) => (_jsxs(Text, { dimColor: true, children: [" ", _jsx(Text, { color: i === 0 ? theme.info : undefined, children: l.slice(0, 4) }), l.slice(4)] }, `t${i}`))) : null, summary.lastRound ? _jsx(Text, { dimColor: true, children: " " + repetitionLine(summary.lastRound.chars, summary.lastRound.ms, termCols() - 6) }) : null, summary.unverified ? (_jsx(Text, { color: theme.warn, children: "\u26A0 changed files \u00B7 not verified (no passing check ran)" })) : null] }));
18
20
  }
@@ -7,6 +7,8 @@ import { jsxs as _jsxs, jsx as _jsx } from "react/jsx-runtime";
7
7
  import { useEffect, useState } from "react";
8
8
  import { Box, Text } from "ink";
9
9
  import { ShimmerText, PEARL } from "./shimmer.js";
10
+ import { termCols } from "./term.js";
11
+ import { cellWidth, truncateToWidth } from "./StatusRule.js";
10
12
  const DEFAULT_VERBS = [
11
13
  "Thinking", "Reasoning", "Noodling", "Synthesizing", "Percolating", "Untangling", "Weighing",
12
14
  ];
@@ -41,6 +43,13 @@ export function expandStar(frames = FRAMES) {
41
43
  return out;
42
44
  }
43
45
  const SEQUENCE = expandStar();
46
+ const GLYPH_CELLS = 3; // the widest star frame counted wide, plus its space — constant, so a tick never reflows the row
47
+ /** The verb with its ellipsis, clipped to the width left after the star and the metrics: a long plan step
48
+ * ("Step 3/7 · Wire the fallback into buildRouter") never wraps the row (TUI plan #5). Pure. */
49
+ export function spinnerLabel(label, cols, metrics) {
50
+ const room = cols - 1 - GLYPH_CELLS - (metrics ? 2 + cellWidth(metrics) : 0);
51
+ return cellWidth(`${label}…`) <= room ? `${label}…` : truncateToWidth(label, room);
52
+ }
44
53
  export function ThinkingSpinner({ active, verb, verbs = DEFAULT_VERBS, verbIntervalMs = 2000, tickMs = 150, // 150ms (~7fps): the star still reads as animated, but each tick re-renders the whole inline frame — the dominant streaming-phase driver, kept slow to reduce flashing
45
54
  metrics, }) {
46
55
  const [tick, setTick] = useState(0);
@@ -61,8 +70,8 @@ metrics, }) {
61
70
  return null;
62
71
  const [tone, glyph] = SEQUENCE[tick];
63
72
  const style = TONE_STYLE[tone];
64
- const label = verb ?? verbs[verbIdx % verbs.length];
73
+ const label = spinnerLabel(verb ?? verbs[verbIdx % verbs.length], termCols(), metrics);
65
74
  // Star keeps its amber tone animation; the VERB now carries a pearl (slate→white) shimmer sweep driven by the
66
75
  // same tick — the continuous light replaces the old tone-flash as the "alive" cue.
67
- return (_jsxs(Box, { children: [_jsxs(Text, { color: style.color, bold: style.bold, dimColor: style.dim, children: [glyph, " "] }), _jsx(ShimmerText, { text: `${label}…`, frame: tick, palette: PEARL }), metrics ? _jsx(Text, { dimColor: true, children: " " + metrics }) : null] }));
76
+ return (_jsxs(Box, { children: [_jsxs(Text, { color: style.color, bold: style.bold, dimColor: style.dim, children: [glyph, " "] }), _jsx(ShimmerText, { text: label, frame: tick, palette: PEARL }), metrics ? _jsx(Text, { dimColor: true, children: " " + metrics }) : null] }));
68
77
  }
@@ -2,11 +2,20 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
3
  import { theme } from "./theme.js";
4
4
  import { ToolStep } from "./ToolStep.js";
5
+ import { termCols } from "./term.js";
6
+ import { batchChips } from "./batchLine.js";
7
+ import { KIND_HUE, toolKind } from "./toolicons.js";
5
8
  const fmtDur = (ms) => ms < 1000 ? `${Math.round(ms)}ms` : ms < 60_000 ? `${(ms / 1000).toFixed(1)}s` : `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;
6
9
  /** The batch header (pure) — kept separate so the exact wording/layout is unit-testable without a render. */
7
10
  export function batchHeader(count, durationMs) {
8
11
  return `${count} tools in parallel · ${fmtDur(durationMs)}`;
9
12
  }
10
- export function ToolBatch({ steps, durationMs }) {
11
- return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.accent, children: "\u21C9 " }), _jsx(Text, { bold: true, children: `${steps.length} tools in parallel` }), _jsx(Text, { dimColor: true, children: ` ${fmtDur(durationMs)}` })] }), steps.map((step) => _jsx(ToolStep, { step: step }, step.id))] }));
13
+ const TONE = { done: theme.success, error: theme.error, blocked: theme.blocked, cancelled: theme.muted };
14
+ export function ToolBatch({ steps, durationMs, expanded }) {
15
+ if (expanded) {
16
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: theme.muted, paddingX: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.accent, children: "\u21C9 " }), _jsx(Text, { bold: true, children: `${steps.length} tools in parallel` }), _jsx(Text, { dimColor: true, children: ` ${fmtDur(durationMs)}` })] }), steps.map((step) => _jsx(ToolStep, { step: step }, step.id))] }));
17
+ }
18
+ const { head, chips, folded, hint } = batchChips(steps, durationMs, termCols());
19
+ const broken = steps.filter((s) => s.status === "error");
20
+ return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: theme.accent, children: head.slice(0, 2) }), _jsx(Text, { dimColor: true, children: head.slice(2) }), chips.map((c, i) => (_jsxs(Text, { children: [" ", _jsx(Text, { color: TONE[c.tone], children: c.glyph }), " ", _jsx(Text, { color: KIND_HUE[toolKind(c.name)], children: c.label })] }, i))), folded ? _jsx(Text, { dimColor: true, children: ` ${folded}` }) : null, hint ? _jsx(Text, { color: theme.info, children: ` ${hint}` }) : null] }), broken.map((s) => _jsx(Box, { paddingLeft: 2, children: _jsx(ToolStep, { step: s }) }, s.id))] }));
12
21
  }
@@ -1,14 +1,16 @@
1
- import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
1
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
2
2
  import { Box, Text } from "ink";
3
3
  import { formatDuration } from "./format.js";
4
4
  import { fileLink } from "./osc.js";
5
5
  import { theme } from "./theme.js";
6
6
  import { computeEditDiff } from "./editdiff.js";
7
7
  import { useTick } from "./tick.js";
8
- import { rowBackgroundHint } from "./liveTools.js";
8
+ import { rowBackgroundHint, BULK_ARGS } from "./liveTools.js";
9
9
  import { glyphFor, toolKind, KIND_HUE } from "./toolicons.js";
10
- import { renderBar, mediaEtaMs, mediaProgressFraction } from "./progressbar.js";
10
+ import { renderSweepBar } from "./progressbar.js";
11
11
  import { ShimmerText, huePalette } from "./shimmer.js";
12
+ import { foldLine } from "./fold.js";
13
+ import { termCols } from "./term.js";
12
14
  const PATH_KEYS = new Set(["path", "file", "filename"]);
13
15
  // Icon is now per ACTION (see toolicons.ts: read ▤ · write ✎ · search ◎ · shell ❯ · web ◍ · git ❖ · skill ◆ ·
14
16
  // agent ✺), animated while running; COLOR still carries the status (muted → amber → green → red).
@@ -17,10 +19,10 @@ const COLOR = { selected: theme.muted, running: theme.running, done: theme.succe
17
19
  // (never truncated), so you can always read the exact file name / path a tool wrote or read. Order matters:
18
20
  // path-like keys first.
19
21
  const KEY_ARGS = ["path", "file", "filename", "command", "cmd", "pattern", "url", "query", "workspace", "cwd", "name"];
20
- // Bulky payloads — never dumped (they'd bury the path and blow up the line); shown as a size instead.
21
- const BULK_ARGS = ["content", "text", "body", "data", "new_string", "old_string", "diff", "message"];
22
22
  const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
23
- export function argsPreview(args) {
23
+ /** `link: false` gives the plain text (a live row clips it, and clipping an OSC-8 escape cuts it); `sizes` are a
24
+ * draft's bulk arguments by their running length, shown where the finished call shows its own. */
25
+ export function argsPreview(args, opts = {}) {
24
26
  if (!args)
25
27
  return "";
26
28
  const parts = [];
@@ -33,7 +35,7 @@ export function argsPreview(args) {
33
35
  for (const k of KEY_ARGS) {
34
36
  const v = args[k];
35
37
  if (v != null && (typeof v === "string" || typeof v === "number")) {
36
- const shown = PATH_KEYS.has(k) && typeof v === "string" ? fileLink(v) : String(v); // clickable path (OSC 8)
38
+ const shown = PATH_KEYS.has(k) && typeof v === "string" && opts.link !== false ? fileLink(v) : String(v); // clickable path (OSC 8)
37
39
  parts.push(`${k}: ${shown}`);
38
40
  seen.add(k);
39
41
  }
@@ -44,6 +46,10 @@ export function argsPreview(args) {
44
46
  parts.push(`${k}: ${args[k].length} chars`);
45
47
  seen.add(k);
46
48
  }
49
+ else if (opts.sizes?.[k] !== undefined) {
50
+ parts.push(`${k}: ${opts.sizes[k]} chars`);
51
+ seen.add(k);
52
+ }
47
53
  }
48
54
  // 3) any remaining scalar args, each individually trimmed (never at the cost of the path above).
49
55
  for (const [k, v] of Object.entries(args)) {
@@ -77,6 +83,16 @@ export function shellCommandHint(step) {
77
83
  return trimmed.length > 120 ? trimmed.slice(0, 117) + "..." : trimmed;
78
84
  }
79
85
  export function ToolStep({ step }) {
86
+ if (step.repeat)
87
+ return _jsx(FoldRow, { step: step });
88
+ return _jsx(CallRow, { step: step });
89
+ }
90
+ // A settled fold (ui/fold.ts): N more identical rounds as one counting line, ↻ in muted amber, the rest dim.
91
+ function FoldRow({ step }) {
92
+ const line = foldLine(step, termCols());
93
+ return _jsxs(Text, { children: [_jsx(Text, { color: theme.blocked, children: line.slice(0, 1) }), _jsx(Text, { dimColor: true, children: line.slice(1) })] });
94
+ }
95
+ function CallRow({ step }) {
80
96
  // ONE shared animation clock (tick.ts) drives both the per-action icon animation AND the live elapsed timer,
81
97
  // so a running row needs no setInterval of its own — this replaces N per-row 250ms timers with a single
82
98
  // ~8fps shared tick (richer motion, fewer timers). Settled rows don't subscribe, so they never re-render.
@@ -91,14 +107,21 @@ export function ToolStep({ step }) {
91
107
  // Enterprise "what changed at a glance": only on a SETTLED edit (not mid-run, not errored — the write
92
108
  // may never have landed), and only when the tool's own args are actually diffable.
93
109
  const editDiff = step.status === "done" ? computeEditDiff(step.name, step.args) : undefined;
94
- // Media-gen rows (image_generate/video_generate): the flux/video brokers report no percentage, so we
95
- // fake a determinate feel from elapsed-vs-ETA (progressbar.ts), capped at 95% until the real result
96
- // lands. Only RUNNING media rows get the bar — everything else renders exactly as before.
110
+ // Media-gen rows (image_generate/video_generate): the flux/video brokers report no percentage, so a running row
111
+ // shows a sweep beside its real elapsed clock. It used to draw elapsed ÷ a guessed ETA as a percentage — a number
112
+ // nobody measured. Only RUNNING media rows get the sweep; everything else renders exactly as before.
97
113
  const isRunningMedia = toolKind(step.name) === "media" && step.status === "running";
98
- const mediaFraction = isRunningMedia && elapsed != null ? mediaProgressFraction(elapsed, mediaEtaMs(step.name, step.args)) : undefined;
114
+ // A call that never ran reads as exactly that — ⊘ with the reason inline, no timer, no preview (TUI plan #3): a refused
115
+ // or cancelled call used to paint as a green success with the refusal text as its "output".
116
+ if (step.outcome) {
117
+ const t = stepTitle(step);
118
+ return (_jsxs(Text, { children: [_jsx(Text, { color: step.outcome === "blocked" ? theme.blocked : theme.muted, bold: true, children: "\u2298" }), " ", _jsx(Text, { color: KIND_HUE[toolKind(step.name)], children: t.head }), t.head === "$" ? " " : "", t.body, _jsx(Text, { color: step.outcome === "blocked" ? theme.blocked : undefined, dimColor: step.outcome === "cancelled", children: step.outcome === "blocked" ? ` · blocked${step.summary ? `: ${step.summary}` : ""} · did not run` : " · cancelled · did not run" })] }));
119
+ }
99
120
  return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { children: [_jsx(Text, { color: step.status === "running" ? KIND_HUE[toolKind(step.name)] : COLOR[step.status], bold: true, children: glyphFor(step.name, step.status, frame) }), " ", (() => {
100
121
  const t = stepTitle(step);
101
- const head = step.status === "running" ? _jsx(ShimmerText, { text: t.head, frame: frame, palette: huePalette(KIND_HUE[toolKind(step.name)]) }) : t.head;
122
+ // The tool's name (or "$") always takes its kind's color — the same everywhere a tool row appears (TUI plan #12):
123
+ // shimmering while it runs, solid once settled; the glyph before it carries the outcome.
124
+ const head = step.status === "running" ? _jsx(ShimmerText, { text: t.head, frame: frame, palette: huePalette(KIND_HUE[toolKind(step.name)]) }) : _jsx(Text, { color: KIND_HUE[toolKind(step.name)], children: t.head });
102
125
  return _jsxs(_Fragment, { children: [head, t.head === "$" ? " " : "", t.body, t.note ? _jsx(Text, { dimColor: true, children: ` · ${t.note}` }) : null] });
103
- })(), mediaFraction != null ? (_jsxs(Text, { children: [" ", _jsx(Text, { color: theme.mediaProgress, children: renderBar(mediaFraction) }), " ", Math.round(mediaFraction * 100), "%"] })) : null, elapsed != null ? _jsxs(Text, { dimColor: true, children: [" ", formatDuration(elapsed)] }) : null, editDiff ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: theme.success, children: ["+", editDiff.added] }), " ", _jsxs(Text, { color: theme.error, children: ["-", editDiff.removed] })] })) : null] }), rowBackgroundHint(step, now) ? _jsxs(Text, { dimColor: true, children: [" ", rowBackgroundHint(step, now)] }) : null, step.summary ? step.summary.split("\n").map((l, i) => (_jsxs(Text, { dimColor: true, children: [" ", l] }, `sm${i}`))) : null, editDiff?.preview?.map((l, i) => (_jsxs(Text, { color: l.kind === "add" ? theme.success : theme.error, children: [" ", l.kind === "add" ? "+ " : "- ", l.text] }, i)))] }));
126
+ })(), isRunningMedia ? _jsxs(Text, { children: [" ", _jsx(Text, { color: theme.mediaProgress, children: renderSweepBar(frame) })] }) : null, elapsed != null ? _jsxs(Text, { dimColor: true, children: [" ", formatDuration(elapsed)] }) : null, step.exitCode !== undefined ? _jsx(Text, { color: theme.error, children: ` · exit ${step.exitCode}` }) : null, editDiff ? (_jsxs(Text, { children: [" ", _jsxs(Text, { color: theme.success, children: ["+", editDiff.added] }), " ", _jsxs(Text, { color: theme.error, children: ["-", editDiff.removed] })] })) : null] }), rowBackgroundHint(step, now) ? _jsxs(Text, { dimColor: true, children: [" ", rowBackgroundHint(step, now)] }) : null, step.summary ? step.summary.split("\n").map((l, i) => (_jsxs(Text, { dimColor: true, children: [" ", l] }, `sm${i}`))) : null, editDiff?.preview?.map((l, i) => (_jsxs(Text, { color: l.kind === "add" ? theme.success : theme.error, children: [" ", l.kind === "add" ? "+ " : "- ", l.text] }, i)))] }));
104
127
  }
@@ -12,6 +12,8 @@ import { StatsCard } from "./StatsCard.js";
12
12
  import { ToolBatch } from "./ToolBatch.js";
13
13
  import { SB_MARK, SB_IN, SB_OUT } from "./brand.js";
14
14
  import { termCols, termRows } from "./term.js";
15
+ import { reportLine } from "./reportLine.js";
16
+ import { theme } from "./theme.js";
15
17
  // In fullscreen we can't use <Static> (it targets the scrollback the alt-screen buffer hides), so render
16
18
  // the last N entries as a plain column the parent region clips to the visible height. N is generous — the
17
19
  // parent's overflow:hidden + justifyContent:flex-end shows only what fits, bottom-anchored.
@@ -104,19 +106,28 @@ function clampReasoning(s) {
104
106
  return { text: s, hidden: 0 };
105
107
  return { text: lines.slice(-REASONING_TAIL_LINES).join("\n"), hidden: lines.length - REASONING_TAIL_LINES };
106
108
  }
109
+ // A finished sub-agent's one line: the glyph in its outcome color, the name bright, the rest dim, the expand hint cyan.
110
+ function ReportRow({ agent }) {
111
+ const { tone, line, hint } = reportLine(agent, termCols());
112
+ const body = line.slice(2, hint ? line.length - hint.length : undefined);
113
+ const name = body.split(" · ")[0];
114
+ return (_jsxs(Text, { children: [_jsx(Text, { color: tone === "done" ? theme.success : tone === "stopped" ? theme.blocked : theme.error, children: line.slice(0, 2) }), _jsx(Text, { bold: true, children: name }), _jsx(Text, { dimColor: true, children: body.slice(name.length) }), hint ? _jsx(Text, { color: theme.info, children: hint }) : null] }));
115
+ }
107
116
  function renderEntry(entry, live = false) {
108
117
  if (entry.kind === "summary")
109
118
  return _jsx(SummaryCard, { summary: entry.summary });
119
+ if (entry.kind === "report")
120
+ return _jsx(ReportRow, { agent: entry.agent });
110
121
  if (entry.kind === "stats")
111
122
  return _jsx(StatsCard, { stats: entry.stats });
112
123
  if (entry.kind === "bus")
113
124
  return _jsx(BusCard, { entry: entry });
114
125
  if (entry.kind === "toolBatch")
115
- return _jsx(ToolBatch, { steps: entry.steps, durationMs: entry.durationMs });
126
+ return _jsx(ToolBatch, { steps: entry.steps, durationMs: entry.durationMs, expanded: entry.expanded });
116
127
  if (entry.kind === "message") {
117
128
  const { message } = entry;
118
129
  if (message.role === "user") {
119
- return _jsxs(Text, { children: ["❯ ", message.content] });
130
+ return _jsxs(Text, { children: ["❯ ", message.content, message.tag ? _jsx(Text, { dimColor: true, children: ` ${message.tag}` }) : null] });
120
131
  }
121
132
  if (message.role === "system") {
122
133
  return _jsx(Text, { dimColor: true, children: message.content }); // slash-command output / status notes
@@ -0,0 +1,61 @@
1
+ // When the phase line offers ctrl+y — "use what you have" (TUI A3.3) — and what it says. Three measured triggers: one
2
+ // reasoning stream running 30 s or more with no answer text and no tool call; a prompt read of 30 s or more (it arms,
3
+ // and answers think-off the moment the read ends); the loop guard refusing a repeated call. Pure, so each trigger and
4
+ // every width is unit-tested; the shell feeds it from its turn handlers and the existing 500 ms clock (no new timer).
5
+ import { seg } from "./fit.js";
6
+ export const ACT_NOW_HINT_MS = 30_000;
7
+ export const ACT_NOW_KEY = "ctrl+y";
8
+ export function actNowOffer(st, now, o = { thinking: true }) {
9
+ const hint = o.hintMs ?? ACT_NOW_HINT_MS;
10
+ if (st.armedTools)
11
+ return { kind: "tools" };
12
+ if (st.armed)
13
+ return { kind: "read", armed: true }; // pressed before the first token — queued or still reading
14
+ if (st.guard)
15
+ return { kind: "loop", detail: st.guard };
16
+ if (st.reasoningSince !== undefined && now - st.reasoningSince >= hint)
17
+ return { kind: "reasoning", ms: now - st.reasoningSince };
18
+ // A read only has reasoning to skip when thinking is on; with it off the answer already starts the moment the read ends.
19
+ if (o.thinking && st.readingSince !== undefined && now - st.readingSince >= hint)
20
+ return { kind: "read", armed: false };
21
+ return null;
22
+ }
23
+ /** The loop guard's own words in a batch's results, said short: "bash ×8 with identical args, refused". */
24
+ export function guardDetail(results) {
25
+ for (const r of results) {
26
+ const text = String(r.result ?? "");
27
+ const loop = /^Loop guard: "([\w:.-]+)" has been called (\d+) times/.exec(text);
28
+ if (loop)
29
+ return `${loop[1]} ×${loop[2]} with identical args, refused`;
30
+ const status = /^Loop guard: "([\w:.-]+)" already returned your status/.exec(text);
31
+ if (status)
32
+ return `${status[1]} polled with no change, refused`;
33
+ const repeat = /^Repeated action: "([\w:.-]+)"/.exec(text);
34
+ if (repeat)
35
+ return `${repeat[1]} repeats a finished call, refused`;
36
+ const capped = /^Blocked ([\w:.-]+): /.exec(text);
37
+ if (capped)
38
+ return `${capped[1]} over its per-turn cap, refused`;
39
+ }
40
+ return undefined;
41
+ }
42
+ const fmt = (ms) => { const s = Math.round(ms / 1000); return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${s % 60}s`; };
43
+ /** The phase line with the offer, as fit segments (sep ""): the detail gives way first, then "⏎ steer"; "ctrl+y use what
44
+ * you have" and "esc stop" always stay. `phase` is the line's own phase text. Null offer → null (the plain line). */
45
+ export function actNowLine(phase, offer) {
46
+ if (!offer)
47
+ return null;
48
+ if (offer.kind === "tools")
49
+ return [seg(` ${phase}`), seg([" · ▸ armed: answers once these tools finish", " · ▸ armed"], 7, true), seg(" · esc stop")];
50
+ if (offer.kind === "read") {
51
+ return offer.armed
52
+ ? [seg(` ${phase}`), seg([" · ▸ armed: answers think-off the moment the read ends", " · ▸ armed"], 7, true), seg(" · esc stop")]
53
+ : [seg(` ${phase}`), seg([` · ${ACT_NOW_KEY} skip the reasoning once the read ends`, ` · ${ACT_NOW_KEY} skip reasoning`], 7, true), seg(" · esc stop")];
54
+ }
55
+ const head = offer.kind === "loop"
56
+ ? [seg(" loop"), seg(` · ${offer.detail}`, 7)]
57
+ : [seg(` ${phase} ${fmt(offer.ms)}`), seg(" · no answer or tool call yet", 7)];
58
+ return [...head, seg(` · ${ACT_NOW_KEY} use what you have`), seg(" · ⏎ steer", 5), seg(" · esc stop")];
59
+ }
60
+ /** Under 45 columns the line is just the keys. */
61
+ export const ACT_NOW_NARROW = ` ${ACT_NOW_KEY} · esc`;
@@ -0,0 +1,165 @@
1
+ // Live tool rows (TUI plan #8): one fixed row per call from its first draft until the batch settles — the result rides
2
+ // on the row, never under it, so the block stays 1 + min(N, MAX) rows for its whole life. Every row is fitted to
3
+ // cols−1 on PLAIN text (no OSC-8 path links: clipping an escaped string cuts the escape). Narrowing gives up, in order:
4
+ // a draft's bulk sizes, the elapsed time, then the path's directories (the basename stays).
5
+ import { cellWidth, truncateToWidth } from "./StatusRule.js";
6
+ import { fmtElapsed, formatDuration } from "./format.js";
7
+ import { argsPreview } from "./ToolStep.js";
8
+ import { computeEditDiff } from "./editdiff.js";
9
+ import { fitSegments, seg } from "./fit.js";
10
+ import { fmtTok } from "./format.js";
11
+ import { humanStep } from "./BgPanel.js";
12
+ const SHELL_TOOLS = new Set(["bash", "shell_exec", "shell_background"]);
13
+ const PATH_KEYS = ["path", "file", "filename"];
14
+ /** A row's time: sub-second precision while short ("80ms", "1.1s"), minutes past one ("2m 13s"). */
15
+ const rowTime = (ms) => (ms < 60_000 ? formatDuration(ms) : fmtElapsed(ms));
16
+ /** "src/ui/StatusRule.tsx" → "…/StatusRule.tsx": the basename is what identifies the file at a glance. */
17
+ export function shortPath(p) {
18
+ const i = p.lastIndexOf("/");
19
+ return i > 0 ? `…/${p.slice(i + 1)}` : p;
20
+ }
21
+ function tail(step, now) {
22
+ if (step.status === "selected") {
23
+ if (step.drafting) {
24
+ const t = `drafting ${fmtElapsed(now - (step.startedAt ?? now))}`;
25
+ return { full: t, short: "drafting" };
26
+ }
27
+ return { full: "waiting its turn", short: "waiting" };
28
+ }
29
+ if (step.status === "running")
30
+ return { full: rowTime(now - (step.startedAt ?? now)), short: "" };
31
+ const parts = [];
32
+ if (step.outcome === "blocked")
33
+ parts.push(`blocked${step.summary ? `: ${step.summary}` : ""}`);
34
+ else if (step.outcome === "cancelled")
35
+ parts.push("cancelled");
36
+ else if (step.exitCode !== undefined)
37
+ parts.push(`exit ${step.exitCode}`);
38
+ else if (step.status === "done") {
39
+ const diff = computeEditDiff(step.name, step.args);
40
+ if (diff)
41
+ parts.push(`+${diff.added} -${diff.removed}`);
42
+ else if (step.lines)
43
+ parts.push(`${step.lines} line${step.lines === 1 ? "" : "s"}`);
44
+ }
45
+ const ms = step.durationMs ?? (step.endedAt !== undefined && step.startedAt !== undefined ? step.endedAt - step.startedAt : undefined);
46
+ const short = parts.join(" · ");
47
+ return { full: [...parts, ...(ms !== undefined ? [rowTime(ms)] : [])].join(" · "), short };
48
+ }
49
+ /** One live row: `head` (the tool name, or "$" for a shell call — colored by its kind) and `rest`, fitted so the whole
50
+ * row (padding + status glyph + space + head + rest) stays within cols−1. A name wider than 60% of the row clips first
51
+ * (an MCP name runs to 50-odd cells), so the call's outcome still shows. The first candidate that fits wins: the full
52
+ * row, then without a draft's sizes, then the short tail (no elapsed), then the path's basename only, then no tail. */
53
+ export function liveRow(step, cols, now = Date.now()) {
54
+ const t = tail(step, now);
55
+ const max = cols - 1 - 4; // paddingLeft + the status glyph (counted wide, as cellWidth does) + space
56
+ const shell = SHELL_TOOLS.has(step.name) && typeof step.args?.command === "string";
57
+ const head = shell ? "$" : truncateToWidth(step.name, Math.max(1, Math.min(max - 2, Math.max(12, Math.floor(max * 0.6)))));
58
+ const args = step.args ?? {};
59
+ if (step.name === "delegate_task" && typeof args.task === "string") { // its title is the task the specialist works on
60
+ const task = ` · ${args.task.replace(/\s+/g, " ").trim()}`;
61
+ const roomD = Math.max(1, max - cellWidth(head));
62
+ const withT = t.full ? `${task} · ${t.full}` : task;
63
+ return { head, rest: cellWidth(withT) <= roomD ? withT : t.full ? `${truncateToWidth(task, Math.max(1, roomD - cellWidth(t.full) - 3))} · ${t.full}` : truncateToWidth(task, roomD) };
64
+ }
65
+ const pathKey = PATH_KEYS.find((k) => typeof args[k] === "string");
66
+ const [sized, plain, short] = shell
67
+ ? Array(3).fill(` ${String(args.command).replace(/\s+/g, " ").trim()}`)
68
+ : [
69
+ `(${argsPreview(args, { link: false, sizes: step.sizes })})`,
70
+ `(${argsPreview(args, { link: false })})`,
71
+ `(${argsPreview(pathKey ? { ...args, [pathKey]: shortPath(args[pathKey]) } : args, { link: false })})`,
72
+ ];
73
+ const withTail = (body, tl) => (tl ? `${body} · ${tl}` : body);
74
+ const candidates = [withTail(sized, t.full), withTail(plain, t.full), withTail(plain, t.short), withTail(short, t.short), short];
75
+ const room = Math.max(1, max - cellWidth(head));
76
+ return { head, rest: candidates.find((c) => cellWidth(c) <= room) ?? truncateToWidth(short, room) };
77
+ }
78
+ /** The block's one header line, changing only as calls change state, fitted to the block's width (`cols` less its
79
+ * 1-cell padding) so it never wraps mid-batch: "waiting its turn" shortens, then the counts leave — waiting, drafting,
80
+ * done, running — and a failure goes last; "⇉ N calls" stays. */
81
+ export function batchHeader(rows, cols = 1000) {
82
+ const n = rows.length;
83
+ if (n && rows.every((r) => r.status === "selected" && r.drafting))
84
+ return fitSegments([seg([`drafting ${n} tool call${n === 1 ? "" : "s"}`, `drafting ${n}`], 1, true)], cols - 1);
85
+ const count = (f) => rows.filter(f).length;
86
+ const running = count((r) => r.status === "running");
87
+ const drafting = count((r) => r.status === "selected" && !!r.drafting);
88
+ const waiting = count((r) => r.status === "selected" && !r.drafting);
89
+ const failed = count((r) => r.status === "error");
90
+ const done = count((r) => r.status === "done");
91
+ return fitSegments([
92
+ seg(`⇉ ${n} call${n === 1 ? "" : "s"}`),
93
+ ...(running ? [seg(`${running} running`, 3)] : []),
94
+ ...(done ? [seg(`${done} done`, 4)] : []),
95
+ ...(failed ? [seg(`${failed} failed`, 2)] : []),
96
+ ...(drafting ? [seg(`${drafting} drafting`, 5)] : []),
97
+ ...(waiting ? [seg([`${waiting} waiting its turn`, `${waiting} waiting`], 6)] : []),
98
+ ], cols - 1);
99
+ }
100
+ /** The delegation's own motion (James, 11/04: "a new tui animation for delegation … make it unique"): a mark relayed
101
+ * along a three-cell track, planner → specialist, then a beat of rest — nothing else in the TUI moves this way. */
102
+ const RELAY = ["▸▹▹", "▹▸▹", "▹▹▸", "▹▹▹"];
103
+ const RELAY_TICKS = 2; // shared-clock ticks per step (~240 ms)
104
+ export function relayFrame(frame) {
105
+ return RELAY[Math.floor(frame / RELAY_TICKS) % RELAY.length];
106
+ }
107
+ /** The child line under a running delegate_task (TUI plan #9): the specialist, its round, what it is doing, its ledger
108
+ * and tokens. Narrowing drops the tokens, then the ledger, then the model — "r4 · reading discovery.ts" stays. */
109
+ export function delegateLine(p, cols) {
110
+ const doing = p.tool ? `${humanStep(p.tool)}${p.arg ? ` ${p.arg}` : ""}` : p.thinking ? "thinking" : p.round ? "between rounds" : "starting";
111
+ const shortDoing = p.tool && p.arg ? `${humanStep(p.tool)} ${p.arg.split("/").pop()}` : doing;
112
+ const ledger = [p.writes ? `wrote ${p.writes}` : "", p.reads ? `read ${p.reads}` : "", p.commands ? `ran ${p.commands}` : ""].filter(Boolean).join(" · ");
113
+ return fitSegments([
114
+ seg(p.model, 3),
115
+ seg([`round ${p.round + 1}`, `r${p.round + 1}`], 2, true),
116
+ seg([doing, shortDoing], 1, true),
117
+ ...(ledger ? [seg(ledger, 4)] : []),
118
+ ...(p.tokens ? [seg(`${fmtTok(p.tokens)} tok`, 5)] : []),
119
+ ], cols, { lead: " ▸▹▹ " }).slice(" ▸▹▹ ".length);
120
+ }
121
+ const base = (p) => p.split("/").pop() || p;
122
+ const words = (cmd, n) => cmd.replace(/\s+/g, " ").trim().split(" ").slice(0, n).join(" ");
123
+ /** One call as a chip: its outcome glyph and a few words that identify it ("BgPanel.tsx 195", "npm test exit 1"). */
124
+ export function chipOf(step) {
125
+ const a = step.args ?? {};
126
+ const tone = step.outcome ?? (step.status === "error" ? "error" : "done");
127
+ const glyph = tone === "done" ? "✓" : tone === "error" ? "✗" : "⊘";
128
+ const path = PATH_KEYS.map((k) => a[k]).find((v) => typeof v === "string");
129
+ let label;
130
+ if (SHELL_TOOLS.has(step.name) && typeof a.command === "string")
131
+ label = words(a.command, 2);
132
+ else if (/grep|search|find|glob/.test(step.name) && typeof (a.pattern ?? a.query) === "string")
133
+ label = `${/find|glob/.test(step.name) ? "find" : "grep"} "${String(a.pattern ?? a.query).slice(0, 24)}"`;
134
+ else if (step.name === "web_fetch" && typeof a.url === "string")
135
+ label = a.url.replace(/^https?:\/\//, "").split("/")[0];
136
+ else if (step.name === "delegate_task")
137
+ label = "delegate";
138
+ else if (path)
139
+ label = base(path);
140
+ else
141
+ label = step.name;
142
+ const tail = step.outcome === "blocked" ? "blocked" : step.outcome === "cancelled" ? "cancelled"
143
+ : step.exitCode !== undefined ? `exit ${step.exitCode}`
144
+ : (() => { const d = step.status === "done" ? computeEditDiff(step.name, step.args) : undefined; return d ? `+${d.added} -${d.removed}` : step.lines && !SHELL_TOOLS.has(step.name) ? String(step.lines) : ""; })();
145
+ return { tone, glyph, label: tail ? `${label} ${tail}` : label, name: step.name };
146
+ }
147
+ /** The chip line: "⇉ 4 calls · 3.4s", then chips while they fit in cols−1, the rest folded into "+3 ✓ +1 ✗", then the
148
+ * ctrl+o hint. Failures are never lost to the fold — the caller breaks every failed or refused call out underneath. */
149
+ export function batchChips(steps, durationMs, cols) {
150
+ const head = `⇉ ${steps.length} calls · ${rowTime(durationMs)}`;
151
+ const all = steps.map(chipOf);
152
+ const hint = "ctrl+o";
153
+ const max = cols - 1;
154
+ const width = (chips, folded, h) => cellWidth(head) + chips.reduce((n, c) => n + 2 + cellWidth(`${c.glyph} ${c.label}`), 0) + (folded ? 2 + cellWidth(folded) : 0) + (h ? 3 + cellWidth(h) : 0);
155
+ const foldOf = (rest) => {
156
+ const ok = rest.filter((c) => c.tone === "done").length, bad = rest.length - ok;
157
+ return [ok ? `+${ok} ✓` : "", bad ? `+${bad} ✗` : ""].filter(Boolean).join(" ");
158
+ };
159
+ for (let n = all.length; n >= 0; n--) {
160
+ const shown = all.slice(0, n), folded = foldOf(all.slice(n));
161
+ if (width(shown, folded, hint) <= max)
162
+ return { head, chips: shown, folded, hint };
163
+ }
164
+ return { head: truncateToWidth(head, max), chips: [], folded: cellWidth(head) + 2 + cellWidth(foldOf(all)) <= max ? foldOf(all) : "", hint: "" };
165
+ }