@vecteur/cli 0.11.1 → 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
@@ -37,26 +37,13 @@ export class TerminalWriter {
37
37
  if (this.awaiting) this.since += rows;
38
38
  else if (this.row) this.row = Math.min(this.stdout.rows ?? 24, this.row + rows);
39
39
  }
40
- progress(view, { controlsOnly = false } = {}) {
40
+ progress(view) {
41
41
  const subject = view.run?.subject?.id;
42
- if (subject !== this.subject) { this.subject = subject; this.lastProgress = null; this.lastQuestion = null; this.controls = new Map(); }
42
+ if (subject !== this.subject) { this.subject = subject; this.lastProgress = null; }
43
43
  if (!subject || view.run.terminal) return;
44
- if (!controlsOnly && view.run.progress && view.run.progress !== this.lastProgress) {
44
+ if (view.run.progress && view.run.progress !== this.lastProgress) {
45
45
  this.append(safe(`${view.run.progress} · ${view.run.elapsed ?? "Elapsed unavailable"}`)); this.lastProgress = view.run.progress;
46
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;
55
- const question = view.run.question;
56
- if (question?.id !== this.lastQuestion) {
57
- this.lastQuestion = question?.id;
58
- if (question) this.append(safe(`Vecteur needs your answer — /answer\n${question.questions.map(row => row.question).join("\n")}`));
59
- }
60
47
  }
61
48
  /** Scrollback text, then the given live frame in the same write: the composer never blinks out. */
62
49
  append(text, frame = null) {
@@ -141,9 +128,9 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
141
128
  let lastPlainStatus = "", lastPlainIdentity = "", plainDraft = "", frameTimer, clockTimer, cancelAt = 0, cancelRun, exitAt = 0;
142
129
  let snapshot = null, localPicker = null, loginAction = 0, updateChecked = false, tick = 0;
143
130
  // While a vendor owns the TTY (handoff) Vecteur writes nothing: frames, clocks, streamed
144
- // 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.
145
132
  let vendorOwnsTerminal = false, resizedDuringHandoff = false; const heldMessages = [];
146
- // Immutable event blocks commit once; mutable controls have their own live/final section.
133
+ // Immutable event blocks commit once.
147
134
  const streamed = { run: null, keys: new Set() };
148
135
  // The identity header is live until the first transcript block, then committed once.
149
136
  let headerLive = true, cursorHidden = false;
@@ -208,7 +195,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
208
195
  const commitBlocks = (runId, blocks) => {
209
196
  if (streamed.run !== runId) { streamed.run = runId; streamed.keys = new Set(); }
210
197
  for (const block of blocks) {
211
- if (!block.committed || ["control", "terminal"].includes(block.kind) || streamed.keys.has(block.key)) continue;
198
+ if (!block.committed || block.kind === "terminal" || streamed.keys.has(block.key)) continue;
212
199
  print(writer.plain ? blockText(block) : layout.richMessage({ kind: "block", block }, stdout.columns ?? 80, theme));
213
200
  streamed.keys.add(block.key);
214
201
  }
@@ -219,7 +206,6 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
219
206
  if (ticking && !clockTimer) clockTimer = setInterval(() => { tick++; draw(); }, prefs.reducedMotion ? 1000 : 200);
220
207
  if (!ticking) { clearInterval(clockTimer); clockTimer = null; }
221
208
  const run = session.run;
222
- if (!writer.plain && (stdout.rows ?? 24) < 18) writer.progress(view, { controlsOnly: true });
223
209
  if (run?.open && Array.isArray(run.events)) commitBlocks(run.run_id, view.run.blocks);
224
210
  if (process.connected && process.send && env.VECTEUR_UPDATE_SESSION && session.release?.compatible
225
211
  && session.registry && (!view.busy || view.prompt)) {
@@ -232,7 +218,7 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
232
218
  history.length = 0; historyIndex = 0; historyDraft = ""; historyAccount = accountKey; input.undo = []; input.killed = ""; snapshot = null; }
233
219
  if (writer.plain) {
234
220
  writer.progress(view);
235
- 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}`;
236
222
  if (identity !== lastPlainIdentity) { writer.append(safe(identity)); lastPlainIdentity = identity; }
237
223
  }
238
224
  if (view.prompt !== activePrompt) {
@@ -262,10 +248,6 @@ export async function startTerminal(options = {}, { stdin = process.stdin, stdou
262
248
  // Flush the terminal prefix too: unmatched calls close only in the final direct record.
263
249
  if (message.kind === "answer" && message.sections?.blocks) commitBlocks(message.runId, message.sections.blocks);
264
250
  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
251
  const text = writer.plain ? message.kind === "answer" && message.sections
270
252
  ? safe(humanRunSections(message.sections, { shownKeys })) : safe(message.text)
271
253
  : layout.richMessage(message, stdout.columns ?? 80, theme, { shownKeys });
package/src/tui/view.js CHANGED
@@ -2,7 +2,7 @@ import stringWidth from "string-width";
2
2
  import wrapAnsi from "wrap-ansi";
3
3
  import { parseMarkdown } from "../markdown.js";
4
4
  import { blockContent } from "../blocks.js";
5
- import { terminalText, plainLine, taskLines } from "../format.js";
5
+ import { terminalText, plainLine } from "../format.js";
6
6
 
7
7
  // Unknown palette: the terminal owns its readable default pair. Only repeated metadata is faint.
8
8
  export const DEFAULT_THEME = Object.freeze({ primary: "", accent: "1", attention: "1", success: "1", error: "1",
@@ -178,9 +178,11 @@ export function markdownView(source, width, color = true) {
178
178
  } else if (block.kind === "hr") {
179
179
  lines.push(paint("─".repeat(Math.min(width, 48)), "rule", theme));
180
180
  } else if (block.kind === "list") {
181
- block.items.forEach((item, index) => {
182
- const prefix = block.ordered ? `${index + 1}. ` : "• ";
183
- 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));
184
186
  });
185
187
  } else {
186
188
  let value = inline(block.inline, theme);
@@ -254,7 +256,7 @@ function trimStart(value, max) {
254
256
  }
255
257
 
256
258
  const execution = view => view.location && view.location !== "Vecteur cloud" ? view.location : "Cloud";
257
- const routeOf = view => `${view.lead ? `${view.lead} · ` : ""}${view.model} · ${execution(view)}`;
259
+ const routeOf = view => `${view.model} · ${execution(view)}`;
258
260
  const customOrigin = view => view.origin && view.origin !== "https://vecteur.space" ? view.origin : "";
259
261
 
260
262
  /**
@@ -295,7 +297,7 @@ export function richLayout(view, composer, cursor, options = {}) {
295
297
  const theme = themeOf(color);
296
298
  const width = Math.max(20, columns - 1), budget = Math.max(1, rows - 3);
297
299
  const active = !!view.run?.subject && !view.run.terminal;
298
- const pending = view.run?.blocks?.find(block => !block.committed && block.calls);
300
+ const pending = view.run?.blocks?.find(block => !block.committed && block.kind === "tool");
299
301
  const pendingContent = pending ? blockContent(pending) : null;
300
302
  // Compact layouts reserve their activity row for the open call, including its state.
301
303
  const callSummary = pendingContent ? `${pendingContent.tool} ${trimEnd(plainLine(pendingContent.title),
@@ -304,7 +306,7 @@ export function richLayout(view, composer, cursor, options = {}) {
304
306
  const glyph = tick === null ? "●" : SPINNER[tick % SPINNER.length];
305
307
  const runHint = readOnly ? "Read-only · /help · Ctrl+D detach"
306
308
  : signedOut ? `${view.offline ? "/resume" : "/login"} · /help · Ctrl+D detach`
307
- : `${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`;
308
310
  const idleHint = `${readOnly ? "Read-only · /project" : signedOut ? "Enter sign in" : view.busy ? "Please wait" : "Enter send"} · / commands · ? shortcuts`;
309
311
  if (rows < 12) {
310
312
  const focus = view.focus ?? view.prompt;
@@ -361,27 +363,16 @@ export function richLayout(view, composer, cursor, options = {}) {
361
363
  // Activity: the one animated glyph, the current step and the server-anchored clock.
362
364
  if (active && !compactFocus) {
363
365
  const clock = view.run.elapsed ?? "Elapsed unavailable";
364
- const doing = compactRun ? callSummary ?? view.status : (view.run.progress || "Working").replace(/^Starting: (.+)$/, "$1").replace(/[.…]+$/, "") + "…";
366
+ const doing = compactRun ? callSummary ?? view.status : (view.run.progress || "Working").replace(/[.…]+$/, "") + "…";
365
367
  const head = `${paint(glyph, "accent", theme)} ${paint(terminalText(doing), "primary", theme)}`, tail = paint(terminalText(clock), "quiet", theme);
366
368
  if (measure(`${glyph} ${terminalText(doing)} · ${terminalText(clock)}`) <= width) lines.push(`${head} ${paint("·", "quiet", theme)} ${tail}`);
367
369
  else if (compactRun) lines.push(callSummary ? paint(terminalText(doing), "attention", theme) : wrap(head, width)[0], ` ${tail}`);
368
370
  else lines.push(wrap(`${paint(glyph, "accent", theme)} ${tail} · ${paint(terminalText(doing), "primary", theme)}`, width)[0]);
369
371
  if (!compactRun && view.status && view.status !== "Running") line(` ${view.status}`, "secondary", 1);
370
372
  }
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
- }
373
+ if (active && !compactFocus && !compactRun && pendingContent) {
374
+ line(` ${pendingContent.tool} ${pendingContent.title} · ${pendingContent.status}`, "attention", 1);
382
375
  }
383
- if (!compactFocus && !compactRun && view.run?.question) line(readOnly ? "Waiting for an editor to answer"
384
- : signedOut ? "Question pending — reconnect to answer" : "Your answer is needed · /answer", "attention", 1);
385
376
  if (prompt) {
386
377
  line(prompt.title, "strong", compactFocus ? 1 : 3);
387
378
  if (!prompt.typed) {
@@ -428,7 +419,7 @@ export function richLayout(view, composer, cursor, options = {}) {
428
419
  const placeholder = prompt ? (prompt.typed ? "Type your answer…" : "Filter or type a choice number…")
429
420
  : readOnly ? "Read-only Project — draft here…" : view.offline ? "Draft offline…"
430
421
  : !view.account ? "Sign in to send — draft here…"
431
- : active ? "Draft your next question…" : "Ask Laplace…";
422
+ : active ? "Draft your next question…" : "Ask Vecteur…";
432
423
  lines.push(...composerBand(draft.lines.map((value, index) => ` ${index ? " " : paint("›", "accent", theme)} ${composer ? paint(value, "primary", theme)
433
424
  : paint("▌", "accent", theme) + paint(placeholder, "secondary", theme)}`), width, theme,
434
425
  { top: selection, bottom: draft.scrolling ? draft.position : "" }));
@@ -446,7 +437,7 @@ export function richLayout(view, composer, cursor, options = {}) {
446
437
  }
447
438
  if (firstUse) {
448
439
  const note = "New folder · A project will be created on your first message. /link existing";
449
- 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)];
450
441
  const suggestions = ONBOARDING.map(text => `${paint("›", "accent", theme)} ${paint(text, "secondary", theme)}`);
451
442
  const quiet = wrap(note, width).map(row => paint(row, "quiet", theme));
452
443
  const body = [[...intro, "", ...suggestions, "", ...quiet], [...intro, "", ...quiet], quiet]
@@ -466,7 +457,7 @@ export function richFrame(view, composer, cursor, options = {}) {
466
457
  const indent = (text, first, rest = " ") => text.split("\n").map((line, i) => (i ? (line ? rest : "") : first) + line).join("\n");
467
458
 
468
459
  /** One scrollback block per message: the ask, the answer with its record, or a quiet notice. */
469
- export function richMessage(message, columns, color, { stepsShown = false, shownKeys = new Set() } = {}) {
460
+ export function richMessage(message, columns, color, { shownKeys = new Set() } = {}) {
470
461
  const theme = themeOf(color), width = Math.max(20, columns - 1);
471
462
  if (message.kind === "user") {
472
463
  const rows = wrap(terminalText(message.text), width - 2).map((row, index) =>
@@ -478,34 +469,20 @@ export function richMessage(message, columns, color, { stepsShown = false, shown
478
469
  if (message.kind !== "answer") return wrap(terminalText(message.text), width - 2).map(line => " " + line).join("\n");
479
470
  const run = message.sections;
480
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.
481
473
  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), "");
474
+ for (const block of run.blocks) {
475
+ if (block.kind !== "terminal" && !shownKeys.has(block.key)) out.push(richBlock(block, columns, theme));
487
476
  }
488
- out.push(run.answer !== undefined ? indent(markdownView(run.answer, width - 2, theme), paint("●", "accent", theme) + " ")
477
+ if (out.length) out.push("");
478
+ out.push(run.answer ? indent(markdownView(run.answer, width - 2, theme), paint("●", "accent", theme) + " ")
489
479
  : 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))));
493
- const section = (title, rows) => { if (rows.length) out.push("", " " + paint(title, "strong", theme), ...rows); };
494
- const one = text => text.split("\n").map(part => part.trim()).filter(Boolean).join(" · ");
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)}`)));
498
- // Evidence rows are never truncated: quantity, unit and origin wrap with a hanging indent.
499
480
  const full = (row, role = "secondary") => prose(terminalText(row.trim()), width - 4).map((part, i) => (i ? " " : " ") + paint(part, role, theme));
500
- section("Inputs and origins", run.origins.flatMap(row => full(row)));
501
- section("Assumptions", run.assumptions.flatMap(row => full(row)));
502
- section("Transfer tables", run.tables.flatMap(rows => rows.flatMap(row => full(row))));
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)
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)
505
483
  .map((part, index) => ` ${index ? " " : paint("↓", "accent", theme)} ${paint(part, "secondary", theme)}`)));
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)));
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))));
509
486
  return "\n" + out.join("\n") + "\n";
510
487
  }
511
488
 
@@ -514,24 +491,10 @@ export function richMessage(message, columns, color, { stepsShown = false, shown
514
491
  export function richBlock(block, columns = 80, color = true, { full = false } = {}) {
515
492
  const theme = themeOf(color), width = Math.max(20, columns - 1);
516
493
  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";
494
+ const role = ["ok", "completed"].includes(c.status) ? "success" : c.status === "running" ? "attention" : "error";
520
495
  const header = `${paint("●", role, theme)} ${paint(terminalText(c.tool ?? c.title), "strong", theme)}${c.tool ? ` ${paint(terminalText(c.title), "primary", theme)}` : ""}`;
521
496
  const out = wrap(header, width);
522
497
  for (const row of c.rows) out.push(...wrap(terminalText(row).trim(), width - 5).map((line, i) =>
523
498
  `${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
499
  return out.join("\n");
537
500
  }
package/src/wire.js ADDED
@@ -0,0 +1,73 @@
1
+ /** Wire v6 as this door reads it: one run is one turn; an event is `{run_id, seq, kind, payload}`.
2
+ * The vocabularies are the owner's (`contract.js`, generated); the payload shapes below follow `runner/wire.py`.
3
+ * Anything this reader does not know is refused by name, never rendered as a success. */
4
+ import { EVENT_KINDS, STORED_WIRE_VERSIONS, TERMINAL_DEFECTS, TERMINAL_STATES, TOOL_KINDS } from "./contract.js";
5
+ import { CliError } from "./errors.js";
6
+
7
+ const CAS_REF = /^sha256:[0-9a-f]{64}$/;
8
+ const STATE_HASH = /^[0-9a-f]{64}$/;
9
+ const object = value => !!value && typeof value === "object" && !Array.isArray(value);
10
+ const text = value => typeof value === "string" && value.length > 0;
11
+ const count = value => Number.isSafeInteger(value) && value >= 0;
12
+
13
+ export const isStateHash = value => typeof value === "string" && STATE_HASH.test(value);
14
+
15
+ /** One check per kind; a payload may carry more than these fields, never less. */
16
+ const PAYLOADS = {
17
+ assistant_delta: p => typeof p.text === "string",
18
+ tool_call: p => text(p.call_id) && TOOL_KINDS.includes(p.tool) && typeof p.title === "string" && object(p.input),
19
+ tool_result: p => text(p.call_id) && typeof p.ok === "boolean" && typeof p.excerpt === "string" && count(p.bytes),
20
+ synthesis: p => typeof p.markdown === "string",
21
+ artifact: p => text(p.path) && count(p.revision) && CAS_REF.test(p.cas_ref) && text(p.media_type) && count(p.bytes) && text(p.kind),
22
+ study: p => CAS_REF.test(p.cas_ref),
23
+ review: p => CAS_REF.test(p.cas_ref) && text(p.verdict),
24
+ terminal: p => (p.defect === undefined || TERMINAL_DEFECTS.includes(p.defect)) && (p.usage === null || object(p.usage)),
25
+ };
26
+
27
+ /** The runner numbers a run's events from 1 (runner/store.py `append`) and resumes after the Last-Event-ID it is sent. */
28
+ export const FIRST_EVENT_SEQ = 1;
29
+
30
+ export function validateEvent(value, runId, expectedSeq) {
31
+ if (!object(value) || Object.keys(value).sort().join(",") !== "kind,payload,run_id,seq") {
32
+ throw new CliError("event_invalid", "Server returned malformed owner data");
33
+ }
34
+ if (value.run_id !== runId || value.seq !== expectedSeq) {
35
+ throw new CliError("event_sequence_invalid", `Expected event sequence ${expectedSeq}`);
36
+ }
37
+ if (!EVENT_KINDS.includes(value.kind)) {
38
+ throw new CliError("event_kind_unknown", `Run event ${expectedSeq} has a kind this CLI does not know (${String(value.kind).slice(0, 40)}); next: vecteur update`);
39
+ }
40
+ if (value.kind === "terminal" && object(value.payload) && !TERMINAL_STATES.includes(value.payload.state)) {
41
+ throw new CliError("terminal_state_unknown", `Run ended in a state this CLI does not know (${String(value.payload.state).slice(0, 40)}); next: vecteur update`);
42
+ }
43
+ if (!object(value.payload) || !PAYLOADS[value.kind](value.payload)) {
44
+ throw new CliError("event_invalid", `Run event ${expectedSeq} (${value.kind}) is malformed`);
45
+ }
46
+ return value;
47
+ }
48
+
49
+ /** The run record: an open run has no terminal and no result hash; a closed one has both, and its last event says the same state. */
50
+ export function validateRun(value, runId = value?.run_id) {
51
+ const invalid = why => new CliError("run_invalid", `Server returned malformed run record (${why})`);
52
+ if (!object(value) || !text(value.run_id) || value.run_id !== runId) throw invalid("identity");
53
+ if (!isStateHash(value.state_hash)) throw invalid("state_hash");
54
+ if (typeof value.result_hash !== "string" || typeof value.terminal !== "string" || !Array.isArray(value.events)) throw invalid("shape");
55
+ if (value.stored_wire_version !== undefined && !STORED_WIRE_VERSIONS.includes(value.stored_wire_version)) {
56
+ throw new CliError("wire_version_unsupported", "this Run is stored in a wire version this CLI cannot read; next: vecteur update");
57
+ }
58
+ if (value.duration_seconds !== undefined && value.duration_seconds !== null && !count(value.duration_seconds)) throw invalid("duration_seconds");
59
+ value.events.forEach((event, index) => validateEvent(event, value.run_id, FIRST_EVENT_SEQ + index));
60
+ const last = value.events.at(-1);
61
+ if (value.events.some((event, index) => event.kind === "terminal" && index !== value.events.length - 1)) throw invalid("events after terminal");
62
+ if (value.terminal === "") {
63
+ if (value.result_hash !== "" || last?.kind === "terminal") throw invalid("open run carries a result");
64
+ return value;
65
+ }
66
+ if (!TERMINAL_STATES.includes(value.terminal)) {
67
+ throw new CliError("terminal_state_unknown", `Run ended in a state this CLI does not know (${value.terminal.slice(0, 40)}); next: vecteur update`);
68
+ }
69
+ if (!value.result_hash) throw invalid("terminal without result_hash");
70
+ if (last?.kind !== "terminal") throw new CliError("terminal_invalid", "Run record has no final terminal event");
71
+ if (last.payload.state !== value.terminal) throw new CliError("terminal_mismatch", "Run terminal event disagrees with its record");
72
+ return value;
73
+ }
package/src/executor.js DELETED
@@ -1,171 +0,0 @@
1
- /** The foreground process owns consent, a per-Run secret and one bounded shell process group. */
2
- import { randomBytes, createHash } from 'node:crypto';
3
- import { spawn } from 'node:child_process';
4
- import { localProcessEnv, scanContent, withLocalLock, pinCheck, walk, closeChain, consumeExec } from './localfiles.js';
5
- import { CliError } from './errors.js';
6
- import { validateLocalExecStatus } from './contract.js';
7
-
8
- const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
9
- const hash = value => createHash('sha256').update(value).digest('hex');
10
- const fail = () => { throw new CliError('protocol_invalid', 'Invalid local executor protocol'); };
11
-
12
- export function ring(cap) {
13
- let bytes = Buffer.alloc(0), count = 0;
14
- return {
15
- push(chunk) { count += chunk.length; bytes = Buffer.concat([bytes, chunk.subarray(-cap)]).subarray(-cap); },
16
- get count() { return count; },
17
- finish() {
18
- let start = 0;
19
- if (count > bytes.length) while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
20
- const tail = bytes.subarray(start);
21
- if (tail.length) scanContent(tail, 'stdout.txt');
22
- return { text: new TextDecoder('utf-8', { fatal: true }).decode(tail), count, truncated: count > tail.length };
23
- },
24
- };
25
- }
26
-
27
- export class Executor {
28
- constructor({ client, grant, pin, env = process.env, approve = null, session = false }) {
29
- this.client = client; this.grant = grant; this.pin = pin; this.env = env;
30
- this.approve = approve; this.session = session; this.closed = false; this.unknown = false; this.paused = false; this.revoked = false;
31
- this.secret = randomBytes(32).toString('hex'); this.descriptor = { secret_sha256: hash(Buffer.from(this.secret, 'hex')) };
32
- this.abort = new AbortController();
33
- this.seen = new Set(); this.active = null;
34
- }
35
-
36
- check({ allowPaused = false } = {}) {
37
- if (this.closed || this.unknown || !this.secret || this.paused && !allowPaused) throw new CliError('executor_revoked', 'Local execution stopped');
38
- pinCheck(this.grant, this.pin(), this.env, { execution: true });
39
- }
40
-
41
- stop(reason = 'outcome_unknown') {
42
- this.closed = true; this.revoked ||= reason === 'executor_revoked'; this.abort.abort();
43
- this.active?.stop(reason);
44
- this.secret = null;
45
- }
46
-
47
- async pump(runId) {
48
- this.runId = runId;
49
- let task = null;
50
- try {
51
- while (!this.closed) {
52
- await withLocalLock(() => this.check({ allowPaused: true }), this.env, { timeout: 2000 });
53
- const polledAt = performance.now();
54
- const reply = await this.client.localExec(runId, { secret: this.secret });
55
- if (!validateLocalExecStatus(reply) || reply.requests.length > 1) fail();
56
- if (reply.stop) break;
57
- this.paused = reply.paused;
58
- if (this.paused) {
59
- if (task) task.interrupted = true;
60
- this.approval?.abort(); this.active?.stop('executor_revoked');
61
- }
62
- for (const request of reply.requests) {
63
- if (!task && !this.seen.has(request.id)) {
64
- this.seen.add(request.id);
65
- const current = { interrupted: false }; task = current;
66
- current.done = this.execute(request, polledAt).catch(() => { if (!current.interrupted) this.stop(); })
67
- .finally(() => { if (task === current) task = null; });
68
- }
69
- }
70
- await sleep(1000);
71
- }
72
- } finally {
73
- this.stop();
74
- await task?.done;
75
- }
76
- }
77
-
78
- async execute(request, polledAt = performance.now()) {
79
- const { id, command, timeout, approval_remaining, hard_remaining } = request;
80
- const secret = this.secret;
81
- // Subtract the entire poll round trip conservatively; server and client wall clocks may differ.
82
- const approval = polledAt + approval_remaining*1000, hard = polledAt + hard_remaining*1000;
83
- if (!/^[0-9a-f]{32}$/.test(id) || typeof command !== 'string' || command.includes('\0')
84
- || !Buffer.byteLength(command) || Buffer.byteLength(command) > 8192
85
- || !Number.isInteger(timeout) || timeout < 1 || timeout > 600 || !Number.isFinite(approval)
86
- || !Number.isFinite(hard) || hard <= performance.now() || request.state !== 'pending') fail();
87
- let choice = this.session ? 'session' : null, alarm;
88
- const approvalAbort = this.approval = new AbortController();
89
- const cancelApproval = () => approvalAbort.abort();
90
- if (!choice) {
91
- this.abort.signal.addEventListener('abort', cancelApproval, { once: true });
92
- if (!this.approve) fail();
93
- choice = await Promise.race([
94
- // Leaving the open prompt (Esc, cancel) is a decline; the server must see a refusal, never silence.
95
- this.approve({ command, timeout, folder: this.grant.root.path, signal: approvalAbort.signal }).catch(e => { if (e?.code === 'action_cancelled') return 'decline'; throw e; }),
96
- new Promise(resolve => { alarm = setTimeout(() => { resolve('expired'); approvalAbort.abort(); }, Math.max(0, approval-performance.now())); }),
97
- ]).finally(() => {
98
- if (this.approval === approvalAbort) this.approval = null;
99
- clearTimeout(alarm); this.abort.signal.removeEventListener('abort', cancelApproval);
100
- });
101
- }
102
- // Explicit revocation while the prompt was open: the server must record executor_revoked, not_started.
103
- if (this.revoked) { await this.client.localExec(this.runId, { secret, action: 'refuse', code: 'executor_revoked' }, id); return; }
104
- if (this.closed) return; // stop-driven cancel: not the user's decision, and the secret is gone
105
- await withLocalLock(() => this.check(), this.env, { timeout: 2000 });
106
- if (!['once', 'session'].includes(choice)) {
107
- await this.client.localExec(this.runId, { secret: this.secret, action: 'refuse', code: choice === 'expired' ? 'approval_timeout' : 'user_declined' }, id);
108
- return;
109
- }
110
- if (choice === 'session') this.session = true;
111
- const nonce = randomBytes(32).toString('hex');
112
- const ack = await this.client.localExec(this.runId, { secret: this.secret, action: 'start', nonce }, id);
113
- if (ack?.permit !== true || ack.state !== 'started') return;
114
- let chain, execution;
115
- try {
116
- await withLocalLock(() => {
117
- this.check();
118
- if (performance.now() + (timeout + 2)*1000 > hard) fail();
119
- consumeExec(this.runId, id, this.env);
120
- chain = walk(this.grant);
121
- execution = this.shell(id, command, timeout, chain[0].fd);
122
- }, this.env);
123
- // No await between the last pin check, permit consumption and spawn.
124
- const answer = await execution;
125
- if (answer.effect === 'unknown') this.unknown = true;
126
- // Revocation bars starts immediately; the consumed permit may still seal its typed outcome.
127
- if (!this.secret && answer.code !== 'executor_revoked') return;
128
- const body = { secret, action: 'seal', nonce, result: answer };
129
- try { await this.client.localExec(this.runId, body, id); }
130
- catch { await this.client.localExec(this.runId, body, id); } // identical seal only; never repeat spawn
131
- } finally { if (chain) closeChain(chain); }
132
- }
133
-
134
- async shell(id, command, timeout, fd) {
135
- const start = performance.now(), out = ring(16000), err = ring(8000);
136
- const child = spawn('/bin/bash', ['--noprofile', '--norc', '-c', command], {
137
- cwd: `/proc/${process.pid}/fd/${fd}`, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
138
- env: localProcessEnv(this.env, this.grant.root.path),
139
- });
140
- let reason = null, escalation, failed = false;
141
- const kill = signal => { if (!child.pid) return; try { process.kill(-child.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
142
- const stop = why => {
143
- if (why && !reason) reason = why;
144
- kill('SIGTERM');
145
- escalation ??= setTimeout(() => kill('SIGKILL'), 2000);
146
- };
147
- this.active = { stop };
148
- child.stdout.on('data', chunk => out.push(chunk)); child.stderr.on('data', chunk => err.push(chunk));
149
- child.on('error', () => { failed = true; });
150
- child.on('exit', () => stop(null)); // descendants may still hold the pipes after their leader exits
151
- const wall = setTimeout(() => stop('timeout'), timeout * 1000);
152
- const code = await new Promise(resolve => child.on('close', resolve));
153
- clearTimeout(wall);
154
- if (escalation) { kill('SIGKILL'); clearTimeout(escalation); }
155
- this.active = null;
156
- const result = { request_id: id, code: failed ? 'spawn_failed' : reason ?? (code === 0 ? 'ok' : 'command_failed'),
157
- exit_code: code, seconds: (performance.now()-start)/1000, stdout_tail: '', stderr_tail: '', stdout_bytes: out.count, stderr_bytes: err.count,
158
- truncated: { stdout: out.count > 16000, stderr: err.count > 8000 }, effect: failed ? 'not_started' : reason ? 'unknown' : 'completed' };
159
- // Counts survive a refusal; no unscanned text is ever attached to an error or persisted.
160
- const streams = [];
161
- for (const [stream, buffer] of [['stdout', out], ['stderr', err]]) {
162
- try { streams.push([stream, buffer.finish()]); }
163
- catch (error) { result.code = error.code === 'secret_suspected' ? error.code : 'scan_unsupported'; }
164
- }
165
- for (const [stream, data] of streams) {
166
- result[stream+'_bytes'] = data.count; result.truncated[stream] = data.truncated;
167
- if (!['secret_suspected', 'scan_unsupported'].includes(result.code)) result[stream+'_tail'] = data.text;
168
- }
169
- return result;
170
- }
171
- }
package/src/produce.js DELETED
@@ -1,49 +0,0 @@
1
- /** v5 §2.5, CU-4 parity: the closed Produce entries, in the words of the cockpit's Produce panel (`ProducePanel.vue`; its spec
2
- * holds this table to the panel). The same intent has one mode on every door. This is the grammar only: which entry is
3
- * available is the run door's alone (A38, `backend/src/vecteur/contract/produce-availability.json`), and its refusal
4
- * `produce_unavailable` names the entry. */
5
- import { CliError } from "./client.js";
6
-
7
- const documents = { field: "profile", choices: ["nasa", "esa"] };
8
- const code = { field: "standard", choices: ["vecteur", "nasa", "user"] };
9
- const standalone = target => ({ mode: "standalone", target, ...code });
10
-
11
- export const PRODUCE_ENTRIES = {
12
- business: { fleet_market_benchmark: { mode: "fleet_market_benchmark" } },
13
- knowledge: {
14
- mrd: { mode: "mrd", ...documents }, srd: { mode: "srd", ...documents }, dddj: { mode: "dddj", ...documents },
15
- ard: { mode: "ard", ...documents }, ingest: { mode: "ingest" },
16
- },
17
- code: {
18
- numpy_scipy: standalone("numpy_scipy"), orekit: standalone("orekit"), spice: standalone("spice"),
19
- gmat: standalone("gmat"), basilisk: standalone("basilisk"), integrate: { mode: "integrate", ...code },
20
- // The coding agent: no target and no standard; the host re-runs the tests it delivers.
21
- standalone: { mode: "standalone" },
22
- },
23
- };
24
-
25
- const USAGE = `Use /produce business <ask> or /produce knowledge <${Object.keys(PRODUCE_ENTRIES.knowledge).join("|")}> [profile=nasa|esa] <ask>; `
26
- + "a knowledge document needs a completed analysis in this Project first";
27
-
28
- /** `<specialist> [entry] [field=choice] <ask>` -> { ask, intent }. Business has one entry; the others name theirs. An absent
29
- * choice is the panel's first option. Anything else sends nothing. */
30
- export function produceIntent(argument) {
31
- const match = /^(business|knowledge|code)\s+([\s\S]+)$/.exec(argument.trim());
32
- if (!match) throw new CliError("usage_invalid", USAGE);
33
- const specialist = match[1];
34
- let rest = match[2].trim();
35
- let name = "fleet_market_benchmark";
36
- if (specialist !== "business") {
37
- const head = /^(\S+)\s+([\s\S]+)$/.exec(rest);
38
- if (!head || !Object.hasOwn(PRODUCE_ENTRIES[specialist], head[1])) throw new CliError("usage_invalid", USAGE);
39
- [name, rest] = [head[1], head[2].trim()];
40
- }
41
- const { mode, target, field, choices } = PRODUCE_ENTRIES[specialist][name];
42
- let chosen = choices?.[0];
43
- const stated = field ? new RegExp(`^${field}=(\\S+)\\s+([\\s\\S]+)$`).exec(rest) : null;
44
- if (stated) {
45
- if (!choices.includes(stated[1])) throw new CliError("usage_invalid", USAGE);
46
- [chosen, rest] = [stated[1], stated[2].trim()];
47
- }
48
- return { ask: rest, intent: { kind: "produce", specialist, mode, ...(target ? { target } : {}), ...(field ? { [field]: chosen } : {}) } };
49
- }