@revoengine/cli 1.0.14 → 1.0.15
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 +13 -13
- package/dist/src/client.d.ts +0 -11
- package/dist/src/client.js +0 -32
- package/dist/src/commands/env.js +1 -5
- package/dist/src/commands/terminal-browser.d.ts +1 -0
- package/dist/src/commands/terminal-browser.js +23 -1
- package/dist/src/commands/terminal-policy.d.ts +6 -0
- package/dist/src/commands/terminal-policy.js +19 -0
- package/dist/src/commands/terminal-pty.js +2 -0
- package/dist/src/commands/terminal-reconnect-grace.d.ts +19 -0
- package/dist/src/commands/terminal-reconnect-grace.js +58 -0
- package/dist/src/commands/terminal-service.d.ts +4 -3
- package/dist/src/commands/terminal-service.js +19 -15
- package/dist/src/commands/terminal.d.ts +17 -1
- package/dist/src/commands/terminal.js +390 -78
- package/dist/src/config.d.ts +0 -3
- package/dist/src/config.js +0 -2
- package/dist/src/migration.js +0 -1
- package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
- package/dist/src/resource-syncs/database-view-sync.js +1 -12
- package/package.json +5 -4
- package/scripts/ensure-pty-helper.mjs +0 -9
|
@@ -6,16 +6,46 @@ import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
|
6
6
|
import { spawn } from 'node:child_process';
|
|
7
7
|
import WebSocket from 'ws';
|
|
8
8
|
import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
|
|
9
|
-
import { promptConfirm } from "../prompt.js";
|
|
10
9
|
import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
|
|
11
10
|
import { createSandboxScratchDirectory, isTerminalSandbox, sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
|
|
12
|
-
import { executionPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
|
|
13
|
-
import { closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
|
|
11
|
+
import { executionAllowedByGrant, executionPolicyDeadline, remainingPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
|
|
12
|
+
import { closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
|
|
14
13
|
import { uploadWorkspaceImages } from "./terminal-image.js";
|
|
15
14
|
import { ensurePtyHelperExecutable, normalizePtyStartError } from "./terminal-pty.js";
|
|
16
|
-
import { TerminalReconnectGrace } from "./terminal-reconnect-grace.js";
|
|
15
|
+
import { TerminalReconnectGrace, TerminalTransportRecovery, isRunnerTransportHeartbeat } from "./terminal-reconnect-grace.js";
|
|
17
16
|
import { TerminalOperationalLog } from "./terminal-operational-log.js";
|
|
18
17
|
import { createSecureBrowserIdentity, decryptSecureBrowserInput } from "./terminal-secure-browser.js";
|
|
18
|
+
export function selectRegisteredTerminal(devices, grants, name, terminalId) {
|
|
19
|
+
const matching = devices.filter(device => terminalId
|
|
20
|
+
? device.agentTerminalId === terminalId : device.name === name);
|
|
21
|
+
const statuses = new Map(grants.map(grant => [grant.agentTerminalId, grant.status]));
|
|
22
|
+
for (const status of ['approved', 'pending']) {
|
|
23
|
+
const candidates = matching.filter(device => statuses.get(device.agentTerminalId) === status);
|
|
24
|
+
if (candidates.length > 1)
|
|
25
|
+
throw new Error(`Multiple ${status} terminals match ${name} (${candidates.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
|
|
26
|
+
if (candidates.length)
|
|
27
|
+
return candidates[0];
|
|
28
|
+
}
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
function terminalSelector(argv) {
|
|
32
|
+
const named = argv.includes('--name') || argv.some(value => value.startsWith('--name='));
|
|
33
|
+
const identified = argv.includes('--terminal-id') || argv.some(value => value.startsWith('--terminal-id='));
|
|
34
|
+
const requestedName = option(argv, 'name');
|
|
35
|
+
const requestedId = option(argv, 'terminal-id');
|
|
36
|
+
if (named && (!requestedName || requestedName.startsWith('--'))
|
|
37
|
+
|| identified && (!requestedId || requestedId.startsWith('--')))
|
|
38
|
+
throw new Error('--name and --terminal-id require a value.');
|
|
39
|
+
const name = requestedName ?? os.hostname();
|
|
40
|
+
const terminalId = requestedId?.toLowerCase();
|
|
41
|
+
if (identified && named)
|
|
42
|
+
throw new Error('Use either --name or --terminal-id, not both.');
|
|
43
|
+
if (!name.trim() || name.length > 128 || name !== name.trim() || /[\u0000-\u001f\u007f]/u.test(name))
|
|
44
|
+
throw new Error('--name must be a nonempty terminal name of at most 128 characters.');
|
|
45
|
+
if (terminalId !== undefined && !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(terminalId))
|
|
46
|
+
throw new Error('--terminal-id must be a terminal UUID.');
|
|
47
|
+
return { name, terminalId };
|
|
48
|
+
}
|
|
19
49
|
export const MAX_TERMINAL_PROCESS_MS = 59 * 60_000;
|
|
20
50
|
const configDir = getConfigDir;
|
|
21
51
|
const runnerConfig = () => path.join(configDir(), 'runner.json');
|
|
@@ -94,6 +124,113 @@ function saveStore(store) {
|
|
|
94
124
|
}
|
|
95
125
|
}
|
|
96
126
|
}
|
|
127
|
+
async function updateStore(update) {
|
|
128
|
+
fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
129
|
+
const lock = `${runnerConfig()}.lock`;
|
|
130
|
+
const deadline = Date.now() + 10_000;
|
|
131
|
+
let descriptor;
|
|
132
|
+
while (descriptor === undefined) {
|
|
133
|
+
try {
|
|
134
|
+
descriptor = fs.openSync(lock, 'wx', 0o600);
|
|
135
|
+
try {
|
|
136
|
+
fs.writeFileSync(descriptor, String(process.pid));
|
|
137
|
+
}
|
|
138
|
+
catch (error) {
|
|
139
|
+
fs.closeSync(descriptor);
|
|
140
|
+
fs.unlinkSync(lock);
|
|
141
|
+
throw error;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
if (error.code !== 'EEXIST')
|
|
146
|
+
throw error;
|
|
147
|
+
try {
|
|
148
|
+
const age = Date.now() - fs.statSync(lock).mtimeMs;
|
|
149
|
+
if (age > 120_000) {
|
|
150
|
+
const pid = Number(fs.readFileSync(lock, 'utf8'));
|
|
151
|
+
let alive = Number.isSafeInteger(pid) && pid > 0;
|
|
152
|
+
if (alive)
|
|
153
|
+
try {
|
|
154
|
+
process.kill(pid, 0);
|
|
155
|
+
}
|
|
156
|
+
catch (probeError) {
|
|
157
|
+
if (probeError.code === 'ESRCH')
|
|
158
|
+
alive = false;
|
|
159
|
+
}
|
|
160
|
+
if (!alive) {
|
|
161
|
+
fs.unlinkSync(lock);
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
catch (statError) {
|
|
167
|
+
if (statError.code !== 'ENOENT')
|
|
168
|
+
throw statError;
|
|
169
|
+
}
|
|
170
|
+
if (Date.now() >= deadline)
|
|
171
|
+
throw new Error('Terminal registration store is busy. Retry the command.');
|
|
172
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
const current = readStore();
|
|
177
|
+
update(current);
|
|
178
|
+
saveStore(current);
|
|
179
|
+
}
|
|
180
|
+
finally {
|
|
181
|
+
fs.closeSync(descriptor);
|
|
182
|
+
fs.unlinkSync(lock);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
export function acquireRunnerLock(agentTerminalId) {
|
|
186
|
+
fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
187
|
+
const lock = path.join(configDir(), `runner-${agentTerminalId}.lock`);
|
|
188
|
+
let descriptor;
|
|
189
|
+
for (;;) {
|
|
190
|
+
try {
|
|
191
|
+
descriptor = fs.openSync(lock, 'wx', 0o600);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
if (error.code !== 'EEXIST')
|
|
196
|
+
throw error;
|
|
197
|
+
let pid;
|
|
198
|
+
try {
|
|
199
|
+
pid = Number(fs.readFileSync(lock, 'utf8'));
|
|
200
|
+
}
|
|
201
|
+
catch (readError) {
|
|
202
|
+
if (readError.code === 'ENOENT')
|
|
203
|
+
continue;
|
|
204
|
+
throw readError;
|
|
205
|
+
}
|
|
206
|
+
if ((!Number.isSafeInteger(pid) || pid <= 0) && Date.now() - fs.statSync(lock).mtimeMs > 5_000) {
|
|
207
|
+
fs.unlinkSync(lock);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (Number.isSafeInteger(pid) && pid > 0) {
|
|
211
|
+
try {
|
|
212
|
+
process.kill(pid, 0);
|
|
213
|
+
}
|
|
214
|
+
catch (probeError) {
|
|
215
|
+
if (probeError.code === 'ESRCH') {
|
|
216
|
+
fs.unlinkSync(lock);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
throw new Error(`Terminal ${agentTerminalId} is already connected by another local CLI process. Use a different --name or --terminal-id.`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
try {
|
|
225
|
+
fs.writeFileSync(descriptor, String(process.pid));
|
|
226
|
+
}
|
|
227
|
+
catch (error) {
|
|
228
|
+
fs.closeSync(descriptor);
|
|
229
|
+
fs.unlinkSync(lock);
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
return () => { fs.closeSync(descriptor); fs.unlinkSync(lock); };
|
|
233
|
+
}
|
|
97
234
|
export function resolveWorkspaceDirectory(root, requested) {
|
|
98
235
|
const workspace = fs.realpathSync(root);
|
|
99
236
|
const workdir = fs.realpathSync(requested);
|
|
@@ -128,7 +265,7 @@ function resolveProfile(argv) {
|
|
|
128
265
|
throw new Error('A personal Revo API key is required. Run revo auth login or select a CLI profile.');
|
|
129
266
|
return { baseUrl: configured.baseUrl.replace(/\/$/, ''), token,
|
|
130
267
|
instance: option(argv, 'instance') || (urlOverride || tokenOverride ? undefined : configured.instance),
|
|
131
|
-
realtimeUrl: option(argv, 'realtime-url')
|
|
268
|
+
realtimeUrl: option(argv, 'realtime-url') };
|
|
132
269
|
}
|
|
133
270
|
function apiUrl(profile, route) {
|
|
134
271
|
const base = profile.baseUrl.replace(/\/(?:api\/)?v1\/?$/, '');
|
|
@@ -138,12 +275,6 @@ function apiUrl(profile, route) {
|
|
|
138
275
|
return `${base}/api/v1${route}`;
|
|
139
276
|
}
|
|
140
277
|
async function api(profile, method, route, body) {
|
|
141
|
-
if (profile.production && !profile.productionWriteConfirmed && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
|
|
142
|
-
const confirmed = await promptConfirm(`PRODUCTION: send ${method} ${apiUrl(profile, route)}?`, false);
|
|
143
|
-
if (!confirmed)
|
|
144
|
-
throw new Error('Production write cancelled. Confirm the operation in an interactive terminal.');
|
|
145
|
-
profile.productionWriteConfirmed = true;
|
|
146
|
-
}
|
|
147
278
|
const response = await fetch(apiUrl(profile, route), {
|
|
148
279
|
method,
|
|
149
280
|
redirect: 'manual',
|
|
@@ -175,12 +306,15 @@ function send(socket, frame) {
|
|
|
175
306
|
socket.send(JSON.stringify(frame));
|
|
176
307
|
}
|
|
177
308
|
export function boundResultFrame(frame) {
|
|
178
|
-
const bounded = { ...frame, stdout: String(frame.stdout || ''), stderr: String(frame.stderr || '')
|
|
179
|
-
|
|
309
|
+
const bounded = { ...frame, stdout: String(frame.stdout || ''), stderr: String(frame.stderr || ''),
|
|
310
|
+
truncated: frame.truncated === true };
|
|
311
|
+
while (Buffer.byteLength(bounded.stdout) + Buffer.byteLength(bounded.stderr) > 80_000
|
|
312
|
+
|| Buffer.byteLength(JSON.stringify(bounded)) > 90_000) {
|
|
180
313
|
if (bounded.stdout.length >= bounded.stderr.length)
|
|
181
314
|
bounded.stdout = bounded.stdout.slice(0, Math.floor(bounded.stdout.length * 0.75));
|
|
182
315
|
else
|
|
183
316
|
bounded.stderr = bounded.stderr.slice(0, Math.floor(bounded.stderr.length * 0.75));
|
|
317
|
+
bounded.truncated = true;
|
|
184
318
|
}
|
|
185
319
|
return bounded;
|
|
186
320
|
}
|
|
@@ -226,8 +360,8 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
226
360
|
let terminal;
|
|
227
361
|
try {
|
|
228
362
|
if (tty) {
|
|
229
|
-
ensurePtyHelperExecutable();
|
|
230
363
|
const pty = await import('node-pty');
|
|
364
|
+
ensurePtyHelperExecutable();
|
|
231
365
|
terminal = pty.spawn(launch.file, launch.args, {
|
|
232
366
|
cwd: workdir, env, name: 'xterm-256color', cols: input.cols || 80, rows: input.rows || 24,
|
|
233
367
|
});
|
|
@@ -283,12 +417,18 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
283
417
|
hardStop.unref?.();
|
|
284
418
|
};
|
|
285
419
|
const timer = setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), MAX_TERMINAL_PROCESS_MS));
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
420
|
+
let policyTimer;
|
|
421
|
+
const updatePolicyDeadline = (deadline) => {
|
|
422
|
+
if (policyTimer)
|
|
423
|
+
clearTimeout(policyTimer);
|
|
424
|
+
policyTimer = deadline == null ? undefined : setTimeout(() => {
|
|
425
|
+
if (finished)
|
|
426
|
+
return;
|
|
427
|
+
policyExpired = true;
|
|
428
|
+
terminate();
|
|
429
|
+
}, Math.max(0, deadline - Date.now()));
|
|
430
|
+
};
|
|
431
|
+
updatePolicyDeadline(input.policyDeadlineMs ?? null);
|
|
292
432
|
const append = (chunk, kind) => {
|
|
293
433
|
const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
|
|
294
434
|
if (logPart.length && logFd !== undefined) {
|
|
@@ -339,6 +479,9 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
339
479
|
clearTimeout(timer);
|
|
340
480
|
if (policyTimer)
|
|
341
481
|
clearTimeout(policyTimer);
|
|
482
|
+
const diagnostic = [error?.message, policyExpired ? 'terminal_policy_expired' : null].filter(Boolean).join('\n');
|
|
483
|
+
if (diagnostic)
|
|
484
|
+
append(Buffer.from(`${stderr && !stderr.endsWith('\n') ? '\n' : ''}${diagnostic}`), 'stderr');
|
|
342
485
|
if (scratch) {
|
|
343
486
|
try {
|
|
344
487
|
fs.rmSync(scratch, { recursive: true, force: true });
|
|
@@ -354,15 +497,14 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
354
497
|
}
|
|
355
498
|
}
|
|
356
499
|
onDone({ executed: !error, exitCode: (timedOut || policyExpired) && exitCode === 0 ? null : exitCode,
|
|
357
|
-
stdout, stderr
|
|
358
|
-
.filter(Boolean).join('\n'),
|
|
500
|
+
stdout, stderr,
|
|
359
501
|
timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath,
|
|
360
502
|
...(policyExpired ? { policyExpired: true } : {}) });
|
|
361
503
|
};
|
|
362
504
|
child?.on('close', code => finish(code));
|
|
363
505
|
child?.on('error', error => finish(null, error));
|
|
364
506
|
terminal?.onExit(({ exitCode }) => finish(exitCode));
|
|
365
|
-
return { pid, terminate,
|
|
507
|
+
return { pid, terminate, updatePolicyDeadline,
|
|
366
508
|
write: chars => { if (terminal)
|
|
367
509
|
terminal.write(chars);
|
|
368
510
|
else
|
|
@@ -408,14 +550,20 @@ export function runWorkspacePatch(input, onDone) {
|
|
|
408
550
|
}
|
|
409
551
|
catch { /* exited */ }
|
|
410
552
|
}, 60_000);
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
if (
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
553
|
+
let policyTimer;
|
|
554
|
+
const updatePolicyDeadline = (deadline) => {
|
|
555
|
+
if (policyTimer)
|
|
556
|
+
clearTimeout(policyTimer);
|
|
557
|
+
policyTimer = deadline == null ? undefined : setTimeout(() => {
|
|
558
|
+
policyExpired = true;
|
|
559
|
+
if (child.pid)
|
|
560
|
+
try {
|
|
561
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
562
|
+
}
|
|
563
|
+
catch { /* exited */ }
|
|
564
|
+
}, Math.max(0, deadline - Date.now()));
|
|
565
|
+
};
|
|
566
|
+
updatePolicyDeadline(input.policyDeadlineMs ?? null);
|
|
419
567
|
child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8').slice(0, 4_000 - stdout.length); });
|
|
420
568
|
child.stderr?.on('data', (chunk) => { stderr += chunk.toString('utf8').slice(0, 4_000 - stderr.length); });
|
|
421
569
|
child.stdin?.on('error', () => { });
|
|
@@ -437,7 +585,7 @@ export function runWorkspacePatch(input, onDone) {
|
|
|
437
585
|
};
|
|
438
586
|
child.on('close', code => finish(code));
|
|
439
587
|
child.on('error', error => finish(null, error));
|
|
440
|
-
return child;
|
|
588
|
+
return Object.assign(child, { updatePolicyDeadline });
|
|
441
589
|
}
|
|
442
590
|
async function connect(profile, device) {
|
|
443
591
|
const logDeviceId = /^[A-Za-z0-9_-]{1,128}$/u.test(device.agentTerminalId)
|
|
@@ -450,6 +598,7 @@ async function connect(profile, device) {
|
|
|
450
598
|
let activeConnectionId = '';
|
|
451
599
|
const activeChildren = new Set();
|
|
452
600
|
const children = new Map();
|
|
601
|
+
const activePolicies = new Map();
|
|
453
602
|
const cancelledExecutions = new Set();
|
|
454
603
|
const outputByExecution = new Map();
|
|
455
604
|
const completed = new Map();
|
|
@@ -464,9 +613,30 @@ async function connect(profile, device) {
|
|
|
464
613
|
let minimumPolicyGrantRevision = 0;
|
|
465
614
|
let policyRevisionUnavailable = false;
|
|
466
615
|
let securePolicyEpoch = 0;
|
|
616
|
+
const updateGrantPolicy = async (revision, grant) => {
|
|
617
|
+
if (revision < minimumPolicyGrantRevision)
|
|
618
|
+
return;
|
|
619
|
+
minimumPolicyGrantRevision = revision;
|
|
620
|
+
policyRevisionUnavailable = false;
|
|
621
|
+
let stopped = 0;
|
|
622
|
+
for (const [executionId, child] of children) {
|
|
623
|
+
const policy = activePolicies.get(executionId);
|
|
624
|
+
if (!policy || !executionAllowedByGrant(policy, grant)) {
|
|
625
|
+
cancelledExecutions.add(executionId);
|
|
626
|
+
child.terminate();
|
|
627
|
+
stopped++;
|
|
628
|
+
}
|
|
629
|
+
else
|
|
630
|
+
child.updatePolicyDeadline?.(remainingPolicyDeadline(policy, grant));
|
|
631
|
+
}
|
|
632
|
+
const closed = await reconcileBrowserSessions(grant.networkMode);
|
|
633
|
+
operationalLog.write(stopped || closed ? 'WARN' : 'INFO', {}, 'terminal.policy_updated', { stoppedExecutions: stopped, closedBrowserSessions: closed });
|
|
634
|
+
};
|
|
467
635
|
const sendCurrent = (frame) => {
|
|
468
636
|
if (activeConnectionId && activeSocket?.readyState === WebSocket.OPEN)
|
|
469
|
-
send(activeSocket,
|
|
637
|
+
send(activeSocket, frame.type === 'result'
|
|
638
|
+
? boundResultFrame({ ...frame, connectionId: activeConnectionId })
|
|
639
|
+
: { ...frame, connectionId: activeConnectionId });
|
|
470
640
|
};
|
|
471
641
|
const flushExecution = (executionId) => {
|
|
472
642
|
if (!resumed.has(executionId))
|
|
@@ -500,6 +670,7 @@ async function connect(profile, device) {
|
|
|
500
670
|
headers: { Authorization: `Bearer ${profile.token}`,
|
|
501
671
|
...(profile.instance ? { instance: profile.instance } : {}) },
|
|
502
672
|
perMessageDeflate: false,
|
|
673
|
+
handshakeTimeout: 10_000,
|
|
503
674
|
});
|
|
504
675
|
activeSocket = socket;
|
|
505
676
|
let connectionId = '';
|
|
@@ -507,19 +678,40 @@ async function connect(profile, device) {
|
|
|
507
678
|
let heartbeat;
|
|
508
679
|
let lastHeartbeat = Date.now();
|
|
509
680
|
let incoming = Promise.resolve();
|
|
681
|
+
const recovery = new TerminalTransportRecovery(() => socket.terminate(), () => {
|
|
682
|
+
backoffMs = 1_000;
|
|
683
|
+
reconnectGrace.clear();
|
|
684
|
+
});
|
|
510
685
|
socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
|
|
511
686
|
secret: device.secret, capabilities: ['workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
|
|
512
|
-
'terminal_policy_v2',
|
|
687
|
+
'terminal_policy_v2', 'terminal_policy_selective_v1',
|
|
513
688
|
'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
|
|
514
689
|
'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'save_image_v1',
|
|
515
690
|
...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])],
|
|
516
691
|
secureBrowserPublicKey: secureIdentity.publicKey, secureBrowserKeyId: secureIdentity.keyId }));
|
|
517
692
|
socket.on('message', raw => {
|
|
693
|
+
let frame;
|
|
694
|
+
try {
|
|
695
|
+
frame = JSON.parse(raw.toString());
|
|
696
|
+
}
|
|
697
|
+
catch {
|
|
698
|
+
socket.terminate();
|
|
699
|
+
return;
|
|
700
|
+
}
|
|
701
|
+
// A queued browser action or output processing must not hide a live transport.
|
|
702
|
+
if (isRunnerTransportHeartbeat(frame, connectionId)) {
|
|
703
|
+
lastHeartbeat = Date.now();
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
518
706
|
incoming = incoming.then(async () => {
|
|
519
707
|
if (stopping || socket.readyState !== WebSocket.OPEN)
|
|
520
708
|
return;
|
|
521
|
-
const frame = JSON.parse(raw.toString());
|
|
522
709
|
if (frame.type === 'ready' && frame.connectionId) {
|
|
710
|
+
if (connectionId) {
|
|
711
|
+
socket.terminate();
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
lastHeartbeat = Date.now();
|
|
523
715
|
securePolicyEpoch++;
|
|
524
716
|
connectionId = frame.connectionId;
|
|
525
717
|
activeConnectionId = connectionId;
|
|
@@ -530,12 +722,16 @@ async function connect(profile, device) {
|
|
|
530
722
|
}
|
|
531
723
|
else
|
|
532
724
|
policyRevisionUnavailable = true;
|
|
533
|
-
|
|
534
|
-
|
|
725
|
+
const ready = frame;
|
|
726
|
+
if (ready.grantMode && ready.networkMode && Number.isSafeInteger(ready.policyGrantRevision))
|
|
727
|
+
await updateGrantPolicy(ready.policyGrantRevision, { mode: ready.grantMode, networkMode: ready.networkMode });
|
|
535
728
|
console.log(`Connected ${device.name} (${device.agentTerminalId}).`);
|
|
536
729
|
operationalLog.write('INFO', {}, 'socket.ready', { resumedExecutions: children.size + completed.size });
|
|
537
|
-
|
|
730
|
+
const pendingResumes = new Set([...children.keys(), ...completed.keys()]);
|
|
731
|
+
recovery.ready(pendingResumes);
|
|
732
|
+
for (const executionId of pendingResumes) {
|
|
538
733
|
send(socket, { type: 'resume', connectionId, executionId });
|
|
734
|
+
}
|
|
539
735
|
heartbeat = setInterval(() => {
|
|
540
736
|
if (Date.now() - lastHeartbeat > 45_000) {
|
|
541
737
|
socket.terminate();
|
|
@@ -545,8 +741,22 @@ async function connect(profile, device) {
|
|
|
545
741
|
}, 15_000);
|
|
546
742
|
return;
|
|
547
743
|
}
|
|
548
|
-
if (frame.type === 'heartbeat')
|
|
549
|
-
|
|
744
|
+
if (frame.type === 'heartbeat')
|
|
745
|
+
return;
|
|
746
|
+
if (frame.type === 'policy_updated') {
|
|
747
|
+
const update = frame;
|
|
748
|
+
if (update.connectionId !== connectionId)
|
|
749
|
+
return;
|
|
750
|
+
if (!Number.isSafeInteger(update.policyGrantRevision) || update.policyGrantRevision < 0
|
|
751
|
+
|| !['review', 'full'].includes(update.grantMode || '')
|
|
752
|
+
|| !['restricted', 'sandbox', 'external'].includes(update.networkMode || '')) {
|
|
753
|
+
policyRevisionUnavailable = true;
|
|
754
|
+
for (const child of children.values())
|
|
755
|
+
child.terminate();
|
|
756
|
+
await closeBrowserSessions();
|
|
757
|
+
return;
|
|
758
|
+
}
|
|
759
|
+
await updateGrantPolicy(update.policyGrantRevision, { mode: update.grantMode, networkMode: update.networkMode });
|
|
550
760
|
return;
|
|
551
761
|
}
|
|
552
762
|
if (frame.type === 'policy_revoked') {
|
|
@@ -612,11 +822,13 @@ async function connect(profile, device) {
|
|
|
612
822
|
if (frame.connectionId !== connectionId || !frame.executionId)
|
|
613
823
|
return;
|
|
614
824
|
if (frame.type === 'resumed') {
|
|
825
|
+
recovery.accepted(frame.executionId);
|
|
615
826
|
resumed.add(frame.executionId);
|
|
616
827
|
flushExecution(frame.executionId);
|
|
617
828
|
return;
|
|
618
829
|
}
|
|
619
830
|
if (frame.type === 'result_ack' || frame.type === 'resume_rejected') {
|
|
831
|
+
recovery.accepted(frame.executionId);
|
|
620
832
|
if (frame.type === 'resume_rejected') {
|
|
621
833
|
operationalLog.write('WARN', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.resume_rejected');
|
|
622
834
|
children.get(frame.executionId)?.terminate();
|
|
@@ -709,6 +921,7 @@ async function connect(profile, device) {
|
|
|
709
921
|
return;
|
|
710
922
|
}
|
|
711
923
|
try {
|
|
924
|
+
activePolicies.set(frame.executionId, frame);
|
|
712
925
|
traces.set(frame.executionId, trace);
|
|
713
926
|
operationalLog.write('INFO', trace, 'execution.started', { operation, sandbox: frame.sandbox });
|
|
714
927
|
resumed.add(frame.executionId);
|
|
@@ -716,11 +929,18 @@ async function connect(profile, device) {
|
|
|
716
929
|
if (operation === 'save_image') {
|
|
717
930
|
const controller = new AbortController();
|
|
718
931
|
const policyDeadline = executionPolicyDeadline(frame);
|
|
719
|
-
|
|
720
|
-
|
|
932
|
+
let policyTimer;
|
|
933
|
+
const updatePolicyDeadline = (deadline) => {
|
|
934
|
+
if (policyTimer)
|
|
935
|
+
clearTimeout(policyTimer);
|
|
936
|
+
policyTimer = deadline == null ? undefined : setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
|
|
937
|
+
policyTimer?.unref?.();
|
|
938
|
+
};
|
|
939
|
+
updatePolicyDeadline(policyDeadline);
|
|
721
940
|
const child = { pid: undefined, write: () => undefined,
|
|
722
941
|
closeStdin: () => undefined, resize: () => undefined,
|
|
723
|
-
terminate: () => controller.abort()
|
|
942
|
+
terminate: () => controller.abort(),
|
|
943
|
+
updatePolicyDeadline };
|
|
724
944
|
children.set(frame.executionId, child);
|
|
725
945
|
activeChildren.add(child);
|
|
726
946
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
@@ -728,6 +948,7 @@ async function connect(profile, device) {
|
|
|
728
948
|
if (policyTimer)
|
|
729
949
|
clearTimeout(policyTimer);
|
|
730
950
|
children.delete(frame.executionId);
|
|
951
|
+
activePolicies.delete(frame.executionId);
|
|
731
952
|
activeChildren.delete(child);
|
|
732
953
|
completed.set(frame.executionId, { executed: true, exitCode: 0, stdout: `Uploaded ${count} image(s).`, stderr: '' });
|
|
733
954
|
operationalLog.write('INFO', trace, 'execution.completed', { operation, exitCode: 0, images: count });
|
|
@@ -737,6 +958,7 @@ async function connect(profile, device) {
|
|
|
737
958
|
if (policyTimer)
|
|
738
959
|
clearTimeout(policyTimer);
|
|
739
960
|
children.delete(frame.executionId);
|
|
961
|
+
activePolicies.delete(frame.executionId);
|
|
740
962
|
activeChildren.delete(child);
|
|
741
963
|
completed.set(frame.executionId, { executed: false, exitCode: null, stdout: '',
|
|
742
964
|
stderr: error instanceof Error ? error.message : 'image_upload_failed' });
|
|
@@ -750,12 +972,19 @@ async function connect(profile, device) {
|
|
|
750
972
|
if (operation === 'browser') {
|
|
751
973
|
const controller = new AbortController();
|
|
752
974
|
const policyDeadline = executionPolicyDeadline(frame);
|
|
753
|
-
|
|
754
|
-
|
|
975
|
+
let policyTimer;
|
|
976
|
+
const updatePolicyDeadline = (deadline) => {
|
|
977
|
+
if (policyTimer)
|
|
978
|
+
clearTimeout(policyTimer);
|
|
979
|
+
policyTimer = deadline == null ? undefined : setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
|
|
980
|
+
policyTimer?.unref?.();
|
|
981
|
+
};
|
|
982
|
+
updatePolicyDeadline(policyDeadline);
|
|
755
983
|
let actionAttempted = false;
|
|
756
984
|
const child = { pid: undefined, write: () => undefined,
|
|
757
985
|
closeStdin: () => undefined, resize: () => undefined,
|
|
758
|
-
terminate: () => controller.abort()
|
|
986
|
+
terminate: () => controller.abort(),
|
|
987
|
+
updatePolicyDeadline };
|
|
759
988
|
children.set(frame.executionId, child);
|
|
760
989
|
activeChildren.add(child);
|
|
761
990
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
@@ -778,6 +1007,7 @@ async function connect(profile, device) {
|
|
|
778
1007
|
if (policyTimer)
|
|
779
1008
|
clearTimeout(policyTimer);
|
|
780
1009
|
children.delete(frame.executionId);
|
|
1010
|
+
activePolicies.delete(frame.executionId);
|
|
781
1011
|
activeChildren.delete(child);
|
|
782
1012
|
completed.set(frame.executionId, { executed: true, exitCode: 0,
|
|
783
1013
|
stdout: browserResult.dom, stderr: '', screenshotPath: browserResult.screenshotPath || null,
|
|
@@ -791,6 +1021,7 @@ async function connect(profile, device) {
|
|
|
791
1021
|
if (policyTimer)
|
|
792
1022
|
clearTimeout(policyTimer);
|
|
793
1023
|
children.delete(frame.executionId);
|
|
1024
|
+
activePolicies.delete(frame.executionId);
|
|
794
1025
|
activeChildren.delete(child);
|
|
795
1026
|
const code = error instanceof Error && /^[a-z][a-z_]+$/u.test(error.message)
|
|
796
1027
|
? error.message : 'browser_failed';
|
|
@@ -811,6 +1042,7 @@ async function connect(profile, device) {
|
|
|
811
1042
|
allowDelete: frame.sandbox === 'unrestricted',
|
|
812
1043
|
policyDeadlineMs: executionPolicyDeadline(frame) }, result => {
|
|
813
1044
|
children.delete(frame.executionId);
|
|
1045
|
+
activePolicies.delete(frame.executionId);
|
|
814
1046
|
activeChildren.delete(child);
|
|
815
1047
|
completed.set(frame.executionId, { ...result, cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
816
1048
|
operationalLog.write(result.exitCode === 0 ? 'INFO' : 'ERROR', trace, result.exitCode === 0 ? 'execution.completed' : 'execution.failed', { operation, exitCode: result.exitCode ?? 'none', executed: result.executed });
|
|
@@ -826,6 +1058,7 @@ async function connect(profile, device) {
|
|
|
826
1058
|
process.kill(-patchChild.pid, 'SIGTERM');
|
|
827
1059
|
}
|
|
828
1060
|
catch { /* exited */ } },
|
|
1061
|
+
updatePolicyDeadline: deadline => patchChild.updatePolicyDeadline(deadline),
|
|
829
1062
|
};
|
|
830
1063
|
children.set(frame.executionId, child);
|
|
831
1064
|
activeChildren.add(child);
|
|
@@ -839,6 +1072,7 @@ async function connect(profile, device) {
|
|
|
839
1072
|
cols: frame.cols, rows: frame.rows,
|
|
840
1073
|
executionId: frame.executionId }, result => {
|
|
841
1074
|
children.delete(frame.executionId);
|
|
1075
|
+
activePolicies.delete(frame.executionId);
|
|
842
1076
|
activeChildren.delete(child);
|
|
843
1077
|
const { stdout, stderr, ...completion } = result;
|
|
844
1078
|
completed.set(frame.executionId, { ...completion,
|
|
@@ -861,6 +1095,7 @@ async function connect(profile, device) {
|
|
|
861
1095
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
862
1096
|
}
|
|
863
1097
|
catch (error) {
|
|
1098
|
+
activePolicies.delete(frame.executionId);
|
|
864
1099
|
resumed.delete(frame.executionId);
|
|
865
1100
|
outputByExecution.delete(frame.executionId);
|
|
866
1101
|
traces.delete(frame.executionId);
|
|
@@ -876,6 +1111,7 @@ async function connect(profile, device) {
|
|
|
876
1111
|
operationalLog.write(code === 1000 ? 'INFO' : 'WARN', {}, 'socket.closed', { code, activeExecutions: children.size, policyViolation: code === 1008 });
|
|
877
1112
|
if (heartbeat)
|
|
878
1113
|
clearInterval(heartbeat);
|
|
1114
|
+
recovery.close();
|
|
879
1115
|
if (activeSocket === socket)
|
|
880
1116
|
activeConnectionId = '';
|
|
881
1117
|
resumed.clear();
|
|
@@ -922,13 +1158,13 @@ async function connect(profile, device) {
|
|
|
922
1158
|
export async function handleTerminalCommand(argv) {
|
|
923
1159
|
const command = argv[0] || 'help';
|
|
924
1160
|
if (command === 'help' || argv.includes('--help')) {
|
|
925
|
-
console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME] [--url URL] [--realtime-url URL]\nrevo terminal service install|uninstall --workspace PATH [--project NAME]');
|
|
1161
|
+
console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID] [--url URL] [--realtime-url URL]\nrevo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]');
|
|
926
1162
|
return;
|
|
927
1163
|
}
|
|
928
1164
|
if (command === 'service') {
|
|
929
1165
|
const action = argv[1];
|
|
930
1166
|
if (!action || action === 'help') {
|
|
931
|
-
console.log('revo terminal service install|uninstall --workspace PATH [--project NAME]');
|
|
1167
|
+
console.log('revo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]');
|
|
932
1168
|
return;
|
|
933
1169
|
}
|
|
934
1170
|
if (action !== 'install' && action !== 'uninstall')
|
|
@@ -938,8 +1174,22 @@ export async function handleTerminalCommand(argv) {
|
|
|
938
1174
|
throw new Error('Terminal service requires --workspace PATH.');
|
|
939
1175
|
const workspace = fs.existsSync(requestedWorkspace) ? fs.realpathSync(requestedWorkspace) : path.resolve(requestedWorkspace);
|
|
940
1176
|
const envName = selectedProject(argv) || getActiveEnvironmentName();
|
|
1177
|
+
const { name, terminalId } = terminalSelector(argv);
|
|
1178
|
+
const saved = envName === 'default' ? loadStoredConfig({ allowLegacy: false }) : getEnvironmentProfile(envName);
|
|
1179
|
+
const baseUrl = saved?.baseUrl?.replace(/\/$/, '');
|
|
1180
|
+
const devices = readStore().devices.filter(item => item.workspace === workspace && item.baseUrl === baseUrl
|
|
1181
|
+
&& (!saved?.instance || item.instance === saved.instance));
|
|
1182
|
+
const matching = devices.filter(item => terminalId ? item.agentTerminalId === terminalId : item.name === name);
|
|
941
1183
|
if (action === 'uninstall') {
|
|
942
|
-
|
|
1184
|
+
if (matching.length > 1)
|
|
1185
|
+
throw new Error(`Multiple terminals match ${name} (${matching.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
|
|
1186
|
+
if (!terminalId && matching.length === 0 && option(argv, 'name'))
|
|
1187
|
+
throw new Error('No local terminal registration matches --name. Use --terminal-id to uninstall its service.');
|
|
1188
|
+
const selectedId = terminalId || matching[0]?.agentTerminalId;
|
|
1189
|
+
const result = uninstallTerminalService({ workspace, envName,
|
|
1190
|
+
terminalId: selectedId && (terminalId || option(argv, 'name')
|
|
1191
|
+
|| terminalServiceInstalled(workspace, envName, selectedId)) ? selectedId : undefined,
|
|
1192
|
+
configHome: process.env.XDG_CONFIG_HOME });
|
|
943
1193
|
console.log(result.removed ? `Terminal service stopped and removed (${result.label}). Grant remains active.`
|
|
944
1194
|
: `No terminal service installed for this workspace (${result.label}).`);
|
|
945
1195
|
return;
|
|
@@ -949,20 +1199,33 @@ export async function handleTerminalCommand(argv) {
|
|
|
949
1199
|
for (const unsupported of ['token', 'url', 'instance', 'realtime-url'])
|
|
950
1200
|
if (option(argv, unsupported))
|
|
951
1201
|
throw new Error(`Service install cannot use --${unsupported}; use a saved CLI login/profile.`);
|
|
952
|
-
const saved = envName === 'default' ? loadStoredConfig({ allowLegacy: false }) : getEnvironmentProfile(envName);
|
|
953
1202
|
if (!saved?.token?.startsWith('sk-'))
|
|
954
1203
|
throw new Error('A saved personal Revo API key is required. Run revo auth login or select a saved --project profile.');
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
const device = devices[0];
|
|
961
|
-
const profile = { baseUrl, token: saved.token, instance: device.instance };
|
|
1204
|
+
if (!matching.length)
|
|
1205
|
+
throw new Error('No registered terminal for this workspace, name and saved profile. Run revo terminal connect first.');
|
|
1206
|
+
if (!saved.instance && new Set(matching.map(item => item.instance)).size !== 1)
|
|
1207
|
+
throw new Error('The saved profile matches terminals in multiple instances. Select an instance-bound profile.');
|
|
1208
|
+
const profile = { baseUrl: baseUrl, token: saved.token, instance: saved.instance || matching[0].instance };
|
|
962
1209
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1210
|
+
const selected = selectRegisteredTerminal(matching, listing.devices, name, terminalId);
|
|
1211
|
+
if (!selected || !listing.devices.some(grant => grant.agentTerminalId === selected.agentTerminalId && grant.status === 'approved'))
|
|
1212
|
+
throw new Error('The selected terminal is not approved.');
|
|
1213
|
+
if (terminalServiceInstalled(workspace, envName))
|
|
1214
|
+
throw new Error('Uninstall the legacy workspace service before installing a terminal-specific service.');
|
|
1215
|
+
if (!terminalServiceInstalled(workspace, envName, selected.agentTerminalId)) {
|
|
1216
|
+
let releaseRunnerLock;
|
|
1217
|
+
try {
|
|
1218
|
+
releaseRunnerLock = acquireRunnerLock(selected.agentTerminalId);
|
|
1219
|
+
}
|
|
1220
|
+
catch (error) {
|
|
1221
|
+
if (error instanceof Error && error.message.includes('already connected'))
|
|
1222
|
+
throw new Error('Stop the selected foreground terminal runner before installing its background service.');
|
|
1223
|
+
throw error;
|
|
1224
|
+
}
|
|
1225
|
+
releaseRunnerLock();
|
|
1226
|
+
}
|
|
1227
|
+
const result = installTerminalService({ workspace, envName, terminalId: selected.agentTerminalId,
|
|
1228
|
+
pathValue: process.env.PATH,
|
|
966
1229
|
configHome: process.env.XDG_CONFIG_HOME });
|
|
967
1230
|
console.log(result.installed ? `Terminal service installed and started (${result.label}).`
|
|
968
1231
|
: `Terminal service already installed (${result.label}).`);
|
|
@@ -979,53 +1242,96 @@ export async function handleTerminalCommand(argv) {
|
|
|
979
1242
|
}
|
|
980
1243
|
const workspace = fs.realpathSync(option(argv, 'workspace') || process.cwd());
|
|
981
1244
|
const store = readStore();
|
|
982
|
-
|
|
1245
|
+
const selector = terminalSelector(argv);
|
|
1246
|
+
let { name } = selector;
|
|
1247
|
+
const { terminalId } = selector;
|
|
1248
|
+
const profileDevices = store.devices.filter(item => item.workspace === workspace
|
|
1249
|
+
&& item.baseUrl === profile.baseUrl && item.instance === profile.instance);
|
|
1250
|
+
let matchingDevices = profileDevices.filter(item => terminalId ? item.agentTerminalId === terminalId : item.name === name);
|
|
1251
|
+
if (command === 'connect' && !terminalId && option(argv, 'name') === undefined
|
|
1252
|
+
&& !matchingDevices.length
|
|
1253
|
+
&& terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName())) {
|
|
1254
|
+
if (profileDevices.length !== 1)
|
|
1255
|
+
throw new Error('Legacy workspace service has no unique terminal registration. Uninstall it and reconnect with --name or --terminal-id.');
|
|
1256
|
+
name = profileDevices[0].name;
|
|
1257
|
+
matchingDevices = profileDevices;
|
|
1258
|
+
}
|
|
983
1259
|
if (command === 'disconnect') {
|
|
984
|
-
if (!
|
|
985
|
-
|
|
1260
|
+
if (!matchingDevices.length) {
|
|
1261
|
+
if (terminalId)
|
|
1262
|
+
throw new Error('No local terminal registration for --terminal-id in this workspace and profile.');
|
|
1263
|
+
console.log('No local terminal registration for this workspace and name.');
|
|
986
1264
|
return;
|
|
987
1265
|
}
|
|
988
|
-
if (terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName()))
|
|
989
|
-
throw new Error('Uninstall the terminal service before revoking this terminal grant.');
|
|
990
|
-
const selectedDevice = device;
|
|
991
1266
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
1267
|
+
let selectedDevice = selectRegisteredTerminal(matchingDevices, listing.devices, name, terminalId);
|
|
1268
|
+
if (!selectedDevice) {
|
|
1269
|
+
if (matchingDevices.length !== 1)
|
|
1270
|
+
throw new Error(`Multiple removed terminals match ${name} (${matchingDevices.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
|
|
1271
|
+
selectedDevice = matchingDevices[0];
|
|
1272
|
+
}
|
|
1273
|
+
if (terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName(), selectedDevice.agentTerminalId)
|
|
1274
|
+
|| terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName()))
|
|
1275
|
+
throw new Error('Uninstall the selected terminal service before revoking its grant.');
|
|
992
1276
|
if (listing.devices.some(item => item.agentTerminalId === selectedDevice.agentTerminalId))
|
|
993
1277
|
await api(profile, 'POST', `/agents/terminals/${selectedDevice.agentTerminalId}/revoke`);
|
|
994
|
-
|
|
995
|
-
|
|
1278
|
+
await updateStore(current => {
|
|
1279
|
+
current.devices = current.devices.filter(item => item.agentTerminalId !== selectedDevice.agentTerminalId);
|
|
1280
|
+
});
|
|
996
1281
|
console.log('Terminal registration removed.');
|
|
997
1282
|
return;
|
|
998
1283
|
}
|
|
999
1284
|
if (command === 'status') {
|
|
1000
1285
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
1001
|
-
console.log(JSON.stringify({ devices: listing.devices.map(item => ({ agentTerminalId: item.agentTerminalId,
|
|
1286
|
+
console.log(JSON.stringify({ devices: listing.devices.map(item => ({ agentTerminalId: item.agentTerminalId, name: item.name, workspace: item.workspace,
|
|
1287
|
+
status: item.status, mode: item.mode, networkMode: item.networkMode })) }, null, 2));
|
|
1002
1288
|
return;
|
|
1003
1289
|
}
|
|
1004
1290
|
if (command !== 'connect')
|
|
1005
1291
|
throw new Error(`Unknown command: ${command}`);
|
|
1006
1292
|
if (process.platform !== 'darwin' && process.platform !== 'linux')
|
|
1007
1293
|
throw new Error('Runner supports macOS and Linux.');
|
|
1008
|
-
|
|
1294
|
+
let device;
|
|
1295
|
+
if (matchingDevices.length) {
|
|
1009
1296
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1297
|
+
device = selectRegisteredTerminal(matchingDevices, listing.devices, name, terminalId);
|
|
1298
|
+
if (!device) {
|
|
1299
|
+
if (matchingDevices.length > 1)
|
|
1300
|
+
throw new Error(`Multiple removed terminals match ${name} (${matchingDevices.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
|
|
1301
|
+
await updateStore(current => {
|
|
1302
|
+
current.devices = current.devices.filter(item => !matchingDevices.some(stale => stale.agentTerminalId === item.agentTerminalId));
|
|
1303
|
+
});
|
|
1014
1304
|
}
|
|
1015
1305
|
}
|
|
1306
|
+
if (terminalId && !device)
|
|
1307
|
+
throw new Error('No approved or pending local terminal registration matches --terminal-id.');
|
|
1016
1308
|
if (!device) {
|
|
1017
1309
|
const currentUser = me || await api(profile, 'GET', '/me');
|
|
1018
1310
|
const rt = option(argv, 'realtime-url') || profile.realtimeUrl || currentUser.instance?.endpoints?.realtime;
|
|
1019
1311
|
if (!rt)
|
|
1020
1312
|
throw new Error('Realtime endpoint unavailable. Pass --realtime-url.');
|
|
1021
1313
|
const secret = randomBytes(32).toString('hex');
|
|
1022
|
-
device = { agentTerminalId: randomUUID(), secret, workspace, name
|
|
1314
|
+
device = { agentTerminalId: randomUUID(), secret, workspace, name,
|
|
1023
1315
|
baseUrl: profile.baseUrl, instance: profile.instance, realtimeUrl: realtimeUrl(rt) };
|
|
1024
1316
|
await api(profile, 'POST', '/agents/terminals/pair', { agentTerminalId: device.agentTerminalId,
|
|
1025
1317
|
secretHash: createHash('sha256').update(Buffer.from(secret, 'hex')).digest('hex'),
|
|
1026
1318
|
name: device.name, workspace });
|
|
1027
|
-
|
|
1028
|
-
|
|
1319
|
+
try {
|
|
1320
|
+
await updateStore(current => {
|
|
1321
|
+
if (current.devices.some(item => item.agentTerminalId === device.agentTerminalId))
|
|
1322
|
+
throw new Error('Terminal registration ID already exists locally.');
|
|
1323
|
+
current.devices.push(device);
|
|
1324
|
+
});
|
|
1325
|
+
}
|
|
1326
|
+
catch (error) {
|
|
1327
|
+
try {
|
|
1328
|
+
await api(profile, 'POST', `/agents/terminals/${device.agentTerminalId}/revoke`);
|
|
1329
|
+
}
|
|
1330
|
+
catch {
|
|
1331
|
+
throw new Error(`Could not save terminal registration; remove pending grant ${device.agentTerminalId} in AI Agents → Terminals.`);
|
|
1332
|
+
}
|
|
1333
|
+
throw error;
|
|
1334
|
+
}
|
|
1029
1335
|
console.log(`Pending approval in AI Agents → Terminals: ${device.name} (${device.agentTerminalId}).`);
|
|
1030
1336
|
}
|
|
1031
1337
|
for (;;) {
|
|
@@ -1037,5 +1343,11 @@ export async function handleTerminalCommand(argv) {
|
|
|
1037
1343
|
throw new Error('Terminal grant revoked or missing.');
|
|
1038
1344
|
await new Promise(resolve => setTimeout(resolve, 2_000));
|
|
1039
1345
|
}
|
|
1040
|
-
|
|
1346
|
+
const releaseRunnerLock = acquireRunnerLock(device.agentTerminalId);
|
|
1347
|
+
try {
|
|
1348
|
+
await connect(profile, device);
|
|
1349
|
+
}
|
|
1350
|
+
finally {
|
|
1351
|
+
releaseRunnerLock();
|
|
1352
|
+
}
|
|
1041
1353
|
}
|