@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/client.js CHANGED
@@ -1,14 +1,19 @@
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
7
  ARTIFACT_MEDIA_TYPES, EVENT_KINDS, OWNER_CONTRACT_IDENTITY, RETIRED_EVENT_KINDS, validateAdmitted,
5
8
  validateCliRelease, validateCustomerCostProjection, validateDeviceAuthorization, validateLimitDenial,
6
9
  validatePatCreated, validateProject, validateRunAck, validateAccount, validateQuotaDenial,
7
- RECOVERY_ACTIONS, validateRunControl, validateSource, validateSourceOffer,
10
+ RECOVERY_ACTIONS, validateRunStopOffer, validateRunControl, validateSource, validateSourceOffer,
11
+ AGENT_LABELS, CHILD_WIRE_VERSIONS, SPECIALIST_TOOL_WIRE_VERSION, LOCAL_EXEC_WIRE_VERSION, STORED_WIRE_VERSIONS, WIRE_READER_HEADER, WIRE_READER_VERSION, WIRE_VERSION_UNSUPPORTED,
8
12
  } from "./contract.js";
9
- import { readCredentials } from "./credentials.js";
13
+ import { credentialsPath, readCredentials } from "./credentials.js";
14
+ import { readStore, writeStore } from "./store.js";
10
15
  import { CliError } from "./errors.js";
11
- import { canonicalJson } from "./format.js";
16
+ import { canonicalJson, capabilityCall } from "./format.js";
12
17
 
13
18
  // Re-exported so every existing importer keeps its one import site; `errors.js` owns the type.
14
19
  export { CliError };
@@ -31,6 +36,20 @@ export function isStateHash(value) {
31
36
  return typeof value === "string" && STATE_HASH_SHAPE.test(value);
32
37
  }
33
38
 
