@0perator/operator 0.1.352 → 0.1.354

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/acp/agent.js +4 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +55 -2
  4. package/dist/autonomy/headless.js +4 -1
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1072 -178
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +547 -92
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +135 -30
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +51 -22
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/net-error.js +2 -1
  27. package/dist/engine/owner-act.js +52 -0
  28. package/dist/engine/selfheal.js +48 -0
  29. package/dist/engine/verify-gate.js +52 -0
  30. package/dist/flywheel/processor.js +3 -1
  31. package/dist/flywheel/srft.js +8 -4
  32. package/dist/hooks/index.js +12 -8
  33. package/dist/mcp/index.js +9 -4
  34. package/dist/permissions/index.js +32 -11
  35. package/dist/permissions/modes.js +42 -0
  36. package/dist/permissions/plan-review.js +100 -0
  37. package/dist/permissions/policy.js +16 -5
  38. package/dist/permissions/signature.js +8 -3
  39. package/dist/remote/safe-commands.js +1 -1
  40. package/dist/router/read-rates.js +152 -0
  41. package/dist/selfimprove/backfill.js +174 -0
  42. package/dist/selfimprove/index.js +146 -57
  43. package/dist/selfimprove/lessons.js +429 -0
  44. package/dist/selfimprove/sync.js +58 -0
  45. package/dist/session.js +375 -31
  46. package/dist/skills/finder.js +219 -0
  47. package/dist/tools/deferred.js +28 -18
  48. package/dist/tools/executor.js +7 -3
  49. package/dist/tools/registry.js +34 -4
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
@@ -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)
@@ -1,20 +1,170 @@
1
- import { isErrorResult, resultPreview } from "./format.js";
2
- /** Seed one live row per call, all "running" from the same instant — the batch was just dispatched
3
- * together. Reads and independent bash/shell_exec overlap; conflicting writes and device barriers
4
- * still serialize (BTX). Each row's own elapsed timer ticks per-row once ToolStep renders it. */
5
- export function seedLiveTools(calls, now = Date.now()) {
6
- return calls.map((c) => ({ id: c.id, name: c.name, args: c.args, status: "running", startedAt: now }));
7
- }
8
- /** Flip the ONE row matching `id` to done/error with its real result, live — called from onToolResult
9
- * as each call in the batch settles. Rows are otherwise left untouched (still running), and an id with
10
- * no matching row is a no-op (defensive: a stale/duplicate settle should never throw). */
11
- export function settleLiveTool(rows, id, result, now = Date.now()) {
1
+ import { settledFields } from "./fold.js";
2
+ // Bulky payloads — never dumped (they'd bury the path and blow up the line); shown as a size instead.
3
+ export const BULK_ARGS = ["content", "text", "body", "data", "new_string", "old_string", "diff", "message"];
4
+ const BULK = new Set(BULK_ARGS);
5
+ /** The partial arguments of a call still being written, for DISPLAY only: every key whose string value has closed
6
+ * (path, command, url…), and the running length of each bulk string so far. Nothing is repaired or run — the same
7
+ * string/escape state machine as json-repair's looksTruncated walks the text, and stops at the first unfinished token. */
8
+ export function draftArgs(raw) {
9
+ const args = {};
10
+ const sizes = {};
11
+ const n = raw.length;
12
+ let i = 0;
13
+ const ws = () => { while (i < n && /\s/.test(raw[i]))
14
+ i++; };
15
+ // A JSON string from raw[i] (the opening quote): its decoded text so far and whether it closed.
16
+ const str = () => {
17
+ let out = "";
18
+ i++;
19
+ while (i < n) {
20
+ const ch = raw[i];
21
+ if (ch === '"') {
22
+ i++;
23
+ return { value: out, done: true };
24
+ }
25
+ if (ch !== "\\") {
26
+ out += ch;
27
+ i++;
28
+ continue;
29
+ }
30
+ if (i + 1 >= n)
31
+ return { value: out, done: false };
32
+ const e = raw[i + 1];
33
+ if (e === "u") {
34
+ if (i + 6 > n)
35
+ return { value: out, done: false };
36
+ out += String.fromCharCode(parseInt(raw.slice(i + 2, i + 6), 16) || 0xfffd);
37
+ i += 6;
38
+ continue;
39
+ }
40
+ out += e === "n" ? "\n" : e === "t" ? "\t" : e === "r" ? "\r" : e === "b" ? "\b" : e === "f" ? "\f" : e;
41
+ i += 2;
42
+ }
43
+ return { value: out, done: false };
44
+ };
45
+ // Skip one nested object/array (or scalar); false when it runs off the end of what has streamed.
46
+ const skip = () => {
47
+ let depth = 0;
48
+ while (i < n) {
49
+ const ch = raw[i];
50
+ if (ch === '"') {
51
+ if (!str().done)
52
+ return false;
53
+ continue;
54
+ }
55
+ if (ch === "{" || ch === "[")
56
+ depth++;
57
+ else if (ch === "}" || ch === "]") {
58
+ if (depth === 0)
59
+ return true;
60
+ depth--;
61
+ if (depth === 0) {
62
+ i++;
63
+ return true;
64
+ }
65
+ }
66
+ else if (ch === "," && depth === 0)
67
+ return true;
68
+ i++;
69
+ }
70
+ return false;
71
+ };
72
+ ws();
73
+ if (raw[i] !== "{")
74
+ return { args, sizes };
75
+ i++;
76
+ for (;;) {
77
+ ws();
78
+ if (i >= n || raw[i] === "}")
79
+ break;
80
+ if (raw[i] === ",") {
81
+ i++;
82
+ continue;
83
+ }
84
+ if (raw[i] !== '"')
85
+ break;
86
+ const key = str();
87
+ if (!key.done)
88
+ break;
89
+ ws();
90
+ if (raw[i] !== ":")
91
+ break;
92
+ i++;
93
+ ws();
94
+ if (i >= n)
95
+ break;
96
+ if (raw[i] === '"') {
97
+ const v = str();
98
+ if (BULK.has(key.value))
99
+ sizes[key.value] = v.value.length;
100
+ else if (v.done)
101
+ args[key.value] = v.value;
102
+ if (!v.done)
103
+ break;
104
+ continue;
105
+ }
106
+ const start = i;
107
+ if (!skip())
108
+ break;
109
+ const token = raw.slice(start, i).trim();
110
+ try {
111
+ const v = JSON.parse(token);
112
+ if (typeof v === "number" || typeof v === "boolean")
113
+ args[key.value] = v;
114
+ }
115
+ catch { /* nested: not shown */ }
116
+ }
117
+ return { args, sizes };
118
+ }
119
+ /** Upsert one draft row: a call the model is still writing. Its startedAt is when the draft began ("drafting 1m 12s"). */
120
+ export function draftLiveTool(rows, d, now = Date.now()) {
121
+ const { args, sizes } = draftArgs(d.args);
122
+ const i = rows.findIndex((r) => r.id === d.id);
123
+ if (i < 0)
124
+ return [...rows, { id: d.id, name: d.name, args, sizes, status: "selected", drafting: true, startedAt: now }];
125
+ const next = rows.slice();
126
+ next[i] = { ...rows[i], name: d.name, args, sizes };
127
+ return next;
128
+ }
129
+ export function bufferDraft(pending, d, now = Date.now()) {
130
+ pending.set(d.id, { id: d.id, name: d.name, args: d.args, at: pending.get(d.id)?.at ?? now });
131
+ }
132
+ /** Fold the buffered drafts into the rows — draftLiveTool once per call, a new row's clock from its first piece — and
133
+ * empty the buffer. */
134
+ export function applyDrafts(rows, pending) {
135
+ let next = rows;
136
+ for (const d of pending.values())
137
+ next = draftLiveTool(next, d, d.at);
138
+ pending.clear();
139
+ return next;
140
+ }
141
+ /** The batch was dispatched (onToolStart): one row per call, in call order, each WAITING its turn — not running.
142
+ * A drafted row keeps its id, so it flips in place; its final, parsed args replace the draft's. */
143
+ export function seedLiveTools(calls, rows = []) {
144
+ return calls.map((c) => ({ ...rows.find((r) => r.id === c.id), id: c.id, name: c.name, args: c.args, status: "selected", drafting: false, sizes: undefined, startedAt: undefined }));
145
+ }
146
+ /** The call was really released to run (onToolCallStart): its timer starts now. */
147
+ export function startLiveTool(rows, id, now = Date.now()) {
148
+ let changed = false;
149
+ const next = rows.map((r) => {
150
+ if (r.id !== id || r.status !== "selected")
151
+ return r;
152
+ changed = true;
153
+ return { ...r, status: "running", drafting: false, startedAt: now };
154
+ });
155
+ return changed ? next : rows;
156
+ }
157
+ /** Flip the ONE row matching `id` to its settled state with its real result, live — called from onToolResult as each
158
+ * call in the batch settles (`refused`: the engine's report that a layer answered for it). A row that never got a start
159
+ * signal (a host that doesn't wire onToolCallStart) settles from waiting; an id with no matching row is a no-op (a
160
+ * stale/duplicate settle should never throw). */
161
+ export function settleLiveTool(rows, id, result, now = Date.now(), refused) {
12
162
  let changed = false;
13
163
  const next = rows.map((r) => {
14
- if (r.id !== id || r.status !== "running")
164
+ if (r.id !== id || (r.status !== "running" && r.status !== "selected"))
15
165
  return r;
16
166
  changed = true;
17
- return { ...r, status: isErrorResult(result) ? "error" : "done", endedAt: now, summary: resultPreview(result) };
167
+ return { ...r, ...settledFields(result, refused), drafting: false, endedAt: now };
18
168
  });
19
169
  return changed ? next : rows;
20
170
  }
@@ -5,6 +5,9 @@ import { BYO_PRESETS, fmtCtx, pickerRow, shortName } from "../router/models.js";
5
5
  import { markPickerOptions, portalIdFor } from "../router/portal.js";
6
6
  import { CONTEXT_PRESETS } from "../config/settings.js";
7
7
  import { DISCUSS } from "./QuestionPrompt.js";
8
+ import { fitSegments, seg } from "./fit.js";
9
+ import { cellWidth, truncateToWidth } from "./StatusRule.js";
10
+ import { approxTokens, fmtWait, fmtWhen, readSeconds } from "../router/read-rates.js";
8
11
  /** The last /model row: an action, never a ModelProfile — so the lists fed from the registry (the ACP dropdown, a
9
12
  * follower's model list) can never offer it. */
10
13
  export const CONNECT_ROW = "+ Connect a provider key (Anthropic, Google, Nous, OpenAI, …)";
@@ -18,14 +21,44 @@ const group = (m) => (m.kind === "orchestrated" ? 3 : m.tier === "free" ? 2 : m.
18
21
  export function pickerOrder(models) {
19
22
  return models.map((m, i) => ({ m, i })).sort((a, b) => group(a.m) - group(b.m) || a.i - b.i).map(({ m }) => m);
20
23
  }
24
+ /** A row's cost tail as fit parts: the source of the rate gives way first, then the time; the size always stays. Over
25
+ * the model's window it says so instead. No measured rate → the size and "read speed not measured yet", never a guess.
26
+ * "up to": the model may still hold part of this prefix from an earlier turn. */
27
+ export function costParts(c, now = Date.now()) {
28
+ if (!c)
29
+ return [];
30
+ if (c.window && c.tokens > c.window)
31
+ return [seg(` · this conversation (${approxTokens(c.tokens)}) is over its window`)];
32
+ const secs = readSeconds(c.tokens, c.rate);
33
+ if (secs === undefined)
34
+ return [seg(` · re-reads up to ${approxTokens(c.tokens)}`), seg(" (read speed not measured yet)", 2)];
35
+ return [seg(` · re-reads up to ${approxTokens(c.tokens)}`), seg(` ≈ ${fmtWait(secs)}`, 1), seg(` (${Math.round(c.rate.tokPerSec)} tok/s, ${fmtWhen(c.rate.at, now)})`, 2)];
36
+ }
37
+ // The QuestionPrompt box spends ~16 cells around a row (border, padding, "❯ [12] ", a portal marker): rows are fitted to
38
+ // what is left so a cost tail never wraps a row (click anchoring counts one line per row).
39
+ const ROW_CHROME = 16;
21
40
  /** The /model rows in picker order — pickerRow for each (the active single model shows its served window), " · cached"
22
- * on free rows served from the disk cache — closed by the connect row. */
41
+ * on free rows served from the disk cache, and with `cost` the re-read each switch would cost — closed by the connect
42
+ * row. With `cols`, a row with a cost is fitted to one line. */
23
43
  export function modelPickerView(models, o) {
24
44
  const ordered = pickerOrder(models);
25
45
  const rows = ordered.map((m) => {
26
46
  const active = m.id === o.active;
27
47
  const row = pickerRow(m, { servedCtx: active && m.kind === "single" ? o.servedCtx : undefined });
28
- return `${row}${o.staleFree && m.tier === "free" ? " · cached" : ""}${active ? " (active)" : ""}`;
48
+ const cost = active ? [] : costParts(o.cost?.(m), o.now);
49
+ const tail = `${o.staleFree && m.tier === "free" ? " · cached" : ""}${active ? " (active)" : ""}`;
50
+ if (!cost.length)
51
+ return `${row}${tail}`;
52
+ const segs = [seg(row), ...cost, ...(tail ? [seg(tail)] : [])];
53
+ if (!o.cols)
54
+ return segs.map((x) => x.forms[0]).join("");
55
+ const width = Math.max(20, o.cols - ROW_CHROME);
56
+ const fitted = fitSegments(segs, width, { sep: "" });
57
+ if (cellWidth(segs.map((x) => x.forms[0]).join("")) <= width - 1 || !fitted.endsWith("…"))
58
+ return fitted;
59
+ // Still too wide once the rate's parts gave way: the name gives way, the size stays ("re-reads up to ~61K").
60
+ const keep = `${cost[0].forms[0]}${tail}`;
61
+ return `${truncateToWidth(row, Math.max(8, width - 1 - cellWidth(keep)))}${keep}`;
29
62
  });
30
63
  return {
31
64
  rows: [...rows, CONNECT_ROW],
@@ -88,11 +121,50 @@ export function pickerAnswer(entries, answer, index) {
88
121
  const typed = answer.trim();
89
122
  return !typed || answer === DISCUSS ? null : { typed };
90
123
  }
91
- /** The /model line after a pick: `model → <id> · ctx N% · turns N`; a free row repeats its caveat instead. */
92
- export function modelLine(id, chosen, ctxPct, turns) {
124
+ /** The /model line after a pick: `model → <id> · ctx N% · turns N`; a free row repeats its caveat instead. With the
125
+ * switch's measured cost it adds what the next message will re-read (TUI A3.6). */
126
+ export function modelLine(id, chosen, ctxPct, turns, cost, now = Date.now()) {
127
+ const reread = cost && cost.tokens > 0 && !(cost.window && cost.tokens > cost.window)
128
+ ? ` · re-reads up to ${approxTokens(cost.tokens)} on your next message${(() => { const secs = readSeconds(cost.tokens, cost.rate); return secs === undefined ? "" : ` (≈ ${fmtWait(secs)} at ${Math.round(cost.rate.tokPerSec)} tok/s, measured ${fmtWhen(cost.rate.at, now)})`; })()}`
129
+ : cost?.window && cost.tokens > cost.window ? ` · this conversation (${approxTokens(cost.tokens)}) is over its window — the first turn compacts it` : "";
93
130
  if (chosen?.tier === "free")
94
- return `model → ${id} · ${chosen.desc ?? "free tier"}`;
95
- return `model → ${id} · ctx ${ctxPct}% · turns ${turns}`;
131
+ return `model → ${id} · ${chosen.desc ?? "free tier"}${reread}`;
132
+ return `model → ${id} · ctx ${ctxPct}% · turns ${turns}${reread}`;
133
+ }
134
+ /** Whether a pick earns the re-read confirm step: 16K tokens or more to re-read, unless a measured read says it takes
135
+ * under 30 s — or a conversation that is over the model's window. */
136
+ export function wantsRereadConfirm(c) {
137
+ if (!c)
138
+ return false;
139
+ if (c.window && c.tokens > c.window)
140
+ return true;
141
+ if (c.tokens < 16_000)
142
+ return false;
143
+ const secs = readSeconds(c.tokens, c.rate);
144
+ return secs === undefined || secs >= 30;
145
+ }
146
+ /** The confirm step: switch now (the next turn starts with that read), compact on the current, cache-warm model first
147
+ * (priced as its summary cap at its measured decode rate, then the bounded re-read at the target's rate), or stay.
148
+ * Every time shown comes from a measured rate; an unmeasured one shows sizes only. */
149
+ export function rereadConfirmView(o) {
150
+ const { target, current, cost } = o;
151
+ const over = !!(cost.window && cost.tokens > cost.window);
152
+ const secs = readSeconds(cost.tokens, cost.rate);
153
+ const measured = secs === undefined ? "" : ` ≈ ${fmtWait(secs)} (${Math.round(cost.rate.tokPerSec)} tok/s, measured ${fmtWhen(cost.rate.at, o.now)})`;
154
+ const question = over
155
+ ? `${target} can't hold this conversation (${approxTokens(cost.tokens)} > its ${approxTokens(cost.window).slice(1)} window): its first turn compacts it`
156
+ : `${target} may have none of this cached: it re-reads up to ${approxTokens(cost.tokens)} tok${measured}`;
157
+ const rows = [over ? "Switch now · the first turn compacts the conversation" : "Switch now · the next turn starts with that read"];
158
+ const choices = ["switch"];
159
+ if (o.compact) {
160
+ const sum = readSeconds(o.compact.summaryMax, o.compact.decode);
161
+ const after = readSeconds(o.compact.afterMax, cost.rate);
162
+ rows.push(`Compact on ${current} first (cache-warm${sum === undefined ? "" : `, ≈${fmtWait(sum)}`}), then switch · re-read ≤${approxTokens(o.compact.afterMax).slice(1)}${after === undefined ? "" : ` ≈ ${fmtWait(after)}`}`);
163
+ choices.push("compact");
164
+ }
165
+ rows.push(`Stay on ${current}`);
166
+ choices.push("stay");
167
+ return { question, rows, choices };
96
168
  }
97
169
  /** After a key is stored: the rows it unlocked, by name — or why none show yet. */
98
170
  export function keyStoredLine(account, rows, preset, free = false) {
@@ -0,0 +1,103 @@
1
+ import { fitSegments, seg } from "./fit.js";
2
+ import { approxTokens } from "../router/read-rates.js";
3
+ /** The bound /compact can promise, as the strip shows it: "61K → ≤18K". */
4
+ export function compactCost(est) {
5
+ if (!est || est.afterMax >= est.before)
6
+ return undefined;
7
+ return `${approxTokens(est.before).slice(1)} → ≤${approxTokens(est.afterMax).slice(1)}`;
8
+ }
9
+ const REASONING_TAIL = 2400; // chars of the kept reasoning handed back with "continue from that reasoning"
10
+ /** The steps after an Esc. With reasoning on screen, "continue from that reasoning" hands its tail back to the model —
11
+ * it never reached the model's context (the interrupted round is dropped). "think off" changes enable_thinking for that
12
+ * one turn only, so the system prompt — and the cached prefix — stay as they are. */
13
+ export function interruptSteps(o) {
14
+ const r = (o.reasoning ?? "").trim();
15
+ const tail = r.length > REASONING_TAIL ? `…${r.slice(-REASONING_TAIL)}` : r;
16
+ const cont = r
17
+ ? { label: "continue from that reasoning", short: "continue", action: { kind: "send", display: "continue from that reasoning",
18
+ text: `Continue from where you were when I stopped you. Your reasoning up to that point never reached you; here is how it ended:\n\n${tail}` } }
19
+ : { label: "continue", short: "continue", action: { kind: "send", display: "continue", text: "Continue from where you were when I stopped you." } };
20
+ const steps = [
21
+ cont,
22
+ { label: "continue, think off", short: "no-think", action: { kind: "send", display: "continue, think off", text: "Continue from where you were when I stopped you.", thinkOff: true } },
23
+ ];
24
+ const cost = compactCost(o.compact);
25
+ if (cost)
26
+ steps.push({ label: "compact, then continue", short: "compact", cost, action: { kind: "compact-send", display: "compact, then continue", text: "Continue from where you were when I stopped you." } });
27
+ steps.push({ label: "model…", short: "model", action: { kind: "model" } });
28
+ return steps;
29
+ }
30
+ /** The steps after an engine stop: the stop's own options, sent verbatim, so the model's behavior does not change —
31
+ * plus "show what it had" when a cut reply was kept on screen, and "think off" where reasoning is the likely cause.
32
+ * Null when there is nothing to offer: no strip, never an empty one that eats the next Esc (review F13). */
33
+ export function engineStopSteps(kind, o = {}) {
34
+ const steps = stopSteps(kind, o);
35
+ return steps.length ? steps : null;
36
+ }
37
+ function stopSteps(kind, o) {
38
+ const send = (label, short, text, thinkOff = false) => ({ label, short, action: { kind: "send", display: label, text, thinkOff: thinkOff || undefined } });
39
+ const cost = compactCost(o.compact);
40
+ const compactStep = (label, text) => (cost ? [{ label, short: "compact", cost, action: { kind: "compact-send", display: label, text } }] : []);
41
+ switch (kind) {
42
+ case "repetition": return [
43
+ send("another pass, different approach", "retry", "Take another pass with a different approach."),
44
+ ...(o.partialChars ? [{ label: "show what it had", short: "show", cost: `${approxTokens(o.partialChars).slice(1)} chars, cut`, action: { kind: "show" } }] : []),
45
+ send("another pass, think off", "no-think", "Take another pass with a different approach.", true),
46
+ ];
47
+ case "reasoning_budget": return [
48
+ send("go ahead with the next step", "go", "Go ahead with the next concrete step."),
49
+ send("go ahead, think off", "no-think", "Go ahead with the next concrete step.", true),
50
+ ];
51
+ case "paused": return [send("keep going", "go", "Keep going from here."), ...compactStep("compact, then keep going", "Keep going from here.")];
52
+ case "window": return compactStep("compact, then carry on", "Carry on from here.");
53
+ case "rounds": return [send("continue", "continue", "Continue from here."), send("continue, think off", "no-think", "Continue from here.", true)];
54
+ case "unanswered": return [send("send it again", "again", "Answer my last message — nothing answered it last time."), { label: "model…", short: "model", action: { kind: "model" } }];
55
+ case "length": return [send("continue", "continue", "Continue exactly where you stopped.")];
56
+ case "yield": return [
57
+ send("keep going meanwhile", "go", "Keep going on the next step meanwhile."),
58
+ send("take a step over yourself", "take over", "Take the delegated step over yourself."),
59
+ ];
60
+ case "owner": return [
61
+ send("answer from what you have", "answer", "Answer now from what you have — no more tool calls.", true),
62
+ send("keep working on it", "go", "Keep working on it."),
63
+ ];
64
+ case "stopped": return [send("try a different way", "retry", "Try a different way."), send("try a different way, think off", "no-think", "Try a different way.", true)];
65
+ }
66
+ }
67
+ /** The strip, one line fitted to cols−1: " 1 continue 2 continue, think off 3 compact, then continue (61K → ≤18K)
68
+ * 4 model… or type". The cost parentheses go first, then the labels shorten; under 50 columns it reads
69
+ * "1·2·3·4 or type". */
70
+ export function nextStepLine(steps, cols) {
71
+ if (!steps.length)
72
+ return "";
73
+ if (cols < 50)
74
+ return fitSegments([seg(`${steps.map((_, i) => i + 1).join("·")} or type`)], cols, { lead: " " });
75
+ const segs = [];
76
+ steps.forEach((s, i) => {
77
+ segs.push(seg(`${i + 1} `), seg([s.label, s.short], 1, true));
78
+ if (s.cost)
79
+ segs.push(seg(` (${s.cost})`, 2));
80
+ segs.push(seg(" "));
81
+ });
82
+ segs.push(seg("or type"));
83
+ return fitSegments(segs, cols, { lead: " ", sep: "" });
84
+ }
85
+ /** The step a key picks: a digit within range, on an EMPTY draft (any other key types normally and hides the strip). */
86
+ export function pickStep(input, steps, draftEmpty) {
87
+ if (!draftEmpty || !/^[1-9]$/.test(input))
88
+ return undefined;
89
+ return steps[Number(input) - 1];
90
+ }
91
+ /** The partial on screen at an Esc, settled as an entry (so "output above kept" is true for what the owner was
92
+ * watching), and the line after it saying it is screen-only. Null when nothing had streamed. */
93
+ export function settledPartial(text, reasoning) {
94
+ const t = text.trim();
95
+ const r = reasoning.trim();
96
+ if (!t && !r)
97
+ return null;
98
+ const chars = t.length + r.length;
99
+ return {
100
+ entry: { content: t, reasoning: r || undefined },
101
+ note: ` ${approxTokens(chars).slice(1)} chars of that reply kept above, on screen only — never sent to the model`,
102
+ };
103
+ }