@vecteur/cli 0.10.0 → 0.12.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/session.js CHANGED
@@ -1,23 +1,24 @@
1
1
  import { EventEmitter } from "node:events";
2
2
  import { randomUUID } from "node:crypto";
3
- import { open, writeFile } from "node:fs/promises";
4
- import { constants } from "node:fs";
5
- import { basename, relative, resolve } from "node:path";
3
+ import { writeFile } from "node:fs/promises";
4
+ import { basename, isAbsolute, relative, resolve } from "node:path";
6
5
  import { VecteurClient, CliError, configuration, delay, isTokenShaped, requestTimeout,
7
6
  resolveOrigin, shouldOpenBrowser, waitForDeviceAuthorization } from "./client.js";
8
7
  import { readCredentials, writeCredentials, clearCredentials } from "./credentials.js";
9
8
  import { FolderRegistry, UNSIGNED_ACCOUNT } from "./folders.js";
10
- import { runView } from "./blocks.js";
9
+ import { runView, artifactRows } from "./blocks.js";
11
10
  import { downloadArtifact, exportRun } from "./download.js";
12
- import { humanCost, runSections } from "./format.js";
13
- import { CATALOGUE_ENVELOPE_SHA256, MODEL_CATALOGUE, PRODUCT_ROUTES } from "./contract.js";
11
+ import { humanRun, runSections, turnFooter, terminalText, proposalReview, adoptionHint } from "./format.js";
12
+ import { withLocalLock, withAdmissionLock, qualify, currentGrant, createGrant, prepareConsent, checkConsent, endGrants, pinCheck, selectionMetadata,
13
+ readConfined, recordUpload, discover, nameOffers, tombstoned, writeNewConfined,
14
+ reconcileWrites, reconcileAdmissions, inspectTarget, observeTargetMetadata, observeTargets, proposals, proposalName, writeProposalConfined, downloadLocalArtifact } from './localfiles.js';
15
+ import { ARTIFACT_MEDIA_TYPES, MODEL_CHOICES } from "./contract.js";
16
+ import { OWNER_WORDED } from "./client.js";
14
17
  import { openBrowser } from "./browser.js";
15
18
 
16
19
  export const NEW_FOLDER = "New folder — send an ask or /link an existing Project";
17
20
  const AUTH_ERRORS = new Set(["pat_expired", "pat_invalid", "pat_revoked"]);
18
21
  const TRANSIENT = new Set(["request_failed", "request_timeout", "terminal_invalid"]);
