@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.
package/src/folders.js CHANGED
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
2
2
  import { readFileSync, realpathSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, isAbsolute, join, relative, sep, parse } from "node:path";
5
+ import { localMutation, endGrants } from "./localfiles.js";
5
6
  import { credentialsPath } from "./credentials.js";
6
7
  import { CliError } from "./errors.js";
7
8
  import { readStore, withStoreLock, writeStore } from "./store.js";
@@ -71,6 +72,7 @@ function readRegistry(file) {
71
72
  export class FolderRegistry {
72
73
  constructor({ origin, accountId, cwd = process.cwd(), env = process.env }) {
73
74
  if (!origin || !accountId) throw new CliError("folder_identity_invalid", "Origin and account are required");
75
+ this.env = env;
74
76
  this.origin = origin;
75
77
  this.accountId = accountId;
76
78
  this.folder = identity(cwd);
@@ -137,7 +139,13 @@ export class FolderRegistry {
137
139
 
138
140
  broadRoot() { return broadRoot(this.folder.path, this.home); }
139
141
 
140
- bind(projectId, { confirmHome = false, confirmBroad = confirmHome } = {}) {
142
+ bind(projectId, options = {}) {
143
+ return localMutation('bind', { origin: this.origin, accountId: this.accountId, cwd: this.folder.path, args: [projectId, options] }, this.env, () => {
144
+ return this.bindLocked(projectId, options);
145
+ });
146
+ }
147
+
148
+ bindLocked(projectId, { confirmHome = false, confirmBroad = confirmHome } = {}) {
141
149
  this.requireAccount();
142
150
  if (typeof projectId !== "string" || !projectId) throw new CliError("project_invalid", "Choose a Project first");
143
151
  const broad = this.broadRoot();
@@ -149,6 +157,8 @@ export class FolderRegistry {
149
157
  if (row.pendingCreate || row.pendingRun) {
150
158
  throw new CliError("operation_unresolved", "Resolve the pending submission before relinking");
151
159
  }
160
+ // Validate first, then durably end authority before publishing the binding.
161
+ endGrants({ origin: this.origin, accountId: this.accountId, root: this.folder.path }, this.env);
152
162
  row.projectId = projectId;
153
163
  delete row.unlinked;
154
164
  delete row.pendingCreate;
@@ -156,11 +166,18 @@ export class FolderRegistry {
156
166
  }
157
167
 
158
168
  unlink() {
169
+ return localMutation('unlink', { origin: this.origin, accountId: this.accountId, cwd: this.folder.path, args: [] }, this.env, () => {
170
+ return this.unlinkLocked();
171
+ });
172
+ }
173
+
174
+ unlinkLocked() {
159
175
  return withStoreLock(this.file, () => {
160
176
  const store = this.#read();
161
177
  const row = store.folders[this.key];
162
178
  if (row?.pendingCreate || row?.pendingRun) throw new CliError("operation_unresolved",
163
179
  "Reconcile the pending submission before unlinking; its identity must survive");
180
+ endGrants({ origin: this.origin, accountId: this.accountId, root: this.folder.path }, this.env);
164
181
  store.folders[this.key] = { ...row, origin: this.origin, accountId: this.accountId, folder: this.folder, unlinked: true };
165
182
  delete store.folders[this.key].projectId;
166
183
  writeStore(this.file, store);
@@ -178,11 +195,19 @@ export class FolderRegistry {
178
195
  }
179
196
 
180
197
  completeCreation(key, projectId) {
181
- this.#update(row => {
198
+ return localMutation('completeCreation', { origin: this.origin, accountId: this.accountId,
199
+ cwd: this.folder.path, args: [key, projectId] }, this.env, () => this.completeCreationLocked(key, projectId));
200
+ }
201
+
202
+ completeCreationLocked(key, projectId) {
203
+ return this.#update(row => {
182
204
  if (row.projectId === projectId && !row.pendingCreate) return;
183
205
  if (row.pendingCreate?.key !== key || typeof projectId !== "string" || !projectId) {
184
206
  throw new CliError("creation_mismatch", "Project creation identity changed");
185
207
  }
208
+ // Validation and idempotent completion precede revocation. Its recovery intent
209
+ // must be durable before the new binding can become visible to another terminal.
210
+ endGrants({ origin: this.origin, accountId: this.accountId, root: this.folder.path }, this.env);
186
211
  row.projectId = projectId;
187
212
  delete row.unlinked;
188
213
  delete row.pendingCreate;
@@ -241,6 +266,7 @@ export class FolderRegistry {
241
266
 
242
267
  reserveRun(projectId, body, draftRef = this.draftRef) {
243
268
  this.requireAccount();
269
+ if (body.local_exec !== undefined) throw new CliError('admission_unresolved', 'Execution consent cannot be frozen');
244
270
  return this.#update(row => {
245
271
  if (row.pendingRun) throw new CliError("submission_pending", "Another submission needs reconciliation before a new ask");
246
272
  row.pendingRun = { key: randomUUID(), projectId, body: structuredClone(body), draftRef: structuredClone(draftRef) };
package/src/format.js CHANGED
@@ -1,13 +1,44 @@
1
- import {
2
- ORIGIN_KINDS, ORIGIN_WORD, TERMINAL_FIELDS, TERMINAL_RECOVERY_DECLARATIONS,
3
- validateArtifact, validateSynthesis,
4
- } from "./contract.js";
1
+ import { runBlocks, runArtifacts, artifactRows, blockText } from "./blocks.js";
2
+ import { MODEL_CHOICES, PLAN_WORDS, STOP_ACTION_HREFS, TERMINAL_STATES } from "./contract.js";
3
+ import { STOP_WORDS } from "./stop-words.js";
5
4
  import { CliError } from "./errors.js";
6
5
 
7
6
  /** Terminal presentation only; exact copy and JSON paths retain the original bytes. */
8
7
  export const terminalText = value => String(value ?? "").replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f-\x9f]/g,
9
8
  char => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`).replace(/\t/g, " ");
10
9
 
10
+ /** A bounded unified whole-file hunk. This is a review display, never an executable patch. */
11
+ export function localFileDiff(before, after, from, to) {
12
+ const decode = bytes => new TextDecoder('utf-8',{fatal:true}).decode(bytes);
13
+ let a, b;
14
+ try { a=decode(before); b=decode(after); }
15
+ catch { return `${terminalText(from)} → ${terminalText(to)}: binary or non-UTF-8 diff unavailable`; }
16
+ const lines = text => text ? text.match(/[^\n]*\n|[^\n]+$/g) : [];
17
+ const left=lines(a), right=lines(b);
18
+ if (a===b) return `${terminalText(from)} → ${terminalText(to)}: already identical`;
19
+ const out=[`--- ${terminalText(from)}`,`+++ ${terminalText(to)}`,`@@ -${left.length?1:0},${left.length} +${right.length?1:0},${right.length} @@`];
20
+ let size=0, count=0;
21
+ for (const [prefix, rows] of [['-',left],['+',right]]) for(const line of rows) {
22
+ const rendered=prefix+terminalText(line.replace(/\n$/,''));
23
+ if (++count>200 || size+rendered.length>16000) return out.join('\n')+'\n… diff truncated (200 lines / 16000 characters)';
24
+ size+=rendered.length;out.push(rendered);
25
+ if(!line.endsWith('\n'))out.push('\');
26
+ }
27
+ return out.join('\n');
28
+ }
29
+
30
+ export function proposalReview(rel, snapshot, bytes) {
31
+ return [snapshot.classification === 'local changed' ? `you changed ${terminalText(rel)} since Vecteur read it; your edit is kept`
32
+ : snapshot.classification === 'first sync' ? 'Vecteur has no earlier version of this file from you' : snapshot.classification,
33
+ snapshot.baseline ? snapshot.baseBytes ? localFileDiff(snapshot.baseBytes,snapshot.bytes ?? Buffer.alloc(0),'base','local now') : 'base → local now: base diff unavailable (hash-based status retained)' : '',
34
+ localFileDiff(snapshot.bytes ?? Buffer.alloc(0),bytes,'local now','proposed')].filter(Boolean).join('\n');
35
+ }
36
+
37
+ export function adoptionHint(proposal, original) {
38
+ const quote = value => "'"+value.replaceAll("'", "'\\''")+"'";
39
+ return `Review and adopt in your editor, or:\nmv -i -- ${quote(proposal)} ${quote(original)}`;
40
+ }
41
+
11
42
  export function canonicalJson(value) {
12
43
  validateNumbers(value);
13
44
  return `${JSON.stringify(sortValue(value))}\n`;
@@ -41,364 +72,106 @@ function sortValue(value) {
41
72
  return value;
42
73
  }
43
74
 
44
- /**
45
- * ONE CLASSIFICATION OF THE EVIDENCE A RUN USED, SPOKEN BY THIS DOOR TOO.
46
- *
47
- * PRD-UX-16: every load-bearing value in a step's inputs shows its origin — your brief, assumed,
48
- * derived, your file, catalogue, default — and a value the program attributed to nothing renders
49
- * an explicit marker, NEVER a blank. PRD-CLI-9: every door sees the same state. The web has said
50
- * this for a while; this door printed `[3] step_finished` and nothing else, so the same run
51
- * answered "where did this number come from?" on one surface and stayed silent on the other.
52
- *
53
- * The words come from `contract.js`, generated from `frontend/src/run/provenance.ts` — the
54
- * web's own owner — so the two doors cannot drift into different vocabularies without the
55
- * contract gate going red.
56
- */
57
- export function originWord(origin) {
58
- if (!origin || typeof origin !== "object" || typeof origin.kind !== "string") {
59
- return ORIGIN_WORD.unattributed;
60
- }
61
- // A kind the engine invented and this build does not know is NOT silently "unstated": that
62
- // would report an attribution failure where there is a version skew, and the two read
63
- // completely differently to whoever is trying to trust the number.
64
- if (!ORIGIN_KINDS.includes(origin.kind)) return `unknown origin \`${origin.kind}\``;
65
- return ORIGIN_WORD[origin.kind];
66
- }
67
-
68
- /** `name = value unit (origin word, ref)` — one line per input, in wire order. */
69
- export function inputLines(inputs) {
70
- if (!Array.isArray(inputs)) return [];
71
- return inputs.map((row) => {
72
- const unit = typeof row?.unit === "string" && row.unit ? ` ${row.unit}` : "";
73
- const word = originWord(row?.origin);
74
- // The REF is what makes the word actionable — "your file" is a category, "your file
75
- // (orbit.csv)" is an answer. It is omitted only when the origin does not carry one.
76
- const ref = typeof row?.origin?.ref === "string" && row.origin.ref
77
- ? ` ${row.origin.ref}` : "";
78
- const rendered = `${row?.name ?? "?"} = ${JSON.stringify(row?.value)}${unit} (${word}${ref})`;
79
- return ` ${plainLine(rendered)}`;
80
- });
81
- }
82
-
83
- /**
84
- * ONE ROW PER INTENT, SPOKEN BY THIS DOOR TOO (RunWire v2, CONTRACTS.md S1).
85
- *
86
- * The rows are the `step_finished` facts keyed by `step_id`: the finding as the title, the
87
- * outcome word, the attempt count and the `RESULT:` line the program printed. Tool calls stay
88
- * folded; this door prints the plan, not the process.
89
- */
90
- /** The budget that closed a partial row (`step_finished.cause`), in the reader's words — the same
91
- * words the workbench's row meta uses (`StepRow.vue`). */
92
- const CAUSE_WORD = Object.freeze({
93
- row_budget: "stopped at its budget", wall_budget: "stopped at the turn's time limit",
94
- answer_now: "stopped to answer now; what it printed stands",
95
- });
96
-
97
- /**
98
- * THE ENGINEERING DOOR, SPOKEN BY THIS DOOR TOO (v2.4 S3; the web reads the same bytes in
99
- * `frontend/src/run/door.ts`, and both readers are held to `tests/fixtures/door-observations.json`).
100
- *
101
- * A `python` call whose summary is `run <verb>` is a call of one published engineering method;
102
- * its result's stdout is the bounded observation `laplace_ope/door_tail.py` prints. The reader is
103
- * tolerant: the excerpt keeps a long stream's first and last lines around `[…]`, so every section
104
- * is optional and the last `RESULT:` line is the headline of last resort.
105
- */
106
- const DOOR_SUMMARY = /^run ([a-z][a-z0-9]*(?:_[a-z0-9]+)+)$/;
107
- const DOOR_HEAD = /^([a-z][a-z0-9_]*): ok\b/;
108
- const QUANTITY_LINE = /^ {2}(\S+) = (.*?)(?: {2}-- (.*))?$/;
109
- const SECTION_OPEN = /^(inputs \(as given\):|inputs the owner defaulted|not set \(|quantities:|validity:|warnings:|files:|RESULT:)/;
110
- const NUMBER = /^(-?(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?|true|false|nan|-?inf)(?: (.+))?$/;
111
-
112
- function quantityParts(text) {
113
- const trimmed = text.trim();
114
- if (trimmed.startsWith("[") || trimmed.startsWith("{")) return { value: trimmed, unit: "" };
115
- const number = NUMBER.exec(trimmed);
116
- return number ? { value: number[1], unit: (number[2] ?? "").trim() } : { value: trimmed, unit: "" };
117
- }
118
-
119
- /** `{verb, headline: [{id, label, value, unit}], warnings}` of an observation, or null. */
120
- export function doorObservation(text) {
121
- const lines = String(text ?? "").split("\n").map(line => line.replace(/\s+$/, ""));
122
- const head = DOOR_HEAD.exec(lines.find(line => line.trim()) ?? "");
123
- if (!head) return null;
124
- const cut = new Set();
125
- lines.forEach((line, index) => {
126
- if (line.trim() === "[…]") [index - 1, index, index + 1].forEach(n => cut.add(n));
127
- });
128
- const quantities = [];
129
- const warnings = [];
130
- let resultLine = "";
131
- let section = "";
132
- for (const [index, line] of lines.entries()) {
133
- if (index === 0 || cut.has(index)) continue;
134
- const open = SECTION_OPEN.exec(line);
135
- if (open) {
136
- section = open[1];
137
- if (section === "warnings:" && line.includes("none")) section = "";
138
- if (section === "RESULT:") resultLine = line.slice("RESULT:".length).trim();
139
- continue;
140
- }
141
- if (section === "quantities:") {
142
- const row = QUANTITY_LINE.exec(line);
143
- if (row) quantities.push({ id: row[1], label: row[3]?.trim() || row[1].replaceAll("_", " "), ...quantityParts(row[2]) });
144
- } else if (section === "warnings:" && /^ {2}- /.test(line)) {
145
- warnings.push(line.replace(/^ {2}- /, "").trim());
146
- }
147
- }
148
- const byId = new Map(quantities.map(quantity => [quantity.id, quantity]));
149
- const headline = [];
150
- for (const part of resultLine.split(/; (?=\S+ = )/)) {
151
- const row = /^(\S+) = (.*)$/.exec(part.trim());
152
- if (!row) continue;
153
- headline.push({ id: row[1], label: byId.get(row[1])?.label ?? row[1].replaceAll("_", " "), ...quantityParts(row[2]) });
154
- }
155
- // No parsable RESULT line: the last three physical quantities stand in (else the first three).
156
- if (!headline.length) headline.push(...quantities.filter(quantity => quantity.unit).slice(-3));
157
- if (!headline.length) headline.push(...quantities.slice(0, 3));
158
- return { verb: head[1], headline, warnings };
159
- }
160
-
161
- /** The door calls of each row, by `step_id`: `{purpose, verb, observation, refusal}` in call order. */
162
- function doorCallsByStep(events) {
163
- const results = new Map();
164
- for (const event of events) {
165
- if (event?.kind === "tool_result" && typeof event.payload?.call_id === "string") {
166
- results.set(event.payload.call_id, event.payload);
167
- }
168
- }
169
- const rows = new Map();
170
- for (const event of events) {
171
- const call = event?.kind === "tool_call" ? event.payload : null;
172
- const verb = call?.tool === "python" ? DOOR_SUMMARY.exec(String(call.summary ?? "").trim())?.[1] : null;
173
- if (!verb) continue;
174
- const result = results.get(call.call_id);
175
- const observation = result?.status === "ok" ? doorObservation(result.stdout_excerpt) : null;
176
- if (result?.status === "ok" && observation?.verb !== verb) continue; // free code that opened with `# run x_y`
177
- const refusal = result && result.status !== "ok"
178
- ? String(result.stderr_excerpt || result.stdout_excerpt || "").trim().split("\n").filter(Boolean).slice(-3).join(" · ") : "";
179
- const list = rows.get(call.step_id) ?? [];
180
- list.push({ purpose: String(call.title ?? "").trim(), verb, observation, refusal, running: !result });
181
- rows.set(call.step_id, list);
182
- }
183
- return rows;
184
- }
185
-
186
- function doorLine({ purpose, verb, observation, refusal, running }) {
187
- const said = observation
188
- ? observation.headline.map(quantity => `${quantity.label} ${quantity.value}${quantity.unit ? ` ${quantity.unit}` : ""}`).join(", ")
189
- : (refusal ? `refused: ${refusal}` : running ? "running" : "computed");
190
- const lines = [` ▸ ${plainLine(purpose || verb)} — ${verb}: ${plainLine(said)}`];
191
- for (const warning of (observation?.warnings ?? []).slice(0, 2)) lines.push(` ! ${plainLine(warning)}`);
192
- return lines.join("\n");
193
- }
194
-
195
- export function taskLines(events) {
196
- const doors = doorCallsByStep(events);
197
- // The conclusion is engineering work (it prints the answer from evidence); its text is the
198
- // synthesis, so the row stays one line.
199
- const concluded = new Set(events.filter((event) => event?.kind === "tool_call" && event.payload?.tool === "conclude")
200
- .map((event) => event.payload.step_id));
201
- // Only a run that called the door tells engineering rows from execution rows; any other run
202
- // prints exactly as before.
203
- const distinguishes = doors.size > 0 || concluded.size > 0;
204
- return events.flatMap((event) => {
205
- if (event?.kind !== "step_finished") return [];
206
- const row = event.payload;
207
- if (!row || typeof row !== "object" || typeof row.step_id !== "string") return [];
208
- const outcome = CAUSE_WORD[row.cause] ?? row.status;
209
- const result = typeof row.result_line === "string" && row.result_line.trim() ? row.result_line : "";
210
- if (distinguishes) {
211
- const calls = doors.get(row.step_id);
212
- if (calls?.length) {
213
- const rest = row.status === "computed" ? [] : [` (${plainLine(row.title)} — ${outcome})`];
214
- return [[...calls.map(doorLine), ...rest].join("\n")];
215
- }
216
- if (row.status === "asked" || concluded.has(row.step_id)) return [` ▸ ${plainLine(`${row.title} — ${outcome}`)}`];
217
- // Execution, compressed to one line: what ran, how it ended, what it printed.
218
- return [` · ${plainLine(`${row.title} — ${outcome}${result ? `: ${result}` : ""}`)}`];
219
- }
220
- const attempts = Number.isInteger(row.attempts) && row.attempts > 0
221
- ? ` · ${row.attempts} ${row.attempts === 1 ? "attempt" : "attempts"}` : "";
222
- const printed = result ? `\n ${plainLine(result)}` : "";
223
- return [` ${plainLine(`${row.title} — ${outcome}${attempts}`)}${printed}`];
224
- });
225
- }
226
-
227
- /**
228
- * SOURCES › ASSUMPTIONS, SPOKEN BY THIS DOOR TOO (RunWire v2 `input_rows`, CONTRACTS S1).
229
- *
230
- * One block per owner verb the turn's programs called, the LAST ledger event of the run
231
- * standing: what the customer stated (`your brief`), what the program assumed, what the
232
- * method's declared default was let stand, and how many arguments the program set from a
233
- * variable (no value the record can read). Rows print through `inputLines`, the same shape
234
- * as the legacy step inputs, so the origin words are the contract's.
235
- */
236
- export function assumptionLines(events) {
237
- const ledger = events.filter((event) => event?.kind === "input_rows").at(-1);
238
- const blocks = Array.isArray(ledger?.payload?.blocks) ? ledger.payload.blocks : [];
239
- return blocks.flatMap((block) => {
240
- if (!block || typeof block.verb !== "string") return [];
241
- const set = Number.isInteger(block.program_set) && block.program_set > 0
242
- ? ` · ${block.program_set} set by the program` : "";
243
- const rows = Array.isArray(block.rows) ? block.rows : [];
244
- return [` ${plainLine(block.verb)}${set}`, ...inputLines(rows)];
245
- });
246
- }
247
-
248
75
  export function shellQuote(value) {
249
76
  return `'${String(value).replaceAll("'", `'"'"'`)}'`;
250
77
  }
251
78
 
252
79
  export function safeArtifactName(artifact) {
253
- const leaf = artifact.filename.replaceAll("\\", "/").split("/").at(-1);
80
+ const leaf = artifact.path.replaceAll("\\", "/").split("/").at(-1);
254
81
  if (!leaf || leaf === "." || leaf === ".." || leaf.startsWith("-") || leaf.startsWith(".")) {
255
82
  return `artifact-${artifact.cas_ref.slice("sha256:".length, "sha256:".length + 12)}`;
256
83
  }
257
84
  return leaf;
258
85
  }
259
86
 
87
+ /** The closed turn: its state, its typed defect and its answer (the last `synthesis`). An unknown state is refused by name. */
260
88
  function terminalPresentation(value) {
261
- const terminalEvent = value.events.at(-1);
262
- if (terminalEvent?.kind !== "terminal") {
263
- throw new CliError("terminal_invalid", "Run record has no final terminal event");
264
- }
265
- const payload = terminalEvent.payload;
266
- const allowed = new Set([...TERMINAL_FIELDS, "terminal"]);
267
- if (Object.keys(payload).some(key => !allowed.has(key))) {
268
- throw new CliError("terminal_invalid", "Run terminal carries an undeclared field");
269
- }
270
- if (payload.state !== undefined && payload.terminal !== undefined
271
- && payload.state !== payload.terminal) {
272
- throw new CliError("terminal_mismatch", "Run terminal carries conflicting states");
273
- }
274
- const state = payload.state ?? payload.terminal;
275
- if (state !== value.terminal) {
276
- throw new CliError("terminal_mismatch", "Run terminal event disagrees with its record");
277
- }
278
- const syntheses = value.events.filter(event => event.kind === "synthesis").map(event => event.payload);
279
- const synthesis = syntheses.at(-1) ?? null;
280
- if (synthesis !== null && !validateSynthesis(synthesis)) {
281
- throw new CliError("synthesis_invalid", "Run carries malformed synthesis");
282
- }
283
- if (["ok", "partial"].includes(state)
284
- && (!synthesis || synthesis.terminal !== state)) {
285
- throw new CliError("synthesis_invalid", `Run terminal ${state} disagrees with its synthesis`);
286
- }
287
- if (payload.answer !== undefined
288
- && (!synthesis || payload.answer !== synthesis.answer)) {
289
- throw new CliError("synthesis_invalid", "Run terminal answer differs from its synthesis");
89
+ const last = value.events.at(-1);
90
+ if (last?.kind !== "terminal") throw new CliError("terminal_invalid", "Run record has no final terminal event");
91
+ const state = last.payload?.state;
92
+ if (!TERMINAL_STATES.includes(state)) {
93
+ throw new CliError("terminal_state_unknown", `Run ended in a state this CLI does not know (${plainLine(state).slice(0, 40)}); next: vecteur update`);
290
94
  }
95
+ if (state !== value.terminal) throw new CliError("terminal_mismatch", "Run terminal event disagrees with its record");
96
+ return { state, defect: last.payload.defect, answer: value.events.findLast(event => event.kind === "synthesis")?.payload.markdown };
97
+ }
291
98
 
292
- const defect = payload.defect;
293
- const recovery = payload.recovery;
294
- if (!["ok", "partial"].includes(state) && defect === undefined) {
295
- throw new CliError("recovery_invalid", `Run terminal ${state} carries no typed cause/recovery`);
296
- }
297
- if ((defect === undefined) !== (recovery === undefined)) {
298
- throw new CliError("recovery_invalid", "Run terminal cause and recovery must travel together");
299
- }
300
- if (defect !== undefined) {
301
- const declarations = TERMINAL_RECOVERY_DECLARATIONS[defect];
302
- if (!declarations || !Array.isArray(recovery) || recovery.length === 0) {
303
- throw new CliError("recovery_invalid", "Run terminal recovery is not owner-declared");
304
- }
305
- for (const action of recovery) {
306
- const fields = action && typeof action === "object" && !Array.isArray(action)
307
- ? Object.keys(action).sort().join(",") : "";
308
- const declaration = declarations.find(([capability]) => capability === action?.capability);
309
- const argumentsValue = action?.arguments;
310
- if (fields !== "arguments,capability" || !declaration || !argumentsValue
311
- || typeof argumentsValue !== "object" || Array.isArray(argumentsValue)
312
- || Object.keys(argumentsValue).sort().join(",") !== [...declaration[1]].sort().join(",")
313
- || Object.values(argumentsValue).some(item => !(
314
- (typeof item === "string" && item.length > 0)
315
- || (Number.isSafeInteger(item) && item > 0)
316
- ))) {
317
- throw new CliError("recovery_invalid", "Run terminal recovery action is malformed");
318
- }
319
- }
99
+ /** A template with every `{name}` filled, or null when one is not: a half-filled sentence is never printed. */
100
+ function fillWords(template, values) {
101
+ let missing = false;
102
+ const said = template.replace(/\{(\w+)\}/g, (_, name) => { if (values[name] === undefined) missing = true; return values[name] ?? ""; });
103
+ return missing ? null : said;
104
+ }
105
+
106
+ /** The stop card of a `budget` terminal. The wire carries no stop object: the words are the generic limit's
107
+ * (`stop-words.js`), and what this reader may do about it is the server's offer; without it no plan is named. */
108
+ function stopLines(value, terminal, offer, origin = "") {
109
+ const choice = MODEL_CHOICES.find(row => row.route_id === value.requested_route_id && row.route_id !== "auto");
110
+ const words = { model: choice?.label ?? "The model", price: PLAN_WORDS.pro_price };
111
+ const computed = value.events.some(event => event.kind === "tool_result" && event.payload.ok);
112
+ const result = terminal.answer ? STOP_WORDS.result.authored : computed ? STOP_WORDS.result.computed : STOP_WORDS.result.nothing;
113
+ const lines = [STOP_WORDS.heading.limit, `${fillWords(STOP_WORDS.reason.limit, words) ?? ""} ${result}`.trim()];
114
+ for (const id of offer?.actions ?? []) {
115
+ if (id === "upgrade_plan") lines.push(`${PLAN_WORDS.pro_action}: ${origin}${STOP_ACTION_HREFS.upgrade_plan}`,
116
+ ...[fillWords(STOP_WORDS.action_line.upgrade_plan, words)].filter(Boolean).map(line => ` ${line}`));
117
+ if (id === "contact_sales") lines.push(`${PLAN_WORDS.enterprise_action}: ${origin}${STOP_ACTION_HREFS.contact_sales}`, ` ${STOP_WORDS.action_line.contact_sales}`);
118
+ if (id === "continue_with_model" && offer.continuation) lines.push(`${fillWords(STOP_WORDS.continue_with, { model: offer.continuation.label })}: /model, then ask a follow-up`);
320
119
  }
321
- return { state, answer: payload.answer, defect, recovery: recovery ?? [] };
120
+ if (!offer || offer.actions.includes("see_usage")) lines.push(`${STOP_WORDS.see_usage}: ${origin}${STOP_ACTION_HREFS.see_usage}`, STOP_WORDS.usage_note);
121
+ return lines.map(plainLine);
322
122
  }
323
123
 
324
- function recoveryLine(action) {
325
- const args = Object.entries(action.arguments)
326
- .map(([name, value]) => `${name}=${JSON.stringify(value)}`).join(" ");
327
- return `Recovery: ${action.capability}${args ? ` ${args}` : ""}`;
124
+ /** The typed tail of a closed turn, shared by the terminal block and the transcript. */
125
+ export function terminalBlockLines(value) {
126
+ const terminal = terminalPresentation(value);
127
+ return [`Terminal: ${terminal.state}`, ...(terminal.defect ? [`Cause: ${plainLine(terminal.defect)}`] : [])];
328
128
  }
329
129
 
330
- export function currentTransferTables(events) {
331
- const candidates = new Map();
332
- const cleared = new Map();
333
- for (const event of events) {
334
- if (event.kind !== "engineering_projection") continue;
335
- const projection = event.payload;
336
- if (projection?.kind === "projection_clear" && projection.clear_kind === "transfer_table") {
337
- const ids = cleared.get(projection.node_id) ?? new Set();
338
- ids.add(projection.execution_id);
339
- cleared.set(projection.node_id, ids);
340
- } else if (projection?.kind === "transfer_table") {
341
- const rows = candidates.get(projection.node_id) ?? [];
342
- rows.push(projection);
343
- candidates.set(projection.node_id, rows);
344
- }
345
- }
346
- return [...candidates.entries()].flatMap(([node, rows]) => {
347
- const current = [...rows].reverse().find(row => !cleared.get(node)?.has(row.execution_id));
348
- return current ? [current] : [];
349
- });
130
+ /** The server owns amounts and coverage. This function never computes a currency value. */
131
+ export function turnFooter(run, cost) {
132
+ const seconds = run?.duration_seconds;
133
+ const duration = Number.isSafeInteger(seconds) && seconds >= 0 ? `${seconds}s` : "duration unavailable";
134
+ const amount = cost?.display?.scope_used ?? cost?.display?.used ?? "no exact amount available";
135
+ const coverage = cost?.coverage ? ` (${cost.coverage} coverage)` : "";
136
+ return plainLine(`✻ ${run?.terminal || "open"} · ${duration} · ${amount}${coverage} this UTC month · /usage`);
350
137
  }
351
138
 
352
139
  /** One projection of a Run record; plain text and the rich terminal both render these sections. */
353
- export function runSections(value, { projectId, currentTransferIds } = {}) {
140
+ export function runSections(value, { projectId, stopOffer, origin } = {}) {
354
141
  const terminal = value.terminal === "" ? null : terminalPresentation(value);
355
- const origins = value.events.flatMap(event => event.kind === "step_finished"
356
- ? inputLines(event.payload?.step?.inputs ?? event.payload?.inputs) : []);
357
- const artifacts = value.events.filter(event => event.kind === "artifact").map(event => event.payload);
358
- if (!artifacts.every(validateArtifact)) {
359
- throw new CliError("artifact_invalid", "Run carries malformed artifact metadata");
360
- }
361
142
  const project = projectId ? ` --project ${shellQuote(projectId)}` : "";
362
- const tables = currentTransferTables(value.events).filter(projection =>
363
- currentTransferIds?.has(projection.projection_id)).map(projection => {
364
- if (typeof projection.search_status !== "string" || projection.origin !== "unattributed"
365
- || typeof projection.validation_status !== "string" || typeof projection.withheld !== "boolean") {
366
- throw new CliError("projection_invalid", "Transfer table metadata is malformed");
367
- }
368
- return [`Transfer table: ${plainLine(projection.search_status)} · input origins ${projection.origin}`
369
- + ` · validation ${plainLine(projection.validation_status)}`
370
- + ` · path ${projection.withheld ? "withheld" : "shown"}`,
371
- ` vecteur projection get ${shellQuote(value.run_id)} ${shellQuote(projection.projection_id)}`
372
- + ` --output ${shellQuote("transfer-table.json")}${project}`];
373
- });
374
- const tail = [`Run: ${plainLine(value.run_id)}`];
375
- if (terminal) {
376
- tail.push(`Terminal: ${terminal.state}`);
377
- if (terminal.defect !== undefined) tail.push(`Cause: ${terminal.defect}`);
378
- tail.push(...terminal.recovery.map(recoveryLine));
143
+ const tail = [`Run: ${plainLine(value.run_id)}`, ...(terminal ? terminalBlockLines(value) : [])];
144
+ for (const event of value.events) {
145
+ if (event.kind === "review") tail.push(`Review: ${plainLine(event.payload.verdict)}`);
146
+ if (event.kind === "study") tail.push(`Study record: vecteur artifact get ${shellQuote(event.payload.cas_ref)}${project}`);
379
147
  }
380
- return { answer: terminal?.answer, state: terminal?.state ?? "", tasks: taskLines(value.events), origins,
381
- assumptions: assumptionLines(value.events), tables, artifacts: artifacts.map(artifact => ({ artifact,
382
- command: `vecteur artifact get ${shellQuote(artifact.cas_ref)} --output ${shellQuote(safeArtifactName(artifact))}${project}` })),
383
- tail };
148
+ return { blocks: runBlocks(value), state: terminal?.state ?? "", answer: terminal?.answer, duration_seconds: value.duration_seconds,
149
+ artifacts: artifactRows(runArtifacts(value.events)).map(row => ({ ...row,
150
+ command: `vecteur artifact get ${shellQuote(row.artifact.cas_ref)} --output ${shellQuote(safeArtifactName(row.artifact))}${project}` })),
151
+ tail, stop: terminal?.state === "budget" ? stopLines(value, terminal, stopOffer, origin) : [] };
152
+ }
153
+
154
+ export function humanRun(value, { projectId, cost, stopOffer, origin, shownKeys = new Set() } = {}) {
155
+ return humanRunSections(runSections(value, { projectId, stopOffer, origin }), { cost, shownKeys });
384
156
  }
385
157
 
386
- export function humanRun(value, { projectId, cost, currentTransferIds } = {}) {
387
- const run = runSections(value, { projectId, currentTransferIds });
158
+ /** A turn in plain text: the working trace (one line per tool call), the answer, the files, the terminal state and,
159
+ * at a limit, the stop card. Rows already printed live are not repeated. */
160
+ export function humanRunSections(run, { cost, shownKeys = new Set() } = {}) {
388
161
  const lines = [];
389
- if (run.answer !== undefined) lines.push(run.answer, "");
390
- if (run.tasks.length) lines.push("Steps:", ...run.tasks, "");
391
- if (run.origins.length) lines.push("Inputs and origins:", ...run.origins, "");
392
- if (run.assumptions.length) lines.push("Assumptions:", ...run.assumptions, "");
393
- for (const table of run.tables) lines.push(...table, "");
162
+ const trace = run.blocks.filter(block => block.kind !== "terminal" && !shownKeys.has(block.key));
163
+ if (trace.length) lines.push("Working:", ...trace.map(block => ` ${blockText(block)}`), "");
164
+ if (run.answer) lines.push(run.answer, "");
165
+ else if (run.state) lines.push("No answer was published for this Run.", "");
394
166
  if (run.artifacts.length) {
395
- lines.push("Artifacts:");
396
- for (const { artifact, command } of run.artifacts) {
397
- lines.push(` ${artifact.filename} (${artifact.kind}, ${artifact.id})`, ` ${command}`);
167
+ lines.push("Files:");
168
+ for (const { artifact, command, number, sameBytesAs } of run.artifacts) {
169
+ lines.push(` ${terminalText(artifact.path)} (${plainLine(artifact.kind)}, ${artifact.bytes} B) · /download ${number}${sameBytesAs ? ` · same bytes as ${sameBytesAs}` : ""}`, ` ${terminalText(command)}`);
398
170
  }
399
171
  lines.push("");
400
172
  }
401
173
  lines.push(...run.tail);
174
+ if (run.stop.length) lines.push("", ...run.stop);
402
175
  if (cost) lines.push("", humanCost(cost).trimEnd());
403
176
  return `${lines.join("\n")}\n`;
404
177
  }
@@ -429,21 +202,15 @@ export function human(value, options = {}) {
429
202
  return canonicalJson(value);
430
203
  }
431
204
 
205
+ /** One live line per event worth a line: a tool call as it starts, a failed result, a file as it lands. */
432
206
  export function progress(event) {
433
- if (event?.kind === "step_started") {
434
- const title = plainLine(event.payload?.title ?? "");
435
- return title.trim() ? `Starting: ${title}\n` : "Starting\n";
436
- }
437
- if (event?.kind === "artifact") {
438
- return `File ready: ${plainLine(event.payload.filename)}\n`;
439
- }
440
- if (event?.kind !== "step_finished") return "";
441
- const lines = inputLines(event?.payload?.step?.inputs ?? event?.payload?.inputs);
442
- const title = plainLine(event.payload?.step?.title ?? event.payload?.title ?? "");
443
- const head = title.trim() ? `Finished: ${title}\n` : "Finished\n";
444
- return lines.length ? `${head}${lines.join("\n")}\n` : head;
207
+ const payload = event?.payload;
208
+ if (event?.kind === "tool_call") return `${String(payload.tool).charAt(0).toUpperCase()}${String(payload.tool).slice(1)}: ${plainLine(payload.title)}\n`;
209
+ if (event?.kind === "tool_result" && !payload.ok) return ` failed: ${plainLine(payload.excerpt.split("\n").filter(line => line.trim()).at(-1) ?? "no output")}\n`;
210
+ if (event?.kind === "artifact") return `File ready: ${plainLine(payload.path)}\n`;
211
+ return "";
445
212
  }
446
213
 
447
- function plainLine(value) {
214
+ export function plainLine(value) {
448
215
  return String(value).replace(/[\u0000-\u001f\u007f-\u009f]+/g, " ");
449
216
  }
package/src/input.js CHANGED
@@ -5,7 +5,7 @@ const START = "\x1b[200~", END = "\x1b[201~";
5
5
  const MAX_BYTES = 256 * 1024;
6
6
  const graphemes = new Intl.Segmenter(undefined, { granularity: "grapheme" });
7
7
 
8
- /** Stream decoder shared by both terminal views; paste is always one edit, never a send. */
8
+ /** Stream decoder shared by both views; negotiated paste is one edit, never a send. */
9
9
  export class ComposerInput extends EventEmitter {
10
10
  constructor() {
11
11
  super(); this.text = ""; this.cursor = 0; this.pending = ""; this.pasting = false;
@@ -61,10 +61,14 @@ export class ComposerInput extends EventEmitter {
61
61
  this.checkpoint();
62
62
  this.text = value; this.cursor += text.length; this.emit("change", this.text);
63
63
  }
64
- feed(bytes) {
64
+ feed(bytes, { unbracketed = false } = {}) {
65
65
  clearTimeout(this.escapeTimer);
66
66
  const epoch = this.focusEpoch;
67
- this.pending += typeof bytes === "string" ? bytes : this.decoder.write(bytes);
67
+ let chunk = typeof bytes === "string" ? bytes : this.decoder.write(bytes);
68
+ // Unmarked multiline reads are drafts, including every trailing CR. A split read
69
+ // consisting only of CR/CRLF is indistinguishable from Enter without negotiation.
70
+ if (unbracketed) chunk = chunk === "\r\n" ? "\r" : chunk === "\r" ? chunk : chunk.replace(/\r\n?/g, "\n");
71
+ this.pending += chunk;
68
72
  while (this.pending) {
69
73
  if (this.pasting) {
70
74
  const end = this.pending.indexOf(END);