@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/executor.js
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
/** The foreground process owns consent, a per-Run secret and one bounded shell process group. */
|
|
2
|
+
import { randomBytes, createHash } from 'node:crypto';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { localProcessEnv, scanContent, withLocalLock, pinCheck, walk, closeChain, consumeExec } from './localfiles.js';
|
|
5
|
+
import { CliError } from './errors.js';
|
|
6
|
+
import { validateLocalExecStatus } from './contract.js';
|
|
7
|
+
|
|
8
|
+
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
9
|
+
const hash = value => createHash('sha256').update(value).digest('hex');
|
|
10
|
+
const fail = () => { throw new CliError('protocol_invalid', 'Invalid local executor protocol'); };
|
|
11
|
+
|
|
12
|
+
export function ring(cap) {
|
|
13
|
+
let bytes = Buffer.alloc(0), count = 0;
|
|
14
|
+
return {
|
|
15
|
+
push(chunk) { count += chunk.length; bytes = Buffer.concat([bytes, chunk.subarray(-cap)]).subarray(-cap); },
|
|
16
|
+
get count() { return count; },
|
|
17
|
+
finish() {
|
|
18
|
+
let start = 0;
|
|
19
|
+
if (count > bytes.length) while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++;
|
|
20
|
+
const tail = bytes.subarray(start);
|
|
21
|
+
if (tail.length) scanContent(tail, 'stdout.txt');
|
|
22
|
+
return { text: new TextDecoder('utf-8', { fatal: true }).decode(tail), count, truncated: count > tail.length };
|
|
23
|
+
},
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export class Executor {
|
|
28
|
+
constructor({ client, grant, pin, env = process.env, approve = null, session = false }) {
|
|
29
|
+
this.client = client; this.grant = grant; this.pin = pin; this.env = env;
|
|
30
|
+
this.approve = approve; this.session = session; this.closed = false; this.unknown = false; this.paused = false; this.revoked = false;
|
|
31
|
+
this.secret = randomBytes(32).toString('hex'); this.descriptor = { secret_sha256: hash(Buffer.from(this.secret, 'hex')) };
|
|
32
|
+
this.abort = new AbortController();
|
|
33
|
+
this.seen = new Set(); this.active = null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
check({ allowPaused = false } = {}) {
|
|
37
|
+
if (this.closed || this.unknown || !this.secret || this.paused && !allowPaused) throw new CliError('executor_revoked', 'Local execution stopped');
|
|
38
|
+
pinCheck(this.grant, this.pin(), this.env, { execution: true });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
stop(reason = 'outcome_unknown') {
|
|
42
|
+
this.closed = true; this.revoked ||= reason === 'executor_revoked'; this.abort.abort();
|
|
43
|
+
this.active?.stop(reason);
|
|
44
|
+
this.secret = null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async pump(runId) {
|
|
48
|
+
this.runId = runId;
|
|
49
|
+
let task = null;
|
|
50
|
+
try {
|
|
51
|
+
while (!this.closed) {
|
|
52
|
+
await withLocalLock(() => this.check({ allowPaused: true }), this.env, { timeout: 2000 });
|
|
53
|
+
const polledAt = performance.now();
|
|
54
|
+
const reply = await this.client.localExec(runId, { secret: this.secret });
|
|
55
|
+
if (!validateLocalExecStatus(reply) || reply.requests.length > 1) fail();
|
|
56
|
+
if (reply.stop) break;
|
|
57
|
+
this.paused = reply.paused;
|
|
58
|
+
if (this.paused) {
|
|
59
|
+
if (task) task.interrupted = true;
|
|
60
|
+
this.approval?.abort(); this.active?.stop('executor_revoked');
|
|
61
|
+
}
|
|
62
|
+
for (const request of reply.requests) {
|
|
63
|
+
if (!task && !this.seen.has(request.id)) {
|
|
64
|
+
this.seen.add(request.id);
|
|
65
|
+
const current = { interrupted: false }; task = current;
|
|
66
|
+
current.done = this.execute(request, polledAt).catch(() => { if (!current.interrupted) this.stop(); })
|
|
67
|
+
.finally(() => { if (task === current) task = null; });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
await sleep(1000);
|
|
71
|
+
}
|
|
72
|
+
} finally {
|
|
73
|
+
this.stop();
|
|
74
|
+
await task?.done;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async execute(request, polledAt = performance.now()) {
|
|
79
|
+
const { id, command, timeout, approval_remaining, hard_remaining } = request;
|
|
80
|
+
const secret = this.secret;
|
|
81
|
+
// Subtract the entire poll round trip conservatively; server and client wall clocks may differ.
|
|
82
|
+
const approval = polledAt + approval_remaining*1000, hard = polledAt + hard_remaining*1000;
|
|
83
|
+
if (!/^[0-9a-f]{32}$/.test(id) || typeof command !== 'string' || command.includes('\0')
|
|
84
|
+
|| !Buffer.byteLength(command) || Buffer.byteLength(command) > 8192
|
|
85
|
+
|| !Number.isInteger(timeout) || timeout < 1 || timeout > 600 || !Number.isFinite(approval)
|
|
86
|
+
|| !Number.isFinite(hard) || hard <= performance.now() || request.state !== 'pending') fail();
|
|
87
|
+
let choice = this.session ? 'session' : null, alarm;
|
|
88
|
+
const approvalAbort = this.approval = new AbortController();
|
|
89
|
+
const cancelApproval = () => approvalAbort.abort();
|
|
90
|
+
if (!choice) {
|
|
91
|
+
this.abort.signal.addEventListener('abort', cancelApproval, { once: true });
|
|
92
|
+
if (!this.approve) fail();
|
|
93
|
+
choice = await Promise.race([
|
|
94
|
+
// Leaving the open prompt (Esc, cancel) is a decline; the server must see a refusal, never silence.
|
|
95
|
+
this.approve({ command, timeout, folder: this.grant.root.path, signal: approvalAbort.signal }).catch(e => { if (e?.code === 'action_cancelled') return 'decline'; throw e; }),
|
|
96
|
+
new Promise(resolve => { alarm = setTimeout(() => { resolve('expired'); approvalAbort.abort(); }, Math.max(0, approval-performance.now())); }),
|
|
97
|
+
]).finally(() => {
|
|
98
|
+
if (this.approval === approvalAbort) this.approval = null;
|
|
99
|
+
clearTimeout(alarm); this.abort.signal.removeEventListener('abort', cancelApproval);
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
// Explicit revocation while the prompt was open: the server must record executor_revoked, not_started.
|
|
103
|
+
if (this.revoked) { await this.client.localExec(this.runId, { secret, action: 'refuse', code: 'executor_revoked' }, id); return; }
|
|
104
|
+
if (this.closed) return; // stop-driven cancel: not the user's decision, and the secret is gone
|
|
105
|
+
await withLocalLock(() => this.check(), this.env, { timeout: 2000 });
|
|
106
|
+
if (!['once', 'session'].includes(choice)) {
|
|
107
|
+
await this.client.localExec(this.runId, { secret: this.secret, action: 'refuse', code: choice === 'expired' ? 'approval_timeout' : 'user_declined' }, id);
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (choice === 'session') this.session = true;
|
|
111
|
+
const nonce = randomBytes(32).toString('hex');
|
|
112
|
+
const ack = await this.client.localExec(this.runId, { secret: this.secret, action: 'start', nonce }, id);
|
|
113
|
+
if (ack?.permit !== true || ack.state !== 'started') return;
|
|
114
|
+
let chain, execution;
|
|
115
|
+
try {
|
|
116
|
+
await withLocalLock(() => {
|
|
117
|
+
this.check();
|
|
118
|
+
if (performance.now() + (timeout + 2)*1000 > hard) fail();
|
|
119
|
+
consumeExec(this.runId, id, this.env);
|
|
120
|
+
chain = walk(this.grant);
|
|
121
|
+
execution = this.shell(id, command, timeout, chain[0].fd);
|
|
122
|
+
}, this.env);
|
|
123
|
+
// No await between the last pin check, permit consumption and spawn.
|
|
124
|
+
const answer = await execution;
|
|
125
|
+
if (answer.effect === 'unknown') this.unknown = true;
|
|
126
|
+
// Revocation bars starts immediately; the consumed permit may still seal its typed outcome.
|
|
127
|
+
if (!this.secret && answer.code !== 'executor_revoked') return;
|
|
128
|
+
const body = { secret, action: 'seal', nonce, result: answer };
|
|
129
|
+
try { await this.client.localExec(this.runId, body, id); }
|
|
130
|
+
catch { await this.client.localExec(this.runId, body, id); } // identical seal only; never repeat spawn
|
|
131
|
+
} finally { if (chain) closeChain(chain); }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
async shell(id, command, timeout, fd) {
|
|
135
|
+
const start = performance.now(), out = ring(16000), err = ring(8000);
|
|
136
|
+
const child = spawn('/bin/bash', ['--noprofile', '--norc', '-c', command], {
|
|
137
|
+
cwd: `/proc/${process.pid}/fd/${fd}`, detached: true, stdio: ['ignore', 'pipe', 'pipe'],
|
|
138
|
+
env: localProcessEnv(this.env, this.grant.root.path),
|
|
139
|
+
});
|
|
140
|
+
let reason = null, escalation, failed = false;
|
|
141
|
+
const kill = signal => { if (!child.pid) return; try { process.kill(-child.pid, signal); } catch (error) { if (error.code !== 'ESRCH') throw error; } };
|
|
142
|
+
const stop = why => {
|
|
143
|
+
if (why && !reason) reason = why;
|
|
144
|
+
kill('SIGTERM');
|
|
145
|
+
escalation ??= setTimeout(() => kill('SIGKILL'), 2000);
|
|
146
|
+
};
|
|
147
|
+
this.active = { stop };
|
|
148
|
+
child.stdout.on('data', chunk => out.push(chunk)); child.stderr.on('data', chunk => err.push(chunk));
|
|
149
|
+
child.on('error', () => { failed = true; });
|
|
150
|
+
child.on('exit', () => stop(null)); // descendants may still hold the pipes after their leader exits
|
|
151
|
+
const wall = setTimeout(() => stop('timeout'), timeout * 1000);
|
|
152
|
+
const code = await new Promise(resolve => child.on('close', resolve));
|
|
153
|
+
clearTimeout(wall);
|
|
154
|
+
if (escalation) { kill('SIGKILL'); clearTimeout(escalation); }
|
|
155
|
+
this.active = null;
|
|
156
|
+
const result = { request_id: id, code: failed ? 'spawn_failed' : reason ?? (code === 0 ? 'ok' : 'command_failed'),
|
|
157
|
+
exit_code: code, seconds: (performance.now()-start)/1000, stdout_tail: '', stderr_tail: '', stdout_bytes: out.count, stderr_bytes: err.count,
|
|
158
|
+
truncated: { stdout: out.count > 16000, stderr: err.count > 8000 }, effect: failed ? 'not_started' : reason ? 'unknown' : 'completed' };
|
|
159
|
+
// Counts survive a refusal; no unscanned text is ever attached to an error or persisted.
|
|
160
|
+
const streams = [];
|
|
161
|
+
for (const [stream, buffer] of [['stdout', out], ['stderr', err]]) {
|
|
162
|
+
try { streams.push([stream, buffer.finish()]); }
|
|
163
|
+
catch (error) { result.code = error.code === 'secret_suspected' ? error.code : 'scan_unsupported'; }
|
|
164
|
+
}
|
|
165
|
+
for (const [stream, data] of streams) {
|
|
166
|
+
result[stream+'_bytes'] = data.count; result.truncated[stream] = data.truncated;
|
|
167
|
+
if (!['secret_suspected', 'scan_unsupported'].includes(result.code)) result[stream+'_tail'] = data.text;
|
|
168
|
+
}
|
|
169
|
+
return result;
|
|
170
|
+
}
|
|
171
|
+
}
|
package/src/folders.js
CHANGED
|
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
2
2
|
import { readFileSync, realpathSync, statSync } from "node:fs";
|
|
3
3
|
import { homedir } from "node:os";
|
|
4
4
|
import { dirname, isAbsolute, join, relative, sep, parse } from "node:path";
|
|
5
|
+
import { localMutation, endGrants } from "./localfiles.js";
|
|
5
6
|
import { credentialsPath } from "./credentials.js";
|
|
6
7
|
import { CliError } from "./errors.js";
|
|
7
8
|
import { readStore, withStoreLock, writeStore } from "./store.js";
|
|
@@ -71,6 +72,7 @@ function readRegistry(file) {
|
|
|
71
72
|
export class FolderRegistry {
|
|
72
73
|
constructor({ origin, accountId, cwd = process.cwd(), env = process.env }) {
|
|
73
74
|
if (!origin || !accountId) throw new CliError("folder_identity_invalid", "Origin and account are required");
|
|
75
|
+
this.env = env;
|
|
74
76
|
this.origin = origin;
|
|
75
77
|
this.accountId = accountId;
|
|
76
78
|
this.folder = identity(cwd);
|
|
@@ -137,7 +139,13 @@ export class FolderRegistry {
|
|
|
137
139
|
|
|
138
140
|
broadRoot() { return broadRoot(this.folder.path, this.home); }
|
|
139
141
|
|
|
140
|
-
bind(projectId,
|
|
142
|
+
bind(projectId, options = {}) {
|
|
143
|
+
return localMutation('bind', { origin: this.origin, accountId: this.accountId, cwd: this.folder.path, args: [projectId, options] }, this.env, () => {
|
|
144
|
+
return this.bindLocked(projectId, options);
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
bindLocked(projectId, { confirmHome = false, confirmBroad = confirmHome } = {}) {
|
|
141
149
|
this.requireAccount();
|
|
142
150
|
if (typeof projectId !== "string" || !projectId) throw new CliError("project_invalid", "Choose a Project first");
|
|
143
151
|
const broad = this.broadRoot();
|
|
@@ -149,6 +157,8 @@ export class FolderRegistry {
|
|
|
149
157
|
if (row.pendingCreate || row.pendingRun) {
|
|
150
158
|
throw new CliError("operation_unresolved", "Resolve the pending submission before relinking");
|
|
151
159
|
}
|
|
160
|
+
// Validate first, then durably end authority before publishing the binding.
|
|
161
|
+
endGrants({ origin: this.origin, accountId: this.accountId, root: this.folder.path }, this.env);
|
|
152
162
|
row.projectId = projectId;
|
|
153
163
|
delete row.unlinked;
|
|
154
164
|
delete row.pendingCreate;
|
|
@@ -156,11 +166,18 @@ export class FolderRegistry {
|
|
|
156
166
|
}
|
|
157
167
|
|
|
158
168
|
unlink() {
|
|
169
|
+
return localMutation('unlink', { origin: this.origin, accountId: this.accountId, cwd: this.folder.path, args: [] }, this.env, () => {
|
|
170
|
+
return this.unlinkLocked();
|
|
171
|
+
});
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
unlinkLocked() {
|
|
159
175
|
return withStoreLock(this.file, () => {
|
|
160
176
|
const store = this.#read();
|
|
161
177
|
const row = store.folders[this.key];
|
|
162
178
|
if (row?.pendingCreate || row?.pendingRun) throw new CliError("operation_unresolved",
|
|
163
179
|
"Reconcile the pending submission before unlinking; its identity must survive");
|
|
180
|
+
endGrants({ origin: this.origin, accountId: this.accountId, root: this.folder.path }, this.env);
|
|
164
181
|
store.folders[this.key] = { ...row, origin: this.origin, accountId: this.accountId, folder: this.folder, unlinked: true };
|
|
165
182
|
delete store.folders[this.key].projectId;
|
|
166
183
|
writeStore(this.file, store);
|
|
@@ -178,11 +195,19 @@ export class FolderRegistry {
|
|
|
178
195
|
}
|
|
179
196
|
|
|
180
197
|
completeCreation(key, projectId) {
|
|
181
|
-
|
|
198
|
+
return localMutation('completeCreation', { origin: this.origin, accountId: this.accountId,
|
|
199
|
+
cwd: this.folder.path, args: [key, projectId] }, this.env, () => this.completeCreationLocked(key, projectId));
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
completeCreationLocked(key, projectId) {
|
|
203
|
+
return this.#update(row => {
|
|
182
204
|
if (row.projectId === projectId && !row.pendingCreate) return;
|
|
183
205
|
if (row.pendingCreate?.key !== key || typeof projectId !== "string" || !projectId) {
|
|
184
206
|
throw new CliError("creation_mismatch", "Project creation identity changed");
|
|
185
207
|
}
|
|
208
|
+
// Validation and idempotent completion precede revocation. Its recovery intent
|
|
209
|
+
// must be durable before the new binding can become visible to another terminal.
|
|
210
|
+
endGrants({ origin: this.origin, accountId: this.accountId, root: this.folder.path }, this.env);
|
|
186
211
|
row.projectId = projectId;
|
|
187
212
|
delete row.unlinked;
|
|
188
213
|
delete row.pendingCreate;
|
|
@@ -241,6 +266,7 @@ export class FolderRegistry {
|
|
|
241
266
|
|
|
242
267
|
reserveRun(projectId, body, draftRef = this.draftRef) {
|
|
243
268
|
this.requireAccount();
|
|
269
|
+
if (body.local_exec !== undefined) throw new CliError('admission_unresolved', 'Execution consent cannot be frozen');
|
|
244
270
|
return this.#update(row => {
|
|
245
271
|
if (row.pendingRun) throw new CliError("submission_pending", "Another submission needs reconciliation before a new ask");
|
|
246
272
|
row.pendingRun = { key: randomUUID(), projectId, body: structuredClone(body), draftRef: structuredClone(draftRef) };
|