@vecteur/cli 0.10.0 → 0.12.4

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.
@@ -0,0 +1,19 @@
1
+ // What the CLI's stop card says when a turn ends in `budget`. The CLI owns these words: the web's v5 owner
2
+ // (`frontend/src/run/stop-words.ts`) went with the v6 run screen, and only the keys `format.js` reads are kept.
3
+ // Facts are never written here: `{model}` comes from the catalogue, `{steps}` and `{price}` from the plan owner.
4
+ export const STOP_WORDS = Object.freeze({
5
+ heading: { limit: "This study paused at a limit" },
6
+ reason: { limit: "{model} needs more room for its next step than is left for this period." },
7
+ result: {
8
+ authored: "Your computed work is saved, and what was written before the stop is below.",
9
+ computed: "What ran is listed below; no final answer to your question was delivered.",
10
+ nothing: "Nothing was computed yet. Your question is kept.",
11
+ },
12
+ usage_note: "A step reserves room before it runs, so this can appear before your usage reads full.",
13
+ action_line: {
14
+ upgrade_plan: "Room for longer studies: up to {steps} steps per run and a larger usage allowance. {price}.",
15
+ contact_sales: "If your studies regularly need more than Pro allows, we'll work out what fits.",
16
+ },
17
+ continue_with: "Continue with {model}",
18
+ see_usage: "See usage",
19
+ });
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";
@@ -38,16 +39,11 @@ export class TerminalWriter {
38
39
  }
39
40
  progress(view) {
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; }
42
43
  if (!subject || view.run.terminal) return;
43
44
  if (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
  }
46
- const question = view.run.question;
47
- if (question?.id !== this.lastQuestion) {
48
- this.lastQuestion = question?.id;
49
- if (question) this.append(safe(`Vecteur needs your answer — /answer\n${question.questions.map(row => row.question).join("\n")}`));
50
- }
51
47
  }
52
48
  /** Scrollback text, then the given live frame in the same write: the composer never blinks out. */
53
49
  append(text, frame = null) {
@@ -110,7 +106,13 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
110
106
  if (!options.plain) throw error;
111
107
  prefs = { plain: true, reducedMotion: true };
112
108
  }
113
- let rich = !options.plain && !prefs.plain && env.TERM !== "dumb";
109
+ let rich = stdout.isTTY === true && !options.plain && !prefs.plain && env.TERM !== "dumb";
110
+ let pasteMode = false;
111
+ const syncPasteMode = () => {
112
+ if (pasteMode === rich) return;
113
+ pasteMode = rich;
114
+ stdout.write(pasteMode ? "\x1b[?2004h" : "\x1b[?2004l");
115
+ };
114
116
  const color = !options.noColor && env.NO_COLOR === undefined;
115
117
  // Colour roles start palette-relative; a terminal that reports its own colours gets exact blends.
116
118
  let theme = color; const reported = {};
@@ -126,10 +128,10 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
126
128
  let lastPlainStatus = "", lastPlainIdentity = "", plainDraft = "", frameTimer, clockTimer, cancelAt = 0, cancelRun, exitAt = 0;
127
129
  let snapshot = null, localPicker = null, loginAction = 0, updateChecked = false, tick = 0;
128
130
  // While a vendor owns the TTY (handoff) Vecteur writes nothing: frames, clocks, streamed
129
- // steps and messages wait, and are flushed once when the vendor exits.
131
+ // blocks and messages wait, and are flushed once when the vendor exits.
130
132
  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 };
133
+ // Immutable event blocks commit once.
134
+ const streamed = { run: null, keys: new Set() };
133
135
  // The identity header is live until the first transcript block, then committed once.
134
136
  let headerLive = true, cursorHidden = false;
135
137
  const directory = () => session.cwd === homedir() || session.cwd.startsWith(homedir() + "/") ? "~" + session.cwd.slice(homedir().length) : session.cwd;
@@ -161,7 +163,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
161
163
  // The real cursor stays hidden in rich mode (the composer draws its own caret) and always
162
164
  // returns on exit, error, plain fallback and vendor handoff.