19
- const MEDIA = { ".txt": "text/plain", ".md": "text/markdown", ".csv": "text/csv", ".json": "application/json",
20
- ".pdf": "application/pdf", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document" };
21
22
 
22
23
  /** One cloud session, two real renderers. It owns no terminal, device or native-agent runtime. */
23
24
  export class Session extends EventEmitter {
@@ -34,12 +35,9 @@ export class Session extends EventEmitter {
34
35
 
35
36
  view(now = Date.now()) {
36
37
  const canEdit = this.project?.role !== "VIEWER";
37
- const activity = !canEdit && this.status === "Waiting for your answer" ? "Waiting for an editor" : this.status;
38
- this.projectionCache ??= {};
39
- const projection = runView(this.run, this.projectionCache, now);
40
- const requested = this.model ?? "auto";
41
- const modelLabel = MODEL_CATALOGUE.find(row => row.profile_id === requested)?.label
42
- ?? 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;
43
41
  const bound = this.binding?.state === "bound" && this.binding.projectId === this.project?.id;
44
42
  return { origin: this.origin, folder: bound ? relative(this.binding.folder.path, this.cwd) || "." : this.cwd,
45
43
  account: this.account, project: this.project,
@@ -48,11 +46,11 @@ export class Session extends EventEmitter {
48
46
  offline: this.offline, issue: this.issue, login: this.loginChallenge, release: this.release,
49
47
  // First use: signed in and online, the folder resolved to no binding/Project/Run, nothing pending.
50
48
  firstUse: !!this.account && !this.offline && !this.busy && !this.project && !this.run && this.status === NEW_FOLDER,
51
- attachments: this.attachments.map(item => ({ path: item.path, size: item.bytes.length })),
52
- 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,
53
52
  run: projection, available: { submit: !this.offline && !!this.account && canEdit && !this.busy && !this.run?.open,
54
- cancel: !this.offline && !!this.account && canEdit && !!this.run?.open, steer: !this.offline && !!this.account && canEdit && !!this.run?.open && !projection.question,
55
- localExecution: false, nativeAgent: false } };
53
+ cancel: !this.offline && !!this.account && canEdit && !!this.run?.open } };
56
54
  }
57
55
 
58
56
  change() { if (!this.closed) this.emit("change", this.view()); }
@@ -69,10 +67,10 @@ export class Session extends EventEmitter {
69
67
  this.change();
70
68
  }
71
69
 
72
- async choose(title, options, { typed = false, multiple = false } = {}) {
70
+ async choose(title, options, { typed = false, multiple = false, liveTitle } = {}) {
73
71
  if (this.prompt) throw new CliError("prompt_busy", "Answer the current question first");
74
72
  return new Promise((resolveChoice, reject) => {
75
- this.prompt = { id: ++this.promptGeneration, title, options, typed, multiple };
73
+ this.prompt = { id: ++this.promptGeneration, title: liveTitle ?? title, card: liveTitle ? title : undefined, options, typed, multiple };
76
74
  this.resolvePrompt = answer => { this.prompt = null; this.resolvePrompt = null; this.rejectPrompt = null; this.change(); resolveChoice(answer); };
77
75
  this.rejectPrompt = reject;
78
76
  this.change();
@@ -225,6 +223,7 @@ export class Session extends EventEmitter {
225
223
  this.model = null; this.projectName = null; this.lastPrintedRun = null;
226
224
  }
227
225
  this.account = account;
226
+ this.activeCredential = { kind: this.env.VECTEUR_TOKEN ? 'environment' : 'stored', token };
228
227
  const newRegistry = !this.registry || this.registry.accountId !== account.id;
229
228
  if (newRegistry) this.registry = new FolderRegistry({ origin: this.origin, accountId: account.id, cwd: this.cwd, env: this.env });
230
229
  if (newRegistry && this.draft) {
@@ -232,6 +231,13 @@ export class Session extends EventEmitter {
232
231
  else this.registry.newDraft();
233
232
  }
234
233
  this.registry.rememberLogin(token);
234
+ this.client.localEnv = this.env;
235
+ try {
236
+ qualify();
237
+ const reports = await withLocalLock(() => reconcileWrites(this.env), this.env);
238
+ for (const report of reports) if (report.remains.length) this.message(`Local save recovery: ${JSON.stringify(report)}`);
239
+ } catch (error) { if (error.code !== 'platform_unqualified') throw error; }
240
+
235
241
  this.cwd = this.registry.folder.path;
236
242
  if (!this.draft) {
237
243
  const drafts = this.registry.state().drafts;
@@ -248,6 +254,7 @@ export class Session extends EventEmitter {
248
254
  if (!current()) return;
249
255
  this.projects = projects;
250
256
  const binding = this.registry.binding(); this.binding = binding;
257
+ this.provenance = "binding";
251
258
  if (binding && binding.state !== "bound") {
252
259
  this.status = "Folder identity changed — /unlink before relinking"; this.change(); return;
253
260
  }
@@ -264,6 +271,7 @@ export class Session extends EventEmitter {
264
271
  this.change(); return;
265
272
  }
266
273
  this.change();
274
+ if (this.project) await this.scanLocalTargets();
267
275
  await this.loadNewest();
268
276
  }
269
277
 
@@ -274,18 +282,35 @@ export class Session extends EventEmitter {
274
282
  if (this.closed || generation !== this.generation) return;
275
283
  if (newest) {
276
284
  this.run = { ...newest, open: !newest.terminal };
285
+ if (newest.run_id !== this.lastPrintedRun && newest.ask !== undefined) this.message(newest.ask, "user");
277
286
  if (this.run.open) {
278
- this.status = runView(this.run, this.projectionCache).question ? "Waiting for your answer" : "Running";
287
+ this.status = "Running";
279
288
  this.change(); void this.follow().catch(error => this.report(error));
280
289
  }
281
- else { this.status = newest.terminal; this.announceRun(); this.change(); }
290
+ else { this.status = newest.terminal; if (await this.announceRun()) await this.announceFooter(this.project.id); this.change(); await this.offerSaves(); }
282
291
  } else { this.run = null; this.change(); }
283
292
  }
284
293
  }
285
294
 
286
- announceRun() {
287
- if (this.lastPrintedRun === this.run?.run_id) return;
288
- this.message(runView(this.run).transcript, "answer", { runId: this.run?.run_id, sections: runSections(this.run) }); this.lastPrintedRun = this.run?.run_id;
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" });
302
+ const options = { stopOffer, origin: this.origin };
303
+ this.message(humanRun(run, options), "answer", { runId: run.run_id, sections: runSections(run, options) });
304
+ this.lastPrintedRun = run.run_id;
305
+ return true;
306
+ }
307
+
308
+ async announceFooter(projectId) {
309
+ const run = this.run;
310
+ let cost;
311
+ try { cost = await this.client.customerCost(projectId); }
312
+ catch { /* A missing cost read is explicitly unavailable, never a guessed amount. */ }
313
+ if (this.run === run && !this.closed) this.message(turnFooter(run, cost), "turn-footer", { run, value: cost });
289
314
  }
290
315
 
291
316
  recoverDraft() {
@@ -310,7 +335,7 @@ export class Session extends EventEmitter {
310
335
  this.change();
311
336
  }
312
337
 
313
- async ensureProject() {
338
+ async ensureProject(consent = undefined) {
314
339
  if (!this.account) throw new CliError("login_required", "Sign in with /login; your draft is kept");
315
340
  if (this.project) return this.project;
316
341
  if (this.registry.binding()) throw new CliError("binding_unavailable", "Resolve the existing binding with /project or /unlink");
@@ -326,8 +351,12 @@ export class Session extends EventEmitter {
326
351
  const pending = this.registry.reserveCreation(this.projectName ?? basename(this.cwd), workspace);
327
352
  const project = pending.projectId ? await this.client.projectGet(pending.projectId)
328
353
  : await this.client.projectCreate(pending.name, pending.workspaceId, undefined, pending.key);
329
- if (!pending.projectId) this.registry.completeCreation(pending.key, project.id);
330
- this.project = project; this.binding = this.registry.binding();
354
+ if (!pending.projectId) await withAdmissionLock(() => {
355
+ if(consent)checkConsent(this.localPin(),consent.epoch,this.env);
356
+ this.registry.completeCreation(pending.key, project.id);
357
+ if(consent)consent.epoch=prepareConsent(this.localPin(),this.env);
358
+ },this.env);
359
+ this.project = project; this.binding = this.registry.binding(); this.provenance = "binding";
331
360
  return project;
332
361
  }
333
362
 
@@ -343,11 +372,8 @@ export class Session extends EventEmitter {
343
372
  return;
344
373
  }
345
374
  if (this.run?.open) {
346
- this.setDraft(text); const run = this.run;
347
- const action = await this.choose("This Run is still working", [
348
- { label: "Keep drafting the next question", value: "draft" }, { label: "Send as steering to this Run", value: "steer" },
349
- ]);
350
- 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();
351
377
  return;
352
378
  }
353
379
  this.setDraft(text);
@@ -356,32 +382,77 @@ export class Session extends EventEmitter {
356
382
  this.busy = true; this.status = "Submitting"; this.change();
357
383
  try {
358
384
  if (this.registry?.state().pendingRun) throw new CliError("submission_pending", "Use /resume to resolve the interrupted submission; your new draft is kept");
359
- const project = await this.ensureProject();
360
- if (project.role === "VIEWER") throw new CliError("role_forbidden", "Editor access is required to ask Vecteur");
361
- const newest = await this.client.projectNewestRun(project.id);
362
- if (newest && !newest.terminal) {
363
- this.run = { ...newest, open: true }; void this.follow().catch(error => this.report(error));
364
- throw new CliError("run_busy", "Another terminal has an open Run. Following it; your draft is kept.");
385
+ if (this.project?.role === 'VIEWER') throw new CliError('role_forbidden', 'Editor access is required to ask Vecteur');
386
+ if (await this.offerAttachments(text) === false) { this.status = 'Draft kept — named files not offered'; return; }
387
+ const consentAccount=this.account.id;
388
+ const destination = { origin: this.origin, id: this.project?.id, name: this.project?.name ?? this.projectName ?? basename(this.cwd) };
389
+ let consent = false;
390
+ if (this.attachments.length) {
391
+ const grant = this.project && currentGrant(this.localPin(), this.env);
392
+ if (!grant) {
393
+ const epoch=await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env);
394
+ if(await this.confirmFiles(destination))consent={epoch};
395
+ if (!consent) { this.status = 'Draft kept — files not uploaded'; return; }
396
+ }
365
397
  }
366
- const selections = [];
367
- for (const item of this.attachments) {
368
- item.source ??= await this.client.inputAdd(project.id, item.bytes, item.media);
369
- const offer = item.source.offer ?? await this.client.inputOffer(project.id, item.source);
370
- if (!offer.extracts.length) throw new CliError("extraction_unavailable", "This file has no selectable extracts");
371
- selections.push({ source_handle: { cas_ref: item.source.cas_ref, acquisition_ref: item.source.acquisition_ref },
372
- offer_id: offer.id, selected_extract_ids: offer.extracts.map(extract => extract.id).sort(), method: "exact-extract" });
398
+ const project = await this.ensureProject(consent || undefined);
399
+ if (project.role === "VIEWER") throw new CliError("role_forbidden", "Editor access is required to ask Vecteur");
400
+ if (this.attachments.length && consent && (destination.origin !== this.origin || (destination.id ? destination.id !== project.id : destination.name !== project.name))) {
401
+ if (!await this.confirmFiles({ origin: this.origin, id: project.id, name: project.name })) return;
373
402
  }
374
- selections.sort((a, b) => a.source_handle.cas_ref.localeCompare(b.source_handle.cas_ref)
375
- || a.source_handle.acquisition_ref.localeCompare(b.source_handle.acquisition_ref));
376
- const body = { ask: text, attachments: selections.map(item => item.source_handle),
377
- parent_state_hash: newest?.state_hash ?? null, ui_context: null,
378
- ...(selections.length ? { selections } : {}), ...(this.model ? { model_choice: this.model } : {}) };
379
- const pending = this.registry.reserveRun(project.id, body, draftRef);
380
- await this.admitPending(pending);
403
+ await withAdmissionLock(async () => {
404
+ const newest = await this.client.projectNewestRun(project.id);
405
+ const checkDestination=()=>{
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');
407
+ };
408
+ checkDestination();
409
+ if (newest && !newest.terminal) {
410
+ this.run = { ...newest, open: true };
411
+ throw new CliError("run_busy", "Another terminal has an open Run. Following it; your draft is kept.");
412
+ }
413
+ const selections = [];
414
+ let grant;
415
+ if (this.attachments.length) {
416
+ grant = currentGrant(this.localPin(), this.env);
417
+ if (!grant) { if (!consent) throw new CliError('grant_changed', 'Permission changed; confirm files again'); grant = createGrant(this.localPin(), this.env, consent.epoch); }
418
+ }
419
+ for (const item of this.attachments) {
420
+ checkDestination();
421
+ pinCheck(grant, this.localPin(), this.env);
422
+ if (item.generation !== undefined && item.generation !== grant.generation) throw new CliError('grant_changed', 'Selection withdrawn; select it again');
423
+ const file = readConfined(grant, item.rel, this.env, { selected: item });
424
+ pinCheck(grant, this.localPin(), this.env);
425
+ this.message(`Upload ${file.rel} (${file.size} B) to ${project.name} on ${this.origin}`);
426
+ item.source = await this.client.inputAdd(project.id, file.bytes, file.media);
427
+ checkDestination();
428
+ recordUpload(grant, file, item.source, this.env);
429
+ const offer = item.source.offer ?? await this.client.inputOffer(project.id, item.source);
430
+ if (!offer.extracts.length) throw new CliError("extraction_unavailable", "This file has no selectable extracts");
431
+ selections.push({ source_handle: { cas_ref: item.source.cas_ref, acquisition_ref: item.source.acquisition_ref },
432
+ offer_id: offer.id, selected_extract_ids: offer.extracts.map(extract => extract.id).sort(), method: "exact-extract" });
433
+ }
434
+ selections.sort((a, b) => a.source_handle.cas_ref.localeCompare(b.source_handle.cas_ref)
435
+ || a.source_handle.acquisition_ref.localeCompare(b.source_handle.acquisition_ref));
436
+ const body = { ask: text, attachments: selections.map(item => item.source_handle),
437
+ parent_state_hash: newest?.state_hash ?? null, ui_context: { layout: 'folder' },
438
+ ...(selections.length ? { selections } : {}), ...(this.model ? { model_choice: this.model } : {}) };
439
+ return this.admitPendingLocked(this.registry.reserveRun(project.id, body, draftRef));
440
+ }, this.env);
441
+ void this.follow().catch(error => this.report(error));
442
+ } catch(error) {
443
+ if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest();
444
+ else if(error.code==='run_busy' && this.run?.open) void this.follow().catch(error=>this.report(error));
445
+ throw error;
381
446
  } finally { this.busy = false; this.change(); }
382
447
  }
383
448
 
384
449
  async admitPending(pending) {
450
+ try { await withAdmissionLock(() => this.admitPendingLocked(pending), this.env); }
451
+ catch(error) { if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest(); throw error; }
452
+ void this.follow().catch(error=>this.report(error));
453
+ }
454
+
455
+ async admitPendingLocked(pending) {
385
456
  if (this.project?.id !== pending.projectId) {
386
457
  const project = await this.client.projectGet(pending.projectId);
387
458
  this.followController?.abort(); this.generation++; this.run = null; this.project = project; this.change();
@@ -389,32 +460,33 @@ export class Session extends EventEmitter {
389
460
  let ack;
390
461
  try { ack = await this.client.runAdmit(pending.projectId, pending.body, pending.key); }
391
462
  catch (error) {
392
- if (["state_busy", "state_fork"].includes(error.code)) {
463
+ const worded = OWNER_WORDED.includes(error.code);
464
+ if (["state_busy", "state_fork"].includes(error.code) || error.admission === "refused" || worded) {
393
465
  this.registry.rejectRunAdmission(pending.key);
394
- await this.loadNewest();
466
+ }
467
+ if (["state_busy", "state_fork"].includes(error.code)) {
395
468
  throw new CliError(error.code, "Submission refused; draft kept. Review the latest Run and explicitly send again.");
396
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.`);
397
472
  // The owner marked this key as never admittable (nothing dispatched): release only this
398
473
  // reservation and keep the draft. Any other failure stays pending for /resume.
399
- if (error.admission === "refused") {
400
- this.registry.rejectRunAdmission(pending.key);
401
- throw new CliError(error.code, "Submission refused before it ran; draft kept. Fix it and send again.");
402
- }
474
+ if (error.admission === "refused") throw new CliError(error.code, "Submission refused before it ran; draft kept. Fix it and send again.");
403
475
  throw error;
404
476
  }
405
477
  this.registry.finishRunAdmission(pending.key);
406
478
  if (this.draft === pending.body.ask) { clearTimeout(this.draftTimer); this.draft = ""; }
407
479
  this.attachments = [];
408
480
  this.message(pending.body.ask, "user");
409
- this.run = { ...ack, events: [], terminal: "", open: true };
481
+ this.run = { ...ack, ask: pending.body.ask, events: [], terminal: "", open: true };
410
482
  this.status = "Running"; this.change();
411
- void this.follow().catch(error => this.report(error));
412
483
  }
413
484
 
414
485
  async resume() {
415
486
  if (this.offline) { this.offline = false; return this.initialize(); }
416
487
  if (this.busy) throw new CliError("session_busy", "This submission is already being reconciled");
417
488
  if (!this.account || !this.registry) return this.initialize();
489
+ await withAdmissionLock(() => reconcileAdmissions(this.client, this.origin, this.env), this.env);
418
490
  const state = this.registry.state();
419
491
  if (state.pendingRun) {
420
492
  this.busy = true; this.change();
@@ -432,56 +504,322 @@ export class Session extends EventEmitter {
432
504
  const run = this.run; const generation = ++this.generation;
433
505
  const projectId = this.project.id;
434
506
  let attempts = 0;
435
- while (!this.closed && generation === this.generation && run?.open) {
436
- try {
437
- const direct = await this.client.runEvents(run.run_id, event => {
438
- if (generation !== this.generation) return;
439
- run.events.push(event);
440
- this.status = runView(run, this.projectionCache).question ? "Waiting for your answer" : "Running";
441
- this.change();
442
- }, controller.signal, [...run.events]);
443
- if (generation !== this.generation) return;
444
- this.run = { ...direct, accepted_at: direct.run_id === run.run_id ? run.accepted_at : undefined, open: !direct.terminal };
445
- this.status = direct.terminal; this.announceRun();
507
+ try {
508
+ while (!this.closed && generation === this.generation && run?.open) {
446
509
  try {
447
- const cost = await this.client.customerCost(projectId);
448
- if (generation === this.generation) this.message(humanCost(cost), "cost", { value: cost });
449
- } catch (error) { if (generation === this.generation) this.message(`Usage unavailable: ${error.code}`); }
450
- this.change(); return;
451
- } catch (error) {
452
- if (controller.signal.aborted || this.closed || generation !== this.generation) return;
453
- if (AUTH_ERRORS.has(error.code)) { this.report(error); return; }
454
- if (!TRANSIENT.has(error.code) || ++attempts > 5) throw error;
455
- this.status = "Connection lost — reconnecting to the same Run"; this.change();
456
- await delay(Math.min(500 * 2 ** attempts, 8_000), controller.signal);
510
+ const direct = await this.client.runEvents(run.run_id, event => {
511
+ if (generation !== this.generation) return;
512
+ run.events.push(event); this.status = "Running"; this.change();
513
+ }, controller.signal, [...run.events]);
514
+ if (generation !== this.generation) return;
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();
518
+ if (generation !== this.generation) return;
519
+ await this.announceFooter(projectId);
520
+ this.change(); await this.offerSaves().catch(error=>this.report(error)); return;
521
+ } catch (error) {
522
+ if (controller.signal.aborted || this.closed || generation !== this.generation) return;
523
+ if (AUTH_ERRORS.has(error.code)) { this.report(error); return; }
524
+ if (!TRANSIENT.has(error.code) || ++attempts > 5) throw error;
525
+ this.status = "Connection lost — reconnecting to the same Run"; this.change();
526
+ await delay(Math.min(500 * 2 ** attempts, 8_000), controller.signal);
527
+ }
457
528
  }
458
- }
529
+ } finally { controller.abort(); }
459
530
  }
460
531
 
461
532
  attach(path) { return this.transition(() => this.selectAttachment(path)); }
462
533
 
534
+ localPin() {
535
+ return { origin: this.origin, accountId: this.account?.id, projectId: this.project?.id, role: this.project?.role,
536
+ root: this.registry.folder, provenance: this.provenance ?? 'binding', binding: () => this.registry.binding(),
537
+ credential: this.activeCredential ?? { kind: this.env.VECTEUR_TOKEN ? 'environment' : 'stored', token: this.env.VECTEUR_TOKEN ?? readCredentials(this.env)?.logins?.[this.origin]?.token } };
538
+ }
539
+
540
+ fileConsentText(destination) {
541
+ const project = destination.id ? destination.name : `a new Project named ${destination.name}`;
542
+ return `Allow Vecteur to read files you select in ${this.registry.folder.path} and save new files it makes there? Files you select upload to ${project} on ${destination.origin}; their content reaches this Run's model provider route; local residency is not guaranteed.`;
543
+ }
544
+
545
+ async confirmFiles(destination) {
546
+ const files = this.attachments;
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')}`, [
548
+ { label: 'Yes, allow select and save-new', value: true }, { label: 'No, keep draft and selections', value: false },
549
+ ], { liveTitle: `Send ${files.length} selected file${files.length===1?'':'s'}?` });
550
+ }
551
+
463
552
  async selectAttachment(path) {
464
- if (this.registry?.state().pendingRun) throw new CliError("submission_pending", "Resolve the pending submission before changing its files");
465
- const filename = resolve(this.cwd, path);
466
- const handle = await open(filename, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
467
- let bytes;
468
- try {
469
- const info = await handle.stat();
470
- if (!info.isFile() || info.size <= 0 || info.size > 8 * 1024 * 1024) throw new CliError("attachment_invalid", "Select one non-empty file no larger than 8 MiB");
471
- bytes = await handle.readFile();
472
- const after = await handle.stat();
473
- if (bytes.length !== info.size || after.size !== info.size || after.mtimeMs !== info.mtimeMs
474
- || after.ctimeMs !== info.ctimeMs) throw new CliError("attachment_changed", "File changed while reading; select it again");
475
- } finally { await handle.close(); }
476
- if (this.attachments.length >= 8 || this.attachments.reduce((sum, item) => sum + item.bytes.length, bytes.length) > 32 * 1024 * 1024) {
477
- throw new CliError("attachments_full", "Select at most 8 files and 32 MiB per turn; /clear-files removes pending files");
553
+ if (this.project?.role === 'VIEWER') throw new CliError('role_forbidden', 'Editor access is required to select upload files');
554
+ if (this.registry?.state().pendingRun) throw new CliError('submission_pending', 'Resolve the pending submission before changing its files');
555
+ if (!this.registry) this.unsignedDraft();
556
+ const rel = isAbsolute(path) ? relative(this.registry.folder.path, path) : path;
557
+ const item = selectionMetadata(this.registry.folder, rel, this.env);
558
+ if (this.attachments.some(f => f.rel === item.rel)) return;
559
+ if (this.attachments.length >= 8 || this.attachments.reduce((sum, f) => sum + f.size, item.size) > 32 * 1024 * 1024) throw new CliError('attachments_full', 'Select at most 8 files and 32 MiB per turn');
560
+ const grant = this.project && currentGrant(this.localPin(), this.env);
561
+ this.attachments.push({ ...item, ...(grant ? { generation: grant.generation } : {}) });
562
+ this.message(`Upload ${item.rel} (${item.size} B) to ${this.project?.name ?? 'a new Project'} on ${this.origin} · on send`);
563
+ this.change();
564
+ }
565
+
566
+ async completeFiles(prefix) {
567
+ if (!this.registry) this.unsignedDraft();
568
+ return discover(this.registry.folder, this.env, prefix).map(f => f.rel);
569
+ }
570
+
571
+ async offerAttachments(text) {
572
+ const mentions = [...text.matchAll(/(?:^|\s)@([^\s]+)/g)].map(m => m[1]);
573
+ for (const rel of mentions) await this.selectAttachment(rel);
574
+ const words = [...new Set(text.split(/\s+/).filter(w => w && !w.startsWith('@')))];
575
+ if (!words.length) return;
576
+ let files = [];
577
+ try { files = discover(this.registry.folder, this.env); }
578
+ catch (e) {
579
+ this.message(`File offers were unavailable (${e.code ?? 'discovery_failed'}); continuing without filename offers.`);
580
+ }
581
+ const notices = new Set(), blocked = new Set();
582
+ const notice = (name, code) => {
583
+ if (!notices.has(name)) this.message(`${name}: not offered (${code})`);
584
+ notices.add(name);
585
+ };
586
+ const selected = this.attachments.map(f => f.rel);
587
+ for (const name of words) {
588
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(name) || selected.includes(name.replace(/^\.\//,''))) continue;
589
+ try {
590
+ // Discovery intentionally hides excluded and non-regular entries. Check an
591
+ // explicitly named path through the same metadata-only selection boundary.
592
+ const file = selectionMetadata(this.registry.folder, name, this.env, { ifPresent: true });
593
+ if (!files.some(f=>f.rel===file.rel)) files.push(file);
594
+ } catch (e) {
595
+ if (e.code === 'ENOENT') continue;
596
+ if (!['excluded','path_excluded','outside_folder','symlink_refused','not_regular_file','hardlink_refused','attachment_invalid','ignore_policy_unknown'].includes(e.code)) throw e;
597
+ notice(name, e.code === 'excluded' ? 'path_excluded' : e.code); blocked.add(name);
598
+ }
599
+ }
600
+ let offers = 0;
601
+ for (const name of words.filter(w=>!blocked.has(w))) {
602
+ const matches = nameOffers(name, files, this.attachments.map(f=>f.rel))[0];
603
+ if (!matches) continue;
604
+ const grant = this.project && currentGrant(this.localPin(), this.env);
605
+ const safe = [];
606
+ for (const file of matches) {
607
+ try {
608
+ // Without a grant, offer metadata only. The common first-use card in
609
+ // submit must be accepted before the selected content is read/scanned.
610
+ if (grant) await withLocalLock(() => {
611
+ pinCheck(grant, this.localPin(), this.env);
612
+ // This preflight only decides the offer; upload rereads and rechecks
613
+ // the selection under the same grant before any network egress.
614
+ readConfined(grant, file.rel, this.env, { selected: file });
615
+ pinCheck(grant, this.localPin(), this.env);
616
+ }, this.env);
617
+ safe.push(file);
618
+ } catch (e) {
619
+ if (!['secret_suspected','scan_unsupported','excluded','path_excluded','outside_folder','symlink_refused','not_regular_file','hardlink_refused','attachment_invalid','attachment_changed'].includes(e.code)) throw e;
620
+ notice(matches.length === 1 ? name : file.rel, e.code === 'excluded' ? 'path_excluded' : e.code);
621
+ }
622
+ }
623
+ if (!safe.length || offers >= 3) continue;
624
+ offers++;
625
+ if (safe.length === 1) {
626
+ const file = safe[0];
627
+ if (await this.choose(`Attach ./${file.rel} (${file.size} B)? [y/N]`, [{label:'Yes',value:true},{label:'No',value:false}])) await this.selectAttachment(file.rel);
628
+ } else {
629
+ const rel = await this.choose('Ambiguous filename — choose a file to attach', [...safe.map(f => ({label:`./${f.rel} (${f.size} B)`,value:f.rel})),{label:'Do not attach',value:null}]);
630
+ if (rel) await this.selectAttachment(rel);
631
+ }
478
632
  }
479
- const ok = await this.choose(`Attach ${filename} (${bytes.length} bytes) to ${this.project?.name ?? "the Project created on send"} at ${this.origin}? Selected extracts go to the chosen model route.`, [
480
- { label: "Attach on next send", value: true }, { label: "Cancel", value: false },
633
+ if (notices.size) return this.choose('Send without these files?', [
634
+ {label:'Yes, send without these files',value:true}, {label:'No, keep draft',value:false},
481
635
  ]);
482
- if (!ok || this.closed) return;
483
- const extension = /\.[^.]+$/.exec(filename)?.[0].toLowerCase();
484
- this.attachments.push({ path: filename, bytes, media: MEDIA[extension] ?? "application/octet-stream" }); this.change();
636
+ }
637
+
638
+ async revokeFiles() {
639
+ this.requireLogin();
640
+ return withLocalLock(() => {
641
+ endGrants({origin:this.origin,accountId:this.account.id,root:this.registry.folder.path},this.env);
642
+ this.saveProposal = null;
643
+ this.message('Local file permission revoked; pending selections need fresh consent.');
644
+ }, this.env);
645
+ }
646
+
647
+ async scanLocalTargets() {
648
+ try {
649
+ qualify();
650
+ return await withLocalLock(()=>{
651
+ const pin = this.localPin(), grant = currentGrant(pin,this.env);
652
+ if (!grant) return proposals(pin,this.env);
653
+ pinCheck(grant,pin,this.env);
654
+ const reports = observeTargets(grant,this.env,pin);
655
+ for (const row of reports) this.message(`${terminalText(row.path)}: ${row.code}, local observation unavailable`);
656
+ return proposals(grant,this.env);
657
+ },this.env);
658
+ } catch (error) {
659
+ this.message(`${error.code}: local observation unavailable; cloud files remain available.`);
660
+ return [];
661
+ }
662
+ }
663
+
664
+ async confirmLocalRead(project, epoch) {
665
+ const prepared = epoch ?? await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env);
666
+ const answer = (await this.choose(`${this.fileConsentText({origin:this.origin,id:project.id,name:project.name})}\nEnter yes to allow local reads · n no`, [], {typed:true})).trim().toLowerCase();
667
+ if (!['','y','yes'].includes(answer)) return null;
668
+ return withLocalLock(()=>{
669
+ if (this.project!==project) throw new CliError('grant_changed','Diff destination changed');
670
+ const grant=createGrant(this.localPin(),this.env,prepared);
671
+ return pinCheck(grant,this.localPin(),this.env);
672
+ },this.env);
673
+ }
674
+
675
+ async listFiles() {
676
+ const rows = artifactRows(runView(this.run).artifacts);
677
+ const saved = this.account && this.project ? await this.scanLocalTargets() : [];
678
+ this.message([
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`),
681
+ ...saved.map((p,i)=>`${rows.length+i+1}. Proposal ${terminalText(p.path)} → ${terminalText(p.originalPath)} · /files diff ${rows.length+i+1}`),
682
+ ].join('\n') || 'No selected files or artifacts.');
683
+ }
684
+
685
+ async fileDiff(number) {
686
+ this.requireLogin();
687
+ if (!this.project) throw new CliError('project_unavailable','Choose a Project first');
688
+ const project=this.project, rows=artifactRows(runView(this.run).artifacts);
689
+ const saved=await this.scanLocalTargets();
690
+ const row=rows.find(r=>r.number===number), proposal=saved[number-rows.length-1];
691
+ const a=row?.artifact ?? (proposal && {path:proposal.originalPath,cas_ref:proposal.cas_ref,kind:'code'});
692
+ if (!a?.path) throw new CliError('artifact_unavailable','Choose a file number from /files');
693
+ // Historical proposals retain their artifact kind in the scoped journal.
694
+ const kind=row?.artifact.kind ?? proposal.kind;
695
+ let grant=await withLocalLock(()=>{
696
+ const live=currentGrant(this.localPin(),this.env);
697
+ return live ? pinCheck(live,this.localPin(),this.env) : null;
698
+ },this.env);
699
+ grant ??= await this.confirmLocalRead(project);
700
+ if (!grant) return;
701
+ const bytes=await downloadLocalArtifact(sink=>this.client.artifactGet(a.cas_ref,project.id,sink),{...a,kind});
702
+ const snapshot=await withLocalLock(()=>{
703
+ if(this.project!==project)throw new CliError('grant_changed','Diff destination changed');
704
+ return inspectTarget(grant,a.path,a.cas_ref.slice(7),this.env,this.localPin());
705
+ },this.env);
706
+ this.message(proposalReview(a.path,snapshot,bytes));
707
+ }
708
+
709
+ async offerSaves(number) {
710
+ if (!this.account || !this.project || !this.run?.terminal || this.project.role === 'VIEWER') return;
711
+ try { qualify(); } catch (e) { if (number) throw e; return; }
712
+ const run = this.run, project = this.project;
713
+ if ((await this.client.projectNewestRun(project.id))?.run_id !== run.run_id) return;
714
+ if (this.project !== project || this.run !== run) throw new CliError('grant_changed','Save destination changed');
715
+ const grant = currentGrant(this.localPin(), this.env);
716
+ const provisional = grant ?? { ...this.localPin(), generation: null };
717
+ const candidates = [], selected = new Set();
718
+ const normalize = (row, snapshot) => {
719
+ row.snapshot=snapshot;
720
+ row.creates=snapshot.creates;
721
+ row.proposalPath=snapshot.exists?proposalName(row.artifact.path,run.run_id,row.artifact.revision):null;
722
+ row.eligible=snapshot.classification!=='already identical'
723
+ && (snapshot.exists || !!number || !tombstoned(provisional,row.artifact.path,this.env));
724
+ if(!row.eligible) {
725
+ selected.delete(row);
726
+ if(snapshot.classification==='already identical')this.message(`${terminalText(row.artifact.path)}: already identical`);
727
+ }
728
+ return row.eligible;
729
+ };
730
+ for (const row of artifactRows(runView(run).artifacts)) {
731
+ const a = row.artifact;
732
+ if (!a.path || number && row.number !== number) continue;
733
+ try {
734
+ const eligible=await withLocalLock(()=>normalize(row,grant
735
+ ? inspectTarget(grant,a.path,a.cas_ref.slice(7),this.env,this.localPin())
736
+ : observeTargetMetadata(provisional,a.path,this.env)),this.env);
737
+ if(!eligible)continue;
738
+ if (row.snapshot.exists) {
739
+ row.bytes=await downloadLocalArtifact(sink=>this.client.artifactGet(a.cas_ref,project.id,sink),a);
740
+ if(grant) await withLocalLock(()=>pinCheck(grant,this.localPin(),this.env),this.env);
741
+ }
742
+ candidates.push(row);
743
+ } catch (e) { this.message(`${a.path}: ${e.code}, not written · /download ${row.number}`); }
744
+ }
745
+ const current = candidates; // runArtifacts already owns current-revision selection.
746
+ if (!current.length) return;
747
+ for (const row of [...current].sort((a,b) => a.artifact.path.length-b.artifact.path.length || a.artifact.path.localeCompare(b.artifact.path))) if (![...selected].some(r => r.artifact.cas_ref === row.artifact.cas_ref)) selected.add(row);
748
+ const proposal = { runId: run.run_id, projectId:project.id, generation: grant?.generation ?? null, rows:current.map(row => ({ ...row, artifact:structuredClone(row.artifact) })) };
749
+ this.saveProposal = proposal;
750
+ const epoch = !grant ? await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env) : null;
751
+ const rowLabel=row=>{
752
+ const a=row.artifact;
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}`:''}`)
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':'');
755
+ };
756
+ let live=grant;
757
+ while (true) {
758
+ if(live) await withLocalLock(()=>pinCheck(live,this.localPin(),this.env),this.env);
759
+ const paths = [...selected].map(row => row.artifact.path);
760
+ if (!paths.length) break;
761
+ const beside=[...selected].some(r=>r.proposalPath);
762
+ const question=beside && selected.size===1 ? `${terminalText(paths[0])} exists here. Save Vecteur's version beside it as ${terminalText([...selected][0].proposalPath)}?` : `Save ${paths.length} new file${paths.length===1?'':'s'} to ${terminalText(this.cwd)}?`;
763
+ const answer = (await this.choose(`${!live?this.fileConsentText({origin:this.origin,id:project.id,name:project.name})+'\n':''}${question} Enter yes · d ${beside?'diff':'show'} · n no\n${current.filter(r=>r.eligible && !r.written).map(rowLabel).join('\n')}`, [], {typed:true,liveTitle:`${beside&&selected.size===1?'Save beside':'Save '+paths.length}? Enter yes · d ${beside?'diff':'show'} · n no`})).trim().toLowerCase();
764
+ if (answer === 'n' || answer === 'no') { this.saveProposal=null; return; }
765
+ if (answer === 'd') {
766
+ if(!live) {
767
+ live=await this.confirmLocalRead(project,epoch);
768
+ if(!live){this.saveProposal=null;return;}
769
+ proposal.generation=live.generation;
770
+ }
771
+ await withLocalLock(()=>{
772
+ for(const row of selected) {
773
+ normalize(row,inspectTarget(live,row.artifact.path,row.artifact.cas_ref.slice(7),this.env,this.localPin()));
774
+ if(row.bytes)this.message(proposalReview(row.artifact.path,row.snapshot,row.bytes));
775
+ }
776
+ },this.env);
777
+ if(current.length===1 && beside)continue;
778
+ const eligible=current.filter(r=>r.eligible && !r.written);
779
+ if(!eligible.length)break;
780
+ const choices = await this.choose('Every candidate (choose numbers separated by commas)', eligible.map(row=>({label:rowLabel(row),value:row})),{multiple:true});
781
+ selected.clear(); for (const row of choices) if(eligible.includes(row))selected.add(row); continue;
782
+ }
783
+ if (!['','y','yes'].includes(answer)) { this.message('Enter yes, d or n.'); continue; }
784
+ await withLocalLock(()=>{
785
+ if(this.project!==project || this.run!==run)throw new CliError('grant_changed','Save proposal withdrawn');
786
+ live=currentGrant(this.localPin(),this.env);
787
+ if(proposal.generation===null){
788
+ if(live)throw new CliError('grant_changed','Permission changed during confirmation; review again');
789
+ live=createGrant(this.localPin(),this.env,epoch);proposal.generation=live.generation;
790
+ }
791
+ },this.env);
792
+ if (!live || live.generation !== proposal.generation || this.project.id !== proposal.projectId) throw new CliError('grant_changed','Save proposal withdrawn; confirm again');
793
+ if([...selected].some(row=>row.snapshot.exists && !row.snapshot.classification)) {
794
+ await withLocalLock(()=>{
795
+ for(const row of selected)normalize(row,inspectTarget(live,row.artifact.path,row.artifact.cas_ref.slice(7),this.env,this.localPin()));
796
+ },this.env);
797
+ continue;
798
+ }
799
+ for (const row of selected) {
800
+ const artifact = proposal.rows.find(r => r.number===row.number).artifact;
801
+ try {
802
+ const writer=row.proposalPath?writeProposalConfined:writeNewConfined;
803
+ const fetch=row.bytes?async sink=>{sink(row.bytes);return {bytes:row.bytes.length,content_type:ARTIFACT_MEDIA_TYPES[artifact.kind]};}:sink=>this.client.artifactGet(artifact.cas_ref,project.id,sink);
804
+ const saved = await writer(live, artifact.path, fetch, { ...artifact, runId:proposal.runId }, {env:this.env,pin:()=>this.localPin(),head:id=>this.client.projectNewestRun(id),approval:{rel:artifact.path,exists:row.snapshot.exists,sha256:row.snapshot.sha256}});
805
+ this.message(terminalText(`Saved ${relative(this.cwd,saved.path)} (${saved.bytes} B)`));
806
+ if(row.proposalPath)this.message(terminalText(adoptionHint(relative(this.cwd,saved.path),artifact.path)));
807
+ row.written=true;selected.delete(row);
808
+ } catch(e) {
809
+ if(e.code!=='target_changed')throw e;
810
+ this.message(e.message);
811
+ await withLocalLock(()=>normalize(row,inspectTarget(live,artifact.path,artifact.cas_ref.slice(7),this.env,this.localPin())),this.env);
812
+ if(!row.eligible)continue;
813
+ row.bytes ??= await downloadLocalArtifact(sink=>this.client.artifactGet(artifact.cas_ref,project.id,sink),artifact);
814
+ await withLocalLock(()=>{
815
+ normalize(row,inspectTarget(live,artifact.path,artifact.cas_ref.slice(7),this.env,this.localPin()));
816
+ if(row.eligible)this.message(proposalReview(artifact.path,row.snapshot,row.bytes));
817
+ },this.env);
818
+ break;
819
+ }
820
+ }
821
+ }
822
+ this.saveProposal = null;
485
823
  }
486
824
 
487
825
  link(options = {}) { return this.transition(() => this.selectProject(options)); }
@@ -496,18 +834,21 @@ export class Session extends EventEmitter {
496
834
  const id = await this.choose("Choose an existing Project", this.projects.map(row => ({ label: `${row.name} (${row.role})`, value: row.id })));
497
835
  if (this.closed) return;
498
836
  const project = this.projects.find(row => row.id === id);
499
- if (persist) {
500
- try { this.registry.bind(id); }
501
- catch (error) {
502
- if (!["home_binding_confirmation", "root_binding_confirmation"].includes(error.code)) throw error;
503
- const answer = await this.choose(error.message, [], { typed: true });
504
- if (answer !== this.cwd) throw new CliError("binding_cancelled", "Broad directory binding was not confirmed");
505
- this.registry.bind(id, { confirmBroad: true });
837
+ await withAdmissionLock(async () => {
838
+ if (this.project?.id !== id) endGrants({origin:this.origin,accountId:this.account.id,root:this.registry.folder.path},this.env);
839
+ if (persist) {
840
+ try { this.registry.bind(id); }
841
+ catch (error) {
842
+ if (!["home_binding_confirmation", "root_binding_confirmation"].includes(error.code)) throw error;
843
+ const answer = await this.choose(error.message, [], { typed: true });
844
+ if (answer !== this.cwd) throw new CliError("binding_cancelled", "Broad directory binding was not confirmed");
845
+ this.registry.bind(id, { confirmBroad: true });
846
+ }
506
847
  }
507
- }
508
- this.followController?.abort(); this.generation++;
509
- this.binding = this.registry.binding();
510
- this.attachments = []; this.project = project; this.run = null; this.status = "Ready"; this.change();
848
+ this.followController?.abort(); this.generation++;
849
+ this.binding = this.registry.binding(); this.provenance = persist ? "binding" : "explicit";
850
+ this.attachments = []; this.project = project; this.run = null; this.status = "Ready"; this.change();
851
+ }, this.env);
511
852
  await this.loadNewest();
512
853
  }
513
854
 
@@ -546,88 +887,23 @@ export class Session extends EventEmitter {
546
887
  this.run = { ...selected.response, accepted_at: selected.accepted_at, open: !selected.response.terminal };
547
888
  this.message(selected.request.ask, "user");
548
889
  if (this.run.open) void this.follow().catch(error => this.report(error));
549
- else this.message(runView(this.run).transcript, "answer", { runId: this.run.run_id, sections: runSections(this.run) });
890
+ else { this.message(humanRun(this.run), "answer", { runId: this.run.run_id, sections: runSections(this.run) }); await this.announceFooter(this.project.id); }
550
891
  this.status = "Viewing history — next send continues the current Project head"; this.change();
551
892
  return;
552
893
  }
553
894
  }
554
895
 
555
- async steer(text) {
556
- this.requireLogin();
557
- if (!this.run?.open) throw new CliError("run_not_open", "There is no open Run to steer");
558
- const control = { id: randomUUID(), kind: text ? "steer" : "answer_now", ...(text ? { text } : {}) };
559
- const run = this.run, client = this.client;
560
- const value = await client.runControl(run.run_id, control);
561
- if (this.run !== run || this.client !== client) return;
562
- this.message(`Instruction ${value.state}; acceptance does not mean it was executed.`);
563
- }
564
-
565
- async answer() {
566
- this.requireLogin();
567
- const run = this.run, client = this.client;
568
- const question = runView(run).question;
569
- if (!question?.questions?.length) throw new CliError("question_unavailable", "There is no pending clarification");
570
- const current = () => {
571
- this.requireLogin();
572
- 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");
573
- };
574
- if (this.clarificationDraft?.run !== run || this.clarificationDraft?.client !== client || this.clarificationDraft?.id !== question.id) {
575
- this.clarificationDraft = { run, client, id: question.id, answers: [] };
576
- }
577
- const { answers } = this.clarificationDraft;
578
- while (true) {
579
- for (const item of question.questions.slice(answers.length)) {
580
- const options = [...item.options.map(option => ({ label: `${option.label}${option.description ? ` — ${option.description}` : ""}`, value: option.label })),
581
- { label: "Write an answer", value: null }];
582
- const response = item.options.length ? await this.choose(
583
- item.question + (item.multiSelect ? " (choose numbers separated by commas)" : ""), options,
584
- { multiple: item.multiSelect === true }) : null;
585
- const selected = Array.isArray(response) ? response : [response];
586
- const answer = { id: item.id, selected: selected.filter(value => value !== null) };
587
- if (selected.includes(null)) {
588
- do { answer.custom = await this.choose(item.question, [], { typed: true }); }
589
- while (!answer.custom.trim());
590
- }
591
- answers.push(answer);
592
- current();
593
- }
594
- current();
595
- this.message(answers.map((answer, i) => `${question.questions[i].question}\n${[...answer.selected, answer.custom].filter(Boolean).join('; ')}`).join("\n\n"));
596
- const action = await this.choose("Review your answers before sending", [
597
- { label: "Submit these answers", value: "submit" }, { label: "Change answers", value: "edit" },
598
- { label: "Keep answers for later in this session", value: "later" },
599
- ]);
600
- current();
601
- if (action === "later") return;
602
- if (action === "submit") break;
603
- answers.length = 0;
604
- }
605
- await this.client.clarificationAnswer(this.run.run_id, question.id, answers);
606
- this.clarificationDraft = null;
607
- this.status = "Answer submitted"; this.change();
608
- }
609
-
610
896
  modelChoice() { return this.transition(() => this.selectModel()); }
611
897
 
612
898
  async selectModel() {
613
- if (!this.account || this.account.model_cost_estimates.catalogue_envelope_sha256 !== CATALOGUE_ENVELOPE_SHA256) {
614
- throw new CliError("catalogue_outdated", "Model catalogue differs from this CLI; install the origin's current version");
615
- }
616
- const options = [{ label: "Auto — Vecteur selects the model", value: null },
617
- ...PRODUCT_ROUTES.filter(row => row.route_id !== "auto").map(row => ({ label: `${row.label} · ${row.candidates.map(item => item.jurisdiction).join(" → ")}`, value: row.route_id })),
618
- ...MODEL_CATALOGUE.map(row => ({ label: `${row.label} · ${row.provider} · ${row.data_residency}`, value: row.profile_id }))];
619
- 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();
620
903
  }
621
904
 
622
905
  modeDetails() {
623
- const requested = this.model ?? "auto";
624
- const route = PRODUCT_ROUTES.find(row => row.route_id === requested);
625
- const profile = MODEL_CATALOGUE.find(row => row.profile_id === requested);
626
- const matched = this.account?.model_cost_estimates.catalogue_envelope_sha256 === CATALOGUE_ENVELOPE_SHA256;
627
- const destination = !matched ? "Catalogue unavailable or outdated — /login or update this CLI"
628
- : route ? route.candidates.map(row => `${row.provider_id}/${row.model_id} (${row.jurisdiction})`).join(" → ")
629
- : profile ? `${profile.provider} (${profile.data_residency})` : "Unknown";
630
- 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"}\nNative Claude/Codex modes and local execution are unavailable in this version.`;
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"}`;
631
907
  }
632
908
 
633
909
  statusDetails() {
@@ -645,7 +921,10 @@ export class Session extends EventEmitter {
645
921
  await client.credentialSelfRevoke();
646
922
  if (client !== this.client || this.closed) return;
647
923
  clearTimeout(this.draftTimer); this.registry?.saveDraft(this.draft);
648
- if (!this.env.VECTEUR_TOKEN) clearCredentials(this.env, this.origin);
924
+ await withAdmissionLock(() => {
925
+ if (!this.env.VECTEUR_TOKEN) clearCredentials(this.env, this.origin);
926
+ else endGrants({origin:this.origin,accountId:this.account.id},this.env);
927
+ },this.env);
649
928
  this.signedOut = true;
650
929
  this.env = { ...this.env }; delete this.env.VECTEUR_TOKEN;
651
930
  this.followController?.abort(); this.generation++; this.account = null; this.project = null;