@vecteur/cli 0.11.1 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.js CHANGED
@@ -4,19 +4,19 @@ import { closeSync, fsyncSync, linkSync, openSync, unlinkSync } from "node:fs";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
 
6
6
  import {
7
- ARTIFACT_MEDIA_TYPES, EVENT_KINDS, OWNER_CONTRACT_IDENTITY, RETIRED_EVENT_KINDS, validateAdmitted,
8
- validateCliRelease, validateCustomerCostProjection, validateDeviceAuthorization, validateLimitDenial,
9
- validatePatCreated, validateProject, validateRunAck, validateAccount, validateQuotaDenial,
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,
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,
12
11
  } from "./contract.js";
12
+ import { FIRST_EVENT_SEQ, isStateHash, validateEvent, validateRun } from "./wire.js";
13
13
  import { credentialsPath, readCredentials } from "./credentials.js";
14
14
  import { readStore, writeStore } from "./store.js";
15
15
  import { CliError } from "./errors.js";
16
- import { canonicalJson, capabilityCall } from "./format.js";
16
+ import { canonicalJson } from "./format.js";
17
17
 
18
18
  // Re-exported so every existing importer keeps its one import site; `errors.js` owns the type.
19
- export { CliError };
19
+ export { CliError, isStateHash, validateEvent };
20
20
 
21
21
  const DEFAULT_TIMEOUT_MS = 120_000;
22
22
  export const DEFAULT_ORIGIN = "https://vecteur.space";
@@ -27,29 +27,12 @@ const RESPONSE_ACTIVITY = Symbol("response-activity");
27
27
  const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
28
28
  const MAX_FRAME_BYTES = 1024 * 1024;
29
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"]);
30
32
  const CAS_REF_SHAPE = /^sha256:([0-9a-f]{64})$/;
31
- const STATE_HASH_SHAPE = /^[0-9a-f]{64}$/;
32
-
33
-
34
- /** The one shape of a design head, so `--parent` and the head read cannot disagree. */
35
- export function isStateHash(value) {
36
- return typeof value === "string" && STATE_HASH_SHAPE.test(value);
37
- }
38
33
 
39
34
  export const isRequestKey = value => typeof value === "string" && /^[A-Za-z0-9_-]{8,64}$/.test(value);
