@vecteur/cli 0.9.1 → 0.11.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +224 -15
- package/bin/vecteur.js +107 -10
- package/package.json +5 -1
- package/src/blocks.js +201 -6
- package/src/client.js +280 -29
- package/src/commands.js +56 -15
- package/src/contract.js +35 -7
- package/src/credentials.js +8 -0
- package/src/errors.js +4 -1
- package/src/exchange.js +85 -0
- package/src/executor.js +171 -0
- package/src/folders.js +28 -2
- package/src/format.js +332 -28
- package/src/input.js +22 -3
- package/src/localfiles.js +788 -0
- package/src/mcp.js +143 -9
- package/src/produce.js +49 -0
- package/src/session.js +697 -104
- package/src/terminal.js +189 -54
- package/src/tui/view.js +342 -124
package/src/session.js
CHANGED
|
@@ -1,22 +1,64 @@
|
|
|
1
|
+
import { Executor } from "./executor.js";
|
|
1
2
|
import { EventEmitter } from "node:events";
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { basename, relative, resolve } from "node:path";
|
|
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";
|
|
6
7
|
import { VecteurClient, CliError, configuration, delay, isTokenShaped, requestTimeout,
|
|
7
8
|
resolveOrigin, shouldOpenBrowser, waitForDeviceAuthorization } from "./client.js";
|
|
8
9
|
import { readCredentials, writeCredentials, clearCredentials } from "./credentials.js";
|
|
9
10
|
import { FolderRegistry, UNSIGNED_ACCOUNT } from "./folders.js";
|
|
10
11
|
import { runView } from "./blocks.js";
|
|
12
|
+
import { produceIntent } from "./produce.js";
|
|
11
13
|
import { downloadArtifact, exportRun } from "./download.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
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,
|
|
16
|
+
readConfined, recordUpload, discover, nameOffers, tombstoned, writeNewConfined,
|
|
17
|
+
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";
|
|
14
20
|
import { openBrowser } from "./browser.js";
|
|
15
21
|
|
|
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
|
+
export const NEW_FOLDER = "New folder — send an ask or /link an existing Project";
|
|
16
59
|
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
|
|
17
61
|
const TRANSIENT = new Set(["request_failed", "request_timeout", "terminal_invalid"]);
|
|
18
|
-
const MEDIA = { ".txt": "text/plain", ".md": "text/markdown", ".csv": "text/csv", ".json": "application/json",
|
|
19
|
-
".pdf": "application/pdf", ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document" };
|
|
20
62
|
|
|
21
63
|
/** One cloud session, two real renderers. It owns no terminal, device or native-agent runtime. */
|
|
22
64
|
export class Session extends EventEmitter {
|
|
@@ -45,7 +87,10 @@ export class Session extends EventEmitter {
|
|
|
45
87
|
projectLabel: this.project?.name ?? (this.binding ? "Linked Project unavailable" : "New Project on first send"),
|
|
46
88
|
status: activity + (canEdit ? "" : " · Read-only — Viewer") + (projection.terminal ? ` · ${projection.elapsed}` : ""), draft: this.draft, prompt: this.prompt, busy: this.busy,
|
|
47
89
|
offline: this.offline, issue: this.issue, login: this.loginChallenge, release: this.release,
|
|
48
|
-
|
|
90
|
+
// First use: signed in and online, the folder resolved to no binding/Project/Run, nothing pending.
|
|
91
|
+
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,
|
|
49
94
|
lead: "Laplace", location: "Vecteur cloud", model: modelLabel,
|
|
50
95
|
run: projection, available: { submit: !this.offline && !!this.account && canEdit && !this.busy && !this.run?.open,
|
|
51
96
|
cancel: !this.offline && !!this.account && canEdit && !!this.run?.open, steer: !this.offline && !!this.account && canEdit && !!this.run?.open && !projection.question,
|
|
@@ -66,10 +111,10 @@ export class Session extends EventEmitter {
|
|
|
66
111
|
this.change();
|
|
67
112
|
}
|
|
68
113
|
|
|
69
|
-
async choose(title, options, { typed = false, multiple = false } = {}) {
|
|
114
|
+
async choose(title, options, { typed = false, multiple = false, liveTitle } = {}) {
|
|
70
115
|
if (this.prompt) throw new CliError("prompt_busy", "Answer the current question first");
|
|
71
116
|
return new Promise((resolveChoice, reject) => {
|
|
72
|
-
this.prompt = { id: ++this.promptGeneration, title, options, typed, multiple };
|
|
117
|
+
this.prompt = { id: ++this.promptGeneration, title: liveTitle ?? title, card: liveTitle ? title : undefined, options, typed, multiple };
|
|
73
118
|
this.resolvePrompt = answer => { this.prompt = null; this.resolvePrompt = null; this.rejectPrompt = null; this.change(); resolveChoice(answer); };
|
|
74
119
|
this.rejectPrompt = reject;
|
|
75
120
|
this.change();
|
|
@@ -87,6 +132,7 @@ export class Session extends EventEmitter {
|
|
|
87
132
|
}
|
|
88
133
|
|
|
89
134
|
workOffline() {
|
|
135
|
+
this.executor?.stop(); this.execAllowed = false;
|
|
90
136
|
this.cancelLogin(); this.cancelPrompt(); this.followController?.abort(); this.generation++;
|
|
91
137
|
this.offline = true; this.issue = null;
|
|
92
138
|
if (!this.registry) {
|
|
@@ -222,6 +268,7 @@ export class Session extends EventEmitter {
|
|
|
222
268
|
this.model = null; this.projectName = null; this.lastPrintedRun = null;
|
|
223
269
|
}
|
|
224
270
|
this.account = account;
|
|
271
|
+
this.activeCredential = { kind: this.env.VECTEUR_TOKEN ? 'environment' : 'stored', token };
|
|
225
272
|
const newRegistry = !this.registry || this.registry.accountId !== account.id;
|
|
226
273
|
if (newRegistry) this.registry = new FolderRegistry({ origin: this.origin, accountId: account.id, cwd: this.cwd, env: this.env });
|
|
227
274
|
if (newRegistry && this.draft) {
|
|
@@ -229,6 +276,13 @@ export class Session extends EventEmitter {
|
|
|
229
276
|
else this.registry.newDraft();
|
|
230
277
|
}
|
|
231
278
|
this.registry.rememberLogin(token);
|
|
279
|
+
this.client.localEnv = this.env;
|
|
280
|
+
try {
|
|
281
|
+
qualify();
|
|
282
|
+
const reports = await withLocalLock(() => reconcileWrites(this.env), this.env);
|
|
283
|
+
for (const report of reports) if (report.remains.length) this.message(`Local save recovery: ${JSON.stringify(report)}`);
|
|
284
|
+
} catch (error) { if (error.code !== 'platform_unqualified') throw error; }
|
|
285
|
+
|
|
232
286
|
this.cwd = this.registry.folder.path;
|
|
233
287
|
if (!this.draft) {
|
|
234
288
|
const drafts = this.registry.state().drafts;
|
|
@@ -245,6 +299,7 @@ export class Session extends EventEmitter {
|
|
|
245
299
|
if (!current()) return;
|
|
246
300
|
this.projects = projects;
|
|
247
301
|
const binding = this.registry.binding(); this.binding = binding;
|
|
302
|
+
this.provenance = "binding";
|
|
248
303
|
if (binding && binding.state !== "bound") {
|
|
249
304
|
this.status = "Folder identity changed — /unlink before relinking"; this.change(); return;
|
|
250
305
|
}
|
|
@@ -252,7 +307,7 @@ export class Session extends EventEmitter {
|
|
|
252
307
|
this.project = this.projects.find(project => project.id === binding.projectId) ?? null;
|
|
253
308
|
if (!this.project) { this.status = "Linked Project unavailable — /project or /unlink"; this.change(); return; }
|
|
254
309
|
}
|
|
255
|
-
this.status = this.project ? "Ready" :
|
|
310
|
+
this.status = this.project ? "Ready" : NEW_FOLDER;
|
|
256
311
|
const pending = this.registry.state();
|
|
257
312
|
if (pending.pendingRun || pending.pendingCreate) {
|
|
258
313
|
this.followController?.abort(); this.generation++; this.run = null;
|
|
@@ -261,6 +316,7 @@ export class Session extends EventEmitter {
|
|
|
261
316
|
this.change(); return;
|
|
262
317
|
}
|
|
263
318
|
this.change();
|
|
319
|
+
if (this.project) await this.scanLocalTargets();
|
|
264
320
|
await this.loadNewest();
|
|
265
321
|
}
|
|
266
322
|
|
|
@@ -271,18 +327,29 @@ export class Session extends EventEmitter {
|
|
|
271
327
|
if (this.closed || generation !== this.generation) return;
|
|
272
328
|
if (newest) {
|
|
273
329
|
this.run = { ...newest, open: !newest.terminal };
|
|
330
|
+
if (newest.run_id !== this.lastPrintedRun && newest.ask !== undefined) this.message(newest.ask, "user");
|
|
274
331
|
if (this.run.open) {
|
|
275
332
|
this.status = runView(this.run, this.projectionCache).question ? "Waiting for your answer" : "Running";
|
|
276
333
|
this.change(); void this.follow().catch(error => this.report(error));
|
|
277
334
|
}
|
|
278
|
-
else { this.status = newest.terminal; this.announceRun(); this.change(); }
|
|
335
|
+
else { this.status = newest.terminal; if (this.announceRun()) await this.announceFooter(this.project.id); this.change(); await this.offerSaves(); }
|
|
279
336
|
} else { this.run = null; this.change(); }
|
|
280
337
|
}
|
|
281
338
|
}
|
|
282
339
|
|
|
283
|
-
announceRun() {
|
|
284
|
-
if (this.lastPrintedRun === this.run?.run_id) return;
|
|
285
|
-
|
|
340
|
+
announceRun(stopOffer = undefined) {
|
|
341
|
+
if (this.lastPrintedRun === this.run?.run_id) return false;
|
|
342
|
+
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;
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async announceFooter(projectId) {
|
|
348
|
+
const run = this.run;
|
|
349
|
+
let cost;
|
|
350
|
+
try { cost = await this.client.customerCost(projectId); }
|
|
351
|
+
catch { /* A missing cost read is explicitly unavailable, never a guessed amount. */ }
|
|
352
|
+
if (this.run === run && !this.closed) this.message(turnFooter(run, cost), "turn-footer", { run, value: cost });
|
|
286
353
|
}
|
|
287
354
|
|
|
288
355
|
recoverDraft() {
|
|
@@ -307,7 +374,7 @@ export class Session extends EventEmitter {
|
|
|
307
374
|
this.change();
|
|
308
375
|
}
|
|
309
376
|
|
|
310
|
-
async ensureProject() {
|
|
377
|
+
async ensureProject(consent = undefined) {
|
|
311
378
|
if (!this.account) throw new CliError("login_required", "Sign in with /login; your draft is kept");
|
|
312
379
|
if (this.project) return this.project;
|
|
313
380
|
if (this.registry.binding()) throw new CliError("binding_unavailable", "Resolve the existing binding with /project or /unlink");
|
|
@@ -323,12 +390,28 @@ export class Session extends EventEmitter {
|
|
|
323
390
|
const pending = this.registry.reserveCreation(this.projectName ?? basename(this.cwd), workspace);
|
|
324
391
|
const project = pending.projectId ? await this.client.projectGet(pending.projectId)
|
|
325
392
|
: await this.client.projectCreate(pending.name, pending.workspaceId, undefined, pending.key);
|
|
326
|
-
if (!pending.projectId)
|
|
327
|
-
|
|
393
|
+
if (!pending.projectId) await withAdmissionLock(() => {
|
|
394
|
+
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
|
+
this.registry.completeCreation(pending.key, project.id);
|
|
400
|
+
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
|
+
},this.env);
|
|
403
|
+
this.project = project; this.binding = this.registry.binding(); this.provenance = "binding";
|
|
328
404
|
return project;
|
|
329
405
|
}
|
|
330
406
|
|
|
331
|
-
|
|
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) {
|
|
332
415
|
if (this.busy) throw new CliError("session_busy", "The current submission is still being reconciled");
|
|
333
416
|
if (!text.trim()) return;
|
|
334
417
|
if (this.offline || !this.account) {
|
|
@@ -352,67 +435,156 @@ export class Session extends EventEmitter {
|
|
|
352
435
|
const draftRef = structuredClone(this.registry?.draftRef ?? null);
|
|
353
436
|
this.busy = true; this.status = "Submitting"; this.change();
|
|
354
437
|
try {
|
|
355
|
-
if (this.registry?.state().pendingRun) throw new CliError("submission_pending", "Use /resume to resolve the interrupted submission; your new draft is kept");
|
|
356
|
-
|
|
357
|
-
if (
|
|
358
|
-
const
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
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");
|
|
439
|
+
if (this.project?.role === 'VIEWER') throw new CliError('role_forbidden', 'Editor access is required to ask Vecteur');
|
|
440
|
+
if (await this.offerAttachments(text) === false) { this.status = 'Draft kept — named files not offered'; return; }
|
|
441
|
+
const consentAccount=this.account.id;
|
|
442
|
+
const destination = { origin: this.origin, id: this.project?.id, name: this.project?.name ?? this.projectName ?? basename(this.cwd) };
|
|
443
|
+
let consent = false;
|
|
444
|
+
if (this.attachments.some(f => !f.generated)) {
|
|
445
|
+
const grant = this.project && currentGrant(this.localPin(), this.env);
|
|
446
|
+
if (!grant) {
|
|
447
|
+
const epoch=await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env);
|
|
448
|
+
if(await this.confirmFiles(destination))consent={epoch};
|
|
449
|
+
if (!consent) { this.status = 'Draft kept — files not uploaded'; return; }
|
|
450
|
+
}
|
|
362
451
|
}
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
if (!offer.extracts.length) throw new CliError("extraction_unavailable", "This file has no selectable extracts");
|
|
368
|
-
selections.push({ source_handle: { cas_ref: item.source.cas_ref, acquisition_ref: item.source.acquisition_ref },
|
|
369
|
-
offer_id: offer.id, selected_extract_ids: offer.extracts.map(extract => extract.id).sort(), method: "exact-extract" });
|
|
452
|
+
const project = await this.ensureProject(consent || undefined);
|
|
453
|
+
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))) {
|
|
455
|
+
if (!await this.confirmFiles({ origin: this.origin, id: project.id, name: project.name })) return;
|
|
370
456
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
457
|
+
if (this.execAllowed === undefined) await this.execConsent("on");
|
|
458
|
+
const executor = await withAdmissionLock(async () => {
|
|
459
|
+
const newest = await this.client.projectNewestRun(project.id);
|
|
460
|
+
const checkDestination=()=>{
|
|
461
|
+
if(this.project?.id!==project.id || this.origin!==destination.origin || this.account?.id!==consentAccount) throw new CliError('grant_changed','Upload destination changed; draft kept');
|
|
462
|
+
};
|
|
463
|
+
checkDestination();
|
|
464
|
+
if (newest && !newest.terminal) {
|
|
465
|
+
this.run = { ...newest, open: true };
|
|
466
|
+
throw new CliError("run_busy", "Another terminal has an open Run. Following it; your draft is kept.");
|
|
467
|
+
}
|
|
468
|
+
const selections = [];
|
|
469
|
+
let grant;
|
|
470
|
+
if (this.attachments.some(f => !f.generated)) {
|
|
471
|
+
grant = currentGrant(this.localPin(), this.env);
|
|
472
|
+
if (!grant) { if (!consent) throw new CliError('grant_changed', 'Permission changed; confirm files again'); grant = createGrant(this.localPin(), this.env, consent.epoch); }
|
|
473
|
+
}
|
|
474
|
+
for (const item of this.attachments) {
|
|
475
|
+
checkDestination();
|
|
476
|
+
if (!item.generated) pinCheck(grant, this.localPin(), this.env);
|
|
477
|
+
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);
|
|
480
|
+
this.message(`Upload ${file.rel} (${file.size} B) to ${project.name} on ${this.origin}`);
|
|
481
|
+
item.source = await this.client.inputAdd(project.id, file.bytes, file.media);
|
|
482
|
+
checkDestination();
|
|
483
|
+
if (!item.generated) recordUpload(grant, file, item.source, this.env);
|
|
484
|
+
const offer = item.source.offer ?? await this.client.inputOffer(project.id, item.source);
|
|
485
|
+
if (!offer.extracts.length) throw new CliError("extraction_unavailable", "This file has no selectable extracts");
|
|
486
|
+
selections.push({ source_handle: { cas_ref: item.source.cas_ref, acquisition_ref: item.source.acquisition_ref },
|
|
487
|
+
offer_id: offer.id, selected_extract_ids: offer.extracts.map(extract => extract.id).sort(), method: "exact-extract" });
|
|
488
|
+
}
|
|
489
|
+
selections.sort((a, b) => a.source_handle.cas_ref.localeCompare(b.source_handle.cas_ref)
|
|
490
|
+
|| a.source_handle.acquisition_ref.localeCompare(b.source_handle.acquisition_ref));
|
|
491
|
+
const body = { ask: text, attachments: selections.map(item => item.source_handle),
|
|
492
|
+
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);
|
|
515
|
+
}, this.env);
|
|
516
|
+
this.startExecutor(executor);
|
|
517
|
+
void this.follow().catch(error => this.report(error));
|
|
518
|
+
} catch(error) {
|
|
519
|
+
if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest();
|
|
520
|
+
else if(error.code==='run_busy' && this.run?.open) void this.follow().catch(error=>this.report(error));
|
|
521
|
+
throw error;
|
|
378
522
|
} finally { this.busy = false; this.change(); }
|
|
379
523
|
}
|
|
380
524
|
|
|
381
525
|
async admitPending(pending) {
|
|
526
|
+
let executor;
|
|
527
|
+
try { executor = await withAdmissionLock(() => this.admitPendingLocked(pending), this.env); }
|
|
528
|
+
catch(error) { if(['state_busy','state_fork'].includes(error.code)) await this.loadNewest(); throw error; }
|
|
529
|
+
this.startExecutor(executor);
|
|
530
|
+
void this.follow().catch(error=>this.report(error));
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
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');
|
|
382
536
|
if (this.project?.id !== pending.projectId) {
|
|
383
537
|
const project = await this.client.projectGet(pending.projectId);
|
|
384
538
|
this.followController?.abort(); this.generation++; this.run = null; this.project = project; this.change();
|
|
385
539
|
}
|
|
540
|
+
if (ephemeral) {
|
|
541
|
+
if (!this.executor) throw new CliError("admission_unresolved", "Executor consent ended; reconcile through Project history");
|
|
542
|
+
this.executor.check();
|
|
543
|
+
}
|
|
386
544
|
let ack;
|
|
387
545
|
try { ack = await this.client.runAdmit(pending.projectId, pending.body, pending.key); }
|
|
388
546
|
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);
|
|
550
|
+
}
|
|
389
551
|
if (["state_busy", "state_fork"].includes(error.code)) {
|
|
390
|
-
this.registry.rejectRunAdmission(pending.key);
|
|
391
|
-
await this.loadNewest();
|
|
392
552
|
throw new CliError(error.code, "Submission refused; draft kept. Review the latest Run and explicitly send again.");
|
|
393
553
|
}
|
|
394
554
|
// The owner marked this key as never admittable (nothing dispatched): release only this
|
|
395
555
|
// reservation and keep the draft. Any other failure stays pending for /resume.
|
|
396
556
|
if (error.admission === "refused") {
|
|
397
|
-
|
|
557
|
+
if (error.code === "produce_unavailable") throw new CliError(error.code, `${error.message}. Draft kept.`);
|
|
398
558
|
throw new CliError(error.code, "Submission refused before it ran; draft kept. Fix it and send again.");
|
|
399
559
|
}
|
|
400
560
|
throw error;
|
|
401
561
|
}
|
|
402
|
-
this.registry.finishRunAdmission(pending.key);
|
|
562
|
+
if (!ephemeral) this.registry.finishRunAdmission(pending.key);
|
|
563
|
+
this.execPending = null;
|
|
403
564
|
if (this.draft === pending.body.ask) { clearTimeout(this.draftTimer); this.draft = ""; }
|
|
404
565
|
this.attachments = [];
|
|
405
566
|
this.message(pending.body.ask, "user");
|
|
406
|
-
this.run = { ...ack, events: [], terminal: "", open: true };
|
|
567
|
+
this.run = { ...ack, ask: pending.body.ask, controls: [], events: [], terminal: "", open: true };
|
|
407
568
|
this.status = "Running"; this.change();
|
|
408
|
-
|
|
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
|
+
}
|
|
409
579
|
}
|
|
410
580
|
|
|
411
581
|
async resume() {
|
|
412
582
|
if (this.offline) { this.offline = false; return this.initialize(); }
|
|
413
583
|
if (this.busy) throw new CliError("session_busy", "This submission is already being reconciled");
|
|
414
584
|
if (!this.account || !this.registry) return this.initialize();
|
|
585
|
+
await withAdmissionLock(() => reconcileAdmissions(this.client, this.origin, this.env), this.env);
|
|
415
586
|
const state = this.registry.state();
|
|
587
|
+
if (this.execPending) return this.admitPending(this.execPending);
|
|
416
588
|
if (state.pendingRun) {
|
|
417
589
|
this.busy = true; this.change();
|
|
418
590
|
try { return await this.admitPending(state.pendingRun); }
|
|
@@ -426,59 +598,389 @@ export class Session extends EventEmitter {
|
|
|
426
598
|
async follow() {
|
|
427
599
|
this.followController?.abort();
|
|
428
600
|
const controller = new AbortController(); this.followController = controller;
|
|
429
|
-
const run = this.run; const generation = ++this.generation;
|
|
601
|
+
const run = this.run, executor = this.executor; const generation = ++this.generation;
|
|
430
602
|
const projectId = this.project.id;
|
|
431
|
-
let attempts = 0;
|
|
432
|
-
|
|
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;
|
|
433
609
|
try {
|
|
434
|
-
const
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
}, controller.signal, [...run.events]);
|
|
440
|
-
if (generation !== this.generation) return;
|
|
441
|
-
this.run = { ...direct, accepted_at: direct.run_id === run.run_id ? run.accepted_at : undefined, open: !direct.terminal };
|
|
442
|
-
this.status = direct.terminal; this.announceRun();
|
|
443
|
-
try {
|
|
444
|
-
const cost = await this.client.customerCost(projectId);
|
|
445
|
-
if (generation === this.generation) this.message(humanCost(cost), "cost", { value: cost });
|
|
446
|
-
} catch (error) { if (generation === this.generation) this.message(`Usage unavailable: ${error.code}`); }
|
|
447
|
-
this.change(); return;
|
|
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(); }
|
|
448
615
|
} catch (error) {
|
|
449
|
-
if (
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
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;
|
|
454
624
|
}
|
|
625
|
+
if (current() && !permanent) controlTimer = setTimeout(refreshControls, interval);
|
|
626
|
+
};
|
|
627
|
+
void refreshControls();
|
|
628
|
+
controller.signal.addEventListener("abort", () => clearTimeout(controlTimer), { once: true });
|
|
629
|
+
try {
|
|
630
|
+
while (!this.closed && generation === this.generation && run?.open) {
|
|
631
|
+
try {
|
|
632
|
+
const direct = await this.client.runEvents(run.run_id, event => {
|
|
633
|
+
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();
|
|
637
|
+
}, controller.signal, [...run.events]);
|
|
638
|
+
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;
|
|
642
|
+
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
|
+
await this.announceFooter(projectId);
|
|
646
|
+
this.change(); await this.offerSaves().catch(error=>this.report(error)); return;
|
|
647
|
+
} catch (error) {
|
|
648
|
+
if (controller.signal.aborted || this.closed || generation !== this.generation) return;
|
|
649
|
+
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
|
+
if (!TRANSIENT.has(error.code) || ++attempts > 5) throw error;
|
|
659
|
+
this.status = "Connection lost — reconnecting to the same Run"; this.change();
|
|
660
|
+
await delay(Math.min(500 * 2 ** attempts, 8_000), controller.signal);
|
|
661
|
+
}
|
|
662
|
+
}
|
|
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();
|
|
455
670
|
}
|
|
456
671
|
}
|
|
457
672
|
|
|
458
673
|
attach(path) { return this.transition(() => this.selectAttachment(path)); }
|
|
459
674
|
|
|
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
|
+
localPin() {
|
|
693
|
+
return { origin: this.origin, accountId: this.account?.id, projectId: this.project?.id, role: this.project?.role,
|
|
694
|
+
root: this.registry.folder, provenance: this.provenance ?? 'binding', binding: () => this.registry.binding(),
|
|
695
|
+
credential: this.activeCredential ?? { kind: this.env.VECTEUR_TOKEN ? 'environment' : 'stored', token: this.env.VECTEUR_TOKEN ?? readCredentials(this.env)?.logins?.[this.origin]?.token } };
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
fileConsentText(destination) {
|
|
699
|
+
const project = destination.id ? destination.name : `a new Project named ${destination.name}`;
|
|
700
|
+
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.`;
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
async confirmFiles(destination) {
|
|
704
|
+
const files = this.attachments.filter(f=>!f.generated);
|
|
705
|
+
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
|
+
{ label: 'Yes, allow select and save-new', value: true }, { label: 'No, keep draft and selections', value: false },
|
|
707
|
+
], { liveTitle: `Send ${files.length} selected file${files.length===1?'':'s'}?` });
|
|
708
|
+
}
|
|
709
|
+
|
|
460
710
|
async selectAttachment(path) {
|
|
461
|
-
if (this.
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
711
|
+
if (this.project?.role === 'VIEWER') throw new CliError('role_forbidden', 'Editor access is required to select upload files');
|
|
712
|
+
if (this.registry?.state().pendingRun) throw new CliError('submission_pending', 'Resolve the pending submission before changing its files');
|
|
713
|
+
if (!this.registry) this.unsignedDraft();
|
|
714
|
+
const rel = isAbsolute(path) ? relative(this.registry.folder.path, path) : path;
|
|
715
|
+
const item = selectionMetadata(this.registry.folder, rel, this.env);
|
|
716
|
+
if (this.attachments.some(f => f.rel === item.rel)) return;
|
|
717
|
+
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');
|
|
718
|
+
const grant = this.project && currentGrant(this.localPin(), this.env);
|
|
719
|
+
this.attachments.push({ ...item, ...(grant ? { generation: grant.generation } : {}) });
|
|
720
|
+
this.message(`Upload ${item.rel} (${item.size} B) to ${this.project?.name ?? 'a new Project'} on ${this.origin} · on send`);
|
|
721
|
+
this.change();
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
async completeFiles(prefix) {
|
|
725
|
+
if (!this.registry) this.unsignedDraft();
|
|
726
|
+
return discover(this.registry.folder, this.env, prefix).map(f => f.rel);
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
async offerAttachments(text) {
|
|
730
|
+
const mentions = [...text.matchAll(/(?:^|\s)@([^\s]+)/g)].map(m => m[1]);
|
|
731
|
+
for (const rel of mentions) await this.selectAttachment(rel);
|
|
732
|
+
const words = [...new Set(text.split(/\s+/).filter(w => w && !w.startsWith('@')))];
|
|
733
|
+
if (!words.length) return;
|
|
734
|
+
let files = [];
|
|
735
|
+
try { files = discover(this.registry.folder, this.env); }
|
|
736
|
+
catch (e) {
|
|
737
|
+
this.message(`File offers were unavailable (${e.code ?? 'discovery_failed'}); continuing without filename offers.`);
|
|
738
|
+
}
|
|
739
|
+
const notices = new Set(), blocked = new Set();
|
|
740
|
+
const notice = (name, code) => {
|
|
741
|
+
if (!notices.has(name)) this.message(`${name}: not offered (${code})`);
|
|
742
|
+
notices.add(name);
|
|
743
|
+
};
|
|
744
|
+
const selected = this.attachments.map(f => f.rel);
|
|
745
|
+
for (const name of words) {
|
|
746
|
+
if (/^[a-z][a-z0-9+.-]*:\/\//i.test(name) || selected.includes(name.replace(/^\.\//,''))) continue;
|
|
747
|
+
try {
|
|
748
|
+
// Discovery intentionally hides excluded and non-regular entries. Check an
|
|
749
|
+
// explicitly named path through the same metadata-only selection boundary.
|
|
750
|
+
const file = selectionMetadata(this.registry.folder, name, this.env, { ifPresent: true });
|
|
751
|
+
if (!files.some(f=>f.rel===file.rel)) files.push(file);
|
|
752
|
+
} catch (e) {
|
|
753
|
+
if (e.code === 'ENOENT') continue;
|
|
754
|
+
if (!['excluded','path_excluded','outside_folder','symlink_refused','not_regular_file','hardlink_refused','attachment_invalid','ignore_policy_unknown'].includes(e.code)) throw e;
|
|
755
|
+
notice(name, e.code === 'excluded' ? 'path_excluded' : e.code); blocked.add(name);
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
let offers = 0;
|
|
759
|
+
for (const name of words.filter(w=>!blocked.has(w))) {
|
|
760
|
+
const matches = nameOffers(name, files, this.attachments.map(f=>f.rel))[0];
|
|
761
|
+
if (!matches) continue;
|
|
762
|
+
const grant = this.project && currentGrant(this.localPin(), this.env);
|
|
763
|
+
const safe = [];
|
|
764
|
+
for (const file of matches) {
|
|
765
|
+
try {
|
|
766
|
+
// Without a grant, offer metadata only. The common first-use card in
|
|
767
|
+
// submit must be accepted before the selected content is read/scanned.
|
|
768
|
+
if (grant) await withLocalLock(() => {
|
|
769
|
+
pinCheck(grant, this.localPin(), this.env);
|
|
770
|
+
// This preflight only decides the offer; upload rereads and rechecks
|
|
771
|
+
// the selection under the same grant before any network egress.
|
|
772
|
+
readConfined(grant, file.rel, this.env, { selected: file });
|
|
773
|
+
pinCheck(grant, this.localPin(), this.env);
|
|
774
|
+
}, this.env);
|
|
775
|
+
safe.push(file);
|
|
776
|
+
} catch (e) {
|
|
777
|
+
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;
|
|
778
|
+
notice(matches.length === 1 ? name : file.rel, e.code === 'excluded' ? 'path_excluded' : e.code);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
if (!safe.length || offers >= 3) continue;
|
|
782
|
+
offers++;
|
|
783
|
+
if (safe.length === 1) {
|
|
784
|
+
const file = safe[0];
|
|
785
|
+
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);
|
|
786
|
+
} else {
|
|
787
|
+
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}]);
|
|
788
|
+
if (rel) await this.selectAttachment(rel);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
if (notices.size) return this.choose('Send without these files?', [
|
|
792
|
+
{label:'Yes, send without these files',value:true}, {label:'No, keep draft',value:false},
|
|
478
793
|
]);
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
async revokeFiles() {
|
|
797
|
+
this.executor?.stop(); this.execAllowed = false;
|
|
798
|
+
this.requireLogin();
|
|
799
|
+
return withLocalLock(() => {
|
|
800
|
+
endGrants({origin:this.origin,accountId:this.account.id,root:this.registry.folder.path},this.env);
|
|
801
|
+
this.saveProposal = null;
|
|
802
|
+
this.message('Local file permission revoked; pending selections need fresh consent.');
|
|
803
|
+
}, this.env);
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
async scanLocalTargets() {
|
|
807
|
+
try {
|
|
808
|
+
qualify();
|
|
809
|
+
return await withLocalLock(()=>{
|
|
810
|
+
const pin = this.localPin(), grant = currentGrant(pin,this.env);
|
|
811
|
+
if (!grant) return proposals(pin,this.env);
|
|
812
|
+
pinCheck(grant,pin,this.env);
|
|
813
|
+
const reports = observeTargets(grant,this.env,pin);
|
|
814
|
+
for (const row of reports) this.message(`${terminalText(row.path)}: ${row.code}, local observation unavailable`);
|
|
815
|
+
return proposals(grant,this.env);
|
|
816
|
+
},this.env);
|
|
817
|
+
} catch (error) {
|
|
818
|
+
this.message(`${error.code}: local observation unavailable; cloud files remain available.`);
|
|
819
|
+
return [];
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
async confirmLocalRead(project, epoch) {
|
|
824
|
+
const prepared = epoch ?? await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env);
|
|
825
|
+
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();
|
|
826
|
+
if (!['','y','yes'].includes(answer)) return null;
|
|
827
|
+
return withLocalLock(()=>{
|
|
828
|
+
if (this.project!==project) throw new CliError('grant_changed','Diff destination changed');
|
|
829
|
+
const grant=createGrant(this.localPin(),this.env,prepared);
|
|
830
|
+
return pinCheck(grant,this.localPin(),this.env);
|
|
831
|
+
},this.env);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
async listFiles() {
|
|
835
|
+
const rows = artifactRows(runView(this.run).artifacts);
|
|
836
|
+
const saved = this.account && this.project ? await this.scanLocalTargets() : [];
|
|
837
|
+
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`),
|
|
840
|
+
...saved.map((p,i)=>`${rows.length+i+1}. Proposal ${terminalText(p.path)} → ${terminalText(p.originalPath)} · /files diff ${rows.length+i+1}`),
|
|
841
|
+
].join('\n') || 'No selected files or artifacts.');
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
async fileDiff(number) {
|
|
845
|
+
this.requireLogin();
|
|
846
|
+
if (!this.project) throw new CliError('project_unavailable','Choose a Project first');
|
|
847
|
+
const project=this.project, rows=artifactRows(runView(this.run).artifacts);
|
|
848
|
+
const saved=await this.scanLocalTargets();
|
|
849
|
+
const row=rows.find(r=>r.number===number), proposal=saved[number-rows.length-1];
|
|
850
|
+
const a=row?.artifact ?? (proposal && {path:proposal.originalPath,cas_ref:proposal.cas_ref,kind:'code'});
|
|
851
|
+
if (!a?.path) throw new CliError('artifact_unavailable','Choose a file number from /files');
|
|
852
|
+
// Historical proposals retain their artifact kind in the scoped journal.
|
|
853
|
+
const kind=row?.artifact.kind ?? proposal.kind;
|
|
854
|
+
let grant=await withLocalLock(()=>{
|
|
855
|
+
const live=currentGrant(this.localPin(),this.env);
|
|
856
|
+
return live ? pinCheck(live,this.localPin(),this.env) : null;
|
|
857
|
+
},this.env);
|
|
858
|
+
grant ??= await this.confirmLocalRead(project);
|
|
859
|
+
if (!grant) return;
|
|
860
|
+
const bytes=await downloadLocalArtifact(sink=>this.client.artifactGet(a.cas_ref,project.id,sink),{...a,kind});
|
|
861
|
+
const snapshot=await withLocalLock(()=>{
|
|
862
|
+
if(this.project!==project)throw new CliError('grant_changed','Diff destination changed');
|
|
863
|
+
return inspectTarget(grant,a.path,a.cas_ref.slice(7),this.env,this.localPin());
|
|
864
|
+
},this.env);
|
|
865
|
+
this.message(proposalReview(a.path,snapshot,bytes));
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
async offerSaves(number) {
|
|
869
|
+
if (!this.account || !this.project || !this.run?.terminal || this.project.role === 'VIEWER') return;
|
|
870
|
+
try { qualify(); } catch (e) { if (number) throw e; return; }
|
|
871
|
+
const run = this.run, project = this.project;
|
|
872
|
+
if ((await this.client.projectNewestRun(project.id))?.run_id !== run.run_id) return;
|
|
873
|
+
if (this.project !== project || this.run !== run) throw new CliError('grant_changed','Save destination changed');
|
|
874
|
+
const grant = currentGrant(this.localPin(), this.env);
|
|
875
|
+
const provisional = grant ?? { ...this.localPin(), generation: null };
|
|
876
|
+
const candidates = [], selected = new Set();
|
|
877
|
+
const normalize = (row, snapshot) => {
|
|
878
|
+
row.snapshot=snapshot;
|
|
879
|
+
row.creates=snapshot.creates;
|
|
880
|
+
row.proposalPath=snapshot.exists?proposalName(row.artifact.path,run.run_id,row.artifact.revision):null;
|
|
881
|
+
row.eligible=snapshot.classification!=='already identical'
|
|
882
|
+
&& (snapshot.exists || !!number || !tombstoned(provisional,row.artifact.path,this.env));
|
|
883
|
+
if(!row.eligible) {
|
|
884
|
+
selected.delete(row);
|
|
885
|
+
if(snapshot.classification==='already identical')this.message(`${terminalText(row.artifact.path)}: already identical`);
|
|
886
|
+
}
|
|
887
|
+
return row.eligible;
|
|
888
|
+
};
|
|
889
|
+
for (const row of artifactRows(runView(run).artifacts)) {
|
|
890
|
+
const a = row.artifact;
|
|
891
|
+
if (!a.path || number && row.number !== number) continue;
|
|
892
|
+
try {
|
|
893
|
+
const eligible=await withLocalLock(()=>normalize(row,grant
|
|
894
|
+
? inspectTarget(grant,a.path,a.cas_ref.slice(7),this.env,this.localPin())
|
|
895
|
+
: observeTargetMetadata(provisional,a.path,this.env)),this.env);
|
|
896
|
+
if(!eligible)continue;
|
|
897
|
+
if (row.snapshot.exists) {
|
|
898
|
+
row.bytes=await downloadLocalArtifact(sink=>this.client.artifactGet(a.cas_ref,project.id,sink),a);
|
|
899
|
+
if(grant) await withLocalLock(()=>pinCheck(grant,this.localPin(),this.env),this.env);
|
|
900
|
+
}
|
|
901
|
+
candidates.push(row);
|
|
902
|
+
} catch (e) { this.message(`${a.path}: ${e.code}, not written · /download ${row.number}`); }
|
|
903
|
+
}
|
|
904
|
+
const current = candidates; // runArtifacts already owns current-revision selection.
|
|
905
|
+
if (!current.length) return;
|
|
906
|
+
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);
|
|
907
|
+
const proposal = { runId: run.run_id, projectId:project.id, generation: grant?.generation ?? null, rows:current.map(row => ({ ...row, artifact:structuredClone(row.artifact) })) };
|
|
908
|
+
this.saveProposal = proposal;
|
|
909
|
+
const epoch = !grant ? await withLocalLock(()=>prepareConsent(this.localPin(),this.env),this.env) : null;
|
|
910
|
+
const rowLabel=row=>{
|
|
911
|
+
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}`:''}`)
|
|
915
|
+
+(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
|
+
};
|
|
917
|
+
let live=grant;
|
|
918
|
+
while (true) {
|
|
919
|
+
if(live) await withLocalLock(()=>pinCheck(live,this.localPin(),this.env),this.env);
|
|
920
|
+
const paths = [...selected].map(row => row.artifact.path);
|
|
921
|
+
if (!paths.length) break;
|
|
922
|
+
const beside=[...selected].some(r=>r.proposalPath);
|
|
923
|
+
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)}?`;
|
|
924
|
+
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();
|
|
925
|
+
if (answer === 'n' || answer === 'no') { this.saveProposal=null; return; }
|
|
926
|
+
if (answer === 'd') {
|
|
927
|
+
if(!live) {
|
|
928
|
+
live=await this.confirmLocalRead(project,epoch);
|
|
929
|
+
if(!live){this.saveProposal=null;return;}
|
|
930
|
+
proposal.generation=live.generation;
|
|
931
|
+
}
|
|
932
|
+
await withLocalLock(()=>{
|
|
933
|
+
for(const row of selected) {
|
|
934
|
+
normalize(row,inspectTarget(live,row.artifact.path,row.artifact.cas_ref.slice(7),this.env,this.localPin()));
|
|
935
|
+
if(row.bytes)this.message(proposalReview(row.artifact.path,row.snapshot,row.bytes));
|
|
936
|
+
}
|
|
937
|
+
},this.env);
|
|
938
|
+
if(current.length===1 && beside)continue;
|
|
939
|
+
const eligible=current.filter(r=>r.eligible && !r.written);
|
|
940
|
+
if(!eligible.length)break;
|
|
941
|
+
const choices = await this.choose('Every candidate (choose numbers separated by commas)', eligible.map(row=>({label:rowLabel(row),value:row})),{multiple:true});
|
|
942
|
+
selected.clear(); for (const row of choices) if(eligible.includes(row))selected.add(row); continue;
|
|
943
|
+
}
|
|
944
|
+
if (!['','y','yes'].includes(answer)) { this.message('Enter yes, d or n.'); continue; }
|
|
945
|
+
await withLocalLock(()=>{
|
|
946
|
+
if(this.project!==project || this.run!==run)throw new CliError('grant_changed','Save proposal withdrawn');
|
|
947
|
+
live=currentGrant(this.localPin(),this.env);
|
|
948
|
+
if(proposal.generation===null){
|
|
949
|
+
if(live)throw new CliError('grant_changed','Permission changed during confirmation; review again');
|
|
950
|
+
live=createGrant(this.localPin(),this.env,epoch);proposal.generation=live.generation;
|
|
951
|
+
}
|
|
952
|
+
},this.env);
|
|
953
|
+
if (!live || live.generation !== proposal.generation || this.project.id !== proposal.projectId) throw new CliError('grant_changed','Save proposal withdrawn; confirm again');
|
|
954
|
+
if([...selected].some(row=>row.snapshot.exists && !row.snapshot.classification)) {
|
|
955
|
+
await withLocalLock(()=>{
|
|
956
|
+
for(const row of selected)normalize(row,inspectTarget(live,row.artifact.path,row.artifact.cas_ref.slice(7),this.env,this.localPin()));
|
|
957
|
+
},this.env);
|
|
958
|
+
continue;
|
|
959
|
+
}
|
|
960
|
+
for (const row of selected) {
|
|
961
|
+
const artifact = proposal.rows.find(r => r.number===row.number).artifact;
|
|
962
|
+
try {
|
|
963
|
+
const writer=row.proposalPath?writeProposalConfined:writeNewConfined;
|
|
964
|
+
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);
|
|
965
|
+
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}});
|
|
966
|
+
this.message(terminalText(`Saved ${relative(this.cwd,saved.path)} (${saved.bytes} B)`));
|
|
967
|
+
if(row.proposalPath)this.message(terminalText(adoptionHint(relative(this.cwd,saved.path),artifact.path)));
|
|
968
|
+
row.written=true;selected.delete(row);
|
|
969
|
+
} catch(e) {
|
|
970
|
+
if(e.code!=='target_changed')throw e;
|
|
971
|
+
this.message(e.message);
|
|
972
|
+
await withLocalLock(()=>normalize(row,inspectTarget(live,artifact.path,artifact.cas_ref.slice(7),this.env,this.localPin())),this.env);
|
|
973
|
+
if(!row.eligible)continue;
|
|
974
|
+
row.bytes ??= await downloadLocalArtifact(sink=>this.client.artifactGet(artifact.cas_ref,project.id,sink),artifact);
|
|
975
|
+
await withLocalLock(()=>{
|
|
976
|
+
normalize(row,inspectTarget(live,artifact.path,artifact.cas_ref.slice(7),this.env,this.localPin()));
|
|
977
|
+
if(row.eligible)this.message(proposalReview(artifact.path,row.snapshot,row.bytes));
|
|
978
|
+
},this.env);
|
|
979
|
+
break;
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
this.saveProposal = null;
|
|
482
984
|
}
|
|
483
985
|
|
|
484
986
|
link(options = {}) { return this.transition(() => this.selectProject(options)); }
|
|
@@ -493,18 +995,21 @@ export class Session extends EventEmitter {
|
|
|
493
995
|
const id = await this.choose("Choose an existing Project", this.projects.map(row => ({ label: `${row.name} (${row.role})`, value: row.id })));
|
|
494
996
|
if (this.closed) return;
|
|
495
997
|
const project = this.projects.find(row => row.id === id);
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
998
|
+
await withAdmissionLock(async () => {
|
|
999
|
+
if (this.project?.id !== id) endGrants({origin:this.origin,accountId:this.account.id,root:this.registry.folder.path},this.env);
|
|
1000
|
+
if (persist) {
|
|
1001
|
+
try { this.registry.bind(id); }
|
|
1002
|
+
catch (error) {
|
|
1003
|
+
if (!["home_binding_confirmation", "root_binding_confirmation"].includes(error.code)) throw error;
|
|
1004
|
+
const answer = await this.choose(error.message, [], { typed: true });
|
|
1005
|
+
if (answer !== this.cwd) throw new CliError("binding_cancelled", "Broad directory binding was not confirmed");
|
|
1006
|
+
this.registry.bind(id, { confirmBroad: true });
|
|
1007
|
+
}
|
|
503
1008
|
}
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
1009
|
+
this.followController?.abort(); this.generation++;
|
|
1010
|
+
this.binding = this.registry.binding(); this.provenance = persist ? "binding" : "explicit";
|
|
1011
|
+
this.attachments = []; this.project = project; this.run = null; this.status = "Ready"; this.change();
|
|
1012
|
+
}, this.env);
|
|
508
1013
|
await this.loadNewest();
|
|
509
1014
|
}
|
|
510
1015
|
|
|
@@ -543,7 +1048,7 @@ export class Session extends EventEmitter {
|
|
|
543
1048
|
this.run = { ...selected.response, accepted_at: selected.accepted_at, open: !selected.response.terminal };
|
|
544
1049
|
this.message(selected.request.ask, "user");
|
|
545
1050
|
if (this.run.open) void this.follow().catch(error => this.report(error));
|
|
546
|
-
else this.message(runView(this.run).transcript, "answer", { runId: this.run.run_id, sections: runSections(this.run) });
|
|
1051
|
+
else { this.message(runView(this.run).transcript, "answer", { runId: this.run.run_id, sections: runSections(this.run) }); await this.announceFooter(this.project.id); }
|
|
547
1052
|
this.status = "Viewing history — next send continues the current Project head"; this.change();
|
|
548
1053
|
return;
|
|
549
1054
|
}
|
|
@@ -556,7 +1061,9 @@ export class Session extends EventEmitter {
|
|
|
556
1061
|
const run = this.run, client = this.client;
|
|
557
1062
|
const value = await client.runControl(run.run_id, control);
|
|
558
1063
|
if (this.run !== run || this.client !== client) return;
|
|
559
|
-
|
|
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();
|
|
560
1067
|
}
|
|
561
1068
|
|
|
562
1069
|
async answer() {
|
|
@@ -624,7 +1131,11 @@ export class Session extends EventEmitter {
|
|
|
624
1131
|
const destination = !matched ? "Catalogue unavailable or outdated — /login or update this CLI"
|
|
625
1132
|
: route ? route.candidates.map(row => `${row.provider_id}/${row.model_id} (${row.jurisdiction})`).join(" → ")
|
|
626
1133
|
: profile ? `${profile.provider} (${profile.data_residency})` : "Unknown";
|
|
627
|
-
|
|
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}`;
|
|
628
1139
|
}
|
|
629
1140
|
|
|
630
1141
|
statusDetails() {
|
|
@@ -632,6 +1143,7 @@ export class Session extends EventEmitter {
|
|
|
632
1143
|
}
|
|
633
1144
|
|
|
634
1145
|
async logout() {
|
|
1146
|
+
this.executor?.stop(); this.execAllowed = false;
|
|
635
1147
|
return this.transition(async () => {
|
|
636
1148
|
this.requireLogin();
|
|
637
1149
|
const yes = await this.choose("Sign out here? Saved drafts stay with this account; a cloud Run keeps running.", [
|
|
@@ -642,7 +1154,10 @@ export class Session extends EventEmitter {
|
|
|
642
1154
|
await client.credentialSelfRevoke();
|
|
643
1155
|
if (client !== this.client || this.closed) return;
|
|
644
1156
|
clearTimeout(this.draftTimer); this.registry?.saveDraft(this.draft);
|
|
645
|
-
|
|
1157
|
+
await withAdmissionLock(() => {
|
|
1158
|
+
if (!this.env.VECTEUR_TOKEN) clearCredentials(this.env, this.origin);
|
|
1159
|
+
else endGrants({origin:this.origin,accountId:this.account.id},this.env);
|
|
1160
|
+
},this.env);
|
|
646
1161
|
this.signedOut = true;
|
|
647
1162
|
this.env = { ...this.env }; delete this.env.VECTEUR_TOKEN;
|
|
648
1163
|
this.followController?.abort(); this.generation++; this.account = null; this.project = null;
|
|
@@ -659,6 +1174,83 @@ export class Session extends EventEmitter {
|
|
|
659
1174
|
this.message(`Downloaded ${result.bytes} verified bytes to ${result.path}`);
|
|
660
1175
|
}
|
|
661
1176
|
|
|
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
|
+
|
|
662
1254
|
async exportRun(output) {
|
|
663
1255
|
this.requireLogin();
|
|
664
1256
|
if (!this.run || this.run.open) throw new CliError("run_unavailable", "Export needs a completed Run");
|
|
@@ -682,6 +1274,7 @@ export class Session extends EventEmitter {
|
|
|
682
1274
|
if (this.registry) this.registry.saveDraft(this.draft);
|
|
683
1275
|
}
|
|
684
1276
|
catch (error) { this.message(`Draft could not be saved: ${error.code ?? "store_error"}`, "error"); }
|
|
1277
|
+
this.executor?.stop();
|
|
685
1278
|
this.closed = true; this.generation++; this.cancelLogin(); this.lifecycle.abort(); this.followController?.abort(); clearTimeout(this.draftTimer);
|
|
686
1279
|
this.rejectPrompt?.(new CliError("session_closed", "Session closed")); this.prompt = null;
|
|
687
1280
|
this.emit("close");
|