@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/README.md +216 -24
- package/bin/vecteur.js +72 -46
- package/package.json +5 -1
- package/src/blocks.js +88 -20
- package/src/client.js +192 -167
- package/src/commands.js +26 -22
- package/src/contract.js +25 -38
- package/src/credentials.js +8 -0
- package/src/download.js +2 -7
- package/src/errors.js +4 -1
- package/src/exchange.js +86 -0
- package/src/folders.js +28 -2
- package/src/format.js +109 -342
- package/src/input.js +7 -3
- package/src/localfiles.js +766 -0
- package/src/markdown.js +41 -68
- package/src/mcp.js +139 -50
- package/src/session.js +464 -185
- package/src/stop-words.js +19 -0
- package/src/terminal.js +52 -37
- package/src/tui/view.js +108 -72
- package/src/wire.js +73 -0
package/src/blocks.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { progress, plainLine, terminalText, terminalBlockLines } from "./format.js";
|
|
2
|
+
import { EVENT_KINDS } from "./contract.js";
|
|
2
3
|
|
|
3
4
|
function elapsed(run, now) {
|
|
4
5
|
if (!run) return null;
|
|
@@ -14,27 +15,94 @@ function elapsed(run, now) {
|
|
|
14
15
|
+ `${pad(Math.floor(seconds / 60) % 60)}:${pad(seconds % 60)}`;
|
|
15
16
|
}
|
|
16
17
|
|
|
17
|
-
/**
|
|
18
|
-
export function runView(run,
|
|
18
|
+
/** The wire owns the facts; this is the turn as a reader sees it. */
|
|
19
|
+
export function runView(run, now = Date.now()) {
|
|
19
20
|
const events = run?.events ?? [];
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
21
|
+
let progressLine = "Waiting for Vecteur";
|
|
22
|
+
for (const event of events) { const line = progress(event); if (line) progressLine = line.trim(); }
|
|
23
|
+
return {
|
|
23
24
|
subject: run ? { kind: "vecteur_run", id: run.run_id } : null,
|
|
24
|
-
answer:
|
|
25
|
-
|
|
25
|
+
answer: events.findLast(event => event.kind === "synthesis")?.payload.markdown ?? "",
|
|
26
|
+
artifacts: runArtifacts(events), progress: progressLine, terminal: run?.terminal ?? "",
|
|
27
|
+
blocks: runBlocks(run), elapsed: elapsed(run, now),
|
|
26
28
|
};
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
const
|
|
34
|
-
if (
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Current revision per path. */
|
|
32
|
+
export function runArtifacts(events = []) {
|
|
33
|
+
const rows = new Map();
|
|
34
|
+
for (const event of events) if (event.kind === "artifact") {
|
|
35
|
+
const prior = rows.get(event.payload.path);
|
|
36
|
+
if (!prior || event.payload.revision >= prior.revision) rows.set(event.payload.path, event.payload);
|
|
37
|
+
}
|
|
38
|
+
return [...rows.values()];
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function artifactRows(artifacts) {
|
|
42
|
+
const first = new Map();
|
|
43
|
+
return artifacts.map((artifact, index) => {
|
|
44
|
+
const number = index + 1, sameBytesAs = first.get(artifact.cas_ref) ?? null;
|
|
45
|
+
if (!sameBytesAs) first.set(artifact.cas_ref, number);
|
|
46
|
+
return { artifact, number, sameBytesAs };
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Pure, replay-safe projection: one block per tool call (with its result once it arrived), one for the terminal,
|
|
51
|
+
* and one for any event kind this build does not know. A block is committed once nothing before it is still running. */
|
|
52
|
+
export function runBlocks(run) {
|
|
53
|
+
if (!run) return [];
|
|
54
|
+
const events = [...(run.events ?? [])].sort((a, b) => a.seq - b.seq);
|
|
55
|
+
const closed = events.some(event => event.kind === "terminal");
|
|
56
|
+
const byCall = new Map(), blocks = [];
|
|
57
|
+
for (const event of events) {
|
|
58
|
+
const payload = event.payload;
|
|
59
|
+
if (event.kind === "tool_call") {
|
|
60
|
+
if (byCall.has(payload.call_id)) continue; // a reconnect may replay a prefix
|
|
61
|
+
const block = { kind: "tool", key: `${run.run_id}:${payload.call_id}`, seq: event.seq, call: payload, result: null };
|
|
62
|
+
byCall.set(payload.call_id, block); blocks.push(block);
|
|
63
|
+
} else if (event.kind === "tool_result") {
|
|
64
|
+
const block = byCall.get(payload.call_id);
|
|
65
|
+
if (block && !block.result) block.result = payload;
|
|
66
|
+
} else if (event.kind === "terminal") {
|
|
67
|
+
blocks.push({ kind: "terminal", key: `${run.run_id}:terminal`, seq: event.seq, state: payload.state,
|
|
68
|
+
lines: terminalBlockLines({ ...run, terminal: payload.state }) });
|
|
69
|
+
} else if (!EVENT_KINDS.includes(event.kind)) {
|
|
70
|
+
blocks.push({ kind: "unknown", key: `${run.run_id}:unknown:${event.seq}`, seq: event.seq, eventKind: String(event.kind) });
|
|
71
|
+
}
|
|
35
72
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
73
|
+
let waiting = false, number = 0;
|
|
74
|
+
for (const block of blocks) {
|
|
75
|
+
waiting ||= block.kind === "tool" && !block.result && !closed;
|
|
76
|
+
block.committed = !waiting;
|
|
77
|
+
block.number = ++number;
|
|
78
|
+
}
|
|
79
|
+
return blocks;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const TOOL_LABEL = tool => String(tool).charAt(0).toUpperCase() + String(tool).slice(1);
|
|
83
|
+
|
|
84
|
+
/** `{tool, title, status, rows}`; `full` adds the call's input and the result excerpt. */
|
|
85
|
+
export function blockContent(block, { full = false } = {}) {
|
|
86
|
+
if (block.kind === "terminal") return { title: `Terminal: ${block.state}`, rows: block.lines, status: block.state };
|
|
87
|
+
if (block.kind === "unknown") return { title: `Unknown event kind: ${block.eventKind}`, rows: ["This CLI cannot read it; next: vecteur update"], status: "unknown" };
|
|
88
|
+
const { call, result } = block;
|
|
89
|
+
const status = result ? (result.ok ? "ok" : "failed") : block.committed ? "no result recorded" : "running";
|
|
90
|
+
const rows = [];
|
|
91
|
+
if (full) {
|
|
92
|
+
rows.push(`Call: ${call.call_id}`, `Input: ${JSON.stringify(call.input)}`);
|
|
93
|
+
if (result) rows.push(`${status} · ${result.bytes} B`, `Output excerpt:\n${result.excerpt || "(empty)"}`);
|
|
94
|
+
} else if (result && !result.ok) {
|
|
95
|
+
// A failed call's last line is usually its cause.
|
|
96
|
+
const cause = result.excerpt.split("\n").filter(line => line.trim()).at(-1);
|
|
97
|
+
if (cause) rows.push(cause);
|
|
98
|
+
}
|
|
99
|
+
return { tool: TOOL_LABEL(call.tool), title: call.title, status, rows };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Human text for plain/dumb and /details: one line per call, never JSON or terminal escape sequences. */
|
|
103
|
+
export function blockText(block, options = {}) {
|
|
104
|
+
const content = blockContent(block, options);
|
|
105
|
+
const head = `[${content.status}] ${content.tool ? content.tool + " " : ""}${content.title}`;
|
|
106
|
+
const rows = content.rows.map(terminalText);
|
|
107
|
+
return `${plainLine(head)}${rows.length ? ": " + rows.join("\n ") : ""}`;
|
|
40
108
|
}
|
package/src/client.js
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
|
+
import { withAdmissionLock, admissionIntent, admissionResolved, unresolvedAdmissions, selectInvocationFiles } from "./localfiles.js";
|
|
1
2
|
import { createHash, randomUUID } from "node:crypto";
|
|
3
|
+
import { closeSync, fsyncSync, linkSync, openSync, unlinkSync } from "node:fs";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
2
5
|
|
|
3
6
|
import {
|
|
4
|
-
ARTIFACT_MEDIA_TYPES,
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
7
|
+
ARTIFACT_MEDIA_TYPES, OWNER_CONTRACT_IDENTITY, RECOVERY_ACTIONS, STORED_WIRE_VERSIONS, STORED_WIRE_VERSION_HEADER,
|
|
8
|
+
WIRE_READER_HEADER, WIRE_READER_VERSION, validateAccount, validateCliRelease, validateCustomerCostProjection,
|
|
9
|
+
validateDeviceAuthorization, validateLimitDenial, validatePatCreated, validateProject, validateQuotaDenial,
|
|
10
|
+
validateRunAck, validateRunStopOffer, validateSource, validateSourceOffer,
|
|
8
11
|
} from "./contract.js";
|
|
9
|
-
import {
|
|
12
|
+
import { FIRST_EVENT_SEQ, isStateHash, validateEvent, validateRun } from "./wire.js";
|
|
13
|
+
import { credentialsPath, readCredentials } from "./credentials.js";
|
|
14
|
+
import { readStore, writeStore } from "./store.js";
|
|
10
15
|
import { CliError } from "./errors.js";
|
|
11
16
|
import { canonicalJson } from "./format.js";
|
|
12
17
|
|
|
13
18
|
// Re-exported so every existing importer keeps its one import site; `errors.js` owns the type.
|
|
14
|
-
export { CliError };
|
|
19
|
+
export { CliError, isStateHash, validateEvent };
|
|
15
20
|
|
|
16
21
|
const DEFAULT_TIMEOUT_MS = 120_000;
|
|
17
22
|
export const DEFAULT_ORIGIN = "https://vecteur.space";
|
|
@@ -22,14 +27,11 @@ const RESPONSE_ACTIVITY = Symbol("response-activity");
|
|
|
22
27
|
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
23
28
|
const MAX_FRAME_BYTES = 1024 * 1024;
|
|
24
29
|
const MAX_EVENTS = 10_000;
|
|
30
|
+
/** Refusals that are final for a submission (nothing was admitted, nothing will be) and carry the owner's sentence. */
|
|
31
|
+
export const OWNER_WORDED = Object.freeze(["not_supported", "project_read_only"]);
|
|
25
32
|
const CAS_REF_SHAPE = /^sha256:([0-9a-f]{64})$/;
|
|
26
|
-
const STATE_HASH_SHAPE = /^[0-9a-f]{64}$/;
|
|
27
33
|
|
|
28
|
-
|
|
29
|
-
/** The one shape of a design head, so `--parent` and the head read cannot disagree. */
|
|
30
|
-
export function isStateHash(value) {
|
|
31
|
-
return typeof value === "string" && STATE_HASH_SHAPE.test(value);
|
|
32
|
-
}
|
|
34
|
+
export const isRequestKey = value => typeof value === "string" && /^[A-Za-z0-9_-]{8,64}$/.test(value);
|
|
33
35
|
|
|
34
36
|
/**
|
|
35
37
|
* A failure after the acknowledgement names the admitted Run, which may still be running:
|
|
@@ -39,10 +41,10 @@ export function admittedFailure(error, runId) {
|
|
|
39
41
|
if (!(error instanceof CliError)) return error;
|
|
40
42
|
if (error.code === "pat_expired") {
|
|
41
43
|
return new CliError("pat_expired",
|
|
42
|
-
`credential expired after Run ${runId} was admitted; next: vecteur login; then: vecteur run get ${runId}
|
|
44
|
+
`credential expired after Run ${runId} was admitted; next: vecteur login; then: vecteur run get ${runId}`, { run_id: runId });
|
|
43
45
|
}
|
|
44
46
|
return new CliError(error.code,
|
|
45
|
-
`Run ${runId} was admitted and may still be running; next: vecteur run get ${runId}
|
|
47
|
+
`Run ${runId} was admitted and may still be running; next: vecteur run get ${runId}`, { run_id: runId });
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
export function redact(value) {
|
|
@@ -187,56 +189,39 @@ export async function waitForDeviceAuthorization(client, grant, { sleep = delay,
|
|
|
187
189
|
}
|
|
188
190
|
}
|
|
189
191
|
|
|
190
|
-
function exactObject(value, fields, code) {
|
|
191
|
-
if (!value || typeof value !== "object" || Array.isArray(value) ||
|
|
192
|
-
Object.keys(value).sort().join("\n") !== [...fields].sort().join("\n")) {
|
|
193
|
-
throw new CliError(code, "Server returned malformed owner data");
|
|
194
|
-
}
|
|
195
|
-
return value;
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
export function validateEvent(value, runId, expectedSeq) {
|
|
199
|
-
exactObject(value, ["run_id", "seq", "kind", "payload"], "event_invalid");
|
|
200
|
-
if (value.run_id !== runId || !Number.isInteger(value.seq) || value.seq !== expectedSeq ||
|
|
201
|
-
!(EVENT_KINDS.includes(value.kind) || RETIRED_EVENT_KINDS.includes(value.kind)) ||
|
|
202
|
-
!value.payload || typeof value.payload !== "object" ||
|
|
203
|
-
Array.isArray(value.payload)) {
|
|
204
|
-
throw new CliError("event_sequence_invalid", `Expected event sequence ${expectedSeq}`);
|
|
205
|
-
}
|
|
206
|
-
if (value.payload.evidence_dag !== undefined) {
|
|
207
|
-
validateEvidenceDag(value.payload.evidence_dag, runId);
|
|
208
|
-
}
|
|
209
|
-
return value;
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
function evidenceReplayInvalid(message) {
|
|
213
|
-
throw new CliError("evidence_replay_invalid", `EvidenceDAG ${message}`);
|
|
214
|
-
}
|
|
215
|
-
|
|
216
192
|
function exactKeys(value, keys) {
|
|
217
193
|
return value && typeof value === "object" && !Array.isArray(value)
|
|
218
194
|
&& Object.keys(value).sort().join("\n") === [...keys].sort().join("\n");
|
|
219
195
|
}
|
|
220
196
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
197
|
+
/**
|
|
198
|
+
* The material a submit selects: the composer's exact shape (one exact-extract selection per
|
|
199
|
+
* attached source, both lists in source order). Absent keeps the Project's carried sources.
|
|
200
|
+
*/
|
|
201
|
+
export function submissionMaterial(selections) {
|
|
202
|
+
if (selections === undefined) return { attachments: [] };
|
|
203
|
+
const key = (s) => `${s.source_handle.cas_ref}\n${s.source_handle.acquisition_ref}`;
|
|
204
|
+
if (!Array.isArray(selections) || selections.length === 0 || !selections.every(s =>
|
|
205
|
+
exactKeys(s, ["source_handle", "offer_id", "selected_extract_ids", "method"])
|
|
206
|
+
&& exactKeys(s.source_handle, ["cas_ref", "acquisition_ref"])
|
|
207
|
+
&& /^sha256:[0-9a-f]{64}$/.test(s.source_handle.cas_ref) && typeof s.source_handle.acquisition_ref === "string"
|
|
208
|
+
&& s.source_handle.acquisition_ref.length > 0 && typeof s.offer_id === "string" && s.offer_id.length > 0
|
|
209
|
+
&& Array.isArray(s.selected_extract_ids) && s.selected_extract_ids.length > 0
|
|
210
|
+
&& s.selected_extract_ids.every(id => typeof id === "string" && id.length > 0)
|
|
211
|
+
&& new Set(s.selected_extract_ids).size === s.selected_extract_ids.length
|
|
212
|
+
&& s.method === "exact-extract") || new Set(selections.map(key)).size !== selections.length) {
|
|
213
|
+
throw new CliError("selection_invalid",
|
|
214
|
+
"Each selection is {source_handle, offer_id, selected_extract_ids, method: exact-extract}, one per source");
|
|
215
|
+
}
|
|
216
|
+
const sorted = [...selections].sort((a, b) => key(a).localeCompare(key(b))).map(s => ({
|
|
217
|
+
source_handle: { cas_ref: s.source_handle.cas_ref, acquisition_ref: s.source_handle.acquisition_ref },
|
|
218
|
+
offer_id: s.offer_id, selected_extract_ids: [...s.selected_extract_ids].sort(), method: s.method,
|
|
219
|
+
}));
|
|
220
|
+
return { attachments: sorted.map(s => ({ ...s.source_handle })), selections: sorted };
|
|
236
221
|
}
|
|
237
222
|
|
|
238
|
-
export async function parseSse(response, runId, onEvent = null, startSeq =
|
|
239
|
-
if (!Number.isSafeInteger(startSeq) || startSeq <
|
|
223
|
+
export async function parseSse(response, runId, onEvent = null, startSeq = FIRST_EVENT_SEQ) {
|
|
224
|
+
if (!Number.isSafeInteger(startSeq) || startSeq < FIRST_EVENT_SEQ || startSeq >= FIRST_EVENT_SEQ + MAX_EVENTS) {
|
|
240
225
|
throw new CliError("cursor_invalid", "Event cursor is outside the supported history bound");
|
|
241
226
|
}
|
|
242
227
|
if (!response.body) throw new CliError("sse_invalid", "Event response has no body");
|
|
@@ -292,7 +277,7 @@ export async function parseSse(response, runId, onEvent = null, startSeq = 0) {
|
|
|
292
277
|
}
|
|
293
278
|
events.push(validateEvent(refuseSecretValue(value), runId, startSeq + events.length));
|
|
294
279
|
await onEvent?.(events.at(-1));
|
|
295
|
-
if (
|
|
280
|
+
if (events.length + startSeq - FIRST_EVENT_SEQ > MAX_EVENTS) throw new CliError("response_too_large", "Event count exceeds limit");
|
|
296
281
|
terminalSeen = events.at(-1).kind === "terminal";
|
|
297
282
|
}
|
|
298
283
|
if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
|
|
@@ -360,6 +345,8 @@ export class VecteurClient {
|
|
|
360
345
|
...(accept ? { Accept: accept } : {}),
|
|
361
346
|
...(acceptEncoding ? { "Accept-Encoding": acceptEncoding } : {}),
|
|
362
347
|
...(lastEventId === undefined ? {} : { "Last-Event-ID": String(lastEventId) }),
|
|
348
|
+
// This reader advertises the highest stored wire version the owner declares.
|
|
349
|
+
...(!anonymousReadiness ? { [WIRE_READER_HEADER]: String(WIRE_READER_VERSION) } : {}),
|
|
363
350
|
},
|
|
364
351
|
body: rawBody ?? (body === undefined ? undefined : JSON.stringify(body)),
|
|
365
352
|
});
|
|
@@ -425,12 +412,20 @@ export class VecteurClient {
|
|
|
425
412
|
const reset = new Date(limit.reset_at * 1000).toISOString().replace(".000Z", "Z");
|
|
426
413
|
ownerMessage = `Customer cost limit reached; binding=${binding}; reset=${reset} UTC; next=${limit.recovery.join(",")}`;
|
|
427
414
|
}
|
|
415
|
+
if (candidate === "wire_version_unsupported") {
|
|
416
|
+
ownerMessage = "this Run is stored in a wire version this CLI cannot read; next: vecteur update";
|
|
417
|
+
}
|
|
428
418
|
if (["pat_expired", "pat_invalid", "pat_revoked"].includes(candidate)) {
|
|
429
419
|
ownerMessage = "credential is expired or revoked; next: vecteur login";
|
|
430
420
|
}
|
|
431
421
|
if (candidate === "pat_ancestry_inactive") {
|
|
432
422
|
ownerMessage = "seat or Organization is inactive; next: contact your Organization owner or Vecteur support";
|
|
433
423
|
}
|
|
424
|
+
// The owner's own sentence for a door this product no longer has and for a read-only (v5) Project.
|
|
425
|
+
if (OWNER_WORDED.includes(candidate) && typeof error.message === "string" && error.message.length > 0
|
|
426
|
+
&& error.message.length <= 512 && !/[\r\n\0]/.test(error.message)) {
|
|
427
|
+
ownerMessage = error.message;
|
|
428
|
+
}
|
|
434
429
|
if (
|
|
435
430
|
candidate === "client_outdated"
|
|
436
431
|
&& Object.keys(error).sort().join("\n") === "code\nmessage"
|
|
@@ -453,6 +448,7 @@ export class VecteurClient {
|
|
|
453
448
|
code,
|
|
454
449
|
ownerMessage || `Public API refused request with HTTP ${response.status}`,
|
|
455
450
|
);
|
|
451
|
+
failure.status = response.status;
|
|
456
452
|
if (admission) failure.admission = admission;
|
|
457
453
|
throw failure;
|
|
458
454
|
}
|
|
@@ -548,19 +544,6 @@ export class VecteurClient {
|
|
|
548
544
|
return value;
|
|
549
545
|
}
|
|
550
546
|
|
|
551
|
-
async runControl(runId, control, signal = undefined) {
|
|
552
|
-
const value = await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/controls`, { body: control, signal });
|
|
553
|
-
if (!validateRunControl(value) || value.id !== control.id) throw new CliError("control_invalid", "Malformed control acknowledgement");
|
|
554
|
-
return value;
|
|
555
|
-
}
|
|
556
|
-
|
|
557
|
-
async clarificationAnswer(runId, questionId, answers, signal = undefined) {
|
|
558
|
-
const value = await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/clarifications/${encodeURIComponent(questionId)}/answer`,
|
|
559
|
-
{ body: { answers }, signal });
|
|
560
|
-
if (!validateRunAck(value) || value.run_id !== runId) throw new CliError("run_ack_invalid", "Malformed answer acknowledgement");
|
|
561
|
-
return value;
|
|
562
|
-
}
|
|
563
|
-
|
|
564
547
|
async inputAdd(projectId, bytes, contentType, signal = undefined) {
|
|
565
548
|
const value = await this.#json("POST", `/api/projects/${encodeURIComponent(projectId)}/inputs`, {
|
|
566
549
|
rawBody: bytes, contentType, signal,
|
|
@@ -668,56 +651,7 @@ export class VecteurClient {
|
|
|
668
651
|
throw new CliError("request_failed",
|
|
669
652
|
`origin ${this.config.origin}; cause=artifact_transport; next: check the network and retry`);
|
|
670
653
|
} finally {
|
|
671
|
-
response
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
async projectionGet(projectId, runId, projection, onChunk, signal = undefined) {
|
|
676
|
-
const ref = projection?.payload_ref;
|
|
677
|
-
if (typeof projectId !== "string" || !projectId || typeof runId !== "string" || !runId
|
|
678
|
-
|| projection?.kind !== "transfer_table" || projection?.run_id !== runId
|
|
679
|
-
|| projection?.project_id !== projectId
|
|
680
|
-
|| !/^projection-[0-9a-f]{64}$/.test(projection?.projection_id ?? "")
|
|
681
|
-
|| ref?.schema !== "vecteur.owner-transfer-table.v1"
|
|
682
|
-
|| ref?.media_type !== "application/vnd.vecteur.owner-transfer-table+json"
|
|
683
|
-
|| !/^[0-9a-f]{64}$/.test(ref?.payload_sha256 ?? "")
|
|
684
|
-
|| typeof onChunk !== "function") {
|
|
685
|
-
throw new CliError("projection_invalid", "projection get requires a sealed transfer table on this Run");
|
|
686
|
-
}
|
|
687
|
-
const route = `/api/projects/${encodeURIComponent(projectId)}/runs/${encodeURIComponent(runId)}`
|
|
688
|
-
+ `/projections/${encodeURIComponent(projection.projection_id)}/payload`;
|
|
689
|
-
const response = await this.request("GET", route, {
|
|
690
|
-
accept: ref.media_type, acceptEncoding: "identity", signal,
|
|
691
|
-
});
|
|
692
|
-
try {
|
|
693
|
-
if (response.headers.get("content-type")?.split(";", 1)[0] !== ref.media_type
|
|
694
|
-
|| (response.headers.get("content-encoding") ?? "identity").toLowerCase() !== "identity") {
|
|
695
|
-
throw new CliError("projection_invalid", "Server returned the wrong projection media type");
|
|
696
|
-
}
|
|
697
|
-
const disposition = response.headers.get("x-vecteur-projection-disposition");
|
|
698
|
-
if (disposition !== "current" && disposition !== "historical") {
|
|
699
|
-
throw new CliError("projection_invalid", "Server returned no valid projection disposition");
|
|
700
|
-
}
|
|
701
|
-
const declared = response.headers.get("content-length");
|
|
702
|
-
if (declared === null || !/^(?:0|[1-9][0-9]*)$/.test(declared)
|
|
703
|
-
|| Number(declared) > 256 * 1024 || !response.body) {
|
|
704
|
-
throw new CliError("projection_invalid", "Projection byte length is invalid");
|
|
705
|
-
}
|
|
706
|
-
const digest = createHash("sha256");
|
|
707
|
-
let bytes = 0;
|
|
708
|
-
for await (const chunk of response.body) {
|
|
709
|
-
response[RESPONSE_ACTIVITY]?.();
|
|
710
|
-
bytes += chunk.byteLength;
|
|
711
|
-
if (bytes > Number(declared)) throw new CliError("projection_invalid", "Projection exceeds its declared size");
|
|
712
|
-
digest.update(chunk);
|
|
713
|
-
await onChunk(chunk);
|
|
714
|
-
}
|
|
715
|
-
if (bytes !== Number(declared) || digest.digest("hex") !== ref.payload_sha256) {
|
|
716
|
-
throw new CliError("projection_invalid", "Projection bytes differ from RunWire");
|
|
717
|
-
}
|
|
718
|
-
return { projection_id: projection.projection_id, project_id: projectId,
|
|
719
|
-
run_id: runId, content_type: ref.media_type, bytes, disposition };
|
|
720
|
-
} finally {
|
|
654
|
+
if (response.body && !response.body.locked) await response.body.cancel().catch(() => {});
|
|
721
655
|
response[RELEASE_TIMEOUT]?.();
|
|
722
656
|
}
|
|
723
657
|
}
|
|
@@ -737,8 +671,8 @@ export class VecteurClient {
|
|
|
737
671
|
+ "next: continue in the web app, or pass --parent <state-hash>");
|
|
738
672
|
}
|
|
739
673
|
// Client-local presentation overlay, as in the web transcript. Never write this
|
|
740
|
-
// timestamp into the immutable
|
|
741
|
-
return newest ? { ...newest.response, accepted_at: newest.accepted_at } : null;
|
|
674
|
+
// timestamp into the immutable run record or send it back to the server.
|
|
675
|
+
return newest ? { ...newest.response, accepted_at: newest.accepted_at, ask: newest.request.ask } : null;
|
|
742
676
|
}
|
|
743
677
|
|
|
744
678
|
async projectHistory(projectId, { limit = 25, before, signal } = {}) {
|
|
@@ -747,55 +681,132 @@ export class VecteurClient {
|
|
|
747
681
|
const page = await this.#json("GET", `/api/projects/${encodeURIComponent(projectId)}/runs?${query}`, { signal });
|
|
748
682
|
if (!exactKeys(page, ["runs", "next_before"]) || !Array.isArray(page.runs) || page.runs.length > limit
|
|
749
683
|
|| (page.next_before !== null && typeof page.next_before !== "string")
|
|
750
|
-
|| page.runs.some(row => row?.request?.project_id !== projectId || typeof row.request.ask !== "string"
|
|
751
|
-
|| !validateAdmitted(row.response) || !isStateHash(row.response.state_hash))) {
|
|
684
|
+
|| page.runs.some(row => row?.request?.project_id !== projectId || typeof row.request.ask !== "string")) {
|
|
752
685
|
throw new CliError("project_runs_invalid", "Server returned malformed Project run history");
|
|
753
686
|
}
|
|
754
|
-
for (const row of page.runs)
|
|
687
|
+
for (const row of page.runs) validateRun(row.response);
|
|
755
688
|
return page;
|
|
756
689
|
}
|
|
757
690
|
|
|
758
|
-
/**
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
* reading the head. A 409 is re-read ONCE to name the head or the open Run, and never
|
|
762
|
-
* re-posted: the Idempotency-Key is per invocation, so a second POST is a second billable
|
|
763
|
-
* admission, written against a head the ask never saw.
|
|
764
|
-
*/
|
|
765
|
-
async runSubmit(projectId, ask, onEvent = null, signal = undefined, parentStateHash = undefined) {
|
|
766
|
-
const parent = parentStateHash === undefined
|
|
767
|
-
? (await this.projectNewestRun(projectId, signal))?.state_hash ?? null
|
|
768
|
-
: parentStateHash;
|
|
769
|
-
let value;
|
|
691
|
+
/** One bounded admission. Callers own the key; neither timeout nor conflict generates another. */
|
|
692
|
+
async runStart(projectId, ask, { requestKey, parentStateHash, attachments, selections, signal } = {}) {
|
|
693
|
+
let parent = parentStateHash;
|
|
770
694
|
try {
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
695
|
+
if (!isRequestKey(requestKey)) throw new CliError("request_key_invalid", "request_key must be 8–64 letters, digits, _ or -");
|
|
696
|
+
if (parent !== undefined && parent !== null && !isStateHash(parent)) throw new CliError("parent_invalid", "Expected a state hash or null");
|
|
697
|
+
if (parent === undefined) parent = (await this.projectNewestRun(projectId, signal))?.state_hash ?? null;
|
|
698
|
+
let material = submissionMaterial(selections);
|
|
699
|
+
if (attachments !== undefined) {
|
|
700
|
+
if (!Array.isArray(attachments) || !attachments.every(handle => exactKeys(handle, ["cas_ref", "acquisition_ref"])
|
|
701
|
+
&& /^sha256:[0-9a-f]{64}$/.test(handle.cas_ref) && typeof handle.acquisition_ref === "string" && handle.acquisition_ref.length)) {
|
|
702
|
+
throw new CliError("selection_invalid", "Attachments must be source handles");
|
|
703
|
+
}
|
|
704
|
+
if (selections !== undefined && canonicalJson(attachments) !== canonicalJson(material.attachments)) {
|
|
705
|
+
throw new CliError("selection_invalid", "Attachments must match the exact-extract selections");
|
|
706
|
+
}
|
|
707
|
+
material = { ...material, attachments };
|
|
776
708
|
}
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
709
|
+
const body = { ask, ...material, parent_state_hash: parent, ui_context: null };
|
|
710
|
+
return await withAdmissionLock(() => this.#startAdmission(projectId, body, requestKey, signal), this.localEnv ?? process.env);
|
|
711
|
+
} catch (error) { throw this.#startFailure(error, requestKey, parent); }
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
#startFailure(error, key, parent) {
|
|
715
|
+
if (!(error instanceof CliError)) throw error;
|
|
716
|
+
if (["idempotency_conflict", "submission_mismatch"].includes(error.code)) {
|
|
717
|
+
error = new CliError("admission_unresolved",
|
|
718
|
+
"This request key could not be reconciled; inspect the Project history before submitting another request");
|
|
781
719
|
}
|
|
720
|
+
error.request_key = key;
|
|
721
|
+
error.parent_state_hash = parent;
|
|
722
|
+
return error;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
async #startAdmission(projectId, body, key, signal) {
|
|
726
|
+
const env = this.localEnv ?? process.env;
|
|
727
|
+
const id = admissionIntent(this.config.origin, projectId, key, body, env);
|
|
782
728
|
try {
|
|
783
|
-
|
|
729
|
+
const ack = await this.runAdmit(projectId, body, key, signal);
|
|
730
|
+
if (!validateRunAck(ack)) throw new CliError("run_ack_invalid", "Server returned malformed run acknowledgement");
|
|
731
|
+
admissionResolved(id, env);
|
|
732
|
+
return { ...ack, parent_state_hash: body.parent_state_hash };
|
|
784
733
|
} catch (error) {
|
|
785
|
-
|
|
734
|
+
if (error.admission === "refused" || ["state_fork", "state_busy", ...OWNER_WORDED].includes(error.code)) admissionResolved(id, env);
|
|
735
|
+
if (error instanceof CliError && ["state_fork", "state_busy"].includes(error.code)) {
|
|
736
|
+
throw await this.#admissionRefused(error.code, projectId, body.parent_state_hash, signal);
|
|
737
|
+
}
|
|
738
|
+
throw error;
|
|
786
739
|
}
|
|
787
740
|
}
|
|
788
741
|
|
|
742
|
+
/** CLI-only request freezing. The immutable file owns retries; no file read/selection occurs on reuse. */
|
|
743
|
+
async runStartLocal(projectId, ask, { requestKey, parentStateHash, paths = [], cwd = process.cwd(), signal } = {}) {
|
|
744
|
+
const env = this.localEnv ?? process.env;
|
|
745
|
+
let parent = parentStateHash;
|
|
746
|
+
try {
|
|
747
|
+
if (!isRequestKey(requestKey)) throw new CliError("request_key_invalid", "request_key must be 8–64 letters, digits, _ or -");
|
|
748
|
+
if (parent !== undefined && parent !== null && !isStateHash(parent)) throw new CliError("parent_invalid", "Expected a state hash or null");
|
|
749
|
+
const intent = { origin: this.config.origin, project_id: projectId, ask,
|
|
750
|
+
parent_state_hash: parent ?? null, paths: [...new Set(paths.map(path => resolve(cwd, path)))].sort() };
|
|
751
|
+
const file = join(dirname(credentialsPath(env)), `request-${createHash("sha256").update(requestKey).digest("hex")}.json`);
|
|
752
|
+
return await withAdmissionLock(async () => {
|
|
753
|
+
// Convenience deliberately does not recover a body from disk or guess a Run from history.
|
|
754
|
+
const saved = readStore(file);
|
|
755
|
+
if (saved) {
|
|
756
|
+
if (parent === undefined || canonicalJson(saved.intent) !== canonicalJson(intent)) {
|
|
757
|
+
throw new CliError("request_key_reused", "This request key already names a different ask, parent, Project or attachment set");
|
|
758
|
+
}
|
|
759
|
+
if (saved.version !== 1 || saved.request_key !== requestKey || saved.body?.ask !== ask
|
|
760
|
+
|| saved.body?.parent_state_hash !== parent || saved.body?.ui_context !== null
|
|
761
|
+
|| canonicalJson(submissionMaterial(saved.body?.selections)) !== canonicalJson({
|
|
762
|
+
attachments: saved.body?.attachments, ...(saved.body?.selections ? { selections: saved.body.selections } : {}) })) {
|
|
763
|
+
throw new CliError("request_file_invalid", "The frozen request is malformed; reconcile through Project history");
|
|
764
|
+
}
|
|
765
|
+
return this.#startAdmission(projectId, saved.body, requestKey, signal);
|
|
766
|
+
}
|
|
767
|
+
if (parent === undefined) parent = (await this.projectNewestRun(projectId, signal))?.state_hash ?? null;
|
|
768
|
+
if (unresolvedAdmissions(this.config.origin, projectId, env).some(row => row.key === requestKey)) {
|
|
769
|
+
throw new CliError("admission_unresolved", "No frozen request file is available; reconcile this key through Project history");
|
|
770
|
+
}
|
|
771
|
+
const selections = paths.length ? await selectInvocationFiles(this, projectId, paths, { cwd, env, signal }) : undefined;
|
|
772
|
+
const body = { ask, ...submissionMaterial(selections), parent_state_hash: parent, ui_context: null };
|
|
773
|
+
if (parentStateHash !== undefined) {
|
|
774
|
+
// writeStore fsyncs complete 0600 bytes; link publishes without replacing an existing key.
|
|
775
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
776
|
+
try {
|
|
777
|
+
writeStore(temporary, { version: 1, request_key: requestKey, intent, body });
|
|
778
|
+
try { linkSync(temporary, file); }
|
|
779
|
+
catch (error) {
|
|
780
|
+
if (error.code === "EEXIST") throw new CliError("request_key_reused", "A request file already exists for this key; its bytes were preserved");
|
|
781
|
+
throw error;
|
|
782
|
+
}
|
|
783
|
+
const fd = openSync(dirname(file), "r");
|
|
784
|
+
try { fsyncSync(fd); } finally { closeSync(fd); }
|
|
785
|
+
} finally { try { unlinkSync(temporary); } catch (error) { if (error.code !== "ENOENT") throw error; } }
|
|
786
|
+
}
|
|
787
|
+
return this.#startAdmission(projectId, body, requestKey, signal);
|
|
788
|
+
}, env);
|
|
789
|
+
} catch (error) { throw this.#startFailure(error, requestKey, parent); }
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** The blocking door: admit, follow to the terminal, return the record. */
|
|
793
|
+
async runSubmit(projectId, ask, onEvent = null, signal = undefined, parentStateHash = undefined, selections = undefined) {
|
|
794
|
+
const value = await this.runStart(projectId, ask, { requestKey: randomUUID(), parentStateHash, selections, signal });
|
|
795
|
+
try { return await this.runEvents(value.run_id, onEvent, signal); }
|
|
796
|
+
catch (error) { throw admittedFailure(error, value.run_id); }
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
async runStatus(runId, signal = undefined) {
|
|
800
|
+
const record = await this.runGet(runId, signal);
|
|
801
|
+
return { run_id: record.run_id, terminal: record.terminal, last_seq: record.events.at(-1)?.seq ?? -1 };
|
|
802
|
+
}
|
|
803
|
+
|
|
789
804
|
async #admissionRefused(code, projectId, sent, signal) {
|
|
790
805
|
let newest;
|
|
791
806
|
try { newest = await this.projectNewestRun(projectId, signal); } catch { newest = undefined; }
|
|
792
807
|
if (code === "state_busy" && newest?.terminal === "") {
|
|
793
808
|
const run = newest.run_id;
|
|
794
|
-
|
|
795
|
-
const waiting = question?.payload?.state === "requested"
|
|
796
|
-
? ` [waiting for an answer: ${this.config.origin}/dashboard/${encodeURIComponent(projectId)}?run=${encodeURIComponent(run)}]`
|
|
797
|
-
: "";
|
|
798
|
-
return new CliError(code, `Run ${run} is still open in Project ${projectId}${waiting}; `
|
|
809
|
+
return new CliError(code, `Run ${run} is still open in Project ${projectId}; `
|
|
799
810
|
+ `nothing was admitted; next: vecteur run get ${run}`);
|
|
800
811
|
}
|
|
801
812
|
if (code === "state_fork" && newest !== undefined) {
|
|
@@ -807,17 +818,29 @@ export class VecteurClient {
|
|
|
807
818
|
return new CliError(code, `nothing was admitted to Project ${projectId}; next: submit again`);
|
|
808
819
|
}
|
|
809
820
|
|
|
821
|
+
/** What this reader may do about a stopped Run. The server decides; a failed read names no plan and never fails the Run. */
|
|
822
|
+
async stopOffer(runId, signal = undefined) {
|
|
823
|
+
try {
|
|
824
|
+
const value = await this.#json("GET", `/api/runs/${encodeURIComponent(runId)}/stop-offer`, { signal });
|
|
825
|
+
return validateRunStopOffer(value) && value.run_id === runId ? value : null;
|
|
826
|
+
} catch (error) {
|
|
827
|
+
if (error?.name === "AbortError") throw error;
|
|
828
|
+
return null;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/** The authenticated measurement door. Measurement never fails the reader's run. */
|
|
833
|
+
async stopEvent(runId, body, signal = undefined) {
|
|
834
|
+
try { await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/stop-offer/events`, { signal, body }); } catch (error) { if (error?.name === "AbortError") throw error; }
|
|
835
|
+
}
|
|
836
|
+
|
|
810
837
|
async runGet(runId, signal = undefined) {
|
|
811
838
|
const value = await this.#json("GET", `/api/runs/${encodeURIComponent(runId)}`, { signal });
|
|
812
|
-
|
|
813
|
-
throw new CliError("run_invalid", "Server returned malformed run record");
|
|
814
|
-
}
|
|
815
|
-
value.events.forEach((event, seq) => validateEvent(event, runId, seq));
|
|
816
|
-
return value;
|
|
839
|
+
return validateRun(value, runId);
|
|
817
840
|
}
|
|
818
841
|
|
|
819
842
|
async runEvents(runId, onEvent = null, signal = undefined, priorEvents = []) {
|
|
820
|
-
priorEvents.forEach((event,
|
|
843
|
+
priorEvents.forEach((event, index) => validateEvent(event, runId, FIRST_EVENT_SEQ + index));
|
|
821
844
|
if (priorEvents.length > MAX_EVENTS) throw new CliError("response_too_large", "Event count exceeds limit");
|
|
822
845
|
if (priorEvents.at(-1)?.kind === "terminal") {
|
|
823
846
|
const direct = await this.runGet(runId, signal);
|
|
@@ -829,15 +852,20 @@ export class VecteurClient {
|
|
|
829
852
|
const response = await this.request("GET", `/api/runs/${encodeURIComponent(runId)}/events`, {
|
|
830
853
|
accept: "text/event-stream",
|
|
831
854
|
signal,
|
|
832
|
-
lastEventId: priorEvents.length ? priorEvents.
|
|
855
|
+
lastEventId: priorEvents.length ? priorEvents.at(-1).seq : undefined,
|
|
833
856
|
});
|
|
834
857
|
let events;
|
|
858
|
+
let streamedVersion;
|
|
835
859
|
try {
|
|
836
860
|
const type = response.headers.get("content-type")?.split(";", 1)[0];
|
|
837
861
|
if (type !== "text/event-stream") {
|
|
838
862
|
throw new CliError("sse_invalid", "Event route is not an SSE stream");
|
|
839
863
|
}
|
|
840
|
-
|
|
864
|
+
streamedVersion = Number(response.headers.get(STORED_WIRE_VERSION_HEADER));
|
|
865
|
+
if (!STORED_WIRE_VERSIONS.includes(streamedVersion)) {
|
|
866
|
+
throw new CliError("sse_invalid", "Event stream declares no known stored wire version");
|
|
867
|
+
}
|
|
868
|
+
events = [...priorEvents, ...await parseSse(response, runId, onEvent, FIRST_EVENT_SEQ + priorEvents.length)];
|
|
841
869
|
} catch (error) {
|
|
842
870
|
if (error?.name === "AbortError") {
|
|
843
871
|
if (signal?.aborted) throw new CliError("request_cancelled", "Following the Run was detached");
|
|
@@ -853,13 +881,10 @@ export class VecteurClient {
|
|
|
853
881
|
throw new CliError("terminal_invalid", "Event stream has no final terminal event");
|
|
854
882
|
}
|
|
855
883
|
const direct = await this.runGet(runId, signal);
|
|
856
|
-
if (JSON.stringify(events) !== JSON.stringify(direct.events)
|
|
884
|
+
if (JSON.stringify(events) !== JSON.stringify(direct.events)
|
|
885
|
+
|| (direct.stored_wire_version !== undefined && streamedVersion !== direct.stored_wire_version)) {
|
|
857
886
|
throw new CliError("record_mismatch", "Event stream disagrees with direct replay");
|
|
858
887
|
}
|
|
859
|
-
const eventTerminal = events.at(-1).payload.state ?? events.at(-1).payload.terminal;
|
|
860
|
-
if (eventTerminal !== direct.terminal) {
|
|
861
|
-
throw new CliError("terminal_mismatch", "Terminal event disagrees with direct record");
|
|
862
|
-
}
|
|
863
888
|
return direct;
|
|
864
889
|
}
|
|
865
890
|
|