@vecteur/cli 0.10.0 → 0.11.1

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.
package/src/terminal.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import { ComposerInput } from "./input.js";
2
2
  import { command, completions, SHORTCUTS } from "./commands.js";
3
3
  import { Session } from "./session.js";
4
- import { terminalText as safe, taskLines } from "./format.js";
4
+ import { terminalText as safe, humanRunSections } from "./format.js";
5
+ import { blockText } from "./blocks.js";
5
6
  import { preferences } from "./preferences.js";
6
7
  import { openBrowser } from "./browser.js";
7
8
  import { readFileSync } from "node:fs";
@@ -36,13 +37,21 @@ export class TerminalWriter {
36
37
  if (this.awaiting) this.since += rows;
37
38
  else if (this.row) this.row = Math.min(this.stdout.rows ?? 24, this.row + rows);
38
39
  }
39
- progress(view) {
40
+ progress(view, { controlsOnly = false } = {}) {
40
41
  const subject = view.run?.subject?.id;
41
- if (subject !== this.subject) { this.subject = subject; this.lastProgress = null; this.lastQuestion = null; }
42
+ if (subject !== this.subject) { this.subject = subject; this.lastProgress = null; this.lastQuestion = null; this.controls = new Map(); }
42
43
  if (!subject || view.run.terminal) return;
43
- if (view.run.progress && view.run.progress !== this.lastProgress) {
44
+ if (!controlsOnly && view.run.progress && view.run.progress !== this.lastProgress) {
44
45
  this.append(safe(`${view.run.progress} · ${view.run.elapsed ?? "Elapsed unavailable"}`)); this.lastProgress = view.run.progress;
45
46
  }
47
+ for (const block of view.run.blocks ?? []) {
48
+ if (block.kind !== "control") continue;
49
+ const signature = JSON.stringify(block.payload);
50
+ if (this.controls.get(block.key) === signature) continue;
51
+ this.controls.set(block.key, signature);
52
+ this.append(safe(`Controls:\n${blockText(block)}`));
53
+ }
54
+ if (controlsOnly) return;
46
55
  const question = view.run.question;
47
56
  if (question?.id !== this.lastQuestion) {
48
57
  this.lastQuestion = question?.id;
@@ -110,7 +119,13 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
110
119
  if (!options.plain) throw error;
111
120
  prefs = { plain: true, reducedMotion: true };
112
121
  }
113
- let rich = !options.plain && !prefs.plain && env.TERM !== "dumb";
122
+ let rich = stdout.isTTY === true && !options.plain && !prefs.plain && env.TERM !== "dumb";
123
+ let pasteMode = false;
124
+ const syncPasteMode = () => {
125
+ if (pasteMode === rich) return;
126
+ pasteMode = rich;
127
+ stdout.write(pasteMode ? "\x1b[?2004h" : "\x1b[?2004l");
128
+ };
114
129
  const color = !options.noColor && env.NO_COLOR === undefined;
115
130
  // Colour roles start palette-relative; a terminal that reports its own colours gets exact blends.
116
131
  let theme = color; const reported = {};
@@ -128,8 +143,8 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
128
143
  // While a vendor owns the TTY (handoff) Vecteur writes nothing: frames, clocks, streamed
129
144
  // steps and messages wait, and are flushed once when the vendor exits.
130
145
  let vendorOwnsTerminal = false, resizedDuringHandoff = false; const heldMessages = [];
131
- // Rich scrollback streams each finished step as one line; the answer block then skips them.
132
- const streamed = { run: null, events: 0, steps: 0 };
146
+ // Immutable event blocks commit once; mutable controls have their own live/final section.
147
+ const streamed = { run: null, keys: new Set() };
133
148
  // The identity header is live until the first transcript block, then committed once.
134
149
  let headerLive = true, cursorHidden = false;
135
150
  const directory = () => session.cwd === homedir() || session.cwd.startsWith(homedir() + "/") ? "~" + session.cwd.slice(homedir().length) : session.cwd;
@@ -161,7 +176,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
161
176
  // The real cursor stays hidden in rich mode (the composer draws its own caret) and always
162
177
  // returns on exit, error, plain fallback and vendor handoff.
163
178
  const showCursor = visible => {
164
- if (env.TERM === "dumb" || visible !== cursorHidden) return;
179
+ if (env.TERM === "dumb" || !stdout.isTTY || visible !== cursorHidden) return;
165
180
  cursorHidden = !visible; stdout.write(visible ? "\x1b[0m\x1b[?25h" : "\x1b[?25l");
166
181
  };
167
182
  const restoreCursor = () => showCursor(true);
@@ -184,29 +199,28 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
184
199
  };
185
200
  const locate = (query = "") => { if (!writer.plain) { input.expectReports ||= !!query; writer.locate(query); } };
186
201
  const schedule = () => { if (!frameTimer && !vendorOwnsTerminal) frameTimer = setTimeout(() => { frameTimer = null; draw(); }, 40); };
187
- const printPlainPrompt = prompt => writer.append(safe(`${prompt.title}\n${prompt.options.map((row, i) => `${i + 1}. ${row.label}`).join("\n")}\nEnter a choice; Esc returns to your draft.`));
202
+ const printPlainPrompt = prompt => writer.append(safe(`${prompt.card ?? prompt.title}\n${prompt.options.map((row, i) => `${i + 1}. ${row.label}`).join("\n")}\nEnter a choice; Esc returns to your draft.`));
188
203
  const maybeUpdate = () => {
189
204
  if (updateChecked || session.closed || session.offline || session.busy || session.prompt || session.loginChallenge || session.run?.open || session.registry?.state().pendingRun || session.registry?.state().pendingCreate || !session.release) return;
190
205
  updateChecked = true;
191
206
  void import("./update.js").then(({ interactiveUpdate }) => interactiveUpdate(session, { automatic: true })).catch(error => session.report(error));
192
207
  };
208
+ const commitBlocks = (runId, blocks) => {
209
+ if (streamed.run !== runId) { streamed.run = runId; streamed.keys = new Set(); }
210
+ for (const block of blocks) {
211
+ if (!block.committed || ["control", "terminal"].includes(block.kind) || streamed.keys.has(block.key)) continue;
212
+ print(writer.plain ? blockText(block) : layout.richMessage({ kind: "block", block }, stdout.columns ?? 80, theme));
213
+ streamed.keys.add(block.key);
214
+ }
215
+ };
193
216
  session.on("change", view => {
194
217
  if (vendorOwnsTerminal) return;
195
218
  const ticking = !writer.plain && !view.offline && session.run?.open;
196
219
  if (ticking && !clockTimer) clockTimer = setInterval(() => { tick++; draw(); }, prefs.reducedMotion ? 1000 : 200);
197
220
  if (!ticking) { clearInterval(clockTimer); clockTimer = null; }
198
221
  const run = session.run;
199
- if (!writer.plain && run?.open && Array.isArray(run.events)) {
200
- if (streamed.run !== run.run_id) Object.assign(streamed, { run: run.run_id, events: 0, steps: 0 });
201
- for (; streamed.events < run.events.length; streamed.events++) {
202
- const event = run.events[streamed.events];
203
- if (event?.kind !== "step_finished") continue;
204
- const [row] = taskLines([event]);
205
- if (!row) continue;
206
- if (!streamed.steps++) print("");
207
- print(layout.richMessage({ kind: "step", text: row.split("\n").map(part => part.trim().replace(/^[▸·]\s*/, "")).filter(Boolean).join(" · ") }, stdout.columns ?? 80, theme));
208
- }
209
- }
222
+ if (!writer.plain && (stdout.rows ?? 24) < 18) writer.progress(view, { controlsOnly: true });
223
+ if (run?.open && Array.isArray(run.events)) commitBlocks(run.run_id, view.run.blocks);
210
224
  if (process.connected && process.send && env.VECTEUR_UPDATE_SESSION && session.release?.compatible
211
225
  && session.registry && (!view.busy || view.prompt)) {
212
226
  const nonce = env.VECTEUR_UPDATE_SESSION; delete env.VECTEUR_UPDATE_SESSION;
@@ -225,7 +239,9 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
225
239
  if (view.prompt && !activePrompt) snapshot = { text: input.text.startsWith("/") ? session.draft : input.text, cursor: input.cursor, undo: input.undo, killed: input.killed };
226
240
  activePrompt = view.prompt; selected = 0; focusChanged();
227
241
  if (activePrompt) {
228
- input.undo = []; input.killed = ""; syncInput(""); if (writer.plain) printPlainPrompt(activePrompt);
242
+ input.undo = []; input.killed = ""; syncInput("");
243
+ if (writer.plain) printPlainPrompt(activePrompt);
244
+ else if (activePrompt.card) print(layout.richMessage({ kind: "notice", text: `${activePrompt.card}\n${activePrompt.options.map((row,i)=>`${i+1}. ${row.label}`).join("\n")}` }, stdout.columns ?? 80, theme), false);
229
245
  } else {
230
246
  const restored = snapshot && snapshot.text === session.draft ? snapshot : { text: session.draft, cursor: session.draft.length };
231
247
  syncInput(restored.text, Math.min(restored.cursor, restored.text.length)); input.undo = restored.undo ?? []; input.killed = restored.killed ?? ""; snapshot = null;
@@ -237,13 +253,23 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
237
253
  schedule(); queueMicrotask(maybeUpdate);
238
254
  });
239
255
  session.on("preferences", value => {
240
- prefs = value; rich = !options.plain && !prefs.plain && env.TERM !== "dumb";
256
+ prefs = value; rich = stdout.isTTY === true && !options.plain && !prefs.plain && env.TERM !== "dumb";
257
+ syncPasteMode();
241
258
  writer.resized(isPlain()); showCursor(writer.plain); locate(); session.change(); draw();
242
259
  });
243
260
  session.on("message", message => {
244
261
  if (vendorOwnsTerminal) { heldMessages.push(message); return; }
245
- print(writer.plain ? safe(message.text) : layout.richMessage(message, stdout.columns ?? 80, theme,
246
- { stepsShown: message.runId && message.runId === streamed.run ? streamed.steps : 0 }), ["user", "answer", "cost"].includes(message.kind));
262
+ // Flush the terminal prefix too: unmatched calls close only in the final direct record.
263
+ if (message.kind === "answer" && message.sections?.blocks) commitBlocks(message.runId, message.sections.blocks);
264
+ const shownKeys = new Set(message.runId === streamed.run ? streamed.keys : []);
265
+ if (message.runId === writer.subject) {
266
+ for (const block of message.sections?.blocks ?? []) if (block.kind === "control"
267
+ && writer.controls?.get(block.key) === JSON.stringify(block.payload)) shownKeys.add(block.key);
268
+ }
269
+ const text = writer.plain ? message.kind === "answer" && message.sections
270
+ ? safe(humanRunSections(message.sections, { shownKeys })) : safe(message.text)
271
+ : layout.richMessage(message, stdout.columns ?? 80, theme, { shownKeys });
272
+ print(text, ["user", "answer", "turn-footer"].includes(message.kind));
247
273
  plainDraft = "";
248
274
  });
249
275
  session.on("copy", answer => {
@@ -310,7 +336,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
310
336
  clearTimeout(frameTimer); frameTimer = null; clearInterval(clockTimer); clockTimer = null;
311
337
  stdin.off("data", onData); stdin.setRawMode(false); stdin.pause();
312
338
  process.off("SIGINT", onSignal);
313
- writer.clearLive(); commitHeader(); showCursor(true); if (env.TERM !== "dumb") stdout.write("\x1b[?2004l");
339
+ writer.clearLive(); commitHeader(); showCursor(true); if (pasteMode) stdout.write("\x1b[?2004l");
314
340
  const { VENDORS, executingServer, runVendor, vendorArgv } = await import("./vendors.js");
315
341
  writer.append(`Opening your ${VENDORS[vendor]} terminal with Vecteur attached for this session only. Exit it to return.`);
316
342
  let note;
@@ -320,7 +346,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
320
346
  finally {
321
347
  vendorOwnsTerminal = false;
322
348
  process.once("SIGINT", onSignal);
323
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004h");
349
+ if (pasteMode) stdout.write("\x1b[?2004h");
324
350
  stdin.setRawMode(true); stdin.resume(); stdin.on("data", onData);
325
351
  }
326
352
  // The vendor's output is history now; find where it left the cursor before drawing again.
@@ -342,6 +368,16 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
342
368
  selected = 0; focusChanged(); syncInput(""); if (writer.plain) printPlainPrompt(localPicker); draw();
343
369
  });
344
370
  input.on("complete", () => {
371
+ const mention = /(?:^|\s)@([^\s]*)$/.exec(input.text.slice(0,input.cursor));
372
+ if (mention && !session.prompt) {
373
+ const completionText=input.text, completionCursor=input.cursor;
374
+ void session.completeFiles(mention[1]).then(paths => {
375
+ if(input.text!==completionText || input.cursor!==completionCursor)return;
376
+ if (paths.length === 1) { input.replace(input.cursor-mention[1].length,input.cursor,paths[0]); draw(); }
377
+ else if (paths.length) session.message(paths.map(p=>'@'+p).join('\n'));
378
+ }).catch(error=>session.report(error));
379
+ return;
380
+ }
345
381
  const row = palette()[paletteSelected]; if (row) { syncInput(`/${row.name}${row.argument ? " " : ""}`); draw(); }
346
382
  });
347
383
  const cancel = () => {
@@ -398,10 +434,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
398
434
  });
399
435
  input.on("exit", () => { try { session.close(); } catch (error) { session.report(error); } });
400
436
  const onData = chunk => {
401
- if (env.TERM === "dumb" && !input.pasting && (String(chunk).match(/[\r\n]/g)?.length ?? 0) > 1) {
402
- input.insert(String(chunk).replace(/\r\n?/g, "\n")); return;
403
- }
404
- input.feed(chunk);
437
+ input.feed(chunk, { unbracketed: !pasteMode });
405
438
  };
406
439
  const onResize = () => {
407
440
  // The vendor owns the TTY: not one byte; the new geometry is applied once on restore.
@@ -415,7 +448,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
415
448
  const done = new Promise(resolve => session.once("close", resolve));
416
449
  stdin.setRawMode(true); stdin.resume(); stdin.on("data", onData); stdout.on("resize", onResize);
417
450
  process.once("SIGTERM", onSignal); process.once("SIGHUP", onSignal); process.once("SIGINT", onSignal);
418
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004h");
451
+ syncPasteMode();
419
452
  process.on("exit", restoreCursor);
420
453
  if (writer.plain) writer.append(`Vecteur ${version}${channel === "preview" ? " · Preview" : ""} · ${safe(session.origin)}`);
421
454
  else { showCursor(false); locate(color ? "\x1b]10;?\x1b\\\x1b]11;?\x1b\\" : ""); }
@@ -426,7 +459,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
426
459
  clearTimeout(frameTimer); clearInterval(clockTimer); input.close(); stdin.off("data", onData); stdout.off("resize", onResize);
427
460
  process.off("SIGTERM", onSignal); process.off("SIGHUP", onSignal); process.off("SIGINT", onSignal);
428
461
  writer.clearLive(); writer.close(); commitHeader(); showCursor(true); process.off("exit", restoreCursor);
429
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004l");
462
+ if (pasteMode) stdout.write("\x1b[?2004l");
430
463
  stdin.setRawMode(false); stdin.pause();
431
464
  stdout.write(session.restart ? "Restarting Vecteur…\n" : session.run?.open ? "Detached. The cloud Run continues; run vecteur here to follow it.\n" : "Session closed.\n");
432
465
  }
package/src/tui/view.js CHANGED
@@ -1,13 +1,12 @@
1
1
  import stringWidth from "string-width";
2
2
  import wrapAnsi from "wrap-ansi";
3
3
  import { parseMarkdown } from "../markdown.js";
4
- import { terminalText } from "../format.js";
4
+ import { blockContent } from "../blocks.js";
5
+ import { terminalText, plainLine, taskLines } from "../format.js";
5
6
 
6
- // Colour roles, each one SGR parameter list. A theme of `null` is NO_COLOR / --no-color: no
7
- // styling at all. Without a palette report every role stays relative to the user's own palette:
8
- // faint for secondary/quiet text and rules, no input fill (a rule-only composer).
9
- export const DEFAULT_THEME = Object.freeze({ accent: "38;5;81", attention: "33", secondary: "2", quiet: "2",
10
- rule: "2", band: "", strong: "1", em: "3", link: "4" });
7
+ // Unknown palette: the terminal owns its readable default pair. Only repeated metadata is faint.
8
+ export const DEFAULT_THEME = Object.freeze({ primary: "", accent: "1", attention: "1", success: "1", error: "1",
9
+ secondary: "", quiet: "2", rule: "", band: "", strong: "1", em: "3", link: "4" });
11
10
  const themeOf = color => color === true ? DEFAULT_THEME : color || null;
12
11
  const RESET = { 1: "22", 2: "22", 3: "23", 4: "24", 7: "27", 38: "39", 48: "49" };
13
12
  // Targeted resets, never SGR 0: a role inside the input band must not clear the band.
@@ -21,7 +20,7 @@ const style = (value, code, theme) => {
21
20
  }
22
21
  return `\x1b[${code}m${value}\x1b[${[...new Set(close)].join(";")}m`;
23
22
  };
24
- const paint = (value, role, theme) => style(value, theme?.[role], theme);
23
+ const paint = (value, role = "primary", theme) => style(value, theme?.[role], theme);
25
24
 
26
25
  // Terminal palette → roles. The reference values are blends of the terminal's own foreground
27
26
  // toward its background; text roles are pulled back toward the foreground until they reach 4.5:1.
@@ -40,26 +39,47 @@ function xterm256([r, g, b]) {
40
39
  // The colour a 256-colour terminal actually shows for an index.
41
40
  const shown = index => index >= 232 ? Array(3).fill(8 + (index - 232) * 10)
42
41
  : [Math.floor((index - 16) / 36), Math.floor((index - 16) / 6) % 6, (index - 16) % 6].map(i => cube[i]);
43
- export function paletteTheme({ fg, bg }, truecolor = false) {
44
- // Every check runs on the colour the terminal will render, never on the pre-rounding value.
42
+ /** Fail loudly when no rendered colour satisfies the actual backgrounds. */
43
+ export function readable(from, grounds, { fg, render = rgb => rgb, excluded = [] } = {}) {
44
+ const allowed = rgb => grounds.every(ground => contrast(rgb, ground) >= 4.5)
45
+ && !excluded.some(other => other.every((channel, index) => channel === rgb[index]));
46
+ for (const toward of [fg ?? from, [0, 0, 0], [255, 255, 255]]) {
47
+ for (let step = 0; step <= 100; step++) {
48
+ const value = render(mix(from, toward, step / 100));
49
+ if (allowed(value)) return value;
50
+ }
51
+ }
52
+ // Near-threshold palettes can exhaust a blend's quantized colours. Search rendered candidates too.
53
+ const levels = [0, 32, 64, 96, 128, 160, 192, 224, 255];
54
+ const candidates = levels.flatMap(r => levels.flatMap(g => levels.map(b => render([r, g, b]))));
55
+ candidates.sort((a, b) => a.reduce((sum, v, i) => sum + (v - from[i]) ** 2, 0)
56
+ - b.reduce((sum, v, i) => sum + (v - from[i]) ** 2, 0));
57
+ const found = candidates.find(allowed);
58
+ if (found) return found;
59
+ throw new RangeError("No readable rendered colour at 4.5:1 for these backgrounds");
60
+ }
61
+
62
+ export function paletteTheme({ fg, bg, red, green }, truecolor = false) {
45
63
  const render = rgb => truecolor ? rgb : shown(xterm256(rgb));
46
64
  const code = (rgb, layer = 38) => truecolor ? `${layer};2;${rgb.join(";")}` : `${layer};5;${xterm256(rgb)}`;
47
65
  const band = render(mix(fg, bg, 0.88));
48
- // Pull toward the foreground until legible on the background and, for roles drawn inside the
49
- // input band (placeholder, caret), on the band too.
50
- const readable = (from, grounds) => {
51
- for (let t = 0; t <= 1; t += 0.05) {
52
- const value = render(mix(from, fg, t));
53
- if (grounds.every(ground => contrast(value, ground) >= 4.5)) return value;
54
- }
55
- return render(fg);
66
+ const grounds = [bg, band], used = [];
67
+ const pick = (base, distinct = false) => {
68
+ const value = readable(base, grounds, { fg, render, excluded: distinct ? used : [] });
69
+ if (distinct) used.push(value);
70
+ return code(value);
56
71
  };
57
72
  const dark = luminance(bg) < 0.4;
58
- return Object.freeze({ ...DEFAULT_THEME,
59
- accent: code(readable(dark ? [105, 215, 239] : [0, 120, 150], [bg, band])),
60
- attention: code(readable(dark ? [233, 173, 12] : [154, 103, 0], [bg])),
61
- secondary: code(readable(mix(fg, bg, 0.25), [bg, band])), quiet: code(readable(mix(fg, bg, 0.42), [bg])),
62
- rule: code(mix(fg, bg, 0.62)), band: code(band, 48) });
73
+ const primary = pick(fg);
74
+ return Object.freeze({
75
+ primary, strong: `1;${primary}`, em: `3;${primary}`, link: `4;${primary}`,
76
+ accent: pick(dark ? [105, 215, 239] : [0, 120, 150], true),
77
+ success: pick(green ?? (dark ? [100, 220, 130] : [0, 115, 45]), true),
78
+ error: pick(red ?? (dark ? [255, 135, 150] : [175, 30, 55]), true),
79
+ secondary: pick(mix(fg, bg, 0.25), true),
80
+ attention: pick(dark ? [233, 173, 12] : [154, 103, 0]),
81
+ quiet: pick(mix(fg, bg, 0.42)), rule: pick(mix(fg, bg, 0.62)), band: code(band, 48),
82
+ });
63
83
  }
64
84
 
65
85
  const SPINNER = ["·", "✢", "✳", "✶", "✻", "✽", "✻", "✶", "✳", "✢"];
@@ -90,16 +110,17 @@ function seal(lines) {
90
110
  return head + line + tail;
91
111
  });
92
112
  }
113
+ // Cached wraps own only immutable text rows; each caller receives a separate array.
93
114
  const wrapped = new Map();
94
115
  const wrap = (value, width, wordWrap = true) => {
95
116
  width = Math.max(1, width);
96
117
  const key = value.length <= 512 ? `${width}:${wordWrap}:${value}` : null;
97
- if (key && wrapped.has(key)) return wrapped.get(key);
118
+ if (key && wrapped.has(key)) return [...wrapped.get(key)];
98
119
  const lines = !value.includes("\n") && measure(value) <= width ? [value]
99
120
  : seal(wrapAnsi(value, width, { hard: true, trim: false, wordWrap }).split("\n"));
100
121
  if (key) {
101
122
  if (wrapped.size === 128) wrapped.delete(wrapped.keys().next().value);
102
- wrapped.set(key, lines);
123
+ wrapped.set(key, Object.freeze([...lines]));
103
124
  }
104
125
  return lines;
105
126
  };
@@ -120,7 +141,7 @@ function inline(tokens, theme) {
120
141
  return token.kind === "strong" ? paint(value, "strong", theme)
121
142
  : token.kind === "em" ? paint(value, "em", theme)
122
143
  : token.kind === "code" ? paint(value, "accent", theme)
123
- : token.kind === "link" ? paint(value, "link", theme) : value;
144
+ : token.kind === "link" ? paint(value, "link", theme) : paint(value, "primary", theme);
124
145
  }).join("");
125
146
  }
126
147
 
@@ -143,7 +164,7 @@ function table(block, width, theme) {
143
164
  const bar = paint(" │ ", "rule", theme);
144
165
  return [paint(grid[0].map((value, i) => pad(value, widths[i])).join(" │ "), "strong", theme),
145
166
  paint(widths.map(w => "─".repeat(w)).join("─┼─"), "rule", theme),
146
- ...grid.slice(1).map(row => widths.map((_, i) => cell(row[i] ?? "", i)).join(bar))];
167
+ ...grid.slice(1).map(row => widths.map((_, i) => paint(cell(row[i] ?? "", i), "primary", theme)).join(bar))];
147
168
  }
