@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/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,24 @@ 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;
301
+ if (stopOffer) void this.client.stopEvent(run.run_id, { event: "shown", surface: "cli" });
342
302
  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;
303
+ this.message(humanRun(run, options), "answer", { runId: run.run_id, sections: runSections(run, options) });
304
+ this.lastPrintedRun = run.run_id;
344
305
  return true;
345
306
  }
346
307
 
@@ -392,26 +353,14 @@ export class Session extends EventEmitter {
392
353
  : await this.client.projectCreate(pending.name, pending.workspaceId, undefined, pending.key);
393
354
  if (!pending.projectId) await withAdmissionLock(() => {
394
355
  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
356
  this.registry.completeCreation(pending.key, project.id);
400
357
  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
358
  },this.env);
403
359
  this.project = project; this.binding = this.registry.binding(); this.provenance = "binding";
404
360
  return project;
405
361
  }
406
362
 
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) {
363
+ async submit(text = this.draft) {
415
364
  if (this.busy) throw new CliError("session_busy", "The current submission is still being reconciled");
416
365
  if (!text.trim()) return;
417
366
  if (this.offline || !this.account) {
@@ -423,11 +372,8 @@ export class Session extends EventEmitter {
423
372
  return;
424
373
  }
425
374
  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);
375
+ // One turn at a time: the reply to a question is the next turn, after this one closes.
376
+ this.setDraft(text); this.status = "This Run is still working — draft kept; send it when the Run ends"; this.change();
431
377
  return;
432
378
  }
433
379
  this.setDraft(text);
@@ -435,13 +381,13 @@ export class Session extends EventEmitter {
435
381
  const draftRef = structuredClone(this.registry?.draftRef ?? null);
436
382
  this.busy = true; this.status = "Submitting"; this.change();
437
383
  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");
384
+ if (this.registry?.state().pendingRun) throw new CliError("submission_pending", "Use /resume to resolve the interrupted submission; your new draft is kept");
439
385
  if (this.project?.role === 'VIEWER') throw new CliError('role_forbidden', 'Editor access is required to ask Vecteur');
440
386
  if (await this.offerAttachments(text) === false) { this.status = 'Draft kept — named files not offered'; return; }
441
387
  const consentAccount=this.account.id;
442
388
  const destination = { origin: this.origin, id: this.project?.id, name: this.project?.name ?? this.projectName ?? basename(this.cwd) };
443
389
  let consent = false;
444
- if (this.attachments.some(f => !f.generated)) {
390
+ if (this.attachments.length) {
445
391
  const grant = this.project && currentGrant(this.localPin(), this.env);
446
392
  if (!grant) {
447
393
  const epoch=await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env);
@@ -451,11 +397,10 @@ export class Session extends EventEmitter {
451
397
  }
452
398
  const project = await this.ensureProject(consent || undefined);
453
399
  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))) {
400
+ if (this.attachments.length && consent && (destination.origin !== this.origin || (destination.id ? destination.id !== project.id : destination.name !== project.name))) {
455
401
  if (!await this.confirmFiles({ origin: this.origin, id: project.id, name: project.name })) return;
456
402
  }
457
- if (this.execAllowed === undefined) await this.execConsent("on");
458
- const executor = await withAdmissionLock(async () => {
403
+ await withAdmissionLock(async () => {
459
404
  const newest = await this.client.projectNewestRun(project.id);
460
405
  const checkDestination=()=>{
461
406
  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 +412,20 @@ export class Session extends EventEmitter {
467
412
  }
468
413
  const selections = [];
469
414
  let grant;
470
- if (this.attachments.some(f => !f.generated)) {
415
+ if (this.attachments.length) {
471
416
  grant = currentGrant(this.localPin(), this.env);
472
417
  if (!grant) { if (!consent) throw new CliError('grant_changed', 'Permission changed; confirm files again'); grant = createGrant(this.localPin(), this.env, consent.epoch); }
473
418
  }
474
419
  for (const item of this.attachments) {
475
420
  checkDestination();
476
- if (!item.generated) pinCheck(grant, this.localPin(), this.env);
421
+ pinCheck(grant, this.localPin(), this.env);
477
422
  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);
423
+ const file = readConfined(grant, item.rel, this.env, { selected: item });
424
+ pinCheck(grant, this.localPin(), this.env);
480
425
  this.message(`Upload ${file.rel} (${file.size} B) to ${project.name} on ${this.origin}`);
481
426
  item.source = await this.client.inputAdd(project.id, file.bytes, file.media);
482
427
  checkDestination();
483
- if (!item.generated) recordUpload(grant, file, item.source, this.env);
428
+ recordUpload(grant, file, item.source, this.env);
484
429
  const offer = item.source.offer ?? await this.client.inputOffer(project.id, item.source);
485
430
  if (!offer.extracts.length) throw new CliError("extraction_unavailable", "This file has no selectable extracts");
486
431
  selections.push({ source_handle: { cas_ref: item.source.cas_ref, acquisition_ref: item.source.acquisition_ref },
@@ -490,30 +435,9 @@ export class Session extends EventEmitter {
490
435
  || a.source_handle.acquisition_ref.localeCompare(b.source_handle.acquisition_ref));
491
436
  const body = { ask: text, attachments: selections.map(item => item.source_handle),
492
437
  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);
438
+ ...(selections.length ? { selections } : {}), ...(this.model ? { model_choice: this.model } : {}) };
439
+ return this.admitPendingLocked(this.registry.reserveRun(project.id, body, draftRef));
515
440
  }, this.env);
516
- this.startExecutor(executor);
517
441
  void this.follow().catch(error => this.report(error));
518
442
  } catch(error) {
519
443
  if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest();
@@ -523,59 +447,39 @@ export class Session extends EventEmitter {
523
447
  }
524
448
 
525
449
  async admitPending(pending) {
526
- let executor;
527
- try { executor = await withAdmissionLock(() => this.admitPendingLocked(pending), this.env); }
450
+ try { await withAdmissionLock(() => this.admitPendingLocked(pending), this.env); }
528
451
  catch(error) { if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest(); throw error; }
529
- this.startExecutor(executor);
530
452
  void this.follow().catch(error=>this.report(error));
531
453
  }
532
454
 
533
455
  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
456
  if (this.project?.id !== pending.projectId) {
537
457
  const project = await this.client.projectGet(pending.projectId);
538
458
  this.followController?.abort(); this.generation++; this.run = null; this.project = project; this.change();
539
459
  }
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
460
  let ack;
545
461
  try { ack = await this.client.runAdmit(pending.projectId, pending.body, pending.key); }
546
462
  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);
463
+ const worded = OWNER_WORDED.includes(error.code);
464
+ if (["state_busy", "state_fork"].includes(error.code) || error.admission === "refused" || worded) {
465
+ this.registry.rejectRunAdmission(pending.key);
550
466
  }
551
467
  if (["state_busy", "state_fork"].includes(error.code)) {
552
468
  throw new CliError(error.code, "Submission refused; draft kept. Review the latest Run and explicitly send again.");
553
469
  }
470
+ // A read-only (v5) Project or a retired door: the owner's own sentence, nothing admitted, draft kept.
471
+ if (worded) throw new CliError(error.code, `${error.message} Nothing was admitted; draft kept.`);
554
472
  // The owner marked this key as never admittable (nothing dispatched): release only this
555
473
  // 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
- }
474
+ if (error.admission === "refused") throw new CliError(error.code, "Submission refused before it ran; draft kept. Fix it and send again.");
560
475
  throw error;
561
476
  }
562
- if (!ephemeral) this.registry.finishRunAdmission(pending.key);
563
- this.execPending = null;
477
+ this.registry.finishRunAdmission(pending.key);
564
478
  if (this.draft === pending.body.ask) { clearTimeout(this.draftTimer); this.draft = ""; }
565
479
  this.attachments = [];
566
480
  this.message(pending.body.ask, "user");
567
- this.run = { ...ack, ask: pending.body.ask, controls: [], events: [], terminal: "", open: true };
481
+ this.run = { ...ack, ask: pending.body.ask, events: [], terminal: "", open: true };
568
482
  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
483
  }
580
484
 
581
485
  async resume() {
@@ -584,7 +488,6 @@ export class Session extends EventEmitter {
584
488
  if (!this.account || !this.registry) return this.initialize();
585
489
  await withAdmissionLock(() => reconcileAdmissions(this.client, this.origin, this.env), this.env);
586
490
  const state = this.registry.state();
587
- if (this.execPending) return this.admitPending(this.execPending);
588
491
  if (state.pendingRun) {
589
492
  this.busy = true; this.change();
590
493
  try { return await this.admitPending(state.pendingRun); }
@@ -598,97 +501,36 @@ export class Session extends EventEmitter {
598
501
  async follow() {
599
502
  this.followController?.abort();
600
503
  const controller = new AbortController(); this.followController = controller;
601
- const run = this.run, executor = this.executor; const generation = ++this.generation;
504
+ const run = this.run; const generation = ++this.generation;
602
505
  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 });
506
+ let attempts = 0;
629
507
  try {
630
508
  while (!this.closed && generation === this.generation && run?.open) {
631
509
  try {
632
510
  const direct = await this.client.runEvents(run.run_id, event => {
633
511
  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();
512
+ run.events.push(event); this.status = "Running"; this.change();
637
513
  }, controller.signal, [...run.events]);
638
514
  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;
515
+ this.run = { ...direct, accepted_at: run.accepted_at, ask: run.ask, open: !direct.terminal };
516
+ this.status = direct.terminal === "budget" ? "Paused at a limit" : direct.terminal;
517
+ await this.announceRun();
642
518
  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
519
  await this.announceFooter(projectId);
646
520
  this.change(); await this.offerSaves().catch(error=>this.report(error)); return;
647
521
  } catch (error) {
648
522
  if (controller.signal.aborted || this.closed || generation !== this.generation) return;
649
523
  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
524
  if (!TRANSIENT.has(error.code) || ++attempts > 5) throw error;
659
525
  this.status = "Connection lost — reconnecting to the same Run"; this.change();
660
526
  await delay(Math.min(500 * 2 ** attempts, 8_000), controller.signal);
661
527
  }
662
528
  }
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
- }
529
+ } finally { controller.abort(); }
671
530
  }
672
531
 
673
532
  attach(path) { return this.transition(() => this.selectAttachment(path)); }
674
533
 
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
534
  localPin() {
693
535
  return { origin: this.origin, accountId: this.account?.id, projectId: this.project?.id, role: this.project?.role,
694
536
  root: this.registry.folder, provenance: this.provenance ?? 'binding', binding: () => this.registry.binding(),
@@ -701,7 +543,7 @@ export class Session extends EventEmitter {
701
543
  }
702
544
 
703
545
  async confirmFiles(destination) {
704
- const files = this.attachments.filter(f=>!f.generated);
546
+ const files = this.attachments;
705
547
  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
548
  { label: 'Yes, allow select and save-new', value: true }, { label: 'No, keep draft and selections', value: false },
707
549
  ], { liveTitle: `Send ${files.length} selected file${files.length===1?'':'s'}?` });
@@ -794,7 +636,6 @@ export class Session extends EventEmitter {
794
636
  }
795
637
 
796
638
  async revokeFiles() {
797
- this.executor?.stop(); this.execAllowed = false;
798
639
  this.requireLogin();
799
640
  return withLocalLock(() => {
800
641
  endGrants({origin:this.origin,accountId:this.account.id,root:this.registry.folder.path},this.env);
@@ -835,8 +676,8 @@ export class Session extends EventEmitter {
835
676
  const rows = artifactRows(runView(this.run).artifacts);
836
677
  const saved = this.account && this.project ? await this.scanLocalTargets() : [];
837
678
  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`),
679
+ ...this.attachments.map(item=>`Pending: ${terminalText(item.rel)} (${item.size} bytes; not uploaded)`),
680
+ ...rows.map(({artifact:a,number,sameBytesAs})=>`${number}. ${terminalText(a.path)} · ${a.kind} · /download ${number} · /files diff ${number}${sameBytesAs?` · same bytes as ${sameBytesAs}`:''} · /web`),
840
681
  ...saved.map((p,i)=>`${rows.length+i+1}. Proposal ${terminalText(p.path)} → ${terminalText(p.originalPath)} · /files diff ${rows.length+i+1}`),
841
682
  ].join('\n') || 'No selected files or artifacts.');
842
683
  }
@@ -909,9 +750,7 @@ export class Session extends EventEmitter {
909
750
  const epoch = !grant ? await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env) : null;
910
751
  const rowLabel=row=>{
911
752
  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}`:''}`)
753
+ 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
754
  +(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
755
  };
917
756
  let live=grant;
@@ -1048,94 +887,23 @@ export class Session extends EventEmitter {
1048
887
  this.run = { ...selected.response, accepted_at: selected.accepted_at, open: !selected.response.terminal };
1049
888
  this.message(selected.request.ask, "user");
1050
889
  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); }
890
+ else { this.message(humanRun(this.run), "answer", { runId: this.run.run_id, sections: runSections(this.run) }); await this.announceFooter(this.project.id); }
1052
891
  this.status = "Viewing history — next send continues the current Project head"; this.change();
1053
892
  return;
1054
893
  }
1055
894
  }
1056
895
 
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
896
  modelChoice() { return this.transition(() => this.selectModel()); }
1115
897
 
1116
898
  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();
899
+ this.model = await this.choose("Model for the next Run (Vecteur billing)", MODEL_CHOICES.map(row => ({
900
+ label: row.route_id === "auto" ? "Auto — Vecteur selects the model" : `${row.label} · ${row.level}`,
901
+ value: row.route_id === "auto" ? null : row.route_id })));
902
+ this.change();
1124
903
  }
1125
904
 
1126
905
  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}`;
906
+ 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
907
  }
1140
908
 
1141
909
  statusDetails() {
@@ -1143,7 +911,6 @@ export class Session extends EventEmitter {
1143
911
  }
1144
912
 
1145
913
  async logout() {
1146
- this.executor?.stop(); this.execAllowed = false;
1147
914
  return this.transition(async () => {
1148
915
  this.requireLogin();
1149
916
  const yes = await this.choose("Sign out here? Saved drafts stay with this account; a cloud Run keeps running.", [
@@ -1174,83 +941,6 @@ export class Session extends EventEmitter {
1174
941
  this.message(`Downloaded ${result.bytes} verified bytes to ${result.path}`);
1175
942
  }
1176
943
 
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
944
  async exportRun(output) {
1255
945
  this.requireLogin();
1256
946
  if (!this.run || this.run.open) throw new CliError("run_unavailable", "Export needs a completed Run");
@@ -1274,7 +964,6 @@ export class Session extends EventEmitter {
1274
964
  if (this.registry) this.registry.saveDraft(this.draft);
1275
965
  }
1276
966
  catch (error) { this.message(`Draft could not be saved: ${error.code ?? "store_error"}`, "error"); }
1277
- this.executor?.stop();
1278
967
  this.closed = true; this.generation++; this.cancelLogin(); this.lifecycle.abort(); this.followController?.abort(); clearTimeout(this.draftTimer);
1279
968
  this.rejectPrompt?.(new CliError("session_closed", "Session closed")); this.prompt = null;
1280
969
  this.emit("close");