@vecteur/cli 0.11.1 → 0.13.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/session.js CHANGED
@@ -1,63 +1,23 @@
1
- import { Executor } from "./executor.js";
2
1
  import { EventEmitter } from "node:events";
3
- import { createHash, randomUUID } from "node:crypto";
4
- import { spawn } from "node:child_process";
5
- import { mkdir, open, readFile, readdir, writeFile } from "node:fs/promises";
6
- import { basename, isAbsolute, join, relative, resolve } from "node:path";
2
+ import { randomUUID } from "node:crypto";
3
+ import { writeFile } from "node:fs/promises";
4
+ import { basename, isAbsolute, relative, resolve } from "node:path";
7
5
  import { VecteurClient, CliError, configuration, delay, isTokenShaped, requestTimeout,
8
6
  resolveOrigin, shouldOpenBrowser, waitForDeviceAuthorization } from "./client.js";
9
7
  import { readCredentials, writeCredentials, clearCredentials } from "./credentials.js";
10
8
  import { FolderRegistry, UNSIGNED_ACCOUNT } from "./folders.js";
11
- import { runView } from "./blocks.js";
12
- import { produceIntent } from "./produce.js";
9
+ import { runView, artifactRows } from "./blocks.js";
13
10
  import { downloadArtifact, exportRun } from "./download.js";
