@revoengine/cli 1.0.13 → 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 +26 -12
- package/dist/src/cli.js +4 -0
- package/dist/src/client.d.ts +5 -11
- package/dist/src/client.js +41 -74
- package/dist/src/commands/component.js +26 -25
- package/dist/src/commands/env.js +1 -5
- package/dist/src/commands/migrate.js +10 -0
- package/dist/src/commands/terminal-browser.d.ts +41 -6
- package/dist/src/commands/terminal-browser.js +503 -20
- package/dist/src/commands/terminal-image.js +59 -1
- package/dist/src/commands/terminal-operational-log.d.ts +18 -0
- package/dist/src/commands/terminal-operational-log.js +119 -0
- package/dist/src/commands/terminal-policy.d.ts +29 -0
- package/dist/src/commands/terminal-policy.js +67 -0
- package/dist/src/commands/terminal-pty.d.ts +4 -0
- package/dist/src/commands/terminal-pty.js +41 -0
- package/dist/src/commands/terminal-reconnect-grace.d.ts +30 -0
- package/dist/src/commands/terminal-reconnect-grace.js +87 -0
- package/dist/src/commands/terminal-sandbox.d.ts +5 -1
- package/dist/src/commands/terminal-sandbox.js +19 -5
- package/dist/src/commands/terminal-secure-browser.d.ts +25 -0
- package/dist/src/commands/terminal-secure-browser.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 +22 -3
- package/dist/src/commands/terminal.js +622 -95
- package/dist/src/config.d.ts +0 -3
- package/dist/src/config.js +0 -2
- package/dist/src/migration.js +10 -11
- package/dist/src/request-queue.d.ts +20 -0
- package/dist/src/request-queue.js +80 -0
- package/dist/src/resource-inventory.js +9 -10
- package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
- package/dist/src/resource-syncs/database-view-sync.js +1 -12
- package/dist/src/resource-syncs/endpoint-sync.js +12 -46
- package/dist/src/types.d.ts +2 -0
- package/package.json +5 -3
|
@@ -4,14 +4,48 @@ import path from 'node:path';
|
|
|
4
4
|
import { fileURLToPath } from 'node:url';
|
|
5
5
|
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
6
6
|
import { spawn } from 'node:child_process';
|
|
7
|
-
import * as pty from 'node-pty';
|
|
8
7
|
import WebSocket from 'ws';
|
|
9
8
|
import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
|
|
10
|
-
import { promptConfirm } from "../prompt.js";
|
|
11
9
|
import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
|
|
12
|
-
import { sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
|
|
13
|
-
import {
|
|
10
|
+
import { createSandboxScratchDirectory, isTerminalSandbox, sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.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";
|
|
14
|
+
import { ensurePtyHelperExecutable, normalizePtyStartError } from "./terminal-pty.js";
|
|
15
|
+
import { TerminalReconnectGrace, TerminalTransportRecovery, isRunnerTransportHeartbeat } from "./terminal-reconnect-grace.js";
|
|
16
|
+
import { TerminalOperationalLog } from "./terminal-operational-log.js";
|
|
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
|
+
}
|
|
15
49
|
export const MAX_TERMINAL_PROCESS_MS = 59 * 60_000;
|
|
16
50
|
const configDir = getConfigDir;
|
|
17
51
|
const runnerConfig = () => path.join(configDir(), 'runner.json');
|
|
@@ -19,6 +53,15 @@ const MAX_MODEL_OUTPUT_BYTES = 100_000;
|
|
|
19
53
|
const MAX_LOCAL_LOG_BYTES = 10_000_000;
|
|
20
54
|
const OUTPUT_FRAME_CHARS = 1_000;
|
|
21
55
|
const LOG_RETENTION_MS = 24 * 60 * 60 * 1_000;
|
|
56
|
+
const OPERATIONAL_ERROR_CODES = new Set([
|
|
57
|
+
'browser_binary_unavailable', 'browser_cancelled', 'browser_failed', 'browser_localhost_only',
|
|
58
|
+
'browser_local_network_guard_unavailable',
|
|
59
|
+
'browser_session_missing', 'browser_session_limit', 'browser_selector_missing', 'browser_selector_ambiguous',
|
|
60
|
+
'browser_secret_input_requires_secure_reference', 'browser_full_page_too_large',
|
|
61
|
+
'browser_element_too_large', 'browser_screenshot_too_large', 'browser_output_outside_workspace',
|
|
62
|
+
'browser_image_upload_unavailable', 'destructive_command_requires_approval',
|
|
63
|
+
'pty_unavailable', 'sandbox_unavailable',
|
|
64
|
+
]);
|
|
22
65
|
const CHILD_ENV_KEYS = ['HOME', 'PATH', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM'];
|
|
23
66
|
export function childEnvironment(source) {
|
|
24
67
|
const safe = {};
|
|
@@ -28,6 +71,10 @@ export function childEnvironment(source) {
|
|
|
28
71
|
return safe;
|
|
29
72
|
}
|
|
30
73
|
function logDirectory() { return path.join(configDir(), 'runner-logs'); }
|
|
74
|
+
function operationalErrorCode(error) {
|
|
75
|
+
const message = error instanceof Error ? error.message : '';
|
|
76
|
+
return OPERATIONAL_ERROR_CODES.has(message) ? message : 'internal_error';
|
|
77
|
+
}
|
|
31
78
|
function pruneLogs(directory) {
|
|
32
79
|
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
33
80
|
for (const name of fs.readdirSync(directory)) {
|
|
@@ -77,6 +124,113 @@ function saveStore(store) {
|
|
|
77
124
|
}
|
|
78
125
|
}
|
|
79
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
|
+
}
|
|
80
234
|
export function resolveWorkspaceDirectory(root, requested) {
|
|
81
235
|
const workspace = fs.realpathSync(root);
|
|
82
236
|
const workdir = fs.realpathSync(requested);
|
|
@@ -111,7 +265,7 @@ function resolveProfile(argv) {
|
|
|
111
265
|
throw new Error('A personal Revo API key is required. Run revo auth login or select a CLI profile.');
|
|
112
266
|
return { baseUrl: configured.baseUrl.replace(/\/$/, ''), token,
|
|
113
267
|
instance: option(argv, 'instance') || (urlOverride || tokenOverride ? undefined : configured.instance),
|
|
114
|
-
realtimeUrl: option(argv, 'realtime-url')
|
|
268
|
+
realtimeUrl: option(argv, 'realtime-url') };
|
|
115
269
|
}
|
|
116
270
|
function apiUrl(profile, route) {
|
|
117
271
|
const base = profile.baseUrl.replace(/\/(?:api\/)?v1\/?$/, '');
|
|
@@ -121,12 +275,6 @@ function apiUrl(profile, route) {
|
|
|
121
275
|
return `${base}/api/v1${route}`;
|
|
122
276
|
}
|
|
123
277
|
async function api(profile, method, route, body) {
|
|
124
|
-
if (profile.production && !profile.productionWriteConfirmed && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
|
|
125
|
-
const confirmed = await promptConfirm(`PRODUCTION: send ${method} ${apiUrl(profile, route)}?`, false);
|
|
126
|
-
if (!confirmed)
|
|
127
|
-
throw new Error('Production write cancelled. Confirm the operation in an interactive terminal.');
|
|
128
|
-
profile.productionWriteConfirmed = true;
|
|
129
|
-
}
|
|
130
278
|
const response = await fetch(apiUrl(profile, route), {
|
|
131
279
|
method,
|
|
132
280
|
redirect: 'manual',
|
|
@@ -158,12 +306,15 @@ function send(socket, frame) {
|
|
|
158
306
|
socket.send(JSON.stringify(frame));
|
|
159
307
|
}
|
|
160
308
|
export function boundResultFrame(frame) {
|
|
161
|
-
const bounded = { ...frame, stdout: String(frame.stdout || ''), stderr: String(frame.stderr || '')
|
|
162
|
-
|
|
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) {
|
|
163
313
|
if (bounded.stdout.length >= bounded.stderr.length)
|
|
164
314
|
bounded.stdout = bounded.stdout.slice(0, Math.floor(bounded.stdout.length * 0.75));
|
|
165
315
|
else
|
|
166
316
|
bounded.stderr = bounded.stderr.slice(0, Math.floor(bounded.stderr.length * 0.75));
|
|
317
|
+
bounded.truncated = true;
|
|
167
318
|
}
|
|
168
319
|
return bounded;
|
|
169
320
|
}
|
|
@@ -173,13 +324,16 @@ function sendResult(socket, frame) {
|
|
|
173
324
|
export async function runCommand(input, onDone, onChunk) {
|
|
174
325
|
const workdir = resolveWorkspaceDirectory(input.workspace, input.workdir);
|
|
175
326
|
const sandbox = input.sandbox || 'workspace';
|
|
327
|
+
if (input.policyDeadlineMs != null && (!Number.isSafeInteger(input.policyDeadlineMs)
|
|
328
|
+
|| input.policyDeadlineMs <= Date.now()))
|
|
329
|
+
throw new Error('terminal_policy_expired');
|
|
176
330
|
if (sandbox !== 'unrestricted' && requiresElevatedCommand(input.cmd))
|
|
177
331
|
throw new Error('destructive_command_requires_approval');
|
|
178
|
-
const scratch = sandbox !== 'unrestricted' ?
|
|
332
|
+
const scratch = sandbox !== 'unrestricted' ? createSandboxScratchDirectory() : undefined;
|
|
179
333
|
const scratchRoot = scratch ? fs.realpathSync(scratch) : undefined;
|
|
180
334
|
let launch;
|
|
181
335
|
try {
|
|
182
|
-
launch = sandboxCommand(input.workspace, workdir, input.cmd, sandbox, process.platform, scratch, [], input.
|
|
336
|
+
launch = sandboxCommand(input.workspace, workdir, input.cmd, sandbox, process.platform, scratch, [], input.networkAccess || 'none');
|
|
183
337
|
}
|
|
184
338
|
catch (error) {
|
|
185
339
|
if (scratch)
|
|
@@ -205,21 +359,25 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
205
359
|
let child;
|
|
206
360
|
let terminal;
|
|
207
361
|
try {
|
|
208
|
-
if (tty)
|
|
362
|
+
if (tty) {
|
|
363
|
+
const pty = await import('node-pty');
|
|
364
|
+
ensurePtyHelperExecutable();
|
|
209
365
|
terminal = pty.spawn(launch.file, launch.args, {
|
|
210
366
|
cwd: workdir, env, name: 'xterm-256color', cols: input.cols || 80, rows: input.rows || 24,
|
|
211
367
|
});
|
|
212
|
-
|
|
368
|
+
}
|
|
369
|
+
else {
|
|
213
370
|
child = spawn(launch.file, launch.args, {
|
|
214
371
|
cwd: workdir, detached: true, stdio: ['pipe', 'pipe', 'pipe'], env,
|
|
215
372
|
});
|
|
373
|
+
}
|
|
216
374
|
}
|
|
217
375
|
catch (error) {
|
|
218
376
|
if (logFd !== undefined)
|
|
219
377
|
fs.closeSync(logFd);
|
|
220
378
|
if (scratch)
|
|
221
379
|
fs.rmSync(scratch, { recursive: true, force: true });
|
|
222
|
-
throw error;
|
|
380
|
+
throw tty ? normalizePtyStartError(error) : error;
|
|
223
381
|
}
|
|
224
382
|
let stdout = '';
|
|
225
383
|
let stderr = '';
|
|
@@ -228,6 +386,7 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
228
386
|
let truncated = false;
|
|
229
387
|
let logTruncated = logFd === undefined;
|
|
230
388
|
let timedOut = false;
|
|
389
|
+
let policyExpired = false;
|
|
231
390
|
let finished = false;
|
|
232
391
|
const pid = child?.pid || terminal?.pid;
|
|
233
392
|
const terminate = () => {
|
|
@@ -258,6 +417,18 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
258
417
|
hardStop.unref?.();
|
|
259
418
|
};
|
|
260
419
|
const timer = setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), MAX_TERMINAL_PROCESS_MS));
|
|
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);
|
|
261
432
|
const append = (chunk, kind) => {
|
|
262
433
|
const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
|
|
263
434
|
if (logPart.length && logFd !== undefined) {
|
|
@@ -306,6 +477,11 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
306
477
|
return;
|
|
307
478
|
finished = true;
|
|
308
479
|
clearTimeout(timer);
|
|
480
|
+
if (policyTimer)
|
|
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');
|
|
309
485
|
if (scratch) {
|
|
310
486
|
try {
|
|
311
487
|
fs.rmSync(scratch, { recursive: true, force: true });
|
|
@@ -320,14 +496,15 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
320
496
|
logTruncated = true;
|
|
321
497
|
}
|
|
322
498
|
}
|
|
323
|
-
onDone({ executed: !error, exitCode: timedOut && exitCode === 0 ? null : exitCode,
|
|
324
|
-
stdout, stderr
|
|
325
|
-
timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath
|
|
499
|
+
onDone({ executed: !error, exitCode: (timedOut || policyExpired) && exitCode === 0 ? null : exitCode,
|
|
500
|
+
stdout, stderr,
|
|
501
|
+
timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath,
|
|
502
|
+
...(policyExpired ? { policyExpired: true } : {}) });
|
|
326
503
|
};
|
|
327
504
|
child?.on('close', code => finish(code));
|
|
328
505
|
child?.on('error', error => finish(null, error));
|
|
329
506
|
terminal?.onExit(({ exitCode }) => finish(exitCode));
|
|
330
|
-
return { pid, terminate,
|
|
507
|
+
return { pid, terminate, updatePolicyDeadline,
|
|
331
508
|
write: chars => { if (terminal)
|
|
332
509
|
terminal.write(chars);
|
|
333
510
|
else
|
|
@@ -343,13 +520,16 @@ export async function runCommand(input, onDone, onChunk) {
|
|
|
343
520
|
export function runWorkspacePatch(input, onDone) {
|
|
344
521
|
if (Buffer.byteLength(input.patch) > 64_000)
|
|
345
522
|
throw new Error('Patch exceeds 64 KB.');
|
|
523
|
+
if (input.policyDeadlineMs != null && (!Number.isSafeInteger(input.policyDeadlineMs)
|
|
524
|
+
|| input.policyDeadlineMs <= Date.now()))
|
|
525
|
+
throw new Error('terminal_policy_expired');
|
|
346
526
|
const workerJs = fileURLToPath(new URL('./terminal-patch-worker.js', import.meta.url));
|
|
347
527
|
const worker = fs.existsSync(workerJs) ? workerJs : fileURLToPath(new URL('./terminal-patch-worker.ts', import.meta.url));
|
|
348
528
|
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'revo-terminal-patch-'));
|
|
349
529
|
let launch;
|
|
350
530
|
try {
|
|
351
531
|
const command = [process.execPath, worker, input.workspace, String(input.allowDelete)].map(shellQuote).join(' ');
|
|
352
|
-
launch = sandboxCommand(input.workspace, input.workspace, command, 'workspace', process.platform, scratch, [path.dirname(worker)]);
|
|
532
|
+
launch = sandboxCommand(input.workspace, input.workspace, command, 'workspace', process.platform, scratch, [path.dirname(worker)], 'none');
|
|
353
533
|
}
|
|
354
534
|
catch (error) {
|
|
355
535
|
fs.rmSync(scratch, { recursive: true, force: true });
|
|
@@ -361,6 +541,7 @@ export function runWorkspacePatch(input, onDone) {
|
|
|
361
541
|
let stderr = '';
|
|
362
542
|
let finished = false;
|
|
363
543
|
let timedOut = false;
|
|
544
|
+
let policyExpired = false;
|
|
364
545
|
const timer = setTimeout(() => {
|
|
365
546
|
timedOut = true;
|
|
366
547
|
if (child.pid)
|
|
@@ -369,6 +550,20 @@ export function runWorkspacePatch(input, onDone) {
|
|
|
369
550
|
}
|
|
370
551
|
catch { /* exited */ }
|
|
371
552
|
}, 60_000);
|
|
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);
|
|
372
567
|
child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8').slice(0, 4_000 - stdout.length); });
|
|
373
568
|
child.stderr?.on('data', (chunk) => { stderr += chunk.toString('utf8').slice(0, 4_000 - stderr.length); });
|
|
374
569
|
child.stdin?.on('error', () => { });
|
|
@@ -378,32 +573,70 @@ export function runWorkspacePatch(input, onDone) {
|
|
|
378
573
|
return;
|
|
379
574
|
finished = true;
|
|
380
575
|
clearTimeout(timer);
|
|
576
|
+
if (policyTimer)
|
|
577
|
+
clearTimeout(policyTimer);
|
|
381
578
|
try {
|
|
382
579
|
fs.rmSync(scratch, { recursive: true, force: true });
|
|
383
580
|
}
|
|
384
581
|
catch { /* temporary cleanup */ }
|
|
385
|
-
onDone({ executed: !error, exitCode: code, stdout,
|
|
386
|
-
stderr: error ?
|
|
582
|
+
onDone({ executed: !error, exitCode: policyExpired ? null : code, stdout,
|
|
583
|
+
stderr: [stderr, error?.message, policyExpired ? 'terminal_policy_expired' : null]
|
|
584
|
+
.filter(Boolean).join('\n'), timedOut });
|
|
387
585
|
};
|
|
388
586
|
child.on('close', code => finish(code));
|
|
389
587
|
child.on('error', error => finish(null, error));
|
|
390
|
-
return child;
|
|
588
|
+
return Object.assign(child, { updatePolicyDeadline });
|
|
391
589
|
}
|
|
392
590
|
async function connect(profile, device) {
|
|
591
|
+
const logDeviceId = /^[A-Za-z0-9_-]{1,128}$/u.test(device.agentTerminalId)
|
|
592
|
+
? device.agentTerminalId : createHash('sha256').update(device.agentTerminalId).digest('hex');
|
|
593
|
+
const operationalLog = new TerminalOperationalLog(path.join(configDir(), 'logs', 'terminal', logDeviceId));
|
|
594
|
+
operationalLog.write('INFO', {}, 'runner.started');
|
|
393
595
|
let backoffMs = 1_000;
|
|
394
596
|
let stopping = false;
|
|
395
597
|
let activeSocket;
|
|
396
598
|
let activeConnectionId = '';
|
|
397
599
|
const activeChildren = new Set();
|
|
398
600
|
const children = new Map();
|
|
601
|
+
const activePolicies = new Map();
|
|
399
602
|
const cancelledExecutions = new Set();
|
|
400
603
|
const outputByExecution = new Map();
|
|
401
604
|
const completed = new Map();
|
|
605
|
+
const traces = new Map();
|
|
606
|
+
const secureRequests = new Map();
|
|
402
607
|
const resumed = new Set();
|
|
403
|
-
|
|
608
|
+
const reconnectGrace = new TerminalReconnectGrace(() => {
|
|
609
|
+
for (const child of children.values())
|
|
610
|
+
child.terminate();
|
|
611
|
+
void closeBrowserSessions();
|
|
612
|
+
});
|
|
613
|
+
let minimumPolicyGrantRevision = 0;
|
|
614
|
+
let policyRevisionUnavailable = false;
|
|
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
|
+
};
|
|
404
635
|
const sendCurrent = (frame) => {
|
|
405
636
|
if (activeConnectionId && activeSocket?.readyState === WebSocket.OPEN)
|
|
406
|
-
send(activeSocket,
|
|
637
|
+
send(activeSocket, frame.type === 'result'
|
|
638
|
+
? boundResultFrame({ ...frame, connectionId: activeConnectionId })
|
|
639
|
+
: { ...frame, connectionId: activeConnectionId });
|
|
407
640
|
};
|
|
408
641
|
const flushExecution = (executionId) => {
|
|
409
642
|
if (!resumed.has(executionId))
|
|
@@ -415,9 +648,10 @@ async function connect(profile, device) {
|
|
|
415
648
|
sendCurrent({ type: 'result', executionId, ...result });
|
|
416
649
|
};
|
|
417
650
|
const stop = () => {
|
|
651
|
+
operationalLog.write('INFO', {}, 'runner.stopping', { activeExecutions: children.size });
|
|
418
652
|
stopping = true;
|
|
419
|
-
|
|
420
|
-
|
|
653
|
+
void closeBrowserSessions();
|
|
654
|
+
reconnectGrace.clear();
|
|
421
655
|
if (activeSocket?.readyState === WebSocket.CONNECTING)
|
|
422
656
|
activeSocket.terminate();
|
|
423
657
|
else
|
|
@@ -431,10 +665,12 @@ async function connect(profile, device) {
|
|
|
431
665
|
while (!stopping) {
|
|
432
666
|
try {
|
|
433
667
|
await new Promise((resolve, reject) => {
|
|
668
|
+
const secureIdentity = createSecureBrowserIdentity();
|
|
434
669
|
const socket = new WebSocket(device.realtimeUrl, {
|
|
435
670
|
headers: { Authorization: `Bearer ${profile.token}`,
|
|
436
671
|
...(profile.instance ? { instance: profile.instance } : {}) },
|
|
437
672
|
perMessageDeflate: false,
|
|
673
|
+
handshakeTimeout: 10_000,
|
|
438
674
|
});
|
|
439
675
|
activeSocket = socket;
|
|
440
676
|
let connectionId = '';
|
|
@@ -442,27 +678,60 @@ async function connect(profile, device) {
|
|
|
442
678
|
let heartbeat;
|
|
443
679
|
let lastHeartbeat = Date.now();
|
|
444
680
|
let incoming = Promise.resolve();
|
|
681
|
+
const recovery = new TerminalTransportRecovery(() => socket.terminate(), () => {
|
|
682
|
+
backoffMs = 1_000;
|
|
683
|
+
reconnectGrace.clear();
|
|
684
|
+
});
|
|
445
685
|
socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
|
|
446
686
|
secret: device.secret, capabilities: ['workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
|
|
447
|
-
'
|
|
448
|
-
|
|
687
|
+
'terminal_policy_v2', 'terminal_policy_selective_v1',
|
|
688
|
+
'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
|
|
689
|
+
'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'save_image_v1',
|
|
690
|
+
...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])],
|
|
691
|
+
secureBrowserPublicKey: secureIdentity.publicKey, secureBrowserKeyId: secureIdentity.keyId }));
|
|
449
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
|
+
}
|
|
450
706
|
incoming = incoming.then(async () => {
|
|
451
707
|
if (stopping || socket.readyState !== WebSocket.OPEN)
|
|
452
708
|
return;
|
|
453
|
-
const frame = JSON.parse(raw.toString());
|
|
454
709
|
if (frame.type === 'ready' && frame.connectionId) {
|
|
710
|
+
if (connectionId) {
|
|
711
|
+
socket.terminate();
|
|
712
|
+
return;
|
|
713
|
+
}
|
|
714
|
+
lastHeartbeat = Date.now();
|
|
715
|
+
securePolicyEpoch++;
|
|
455
716
|
connectionId = frame.connectionId;
|
|
456
717
|
activeConnectionId = connectionId;
|
|
457
718
|
workspace = frame.workspace || device.workspace;
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
reconnectGrace = undefined;
|
|
719
|
+
if (Number.isSafeInteger(frame.policyGrantRevision) && frame.policyGrantRevision >= 0) {
|
|
720
|
+
minimumPolicyGrantRevision = Math.max(minimumPolicyGrantRevision, frame.policyGrantRevision);
|
|
721
|
+
policyRevisionUnavailable = false;
|
|
462
722
|
}
|
|
723
|
+
else
|
|
724
|
+
policyRevisionUnavailable = true;
|
|
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 });
|
|
463
728
|
console.log(`Connected ${device.name} (${device.agentTerminalId}).`);
|
|
464
|
-
|
|
729
|
+
operationalLog.write('INFO', {}, 'socket.ready', { resumedExecutions: children.size + completed.size });
|
|
730
|
+
const pendingResumes = new Set([...children.keys(), ...completed.keys()]);
|
|
731
|
+
recovery.ready(pendingResumes);
|
|
732
|
+
for (const executionId of pendingResumes) {
|
|
465
733
|
send(socket, { type: 'resume', connectionId, executionId });
|
|
734
|
+
}
|
|
466
735
|
heartbeat = setInterval(() => {
|
|
467
736
|
if (Date.now() - lastHeartbeat > 45_000) {
|
|
468
737
|
socket.terminate();
|
|
@@ -472,28 +741,108 @@ async function connect(profile, device) {
|
|
|
472
741
|
}, 15_000);
|
|
473
742
|
return;
|
|
474
743
|
}
|
|
475
|
-
if (frame.type === 'heartbeat')
|
|
476
|
-
|
|
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 });
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
if (frame.type === 'policy_revoked') {
|
|
763
|
+
if (frame.connectionId !== connectionId)
|
|
764
|
+
return;
|
|
765
|
+
securePolicyEpoch++;
|
|
766
|
+
if (Number.isSafeInteger(frame.policyGrantRevision) && frame.policyGrantRevision >= 0)
|
|
767
|
+
minimumPolicyGrantRevision = Math.max(minimumPolicyGrantRevision, frame.policyGrantRevision);
|
|
768
|
+
else
|
|
769
|
+
policyRevisionUnavailable = true;
|
|
770
|
+
operationalLog.write('WARN', {}, 'terminal.policy_revoked', { activeExecutions: children.size });
|
|
771
|
+
for (const [executionId, child] of children) {
|
|
772
|
+
cancelledExecutions.add(executionId);
|
|
773
|
+
child.terminate();
|
|
774
|
+
}
|
|
775
|
+
await closeBrowserSessions();
|
|
776
|
+
return;
|
|
777
|
+
}
|
|
778
|
+
if (frame.type === 'secure_browser_input') {
|
|
779
|
+
if (frame.connectionId !== connectionId || frame.agentTerminalId !== device.agentTerminalId
|
|
780
|
+
|| typeof frame.requestId !== 'string' || !/^[a-f0-9-]{36}$/iu.test(frame.requestId))
|
|
781
|
+
return;
|
|
782
|
+
const secureRequestId = frame.requestId;
|
|
783
|
+
const requestEpoch = securePolicyEpoch;
|
|
784
|
+
const trace = { assistantThreadId: frame.threadId };
|
|
785
|
+
const errorCodes = new Set(['secure_input_invalid', 'secure_input_session_missing',
|
|
786
|
+
'secure_input_origin_changed', 'secure_input_selector_missing',
|
|
787
|
+
'secure_input_not_secret_control', 'secure_input_fill_failed']);
|
|
788
|
+
void (async () => {
|
|
789
|
+
try {
|
|
790
|
+
const now = Date.now();
|
|
791
|
+
for (const [requestId, seenAt] of secureRequests)
|
|
792
|
+
if (now - seenAt > 5 * 60_000)
|
|
793
|
+
secureRequests.delete(requestId);
|
|
794
|
+
if (secureRequests.has(secureRequestId))
|
|
795
|
+
throw new Error('secure_input_replayed');
|
|
796
|
+
secureRequests.set(secureRequestId, now);
|
|
797
|
+
if (secureRequests.size > 512)
|
|
798
|
+
secureRequests.delete(secureRequests.keys().next().value);
|
|
799
|
+
const envelope = frame;
|
|
800
|
+
const value = decryptSecureBrowserInput(envelope, secureIdentity);
|
|
801
|
+
await fillBrowserSecret({ browserSessionId: envelope.browserSessionId,
|
|
802
|
+
origin: envelope.origin, selector: envelope.selector,
|
|
803
|
+
expiresAt: envelope.expiresAt, value,
|
|
804
|
+
isAuthorized: () => requestEpoch === securePolicyEpoch && !stopping
|
|
805
|
+
&& socket.readyState === WebSocket.OPEN && activeConnectionId === connectionId });
|
|
806
|
+
if (requestEpoch !== securePolicyEpoch || socket.readyState !== WebSocket.OPEN)
|
|
807
|
+
throw new Error('secure_input_session_missing');
|
|
808
|
+
operationalLog.write('INFO', trace, 'browser.secure_fill_completed');
|
|
809
|
+
send(socket, { type: 'secure_browser_input_result', connectionId,
|
|
810
|
+
requestId: secureRequestId, status: 'filled' });
|
|
811
|
+
}
|
|
812
|
+
catch (error) {
|
|
813
|
+
const errorCode = error instanceof Error && errorCodes.has(error.message)
|
|
814
|
+
? error.message : 'secure_input_failed';
|
|
815
|
+
operationalLog.write('WARN', trace, 'browser.secure_fill_failed', { errorCode });
|
|
816
|
+
send(socket, { type: 'secure_browser_input_result', connectionId,
|
|
817
|
+
requestId: secureRequestId, status: 'error', errorCode });
|
|
818
|
+
}
|
|
819
|
+
})();
|
|
477
820
|
return;
|
|
478
821
|
}
|
|
479
822
|
if (frame.connectionId !== connectionId || !frame.executionId)
|
|
480
823
|
return;
|
|
481
824
|
if (frame.type === 'resumed') {
|
|
825
|
+
recovery.accepted(frame.executionId);
|
|
482
826
|
resumed.add(frame.executionId);
|
|
483
827
|
flushExecution(frame.executionId);
|
|
484
828
|
return;
|
|
485
829
|
}
|
|
486
830
|
if (frame.type === 'result_ack' || frame.type === 'resume_rejected') {
|
|
487
|
-
|
|
831
|
+
recovery.accepted(frame.executionId);
|
|
832
|
+
if (frame.type === 'resume_rejected') {
|
|
833
|
+
operationalLog.write('WARN', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.resume_rejected');
|
|
488
834
|
children.get(frame.executionId)?.terminate();
|
|
835
|
+
}
|
|
489
836
|
completed.delete(frame.executionId);
|
|
490
837
|
outputByExecution.delete(frame.executionId);
|
|
491
838
|
resumed.delete(frame.executionId);
|
|
839
|
+
traces.delete(frame.executionId);
|
|
492
840
|
return;
|
|
493
841
|
}
|
|
494
842
|
if (frame.type === 'cancel') {
|
|
495
843
|
const child = children.get(frame.executionId);
|
|
496
844
|
if (child) {
|
|
845
|
+
operationalLog.write('WARN', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.cancel_requested');
|
|
497
846
|
cancelledExecutions.add(frame.executionId);
|
|
498
847
|
child.terminate();
|
|
499
848
|
}
|
|
@@ -503,6 +852,7 @@ async function connect(profile, device) {
|
|
|
503
852
|
const child = children.get(frame.executionId);
|
|
504
853
|
if (child && typeof frame.chars === 'string' && Buffer.byteLength(frame.chars) <= 8_192
|
|
505
854
|
&& typeof frame.closeStdin === 'boolean') {
|
|
855
|
+
operationalLog.write('DEBUG', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.stdin', { bytes: Buffer.byteLength(frame.chars), close: frame.closeStdin });
|
|
506
856
|
if (frame.closeStdin)
|
|
507
857
|
child.closeStdin(frame.chars);
|
|
508
858
|
else if (frame.chars)
|
|
@@ -519,50 +869,101 @@ async function connect(profile, device) {
|
|
|
519
869
|
}
|
|
520
870
|
if (frame.type !== 'execute')
|
|
521
871
|
return;
|
|
872
|
+
if (policyRevisionUnavailable || !Number.isSafeInteger(frame.policyGrantRevision)
|
|
873
|
+
|| frame.policyGrantRevision < minimumPolicyGrantRevision) {
|
|
874
|
+
sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
|
|
875
|
+
executed: false, exitCode: null, stdout: '', stderr: 'terminal_permission_changed', timedOut: false });
|
|
876
|
+
return;
|
|
877
|
+
}
|
|
522
878
|
if (children.has(frame.executionId) || completed.has(frame.executionId)) {
|
|
879
|
+
operationalLog.write('DEBUG', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.duplicate');
|
|
523
880
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
524
881
|
return;
|
|
525
882
|
}
|
|
526
883
|
const operation = frame.operation || 'shell';
|
|
884
|
+
const trace = { assistantThreadId: frame.assistantThreadId,
|
|
885
|
+
assistantMessageId: frame.assistantMessageId, executionId: frame.executionId };
|
|
886
|
+
let validBrowserPayload = false;
|
|
887
|
+
if (operation === 'browser' && typeof frame.url === 'string' && frame.url.length <= 2_048
|
|
888
|
+
&& typeof frame.browserSessionId === 'string' && frame.browserAction) {
|
|
889
|
+
try {
|
|
890
|
+
validateBrowserActionInput({ url: frame.url, action: frame.browserAction,
|
|
891
|
+
workspace, browserSessionId: frame.browserSessionId, selector: frame.selector,
|
|
892
|
+
width: frame.width, height: frame.height, value: frame.value, checked: frame.checked,
|
|
893
|
+
key: frame.key, deltaY: frame.deltaY, state: frame.state,
|
|
894
|
+
waitTimeoutMs: frame.waitTimeoutMs, capture: frame.capture, clip: frame.clip,
|
|
895
|
+
localOnly: frame.browserLocalOnly === true });
|
|
896
|
+
validBrowserPayload = true;
|
|
897
|
+
}
|
|
898
|
+
catch { /* invalid_command result below */ }
|
|
899
|
+
}
|
|
527
900
|
const validPayload = operation === 'apply_patch'
|
|
528
901
|
? typeof frame.patch === 'string' && Buffer.byteLength(frame.patch) <= 64_000
|
|
529
|
-
: operation === 'browser' ?
|
|
530
|
-
&& ['navigate', 'dom', 'screenshot'].includes(frame.browserAction || '')
|
|
902
|
+
: operation === 'browser' ? validBrowserPayload
|
|
531
903
|
: operation === 'save_image' ? Array.isArray(frame.files) && frame.files.length > 0 && frame.files.length <= 32
|
|
532
904
|
: operation === 'shell' && typeof frame.cmd === 'string' && !!frame.cmd.trim() && frame.cmd.length <= 8_192;
|
|
533
|
-
if (!validPayload || children.size >= 4 || !
|
|
534
|
-
|| frame.networkAllowed === false && frame.sandbox === 'workspace-network'
|
|
905
|
+
if (!validPayload || children.size >= 4 || !isTerminalSandbox(frame.sandbox)
|
|
535
906
|
|| operation === 'apply_patch' && frame.sandbox === 'workspace-network'
|
|
536
|
-
|| (operation === 'browser' || operation === 'save_image') &&
|
|
537
|
-
|| frame.networkAllowed === false)
|
|
907
|
+
|| (operation === 'browser' || operation === 'save_image') && frame.sandbox !== 'workspace-network'
|
|
538
908
|
|| frame.tty === true && (operation !== 'shell' || !Number.isInteger(frame.cols) || !Number.isInteger(frame.rows)
|
|
539
909
|
|| frame.cols < 20 || frame.cols > 240 || frame.rows < 10 || frame.rows > 100)) {
|
|
910
|
+
operationalLog.write('WARN', trace, 'execution.rejected', { operation,
|
|
911
|
+
reason: children.size >= 4 ? 'runner_busy' : 'invalid_command' });
|
|
540
912
|
sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
|
|
541
913
|
executed: false, exitCode: null, stdout: '', stderr: children.size >= 4 ? 'runner_busy' : 'invalid_command', timedOut: false });
|
|
542
914
|
return;
|
|
543
915
|
}
|
|
916
|
+
const policyError = validateExecutePolicy({ ...frame, operation });
|
|
917
|
+
if (policyError) {
|
|
918
|
+
operationalLog.write('WARN', trace, 'execution.rejected', { operation, reason: policyError });
|
|
919
|
+
sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
|
|
920
|
+
executed: false, exitCode: null, stdout: '', stderr: policyError, timedOut: false });
|
|
921
|
+
return;
|
|
922
|
+
}
|
|
544
923
|
try {
|
|
924
|
+
activePolicies.set(frame.executionId, frame);
|
|
925
|
+
traces.set(frame.executionId, trace);
|
|
926
|
+
operationalLog.write('INFO', trace, 'execution.started', { operation, sandbox: frame.sandbox });
|
|
545
927
|
resumed.add(frame.executionId);
|
|
546
928
|
outputByExecution.set(frame.executionId, []);
|
|
547
929
|
if (operation === 'save_image') {
|
|
548
930
|
const controller = new AbortController();
|
|
931
|
+
const policyDeadline = executionPolicyDeadline(frame);
|
|
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);
|
|
549
940
|
const child = { pid: undefined, write: () => undefined,
|
|
550
941
|
closeStdin: () => undefined, resize: () => undefined,
|
|
551
|
-
terminate: () => controller.abort()
|
|
942
|
+
terminate: () => controller.abort(),
|
|
943
|
+
updatePolicyDeadline };
|
|
552
944
|
children.set(frame.executionId, child);
|
|
553
945
|
activeChildren.add(child);
|
|
554
946
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
555
947
|
void uploadWorkspaceImages(workspace, frame.files, controller.signal).then(count => {
|
|
948
|
+
if (policyTimer)
|
|
949
|
+
clearTimeout(policyTimer);
|
|
556
950
|
children.delete(frame.executionId);
|
|
951
|
+
activePolicies.delete(frame.executionId);
|
|
557
952
|
activeChildren.delete(child);
|
|
558
953
|
completed.set(frame.executionId, { executed: true, exitCode: 0, stdout: `Uploaded ${count} image(s).`, stderr: '' });
|
|
954
|
+
operationalLog.write('INFO', trace, 'execution.completed', { operation, exitCode: 0, images: count });
|
|
559
955
|
if (resumed.has(frame.executionId))
|
|
560
956
|
flushExecution(frame.executionId);
|
|
561
957
|
}).catch(error => {
|
|
958
|
+
if (policyTimer)
|
|
959
|
+
clearTimeout(policyTimer);
|
|
562
960
|
children.delete(frame.executionId);
|
|
961
|
+
activePolicies.delete(frame.executionId);
|
|
563
962
|
activeChildren.delete(child);
|
|
564
963
|
completed.set(frame.executionId, { executed: false, exitCode: null, stdout: '',
|
|
565
964
|
stderr: error instanceof Error ? error.message : 'image_upload_failed' });
|
|
965
|
+
operationalLog.write('ERROR', trace, 'execution.failed', { operation,
|
|
966
|
+
errorCode: 'image_upload_failed' });
|
|
566
967
|
if (resumed.has(frame.executionId))
|
|
567
968
|
flushExecution(frame.executionId);
|
|
568
969
|
});
|
|
@@ -570,34 +971,67 @@ async function connect(profile, device) {
|
|
|
570
971
|
}
|
|
571
972
|
if (operation === 'browser') {
|
|
572
973
|
const controller = new AbortController();
|
|
974
|
+
const policyDeadline = executionPolicyDeadline(frame);
|
|
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);
|
|
983
|
+
let actionAttempted = false;
|
|
573
984
|
const child = { pid: undefined, write: () => undefined,
|
|
574
985
|
closeStdin: () => undefined, resize: () => undefined,
|
|
575
|
-
terminate: () => controller.abort()
|
|
986
|
+
terminate: () => controller.abort(),
|
|
987
|
+
updatePolicyDeadline };
|
|
576
988
|
children.set(frame.executionId, child);
|
|
577
989
|
activeChildren.add(child);
|
|
578
990
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
579
991
|
void runBrowserAction({ url: frame.url, action: frame.browserAction, workspace,
|
|
992
|
+
browserSessionId: frame.browserSessionId, onActionAttempt: () => { actionAttempted = true; },
|
|
580
993
|
selector: frame.selector, width: frame.width, height: frame.height,
|
|
581
|
-
|
|
994
|
+
value: frame.value, checked: frame.checked, key: frame.key, deltaY: frame.deltaY,
|
|
995
|
+
state: frame.state, waitTimeoutMs: frame.waitTimeoutMs,
|
|
996
|
+
capture: frame.capture, clip: frame.clip,
|
|
997
|
+
localOnly: frame.browserLocalOnly === true,
|
|
998
|
+
networkAccessExpiresAt: frame.networkAccessExpiresAt,
|
|
999
|
+
networkAccessOnce: frame.networkAccessOnce,
|
|
1000
|
+
signal: controller.signal })
|
|
582
1001
|
.then(async (browserResult) => {
|
|
583
1002
|
if (frame.browserAction === 'screenshot') {
|
|
584
1003
|
if (!browserResult.screenshotPath || frame.files?.length !== 1)
|
|
585
1004
|
throw new Error('browser_image_upload_unavailable');
|
|
586
1005
|
await uploadWorkspaceImages(workspace, [{ ...frame.files[0], path: browserResult.screenshotPath }], controller.signal);
|
|
587
1006
|
}
|
|
1007
|
+
if (policyTimer)
|
|
1008
|
+
clearTimeout(policyTimer);
|
|
588
1009
|
children.delete(frame.executionId);
|
|
1010
|
+
activePolicies.delete(frame.executionId);
|
|
589
1011
|
activeChildren.delete(child);
|
|
590
1012
|
completed.set(frame.executionId, { executed: true, exitCode: 0,
|
|
591
1013
|
stdout: browserResult.dom, stderr: '', screenshotPath: browserResult.screenshotPath || null,
|
|
1014
|
+
pageUrl: browserResult.pageUrl,
|
|
592
1015
|
cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
1016
|
+
operationalLog.write('INFO', trace, 'execution.completed', { operation,
|
|
1017
|
+
browserAction: frame.browserAction, exitCode: 0, screenshot: frame.browserAction === 'screenshot' });
|
|
593
1018
|
if (resumed.has(frame.executionId))
|
|
594
1019
|
flushExecution(frame.executionId);
|
|
595
1020
|
}).catch(error => {
|
|
1021
|
+
if (policyTimer)
|
|
1022
|
+
clearTimeout(policyTimer);
|
|
596
1023
|
children.delete(frame.executionId);
|
|
1024
|
+
activePolicies.delete(frame.executionId);
|
|
597
1025
|
activeChildren.delete(child);
|
|
598
|
-
|
|
599
|
-
|
|
1026
|
+
const code = error instanceof Error && /^[a-z][a-z_]+$/u.test(error.message)
|
|
1027
|
+
? error.message : 'browser_failed';
|
|
1028
|
+
completed.set(frame.executionId, { executed: actionAttempted, exitCode: null, stdout: '',
|
|
1029
|
+
stderr: actionAttempted ? 'browser_action_outcome_unknown' : code,
|
|
600
1030
|
cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
1031
|
+
operationalLog.write('ERROR', trace, 'execution.failed', { operation,
|
|
1032
|
+
browserAction: frame.browserAction,
|
|
1033
|
+
errorCode: actionAttempted ? 'browser_action_outcome_unknown' : operationalErrorCode(error),
|
|
1034
|
+
executed: actionAttempted });
|
|
601
1035
|
if (resumed.has(frame.executionId))
|
|
602
1036
|
flushExecution(frame.executionId);
|
|
603
1037
|
});
|
|
@@ -605,10 +1039,13 @@ async function connect(profile, device) {
|
|
|
605
1039
|
}
|
|
606
1040
|
if (operation === 'apply_patch') {
|
|
607
1041
|
const patchChild = runWorkspacePatch({ patch: frame.patch, workspace,
|
|
608
|
-
allowDelete:
|
|
1042
|
+
allowDelete: frame.sandbox === 'unrestricted',
|
|
1043
|
+
policyDeadlineMs: executionPolicyDeadline(frame) }, result => {
|
|
609
1044
|
children.delete(frame.executionId);
|
|
1045
|
+
activePolicies.delete(frame.executionId);
|
|
610
1046
|
activeChildren.delete(child);
|
|
611
1047
|
completed.set(frame.executionId, { ...result, cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
1048
|
+
operationalLog.write(result.exitCode === 0 ? 'INFO' : 'ERROR', trace, result.exitCode === 0 ? 'execution.completed' : 'execution.failed', { operation, exitCode: result.exitCode ?? 'none', executed: result.executed });
|
|
612
1049
|
if (resumed.has(frame.executionId))
|
|
613
1050
|
flushExecution(frame.executionId);
|
|
614
1051
|
});
|
|
@@ -621,6 +1058,7 @@ async function connect(profile, device) {
|
|
|
621
1058
|
process.kill(-patchChild.pid, 'SIGTERM');
|
|
622
1059
|
}
|
|
623
1060
|
catch { /* exited */ } },
|
|
1061
|
+
updatePolicyDeadline: deadline => patchChild.updatePolicyDeadline(deadline),
|
|
624
1062
|
};
|
|
625
1063
|
children.set(frame.executionId, child);
|
|
626
1064
|
activeChildren.add(child);
|
|
@@ -628,15 +1066,19 @@ async function connect(profile, device) {
|
|
|
628
1066
|
return;
|
|
629
1067
|
}
|
|
630
1068
|
const child = await runCommand({ cmd: frame.cmd, workdir: frame.workdir || workspace,
|
|
631
|
-
workspace, sandbox: frame.sandbox
|
|
1069
|
+
workspace, sandbox: frame.sandbox, networkAccess: frame.networkAccess,
|
|
1070
|
+
policyDeadlineMs: executionPolicyDeadline(frame),
|
|
632
1071
|
timeoutMs: frame.timeoutMs || 60_000, tty: frame.tty,
|
|
633
1072
|
cols: frame.cols, rows: frame.rows,
|
|
634
1073
|
executionId: frame.executionId }, result => {
|
|
635
1074
|
children.delete(frame.executionId);
|
|
1075
|
+
activePolicies.delete(frame.executionId);
|
|
636
1076
|
activeChildren.delete(child);
|
|
637
1077
|
const { stdout, stderr, ...completion } = result;
|
|
638
1078
|
completed.set(frame.executionId, { ...completion,
|
|
639
1079
|
cancelled: cancelledExecutions.delete(frame.executionId), stdout: '', stderr: '' });
|
|
1080
|
+
operationalLog.write(completion.exitCode === 0 ? 'INFO' : 'ERROR', trace, completion.exitCode === 0 ? 'execution.completed' : 'execution.failed', { operation, exitCode: completion.exitCode ?? 'none', executed: completion.executed,
|
|
1081
|
+
timedOut: completion.timedOut, truncated: completion.truncated });
|
|
640
1082
|
if (resumed.has(frame.executionId))
|
|
641
1083
|
sendCurrent({ type: 'result', executionId: frame.executionId,
|
|
642
1084
|
...completed.get(frame.executionId) });
|
|
@@ -653,30 +1095,34 @@ async function connect(profile, device) {
|
|
|
653
1095
|
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
654
1096
|
}
|
|
655
1097
|
catch (error) {
|
|
1098
|
+
activePolicies.delete(frame.executionId);
|
|
656
1099
|
resumed.delete(frame.executionId);
|
|
657
1100
|
outputByExecution.delete(frame.executionId);
|
|
1101
|
+
traces.delete(frame.executionId);
|
|
1102
|
+
operationalLog.write('ERROR', trace, 'execution.rejected', { operation,
|
|
1103
|
+
errorCode: operationalErrorCode(error) });
|
|
658
1104
|
sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
|
|
659
1105
|
executed: false, exitCode: null, stdout: '', stderr: error instanceof Error ? error.message : 'Command rejected.', timedOut: false });
|
|
660
1106
|
}
|
|
661
1107
|
}).catch(() => socket.terminate());
|
|
662
1108
|
});
|
|
663
1109
|
socket.on('close', (code, reason) => {
|
|
1110
|
+
securePolicyEpoch++;
|
|
1111
|
+
operationalLog.write(code === 1000 ? 'INFO' : 'WARN', {}, 'socket.closed', { code, activeExecutions: children.size, policyViolation: code === 1008 });
|
|
664
1112
|
if (heartbeat)
|
|
665
1113
|
clearInterval(heartbeat);
|
|
1114
|
+
recovery.close();
|
|
666
1115
|
if (activeSocket === socket)
|
|
667
1116
|
activeConnectionId = '';
|
|
668
1117
|
resumed.clear();
|
|
669
1118
|
if (code === 1008 && reason.toString() !== 'heartbeat_timeout') {
|
|
1119
|
+
reconnectGrace.clear();
|
|
670
1120
|
for (const child of children.values())
|
|
671
1121
|
child.terminate();
|
|
1122
|
+
void closeBrowserSessions();
|
|
672
1123
|
}
|
|
673
|
-
else if (!stopping
|
|
674
|
-
reconnectGrace
|
|
675
|
-
for (const child of children.values())
|
|
676
|
-
child.terminate();
|
|
677
|
-
}, 120_000);
|
|
678
|
-
reconnectGrace.unref?.();
|
|
679
|
-
}
|
|
1124
|
+
else if (!stopping)
|
|
1125
|
+
reconnectGrace.start(children.size > 0 || hasBrowserSessions());
|
|
680
1126
|
if (activeSocket === socket)
|
|
681
1127
|
activeSocket = undefined;
|
|
682
1128
|
if (code === 1008 && reason.toString() !== 'heartbeat_timeout')
|
|
@@ -684,16 +1130,21 @@ async function connect(profile, device) {
|
|
|
684
1130
|
else
|
|
685
1131
|
resolve();
|
|
686
1132
|
});
|
|
687
|
-
socket.on('error',
|
|
1133
|
+
socket.on('error', () => {
|
|
1134
|
+
operationalLog.write('WARN', {}, 'socket.error');
|
|
1135
|
+
console.error('Realtime connection failed; terminal will retry.');
|
|
1136
|
+
});
|
|
688
1137
|
});
|
|
689
1138
|
}
|
|
690
1139
|
catch (error) {
|
|
691
1140
|
if (error instanceof Error && error.message.startsWith('Runner rejected by Realtime:'))
|
|
692
1141
|
throw error;
|
|
693
|
-
|
|
1142
|
+
operationalLog.write('WARN', {}, 'runner.connect_failed', { errorCode: operationalErrorCode(error) });
|
|
1143
|
+
console.error('Terminal connection failed; retrying.');
|
|
694
1144
|
}
|
|
695
1145
|
if (stopping)
|
|
696
1146
|
break;
|
|
1147
|
+
operationalLog.write('INFO', {}, 'runner.reconnect_wait', { milliseconds: backoffMs });
|
|
697
1148
|
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
|
698
1149
|
backoffMs = Math.min(backoffMs * 2, 30_000);
|
|
699
1150
|
}
|
|
@@ -707,13 +1158,13 @@ async function connect(profile, device) {
|
|
|
707
1158
|
export async function handleTerminalCommand(argv) {
|
|
708
1159
|
const command = argv[0] || 'help';
|
|
709
1160
|
if (command === 'help' || argv.includes('--help')) {
|
|
710
|
-
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]');
|
|
711
1162
|
return;
|
|
712
1163
|
}
|
|
713
1164
|
if (command === 'service') {
|
|
714
1165
|
const action = argv[1];
|
|
715
1166
|
if (!action || action === 'help') {
|
|
716
|
-
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]');
|
|
717
1168
|
return;
|
|
718
1169
|
}
|
|
719
1170
|
if (action !== 'install' && action !== 'uninstall')
|
|
@@ -723,8 +1174,22 @@ export async function handleTerminalCommand(argv) {
|
|
|
723
1174
|
throw new Error('Terminal service requires --workspace PATH.');
|
|
724
1175
|
const workspace = fs.existsSync(requestedWorkspace) ? fs.realpathSync(requestedWorkspace) : path.resolve(requestedWorkspace);
|
|
725
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);
|
|
726
1183
|
if (action === 'uninstall') {
|
|
727
|
-
|
|
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 });
|
|
728
1193
|
console.log(result.removed ? `Terminal service stopped and removed (${result.label}). Grant remains active.`
|
|
729
1194
|
: `No terminal service installed for this workspace (${result.label}).`);
|
|
730
1195
|
return;
|
|
@@ -734,20 +1199,33 @@ export async function handleTerminalCommand(argv) {
|
|
|
734
1199
|
for (const unsupported of ['token', 'url', 'instance', 'realtime-url'])
|
|
735
1200
|
if (option(argv, unsupported))
|
|
736
1201
|
throw new Error(`Service install cannot use --${unsupported}; use a saved CLI login/profile.`);
|
|
737
|
-
const saved = envName === 'default' ? loadStoredConfig({ allowLegacy: false }) : getEnvironmentProfile(envName);
|
|
738
1202
|
if (!saved?.token?.startsWith('sk-'))
|
|
739
1203
|
throw new Error('A saved personal Revo API key is required. Run revo auth login or select a saved --project profile.');
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
const device = devices[0];
|
|
746
|
-
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 };
|
|
747
1209
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
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,
|
|
751
1229
|
configHome: process.env.XDG_CONFIG_HOME });
|
|
752
1230
|
console.log(result.installed ? `Terminal service installed and started (${result.label}).`
|
|
753
1231
|
: `Terminal service already installed (${result.label}).`);
|
|
@@ -764,53 +1242,96 @@ export async function handleTerminalCommand(argv) {
|
|
|
764
1242
|
}
|
|
765
1243
|
const workspace = fs.realpathSync(option(argv, 'workspace') || process.cwd());
|
|
766
1244
|
const store = readStore();
|
|
767
|
-
|
|
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
|
+
}
|
|
768
1259
|
if (command === 'disconnect') {
|
|
769
|
-
if (!
|
|
770
|
-
|
|
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.');
|
|
771
1264
|
return;
|
|
772
1265
|
}
|
|
773
|
-
if (terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName()))
|
|
774
|
-
throw new Error('Uninstall the terminal service before revoking this terminal grant.');
|
|
775
|
-
const selectedDevice = device;
|
|
776
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.');
|
|
777
1276
|
if (listing.devices.some(item => item.agentTerminalId === selectedDevice.agentTerminalId))
|
|
778
1277
|
await api(profile, 'POST', `/agents/terminals/${selectedDevice.agentTerminalId}/revoke`);
|
|
779
|
-
|
|
780
|
-
|
|
1278
|
+
await updateStore(current => {
|
|
1279
|
+
current.devices = current.devices.filter(item => item.agentTerminalId !== selectedDevice.agentTerminalId);
|
|
1280
|
+
});
|
|
781
1281
|
console.log('Terminal registration removed.');
|
|
782
1282
|
return;
|
|
783
1283
|
}
|
|
784
1284
|
if (command === 'status') {
|
|
785
1285
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
786
|
-
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));
|
|
787
1288
|
return;
|
|
788
1289
|
}
|
|
789
1290
|
if (command !== 'connect')
|
|
790
1291
|
throw new Error(`Unknown command: ${command}`);
|
|
791
1292
|
if (process.platform !== 'darwin' && process.platform !== 'linux')
|
|
792
1293
|
throw new Error('Runner supports macOS and Linux.');
|
|
793
|
-
|
|
1294
|
+
let device;
|
|
1295
|
+
if (matchingDevices.length) {
|
|
794
1296
|
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
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
|
+
});
|
|
799
1304
|
}
|
|
800
1305
|
}
|
|
1306
|
+
if (terminalId && !device)
|
|
1307
|
+
throw new Error('No approved or pending local terminal registration matches --terminal-id.');
|
|
801
1308
|
if (!device) {
|
|
802
1309
|
const currentUser = me || await api(profile, 'GET', '/me');
|
|
803
1310
|
const rt = option(argv, 'realtime-url') || profile.realtimeUrl || currentUser.instance?.endpoints?.realtime;
|
|
804
1311
|
if (!rt)
|
|
805
1312
|
throw new Error('Realtime endpoint unavailable. Pass --realtime-url.');
|
|
806
1313
|
const secret = randomBytes(32).toString('hex');
|
|
807
|
-
device = { agentTerminalId: randomUUID(), secret, workspace, name
|
|
1314
|
+
device = { agentTerminalId: randomUUID(), secret, workspace, name,
|
|
808
1315
|
baseUrl: profile.baseUrl, instance: profile.instance, realtimeUrl: realtimeUrl(rt) };
|
|
809
1316
|
await api(profile, 'POST', '/agents/terminals/pair', { agentTerminalId: device.agentTerminalId,
|
|
810
1317
|
secretHash: createHash('sha256').update(Buffer.from(secret, 'hex')).digest('hex'),
|
|
811
1318
|
name: device.name, workspace });
|
|
812
|
-
|
|
813
|
-
|
|
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
|
+
}
|
|
814
1335
|
console.log(`Pending approval in AI Agents → Terminals: ${device.name} (${device.agentTerminalId}).`);
|
|
815
1336
|
}
|
|
816
1337
|
for (;;) {
|
|
@@ -822,5 +1343,11 @@ export async function handleTerminalCommand(argv) {
|
|
|
822
1343
|
throw new Error('Terminal grant revoked or missing.');
|
|
823
1344
|
await new Promise(resolve => setTimeout(resolve, 2_000));
|
|
824
1345
|
}
|
|
825
|
-
|
|
1346
|
+
const releaseRunnerLock = acquireRunnerLock(device.agentTerminalId);
|
|
1347
|
+
try {
|
|
1348
|
+
await connect(profile, device);
|
|
1349
|
+
}
|
|
1350
|
+
finally {
|
|
1351
|
+
releaseRunnerLock();
|
|
1352
|
+
}
|
|
826
1353
|
}
|