@vecteur/cli 0.9.1 → 0.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/blocks.js CHANGED
@@ -1,4 +1,4 @@
1
- import { humanRun, progress } from "./format.js";
1
+ import { humanRun, progress, plainLine, terminalText, taskLines, terminalBlockLines, engineeringCall, capabilityCall } from "./format.js";
2
2
 
3
3
  function elapsed(run, now) {
4
4
  if (!run) return null;
@@ -17,8 +17,10 @@ function elapsed(run, now) {
17
17
  /** RunWire owns the facts. Optional session cache projects only newly appended events. */
18
18
  export function runView(run, cache, now = Date.now()) {
19
19
  const events = run?.events ?? [];
20
- const same = cache && cache.run === run && cache.count <= events.length && cache.view;
21
- if (same && cache.count === events.length && cache.terminal === run?.terminal) return { ...cache.view, elapsed: elapsed(run, now) };
20
+ const same = cache && cache.run === run && cache.runId === run?.run_id && cache.events === events && cache.count <= events.length && cache.view;
21
+ if (same && cache.count === events.length && cache.terminal === run?.terminal) {
22
+ return { ...cache.view, blocks: [...cache.view.eventBlocks, ...controlBlocks(run, cache.view.eventBlocks.length)], elapsed: elapsed(run, now) };
23
+ }
22
24
  const view = same ? cache.view : {
23
25
  subject: run ? { kind: "vecteur_run", id: run.run_id } : null,
24
26
  answer: "", question: null, artifacts: [], steps: [], progress: "Waiting for Vecteur",
@@ -28,13 +30,206 @@ export function runView(run, cache, now = Date.now()) {
28
30
  const event = events[index];
29
31
  if (event.kind === "synthesis") view.answer = event.payload.answer ?? "";
30
32
  if (event.kind === "clarification") view.question = event.payload.state === "requested" ? event.payload : null;
31
- if (event.kind === "artifact") view.artifacts.push(event.payload);
32
33
  if (["step_started", "step_finished", "task"].includes(event.kind)) view.steps.push(event);
33
34
  const line = progress(event);
34
35
  if (line) view.progress = line.trim();
35
36
  }
36
37
  view.terminal = run?.terminal ?? "";
38
+ view.artifacts = runArtifacts(events);
39
+ view.eventBlocks = eventBlocks(run);
37
40
  view.transcript = run?.terminal ? humanRun(run) : "";
38
- if (cache) Object.assign(cache, { run, count: events.length, terminal: run?.terminal, view });
39
- return { ...view, elapsed: elapsed(run, now) };
41
+ if (cache) Object.assign(cache, { run, runId: run?.run_id, events, count: events.length, terminal: run?.terminal, view });
42
+ return { ...view, blocks: [...view.eventBlocks, ...controlBlocks(run, view.eventBlocks.length)], elapsed: elapsed(run, now) };
43
+ }
44
+
45
+
46
+ /** Current revision per logical path; content identity never removes a destination. */
47
+ export function runArtifacts(events = []) {
48
+ const rows = new Map();
49
+ for (const event of events) if (event.kind === "artifact") {
50
+ const artifact = event.payload;
51
+ const key = artifact.path ? `path:${artifact.path}` : `id:${artifact.id}`;
52
+ const prior = rows.get(key);
53
+ if (!prior || (artifact.revision ?? 0) >= (prior.revision ?? 0)) rows.set(key, artifact);
54
+ }
55
+ return [...rows.values()];
56
+ }
57
+
58
+ export function artifactRows(artifacts) {
59
+ const first = new Map();
60
+ return artifacts.map((artifact, index) => {
61
+ const number = index + 1, sameBytesAs = first.get(artifact.cas_ref) ?? null;
62
+ if (!sameBytesAs) first.set(artifact.cas_ref, number);
63
+ return { artifact, number, sameBytesAs };
64
+ });
65
+ }
66
+
67
+ const tuple = (run, step, call) => JSON.stringify([run, step ?? null, call ?? null]);
68
+ const sourceRead = call => call.tool === "sources" && /^(context_list$|extraction:)/.test(call.summary ?? "");
69
+
70
+ /** Pure, replay-safe projection. Only the complete event prefix may leave the live region.
71
+ * Controls have no event anchor: they follow in a separate section and stay live until terminal.
72
+ * Payloads are never decorated/mutated, so machine JSON remains the owner's exact record.
73
+ */
74
+ export function runBlocks(run) {
75
+ const blocks = eventBlocks(run);
76
+ return [...blocks, ...controlBlocks(run, blocks.length)];
77
+ }
78
+
79
+ function eventBlocks(run) {
80
+ if (!run) return [];
81
+ const events = [...(run.events ?? [])].sort((a, b) => a.seq - b.seq);
82
+ const terminal = events.find(event => event.kind === "terminal");
83
+ const calls = new Map(), byCall = new Map(), questions = new Map(), seen = new Set(), blocks = [];
84
+ let fold = null;
85
+ const closeFold = () => { if (fold) fold.closed = true; fold = null; };
86
+ for (const event of events) {
87
+ const payload = event.payload;
88
+ if (event.kind === "tool_call") {
89
+ const key = tuple(run.run_id, payload.step_id, payload.call_id);
90
+ if (calls.has(key)) continue; // a reconnect may replay a prefix
91
+ const call = { key, seq: event.seq, call: payload, result: null };
92
+ calls.set(key, call); byCall.set(payload.call_id, call);
93
+ if (sourceRead(payload)) {
94
+ if (!fold || fold.stepId !== payload.step_id) {
95
+ closeFold();
96
+ fold = { kind: "sources", key, seq: event.seq, stepId: payload.step_id, calls: [], closed: false };
97
+ blocks.push(fold);
98
+ }
99
+ fold.calls.push(call);
100
+ } else {
101
+ closeFold();
102
+ blocks.push({ kind: "tool", key, seq: event.seq, stepId: payload.step_id, calls: [call] });
103
+ }
104
+ } else if (event.kind === "tool_result") {
105
+ const call = byCall.get(payload.call_id);
106
+ if (call && !call.result) call.result = payload;
107
+ } else if (event.kind === "step_finished" || event.kind === "clarification") {
108
+ closeFold();
109
+ // Each clarification transition is immutable, with the original questions available on resolution.
110
+ if (event.kind === "clarification" && payload.state === "requested") questions.set(payload.id, payload);
111
+ const question = event.kind === "clarification" ? questions.get(payload.id) : null;
112
+ const key = tuple(run.run_id, payload.step_id ?? payload.id, `${event.kind}:${event.seq}`);
113
+ if (seen.has(key)) continue;
114
+ seen.add(key);
115
+ blocks.push({ kind: event.kind === "clarification" ? "clarification" : "step",
116
+ key, seq: event.seq, stepId: payload.step_id, payload, ...(question ? { question } : {}) });
117
+ } else if (event.kind === "terminal") {
118
+ closeFold();
119
+ blocks.push({ kind: "terminal", key: tuple(run.run_id, null, "terminal"), seq: event.seq,
120
+ state: payload.state ?? payload.terminal, lines: terminalBlockLines({ ...run, terminal: payload.state ?? payload.terminal }) });
121
+ }
122
+ }
123
+ let waiting = false, number = 0;
124
+ for (const block of blocks) {
125
+ const complete = !block.calls || block.calls.every(call => call.result || terminal)
126
+ && (block.kind !== "sources" || block.closed || terminal);
127
+ waiting ||= !complete;
128
+ block.committed = !waiting;
129
+ block.number = ++number;
130
+ }
131
+ return blocks;
132
+ }
133
+
134
+ function controlBlocks(run, number) {
135
+ return [...(run?.controls ?? [])].sort((a, b) => a.sequence - b.sequence).map(control => ({
136
+ kind: "control", key: tuple(run.run_id, null, `control:${control.id}`),
137
+ sequence: control.sequence, payload: control, committed: !!run.terminal, number: ++number,
138
+ }));
139
+ }
140
+
141
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
142
+ function sourceSummary(calls) {
143
+ const extracts = new Set(), files = new Set();
144
+ for (const { call, result } of calls) {
145
+ if (result?.status !== "ok" || result.files_changed?.length) return null;
146
+ let data;
147
+ try { data = JSON.parse(result.stdout_excerpt); } catch { return null; }
148
+ if (!data || typeof data !== "object" || Array.isArray(data)
149
+ || data.extracts !== undefined && !Array.isArray(data.extracts)) return null;
150
+ // Count extracts actually read, rather than those merely offered/selected by context_list.
151
+ for (const extract of data.extracts ?? []) {
152
+ const handle = extract?.source_handle;
153
+ if (typeof extract?.id !== "string" || typeof handle?.cas_ref !== "string"
154
+ || typeof handle?.acquisition_ref !== "string") return null;
155
+ extracts.add(extract.id);
156
+ files.add(JSON.stringify([handle.cas_ref, handle.acquisition_ref]));
157
+ }
158
+ if (call.summary !== "context_list" && !Array.isArray(data.extracts)) return null;
159
+ }
160
+ return extracts.size && files.size ? `Read ${plural(extracts.size, "extract")} from ${plural(files.size, "file")}` : null;
161
+ }
162
+
163
+ export function blockContent(block, { full = false } = {}) {
164
+ if (block.kind === "terminal") return { title: `Terminal: ${block.state}`, rows: block.lines, status: block.state };
165
+ if (block.kind === "step") {
166
+ const row = block.payload;
167
+ const rows = taskLines([{ kind: "step_finished", payload: row }]);
168
+ // The existing engineering wording may paraphrase a cause; keep the typed facts too.
169
+ if (row.cause) rows.push(`${plainLine(row.status)} · Cause: ${plainLine(row.cause)}`);
170
+ return { title: "Step", status: row.status, rows };
171
+ }
172
+ if (block.kind === "control") {
173
+ const c = block.payload;
174
+ return { title: c.kind === "answer_now" ? "Answer now" : "Steer", status: c.state,
175
+ rows: [c.state, ...(c.text ? [c.text] : [])] };
176
+ }
177
+ if (block.kind === "clarification") {
178
+ const q = block.payload, source = block.question ?? q;
179
+ const rows = [q.state];
180
+ for (const question of source.questions ?? []) {
181
+ rows.push(question.question);
182
+ for (const choice of question.options ?? []) rows.push(`${choice.id ?? choice.value ?? ""} ${choice.label ?? choice}`);
183
+ }
184
+ if (q.answers) rows.push(`Answers: ${JSON.stringify(q.answers)}`);
185
+ return { title: "Clarification", status: q.state, rows };
186
+ }
187
+ const { call } = block.calls[0];
188
+ const engineering = !!engineeringCall(call, block.calls[0].result);
189
+ const capability = capabilityCall(call);
190
+ const tool = call.tool === "local_exec" ? "Bash" : engineering ? "Run" : call.tool === "python" ? "Python" : call.tool === "sources" ? "Sources"
191
+ : capability ? `${capability.label} ${capability.name}` : call.tool;
192
+ const status = block.calls.some(item => !item.result) ? block.committed ? "no result recorded" : "running"
193
+ : block.calls.find(item => item.result.status !== "ok")?.result.status ?? "ok";
194
+ const rows = [], preview = [];
195
+ const previewTail = status !== "ok";
196
+ const folded = block.kind === "sources" ? sourceSummary(block.calls) : null;
197
+ if (folded && !full) return { tool, title: call.tool === "local_exec" ? `${call.summary} · this computer` : call.title ?? "", status, rows: [`${folded} · ok`], preview: [] };
198
+ if (folded) rows.push(folded);
199
+ for (const item of block.calls) {
200
+ const c = item.call, r = item.result;
201
+ const state = r?.status ?? (block.committed ? "no result recorded" : "running");
202
+ const exit = r?.exit_code !== undefined && r.exit_code !== null ? ` · exit ${r.exit_code}` : "";
203
+ const seconds = r?.seconds !== undefined && r.seconds !== null ? ` · ${r.seconds}s` : "";
204
+ if (engineering && (r || !block.committed)) rows.push(...taskLines([
205
+ { kind: "tool_call", payload: c }, ...(r ? [{ kind: "tool_result", payload: r }] : []),
206
+ { kind: "step_finished", payload: { step_id: c.step_id, title: c.title, status: "computed" } },
207
+ ]));
208
+ rows.push(`${state}${exit}${seconds}`);
209
+ for (const file of r?.files_changed ?? []) rows.push(`wrote ${file.path} (${file.bytes} B)`);
210
+ if (r?.status === "denied" && r.stderr_excerpt) rows.push(r.stderr_excerpt);
211
+ if (full) {
212
+ rows.push(`Call: ${c.call_id}`, `Title: ${c.title ?? ""}`, `Summary: ${c.summary ?? ""}`);
213
+ if (r?.stdout_ref) rows.push(`stdout_ref: ${r.stdout_ref}`);
214
+ if (r) rows.push(`stdout excerpt:\n${r.stdout_excerpt || "(empty)"}`, `stderr excerpt:\n${r.stderr_excerpt || "(empty)"}`);
215
+ } else if (!folded && !engineering) {
216
+ // A failed call often carries its only explanation on stderr.
217
+ const text = (r?.status === "ok" ? r.stdout_excerpt : r?.stderr_excerpt || r?.stdout_excerpt) ?? "";
218
+ if (text) preview.push(...terminalText(text).split("\n").filter(line => line.trim()));
219
+ }
220
+ }
221
+ return { tool, title: call.tool === "local_exec" ? `${call.summary} · this computer` : call.title ?? "", status, rows, preview, previewTail, excerpt: preview.length > 0 };
222
+ }
223
+
224
+ /** Human text for plain/dumb and /details, never JSON or terminal escape sequences. */
225
+ export function blockText(block, options = {}) {
226
+ const content = blockContent(block, options);
227
+ const head = `[${content.status ?? ""}] ${content.tool ? content.tool + " " : ""}${content.title}`;
228
+ const rows = content.rows.map(terminalText);
229
+ const preview = content.preview ?? [];
230
+ if (preview.length) {
231
+ rows.push(...(content.previewTail ? preview.slice(-3) : preview.slice(0, 3)));
232
+ rows.push(preview.length > 3 ? "… output excerpt truncated · ctrl+o for the full block" : "output excerpt · ctrl+o for the full block");
233
+ }
234
+ return `${plainLine(head)}${rows.length ? ": " + rows.join("\n ") : ""}`;
40
235
  }