14
- import { humanRun, runSections, safeArtifactName, stopViewOf, turnFooter, terminalText, proposalReview, adoptionHint } from "./format.js";
15
- import { localProcessEnv, withLocalLock, withAdmissionLock, executionGrant, checkGrantLive, qualify, currentGrant, createGrant, prepareConsent, checkConsent, endGrants, pinCheck, selectionMetadata,
11
+ import { humanRun, runSections, turnFooter, terminalText, proposalReview, adoptionHint } from "./format.js";
12
+ import { withLocalLock, withAdmissionLock, qualify, currentGrant, createGrant, prepareConsent, checkConsent, endGrants, pinCheck, selectionMetadata,
16
13
  readConfined, recordUpload, discover, nameOffers, tombstoned, writeNewConfined,
17
14
  reconcileWrites, reconcileAdmissions, inspectTarget, observeTargetMetadata, observeTargets, proposals, proposalName, writeProposalConfined, downloadLocalArtifact } from './localfiles.js';
18
- import { artifactRows } from './blocks.js';
19
- import { ARTIFACT_MEDIA_TYPES, CATALOGUE_ENVELOPE_SHA256, MODEL_CATALOGUE, PRODUCT_ROUTES } from "./contract.js";
15
+ import { ARTIFACT_MEDIA_TYPES, MODEL_CHOICES } from "./contract.js";
16
+ import { OWNER_WORDED } from "./client.js";
20
17
  import { openBrowser } from "./browser.js";
21
18
 
22
- const PACKAGE_MARKER = ".vecteur-package.json";
23
- const FLAG = /^-{1,2}[A-Za-z][A-Za-z0-9-]*(=[A-Za-z0-9_.:-]+)?$/;
24
- const WORD = /^[A-Za-z0-9_.:\/-]+$/;
25
- const commandDisplay = command => JSON.stringify(command).replace(/[\p{Cc}\p{Cf}]/gu,
26
- character => character.split('').map(unit => '\\u'+unit.charCodeAt(0).toString(16).padStart(4, '0')).join(''));
27
-
28
- /** The folder holding kc.json: the package folder itself, or the one directory an unzipped archive made in it. */
29
- async function packageRoot(directory) {
30
- const entries = await readdir(directory, { withFileTypes: true });
31
- if (entries.some(entry => entry.isFile() && entry.name === "kc.json")) return directory;
32
- const dirs = entries.filter(entry => entry.isDirectory());
33
- if (dirs.length === 1) {
34
- const inner = join(directory, dirs[0].name);
35
- if ((await readdir(inner)).includes("kc.json")) return inner;
36
- }
37
- throw new CliError("package_invalid", "No kc.json in the package folder; unzip the package there first");
38
- }
39
-
40
- /** The approved process template: `python -m pytest` plus plain flags and paths inside the package. */
41
- export function approvedTemplate(manifest, root) {
42
- const argv = manifest?.test;
43
- if (!Array.isArray(argv) || argv[0] !== "python" || argv[1] !== "-m" || argv[2] !== "pytest") {
44
- throw new CliError("template_unapproved", "The declared test command must be: python -m pytest [flags] [paths]");
45
- }
46
- for (const item of [...argv.slice(3), ...(manifest.paths ?? [])]) {
47
- if (typeof item !== "string" || isAbsolute(item) || item.split(/[\\/]/).includes("..")
48
- || relative(root, resolve(root, item)).startsWith("..")) {
49
- throw new CliError("path_escape", `"${item}" leaves the package folder`);
50
- }
51
- if (!FLAG.test(item) && !WORD.test(item.replace(/\*/g, ""))) {
52
- throw new CliError("template_unapproved", `"${item}" is not a plain flag or path`);
53
- }
54
- }
55
- return argv;
56
- }
57
-
58
19
  export const NEW_FOLDER = "New folder — send an ask or /link an existing Project";
59
20
  const AUTH_ERRORS = new Set(["pat_expired", "pat_invalid", "pat_revoked"]);
60
- const MAX_QUIET_ROTATIONS = 30; // 30 x 120 s request bound: one hour of silence
61
21
  const TRANSIENT = new Set(["request_failed", "request_timeout", "terminal_invalid"]);
62
22
 
63
23
  /** One cloud session, two real renderers. It owns no terminal, device or native-agent runtime. */
@@ -75,12 +35,9 @@ export class Session extends EventEmitter {
75
35
 
76
36
  view(now = Date.now()) {
77
37
  const canEdit = this.project?.role !== "VIEWER";
78
- const activity = !canEdit && this.status === "Waiting for your answer" ? "Waiting for an editor" : this.status;
79
- this.projectionCache ??= {};
80
- const projection = runView(this.run, this.projectionCache, now);
81
- const requested = this.model ?? "auto";
82
- const modelLabel = MODEL_CATALOGUE.find(row => row.profile_id === requested)?.label
83
- ?? PRODUCT_ROUTES.find(row => row.route_id === requested)?.label ?? requested;
38
+ const activity = this.status;
39
+ const projection = runView(this.run, now);
40
+ const modelLabel = MODEL_CHOICES.find(row => row.route_id === (this.model ?? "auto"))?.label ?? this.model;
84
41
  const bound = this.binding?.state === "bound" && this.binding.projectId === this.project?.id;
85
42
  return { origin: this.origin, folder: bound ? relative(this.binding.folder.path, this.cwd) || "." : this.cwd,
86
43
  account: this.account, project: this.project,
@@ -89,12 +46,11 @@ export class Session extends EventEmitter {
89
46
  offline: this.offline, issue: this.issue, login: this.loginChallenge, release: this.release,
90
47
  // First use: signed in and online, the folder resolved to no binding/Project/Run, nothing pending.
91
48
  firstUse: !!this.account && !this.offline && !this.busy && !this.project && !this.run && this.status === NEW_FOLDER,
92
- attachments: this.attachments.map(item => ({ path: item.rel ?? item.path, size: item.size ?? item.bytes.length })),
93
- egress: this.attachments.length ? `Upload ${this.attachments.map(item => `${item.rel ?? item.path} (${item.size ?? item.bytes.length} B)`).join(", ")} to ${this.project?.name ?? "a new Project"} on ${this.origin}` : null,
94
- lead: "Laplace", location: "Vecteur cloud", model: modelLabel,
49
+ attachments: this.attachments.map(item => ({ path: item.rel, size: item.size })),
50
+ egress: this.attachments.length ? `Upload ${this.attachments.map(item => `${item.rel} (${item.size} B)`).join(", ")} to ${this.project?.name ?? "a new Project"} on ${this.origin}` : null,
51
+ location: "Vecteur cloud", model: modelLabel,
95
52
  run: projection, available: { submit: !this.offline && !!this.account && canEdit && !this.busy && !this.run?.open,
96
- cancel: !this.offline && !!this.account && canEdit && !!this.run?.open, steer: !this.offline && !!this.account && canEdit && !!this.run?.open && !projection.question,
97
- localExecution: false, nativeAgent: false } };
53
+ cancel: !this.offline && !!this.account && canEdit && !!this.run?.open } };
98
54
  }
99
55
 
100
56
  change() { if (!this.closed) this.emit("change", this.view()); }
@@ -132,7 +88,6 @@ export class Session extends EventEmitter {
132
88
  }
133
89
 
134
90
  workOffline() {
135
- this.executor?.stop(); this.execAllowed = false;
136
91
  this.cancelLogin(); this.cancelPrompt(); this.followController?.abort(); this.generation++;
137
92
  this.offline = true; this.issue = null;
138
93
  if (!this.registry) {
@@ -329,18 +284,23 @@ export class Session extends EventEmitter {
329
284
  this.run = { ...newest, open: !newest.terminal };
330
285
  if (newest.run_id !== this.lastPrintedRun && newest.ask !== undefined) this.message(newest.ask, "user");
331
286
  if (this.run.open) {
332
- this.status = runView(this.run, this.projectionCache).question ? "Waiting for your answer" : "Running";
287
+ this.status = "Running";
333
288
  this.change(); void this.follow().catch(error => this.report(error));
334
289
  }
335
- else { this.status = newest.terminal; if (this.announceRun()) await this.announceFooter(this.project.id); this.change(); await this.offerSaves(); }
290
+ else { this.status = newest.terminal; if (await this.announceRun()) await this.announceFooter(this.project.id); this.change(); await this.offerSaves(); }
336
291
  } else { this.run = null; this.change(); }
337
292
  }
338
293
  }
339
294
 
340
- announceRun(stopOffer = undefined) {
341
- if (this.lastPrintedRun === this.run?.run_id) return false;
295
+ async announceRun() {
296
+ const run = this.run;
297
+ if (!run?.terminal || this.lastPrintedRun === run.run_id) return false;
298
+ // At a limit the server says what this reader may do; a failed read names no plan and never fails the Run.
299
+ const stopOffer = run.terminal === "budget" ? await this.client.stopOffer(run.run_id) : undefined;
300
+ if (this.run !== run || this.closed) return false;
342
301
  const options = { stopOffer, origin: this.origin };
343
- this.message(this.run?.terminal ? humanRun(this.run, options) : runView(this.run).transcript, "answer", { runId: this.run?.run_id, sections: runSections(this.run, options) }); this.lastPrintedRun = this.run?.run_id;
302
+ this.message(humanRun(run, options), "answer", { runId: run.run_id, sections: runSections(run, options) });
303
+ this.lastPrintedRun = run.run_id;
344
304
  return true;
345
305
  }
346
306
 
@@ -392,26 +352,14 @@ export class Session extends EventEmitter {
392
352
  : await this.client.projectCreate(pending.name, pending.workspaceId, undefined, pending.key);
393
353
  if (!pending.projectId) await withAdmissionLock(() => {
394
354
  if(consent)checkConsent(this.localPin(),consent.epoch,this.env);
395
- // /exec consent given before this first send has no Project yet and completeCreation ends folder grants:
396
- // re-issue it for the new Project only if the consented generation is still live (revoke/relink stay fatal).
397
- const carry = this.execGrant?.projectId === undefined && this.execGrant;
398
- if (carry) checkGrantLive(carry, this.localPin(), this.env);
399
355
  this.registry.completeCreation(pending.key, project.id);
400
356
  if(consent)consent.epoch=prepareConsent(this.localPin(),this.env);
401
- if (carry) this.execGrant = executionGrant({ ...this.localPin(), projectId: project.id, role: project.role }, this.env);
402
357
  },this.env);
403
358
  this.project = project; this.binding = this.registry.binding(); this.provenance = "binding";
404
359
  return project;
405
360
  }
406
361
 
407
- /** v5 §2.5 explicit Produce: sends one ask whose named specialist child the host starts before Engineering's turn; its
408
- * rows carry the specialist's label. `produceIntent` owns the grammar and the closed entries. */
409
- produce(argument) {
410
- const { ask, intent } = produceIntent(argument);
411
- return this.submit(ask, intent);
412
- }
413
-
414
- async submit(text = this.draft, intent = undefined) {
362
+ async submit(text = this.draft) {
415
363
  if (this.busy) throw new CliError("session_busy", "The current submission is still being reconciled");
416
364
  if (!text.trim()) return;
417
365
  if (this.offline || !this.account) {
@@ -423,25 +371,24 @@ export class Session extends EventEmitter {
423
371
  return;
424
372
  }
425
373
  if (this.run?.open) {
426
- this.setDraft(text); const run = this.run;
427
- const action = await this.choose("This Run is still working", [
428
- { label: "Keep drafting the next question", value: "draft" }, { label: "Send as steering to this Run", value: "steer" },
429
- ]);
430
- if (action === "steer" && this.run === run && run.open) await this.steer(text);
374
+ // One turn at a time: the reply to a question is the next turn, after this one closes.
375
+ this.setDraft(text); this.status = "This Run is still working — draft kept; send it when the Run ends"; this.change();
431
376
  return;
432
377
  }
433
378
  this.setDraft(text);
379
+ const blank = this.blanks?.find(known => text.includes(known));
380
+ if (blank) { this.status = `Replace ${blank} with your own value, then send`; this.change(); return; } // the server refuses it too, later
434
381
  this.registry?.saveDraft(text);
435
382
  const draftRef = structuredClone(this.registry?.draftRef ?? null);
436
383
  this.busy = true; this.status = "Submitting"; this.change();
437
384
  try {
438
- if (this.execPending || this.registry?.state().pendingRun) throw new CliError("submission_pending", "Use /resume to resolve the interrupted submission; your new draft is kept");
385
+ if (this.registry?.state().pendingRun) throw new CliError("submission_pending", "Use /resume to resolve the interrupted submission; your new draft is kept");
439
386
  if (this.project?.role === 'VIEWER') throw new CliError('role_forbidden', 'Editor access is required to ask Vecteur');
440
387
  if (await this.offerAttachments(text) === false) { this.status = 'Draft kept — named files not offered'; return; }
441
388
  const consentAccount=this.account.id;
442
389
  const destination = { origin: this.origin, id: this.project?.id, name: this.project?.name ?? this.projectName ?? basename(this.cwd) };
443
390
  let consent = false;
444
- if (this.attachments.some(f => !f.generated)) {
391
+ if (this.attachments.length) {
445
392
  const grant = this.project && currentGrant(this.localPin(), this.env);
446
393
  if (!grant) {
447
394
  const epoch=await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env);
@@ -451,11 +398,10 @@ export class Session extends EventEmitter {
451
398
  }
452
399
  const project = await this.ensureProject(consent || undefined);
453
400
  if (project.role === "VIEWER") throw new CliError("role_forbidden", "Editor access is required to ask Vecteur");
454
- if (this.attachments.some(f => !f.generated) && consent && (destination.origin !== this.origin || (destination.id ? destination.id !== project.id : destination.name !== project.name))) {
401
+ if (this.attachments.length && consent && (destination.origin !== this.origin || (destination.id ? destination.id !== project.id : destination.name !== project.name))) {
455
402
  if (!await this.confirmFiles({ origin: this.origin, id: project.id, name: project.name })) return;
456
403
  }
457
- if (this.execAllowed === undefined) await this.execConsent("on");
458
- const executor = await withAdmissionLock(async () => {
404
+ await withAdmissionLock(async () => {
459
405
  const newest = await this.client.projectNewestRun(project.id);
460
406
  const checkDestination=()=>{
461
407
  if(this.project?.id!==project.id || this.origin!==destination.origin || this.account?.id!==consentAccount) throw new CliError('grant_changed','Upload destination changed; draft kept');
@@ -467,20 +413,20 @@ export class Session extends EventEmitter {
467
413
  }
468
414
  const selections = [];
469
415
  let grant;
470
- if (this.attachments.some(f => !f.generated)) {
416
+ if (this.attachments.length) {
471
417
  grant = currentGrant(this.localPin(), this.env);
472
418
  if (!grant) { if (!consent) throw new CliError('grant_changed', 'Permission changed; confirm files again'); grant = createGrant(this.localPin(), this.env, consent.epoch); }
473
419
  }
474
420
  for (const item of this.attachments) {
475
421
  checkDestination();
476
- if (!item.generated) pinCheck(grant, this.localPin(), this.env);
422
+ pinCheck(grant, this.localPin(), this.env);
477
423
  if (item.generation !== undefined && item.generation !== grant.generation) throw new CliError('grant_changed', 'Selection withdrawn; select it again');
478
- const file = item.generated ? {rel:basename(item.path),bytes:item.bytes,size:item.bytes.length,media:item.media} : readConfined(grant, item.rel, this.env, { selected: item });
479
- if (!item.generated) pinCheck(grant, this.localPin(), this.env);
424
+ const file = readConfined(grant, item.rel, this.env, { selected: item });
425
+ pinCheck(grant, this.localPin(), this.env);
480
426
  this.message(`Upload ${file.rel} (${file.size} B) to ${project.name} on ${this.origin}`);
481
427
  item.source = await this.client.inputAdd(project.id, file.bytes, file.media);
482
428
  checkDestination();
483
- if (!item.generated) recordUpload(grant, file, item.source, this.env);
429
+ recordUpload(grant, file, item.source, this.env);
484
430
  const offer = item.source.offer ?? await this.client.inputOffer(project.id, item.source);
485
431
  if (!offer.extracts.length) throw new CliError("extraction_unavailable", "This file has no selectable extracts");
486
432
  selections.push({ source_handle: { cas_ref: item.source.cas_ref, acquisition_ref: item.source.acquisition_ref },
@@ -490,30 +436,9 @@ export class Session extends EventEmitter {
490
436
  || a.source_handle.acquisition_ref.localeCompare(b.source_handle.acquisition_ref));
491
437
  const body = { ask: text, attachments: selections.map(item => item.source_handle),
492
438
  parent_state_hash: newest?.state_hash ?? null, ui_context: { layout: 'folder' },
493
- ...(selections.length ? { selections } : {}), ...(this.model ? { model_choice: this.model } : {}),
494
- ...(intent === undefined ? {} : { intent }) };
495
- this.executor?.stop(); this.executor = null;
496
- if (this.execAllowed) {
497
- const pin = this.localPin();
498
- const grant = this.execGrant;
499
- pinCheck(grant, pin, this.env, { execution: true });
500
- this.executor = new Executor({ client: this.client, grant, pin: () => this.localPin(), env: this.env,
501
- session: this.execSessionPolicy ?? false, approve: ({ command, timeout, folder, signal }) => {
502
- const prompt = this.choose(
503
- `Run on this computer in ${JSON.stringify(folder)} (${timeout}s)?\n${commandDisplay(command)}`, [
504
- { label: "Allow once", value: "once" }, { label: "Allow for this session", value: "session" }, { label: "Decline", value: "decline" }], { liveTitle: `Run this bash command (${timeout}s)?` });
505
- const id = this.prompt?.id;
506
- const cancel = () => { if (id === this.prompt?.id) this.cancelPrompt(); };
507
- signal.addEventListener('abort', cancel, { once: true });
508
- return prompt.finally(() => signal.removeEventListener('abort', cancel));
509
- } });
510
- body.local_exec = this.executor.descriptor;
511
- }
512
- const pending = this.executor ? (this.execPending = { projectId: project.id, body, key: randomUUID() })
513
- : this.registry.reserveRun(project.id, body, draftRef);
514
- return this.admitPendingLocked(pending);
439
+ ...(selections.length ? { selections } : {}), ...(this.model ? { model_choice: this.model } : {}) };
440
+ return this.admitPendingLocked(this.registry.reserveRun(project.id, body, draftRef));
515
441
  }, this.env);
516
- this.startExecutor(executor);
517
442
  void this.follow().catch(error => this.report(error));
518
443
  } catch(error) {
519
444
  if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest();
@@ -523,59 +448,39 @@ export class Session extends EventEmitter {
523
448
  }
524
449
 
525
450
  async admitPending(pending) {
526
- let executor;
527
- try { executor = await withAdmissionLock(() => this.admitPendingLocked(pending), this.env); }
451
+ try { await withAdmissionLock(() => this.admitPendingLocked(pending), this.env); }
528
452
  catch(error) { if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest(); throw error; }
529
- this.startExecutor(executor);
530
453
  void this.follow().catch(error=>this.report(error));
531
454
  }
532
455
 
533
456
  async admitPendingLocked(pending) {
534
- const ephemeral = pending === this.execPending;
535
- if (!ephemeral && pending.body?.local_exec !== undefined) throw new CliError('admission_unresolved', 'Saved execution consent expired; observe the Project history');
536
457
  if (this.project?.id !== pending.projectId) {
537
458
  const project = await this.client.projectGet(pending.projectId);
538
459
  this.followController?.abort(); this.generation++; this.run = null; this.project = project; this.change();
539
460
  }
540
- if (ephemeral) {
541
- if (!this.executor) throw new CliError("admission_unresolved", "Executor consent ended; reconcile through Project history");
542
- this.executor.check();
543
- }
544
461
  let ack;
545
462
  try { ack = await this.client.runAdmit(pending.projectId, pending.body, pending.key); }
546
463
  catch (error) {
547
- if (["state_busy", "state_fork"].includes(error.code) || error.admission === "refused") {
548
- if (ephemeral) { this.execPending = null; this.executor?.stop(); }
549
- else this.registry.rejectRunAdmission(pending.key);
464
+ const worded = OWNER_WORDED.includes(error.code);
465
+ if (["state_busy", "state_fork"].includes(error.code) || error.admission === "refused" || worded) {
466
+ this.registry.rejectRunAdmission(pending.key);
550
467
  }
551
468
  if (["state_busy", "state_fork"].includes(error.code)) {
552
469
  throw new CliError(error.code, "Submission refused; draft kept. Review the latest Run and explicitly send again.");
553
470
  }
471
+ // A read-only (v5) Project or a retired door: the owner's own sentence, nothing admitted, draft kept.
472
+ if (worded) throw new CliError(error.code, `${error.message} Nothing was admitted; draft kept.`);
554
473
  // The owner marked this key as never admittable (nothing dispatched): release only this
555
474
  // reservation and keep the draft. Any other failure stays pending for /resume.
556
- if (error.admission === "refused") {
557
- if (error.code === "produce_unavailable") throw new CliError(error.code, `${error.message}. Draft kept.`);
558
- throw new CliError(error.code, "Submission refused before it ran; draft kept. Fix it and send again.");
559
- }
475
+ if (error.admission === "refused") throw new CliError(error.code, "Submission refused before it ran; draft kept. Fix it and send again.");
560
476
  throw error;
561
477
  }
562
- if (!ephemeral) this.registry.finishRunAdmission(pending.key);
563
- this.execPending = null;
478
+ this.registry.finishRunAdmission(pending.key);
564
479
  if (this.draft === pending.body.ask) { clearTimeout(this.draftTimer); this.draft = ""; }
565
480
  this.attachments = [];
566
481
  this.message(pending.body.ask, "user");
567
- this.run = { ...ack, ask: pending.body.ask, controls: [], events: [], terminal: "", open: true };
482
+ this.run = { ...ack, ask: pending.body.ask, events: [], terminal: "", open: true };
568
483
  this.status = "Running"; this.change();
569
- return ephemeral ? this.executor : null;
570
- }
571
-
572
- startExecutor(executor) {
573
- if (executor) {
574
- this.execPump = executor.pump(this.run.run_id).catch(error => {
575
- executor.stop();
576
- if (this.executor === executor) { this.execAllowed = false; this.execGrant = null; this.report(error); }
577
- });
578
- }
579
484
  }
580
485
 
581
486
  async resume() {
@@ -584,7 +489,6 @@ export class Session extends EventEmitter {
584
489
  if (!this.account || !this.registry) return this.initialize();
585
490
  await withAdmissionLock(() => reconcileAdmissions(this.client, this.origin, this.env), this.env);
586
491
  const state = this.registry.state();
587
- if (this.execPending) return this.admitPending(this.execPending);
588
492
  if (state.pendingRun) {
589
493
  this.busy = true; this.change();
590
494
  try { return await this.admitPending(state.pendingRun); }
@@ -598,97 +502,36 @@ export class Session extends EventEmitter {
598
502
  async follow() {
599
503
  this.followController?.abort();
600
504
  const controller = new AbortController(); this.followController = controller;
601
- const run = this.run, executor = this.executor; const generation = ++this.generation;
505
+ const run = this.run; const generation = ++this.generation;
602
506
  const projectId = this.project.id;
603
- let attempts = 0, quiet = 0;
604
- // Read independently of SSE activity: a quiet/waiting Run can receive controls in another terminal.
605
- let controlTimer, controlFailures = 0, controlState = "available";
606
- const current = () => !controller.signal.aborted && generation === this.generation && this.run === run && run.open;
607
- const refreshControls = async () => {
608
- let interval = 3000, permanent = false;
609
- try {
610
- const controls = await this.client.runControls(run.run_id, controller.signal);
611
- if (!current()) return;
612
- if (controlState !== "available") this.message("Controls available — live updates restored.");
613
- controlState = "available"; controlFailures = 0;
614
- if (JSON.stringify(run.controls) !== JSON.stringify(controls)) { run.controls = controls; this.change(); }
615
- } catch (error) {
616
- if (!current()) return;
617
- const transient = ["request_failed", "request_timeout", "http_429"].includes(error.code)
618
- || /^http_5\d\d$/.test(error.code) || error.status === 429 || error.status >= 500;
619
- permanent = !transient;
620
- interval = Math.min(1000 * 2 ** controlFailures++, 15000);
621
- const state = `${permanent ? "unavailable" : "retrying"}:${error.code}`;
622
- if (state !== controlState) this.message(`Controls unavailable (${error.code}) — ${permanent ? "live updates stopped" : "retrying"}.`);
623
- controlState = state;
624
- }
625
- if (current() && !permanent) controlTimer = setTimeout(refreshControls, interval);
626
- };
627
- void refreshControls();
628
- controller.signal.addEventListener("abort", () => clearTimeout(controlTimer), { once: true });
507
+ let attempts = 0;
629
508
  try {
630
509
  while (!this.closed && generation === this.generation && run?.open) {
631
510
  try {
632
511
  const direct = await this.client.runEvents(run.run_id, event => {
633
512
  if (generation !== this.generation) return;
634
- quiet = 0; run.events.push(event);
635
- this.status = runView(run, this.projectionCache).question ? "Waiting for your answer" : "Running";
636
- this.change();
513
+ run.events.push(event); this.status = "Running"; this.change();
637
514
  }, controller.signal, [...run.events]);
638
515
  if (generation !== this.generation) return;
639
- this.run = { ...direct, accepted_at: direct.run_id === run.run_id ? run.accepted_at : undefined, ask: run.ask, open: !direct.terminal };
640
- const stopped = direct.terminal ? stopViewOf(direct.events) : null;
641
- const stopOffer = stopped ? await this.client.stopOffer(direct.run_id, controller.signal) : undefined;
516
+ this.run = { ...direct, accepted_at: run.accepted_at, ask: run.ask, open: !direct.terminal };
517
+ this.status = direct.terminal === "budget" ? "Paused at a limit" : direct.terminal;
518
+ await this.announceRun();
642
519
  if (generation !== this.generation) return;
643
- if (stopped?.cause === "plan_limit") void this.client.stopEvent(direct.run_id, { event: "shown", surface: "cli" });
644
- this.status = stopped ? "Paused at a limit" : direct.terminal; this.announceRun(stopOffer);
645
520
  await this.announceFooter(projectId);
646
521
  this.change(); await this.offerSaves().catch(error=>this.report(error)); return;
647
522
  } catch (error) {
648
523
  if (controller.signal.aborted || this.closed || generation !== this.generation) return;
649
524
  if (AUTH_ERRORS.has(error.code)) { this.report(error); return; }
650
- // The SSE request rotates at its time bound even during a healthy clarification park.
651
- // The independent authenticated pump owns executor liveness; a poll failure stops it.
652
- // A stream that rotates MAX_QUIET_ROTATIONS times in a row without one event is wedged, not parked.
653
- if (error.code === "request_timeout" && executor && !executor.closed) {
654
- if (++quiet > MAX_QUIET_ROTATIONS) throw new CliError("event_stream_stalled", "The Run's event stream delivered nothing for too long; local execution stopped. /resume to reconnect.");
655
- attempts = 0;
656
- }
657
- else { this.executor?.stop(); this.execAllowed = false; }
658
525
  if (!TRANSIENT.has(error.code) || ++attempts > 5) throw error;
659
526
  this.status = "Connection lost — reconnecting to the same Run"; this.change();
660
527
  await delay(Math.min(500 * 2 ** attempts, 8_000), controller.signal);
661
528
  }
662
529
  }
663
- } finally {
664
- executor?.stop();
665
- if (this.executor === executor) {
666
- this.execSessionPolicy = executor?.session ?? false;
667
- this.executor = null;
668
- }
669
- clearTimeout(controlTimer); controller.abort();
670
- }
530
+ } finally { controller.abort(); }
671
531
  }
672
532
 
673
533
  attach(path) { return this.transition(() => this.selectAttachment(path)); }
674
534
 
675
- async execConsent(argument) {
676
- if (argument === "off") {
677
- this.execAllowed = false; this.execGrant = null; this.execSessionPolicy = false; this.executor?.stop('executor_revoked');
678
- this.message("Local execution revoked."); return;
679
- }
680
- if (argument !== "on") throw new CliError("usage_invalid", "Use /exec on or /exec off");
681
- qualify();
682
- const pin = this.localPin();
683
- const granted = await this.choose(`Allow Vecteur to run commands in ${pin.root.path}? Commands have your OS permissions, including network access and writes outside this folder. Only scanned output tails return to Vecteur.`,
684
- [{ label: "Allow, ask before each command", value: true }, { label: "No", value: false }]);
685
- this.execAllowed = granted;
686
- if (granted) this.execGrant = await withLocalLock(() => {
687
- if (this.project?.id !== pin.projectId || this.account?.id !== pin.accountId) throw new CliError("grant_changed", "Destination changed");
688
- return executionGrant(pin, this.env);
689
- }, this.env);
690
- }
691
-
692
535
  localPin() {
693
536
  return { origin: this.origin, accountId: this.account?.id, projectId: this.project?.id, role: this.project?.role,
694
537
  root: this.registry.folder, provenance: this.provenance ?? 'binding', binding: () => this.registry.binding(),
@@ -701,7 +544,7 @@ export class Session extends EventEmitter {
701
544
  }
702
545
 
703
546
  async confirmFiles(destination) {
704
- const files = this.attachments.filter(f=>!f.generated);
547
+ const files = this.attachments;
705
548
  return this.choose(`${this.fileConsentText(destination)}\nSend ${files.length} selected file${files.length===1?'':'s'}?\n${files.map(f=>`[x] ${f.rel} (${f.size} B)`).join('\n')}`, [
706
549
  { label: 'Yes, allow select and save-new', value: true }, { label: 'No, keep draft and selections', value: false },
707
550
  ], { liveTitle: `Send ${files.length} selected file${files.length===1?'':'s'}?` });
@@ -794,7 +637,6 @@ export class Session extends EventEmitter {
794
637
  }
795
638
 
796
639
  async revokeFiles() {
797
- this.executor?.stop(); this.execAllowed = false;
798
640
  this.requireLogin();
799
641
  return withLocalLock(() => {
800
642
  endGrants({origin:this.origin,accountId:this.account.id,root:this.registry.folder.path},this.env);
@@ -835,8 +677,8 @@ export class Session extends EventEmitter {
835
677
  const rows = artifactRows(runView(this.run).artifacts);
836
678
  const saved = this.account && this.project ? await this.scanLocalTargets() : [];
837
679
  this.message([
838
- ...this.attachments.map(item=>`Pending: ${terminalText(item.rel ?? item.path)} (${item.size ?? item.bytes.length} bytes; not uploaded)`),
839
- ...rows.map(({artifact:a,number,sameBytesAs})=>`${number}. ${terminalText(a.path ?? a.filename)} · ${a.kind} · /download ${number} · /files diff ${number}${sameBytesAs?` · same bytes as ${sameBytesAs}`:''} · /web`),
680
+ ...this.attachments.map(item=>`Pending: ${terminalText(item.rel)} (${item.size} bytes; not uploaded)`),
681
+ ...rows.map(({artifact:a,number,sameBytesAs})=>`${number}. ${terminalText(a.path)} · ${a.kind} · /download ${number} · /files diff ${number}${sameBytesAs?` · same bytes as ${sameBytesAs}`:''} · /web`),
840
682
  ...saved.map((p,i)=>`${rows.length+i+1}. Proposal ${terminalText(p.path)} → ${terminalText(p.originalPath)} · /files diff ${rows.length+i+1}`),
841
683
  ].join('\n') || 'No selected files or artifacts.');
842
684
  }
@@ -909,9 +751,7 @@ export class Session extends EventEmitter {
909
751
  const epoch = !grant ? await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env) : null;
910
752
  const rowLabel=row=>{
911
753
  const a=row.artifact;
912
- const evidence=run.events.flatMap(e=>e.kind==='tool_result'?e.payload?.files_changed??[]:[])
913
- .find(f=>f.path===a.path && 'sha256:'+f.sha256.replace(/^sha256:/,'')===a.cas_ref);
914
- return terminalText(`${selected.has(row)?'[x]':'[ ]'} ${a.path}${evidence?.bytes===undefined?'':` (${evidence.bytes} B)`}${row.creates.length?` · creates ${row.creates.map(p=>p+'/').join(', ')}`:''}${row.proposalPath?` · ${row.snapshot.classification ?? 'comparison after local read consent'} · save beside it as ${row.proposalPath}`:''}`)
754
+ return terminalText(`${selected.has(row)?'[x]':'[ ]'} ${a.path} (${a.bytes} B)${row.creates.length?` · creates ${row.creates.map(p=>p+'/').join(', ')}`:''}${row.proposalPath?` · ${row.snapshot.classification ?? 'comparison after local read consent'} · save beside it as ${row.proposalPath}`:''}`)
915
755
  +(row.snapshot.classification==='local changed'?`\nyou changed ${terminalText(a.path)} since Vecteur read it; your edit is kept`:row.snapshot.classification==='first sync'?'\nVecteur has no earlier version of this file from you':'');
916
756
  };
917
757
  let live=grant;
@@ -1048,94 +888,23 @@ export class Session extends EventEmitter {
1048
888
  this.run = { ...selected.response, accepted_at: selected.accepted_at, open: !selected.response.terminal };
1049
889
  this.message(selected.request.ask, "user");
1050
890
  if (this.run.open) void this.follow().catch(error => this.report(error));
1051
- else { this.message(runView(this.run).transcript, "answer", { runId: this.run.run_id, sections: runSections(this.run) }); await this.announceFooter(this.project.id); }
891
+ else { this.message(humanRun(this.run), "answer", { runId: this.run.run_id, sections: runSections(this.run) }); await this.announceFooter(this.project.id); }
1052
892
  this.status = "Viewing history — next send continues the current Project head"; this.change();
1053
893
  return;
1054
894
  }
1055
895
  }
1056
896
 
1057
- async steer(text) {
1058
- this.requireLogin();
1059
- if (!this.run?.open) throw new CliError("run_not_open", "There is no open Run to steer");
1060
- const control = { id: randomUUID(), kind: text ? "steer" : "answer_now", ...(text ? { text } : {}) };
1061
- const run = this.run, client = this.client;
1062
- const value = await client.runControl(run.run_id, control);
1063
- if (this.run !== run || this.client !== client) return;
1064
- run.controls = [...(run.controls ?? []).filter(c => c.id !== value.id), value].sort((a, b) => a.sequence - b.sequence);
1065
- this.message(`${value.kind === "steer" ? "Steer" : "Answer now"} received by Vecteur.`);
1066
- this.change();
1067
- }
1068
-
1069
- async answer() {
1070
- this.requireLogin();
1071
- const run = this.run, client = this.client;
1072
- const question = runView(run).question;
1073
- if (!question?.questions?.length) throw new CliError("question_unavailable", "There is no pending clarification");
1074
- const current = () => {
1075
- this.requireLogin();
1076
- if (this.run !== run || this.client !== client || runView(this.run).question?.id !== question.id) throw new CliError("question_resolved", "This clarification has already been resolved; your answer was not sent");
1077
- };
1078
- if (this.clarificationDraft?.run !== run || this.clarificationDraft?.client !== client || this.clarificationDraft?.id !== question.id) {
1079
- this.clarificationDraft = { run, client, id: question.id, answers: [] };
1080
- }
1081
- const { answers } = this.clarificationDraft;
1082
- while (true) {
1083
- for (const item of question.questions.slice(answers.length)) {
1084
- const options = [...item.options.map(option => ({ label: `${option.label}${option.description ? ` — ${option.description}` : ""}`, value: option.label })),
1085
- { label: "Write an answer", value: null }];
1086
- const response = item.options.length ? await this.choose(
1087
- item.question + (item.multiSelect ? " (choose numbers separated by commas)" : ""), options,
1088
- { multiple: item.multiSelect === true }) : null;
1089
- const selected = Array.isArray(response) ? response : [response];
1090
- const answer = { id: item.id, selected: selected.filter(value => value !== null) };
1091
- if (selected.includes(null)) {
1092
- do { answer.custom = await this.choose(item.question, [], { typed: true }); }
1093
- while (!answer.custom.trim());
1094
- }
1095
- answers.push(answer);
1096
- current();
1097
- }
1098
- current();
1099
- this.message(answers.map((answer, i) => `${question.questions[i].question}\n${[...answer.selected, answer.custom].filter(Boolean).join('; ')}`).join("\n\n"));
1100
- const action = await this.choose("Review your answers before sending", [
1101
- { label: "Submit these answers", value: "submit" }, { label: "Change answers", value: "edit" },
1102
- { label: "Keep answers for later in this session", value: "later" },
1103
- ]);
1104
- current();
1105
- if (action === "later") return;
1106
- if (action === "submit") break;
1107
- answers.length = 0;
1108
- }
1109
- await this.client.clarificationAnswer(this.run.run_id, question.id, answers);
1110
- this.clarificationDraft = null;
1111
- this.status = "Answer submitted"; this.change();
1112
- }
1113
-
1114
897
  modelChoice() { return this.transition(() => this.selectModel()); }
1115
898
 
1116
899
  async selectModel() {
1117
- if (!this.account || this.account.model_cost_estimates.catalogue_envelope_sha256 !== CATALOGUE_ENVELOPE_SHA256) {
1118
- throw new CliError("catalogue_outdated", "Model catalogue differs from this CLI; install the origin's current version");
1119
- }
1120
- const options = [{ label: "Auto — Vecteur selects the model", value: null },
1121
- ...PRODUCT_ROUTES.filter(row => row.route_id !== "auto").map(row => ({ label: `${row.label} · ${row.candidates.map(item => item.jurisdiction).join(" → ")}`, value: row.route_id })),
1122
- ...MODEL_CATALOGUE.map(row => ({ label: `${row.label} · ${row.provider} · ${row.data_residency}`, value: row.profile_id }))];
1123
- this.model = await this.choose("Model for the next Run (Vecteur billing)", options); this.change();
900
+ this.model = await this.choose("Model for the next Run (Vecteur billing)", MODEL_CHOICES.map(row => ({
901
+ label: row.route_id === "auto" ? "Auto — Vecteur selects the model" : `${row.label} · ${row.level}`,
902
+ value: row.route_id === "auto" ? null : row.route_id })));
903
+ this.change();
1124
904
  }
1125
905
 
1126
906
  modeDetails() {
1127
- const requested = this.model ?? "auto";
1128
- const route = PRODUCT_ROUTES.find(row => row.route_id === requested);
1129
- const profile = MODEL_CATALOGUE.find(row => row.profile_id === requested);
1130
- const matched = this.account?.model_cost_estimates.catalogue_envelope_sha256 === CATALOGUE_ENVELOPE_SHA256;
1131
- const destination = !matched ? "Catalogue unavailable or outdated — /login or update this CLI"
1132
- : route ? route.candidates.map(row => `${row.provider_id}/${row.model_id} (${row.jurisdiction})`).join(" → ")
1133
- : profile ? `${profile.provider} (${profile.data_residency})` : "Unknown";
1134
- let local = "unavailable on this platform";
1135
- try { qualify(); local = this.executor && !this.executor.closed ? "attached to this Run"
1136
- : this.execAllowed && this.execGrant ? "enabled for the next Run" : "available — /exec on to allow commands"; }
1137
- catch { /* qualify owns the supported platform boundary */ }
1138
- return `Lead: Laplace\nExecution: Vecteur cloud\nPayer: Project organization ${this.account?.org_id ?? "(sign in first)"}\nNext model: ${this.view().model}\nData destination: ${destination}\nLast Run profile: ${this.run?.profile || "not known"}\nLocal execution: ${local}`;
907
+ return `Execution: Vecteur cloud\nPayer: Project organization ${this.account?.org_id ?? "(sign in first)"}\nNext model: ${this.view().model}\nLast Run model: ${this.run?.requested_route_id || "not known"}`;
1139
908
  }
1140
909
 
1141
910
  statusDetails() {
@@ -1143,7 +912,6 @@ export class Session extends EventEmitter {
1143
912
  }
1144
913
 
1145
914
  async logout() {
1146
- this.executor?.stop(); this.execAllowed = false;
1147
915
  return this.transition(async () => {
1148
916
  this.requireLogin();
1149
917
  const yes = await this.choose("Sign out here? Saved drafts stay with this account; a cloud Run keeps running.", [
@@ -1174,83 +942,6 @@ export class Session extends EventEmitter {
1174
942
  this.message(`Downloaded ${result.bytes} verified bytes to ${result.path}`);
1175
943
  }
1176
944
 
1177
- /** Round trip: verified Code/package download into a new folder; the user runs it, then /attach the result. */
1178
- async package(index) {
1179
- this.requireLogin();
1180
- const item = runView(this.run).artifacts[index - 1];
1181
- if (!item) throw new CliError("artifact_unavailable", "Choose an artifact number from /files");
1182
- const directory = resolve(this.cwd, `vecteur-package-${item.cas_ref.slice(7, 19)}`);
1183
- await mkdir(directory, { mode: 0o700 }).catch(error => {
1184
- throw new CliError(error?.code === "EEXIST" ? "output_exists" : "export_failed", `could not create ${directory}`);
1185
- });
1186
- const result = await downloadArtifact(this.client, item.cas_ref, this.project.id, join(directory, safeArtifactName(item)));
1187
- // CU-2: the folder remembers which package revision it holds, so a local report binds to that revision only.
1188
- await writeFile(join(directory, PACKAGE_MARKER), JSON.stringify({ cas_ref: item.cas_ref, project_id: this.project.id,
1189
- run_id: this.run?.run_id ?? null, filename: item.filename }), { flag: "wx", mode: 0o600 });
1190
- this.lastPackage = directory;
1191
- this.message([`Saved ${result.bytes} verified bytes to ${result.path}`,
1192
- `Vecteur does not run it on its own. /run-package asks your consent and runs its declared tests here (unzip a .zip into ${directory} first),`,
1193
- "or run them yourself and /attach the report. A report is your evidence, never an accepted result."].join("\n"));
1194
- }
1195
-
1196
- /** CU-2 (v5 §5): with explicit consent, run the declared test command of a downloaded Code package on this machine
1197
- * as an approved process template (python -m pytest + plain flags, inside the package), stop its whole process
1198
- * tree on /stop-package or at the wall, and stage the report — bound to the package revision it tested — for upload
1199
- * on the next send. Without consent nothing runs. */
1200
- async runPackage(argument = "") {
1201
- this.requireLogin();
1202
- if (this.localRun) throw new CliError("package_running", "A package is already running; /stop-package stops it");
1203
- const directory = resolve(this.cwd, argument.trim() || this.lastPackage || ".");
1204
- let marker;
1205
- try { marker = JSON.parse(await readFile(join(directory, PACKAGE_MARKER), "utf8")); }
1206
- catch { throw new CliError("package_unbound", "Run only a package saved with /package (its folder records the revision)"); }
1207
- const root = await packageRoot(directory);
1208
- const raw = await readFile(join(root, "kc.json"));
1209
- let manifest;
1210
- try { manifest = JSON.parse(raw.toString("utf8")); } catch { throw new CliError("package_invalid", "kc.json is not JSON"); }
1211
- const argv = approvedTemplate(manifest, root);
1212
- if (marker.project_id !== this.project.id
1213
- || !runView(this.run).artifacts.some(item => item.cas_ref === marker.cas_ref)) {
1214
- throw new CliError("report_revision_mismatch", "This folder holds a package of another Project turn; open that turn first");
1215
- }
1216
- const ok = await this.choose([`Run on this machine, in ${root}:`, ` ${argv.join(" ")}`,
1217
- `Target ${manifest.target ?? "unspecified"}. It runs with your Python (${this.env.VECTEUR_PYTHON || "python3"}) and your user's rights; only its report is uploaded, on your next send.`].join("\n"), [
1218
- { label: "Run the declared tests", value: true }, { label: "Cancel", value: false }]);
1219
- if (!ok || this.closed) { this.message("Nothing ran."); return null; }
1220
- const started = Date.now();
1221
- const child = spawn(this.env.VECTEUR_PYTHON || "python3", argv.slice(1), {
1222
- cwd: root, detached: true, stdio: ["ignore", "pipe", "pipe"],
1223
- env: localProcessEnv(this.env, root) });
1224
- const out = [], err = [];
1225
- child.stdout.on("data", chunk => out.push(chunk)); child.stderr.on("data", chunk => err.push(chunk));
1226
- const run = this.localRun = { child, stopped: null };
1227
- const wall = setTimeout(() => this.stopPackage("wall"), Number(this.env.VECTEUR_PACKAGE_WALL_S || 600) * 1000);
1228
- const [code, signal] = await new Promise(done => child.on("close", (c, s) => done([c, s])));
1229
- clearTimeout(wall); clearTimeout(run.escalation);
1230
- try { process.kill(-child.pid, "SIGKILL"); } catch { /* the group is already gone */ }
1231
- this.localRun = null;
1232
- const tail = chunks => Buffer.concat(chunks).toString("utf8").slice(-8000);
1233
- const report = { schema: "vecteur.kc.local-test.v1", package_cas_ref: marker.cas_ref, project_id: marker.project_id,
1234
- run_id: marker.run_id, kc_json_sha256: createHash("sha256").update(raw).digest("hex"), target: manifest.target ?? null,
1235
- argv, exit_code: code, signal, stopped: run.stopped, seconds: (Date.now() - started) / 1000,
1236
- stdout_tail: tail(out), stderr_tail: tail(err) };
1237
- const bytes = Buffer.from(JSON.stringify(report, null, 1));
1238
- const path = join(directory, `kc-test-report-${marker.cas_ref.slice(7, 19)}-${started}.json`);
1239
- await writeFile(path, bytes, { flag: "wx", mode: 0o600 });
1240
- this.attachments.push({ path, bytes, media: "application/json", generated:true }); this.change();
1241
- this.message(`${run.stopped ? `Stopped (${run.stopped})` : code === 0 ? "Tests passed" : `Tests failed (exit ${code})`}; the report ${basename(path)} is staged for your next send.`);
1242
- return report;
1243
- }
1244
-
1245
- /** Stop the running package: its whole process group, SIGTERM then SIGKILL after 2 s. */
1246
- stopPackage(reason = "user") {
1247
- const run = this.localRun;
1248
- if (!run) throw new CliError("package_not_running", "No package is running");
1249
- run.stopped = reason;
1250
- try { process.kill(-run.child.pid, "SIGTERM"); } catch { /* exited */ }
1251
- run.escalation = setTimeout(() => { try { process.kill(-run.child.pid, "SIGKILL"); } catch { /* exited */ } }, 2000);
1252
- }
1253
-
1254
945
  async exportRun(output) {
1255
946
  this.requireLogin();
1256
947
  if (!this.run || this.run.open) throw new CliError("run_unavailable", "Export needs a completed Run");
@@ -1274,7 +965,6 @@ export class Session extends EventEmitter {
1274
965
  if (this.registry) this.registry.saveDraft(this.draft);
1275
966
  }
1276
967
  catch (error) { this.message(`Draft could not be saved: ${error.code ?? "store_error"}`, "error"); }
1277
- this.executor?.stop();
1278
968
  this.closed = true; this.generation++; this.cancelLogin(); this.lifecycle.abort(); this.followController?.abort(); clearTimeout(this.draftTimer);
1279
969
  this.rejectPrompt?.(new CliError("session_closed", "Session closed")); this.prompt = null;
1280
970
  this.emit("close");