163
165
  const showCursor = visible => {
164
- if (env.TERM === "dumb" || visible !== cursorHidden) return;
166
+ if (env.TERM === "dumb" || !stdout.isTTY || visible !== cursorHidden) return;
165
167
  cursorHidden = !visible; stdout.write(visible ? "\x1b[0m\x1b[?25h" : "\x1b[?25l");
166
168
  };
167
169
  const restoreCursor = () => showCursor(true);
@@ -184,29 +186,27 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
184
186
  };
185
187
  const locate = (query = "") => { if (!writer.plain) { input.expectReports ||= !!query; writer.locate(query); } };
186
188
  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.`));
189
+ 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
190
  const maybeUpdate = () => {
189
191
  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
192
  updateChecked = true;
191
193
  void import("./update.js").then(({ interactiveUpdate }) => interactiveUpdate(session, { automatic: true })).catch(error => session.report(error));
192
194
  };
195
+ const commitBlocks = (runId, blocks) => {
196
+ if (streamed.run !== runId) { streamed.run = runId; streamed.keys = new Set(); }
197
+ for (const block of blocks) {
198
+ if (!block.committed || block.kind === "terminal" || streamed.keys.has(block.key)) continue;
199
+ print(writer.plain ? blockText(block) : layout.richMessage({ kind: "block", block }, stdout.columns ?? 80, theme));
200
+ streamed.keys.add(block.key);
201
+ }
202
+ };
193
203
  session.on("change", view => {
194
204
  if (vendorOwnsTerminal) return;
195
205
  const ticking = !writer.plain && !view.offline && session.run?.open;
196
206
  if (ticking && !clockTimer) clockTimer = setInterval(() => { tick++; draw(); }, prefs.reducedMotion ? 1000 : 200);
197
207
  if (!ticking) { clearInterval(clockTimer); clockTimer = null; }
198
208
  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
- }
209
+ if (run?.open && Array.isArray(run.events)) commitBlocks(run.run_id, view.run.blocks);
210
210
  if (process.connected && process.send && env.VECTEUR_UPDATE_SESSION && session.release?.compatible
211
211
  && session.registry && (!view.busy || view.prompt)) {
212
212
  const nonce = env.VECTEUR_UPDATE_SESSION; delete env.VECTEUR_UPDATE_SESSION;
@@ -218,14 +218,16 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
218
218
  history.length = 0; historyIndex = 0; historyDraft = ""; historyAccount = accountKey; input.undo = []; input.killed = ""; snapshot = null; }
219
219
  if (writer.plain) {
220
220
  writer.progress(view);
221
- const identity = `${view.account?.email ?? "Not signed in"} · ${view.projectLabel}\n${view.folder}\n${view.lead} · ${view.location} · ${view.model}`;
221
+ const identity = `${view.account?.email ?? "Not signed in"} · ${view.projectLabel}\n${view.folder}\n${view.model} · ${view.location}`;
222
222
  if (identity !== lastPlainIdentity) { writer.append(safe(identity)); lastPlainIdentity = identity; }
223
223
  }
224
224
  if (view.prompt !== activePrompt) {
225
225
  if (view.prompt && !activePrompt) snapshot = { text: input.text.startsWith("/") ? session.draft : input.text, cursor: input.cursor, undo: input.undo, killed: input.killed };
226
226
  activePrompt = view.prompt; selected = 0; focusChanged();
227
227
  if (activePrompt) {
228
- input.undo = []; input.killed = ""; syncInput(""); if (writer.plain) printPlainPrompt(activePrompt);
228
+ input.undo = []; input.killed = ""; syncInput("");
229
+ if (writer.plain) printPlainPrompt(activePrompt);
230
+ 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
231
  } else {
230
232
  const restored = snapshot && snapshot.text === session.draft ? snapshot : { text: session.draft, cursor: session.draft.length };
231
233
  syncInput(restored.text, Math.min(restored.cursor, restored.text.length)); input.undo = restored.undo ?? []; input.killed = restored.killed ?? ""; snapshot = null;
@@ -237,13 +239,19 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
237
239
  schedule(); queueMicrotask(maybeUpdate);
238
240
  });
239
241
  session.on("preferences", value => {
240
- prefs = value; rich = !options.plain && !prefs.plain && env.TERM !== "dumb";
242
+ prefs = value; rich = stdout.isTTY === true && !options.plain && !prefs.plain && env.TERM !== "dumb";
243
+ syncPasteMode();
241
244
  writer.resized(isPlain()); showCursor(writer.plain); locate(); session.change(); draw();
242
245
  });
243
246
  session.on("message", message => {
244
247
  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));
248
+ // Flush the terminal prefix too: unmatched calls close only in the final direct record.
249
+ if (message.kind === "answer" && message.sections?.blocks) commitBlocks(message.runId, message.sections.blocks);
250
+ const shownKeys = new Set(message.runId === streamed.run ? streamed.keys : []);
251
+ const text = writer.plain ? message.kind === "answer" && message.sections
252
+ ? safe(humanRunSections(message.sections, { shownKeys })) : safe(message.text)
253
+ : layout.richMessage(message, stdout.columns ?? 80, theme, { shownKeys });
254
+ print(text, ["user", "answer", "turn-footer"].includes(message.kind));
247
255
  plainDraft = "";
248
256
  });
249
257
  session.on("copy", answer => {
@@ -310,7 +318,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
310
318
  clearTimeout(frameTimer); frameTimer = null; clearInterval(clockTimer); clockTimer = null;
311
319
  stdin.off("data", onData); stdin.setRawMode(false); stdin.pause();
312
320
  process.off("SIGINT", onSignal);
313
- writer.clearLive(); commitHeader(); showCursor(true); if (env.TERM !== "dumb") stdout.write("\x1b[?2004l");
321
+ writer.clearLive(); commitHeader(); showCursor(true); if (pasteMode) stdout.write("\x1b[?2004l");
314
322
  const { VENDORS, executingServer, runVendor, vendorArgv } = await import("./vendors.js");
315
323
  writer.append(`Opening your ${VENDORS[vendor]} terminal with Vecteur attached for this session only. Exit it to return.`);
316
324
  let note;
@@ -320,7 +328,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
320
328
  finally {
321
329
  vendorOwnsTerminal = false;
322
330
  process.once("SIGINT", onSignal);
323
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004h");
331
+ if (pasteMode) stdout.write("\x1b[?2004h");
324
332
  stdin.setRawMode(true); stdin.resume(); stdin.on("data", onData);
325
333
  }
326
334
  // The vendor's output is history now; find where it left the cursor before drawing again.
@@ -342,6 +350,16 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
342
350
  selected = 0; focusChanged(); syncInput(""); if (writer.plain) printPlainPrompt(localPicker); draw();
343
351
  });
344
352
  input.on("complete", () => {
353
+ const mention = /(?:^|\s)@([^\s]*)$/.exec(input.text.slice(0,input.cursor));
354
+ if (mention && !session.prompt) {
355
+ const completionText=input.text, completionCursor=input.cursor;
356
+ void session.completeFiles(mention[1]).then(paths => {
357
+ if(input.text!==completionText || input.cursor!==completionCursor)return;
358
+ if (paths.length === 1) { input.replace(input.cursor-mention[1].length,input.cursor,paths[0]); draw(); }
359
+ else if (paths.length) session.message(paths.map(p=>'@'+p).join('\n'));
360
+ }).catch(error=>session.report(error));
361
+ return;
362
+ }
345
363
  const row = palette()[paletteSelected]; if (row) { syncInput(`/${row.name}${row.argument ? " " : ""}`); draw(); }
346
364
  });
347
365
  const cancel = () => {
@@ -398,10 +416,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
398
416
  });
399
417
  input.on("exit", () => { try { session.close(); } catch (error) { session.report(error); } });
400
418
  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);
419
+ input.feed(chunk, { unbracketed: !pasteMode });
405
420
  };
406
421
  const onResize = () => {
407
422
  // The vendor owns the TTY: not one byte; the new geometry is applied once on restore.
@@ -415,7 +430,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
415
430
  const done = new Promise(resolve => session.once("close", resolve));
416
431
  stdin.setRawMode(true); stdin.resume(); stdin.on("data", onData); stdout.on("resize", onResize);
417
432
  process.once("SIGTERM", onSignal); process.once("SIGHUP", onSignal); process.once("SIGINT", onSignal);
418
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004h");
433
+ syncPasteMode();
419
434
  process.on("exit", restoreCursor);
420
435
  if (writer.plain) writer.append(`Vecteur ${version}${channel === "preview" ? " · Preview" : ""} · ${safe(session.origin)}`);
421
436
  else { showCursor(false); locate(color ? "\x1b]10;?\x1b\\\x1b]11;?\x1b\\" : ""); }
@@ -426,7 +441,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
426
441
  clearTimeout(frameTimer); clearInterval(clockTimer); input.close(); stdin.off("data", onData); stdout.off("resize", onResize);
427
442
  process.off("SIGTERM", onSignal); process.off("SIGHUP", onSignal); process.off("SIGINT", onSignal);
428
443
  writer.clearLive(); writer.close(); commitHeader(); showCursor(true); process.off("exit", restoreCursor);
429
- if (env.TERM !== "dumb") stdout.write("\x1b[?2004l");
444
+ if (pasteMode) stdout.write("\x1b[?2004l");
430
445
  stdin.setRawMode(false); stdin.pause();
431
446
  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
447
  }
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 } 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,13 +174,15 @@ 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") {
160
- block.items.forEach((item, index) => {
161
- const prefix = block.ordered ? `${index + 1}. ` : "• ";
162
- prose(inline(item, theme), measureWidth - prefix.length).forEach((line, i) => lines.push((i ? " ".repeat(prefix.length) : paint(prefix, "quiet", theme)) + line));
181
+ const count = [0, 0]; // the web grammar's items: one level of nesting, numbered per level
182
+ block.items.forEach(item => {
183
+ count[item.depth] += 1; if (!item.depth) count[1] = 0;
184
+ const prefix = " ".repeat(item.depth) + (item.ordered ? `${count[item.depth]}. ` : "• ");
185
+ prose(inline(item.inline, theme), measureWidth - prefix.length).forEach((line, i) => lines.push((i ? " ".repeat(prefix.length) : paint(prefix, "quiet", theme)) + line));
163
186
  });
164
187
  } else {
165
188
  let value = inline(block.inline, theme);
@@ -233,7 +256,7 @@ function trimStart(value, max) {
233
256
  }
234
257
 
235
258
  const execution = view => view.location && view.location !== "Vecteur cloud" ? view.location : "Cloud";
236
- const routeOf = view => `${view.lead ? `${view.lead} · ` : ""}${view.model} · ${execution(view)}`;
259
+ const routeOf = view => `${view.model} · ${execution(view)}`;
237
260
  const customOrigin = view => view.origin && view.origin !== "https://vecteur.space" ? view.origin : "";
238
261
 
239
262
  /**
@@ -274,11 +297,16 @@ export function richLayout(view, composer, cursor, options = {}) {
274
297
  const theme = themeOf(color);
275
298
  const width = Math.max(20, columns - 1), budget = Math.max(1, rows - 3);
276
299
  const active = !!view.run?.subject && !view.run.terminal;
300
+ const pending = view.run?.blocks?.find(block => !block.committed && block.kind === "tool");
301
+ const pendingContent = pending ? blockContent(pending) : null;
302
+ // Compact layouts reserve their activity row for the open call, including its state.
303
+ const callSummary = pendingContent ? `${pendingContent.tool} ${trimEnd(plainLine(pendingContent.title),
304
+ Math.max(1, width - measure(`${pendingContent.tool} · ${pendingContent.status}`)))} · ${pendingContent.status}` : null;
277
305
  const readOnly = view.project?.role === "VIEWER", signedOut = view.offline || !view.account;
278
306
  const glyph = tick === null ? "●" : SPINNER[tick % SPINNER.length];
279
307
  const runHint = readOnly ? "Read-only · /help · Ctrl+D detach"
280
308
  : signedOut ? `${view.offline ? "/resume" : "/login"} · /help · Ctrl+D detach`
281
- : `${view.run?.question ? "/answer" : "/steer · /answer-now"} · /help${width < 60 ? "\n" : " · "}Esc twice cancel · Ctrl+D detach`;
309
+ : `/help${width < 60 ? "\n" : " · "}Esc twice cancel · Ctrl+D detach`;
282
310
  const idleHint = `${readOnly ? "Read-only · /project" : signedOut ? "Enter sign in" : view.busy ? "Please wait" : "Enter send"} · / commands · ? shortcuts`;
283
311
  if (rows < 12) {
284
312
  const focus = view.focus ?? view.prompt;
@@ -286,14 +314,15 @@ export function richLayout(view, composer, cursor, options = {}) {
286
314
  const selected = Math.min(view.selected ?? view.paletteSelected ?? 0, Math.max(0, choices.length - 1));
287
315
  const choice = choices[selected];
288
316
  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));
317
+ ?? view.egress ?? (active ? callSummary ?? `${view.run.elapsed ?? "Elapsed unavailable"} · ${view.status}` : view.status));
290
318
  const status = wrap(terminalText(content), width).slice(0, 1);
319
+ if (active && callSummary && content !== callSummary) status.push(callSummary);
291
320
  if (choice) status.push(wrap(terminalText(`› ${selected + 1}/${choices.length} ${choice.label ?? '/' + choice.name}`), width)[0]);
292
321
  else if (view.login) status.push(['› Open browser', '› Copy link', '› Work offline'][view.loginAction ?? 0]);
293
322
  const draft = composerViewport(composer, cursor, width - 2, 1, theme).lines[0];
294
323
  const hint = focus || choices.length ? '↑↓ Enter choose · Esc back' : view.login ? 'Tab actions · Enter open · Esc offline'
295
324
  : active ? runHint : idleHint;
296
- return { top: [], bottom: [...status, `${paint("›", "accent", theme)} ${draft}`,
325
+ return { top: [], bottom: [...status.map(row => paint(row, "primary", theme)), `${paint("›", "accent", theme)} ${paint(draft, "primary", theme)}`,
297
326
  ...fold(hint, width).slice(0, 2).map(row => paint(row, "secondary", theme))].slice(0, budget) };
298
327
  }
299
328
  // The steady footer names the Workspace, never a personal address; /status shows the account.
@@ -330,18 +359,20 @@ export function richLayout(view, composer, cursor, options = {}) {
330
359
  const text = terminalText(value);
331
360
  lines.push(...wrap(text, width).slice(0, Math.max(0, Math.min(limit, room()))).map(row => paint(row, role, theme)));
332
361
  };
362
+ if (active && compactFocus && compactRun && pending) line(callSummary, "attention", 1);
333
363
  // Activity: the one animated glyph, the current step and the server-anchored clock.
334
364
  if (active && !compactFocus) {
335
365
  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);
366
+ const doing = compactRun ? callSummary ?? view.status : (view.run.progress || "Working").replace(/[.…]+$/, "") + "…";
367
+ const head = `${paint(glyph, "accent", theme)} ${paint(terminalText(doing), "primary", theme)}`, tail = paint(terminalText(clock), "quiet", theme);
338
368
  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]);
369
+ else if (compactRun) lines.push(callSummary ? paint(terminalText(doing), "attention", theme) : wrap(head, width)[0], ` ${tail}`);
370
+ else lines.push(wrap(`${paint(glyph, "accent", theme)} ${tail} · ${paint(terminalText(doing), "primary", theme)}`, width)[0]);
341
371
  if (!compactRun && view.status && view.status !== "Running") line(` ${view.status}`, "secondary", 1);
342
372
  }
343
- if (!compactFocus && !compactRun && view.run?.question) line(readOnly ? "Waiting for an editor to answer"
344
- : signedOut ? "Question pending — reconnect to answer" : "Your answer is needed · /answer", "attention", 1);
373
+ if (active && !compactFocus && !compactRun && pendingContent) {
374
+ line(` ${pendingContent.tool} ${pendingContent.title} · ${pendingContent.status}`, "attention", 1);
375
+ }
345
376
  if (prompt) {
346
377
  line(prompt.title, "strong", compactFocus ? 1 : 3);
347
378
  if (!prompt.typed) {
@@ -352,7 +383,7 @@ export function richLayout(view, composer, cursor, options = {}) {
352
383
  choices.slice(offset, offset + count).forEach((item, i) => {
353
384
  const index = prompt.options.indexOf(item) + 1, current = i + offset === selected;
354
385
  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]);
386
+ 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
387
  });
357
388
  if (!choices.length) line("No matching choices; clear the filter", "attention", 1);
358
389
  if (choices.length > count && more) line(`${selected + 1}/${choices.length} · ↑↓ more choices`, "quiet", 1);
@@ -370,11 +401,11 @@ export function richLayout(view, composer, cursor, options = {}) {
370
401
  const name = Math.min(16, Math.max(...view.palette.map(row => row.name.length + 1)));
371
402
  view.palette.slice(offset, offset + count).forEach((row, i) => {
372
403
  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]);
404
+ 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
405
  });
375
406
  }
376
407
  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);
408
+ if (view.attachments?.length && !compactAttachments) line(view.egress ?? `${view.attachments.length} file(s) selected · uploaded only on send`, "secondary", 1);
378
409
  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
410
  // First use: signed in, idle, an unbound folder, an empty transcript and an empty draft.
380
411
  const firstUse = view.header && view.firstUse && !active && !composer && !prompt
@@ -384,12 +415,12 @@ export function richLayout(view, composer, cursor, options = {}) {
384
415
  if (idle && !firstUse && view.status !== "Ready") line(view.status, "secondary", 1);
385
416
  const maxDraft = Math.max(1, Math.min(6, budget - lines.length - footer.length - 2));
386
417
  const draft = composerViewport(composer, cursor, width - 4, maxDraft, theme);
387
- const selection = compactAttachments ? `${view.attachments.length} file(s) · upload on send` : "";
418
+ const selection = compactAttachments ? view.egress ?? `${view.attachments.length} file(s) · upload on send` : "";
388
419
  const placeholder = prompt ? (prompt.typed ? "Type your answer…" : "Filter or type a choice number…")
389
420
  : readOnly ? "Read-only Project — draft here…" : view.offline ? "Draft offline…"
390
421
  : !view.account ? "Sign in to send — draft here…"
391
- : active ? "Draft your next question…" : "Ask Laplace…";
392
- lines.push(...composerBand(draft.lines.map((value, index) => ` ${index ? " " : paint("›", "accent", theme)} ${composer ? value
422
+ : active ? "Draft your next question…" : "Ask Vecteur…";
423
+ lines.push(...composerBand(draft.lines.map((value, index) => ` ${index ? " " : paint("›", "accent", theme)} ${composer ? paint(value, "primary", theme)
393
424
  : paint("▌", "accent", theme) + paint(placeholder, "secondary", theme)}`), width, theme,
394
425
  { top: selection, bottom: draft.scrolling ? draft.position : "" }));
395
426
  lines.push(...footer);
@@ -406,7 +437,7 @@ export function richLayout(view, composer, cursor, options = {}) {
406
437
  }
407
438
  if (firstUse) {
408
439
  const note = "New folder · A project will be created on your first message. /link existing";
409
- const intro = [paint("What are we working on?", "strong", theme), paint("Ask Laplace about your mission, or start from a file.", "secondary", theme)];
440
+ const intro = [paint("What are we working on?", "strong", theme), paint("Ask about your mission, or start from a file.", "secondary", theme)];
410
441
  const suggestions = ONBOARDING.map(text => `${paint("›", "accent", theme)} ${paint(text, "secondary", theme)}`);
411
442
  const quiet = wrap(note, width).map(row => paint(row, "quiet", theme));
412
443
  const body = [[...intro, "", ...suggestions, "", ...quiet], [...intro, "", ...quiet], quiet]
@@ -426,39 +457,44 @@ export function richFrame(view, composer, cursor, options = {}) {
426
457
  const indent = (text, first, rest = " ") => text.split("\n").map((line, i) => (i ? (line ? rest : "") : first) + line).join("\n");
427
458
 
428
459
  /** 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 } = {}) {
460
+ export function richMessage(message, columns, color, { shownKeys = new Set() } = {}) {
430
461
  const theme = themeOf(color), width = Math.max(20, columns - 1);
431
462
  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);
463
+ const rows = wrap(terminalText(message.text), width - 2).map((row, index) =>
464
+ `${index ? " " : paint("›", "accent", theme)} ${paint(row, "strong", theme)}`);
465
+ return "\n" + rows.map(row => theme?.band ? style(pad(row, width), theme.band, theme) : row).join("\n") + "\n";
439
466
  }
467
+ if (message.kind === "block") return richBlock(message.block, columns, theme);
468
+ if (message.kind === "turn-footer") return paint(terminalText(message.text), "quiet", theme);
440
469
  if (message.kind !== "answer") return wrap(terminalText(message.text), width - 2).map(line => " " + line).join("\n");
441
470
  const run = message.sections;
442
471
  if (!run) return "\n" + indent(markdownView(message.text, width - 2, theme), paint("●", "accent", theme) + " ") + "\n";
472
+ // The turn: its working trace (rows not already printed live), the answer, the files, the terminal state, the stop card.
443
473
  const out = [];
444
- out.push(run.answer !== undefined ? indent(markdownView(run.answer, width - 2, theme), paint("●", "accent", theme) + " ")
474
+ for (const block of run.blocks) {
475
+ if (block.kind !== "terminal" && !shownKeys.has(block.key)) out.push(richBlock(block, columns, theme));
476
+ }
477
+ if (out.length) out.push("");
478
+ out.push(run.answer ? indent(markdownView(run.answer, width - 2, theme), paint("●", "accent", theme) + " ")
445
479
  : paint("●", "attention", theme) + " No answer was published for this Run.");
446
- const section = (title, rows) => { if (rows.length) out.push("", " " + paint(title, "strong", theme), ...rows); };
447
- 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)));
449
- // Evidence rows are never truncated: quantity, unit and origin wrap with a hanging indent.
450
480
  const full = (row, role = "secondary") => prose(terminalText(row.trim()), width - 4).map((part, i) => (i ? " " : " ") + paint(part, role, theme));
451
- section("Inputs and origins", run.origins.flatMap(row => full(row)));
452
- section("Assumptions", run.assumptions.flatMap(row => full(row)));
453
- 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)] : []));
462
- out.push("", ...full(run.tail.map(terminalText).join(" · "), run.state === "ok" ? "quiet" : "attention"));
481
+ if (run.artifacts.length) out.push("", " " + paint("Files", "strong", theme), ...run.artifacts.flatMap(({ artifact, number, sameBytesAs }) =>
482
+ prose(`${terminalText(artifact.path)} · ${terminalText(artifact.kind)} · ${artifact.bytes} B · /download ${number}${sameBytesAs ? ` · same bytes as ${sameBytesAs}` : ""}`, width - 4)
483
+ .map((part, index) => ` ${index ? " " : paint("↓", "accent", theme)} ${paint(part, "secondary", theme)}`)));
484
+ out.push("", ...full(run.tail.map(terminalText).join(" · "), run.state === "completed" ? "quiet" : "attention"));
485
+ if (run.stop.length) out.push("", ...run.stop.flatMap(line => prose(terminalText(line), width - 4).map(part => " " + paint(part, "attention", theme))));
463
486
  return "\n" + out.join("\n") + "\n";
464
487
  }
488
+
489
+
490
+ /** The same human grammar in live scrollback and reload, with bounded excerpt previews. */
491
+ export function richBlock(block, columns = 80, color = true, { full = false } = {}) {
492
+ const theme = themeOf(color), width = Math.max(20, columns - 1);
493
+ const c = blockContent(block, { full });
494
+ const role = ["ok", "completed"].includes(c.status) ? "success" : c.status === "running" ? "attention" : "error";
495
+ const header = `${paint("●", role, theme)} ${paint(terminalText(c.tool ?? c.title), "strong", theme)}${c.tool ? ` ${paint(terminalText(c.title), "primary", theme)}` : ""}`;
496
+ const out = wrap(header, width);
497
+ for (const row of c.rows) out.push(...wrap(terminalText(row).trim(), width - 5).map((line, i) =>
498
+ `${i ? " " : " ⎿ "}${paint(line, "secondary", theme)}`));
499
+ return out.join("\n");
500
+ }