40
35
 
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
-
53
36
  /**
54
37
  * A failure after the acknowledgement names the admitted Run, which may still be running:
55
38
  * retrying the submit would now continue its head and admit a second, billable turn.
@@ -206,113 +189,11 @@ export async function waitForDeviceAuthorization(client, grant, { sleep = delay,
206
189
  }
207
190
  }
208
191
 
209
- function exactObject(value, fields, code) {
210
- if (!value || typeof value !== "object" || Array.isArray(value) ||
211
- Object.keys(value).sort().join("\n") !== [...fields].sort().join("\n")) {
212
- throw new CliError(code, "Server returned malformed owner data");
213
- }
214
- return value;
215
- }
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
-
276
- export function validateEvent(value, runId, expectedSeq) {
277
- exactObject(value, ["run_id", "seq", "kind", "payload"], "event_invalid");
278
- if (value.run_id !== runId || !Number.isInteger(value.seq) || value.seq !== expectedSeq ||
279
- !(EVENT_KINDS.includes(value.kind) || RETIRED_EVENT_KINDS.includes(value.kind)) ||
280
- !value.payload || typeof value.payload !== "object" ||
281
- Array.isArray(value.payload)) {
282
- throw new CliError("event_sequence_invalid", `Expected event sequence ${expectedSeq}`);
283
- }
284
- if (value.payload.evidence_dag !== undefined) {
285
- validateEvidenceDag(value.payload.evidence_dag, runId);
286
- }
287
- return value;
288
- }
289
-
290
- function evidenceReplayInvalid(message) {
291
- throw new CliError("evidence_replay_invalid", `EvidenceDAG ${message}`);
292
- }
293
-
294
192
  function exactKeys(value, keys) {
295
193
  return value && typeof value === "object" && !Array.isArray(value)
296
194
  && Object.keys(value).sort().join("\n") === [...keys].sort().join("\n");
297
195
  }
298
196
 
299
- export function validateEvidenceDag(value, runId) {
300
- if (!exactKeys(value, ["id", "schema_version", "run_id", "nodes", "edges"])) {
301
- evidenceReplayInvalid("shape is invalid");
302
- }
303
- if (value.schema_version !== "evidence-dag.v1" || value.run_id !== runId ||
304
- typeof value.id !== "string" || !value.id || !Array.isArray(value.nodes) ||
305
- !Array.isArray(value.edges)) {
306
- evidenceReplayInvalid("identity or arrays are invalid");
307
- }
308
- const digest = createHash("sha256").update(canonicalJson({
309
- schema_version: value.schema_version, run_id: value.run_id,
310
- nodes: value.nodes, edges: value.edges,
311
- }).trimEnd(), "utf8").digest("hex");
312
- if (value.id !== `evidence-dag:sha256:${digest}`) evidenceReplayInvalid("id seal is invalid");
313
- return value;
314
- }
315
-
316
197
  /**
317
198
  * The material a submit selects: the composer's exact shape (one exact-extract selection per
318
199
  * attached source, both lists in source order). Absent keeps the Project's carried sources.
@@ -339,8 +220,8 @@ export function submissionMaterial(selections) {
339
220
  return { attachments: sorted.map(s => ({ ...s.source_handle })), selections: sorted };
340
221
  }
341
222
 
342
- export async function parseSse(response, runId, onEvent = null, startSeq = 0, guard = null) {
343
- if (!Number.isSafeInteger(startSeq) || startSeq < 0 || startSeq >= MAX_EVENTS) {
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) {
344
225
  throw new CliError("cursor_invalid", "Event cursor is outside the supported history bound");
345
226
  }
346
227
  if (!response.body) throw new CliError("sse_invalid", "Event response has no body");
@@ -395,9 +276,8 @@ export async function parseSse(response, runId, onEvent = null, startSeq = 0, gu
395
276
  throw new CliError("sse_invalid", "SSE metadata disagrees with event data");
396
277
  }
397
278
  events.push(validateEvent(refuseSecretValue(value), runId, startSeq + events.length));
398
- guard?.(events.at(-1));
399
279
  await onEvent?.(events.at(-1));
400
- if (startSeq + events.length > MAX_EVENTS) throw new CliError("response_too_large", "Event count exceeds limit");
280
+ if (events.length + startSeq - FIRST_EVENT_SEQ > MAX_EVENTS) throw new CliError("response_too_large", "Event count exceeds limit");
401
281
  terminalSeen = events.at(-1).kind === "terminal";
402
282
  }
403
283
  if (Buffer.byteLength(buffer, "utf8") > MAX_FRAME_BYTES) {
@@ -465,8 +345,7 @@ export class VecteurClient {
465
345
  ...(accept ? { Accept: accept } : {}),
466
346
  ...(acceptEncoding ? { "Accept-Encoding": acceptEncoding } : {}),
467
347
  ...(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.
348
+ // This reader advertises the highest stored wire version the owner declares.
470
349
  ...(!anonymousReadiness ? { [WIRE_READER_HEADER]: String(WIRE_READER_VERSION) } : {}),
471
350
  },
472
351
  body: rawBody ?? (body === undefined ? undefined : JSON.stringify(body)),
@@ -533,8 +412,8 @@ export class VecteurClient {
533
412
  const reset = new Date(limit.reset_at * 1000).toISOString().replace(".000Z", "Z");
534
413
  ownerMessage = `Customer cost limit reached; binding=${binding}; reset=${reset} UTC; next=${limit.recovery.join(",")}`;
535
414
  }
536
- if (candidate === WIRE_VERSION_UNSUPPORTED) {
537
- ownerMessage = "this Run is stored in a RunWire version this CLI cannot read; next: vecteur update";
415
+ if (candidate === "wire_version_unsupported") {
416
+ ownerMessage = "this Run is stored in a wire version this CLI cannot read; next: vecteur update";
538
417
  }
539
418
  if (["pat_expired", "pat_invalid", "pat_revoked"].includes(candidate)) {
540
419
  ownerMessage = "credential is expired or revoked; next: vecteur login";
@@ -542,8 +421,8 @@ export class VecteurClient {
542
421
  if (candidate === "pat_ancestry_inactive") {
543
422
  ownerMessage = "seat or Organization is inactive; next: contact your Organization owner or Vecteur support";
544
423
  }
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
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
547
426
  && error.message.length <= 512 && !/[\r\n\0]/.test(error.message)) {
548
427
  ownerMessage = error.message;
549
428
  }
@@ -665,35 +544,6 @@ export class VecteurClient {
665
544
  return value;
666
545
  }
667
546
 
668
- async runControl(runId, control, signal = undefined) {
669
- const value = await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/controls`, { body: control, signal });
670
- if (!validateRunControl(value) || value.id !== control.id) throw new CliError("control_invalid", "Malformed control acknowledgement");
671
- return value;
672
- }
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
-
690
- async clarificationAnswer(runId, questionId, answers, signal = undefined) {
691
- const value = await this.#json("POST", `/api/runs/${encodeURIComponent(runId)}/clarifications/${encodeURIComponent(questionId)}/answer`,
692
- { body: { answers }, signal });
693
- if (!validateRunAck(value) || value.run_id !== runId) throw new CliError("run_ack_invalid", "Malformed answer acknowledgement");
694
- return value;
695
- }
696
-
697
547
  async inputAdd(projectId, bytes, contentType, signal = undefined) {
698
548
  const value = await this.#json("POST", `/api/projects/${encodeURIComponent(projectId)}/inputs`, {
699
549
  rawBody: bytes, contentType, signal,
@@ -806,56 +656,6 @@ export class VecteurClient {
806
656
  }
807
657
  }
808
658
 
809
- async projectionGet(projectId, runId, projection, onChunk, signal = undefined) {
810
- const ref = projection?.payload_ref;
811
- if (typeof projectId !== "string" || !projectId || typeof runId !== "string" || !runId
812
- || projection?.kind !== "transfer_table" || projection?.run_id !== runId
813
- || projection?.project_id !== projectId
814
- || !/^projection-[0-9a-f]{64}$/.test(projection?.projection_id ?? "")
815
- || ref?.schema !== "vecteur.owner-transfer-table.v1"
816
- || ref?.media_type !== "application/vnd.vecteur.owner-transfer-table+json"
817
- || !/^[0-9a-f]{64}$/.test(ref?.payload_sha256 ?? "")
818
- || typeof onChunk !== "function") {
819
- throw new CliError("projection_invalid", "projection get requires a sealed transfer table on this Run");
820
- }
821
- const route = `/api/projects/${encodeURIComponent(projectId)}/runs/${encodeURIComponent(runId)}`
822
- + `/projections/${encodeURIComponent(projection.projection_id)}/payload`;
823
- const response = await this.request("GET", route, {
824
- accept: ref.media_type, acceptEncoding: "identity", signal,
825
- });
826
- try {
827
- if (response.headers.get("content-type")?.split(";", 1)[0] !== ref.media_type
828
- || (response.headers.get("content-encoding") ?? "identity").toLowerCase() !== "identity") {
829
- throw new CliError("projection_invalid", "Server returned the wrong projection media type");
830
- }
831
- const disposition = response.headers.get("x-vecteur-projection-disposition");
832
- if (disposition !== "current" && disposition !== "historical") {
833
- throw new CliError("projection_invalid", "Server returned no valid projection disposition");
834
- }
835
- const declared = response.headers.get("content-length");
836
- if (declared === null || !/^(?:0|[1-9][0-9]*)$/.test(declared)
837
- || Number(declared) > 256 * 1024 || !response.body) {
838
- throw new CliError("projection_invalid", "Projection byte length is invalid");
839
- }
840
- const digest = createHash("sha256");
841
- let bytes = 0;
842
- for await (const chunk of response.body) {
843
- response[RESPONSE_ACTIVITY]?.();
844
- bytes += chunk.byteLength;
845
- if (bytes > Number(declared)) throw new CliError("projection_invalid", "Projection exceeds its declared size");
846
- digest.update(chunk);
847
- await onChunk(chunk);
848
- }
849
- if (bytes !== Number(declared) || digest.digest("hex") !== ref.payload_sha256) {
850
- throw new CliError("projection_invalid", "Projection bytes differ from RunWire");
851
- }
852
- return { projection_id: projection.projection_id, project_id: projectId,
853
- run_id: runId, content_type: ref.media_type, bytes, disposition };
854
- } finally {
855
- response[RELEASE_TIMEOUT]?.();
856
- }
857
- }
858
-
859
659
  /**
860
660
  * The Project's newest Run from the owner page — the record the web chains on
861
661
  * (`CanvasPage.vue` designHead). Its public `state_hash` is the design head once the Run is
@@ -871,7 +671,7 @@ export class VecteurClient {
871
671
  + "next: continue in the web app, or pass --parent <state-hash>");
872
672
  }
873
673
  // Client-local presentation overlay, as in the web transcript. Never write this
874
- // timestamp into the immutable RunWire response or send it back to the server.
674
+ // timestamp into the immutable run record or send it back to the server.
875
675
  return newest ? { ...newest.response, accepted_at: newest.accepted_at, ask: newest.request.ask } : null;
876
676
  }
877
677
 
@@ -881,16 +681,15 @@ export class VecteurClient {
881
681
  const page = await this.#json("GET", `/api/projects/${encodeURIComponent(projectId)}/runs?${query}`, { signal });
882
682
  if (!exactKeys(page, ["runs", "next_before"]) || !Array.isArray(page.runs) || page.runs.length > limit
883
683
  || (page.next_before !== null && typeof page.next_before !== "string")
884
- || page.runs.some(row => row?.request?.project_id !== projectId || typeof row.request.ask !== "string"
885
- || !validateAdmitted(row.response) || !isStateHash(row.response.state_hash))) {
684
+ || page.runs.some(row => row?.request?.project_id !== projectId || typeof row.request.ask !== "string")) {
886
685
  throw new CliError("project_runs_invalid", "Server returned malformed Project run history");
887
686
  }
888
- for (const row of page.runs) row.response.events.forEach((event, seq) => validateEvent(event, row.response.run_id, seq));
687
+ for (const row of page.runs) validateRun(row.response);
889
688
  return page;
890
689
  }
891
690
 
892
691
  /** 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 } = {}) {
692
+ async runStart(projectId, ask, { requestKey, parentStateHash, attachments, selections, signal } = {}) {
894
693
  let parent = parentStateHash;
895
694
  try {
896
695
  if (!isRequestKey(requestKey)) throw new CliError("request_key_invalid", "request_key must be 8–64 letters, digits, _ or -");
@@ -907,8 +706,7 @@ export class VecteurClient {
907
706
  }
908
707
  material = { ...material, attachments };
909
708
  }
910
- const body = { ask, ...material, parent_state_hash: parent, ui_context: null,
911
- ...(intent === undefined ? {} : { intent }), ...(executor ? { local_exec: executor.descriptor } : {}) };
709
+ const body = { ask, ...material, parent_state_hash: parent, ui_context: null };
912
710
  return await withAdmissionLock(() => this.#startAdmission(projectId, body, requestKey, signal), this.localEnv ?? process.env);
913
711
  } catch (error) { throw this.#startFailure(error, requestKey, parent); }
914
712
  }
@@ -926,14 +724,14 @@ export class VecteurClient {
926
724
 
927
725
  async #startAdmission(projectId, body, key, signal) {
928
726
  const env = this.localEnv ?? process.env;
929
- const id = body.local_exec ? null : admissionIntent(this.config.origin, projectId, key, body, env);
727
+ const id = admissionIntent(this.config.origin, projectId, key, body, env);
930
728
  try {
931
729
  const ack = await this.runAdmit(projectId, body, key, signal);
932
730
  if (!validateRunAck(ack)) throw new CliError("run_ack_invalid", "Server returned malformed run acknowledgement");
933
- if (id) admissionResolved(id, env);
731
+ admissionResolved(id, env);
934
732
  return { ...ack, parent_state_hash: body.parent_state_hash };
935
733
  } catch (error) {
936
- if (id && (error.admission === "refused" || ["state_fork", "state_busy"].includes(error.code))) admissionResolved(id, env);
734
+ if (error.admission === "refused" || ["state_fork", "state_busy", ...OWNER_WORDED].includes(error.code)) admissionResolved(id, env);
937
735
  if (error instanceof CliError && ["state_fork", "state_busy"].includes(error.code)) {
938
736
  throw await this.#admissionRefused(error.code, projectId, body.parent_state_hash, signal);
939
737
  }
@@ -959,7 +757,6 @@ export class VecteurClient {
959
757
  throw new CliError("request_key_reused", "This request key already names a different ask, parent, Project or attachment set");
960
758
  }
961
759
  if (saved.version !== 1 || saved.request_key !== requestKey || saved.body?.ask !== ask
962
- || saved.body?.local_exec !== undefined
963
760
  || saved.body?.parent_state_hash !== parent || saved.body?.ui_context !== null
964
761
  || canonicalJson(submissionMaterial(saved.body?.selections)) !== canonicalJson({
965
762
  attachments: saved.body?.attachments, ...(saved.body?.selections ? { selections: saved.body.selections } : {}) })) {
@@ -992,24 +789,16 @@ export class VecteurClient {
992
789
  } catch (error) { throw this.#startFailure(error, requestKey, parent); }
993
790
  }
994
791
 
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 });
999
- try {
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; }
1003
- } catch (error) {
1004
- throw admittedFailure(error, value.run_id);
1005
- }
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); }
1006
797
  }
1007
798
 
1008
799
  async runStatus(runId, signal = undefined) {
1009
800
  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 };
801
+ return { run_id: record.run_id, terminal: record.terminal, last_seq: record.events.at(-1)?.seq ?? -1 };
1013
802
  }
1014
803
 
1015
804
  async #admissionRefused(code, projectId, sent, signal) {
@@ -1017,11 +806,7 @@ export class VecteurClient {
1017
806
  try { newest = await this.projectNewestRun(projectId, signal); } catch { newest = undefined; }
1018
807
  if (code === "state_busy" && newest?.terminal === "") {
1019
808
  const run = newest.run_id;
1020
- const question = newest.events.filter((event) => event.kind === "clarification").at(-1);
1021
- const waiting = question?.payload?.state === "requested"
1022
- ? ` [waiting for an answer: ${this.config.origin}/dashboard/${encodeURIComponent(projectId)}?run=${encodeURIComponent(run)}]`
1023
- : "";
1024
- 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}; `
1025
810
  + `nothing was admitted; next: vecteur run get ${run}`);
1026
811
  }
1027
812
  if (code === "state_fork" && newest !== undefined) {
@@ -1051,16 +836,11 @@ export class VecteurClient {
1051
836
 
1052
837
  async runGet(runId, signal = undefined) {
1053
838
  const value = await this.#json("GET", `/api/runs/${encodeURIComponent(runId)}`, { signal });
1054
- if (!validateAdmitted(value) || value.run_id !== runId) {
1055
- throw new CliError("run_invalid", "Server returned malformed run record");
1056
- }
1057
- value.events.forEach((event, seq) => validateEvent(event, runId, seq));
1058
- validateChildRows(value.events, value.stored_wire_version);
1059
- return value;
839
+ return validateRun(value, runId);
1060
840
  }
1061
841
 
1062
842
  async runEvents(runId, onEvent = null, signal = undefined, priorEvents = []) {
1063
- priorEvents.forEach((event, seq) => validateEvent(event, runId, seq));
843
+ priorEvents.forEach((event, index) => validateEvent(event, runId, FIRST_EVENT_SEQ + index));
1064
844
  if (priorEvents.length > MAX_EVENTS) throw new CliError("response_too_large", "Event count exceeds limit");
1065
845
  if (priorEvents.at(-1)?.kind === "terminal") {
1066
846
  const direct = await this.runGet(runId, signal);
@@ -1072,7 +852,7 @@ export class VecteurClient {
1072
852
  const response = await this.request("GET", `/api/runs/${encodeURIComponent(runId)}/events`, {
1073
853
  accept: "text/event-stream",
1074
854
  signal,
1075
- lastEventId: priorEvents.length ? priorEvents.length - 1 : undefined,
855
+ lastEventId: priorEvents.length ? priorEvents.at(-1).seq : undefined,
1076
856
  });
1077
857
  let events;
1078
858
  let streamedVersion;
@@ -1083,11 +863,9 @@ export class VecteurClient {
1083
863
  }
1084
864
  streamedVersion = Number(response.headers.get(STORED_WIRE_VERSION_HEADER));
1085
865
  if (!STORED_WIRE_VERSIONS.includes(streamedVersion)) {
1086
- throw new CliError("sse_invalid", "Event stream declares no known stored RunWire version");
866
+ throw new CliError("sse_invalid", "Event stream declares no known stored wire version");
1087
867
  }
1088
- const guard = rowGuard(streamedVersion);
1089
- priorEvents.forEach(guard);
1090
- events = [...priorEvents, ...await parseSse(response, runId, onEvent, priorEvents.length, guard)];
868
+ events = [...priorEvents, ...await parseSse(response, runId, onEvent, FIRST_EVENT_SEQ + priorEvents.length)];
1091
869
  } catch (error) {
1092
870
  if (error?.name === "AbortError") {
1093
871
  if (signal?.aborted) throw new CliError("request_cancelled", "Following the Run was detached");
@@ -1104,13 +882,9 @@ export class VecteurClient {
1104
882
  }
1105
883
  const direct = await this.runGet(runId, signal);
1106
884
  if (JSON.stringify(events) !== JSON.stringify(direct.events)
1107
- || streamedVersion !== direct.stored_wire_version) {
885
+ || (direct.stored_wire_version !== undefined && streamedVersion !== direct.stored_wire_version)) {
1108
886
  throw new CliError("record_mismatch", "Event stream disagrees with direct replay");
1109
887
  }
1110
- const eventTerminal = events.at(-1).payload.state ?? events.at(-1).payload.terminal;
1111
- if (eventTerminal !== direct.terminal) {
1112
- throw new CliError("terminal_mismatch", "Terminal event disagrees with direct record");
1113
- }
1114
888
  return direct;
1115
889
  }
1116
890
 
package/src/commands.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { withAdmissionLock } from "./localfiles.js";
2
2
  import { CliError } from "./errors.js";
3
- import { runView, runBlocks, blockText } from "./blocks.js";
3
+ import { runBlocks, blockText } from "./blocks.js";
4
4
  import { openBrowser } from "./browser.js";
5
5
  import { diagnose } from "./diagnostics.js";
6
6
  import { humanCost, terminalText } from "./format.js";
7
7
  import { preferences, savePreferences } from "./preferences.js";
8
8
 
9
- export const SHORTCUTS = `Enter sends when ready; while running it offers steering or keeps the draft.
9
+ export const SHORTCUTS = `Enter sends when ready; while a Run is working it keeps the draft.
10
10
  Alt+Enter / Ctrl+J newline; backslash then Enter is the portable fallback.
11
11
  Bracketed paste never sends. Plain/dumb multiline chunks stay drafts; a split-read
12
12
  lone CR/CRLF is indistinguishable from Enter and can send.
@@ -30,13 +30,12 @@ add("offline", "Draft without any network activity", s => {
30
30
  if (s.busy && !s.loginController) throw new CliError("session_busy", "Wait for this action to finish before disconnecting; your draft is kept");
31
31
  s.workOffline();
32
32
  });
33
- add("exec", "Allow local bash commands, or revoke immediately", (s, argument) => s.execConsent(argument), { argument: "on|off", requires: "login" });
34
33
  add("resume", "Reconnect or reconcile an interrupted ask", s => s.resume());
35
34
  add("quit", "Save draft and detach; cloud Run continues", s => s.close(), { aliases: ["exit"] });
36
35
  add("drafts", "Recover a saved draft", s => s.recoverDraft());
37
36
  add("clear", "Clear this draft; Ctrl+_ restores the edit", s => { s.lastClearedDraft = s.draft; s.setDraft(""); });
38
- add("mode", "Lead, model, execution location and payer", s => s.message(s.modeDetails()));
39
- add("model", "Choose the next Run's server model or route", s => s.modelChoice(), { requires: "login" });
37
+ add("mode", "Model, execution location and payer", s => s.message(s.modeDetails()));
38
+ add("model", "Choose the next Run's model", s => s.modelChoice(), { requires: "login" });
40
39
  add("usage", "Read the Project's server-authored usage", async s => {
41
40
  if (!s.project) throw new CliError("project_unavailable", "Choose a Project first with /project");
42
41
  const client = s.client, project = s.project;
@@ -108,48 +107,13 @@ add("download", "Save and verify a result file", (s, argument) => {
108
107
  if (!match) throw new CliError("usage_invalid", "Use /download <artifact number> [output path]");
109
108
  return s.download(Number(match[1]), match[2]);
110
109
  }, { 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" });
120
110
  add("export", "Export the answer, Run record and verified files to a new folder", (s, path) => s.exportRun(path || undefined), { argument: "[folder]", requires: "login" });
121
111
  add("copy", "Copy the exact answer or save it to a new file", (s, path) => s.copy(path || undefined), { argument: "[path]" });
122
- add("answer", "Answer the current clarification", s => s.answer(), { requires: "question" });
123
- add("steer", "Send an instruction to the running Run", (s, text) => s.steer(text), { argument: "<instruction>", required: true, requires: "run" });
124
- add("answer-now", "Ask the running Run to conclude", s => s.steer(""), { requires: "run" });
125
112
  add("cancel", "Request cancellation; keep completed work", s => s.cancel(), { requires: "run" });
126
- add("details", "Read the current or numbered block in full", async (s, argument) => {
113
+ add("details", "Read the current or numbered block in full", (s, argument) => {
127
114
  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")));
115
+ const block = argument ? blocks[Number(argument) - 1] : blocks.findLast(b => b.kind === "tool") ?? blocks.at(-1);
116
+ s.message(block ? terminalText(blockText(block, { full: true })) : "No block details yet.");
153
117
  }, { argument: "[number]" });
154
118
  add("handoff", "Open your Claude Code or Codex here with Vecteur attached", (s, vendor) => {
155
119
  if (!["claude", "codex"].includes(vendor)) throw new CliError("usage_invalid", "Use /handoff claude or /handoff codex");
@@ -172,7 +136,6 @@ export function unavailable(row, session) {
172
136
  if (!session.account) return "Sign in — /login";
173
137
  if (row.requires === "login") return "";
174
138
  if (session.project?.role === "VIEWER") return "Read-only Project";
175
- if (row.requires === "question") return runView(session.run).question ? "" : "No pending question";
176
139
  return session.run?.open ? "" : "No running Run";
177
140
  }
178
141
  export function completions(query = "", session) {