39
+ export const isRequestKey = value => typeof value === "string" && /^[A-Za-z0-9_-]{8,64}$/.test(value);
40
+
41
+ export function validateAnswers(answers) {
42
+ if (!Array.isArray(answers) || !answers.length || !answers.every(answer =>
43
+ answer && typeof answer === "object" && !Array.isArray(answer)
44
+ && Object.keys(answer).every(key => ["id", "selected", "custom"].includes(key))
45
+ && typeof answer.id === "string" && answer.id.length > 0
46
+ && Array.isArray(answer.selected) && answer.selected.every(item => typeof item === "string")
47
+ && (answer.custom === undefined || answer.custom === null || typeof answer.custom === "string"))) {
48
+ throw new CliError("answers_invalid", "Expected an array of {id, selected: string[], custom?: string|null}");
49
+ }
50
+ return answers;
51
+ }
52
+
34
53
  /**
35
54
  * A failure after the acknowledgement names the admitted Run, which may still be running:
36
55
  * retrying the submit would now continue its head and admit a second, billable turn.
@@ -39,10 +58,10 @@ export function admittedFailure(error, runId) {
39
58
  if (!(error instanceof CliError)) return error;
40
59
  if (error.code === "pat_expired") {
41
60
  return new CliError("pat_expired",
42
- `credential expired after Run ${runId} was admitted; next: vecteur login; then: vecteur run get ${runId}`);
61
+ `credential expired after Run ${runId} was admitted; next: vecteur login; then: vecteur run get ${runId}`, { run_id: runId });
43
62
  }
44
63
  return new CliError(error.code,
45
- `Run ${runId} was admitted and may still be running; next: vecteur run get ${runId}`);
64
+ `Run ${runId} was admitted and may still be running; next: vecteur run get ${runId}`, { run_id: runId });
46
65
  }
47
66
 
48
67
  export function redact(value) {
@@ -195,6 +214,65 @@ function exactObject(value, fields, code) {
195
214
  return value;
196
215
  }
197
216
 
217
+ const CHILD_AGENTS = Object.keys(AGENT_LABELS).filter(agent => agent !== "engineering");
218
+ const STORED_WIRE_VERSION_HEADER = "X-Vecteur-Stored-Wire-Version";
219
+
220
+ /**
221
+ * RunWire v3 (v5 spec §4.1): a child row names its agent and the main row that delegated it,
222
+ * and exists only on a record the owner served at version 3 -- read from the record, never
223
+ * guessed from the rows. OPE owns the full nesting law; this reader refuses what it cannot
224
+ * render honestly: an unknown agent, a parent it never saw, or a child row on a v1/v2 record.
225
+ */
226
+ export function validateChildRows(events, storedVersion) {
227
+ const check = rowGuard(storedVersion);
228
+ events.forEach(check);
229
+ return events;
230
+ }
231
+
232
+ /**
233
+ * The same law, one event at a time: the streaming path runs it BEFORE it forwards a live event, and a reconnect
234
+ * seeds it with the events already received so the row context survives. A v5x `capability_tool` call must name
235
+ * an existing ROOT row and carry a closed family, an identifier and no child metadata at all.
236
+ */
237
+ export function rowGuard(storedVersion) {
238
+ if (!STORED_WIRE_VERSIONS.includes(storedVersion)) {
239
+ throw new CliError("run_invalid", "Server returned an unknown stored RunWire version");
240
+ }
241
+ const opened = new Map();
242
+ return (event) => {
243
+ if (event.kind === "tool_call" && event.payload?.tool === "local_exec" && storedVersion < LOCAL_EXEC_WIRE_VERSION) throw new CliError("run_invalid", "Local command requires RunWire v5");
244
+ if (event.kind === "tool_call" && event.payload?.tool === "capability_tool") {
245
+ const payload = event.payload;
246
+ if (!capabilityCall(payload) || ["agent", "parent_step_id", "specialist_tool"].some(key => Object.hasOwn(payload, key))
247
+ || opened.get(payload.step_id) !== null) {
248
+ throw new CliError("run_invalid", "Server returned a malformed capability call");
249
+ }
250
+ return;
251
+ }
252
+ if (event.kind === "tool_call" && event.payload?.tool === "specialist_tool") {
253
+ // RunWire v4 (A8): a specialist family call, only on a v4 record, under an open row of its own agent.
254
+ const { agent, step_id: stepId, specialist_tool: tool } = event.payload;
255
+ if (storedVersion < SPECIALIST_TOOL_WIRE_VERSION || !CHILD_AGENTS.includes(agent)
256
+ || opened.get(stepId) !== agent || typeof tool !== "string" || !tool) {
257
+ throw new CliError("run_invalid", "Server returned a malformed specialist call");
258
+ }
259
+ return;
260
+ }
261
+ if (event.kind !== "step_started" && event.kind !== "step_finished") return;
262
+ const { agent, parent_step_id: parent, step_id: stepId } = event.payload;
263
+ const child = agent !== undefined || parent !== undefined;
264
+ if (!child) {
265
+ if (event.kind === "step_started" && !opened.has(stepId)) opened.set(stepId, null);
266
+ return;
267
+ }
268
+ if (!CHILD_WIRE_VERSIONS.includes(storedVersion) || !CHILD_AGENTS.includes(agent) || typeof parent !== "string"
269
+ || opened.get(parent) !== null || (event.kind === "step_started" && opened.has(stepId))) {
270
+ throw new CliError("run_invalid", "Server returned a malformed child row");
271
+ }
272
+ if (event.kind === "step_started") opened.set(stepId, agent);
273
+ };
274
+ }
275
+
198
276
  export function validateEvent(value, runId, expectedSeq) {
199
277
  exactObject(value, ["run_id", "seq", "kind", "payload"], "event_invalid");
200
278
  if (value.run_id !== runId || !Number.isInteger(value.seq) || value.seq !== expectedSeq ||
@@ -235,7 +313,33 @@ export function validateEvidenceDag(value, runId) {
235
313
  return value;
236
314
  }
237
315
 
238
- export async function parseSse(response, runId, onEvent = null, startSeq = 0) {
316
+ /**
317
+ * The material a submit selects: the composer's exact shape (one exact-extract selection per
318
+ * attached source, both lists in source order). Absent keeps the Project's carried sources.
319
+ */
320
+ export function submissionMaterial(selections) {
321
+ if (selections === undefined) return { attachments: [] };
322
+ const key = (s) => `${s.source_handle.cas_ref}\n${s.source_handle.acquisition_ref}`;
323
+ if (!Array.isArray(selections) || selections.length === 0 || !selections.every(s =>
324
+ exactKeys(s, ["source_handle", "offer_id", "selected_extract_ids", "method"])
325
+ && exactKeys(s.source_handle, ["cas_ref", "acquisition_ref"])
326
+ && /^sha256:[0-9a-f]{64}$/.test(s.source_handle.cas_ref) && typeof s.source_handle.acquisition_ref === "string"
327
+ && s.source_handle.acquisition_ref.length > 0 && typeof s.offer_id === "string" && s.offer_id.length > 0
328
+ && Array.isArray(s.selected_extract_ids) && s.selected_extract_ids.length > 0
329
+ && s.selected_extract_ids.every(id => typeof id === "string" && id.length > 0)
330
+ && new Set(s.selected_extract_ids).size === s.selected_extract_ids.length
331
+ && s.method === "exact-extract") || new Set(selections.map(key)).size !== selections.length) {
332
+ throw new CliError("selection_invalid",
333
+ "Each selection is {source_handle, offer_id, selected_extract_ids, method: exact-extract}, one per source");
334
+ }
335
+ const sorted = [...selections].sort((a, b) => key(a).localeCompare(key(b))).map(s => ({
336
+ source_handle: { cas_ref: s.source_handle.cas_ref, acquisition_ref: s.source_handle.acquisition_ref },
337
+ offer_id: s.offer_id, selected_extract_ids: [...s.selected_extract_ids].sort(), method: s.method,
338
+ }));
339
+ return { attachments: sorted.map(s => ({ ...s.source_handle })), selections: sorted };
340
+ }
341
+
342
+ export async function parseSse(response, runId, onEvent = null, startSeq = 0, guard = null) {
239
343
  if (!Number.isSafeInteger(startSeq) || startSeq < 0 || startSeq >= MAX_EVENTS) {
240
344
  throw new CliError("cursor_invalid", "Event cursor is outside the supported history bound");
241
345
  }
@@ -291,6 +395,7 @@ export async function parseSse(response, runId, onEvent = null, startSeq = 0) {
291
395
  throw new CliError("sse_invalid", "SSE metadata disagrees with event data");
292
396
  }
293
397
  events.push(validateEvent(refuseSecretValue(value), runId, startSeq + events.length));
398
+ guard?.(events.at(-1));
294
399
  await onEvent?.(events.at(-1));
295
400
  if (startSeq + events.length > MAX_EVENTS) throw new CliError("response_too_large", "Event count exceeds limit");
296
401
  terminalSeen = events.at(-1).kind === "terminal";
@@ -360,6 +465,9 @@ export class VecteurClient {
360
465
  ...(accept ? { Accept: accept } : {}),
361
466
  ...(acceptEncoding ? { "Accept-Encoding": acceptEncoding } : {}),
362
467
  ...(lastEventId === undefined ? {} : { "Last-Event-ID": String(lastEventId) }),
468
+ // RunWire v3 (v5 §4.1): this reader reads every declared stored version; without the
469
+ // header the origin treats a client as a v2 reader and refuses a child-enabled Run.
470
+ ...(!anonymousReadiness ? { [WIRE_READER_HEADER]: String(WIRE_READER_VERSION) } : {}),
363
471
  },
364
472
  body: rawBody ?? (body === undefined ? undefined : JSON.stringify(body)),
365
473
  });
@@ -425,12 +533,20 @@ export class VecteurClient {
425
533
  const reset = new Date(limit.reset_at * 1000).toISOString().replace(".000Z", "Z");
426
534
  ownerMessage = `Customer cost limit reached; binding=${binding}; reset=${reset} UTC; next=${limit.recovery.join(",")}`;
427
535
  }
536
+ if (candidate === WIRE_VERSION_UNSUPPORTED) {
537
+ ownerMessage = "this Run is stored in a RunWire version this CLI cannot read; next: vecteur update";
538
+ }
428
539
  if (["pat_expired", "pat_invalid", "pat_revoked"].includes(candidate)) {
429
540
  ownerMessage = "credential is expired or revoked; next: vecteur login";
430
541
  }
431
542
  if (candidate === "pat_ancestry_inactive") {
432
543
  ownerMessage = "seat or Organization is inactive; next: contact your Organization owner or Vecteur support";
433
544
  }
545
+ // A38: the run door names the Produce entry it keeps off, in product words; the CLI holds no copy of the table.
546
+ if (candidate === "produce_unavailable" && typeof error.message === "string" && error.message.length > 0
547
+ && error.message.length <= 512 && !/[\r\n\0]/.test(error.message)) {
548
+ ownerMessage = error.message;
549
+ }
434
550
  if (
435
551
  candidate === "client_outdated"
436
552
  && Object.keys(error).sort().join("\n") === "code\nmessage"
@@ -453,6 +569,7 @@ export class VecteurClient {
453
569
  code,
454
570
  ownerMessage || `Public API refused request with HTTP ${response.status}`,
455
571
  );
572
+ failure.status = response.status;
456
573
  if (admission) failure.admission = admission;
457
574
  throw failure;
458
575
  }
@@ -554,6 +671,22 @@ export class VecteurClient {
554
671
  return value;
555
672
  }
556
673
 
674
+ async localExec(runId, body, requestId = null) {
675
+ const controller = new AbortController(), timer = setTimeout(() => controller.abort(), 2500);
676
+ try { return await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/local-exec${requestId ? '/'+encodeURIComponent(requestId) : ''}`, { body, signal: controller.signal }); }
677
+ finally { clearTimeout(timer); }
678
+ }
679
+
680
+ async runControls(runId, signal = undefined) {
681
+ const value = await this.#json("GET", `/api/runs/${encodeURIComponent(runId)}/controls`, { signal });
682
+ if (!exactKeys(value, ["controls"]) || !Array.isArray(value.controls) || value.controls.length > 32
683
+ || !value.controls.every(validateRunControl) || new Set(value.controls.map(c => c.id)).size !== value.controls.length
684
+ || value.controls.some((c, i) => i > 0 && c.sequence <= value.controls[i - 1].sequence)) {
685
+ throw new CliError("control_invalid", "Malformed controls projection");
686
+ }
687
+ return value.controls;
688
+ }
689
+
557
690
  async clarificationAnswer(runId, questionId, answers, signal = undefined) {
558
691
  const value = await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/clarifications/${encodeURIComponent(questionId)}/answer`,
559
692
  { body: { answers }, signal });
@@ -668,6 +801,7 @@ export class VecteurClient {
668
801
  throw new CliError("request_failed",
669
802
  `origin ${this.config.origin}; cause=artifact_transport; next: check the network and retry`);
670
803
  } finally {
804
+ if (response.body && !response.body.locked) await response.body.cancel().catch(() => {});
671
805
  response[RELEASE_TIMEOUT]?.();
672
806
  }
673
807
  }
@@ -738,7 +872,7 @@ export class VecteurClient {
738
872
  }
739
873
  // Client-local presentation overlay, as in the web transcript. Never write this
740
874
  // timestamp into the immutable RunWire response or send it back to the server.
741
- return newest ? { ...newest.response, accepted_at: newest.accepted_at } : null;
875
+ return newest ? { ...newest.response, accepted_at: newest.accepted_at, ask: newest.request.ask } : null;
742
876
  }
743
877
 
744
878
  async projectHistory(projectId, { limit = 25, before, signal } = {}) {
@@ -755,37 +889,129 @@ export class VecteurClient {
755
889
  return page;
756
890
  }
757
891
 
758
- /**
759
- * One turn, chained onto the Project's design head (OPE admits null only on a Project with no
760
- * head, otherwise only the exact head). `parentStateHash` pins a compare-and-swap instead of
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;
892
+ /** One bounded admission. Callers own the key; neither timeout nor conflict generates another. */
893
+ async runStart(projectId, ask, { requestKey, parentStateHash, attachments, selections, signal, intent, executor } = {}) {
894
+ let parent = parentStateHash;
895
+ try {
896
+ if (!isRequestKey(requestKey)) throw new CliError("request_key_invalid", "request_key must be 8–64 letters, digits, _ or -");
897
+ if (parent !== undefined && parent !== null && !isStateHash(parent)) throw new CliError("parent_invalid", "Expected a state hash or null");
898
+ if (parent === undefined) parent = (await this.projectNewestRun(projectId, signal))?.state_hash ?? null;
899
+ let material = submissionMaterial(selections);
900
+ if (attachments !== undefined) {
901
+ if (!Array.isArray(attachments) || !attachments.every(handle => exactKeys(handle, ["cas_ref", "acquisition_ref"])
902
+ && /^sha256:[0-9a-f]{64}$/.test(handle.cas_ref) && typeof handle.acquisition_ref === "string" && handle.acquisition_ref.length)) {
903
+ throw new CliError("selection_invalid", "Attachments must be source handles");
904
+ }
905
+ if (selections !== undefined && canonicalJson(attachments) !== canonicalJson(material.attachments)) {
906
+ throw new CliError("selection_invalid", "Attachments must match the exact-extract selections");
907
+ }
908
+ material = { ...material, attachments };
909
+ }
910
+ const body = { ask, ...material, parent_state_hash: parent, ui_context: null,
911
+ ...(intent === undefined ? {} : { intent }), ...(executor ? { local_exec: executor.descriptor } : {}) };
912
+ return await withAdmissionLock(() => this.#startAdmission(projectId, body, requestKey, signal), this.localEnv ?? process.env);
913
+ } catch (error) { throw this.#startFailure(error, requestKey, parent); }
914
+ }
915
+
916
+ #startFailure(error, key, parent) {
917
+ if (!(error instanceof CliError)) throw error;
918
+ if (["idempotency_conflict", "submission_mismatch"].includes(error.code)) {
919
+ error = new CliError("admission_unresolved",
920
+ "This request key could not be reconciled; inspect the Project history before submitting another request");
921
+ }
922
+ error.request_key = key;
923
+ error.parent_state_hash = parent;
924
+ return error;
925
+ }
926
+
927
+ async #startAdmission(projectId, body, key, signal) {
928
+ const env = this.localEnv ?? process.env;
929
+ const id = body.local_exec ? null : admissionIntent(this.config.origin, projectId, key, body, env);
770
930
  try {
771
- value = await this.runAdmit(projectId,
772
- { ask, attachments: [], parent_state_hash: parent, ui_context: null }, randomUUID(), signal);
931
+ const ack = await this.runAdmit(projectId, body, key, signal);
932
+ if (!validateRunAck(ack)) throw new CliError("run_ack_invalid", "Server returned malformed run acknowledgement");
933
+ if (id) admissionResolved(id, env);
934
+ return { ...ack, parent_state_hash: body.parent_state_hash };
773
935
  } catch (error) {
774
- if (error instanceof CliError && (error.code === "state_fork" || error.code === "state_busy")) {
775
- throw await this.#admissionRefused(error.code, projectId, parent, signal);
936
+ if (id && (error.admission === "refused" || ["state_fork", "state_busy"].includes(error.code))) admissionResolved(id, env);
937
+ if (error instanceof CliError && ["state_fork", "state_busy"].includes(error.code)) {
938
+ throw await this.#admissionRefused(error.code, projectId, body.parent_state_hash, signal);
776
939
  }
777
940
  throw error;
778
941
  }
779
- if (!validateRunAck(value)) {
780
- throw new CliError("run_ack_invalid", "Server returned malformed run acknowledgement");
781
- }
942
+ }
943
+
944
+ /** CLI-only request freezing. The immutable file owns retries; no file read/selection occurs on reuse. */
945
+ async runStartLocal(projectId, ask, { requestKey, parentStateHash, paths = [], cwd = process.cwd(), signal } = {}) {
946
+ const env = this.localEnv ?? process.env;
947
+ let parent = parentStateHash;
948
+ try {
949
+ if (!isRequestKey(requestKey)) throw new CliError("request_key_invalid", "request_key must be 8–64 letters, digits, _ or -");
950
+ if (parent !== undefined && parent !== null && !isStateHash(parent)) throw new CliError("parent_invalid", "Expected a state hash or null");
951
+ const intent = { origin: this.config.origin, project_id: projectId, ask,
952
+ parent_state_hash: parent ?? null, paths: [...new Set(paths.map(path => resolve(cwd, path)))].sort() };
953
+ const file = join(dirname(credentialsPath(env)), `request-${createHash("sha256").update(requestKey).digest("hex")}.json`);
954
+ return await withAdmissionLock(async () => {
955
+ // Convenience deliberately does not recover a body from disk or guess a Run from history.
956
+ const saved = readStore(file);
957
+ if (saved) {
958
+ if (parent === undefined || canonicalJson(saved.intent) !== canonicalJson(intent)) {
959
+ throw new CliError("request_key_reused", "This request key already names a different ask, parent, Project or attachment set");
960
+ }
961
+ if (saved.version !== 1 || saved.request_key !== requestKey || saved.body?.ask !== ask
962
+ || saved.body?.local_exec !== undefined
963
+ || saved.body?.parent_state_hash !== parent || saved.body?.ui_context !== null
964
+ || canonicalJson(submissionMaterial(saved.body?.selections)) !== canonicalJson({
965
+ attachments: saved.body?.attachments, ...(saved.body?.selections ? { selections: saved.body.selections } : {}) })) {
966
+ throw new CliError("request_file_invalid", "The frozen request is malformed; reconcile through Project history");
967
+ }
968
+ return this.#startAdmission(projectId, saved.body, requestKey, signal);
969
+ }
970
+ if (parent === undefined) parent = (await this.projectNewestRun(projectId, signal))?.state_hash ?? null;
971
+ if (unresolvedAdmissions(this.config.origin, projectId, env).some(row => row.key === requestKey)) {
972
+ throw new CliError("admission_unresolved", "No frozen request file is available; reconcile this key through Project history");
973
+ }
974
+ const selections = paths.length ? await selectInvocationFiles(this, projectId, paths, { cwd, env, signal }) : undefined;
975
+ const body = { ask, ...submissionMaterial(selections), parent_state_hash: parent, ui_context: null };
976
+ if (parentStateHash !== undefined) {
977
+ // writeStore fsyncs complete 0600 bytes; link publishes without replacing an existing key.
978
+ const temporary = `${file}.${randomUUID()}.tmp`;
979
+ try {
980
+ writeStore(temporary, { version: 1, request_key: requestKey, intent, body });
981
+ try { linkSync(temporary, file); }
982
+ catch (error) {
983
+ if (error.code === "EEXIST") throw new CliError("request_key_reused", "A request file already exists for this key; its bytes were preserved");
984
+ throw error;
985
+ }
986
+ const fd = openSync(dirname(file), "r");
987
+ try { fsyncSync(fd); } finally { closeSync(fd); }
988
+ } finally { try { unlinkSync(temporary); } catch (error) { if (error.code !== "ENOENT") throw error; } }
989
+ }
990
+ return this.#startAdmission(projectId, body, requestKey, signal);
991
+ }, env);
992
+ } catch (error) { throw this.#startFailure(error, requestKey, parent); }
993
+ }
994
+
995
+ /** The legacy blocking door retains its success record and error prose. */
996
+ async runSubmit(projectId, ask, onEvent = null, signal = undefined, parentStateHash = undefined,
997
+ selections = undefined, intent = undefined, executor = undefined) {
998
+ const value = await this.runStart(projectId, ask, { requestKey: randomUUID(), parentStateHash, selections, signal, intent, executor });
782
999
  try {
783
- return await this.runEvents(value.run_id, onEvent, signal);
1000
+ const pump = executor?.pump(value.run_id).catch(() => executor.stop());
1001
+ try { return await this.runEvents(value.run_id, onEvent, signal); }
1002
+ finally { executor?.stop(); await pump; }
784
1003
  } catch (error) {
785
1004
  throw admittedFailure(error, value.run_id);
786
1005
  }
787
1006
  }
788
1007
 
1008
+ async runStatus(runId, signal = undefined) {
1009
+ const record = await this.runGet(runId, signal);
1010
+ const latest = record.events.filter(event => event.kind === "clarification").at(-1)?.payload;
1011
+ return { run_id: record.run_id, terminal: record.terminal, last_seq: record.events.at(-1)?.seq ?? -1,
1012
+ clarification: latest?.state === "requested" ? latest : null };
1013
+ }
1014
+
789
1015
  async #admissionRefused(code, projectId, sent, signal) {
790
1016
  let newest;
791
1017
  try { newest = await this.projectNewestRun(projectId, signal); } catch { newest = undefined; }
@@ -807,12 +1033,29 @@ export class VecteurClient {
807
1033
  return new CliError(code, `nothing was admitted to Project ${projectId}; next: submit again`);
808
1034
  }
809
1035
 
1036
+ /** What this reader may do about a stopped Run. The server decides; a failed read names no plan and never fails the Run. */
1037
+ async stopOffer(runId, signal = undefined) {
1038
+ try {
1039
+ const value = await this.#json("GET", `/api/runs/${encodeURIComponent(runId)}/stop-offer`, { signal });
1040
+ return validateRunStopOffer(value) && value.run_id === runId ? value : null;
1041
+ } catch (error) {
1042
+ if (error?.name === "AbortError") throw error;
1043
+ return null;
1044
+ }
1045
+ }
1046
+
1047
+ /** The authenticated measurement door. Measurement never fails the reader's run. */
1048
+ async stopEvent(runId, body, signal = undefined) {
1049
+ try { await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/stop-offer/events`, { signal, body }); } catch (error) { if (error?.name === "AbortError") throw error; }
1050
+ }
1051
+
810
1052
  async runGet(runId, signal = undefined) {
811
1053
  const value = await this.#json("GET", `/api/runs/${encodeURIComponent(runId)}`, { signal });
812
1054
  if (!validateAdmitted(value) || value.run_id !== runId) {
813
1055
  throw new CliError("run_invalid", "Server returned malformed run record");
814
1056
  }
815
1057
  value.events.forEach((event, seq) => validateEvent(event, runId, seq));
1058
+ validateChildRows(value.events, value.stored_wire_version);
816
1059
  return value;
817
1060
  }
818
1061
 
@@ -832,12 +1075,19 @@ export class VecteurClient {
832
1075
  lastEventId: priorEvents.length ? priorEvents.length - 1 : undefined,
833
1076
  });
834
1077
  let events;
1078
+ let streamedVersion;
835
1079
  try {
836
1080
  const type = response.headers.get("content-type")?.split(";", 1)[0];
837
1081
  if (type !== "text/event-stream") {
838
1082
  throw new CliError("sse_invalid", "Event route is not an SSE stream");
839
1083
  }
840
- events = [...priorEvents, ...await parseSse(response, runId, onEvent, priorEvents.length)];
1084
+ streamedVersion = Number(response.headers.get(STORED_WIRE_VERSION_HEADER));
1085
+ if (!STORED_WIRE_VERSIONS.includes(streamedVersion)) {
1086
+ throw new CliError("sse_invalid", "Event stream declares no known stored RunWire version");
1087
+ }
1088
+ const guard = rowGuard(streamedVersion);
1089
+ priorEvents.forEach(guard);
1090
+ events = [...priorEvents, ...await parseSse(response, runId, onEvent, priorEvents.length, guard)];
841
1091
  } catch (error) {
842
1092
  if (error?.name === "AbortError") {
843
1093
  if (signal?.aborted) throw new CliError("request_cancelled", "Following the Run was detached");
@@ -853,7 +1103,8 @@ export class VecteurClient {
853
1103
  throw new CliError("terminal_invalid", "Event stream has no final terminal event");
854
1104
  }
855
1105
  const direct = await this.runGet(runId, signal);
856
- if (JSON.stringify(events) !== JSON.stringify(direct.events)) {
1106
+ if (JSON.stringify(events) !== JSON.stringify(direct.events)
1107
+ || streamedVersion !== direct.stored_wire_version) {
857
1108
  throw new CliError("record_mismatch", "Event stream disagrees with direct replay");
858
1109
  }
859
1110
  const eventTerminal = events.at(-1).payload.state ?? events.at(-1).payload.terminal;
package/src/commands.js CHANGED
@@ -1,17 +1,20 @@
1
+ import { withAdmissionLock } from "./localfiles.js";
1
2
  import { CliError } from "./errors.js";
2
- import { runView } from "./blocks.js";
3
+ import { runView, runBlocks, blockText } from "./blocks.js";
3
4
  import { openBrowser } from "./browser.js";
4
5
  import { diagnose } from "./diagnostics.js";
5
- import { humanCost } from "./format.js";
6
+ import { humanCost, terminalText } from "./format.js";
6
7
  import { preferences, savePreferences } from "./preferences.js";
7
8
 
8
9
  export const SHORTCUTS = `Enter sends when ready; while running it offers steering or keeps the draft.
9
10
  Alt+Enter / Ctrl+J newline; backslash then Enter is the portable fallback.
10
- Paste never sends. Tab completes commands; arrows select; Esc closes a menu.
11
+ Bracketed paste never sends. Plain/dumb multiline chunks stay drafts; a split-read
12
+ lone CR/CRLF is indistinguishable from Enter and can send.
13
+ Tab completes commands; arrows select; Esc closes a menu.
11
14
  Home/End or Ctrl+A/E: line boundaries. Alt+B/F: words. Ctrl+W: cut word.
12
15
  Ctrl+K/U: cut line tail/head. Ctrl+Y: restore cut. Ctrl+_: undo edit.
13
16
  Up/Down: multiline movement, then history at its boundary. Ctrl+R: search history.
14
- ? on empty input: shortcuts. Ctrl+O: step details. Ctrl+L: redraw.
17
+ ? on empty input: shortcuts. Ctrl+O: full block details. Ctrl+L: redraw.
15
18
  Ctrl+C with text clears it (Ctrl+_ restores). Empty idle Ctrl+C twice exits.
16
19
  Esc twice or empty Ctrl+C twice requests cancellation of the same cloud Run.
17
20
  Ctrl+D on empty input saves and detaches; the cloud Run continues. /quit also exits.`;
@@ -27,6 +30,7 @@ add("offline", "Draft without any network activity", s => {
27
30
  if (s.busy && !s.loginController) throw new CliError("session_busy", "Wait for this action to finish before disconnecting; your draft is kept");
28
31
  s.workOffline();
29
32
  });
33
+ add("exec", "Allow local bash commands, or revoke immediately", (s, argument) => s.execConsent(argument), { argument: "on|off", requires: "login" });
30
34
  add("resume", "Reconnect or reconcile an interrupted ask", s => s.resume());
31
35
  add("quit", "Save draft and detach; cloud Run continues", s => s.close(), { aliases: ["exit"] });
32
36
  add("drafts", "Recover a saved draft", s => s.recoverDraft());
@@ -70,12 +74,12 @@ add("project", "Choose a Project or start a new study draft", async (s, argument
70
74
  ]);
71
75
  if (action !== "new") return s.link({ persist: action === "link" });
72
76
  if (s.run?.open || s.registry.state().pendingRun || s.registry.state().pendingCreate) throw new CliError("run_busy", "Resolve or finish the current Run before starting a new study");
73
- s.registry.unlink(); s.binding = null; s.project = null; s.run = null; s.attachments = []; s.status = "New Project on first send"; s.change();
77
+ await withAdmissionLock(() => s.registry.unlink(), s.env); s.binding = null; s.project = null; s.run = null; s.attachments = []; s.status = "New Project on first send"; s.change();
74
78
  }, { argument: "[list]", requires: "login" });
75
79
  add("link", "Link an existing Project to this folder", s => s.link(), { requires: "login" });
76
- add("unlink", "Remove this folder's Project binding", s => {
80
+ add("unlink", "Remove this folder's Project binding", async s => {
77
81
  if (s.run?.open || s.busy || s.registry.state().pendingRun || s.registry.state().pendingCreate) throw new CliError("run_busy", "Resolve or finish the current Run before unlinking");
78
- s.followController?.abort(); s.generation++; s.registry.unlink(); s.binding = null; s.project = null; s.run = null; s.status = "Folder unlinked"; s.change();
82
+ s.followController?.abort(); s.generation++; await withAdmissionLock(() => s.registry.unlink(), s.env); s.binding = null; s.project = null; s.run = null; s.status = "Folder unlinked"; s.change();
79
83
  }, { requires: "login" });
80
84
  add("history", "Read earlier Runs in this Project", s => s.history(), { requires: "login" });
81
85
  add("name", "Name the Project", (s, value) => s.transition(async () => {
@@ -90,25 +94,62 @@ add("clear-files", "Remove pending attachments", s => {
90
94
  if (s.busy || s.registry?.state().pendingRun) throw new CliError("session_busy", "Resolve the pending action before clearing files");
91
95
  s.attachments = []; s.change();
92
96
  });
93
- add("files", "Selected inputs and downloadable results", s => s.message([
94
- ...s.attachments.map(item => `Pending: ${item.path} (${item.bytes.length} bytes; not uploaded)`),
95
- ...runView(s.run).artifacts.map((item, i) => `${i + 1}. ${item.filename} · ${item.kind} · /download ${i + 1} · /web`),
96
- ].join("\n") || "No selected files or artifacts."));
97
+ add("files", "Selected inputs, local authority and downloadable results", (s, argument) => {
98
+ if (argument === 'revoke') return s.revokeFiles();
99
+ const match = /^save (\d+)$/.exec(argument);
100
+ if (match) return s.transition(() => s.offerSaves(Number(match[1])));
101
+ const diff = /^diff (\d+)$/.exec(argument);
102
+ if (diff) return s.transition(() => s.fileDiff(Number(diff[1])));
103
+ if (argument) throw new CliError('usage_invalid', 'Use /files, /files revoke, /files save N or /files diff N');
104
+ return s.listFiles();
105
+ }, {argument:'[revoke|save N|diff N]'});
97
106
  add("download", "Save and verify a result file", (s, argument) => {
98
107
  const match = /^(\d+)(?:\s+(.+))?$/.exec(argument);
99
108
  if (!match) throw new CliError("usage_invalid", "Use /download <artifact number> [output path]");
100
109
  return s.download(Number(match[1]), match[2]);
101
110
  }, { argument: "<number> [path]", required: true, requires: "login" });
111
+ add("package", "Save a result file into its own folder to test locally; then /attach the report", (s, argument) => {
112
+ if (!/^\d+$/.test(argument.trim())) throw new CliError("usage_invalid", "Use /package <artifact number>");
113
+ return s.package(Number(argument));
114
+ }, { argument: "<number>", required: true, requires: "login" });
115
+ add("run-package", "Run a /package folder's declared tests here, with your consent; stage the report for upload", (s, folder) =>
116
+ s.runPackage(folder), { argument: "[folder]", requires: "login" });
117
+ add("stop-package", "Stop the running package and every process it started", s => s.stopPackage());
118
+ add("produce", "Ask one specialist (business, knowledge) to produce; a knowledge document needs a completed analysis in this Project first; Engineering adopts its result", (s, argument) =>
119
+ s.produce(argument), { argument: "<specialist> [entry] [profile=<nasa|esa>] <ask>", required: true, requires: "login" });
102
120
  add("export", "Export the answer, Run record and verified files to a new folder", (s, path) => s.exportRun(path || undefined), { argument: "[folder]", requires: "login" });
103
121
  add("copy", "Copy the exact answer or save it to a new file", (s, path) => s.copy(path || undefined), { argument: "[path]" });
104
122
  add("answer", "Answer the current clarification", s => s.answer(), { requires: "question" });
105
123
  add("steer", "Send an instruction to the running Run", (s, text) => s.steer(text), { argument: "<instruction>", required: true, requires: "run" });
106
124
  add("answer-now", "Ask the running Run to conclude", s => s.steer(""), { requires: "run" });
107
125
  add("cancel", "Request cancellation; keep completed work", s => s.cancel(), { requires: "run" });
108
- add("details", "Read the current or numbered step", (s, argument) => {
109
- const steps = runView(s.run).steps;
110
- const event = argument ? steps[Number(argument) - 1] : steps.at(-1);
111
- s.message(event ? JSON.stringify(event.payload, null, 2) : "No step details yet.");
126
+ add("details", "Read the current or numbered block in full", async (s, argument) => {
127
+ const blocks = runBlocks(s.run);
128
+ const block = argument ? blocks[Number(argument) - 1] : [...blocks].reverse().find(b => b.calls) ?? blocks.at(-1);
129
+ if (!block) { s.message("No block details yet."); return; }
130
+ const lines = [blockText(block, { full: true })];
131
+ for (const { call, result } of block.calls ?? []) {
132
+ if (!result?.stdout_ref) continue;
133
+ const ref = result.stdout_ref, chunks = [];
134
+ let size = 0;
135
+ try {
136
+ s.requireLogin();
137
+ if (!s.project?.id) throw new CliError("project_required", "Select the Run's Project first");
138
+ const metadata = await s.client.artifactGet(ref, s.project.id, chunk => {
139
+ size += chunk.byteLength;
140
+ if (size > 64 * 1024) throw new CliError("stdout_too_large", "Full stdout exceeds the 64 KiB CLI detail limit");
141
+ chunks.push(Buffer.from(chunk));
142
+ }, s.lifecycle.signal);
143
+ if (!metadata.content_type.startsWith("text/") && !["application/json", "image/svg+xml"].includes(metadata.content_type)) {
144
+ throw new CliError("stdout_invalid", "Full stdout is not a textual media type");
145
+ }
146
+ lines.push(`Full stdout · ${call.call_id} · ${ref}:\n${Buffer.concat(chunks).toString("utf8") || "(empty)"}`);
147
+ } catch (error) {
148
+ lines.push(`Full stdout unavailable · ${ref}: ${error.message}`);
149
+ if (error.code === "stdout_too_large") lines.push(`Save full stdout: vecteur artifact get ${ref} -p ${s.project.id} --output <file>`);
150
+ }
151
+ }
152
+ s.message(terminalText(lines.join("\n")));
112
153
  }, { argument: "[number]" });
113
154
  add("handoff", "Open your Claude Code or Codex here with Vecteur attached", (s, vendor) => {
114
155
  if (!["claude", "codex"].includes(vendor)) throw new CliError("usage_invalid", "Use /handoff claude or /handoff codex");