148
169
 
149
170
  /** Shared web grammar; only trusted renderer styling can emit terminal controls. */
@@ -153,7 +174,7 @@ export function markdownView(source, width, color = true) {
153
174
  if (block.kind === "table") lines.push(...table(block, width, theme));
154
175
  else if (block.kind === "codeblock") {
155
176
  if (block.language) lines.push(paint(block.language, "quiet", theme));
156
- lines.push(...wrap(block.text, width - 2, false).map(line => paint("│ ", "rule", theme) + line));
177
+ lines.push(...wrap(block.text, width - 2, false).map(line => paint("│ ", "rule", theme) + paint(line, "primary", theme)));
157
178
  } else if (block.kind === "hr") {
158
179
  lines.push(paint("─".repeat(Math.min(width, 48)), "rule", theme));
159
180
  } else if (block.kind === "list") {
@@ -274,6 +295,11 @@ export function richLayout(view, composer, cursor, options = {}) {
274
295
  const theme = themeOf(color);
275
296
  const width = Math.max(20, columns - 1), budget = Math.max(1, rows - 3);
276
297
  const active = !!view.run?.subject && !view.run.terminal;
298
+ const pending = view.run?.blocks?.find(block => !block.committed && block.calls);
299
+ const pendingContent = pending ? blockContent(pending) : null;
300
+ // Compact layouts reserve their activity row for the open call, including its state.
301
+ const callSummary = pendingContent ? `${pendingContent.tool} ${trimEnd(plainLine(pendingContent.title),
302
+ Math.max(1, width - measure(`${pendingContent.tool} · ${pendingContent.status}`)))} · ${pendingContent.status}` : null;
277
303
  const readOnly = view.project?.role === "VIEWER", signedOut = view.offline || !view.account;
278
304
  const glyph = tick === null ? "●" : SPINNER[tick % SPINNER.length];
279
305
  const runHint = readOnly ? "Read-only · /help · Ctrl+D detach"
@@ -286,14 +312,15 @@ export function richLayout(view, composer, cursor, options = {}) {
286
312
  const selected = Math.min(view.selected ?? view.paletteSelected ?? 0, Math.max(0, choices.length - 1));
287
313
  const choice = choices[selected];
288
314
  const content = focus?.title ?? (view.login ? `Sign in · Code ${view.login.user_code}` : view.issue?.text
289
- ?? (active ? `${view.run.elapsed ?? "Elapsed unavailable"} · ${view.status}` : view.status));
315
+ ?? view.egress ?? (active ? callSummary ?? `${view.run.elapsed ?? "Elapsed unavailable"} · ${view.status}` : view.status));
290
316
  const status = wrap(terminalText(content), width).slice(0, 1);
317
+ if (active && callSummary && content !== callSummary) status.push(callSummary);
291
318
  if (choice) status.push(wrap(terminalText(`› ${selected + 1}/${choices.length} ${choice.label ?? '/' + choice.name}`), width)[0]);
292
319
  else if (view.login) status.push(['› Open browser', '› Copy link', '› Work offline'][view.loginAction ?? 0]);
293
320
  const draft = composerViewport(composer, cursor, width - 2, 1, theme).lines[0];
294
321
  const hint = focus || choices.length ? '↑↓ Enter choose · Esc back' : view.login ? 'Tab actions · Enter open · Esc offline'
295
322
  : active ? runHint : idleHint;
296
- return { top: [], bottom: [...status, `${paint("›", "accent", theme)} ${draft}`,
323
+ return { top: [], bottom: [...status.map(row => paint(row, "primary", theme)), `${paint("›", "accent", theme)} ${paint(draft, "primary", theme)}`,
297
324
  ...fold(hint, width).slice(0, 2).map(row => paint(row, "secondary", theme))].slice(0, budget) };
298
325
  }
299
326
  // The steady footer names the Workspace, never a personal address; /status shows the account.
@@ -330,16 +357,29 @@ export function richLayout(view, composer, cursor, options = {}) {
330
357
  const text = terminalText(value);
331
358
  lines.push(...wrap(text, width).slice(0, Math.max(0, Math.min(limit, room()))).map(row => paint(row, role, theme)));
332
359
  };
360
+ if (active && compactFocus && compactRun && pending) line(callSummary, "attention", 1);
333
361
  // Activity: the one animated glyph, the current step and the server-anchored clock.
334
362
  if (active && !compactFocus) {
335
363
  const clock = view.run.elapsed ?? "Elapsed unavailable";
336
- const doing = compactRun ? view.status : (view.run.progress || "Working").replace(/^Starting: (.+)$/, "$1").replace(/[.…]+$/, "") + "…";
337
- const head = `${paint(glyph, "accent", theme)} ${terminalText(doing)}`, tail = paint(terminalText(clock), "quiet", theme);
364
+ const doing = compactRun ? callSummary ?? view.status : (view.run.progress || "Working").replace(/^Starting: (.+)$/, "$1").replace(/[.…]+$/, "") + "…";
365
+ const head = `${paint(glyph, "accent", theme)} ${paint(terminalText(doing), "primary", theme)}`, tail = paint(terminalText(clock), "quiet", theme);
338
366
  if (measure(`${glyph} ${terminalText(doing)} · ${terminalText(clock)}`) <= width) lines.push(`${head} ${paint("·", "quiet", theme)} ${tail}`);
339
- else if (compactRun) lines.push(wrap(head, width)[0], ` ${tail}`);
340
- else lines.push(wrap(`${paint(glyph, "accent", theme)} ${tail} · ${terminalText(doing)}`, width)[0]);
367
+ else if (compactRun) lines.push(callSummary ? paint(terminalText(doing), "attention", theme) : wrap(head, width)[0], ` ${tail}`);
368
+ else lines.push(wrap(`${paint(glyph, "accent", theme)} ${tail} · ${paint(terminalText(doing), "primary", theme)}`, width)[0]);
341
369
  if (!compactRun && view.status && view.status !== "Running") line(` ${view.status}`, "secondary", 1);
342
370
  }
371
+ if (active && !compactFocus && !compactRun) {
372
+ const pending = view.run.blocks?.find(block => !block.committed && block.calls);
373
+ if (pending) {
374
+ const content = blockContent(pending);
375
+ line(` ${content.tool} ${content.title} · ${content.status}`, "attention", 1);
376
+ if (pending.kind === "sources") line(` ${content.rows.join(" · ")}`, "secondary", 1);
377
+ }
378
+ for (const block of view.run.blocks?.filter(block => block.kind === "control") ?? []) {
379
+ const c = blockContent(block);
380
+ line(` ${c.title} · ${c.rows.join(" · ")}`, "secondary", 1);
381
+ }
382
+ }
343
383
  if (!compactFocus && !compactRun && view.run?.question) line(readOnly ? "Waiting for an editor to answer"
344
384
  : signedOut ? "Question pending — reconnect to answer" : "Your answer is needed · /answer", "attention", 1);
345
385
  if (prompt) {
@@ -352,7 +392,7 @@ export function richLayout(view, composer, cursor, options = {}) {
352
392
  choices.slice(offset, offset + count).forEach((item, i) => {
353
393
  const index = prompt.options.indexOf(item) + 1, current = i + offset === selected;
354
394
  const checked = prompt.multiple ? `${composer.split(/[, ]+/).includes(String(index)) ? "[x]" : "[ ]"} ` : "";
355
- lines.push(wrap(`${current ? paint("›", "accent", theme) : " "} ${index}. ${checked}${current ? paint(terminalText(item.label), "accent", theme) : terminalText(item.label)}`, width)[0]);
395
+ lines.push(wrap(`${current ? paint("›", "accent", theme) : " "} ${index}. ${checked}${current ? paint(terminalText(item.label), "accent", theme) : paint(terminalText(item.label), "primary", theme)}`, width)[0]);
356
396
  });
357
397
  if (!choices.length) line("No matching choices; clear the filter", "attention", 1);
358
398
  if (choices.length > count && more) line(`${selected + 1}/${choices.length} · ↑↓ more choices`, "quiet", 1);
@@ -370,11 +410,11 @@ export function richLayout(view, composer, cursor, options = {}) {
370
410
  const name = Math.min(16, Math.max(...view.palette.map(row => row.name.length + 1)));
371
411
  view.palette.slice(offset, offset + count).forEach((row, i) => {
372
412
  const current = i + offset === selected, label = pad(`/${row.name}`, name);
373
- lines.push(wrap(`${current ? paint("›", "accent", theme) : " "} ${current ? paint(label, "accent", theme) : label} ${paint(terminalText(row.disabled || row.description), "secondary", theme)}`, width)[0]);
413
+ lines.push(wrap(`${current ? paint("›", "accent", theme) : " "} ${current ? paint(label, "accent", theme) : paint(label, "primary", theme)} ${paint(terminalText(row.disabled || row.description), "secondary", theme)}`, width)[0]);
374
414
  });
375
415
  }
376
416
  const compactAttachments = rows < 24 && view.attachments?.length;
377
- if (view.attachments?.length && !compactAttachments) line(`${view.attachments.length} file(s) selected · uploaded only on send`, "secondary", 1);
417
+ if (view.attachments?.length && !compactAttachments) line(view.egress ?? `${view.attachments.length} file(s) selected · uploaded only on send`, "secondary", 1);
378
418
  if (view.issue && !prompt) line(view.issue.text + (view.issue.count > 1 ? ` (${view.issue.count} attempts)` : ""), "attention", Math.max(1, Math.min(3, room())));
379
419
  // First use: signed in, idle, an unbound folder, an empty transcript and an empty draft.
380
420
  const firstUse = view.header && view.firstUse && !active && !composer && !prompt
@@ -384,12 +424,12 @@ export function richLayout(view, composer, cursor, options = {}) {
384
424
  if (idle && !firstUse && view.status !== "Ready") line(view.status, "secondary", 1);
385
425
  const maxDraft = Math.max(1, Math.min(6, budget - lines.length - footer.length - 2));
386
426
  const draft = composerViewport(composer, cursor, width - 4, maxDraft, theme);
387
- const selection = compactAttachments ? `${view.attachments.length} file(s) · upload on send` : "";
427
+ const selection = compactAttachments ? view.egress ?? `${view.attachments.length} file(s) · upload on send` : "";
388
428
  const placeholder = prompt ? (prompt.typed ? "Type your answer…" : "Filter or type a choice number…")
389
429
  : readOnly ? "Read-only Project — draft here…" : view.offline ? "Draft offline…"
390
430
  : !view.account ? "Sign in to send — draft here…"
391
431
  : active ? "Draft your next question…" : "Ask Laplace…";
392
- lines.push(...composerBand(draft.lines.map((value, index) => ` ${index ? " " : paint("›", "accent", theme)} ${composer ? value
432
+ lines.push(...composerBand(draft.lines.map((value, index) => ` ${index ? " " : paint("›", "accent", theme)} ${composer ? paint(value, "primary", theme)
393
433
  : paint("▌", "accent", theme) + paint(placeholder, "secondary", theme)}`), width, theme,
394
434
  { top: selection, bottom: draft.scrolling ? draft.position : "" }));
395
435
  lines.push(...footer);
@@ -426,39 +466,72 @@ export function richFrame(view, composer, cursor, options = {}) {
426
466
  const indent = (text, first, rest = " ") => text.split("\n").map((line, i) => (i ? (line ? rest : "") : first) + line).join("\n");
427
467
 
428
468
  /** One scrollback block per message: the ask, the answer with its record, or a quiet notice. */
429
- export function richMessage(message, columns, color, { stepsShown = false } = {}) {
469
+ export function richMessage(message, columns, color, { stepsShown = false, shownKeys = new Set() } = {}) {
430
470
  const theme = themeOf(color), width = Math.max(20, columns - 1);
431
471
  if (message.kind === "user") {
432
- return "\n" + indent(wrap(terminalText(message.text), width - 2).join("\n"), paint("›", "accent", theme) + " ") + "\n";
433
- }
434
- if (message.kind === "step") return paint(trimEnd(` ⎿ ${message.text}`, width), "secondary", theme);
435
- if (message.kind === "cost") {
436
- const display = message.value?.display ?? {};
437
- const parts = [["Used", display.used], ["Limit", display.limit], ["Remaining", display.remaining]].filter(([, v]) => v !== null && v !== undefined);
438
- return paint(trimEnd(` Usage this UTC month · ${parts.length ? parts.map(([k, v]) => `${k} ${v}`).join(" · ") : "no exact amount available"} · /usage`, width), "quiet", theme);
472
+ const rows = wrap(terminalText(message.text), width - 2).map((row, index) =>
473
+ `${index ? " " : paint("›", "accent", theme)} ${paint(row, "strong", theme)}`);
474
+ return "\n" + rows.map(row => theme?.band ? style(pad(row, width), theme.band, theme) : row).join("\n") + "\n";
439
475
  }
476
+ if (message.kind === "block") return richBlock(message.block, columns, theme);
477
+ if (message.kind === "turn-footer") return paint(terminalText(message.text), "quiet", theme);
440
478
  if (message.kind !== "answer") return wrap(terminalText(message.text), width - 2).map(line => " " + line).join("\n");
441
479
  const run = message.sections;
442
480
  if (!run) return "\n" + indent(markdownView(message.text, width - 2, theme), paint("●", "accent", theme) + " ") + "\n";
443
481
  const out = [];
482
+ // A horizon stop says so, and what can be done, before the work (the plain renderer's `humanRun` prints the same lines).
483
+ if (run.stop?.length) out.push(...run.stop.flatMap(line => (line ? prose(terminalText(line), width - 4).map(part => " " + paint(part, "attention", theme)) : [""])), "");
484
+ for (const block of run.blocks ?? []) {
485
+ if (!shownKeys.has(block.key) && ["tool", "sources", "clarification"].includes(block.kind))
486
+ out.push(richBlock(block, columns, theme), "");
487
+ }
444
488
  out.push(run.answer !== undefined ? indent(markdownView(run.answer, width - 2, theme), paint("●", "accent", theme) + " ")
445
489
  : paint("●", "attention", theme) + " No answer was published for this Run.");
490
+ // The host's publication warnings, beside a non-empty answer, as the plain renderer and the browser show them (`format.js` publicationChecks).
491
+ if (run.answer !== undefined && run.answer !== "" && run.checks?.length)
492
+ out.push("", ...run.checks.flatMap(check => prose(terminalText(check), width - 4).map(part => " " + paint(part, "attention", theme))));
446
493
  const section = (title, rows) => { if (rows.length) out.push("", " " + paint(title, "strong", theme), ...rows); };
447
494
  const one = text => text.split("\n").map(part => part.trim()).filter(Boolean).join(" · ");
448
- section("Steps", run.tasks.slice(stepsShown).map(task => paint(trimEnd(` ⎿ ${one(task.replace(/^\s*[▸·]\s*/, ""))}`, width), "secondary", theme)));
495
+ const shownSteps = new Set((run.blocks ?? []).filter(block => block.kind === "step" && shownKeys.has(block.key)).map(block => block.stepId));
496
+ const tasks = shownSteps.size && run.events ? taskLines(run.events.filter(event => event.kind !== "step_finished" || !shownSteps.has(event.payload?.step_id)), { facts: true }) : run.tasks;
497
+ section("Steps", tasks.slice(stepsShown).flatMap(task => prose(terminalText(one(task.replace(/^\s*[▸·]\s*/, ""))), width - 4).map(row => ` ⎿ ${paint(row, "secondary", theme)}`)));
449
498
  // Evidence rows are never truncated: quantity, unit and origin wrap with a hanging indent.
450
499
  const full = (row, role = "secondary") => prose(terminalText(row.trim()), width - 4).map((part, i) => (i ? " " : " ") + paint(part, role, theme));
451
500
  section("Inputs and origins", run.origins.flatMap(row => full(row)));
452
501
  section("Assumptions", run.assumptions.flatMap(row => full(row)));
453
502
  section("Transfer tables", run.tables.flatMap(rows => rows.flatMap(row => full(row))));
454
- // Up to three files, readable names before digest-named ones; numbers stay the /download numbers.
455
- const numbered = run.artifacts.map((row, i) => ({ ...row, number: i + 1 }));
456
- const digest = row => /^[0-9a-f]{32,}\./.test(row.artifact.filename);
457
- const shown = [...numbered.filter(row => !digest(row)), ...numbered.filter(digest)].slice(0, 3);
458
- const more = run.artifacts.length - shown.length;
459
- section("Files", shown.flatMap(({ artifact, number }) => prose(`${terminalText(artifact.filename)} ${paint(`· ${artifact.kind} · /download ${number}`, "quiet", theme)}`, width - 4)
460
- .map((part, i) => ` ${i ? " " : paint("↓", "accent", theme)} ${part}`))
461
- .concat(more > 0 ? [paint(` … ${more} more · /files`, "quiet", theme)] : []));
503
+ section("Files", run.artifacts.flatMap(({ artifact, number, sameBytesAs }, i) =>
504
+ prose(`${terminalText(artifact.path ?? artifact.filename)} · ${terminalText(artifact.kind)} · /download ${number ?? i + 1}${sameBytesAs ? ` · same bytes as ${sameBytesAs}` : ""}`, width - 4)
505
+ .map((part, index) => ` ${index ? " " : paint("↓", "accent", theme)} ${paint(part, "secondary", theme)}`)));
462
506
  out.push("", ...full(run.tail.map(terminalText).join(" · "), run.state === "ok" ? "quiet" : "attention"));
507
+ section("Controls", (run.blocks ?? []).filter(block => block.kind === "control" && !shownKeys.has(block.key))
508
+ .map(block => richBlock(block, columns, theme)));
463
509
  return "\n" + out.join("\n") + "\n";
464
510
  }
511
+
512
+
513
+ /** The same human grammar in live scrollback and reload, with bounded excerpt previews. */
514
+ export function richBlock(block, columns = 80, color = true, { full = false } = {}) {
515
+ const theme = themeOf(color), width = Math.max(20, columns - 1);
516
+ const c = blockContent(block, { full });
517
+ const role = block.kind === "step"
518
+ ? ["computed", "read"].includes(c.status) ? "success" : ["failed", "refused"].includes(c.status) ? "error" : "attention"
519
+ : c.status === "ok" ? "success" : ["running", "requested", "queued", "claimed"].includes(c.status) ? "attention" : "error";
520
+ const header = `${paint("●", role, theme)} ${paint(terminalText(c.tool ?? c.title), "strong", theme)}${c.tool ? ` ${paint(terminalText(c.title), "primary", theme)}` : ""}`;
521
+ const out = wrap(header, width);
522
+ for (const row of c.rows) out.push(...wrap(terminalText(row).trim(), width - 5).map((line, i) =>
523
+ `${i ? " " : " ⎿ "}${paint(line, "secondary", theme)}`));
524
+ const preview = c.preview ?? [];
525
+ // Preserve the selected logical lines in scrollback, even at narrow widths.
526
+ // Bound each line independently so a long notice cannot displace the cause.
527
+ const selected = c.previewTail ? preview.slice(-3) : preview.slice(0, 3);
528
+ const wrapped = selected.map(row => wrap(row, width - 5));
529
+ const display = wrapped.flatMap(rows => rows.slice(0, 3));
530
+ if (display.length) {
531
+ out.push(...display.map(row => " " + paint(row, "secondary", theme)));
532
+ const truncated = preview.length > 3 || wrapped.some(rows => rows.length > 3);
533
+ const label = truncated ? "… output excerpt truncated · ctrl+o for the full block" : "output excerpt · ctrl+o for the full block";
534
+ out.push(...wrap(label, width - 5).map(row => " " + paint(row, "secondary", theme)));
535
+ }
536
+ return out.join("\n");
537
+ }