@revoengine/cli 1.0.10 → 1.0.12
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 +314 -239
- package/dist/src/cli.js +126 -9
- package/dist/src/client.d.ts +373 -6
- package/dist/src/client.js +1005 -53
- package/dist/src/commands/auth.js +4 -2
- package/dist/src/commands/component.d.ts +67 -0
- package/dist/src/commands/component.js +555 -164
- package/dist/src/commands/database-tables.d.ts +2 -0
- package/dist/src/commands/database-tables.js +169 -0
- package/dist/src/commands/database-views.d.ts +2 -0
- package/dist/src/commands/database-views.js +126 -0
- package/dist/src/commands/endpoints.js +124 -0
- package/dist/src/commands/env.js +44 -24
- package/dist/src/commands/events.d.ts +2 -0
- package/dist/src/commands/events.js +144 -0
- package/dist/src/commands/groups.d.ts +2 -0
- package/dist/src/commands/groups.js +160 -0
- package/dist/src/commands/index.d.ts +9 -0
- package/dist/src/commands/index.js +9 -0
- package/dist/src/commands/job-templates.d.ts +2 -0
- package/dist/src/commands/job-templates.js +107 -0
- package/dist/src/commands/metadata.js +75 -10
- package/dist/src/commands/migrate.d.ts +6 -0
- package/dist/src/commands/migrate.js +658 -0
- package/dist/src/commands/project.js +10 -3
- package/dist/src/commands/role-groups.d.ts +2 -0
- package/dist/src/commands/role-groups.js +141 -0
- package/dist/src/commands/schedules.d.ts +2 -0
- package/dist/src/commands/schedules.js +140 -0
- package/dist/src/commands/terminal-browser.d.ts +16 -0
- package/dist/src/commands/terminal-browser.js +92 -0
- package/dist/src/commands/terminal-image.d.ts +7 -0
- package/dist/src/commands/terminal-image.js +40 -0
- package/dist/src/commands/terminal-patch-worker.d.ts +1 -0
- package/dist/src/commands/terminal-patch-worker.js +24 -0
- package/dist/src/commands/terminal-patch.d.ts +2 -0
- package/dist/src/commands/terminal-patch.js +156 -0
- package/dist/src/commands/terminal-sandbox.d.ts +8 -0
- package/dist/src/commands/terminal-sandbox.js +87 -0
- package/dist/src/commands/terminal-service.d.ts +38 -0
- package/dist/src/commands/terminal-service.js +210 -0
- package/dist/src/commands/terminal.d.ts +49 -0
- package/dist/src/commands/terminal.js +826 -0
- package/dist/src/component-lock.d.ts +111 -3
- package/dist/src/component-lock.js +363 -15
- package/dist/src/config.d.ts +10 -2
- package/dist/src/config.js +49 -14
- package/dist/src/database-table-artifacts.d.ts +7 -0
- package/dist/src/database-table-artifacts.js +8 -0
- package/dist/src/diff-details.d.ts +8 -0
- package/dist/src/diff-details.js +152 -0
- package/dist/src/env-sync.d.ts +0 -3
- package/dist/src/env-sync.js +11 -25
- package/dist/src/http-trace.d.ts +94 -0
- package/dist/src/http-trace.js +226 -0
- package/dist/src/metadata-backfill.d.ts +18 -7
- package/dist/src/metadata-backfill.js +1002 -27
- package/dist/src/migration.d.ts +141 -0
- package/dist/src/migration.js +1632 -0
- package/dist/src/project.d.ts +2 -0
- package/dist/src/project.js +4 -17
- package/dist/src/prompt.js +10 -18
- package/dist/src/resource-inventory.d.ts +28 -0
- package/dist/src/resource-inventory.js +85 -0
- package/dist/src/resource-metadata.d.ts +1 -0
- package/dist/src/resource-metadata.js +3 -0
- package/dist/src/resource-syncs/database-table-sync.d.ts +127 -0
- package/dist/src/resource-syncs/database-table-sync.js +2374 -0
- package/dist/src/resource-syncs/database-view-sync.d.ts +146 -0
- package/dist/src/resource-syncs/database-view-sync.js +1405 -0
- package/dist/src/resource-syncs/endpoint-sync.d.ts +123 -0
- package/dist/src/resource-syncs/endpoint-sync.js +1563 -0
- package/dist/src/resource-syncs/event-sync.d.ts +126 -0
- package/dist/src/resource-syncs/event-sync.js +1046 -0
- package/dist/src/resource-syncs/group-sync.d.ts +93 -0
- package/dist/src/resource-syncs/group-sync.js +928 -0
- package/dist/src/resource-syncs/job-template-sync.d.ts +106 -0
- package/dist/src/resource-syncs/job-template-sync.js +843 -0
- package/dist/src/resource-syncs/role-group-sync.d.ts +90 -0
- package/dist/src/resource-syncs/role-group-sync.js +635 -0
- package/dist/src/resource-syncs/schedule-sync.d.ts +140 -0
- package/dist/src/resource-syncs/schedule-sync.js +1396 -0
- package/dist/src/resource-syncs/util.d.ts +22 -0
- package/dist/src/resource-syncs/util.js +118 -0
- package/dist/src/resource-target.d.ts +11 -0
- package/dist/src/resource-target.js +48 -0
- package/dist/src/runtime-view.d.ts +1 -0
- package/dist/src/runtime-view.js +6 -1
- package/dist/src/sync-output.d.ts +66 -0
- package/dist/src/sync-output.js +268 -0
- package/dist/src/tracked-resources.d.ts +1 -1
- package/dist/src/tracked-resources.js +28 -2
- package/dist/src/types.d.ts +227 -0
- package/dist/src/ui.d.ts +3 -0
- package/dist/src/ui.js +76 -18
- package/dist/src/utils.d.ts +4 -0
- package/dist/src/utils.js +81 -0
- package/dist/src/workspace-component.d.ts +2 -0
- package/dist/src/workspace-component.js +34 -0
- package/dist/src/workspace-diff.d.ts +25 -0
- package/dist/src/workspace-diff.js +75 -0
- package/dist/src/workspace-resource.d.ts +2 -0
- package/dist/src/workspace-resource.js +52 -0
- package/package.json +12 -4
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
6
|
+
import { spawn } from 'node:child_process';
|
|
7
|
+
import * as pty from 'node-pty';
|
|
8
|
+
import WebSocket from 'ws';
|
|
9
|
+
import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
|
|
10
|
+
import { promptConfirm } from "../prompt.js";
|
|
11
|
+
import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
|
|
12
|
+
import { sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
|
|
13
|
+
import { runBrowserAction } from "./terminal-browser.js";
|
|
14
|
+
import { uploadWorkspaceImages } from "./terminal-image.js";
|
|
15
|
+
export const MAX_TERMINAL_PROCESS_MS = 59 * 60_000;
|
|
16
|
+
const configDir = getConfigDir;
|
|
17
|
+
const runnerConfig = () => path.join(configDir(), 'runner.json');
|
|
18
|
+
const MAX_MODEL_OUTPUT_BYTES = 100_000;
|
|
19
|
+
const MAX_LOCAL_LOG_BYTES = 10_000_000;
|
|
20
|
+
const OUTPUT_FRAME_CHARS = 1_000;
|
|
21
|
+
const LOG_RETENTION_MS = 24 * 60 * 60 * 1_000;
|
|
22
|
+
const CHILD_ENV_KEYS = ['HOME', 'PATH', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM'];
|
|
23
|
+
export function childEnvironment(source) {
|
|
24
|
+
const safe = {};
|
|
25
|
+
for (const key of CHILD_ENV_KEYS)
|
|
26
|
+
if (source[key] !== undefined)
|
|
27
|
+
safe[key] = source[key];
|
|
28
|
+
return safe;
|
|
29
|
+
}
|
|
30
|
+
function logDirectory() { return path.join(configDir(), 'runner-logs'); }
|
|
31
|
+
function pruneLogs(directory) {
|
|
32
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
33
|
+
for (const name of fs.readdirSync(directory)) {
|
|
34
|
+
const file = path.join(directory, name);
|
|
35
|
+
try {
|
|
36
|
+
if (name.endsWith('.log') && Date.now() - fs.statSync(file).mtimeMs > LOG_RETENTION_MS)
|
|
37
|
+
fs.unlinkSync(file);
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error.code !== 'ENOENT')
|
|
41
|
+
throw error;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
function readJson(file) {
|
|
46
|
+
try {
|
|
47
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
48
|
+
}
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error.code === 'ENOENT')
|
|
51
|
+
return {};
|
|
52
|
+
throw error;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function readStore() {
|
|
56
|
+
const value = readJson(runnerConfig());
|
|
57
|
+
return { devices: Array.isArray(value.devices) ? value.devices.map((device) => ({
|
|
58
|
+
...device, agentTerminalId: device.agentTerminalId || device.deviceId, deviceId: undefined,
|
|
59
|
+
})) : [] };
|
|
60
|
+
}
|
|
61
|
+
function saveStore(store) {
|
|
62
|
+
fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
|
|
63
|
+
const file = runnerConfig();
|
|
64
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
65
|
+
try {
|
|
66
|
+
fs.writeFileSync(temporary, JSON.stringify(store, null, 2), { mode: 0o600 });
|
|
67
|
+
fs.renameSync(temporary, file);
|
|
68
|
+
fs.chmodSync(file, 0o600);
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
try {
|
|
72
|
+
fs.unlinkSync(temporary);
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
if (error.code !== 'ENOENT')
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
export function resolveWorkspaceDirectory(root, requested) {
|
|
81
|
+
const workspace = fs.realpathSync(root);
|
|
82
|
+
const workdir = fs.realpathSync(requested);
|
|
83
|
+
const relative = path.relative(workspace, workdir);
|
|
84
|
+
if (relative.startsWith('..') || path.isAbsolute(relative))
|
|
85
|
+
throw new Error('Working directory is outside the registered workspace.');
|
|
86
|
+
return workdir;
|
|
87
|
+
}
|
|
88
|
+
function option(argv, name) {
|
|
89
|
+
const index = argv.indexOf(`--${name}`);
|
|
90
|
+
if (index >= 0)
|
|
91
|
+
return argv[index + 1];
|
|
92
|
+
return argv.find(value => value.startsWith(`--${name}=`))?.slice(name.length + 3);
|
|
93
|
+
}
|
|
94
|
+
function selectedProject(argv) {
|
|
95
|
+
const project = option(argv, 'project');
|
|
96
|
+
const legacy = option(argv, 'env');
|
|
97
|
+
if (project !== undefined && legacy !== undefined)
|
|
98
|
+
throw new Error('Use either --project or --env, not both.');
|
|
99
|
+
const selected = project ?? legacy;
|
|
100
|
+
if (selected !== undefined && (!selected.trim() || selected.startsWith('--')))
|
|
101
|
+
throw new Error('--project requires a saved project name.');
|
|
102
|
+
return selected;
|
|
103
|
+
}
|
|
104
|
+
function resolveProfile(argv) {
|
|
105
|
+
const urlOverride = option(argv, 'url');
|
|
106
|
+
const tokenOverride = option(argv, 'token');
|
|
107
|
+
const configured = resolveRuntimeConfig({ baseUrl: urlOverride,
|
|
108
|
+
token: tokenOverride, instance: option(argv, 'instance'), envName: selectedProject(argv) });
|
|
109
|
+
const token = configured.token;
|
|
110
|
+
if (!token || !token.startsWith('sk-'))
|
|
111
|
+
throw new Error('A personal Revo API key is required. Run revo auth login or select a CLI profile.');
|
|
112
|
+
return { baseUrl: configured.baseUrl.replace(/\/$/, ''), token,
|
|
113
|
+
instance: option(argv, 'instance') || (urlOverride || tokenOverride ? undefined : configured.instance),
|
|
114
|
+
realtimeUrl: option(argv, 'realtime-url'), production: configured.production };
|
|
115
|
+
}
|
|
116
|
+
function apiUrl(profile, route) {
|
|
117
|
+
const base = profile.baseUrl.replace(/\/(?:api\/)?v1\/?$/, '');
|
|
118
|
+
const url = new URL(base);
|
|
119
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === 'localhost'))
|
|
120
|
+
throw new Error('Remote Revo API requires HTTPS.');
|
|
121
|
+
return `${base}/api/v1${route}`;
|
|
122
|
+
}
|
|
123
|
+
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
|
+
const response = await fetch(apiUrl(profile, route), {
|
|
131
|
+
method,
|
|
132
|
+
redirect: 'manual',
|
|
133
|
+
headers: { Authorization: `Bearer ${profile.token}`,
|
|
134
|
+
...(profile.instance ? { instance: profile.instance } : {}),
|
|
135
|
+
...(body ? { 'Content-Type': 'application/json' } : {}) },
|
|
136
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
137
|
+
});
|
|
138
|
+
if (response.status >= 300 && response.status < 400)
|
|
139
|
+
throw new Error(`Revo API ${method} ${route} redirected; refusing to forward credentials.`);
|
|
140
|
+
const value = await response.json().catch(() => ({}));
|
|
141
|
+
if (!response.ok)
|
|
142
|
+
throw new Error(`Revo API ${method} ${route} returned ${response.status}: ${String(value?.message || 'request failed')}`);
|
|
143
|
+
return (value?.data ?? value);
|
|
144
|
+
}
|
|
145
|
+
function realtimeUrl(value) {
|
|
146
|
+
const url = new URL(value);
|
|
147
|
+
if (!['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol))
|
|
148
|
+
throw new Error('Invalid Realtime URL.');
|
|
149
|
+
url.protocol = url.protocol === 'https:' || url.protocol === 'wss:' ? 'wss:' : 'ws:';
|
|
150
|
+
if (url.protocol === 'ws:' && url.hostname !== 'localhost')
|
|
151
|
+
throw new Error('Remote Realtime requires TLS.');
|
|
152
|
+
url.pathname = '/runner/v1/ws';
|
|
153
|
+
url.search = '';
|
|
154
|
+
return url.toString();
|
|
155
|
+
}
|
|
156
|
+
function send(socket, frame) {
|
|
157
|
+
if (socket.readyState === WebSocket.OPEN)
|
|
158
|
+
socket.send(JSON.stringify(frame));
|
|
159
|
+
}
|
|
160
|
+
export function boundResultFrame(frame) {
|
|
161
|
+
const bounded = { ...frame, stdout: String(frame.stdout || ''), stderr: String(frame.stderr || '') };
|
|
162
|
+
while (Buffer.byteLength(JSON.stringify(bounded)) > 90_000) {
|
|
163
|
+
if (bounded.stdout.length >= bounded.stderr.length)
|
|
164
|
+
bounded.stdout = bounded.stdout.slice(0, Math.floor(bounded.stdout.length * 0.75));
|
|
165
|
+
else
|
|
166
|
+
bounded.stderr = bounded.stderr.slice(0, Math.floor(bounded.stderr.length * 0.75));
|
|
167
|
+
}
|
|
168
|
+
return bounded;
|
|
169
|
+
}
|
|
170
|
+
function sendResult(socket, frame) {
|
|
171
|
+
send(socket, boundResultFrame(frame));
|
|
172
|
+
}
|
|
173
|
+
export async function runCommand(input, onDone, onChunk) {
|
|
174
|
+
const workdir = resolveWorkspaceDirectory(input.workspace, input.workdir);
|
|
175
|
+
const sandbox = input.sandbox || 'workspace';
|
|
176
|
+
if (sandbox !== 'unrestricted' && requiresElevatedCommand(input.cmd))
|
|
177
|
+
throw new Error('destructive_command_requires_approval');
|
|
178
|
+
const scratch = sandbox !== 'unrestricted' ? fs.mkdtempSync(path.join(os.tmpdir(), 'revo-terminal-')) : undefined;
|
|
179
|
+
const scratchRoot = scratch ? fs.realpathSync(scratch) : undefined;
|
|
180
|
+
let launch;
|
|
181
|
+
try {
|
|
182
|
+
launch = sandboxCommand(input.workspace, workdir, input.cmd, sandbox, process.platform, scratch, [], input.networkAllowed !== false);
|
|
183
|
+
}
|
|
184
|
+
catch (error) {
|
|
185
|
+
if (scratch)
|
|
186
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
187
|
+
throw error;
|
|
188
|
+
}
|
|
189
|
+
const directory = input.logDir || logDirectory();
|
|
190
|
+
const logPath = path.join(directory, `${input.executionId || randomUUID()}.log`);
|
|
191
|
+
let logFd;
|
|
192
|
+
try {
|
|
193
|
+
pruneLogs(directory);
|
|
194
|
+
logFd = fs.openSync(logPath, 'wx', 0o600);
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
console.error(`Runner log unavailable: ${error.message}`);
|
|
198
|
+
}
|
|
199
|
+
const env = { ...childEnvironment(process.env), ...(scratchRoot ? { HOME: scratchRoot,
|
|
200
|
+
TMPDIR: scratchRoot, TMP: scratchRoot, TEMP: scratchRoot, GIT_CONFIG_GLOBAL: '/dev/null',
|
|
201
|
+
XDG_CONFIG_HOME: path.join(scratchRoot, 'xdg-config'),
|
|
202
|
+
npm_config_cache: path.join(scratchRoot, 'npm-cache'), XDG_CACHE_HOME: path.join(scratchRoot, 'xdg-cache'),
|
|
203
|
+
PIP_CACHE_DIR: path.join(scratchRoot, 'pip-cache') } : {}) };
|
|
204
|
+
const tty = input.tty === true;
|
|
205
|
+
let child;
|
|
206
|
+
let terminal;
|
|
207
|
+
try {
|
|
208
|
+
if (tty)
|
|
209
|
+
terminal = pty.spawn(launch.file, launch.args, {
|
|
210
|
+
cwd: workdir, env, name: 'xterm-256color', cols: input.cols || 80, rows: input.rows || 24,
|
|
211
|
+
});
|
|
212
|
+
else
|
|
213
|
+
child = spawn(launch.file, launch.args, {
|
|
214
|
+
cwd: workdir, detached: true, stdio: ['pipe', 'pipe', 'pipe'], env,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
if (logFd !== undefined)
|
|
219
|
+
fs.closeSync(logFd);
|
|
220
|
+
if (scratch)
|
|
221
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
222
|
+
throw error;
|
|
223
|
+
}
|
|
224
|
+
let stdout = '';
|
|
225
|
+
let stderr = '';
|
|
226
|
+
let modelBytes = 0;
|
|
227
|
+
let logBytes = 0;
|
|
228
|
+
let truncated = false;
|
|
229
|
+
let logTruncated = logFd === undefined;
|
|
230
|
+
let timedOut = false;
|
|
231
|
+
let finished = false;
|
|
232
|
+
const pid = child?.pid || terminal?.pid;
|
|
233
|
+
const terminate = () => {
|
|
234
|
+
if (!pid)
|
|
235
|
+
return;
|
|
236
|
+
try {
|
|
237
|
+
process.kill(-pid, 'SIGTERM');
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
try {
|
|
241
|
+
process.kill(pid, 'SIGTERM');
|
|
242
|
+
}
|
|
243
|
+
catch { /* exited */ }
|
|
244
|
+
}
|
|
245
|
+
const hardStop = setTimeout(() => {
|
|
246
|
+
if (finished)
|
|
247
|
+
return;
|
|
248
|
+
try {
|
|
249
|
+
process.kill(-pid, 'SIGKILL');
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
try {
|
|
253
|
+
process.kill(pid, 'SIGKILL');
|
|
254
|
+
}
|
|
255
|
+
catch { /* exited */ }
|
|
256
|
+
}
|
|
257
|
+
}, 2_000);
|
|
258
|
+
hardStop.unref?.();
|
|
259
|
+
};
|
|
260
|
+
const timer = setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), MAX_TERMINAL_PROCESS_MS));
|
|
261
|
+
const append = (chunk, kind) => {
|
|
262
|
+
const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
|
|
263
|
+
if (logPart.length && logFd !== undefined) {
|
|
264
|
+
const header = Buffer.from(`[${kind}] `);
|
|
265
|
+
if (logBytes + header.length + logPart.length <= MAX_LOCAL_LOG_BYTES) {
|
|
266
|
+
try {
|
|
267
|
+
fs.writeSync(logFd, header);
|
|
268
|
+
fs.writeSync(logFd, logPart);
|
|
269
|
+
logBytes += header.length + logPart.length;
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
console.error(`Runner log write failed: ${error.message}`);
|
|
273
|
+
logTruncated = true;
|
|
274
|
+
try {
|
|
275
|
+
fs.closeSync(logFd);
|
|
276
|
+
}
|
|
277
|
+
catch { /* log already unavailable */ }
|
|
278
|
+
logFd = undefined;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
else
|
|
282
|
+
logTruncated = true;
|
|
283
|
+
}
|
|
284
|
+
if (logPart.length < chunk.length)
|
|
285
|
+
logTruncated = true;
|
|
286
|
+
const available = Math.max(0, MAX_MODEL_OUTPUT_BYTES - modelBytes);
|
|
287
|
+
const modelPart = chunk.subarray(0, available);
|
|
288
|
+
modelBytes += modelPart.length;
|
|
289
|
+
if (modelPart.length < chunk.length)
|
|
290
|
+
truncated = true;
|
|
291
|
+
const text = modelPart.toString('utf8');
|
|
292
|
+
if (kind === 'stdout')
|
|
293
|
+
stdout += text;
|
|
294
|
+
else
|
|
295
|
+
stderr += text;
|
|
296
|
+
if (onChunk && text) {
|
|
297
|
+
for (let offset = 0; offset < text.length; offset += OUTPUT_FRAME_CHARS)
|
|
298
|
+
onChunk(kind, text.slice(offset, offset + OUTPUT_FRAME_CHARS));
|
|
299
|
+
}
|
|
300
|
+
};
|
|
301
|
+
child?.stdout?.on('data', (chunk) => append(chunk, 'stdout'));
|
|
302
|
+
child?.stderr?.on('data', (chunk) => append(chunk, 'stderr'));
|
|
303
|
+
terminal?.onData(text => append(Buffer.from(text), 'stdout'));
|
|
304
|
+
const finish = (exitCode, error) => {
|
|
305
|
+
if (finished)
|
|
306
|
+
return;
|
|
307
|
+
finished = true;
|
|
308
|
+
clearTimeout(timer);
|
|
309
|
+
if (scratch) {
|
|
310
|
+
try {
|
|
311
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
312
|
+
}
|
|
313
|
+
catch { /* temporary cleanup */ }
|
|
314
|
+
}
|
|
315
|
+
if (logFd !== undefined) {
|
|
316
|
+
try {
|
|
317
|
+
fs.closeSync(logFd);
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
logTruncated = true;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
onDone({ executed: !error, exitCode: timedOut && exitCode === 0 ? null : exitCode,
|
|
324
|
+
stdout, stderr: error ? `${stderr}\n${error.message}` : stderr,
|
|
325
|
+
timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath });
|
|
326
|
+
};
|
|
327
|
+
child?.on('close', code => finish(code));
|
|
328
|
+
child?.on('error', error => finish(null, error));
|
|
329
|
+
terminal?.onExit(({ exitCode }) => finish(exitCode));
|
|
330
|
+
return { pid, terminate,
|
|
331
|
+
write: chars => { if (terminal)
|
|
332
|
+
terminal.write(chars);
|
|
333
|
+
else
|
|
334
|
+
child?.stdin?.write(chars); },
|
|
335
|
+
closeStdin: chars => { if (terminal)
|
|
336
|
+
terminal.write(`${chars}\x04`);
|
|
337
|
+
else
|
|
338
|
+
child?.stdin?.end(chars); },
|
|
339
|
+
resize: (cols, rows) => { if (terminal)
|
|
340
|
+
terminal.resize(cols, rows); },
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
export function runWorkspacePatch(input, onDone) {
|
|
344
|
+
if (Buffer.byteLength(input.patch) > 64_000)
|
|
345
|
+
throw new Error('Patch exceeds 64 KB.');
|
|
346
|
+
const workerJs = fileURLToPath(new URL('./terminal-patch-worker.js', import.meta.url));
|
|
347
|
+
const worker = fs.existsSync(workerJs) ? workerJs : fileURLToPath(new URL('./terminal-patch-worker.ts', import.meta.url));
|
|
348
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'revo-terminal-patch-'));
|
|
349
|
+
let launch;
|
|
350
|
+
try {
|
|
351
|
+
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)]);
|
|
353
|
+
}
|
|
354
|
+
catch (error) {
|
|
355
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
356
|
+
throw error;
|
|
357
|
+
}
|
|
358
|
+
const child = spawn(launch.file, launch.args, { cwd: input.workspace, detached: true,
|
|
359
|
+
stdio: ['pipe', 'pipe', 'pipe'], env: { ...childEnvironment(process.env), TMPDIR: scratch, TMP: scratch, TEMP: scratch } });
|
|
360
|
+
let stdout = '';
|
|
361
|
+
let stderr = '';
|
|
362
|
+
let finished = false;
|
|
363
|
+
let timedOut = false;
|
|
364
|
+
const timer = setTimeout(() => {
|
|
365
|
+
timedOut = true;
|
|
366
|
+
if (child.pid)
|
|
367
|
+
try {
|
|
368
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
369
|
+
}
|
|
370
|
+
catch { /* exited */ }
|
|
371
|
+
}, 60_000);
|
|
372
|
+
child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8').slice(0, 4_000 - stdout.length); });
|
|
373
|
+
child.stderr?.on('data', (chunk) => { stderr += chunk.toString('utf8').slice(0, 4_000 - stderr.length); });
|
|
374
|
+
child.stdin?.on('error', () => { });
|
|
375
|
+
child.stdin?.end(input.patch);
|
|
376
|
+
const finish = (code, error) => {
|
|
377
|
+
if (finished)
|
|
378
|
+
return;
|
|
379
|
+
finished = true;
|
|
380
|
+
clearTimeout(timer);
|
|
381
|
+
try {
|
|
382
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
383
|
+
}
|
|
384
|
+
catch { /* temporary cleanup */ }
|
|
385
|
+
onDone({ executed: !error, exitCode: code, stdout,
|
|
386
|
+
stderr: error ? `${stderr}\n${error.message}` : stderr, timedOut });
|
|
387
|
+
};
|
|
388
|
+
child.on('close', code => finish(code));
|
|
389
|
+
child.on('error', error => finish(null, error));
|
|
390
|
+
return child;
|
|
391
|
+
}
|
|
392
|
+
async function connect(profile, device) {
|
|
393
|
+
let backoffMs = 1_000;
|
|
394
|
+
let stopping = false;
|
|
395
|
+
let activeSocket;
|
|
396
|
+
let activeConnectionId = '';
|
|
397
|
+
const activeChildren = new Set();
|
|
398
|
+
const children = new Map();
|
|
399
|
+
const cancelledExecutions = new Set();
|
|
400
|
+
const outputByExecution = new Map();
|
|
401
|
+
const completed = new Map();
|
|
402
|
+
const resumed = new Set();
|
|
403
|
+
let reconnectGrace;
|
|
404
|
+
const sendCurrent = (frame) => {
|
|
405
|
+
if (activeConnectionId && activeSocket?.readyState === WebSocket.OPEN)
|
|
406
|
+
send(activeSocket, { ...frame, connectionId: activeConnectionId });
|
|
407
|
+
};
|
|
408
|
+
const flushExecution = (executionId) => {
|
|
409
|
+
if (!resumed.has(executionId))
|
|
410
|
+
return;
|
|
411
|
+
for (const chunk of outputByExecution.get(executionId) || [])
|
|
412
|
+
sendCurrent({ type: 'output', executionId, ...chunk });
|
|
413
|
+
const result = completed.get(executionId);
|
|
414
|
+
if (result)
|
|
415
|
+
sendCurrent({ type: 'result', executionId, ...result });
|
|
416
|
+
};
|
|
417
|
+
const stop = () => {
|
|
418
|
+
stopping = true;
|
|
419
|
+
if (reconnectGrace)
|
|
420
|
+
clearTimeout(reconnectGrace);
|
|
421
|
+
if (activeSocket?.readyState === WebSocket.CONNECTING)
|
|
422
|
+
activeSocket.terminate();
|
|
423
|
+
else
|
|
424
|
+
activeSocket?.close();
|
|
425
|
+
for (const child of activeChildren)
|
|
426
|
+
child.terminate();
|
|
427
|
+
};
|
|
428
|
+
process.on('SIGINT', stop);
|
|
429
|
+
process.on('SIGTERM', stop);
|
|
430
|
+
try {
|
|
431
|
+
while (!stopping) {
|
|
432
|
+
try {
|
|
433
|
+
await new Promise((resolve, reject) => {
|
|
434
|
+
const socket = new WebSocket(device.realtimeUrl, {
|
|
435
|
+
headers: { Authorization: `Bearer ${profile.token}`,
|
|
436
|
+
...(profile.instance ? { instance: profile.instance } : {}) },
|
|
437
|
+
perMessageDeflate: false,
|
|
438
|
+
});
|
|
439
|
+
activeSocket = socket;
|
|
440
|
+
let connectionId = '';
|
|
441
|
+
let workspace = device.workspace;
|
|
442
|
+
let heartbeat;
|
|
443
|
+
let lastHeartbeat = Date.now();
|
|
444
|
+
let incoming = Promise.resolve();
|
|
445
|
+
socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
|
|
446
|
+
secret: device.secret, capabilities: ['workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
|
|
447
|
+
'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_local_v1', 'save_image_v1',
|
|
448
|
+
...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])] }));
|
|
449
|
+
socket.on('message', raw => {
|
|
450
|
+
incoming = incoming.then(async () => {
|
|
451
|
+
if (stopping || socket.readyState !== WebSocket.OPEN)
|
|
452
|
+
return;
|
|
453
|
+
const frame = JSON.parse(raw.toString());
|
|
454
|
+
if (frame.type === 'ready' && frame.connectionId) {
|
|
455
|
+
connectionId = frame.connectionId;
|
|
456
|
+
activeConnectionId = connectionId;
|
|
457
|
+
workspace = frame.workspace || device.workspace;
|
|
458
|
+
backoffMs = 1_000;
|
|
459
|
+
if (reconnectGrace) {
|
|
460
|
+
clearTimeout(reconnectGrace);
|
|
461
|
+
reconnectGrace = undefined;
|
|
462
|
+
}
|
|
463
|
+
console.log(`Connected ${device.name} (${device.agentTerminalId}).`);
|
|
464
|
+
for (const executionId of new Set([...children.keys(), ...completed.keys()]))
|
|
465
|
+
send(socket, { type: 'resume', connectionId, executionId });
|
|
466
|
+
heartbeat = setInterval(() => {
|
|
467
|
+
if (Date.now() - lastHeartbeat > 45_000) {
|
|
468
|
+
socket.terminate();
|
|
469
|
+
return;
|
|
470
|
+
}
|
|
471
|
+
send(socket, { type: 'heartbeat', connectionId });
|
|
472
|
+
}, 15_000);
|
|
473
|
+
return;
|
|
474
|
+
}
|
|
475
|
+
if (frame.type === 'heartbeat') {
|
|
476
|
+
lastHeartbeat = Date.now();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
if (frame.connectionId !== connectionId || !frame.executionId)
|
|
480
|
+
return;
|
|
481
|
+
if (frame.type === 'resumed') {
|
|
482
|
+
resumed.add(frame.executionId);
|
|
483
|
+
flushExecution(frame.executionId);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
if (frame.type === 'result_ack' || frame.type === 'resume_rejected') {
|
|
487
|
+
if (frame.type === 'resume_rejected')
|
|
488
|
+
children.get(frame.executionId)?.terminate();
|
|
489
|
+
completed.delete(frame.executionId);
|
|
490
|
+
outputByExecution.delete(frame.executionId);
|
|
491
|
+
resumed.delete(frame.executionId);
|
|
492
|
+
return;
|
|
493
|
+
}
|
|
494
|
+
if (frame.type === 'cancel') {
|
|
495
|
+
const child = children.get(frame.executionId);
|
|
496
|
+
if (child) {
|
|
497
|
+
cancelledExecutions.add(frame.executionId);
|
|
498
|
+
child.terminate();
|
|
499
|
+
}
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
if (frame.type === 'stdin') {
|
|
503
|
+
const child = children.get(frame.executionId);
|
|
504
|
+
if (child && typeof frame.chars === 'string' && Buffer.byteLength(frame.chars) <= 8_192
|
|
505
|
+
&& typeof frame.closeStdin === 'boolean') {
|
|
506
|
+
if (frame.closeStdin)
|
|
507
|
+
child.closeStdin(frame.chars);
|
|
508
|
+
else if (frame.chars)
|
|
509
|
+
child.write(frame.chars);
|
|
510
|
+
}
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
if (frame.type === 'resize') {
|
|
514
|
+
const child = children.get(frame.executionId);
|
|
515
|
+
if (child && Number.isInteger(frame.cols) && Number.isInteger(frame.rows)
|
|
516
|
+
&& frame.cols >= 20 && frame.cols <= 240 && frame.rows >= 10 && frame.rows <= 100)
|
|
517
|
+
child.resize(frame.cols, frame.rows);
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
if (frame.type !== 'execute')
|
|
521
|
+
return;
|
|
522
|
+
if (children.has(frame.executionId) || completed.has(frame.executionId)) {
|
|
523
|
+
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
524
|
+
return;
|
|
525
|
+
}
|
|
526
|
+
const operation = frame.operation || 'shell';
|
|
527
|
+
const validPayload = operation === 'apply_patch'
|
|
528
|
+
? typeof frame.patch === 'string' && Buffer.byteLength(frame.patch) <= 64_000
|
|
529
|
+
: operation === 'browser' ? typeof frame.url === 'string' && frame.url.length <= 2_048
|
|
530
|
+
&& ['navigate', 'dom', 'screenshot'].includes(frame.browserAction || '')
|
|
531
|
+
: operation === 'save_image' ? Array.isArray(frame.files) && frame.files.length > 0 && frame.files.length <= 32
|
|
532
|
+
: operation === 'shell' && typeof frame.cmd === 'string' && !!frame.cmd.trim() && frame.cmd.length <= 8_192;
|
|
533
|
+
if (!validPayload || children.size >= 4 || !['workspace', 'workspace-network', 'unrestricted'].includes(frame.sandbox || 'unrestricted')
|
|
534
|
+
|| frame.networkAllowed === false && frame.sandbox === 'workspace-network'
|
|
535
|
+
|| operation === 'apply_patch' && frame.sandbox === 'workspace-network'
|
|
536
|
+
|| (operation === 'browser' || operation === 'save_image') && (frame.sandbox !== 'workspace-network'
|
|
537
|
+
|| frame.networkAllowed === false)
|
|
538
|
+
|| frame.tty === true && (operation !== 'shell' || !Number.isInteger(frame.cols) || !Number.isInteger(frame.rows)
|
|
539
|
+
|| frame.cols < 20 || frame.cols > 240 || frame.rows < 10 || frame.rows > 100)) {
|
|
540
|
+
sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
|
|
541
|
+
executed: false, exitCode: null, stdout: '', stderr: children.size >= 4 ? 'runner_busy' : 'invalid_command', timedOut: false });
|
|
542
|
+
return;
|
|
543
|
+
}
|
|
544
|
+
try {
|
|
545
|
+
resumed.add(frame.executionId);
|
|
546
|
+
outputByExecution.set(frame.executionId, []);
|
|
547
|
+
if (operation === 'save_image') {
|
|
548
|
+
const controller = new AbortController();
|
|
549
|
+
const child = { pid: undefined, write: () => undefined,
|
|
550
|
+
closeStdin: () => undefined, resize: () => undefined,
|
|
551
|
+
terminate: () => controller.abort() };
|
|
552
|
+
children.set(frame.executionId, child);
|
|
553
|
+
activeChildren.add(child);
|
|
554
|
+
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
555
|
+
void uploadWorkspaceImages(workspace, frame.files, controller.signal).then(count => {
|
|
556
|
+
children.delete(frame.executionId);
|
|
557
|
+
activeChildren.delete(child);
|
|
558
|
+
completed.set(frame.executionId, { executed: true, exitCode: 0, stdout: `Uploaded ${count} image(s).`, stderr: '' });
|
|
559
|
+
if (resumed.has(frame.executionId))
|
|
560
|
+
flushExecution(frame.executionId);
|
|
561
|
+
}).catch(error => {
|
|
562
|
+
children.delete(frame.executionId);
|
|
563
|
+
activeChildren.delete(child);
|
|
564
|
+
completed.set(frame.executionId, { executed: false, exitCode: null, stdout: '',
|
|
565
|
+
stderr: error instanceof Error ? error.message : 'image_upload_failed' });
|
|
566
|
+
if (resumed.has(frame.executionId))
|
|
567
|
+
flushExecution(frame.executionId);
|
|
568
|
+
});
|
|
569
|
+
return;
|
|
570
|
+
}
|
|
571
|
+
if (operation === 'browser') {
|
|
572
|
+
const controller = new AbortController();
|
|
573
|
+
const child = { pid: undefined, write: () => undefined,
|
|
574
|
+
closeStdin: () => undefined, resize: () => undefined,
|
|
575
|
+
terminate: () => controller.abort() };
|
|
576
|
+
children.set(frame.executionId, child);
|
|
577
|
+
activeChildren.add(child);
|
|
578
|
+
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
579
|
+
void runBrowserAction({ url: frame.url, action: frame.browserAction, workspace,
|
|
580
|
+
selector: frame.selector, width: frame.width, height: frame.height,
|
|
581
|
+
localOnly: frame.browserLocalOnly === true, signal: controller.signal })
|
|
582
|
+
.then(async (browserResult) => {
|
|
583
|
+
if (frame.browserAction === 'screenshot') {
|
|
584
|
+
if (!browserResult.screenshotPath || frame.files?.length !== 1)
|
|
585
|
+
throw new Error('browser_image_upload_unavailable');
|
|
586
|
+
await uploadWorkspaceImages(workspace, [{ ...frame.files[0], path: browserResult.screenshotPath }], controller.signal);
|
|
587
|
+
}
|
|
588
|
+
children.delete(frame.executionId);
|
|
589
|
+
activeChildren.delete(child);
|
|
590
|
+
completed.set(frame.executionId, { executed: true, exitCode: 0,
|
|
591
|
+
stdout: browserResult.dom, stderr: '', screenshotPath: browserResult.screenshotPath || null,
|
|
592
|
+
cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
593
|
+
if (resumed.has(frame.executionId))
|
|
594
|
+
flushExecution(frame.executionId);
|
|
595
|
+
}).catch(error => {
|
|
596
|
+
children.delete(frame.executionId);
|
|
597
|
+
activeChildren.delete(child);
|
|
598
|
+
completed.set(frame.executionId, { executed: false, exitCode: null, stdout: '',
|
|
599
|
+
stderr: error instanceof Error ? error.message : 'browser_failed',
|
|
600
|
+
cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
601
|
+
if (resumed.has(frame.executionId))
|
|
602
|
+
flushExecution(frame.executionId);
|
|
603
|
+
});
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
606
|
+
if (operation === 'apply_patch') {
|
|
607
|
+
const patchChild = runWorkspacePatch({ patch: frame.patch, workspace,
|
|
608
|
+
allowDelete: (frame.sandbox || 'unrestricted') === 'unrestricted' }, result => {
|
|
609
|
+
children.delete(frame.executionId);
|
|
610
|
+
activeChildren.delete(child);
|
|
611
|
+
completed.set(frame.executionId, { ...result, cancelled: cancelledExecutions.delete(frame.executionId) });
|
|
612
|
+
if (resumed.has(frame.executionId))
|
|
613
|
+
flushExecution(frame.executionId);
|
|
614
|
+
});
|
|
615
|
+
const child = { pid: patchChild.pid,
|
|
616
|
+
write: chars => { patchChild.stdin?.write(chars); },
|
|
617
|
+
closeStdin: chars => { patchChild.stdin?.end(chars); },
|
|
618
|
+
resize: () => undefined,
|
|
619
|
+
terminate: () => { if (patchChild.pid)
|
|
620
|
+
try {
|
|
621
|
+
process.kill(-patchChild.pid, 'SIGTERM');
|
|
622
|
+
}
|
|
623
|
+
catch { /* exited */ } },
|
|
624
|
+
};
|
|
625
|
+
children.set(frame.executionId, child);
|
|
626
|
+
activeChildren.add(child);
|
|
627
|
+
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
628
|
+
return;
|
|
629
|
+
}
|
|
630
|
+
const child = await runCommand({ cmd: frame.cmd, workdir: frame.workdir || workspace,
|
|
631
|
+
workspace, sandbox: frame.sandbox || 'unrestricted', networkAllowed: frame.networkAllowed,
|
|
632
|
+
timeoutMs: frame.timeoutMs || 60_000, tty: frame.tty,
|
|
633
|
+
cols: frame.cols, rows: frame.rows,
|
|
634
|
+
executionId: frame.executionId }, result => {
|
|
635
|
+
children.delete(frame.executionId);
|
|
636
|
+
activeChildren.delete(child);
|
|
637
|
+
const { stdout, stderr, ...completion } = result;
|
|
638
|
+
completed.set(frame.executionId, { ...completion,
|
|
639
|
+
cancelled: cancelledExecutions.delete(frame.executionId), stdout: '', stderr: '' });
|
|
640
|
+
if (resumed.has(frame.executionId))
|
|
641
|
+
sendCurrent({ type: 'result', executionId: frame.executionId,
|
|
642
|
+
...completed.get(frame.executionId) });
|
|
643
|
+
}, (stream, text) => {
|
|
644
|
+
const chunks = outputByExecution.get(frame.executionId) || [];
|
|
645
|
+
const chunk = { sequence: chunks.length + 1, stream, text };
|
|
646
|
+
chunks.push(chunk);
|
|
647
|
+
outputByExecution.set(frame.executionId, chunks);
|
|
648
|
+
if (resumed.has(frame.executionId))
|
|
649
|
+
sendCurrent({ type: 'output', executionId: frame.executionId, ...chunk });
|
|
650
|
+
});
|
|
651
|
+
children.set(frame.executionId, child);
|
|
652
|
+
activeChildren.add(child);
|
|
653
|
+
send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
|
|
654
|
+
}
|
|
655
|
+
catch (error) {
|
|
656
|
+
resumed.delete(frame.executionId);
|
|
657
|
+
outputByExecution.delete(frame.executionId);
|
|
658
|
+
sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
|
|
659
|
+
executed: false, exitCode: null, stdout: '', stderr: error instanceof Error ? error.message : 'Command rejected.', timedOut: false });
|
|
660
|
+
}
|
|
661
|
+
}).catch(() => socket.terminate());
|
|
662
|
+
});
|
|
663
|
+
socket.on('close', (code, reason) => {
|
|
664
|
+
if (heartbeat)
|
|
665
|
+
clearInterval(heartbeat);
|
|
666
|
+
if (activeSocket === socket)
|
|
667
|
+
activeConnectionId = '';
|
|
668
|
+
resumed.clear();
|
|
669
|
+
if (code === 1008 && reason.toString() !== 'heartbeat_timeout') {
|
|
670
|
+
for (const child of children.values())
|
|
671
|
+
child.terminate();
|
|
672
|
+
}
|
|
673
|
+
else if (!stopping && children.size) {
|
|
674
|
+
reconnectGrace = setTimeout(() => {
|
|
675
|
+
for (const child of children.values())
|
|
676
|
+
child.terminate();
|
|
677
|
+
}, 120_000);
|
|
678
|
+
reconnectGrace.unref?.();
|
|
679
|
+
}
|
|
680
|
+
if (activeSocket === socket)
|
|
681
|
+
activeSocket = undefined;
|
|
682
|
+
if (code === 1008 && reason.toString() !== 'heartbeat_timeout')
|
|
683
|
+
reject(new Error(`Runner rejected by Realtime: ${reason.toString() || 'policy violation'}.`));
|
|
684
|
+
else
|
|
685
|
+
resolve();
|
|
686
|
+
});
|
|
687
|
+
socket.on('error', error => { console.error(`Realtime connection: ${error.message}`); });
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
catch (error) {
|
|
691
|
+
if (error instanceof Error && error.message.startsWith('Runner rejected by Realtime:'))
|
|
692
|
+
throw error;
|
|
693
|
+
console.error(error);
|
|
694
|
+
}
|
|
695
|
+
if (stopping)
|
|
696
|
+
break;
|
|
697
|
+
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
|
698
|
+
backoffMs = Math.min(backoffMs * 2, 30_000);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
finally {
|
|
702
|
+
stop();
|
|
703
|
+
process.off('SIGINT', stop);
|
|
704
|
+
process.off('SIGTERM', stop);
|
|
705
|
+
}
|
|
706
|
+
}
|
|
707
|
+
export async function handleTerminalCommand(argv) {
|
|
708
|
+
const command = argv[0] || 'help';
|
|
709
|
+
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]');
|
|
711
|
+
return;
|
|
712
|
+
}
|
|
713
|
+
if (command === 'service') {
|
|
714
|
+
const action = argv[1];
|
|
715
|
+
if (!action || action === 'help') {
|
|
716
|
+
console.log('revo terminal service install|uninstall --workspace PATH [--project NAME]');
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
if (action !== 'install' && action !== 'uninstall')
|
|
720
|
+
throw new Error('Use revo terminal service install|uninstall.');
|
|
721
|
+
const requestedWorkspace = option(argv, 'workspace');
|
|
722
|
+
if (!requestedWorkspace)
|
|
723
|
+
throw new Error('Terminal service requires --workspace PATH.');
|
|
724
|
+
const workspace = fs.existsSync(requestedWorkspace) ? fs.realpathSync(requestedWorkspace) : path.resolve(requestedWorkspace);
|
|
725
|
+
const envName = selectedProject(argv) || getActiveEnvironmentName();
|
|
726
|
+
if (action === 'uninstall') {
|
|
727
|
+
const result = uninstallTerminalService({ workspace, envName, configHome: process.env.XDG_CONFIG_HOME });
|
|
728
|
+
console.log(result.removed ? `Terminal service stopped and removed (${result.label}). Grant remains active.`
|
|
729
|
+
: `No terminal service installed for this workspace (${result.label}).`);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
if (!fs.existsSync(workspace))
|
|
733
|
+
throw new Error('Workspace does not exist.');
|
|
734
|
+
for (const unsupported of ['token', 'url', 'instance', 'realtime-url'])
|
|
735
|
+
if (option(argv, unsupported))
|
|
736
|
+
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
|
+
if (!saved?.token?.startsWith('sk-'))
|
|
739
|
+
throw new Error('A saved personal Revo API key is required. Run revo auth login or select a saved --project profile.');
|
|
740
|
+
const baseUrl = saved.baseUrl.replace(/\/$/, '');
|
|
741
|
+
const devices = readStore().devices.filter(item => item.workspace === workspace && item.baseUrl === baseUrl
|
|
742
|
+
&& (!saved.instance || item.instance === saved.instance));
|
|
743
|
+
if (devices.length !== 1)
|
|
744
|
+
throw new Error('Expected one registered terminal for this workspace and saved profile. Run revo terminal connect first.');
|
|
745
|
+
const device = devices[0];
|
|
746
|
+
const profile = { baseUrl, token: saved.token, instance: device.instance };
|
|
747
|
+
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
748
|
+
if (!listing.devices.some(item => item.agentTerminalId === device.agentTerminalId && item.status === 'approved'))
|
|
749
|
+
throw new Error('Terminal grant is not approved. Approve it in AI Agents → Terminals before installing the service.');
|
|
750
|
+
const result = installTerminalService({ workspace, envName, pathValue: process.env.PATH,
|
|
751
|
+
configHome: process.env.XDG_CONFIG_HOME });
|
|
752
|
+
console.log(result.installed ? `Terminal service installed and started (${result.label}).`
|
|
753
|
+
: `Terminal service already installed (${result.label}).`);
|
|
754
|
+
return;
|
|
755
|
+
}
|
|
756
|
+
const profile = resolveProfile(argv);
|
|
757
|
+
let me;
|
|
758
|
+
if (!profile.instance) {
|
|
759
|
+
const currentUser = await api(profile, 'GET', '/me');
|
|
760
|
+
me = currentUser;
|
|
761
|
+
profile.instance = currentUser.instance?.id;
|
|
762
|
+
if (!profile.instance)
|
|
763
|
+
throw new Error('The API key instance could not be resolved. Pass --instance.');
|
|
764
|
+
}
|
|
765
|
+
const workspace = fs.realpathSync(option(argv, 'workspace') || process.cwd());
|
|
766
|
+
const store = readStore();
|
|
767
|
+
let device = store.devices.find(item => item.workspace === workspace && item.baseUrl === profile.baseUrl && item.instance === profile.instance);
|
|
768
|
+
if (command === 'disconnect') {
|
|
769
|
+
if (!device) {
|
|
770
|
+
console.log('No local terminal registration for this workspace.');
|
|
771
|
+
return;
|
|
772
|
+
}
|
|
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
|
+
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
777
|
+
if (listing.devices.some(item => item.agentTerminalId === selectedDevice.agentTerminalId))
|
|
778
|
+
await api(profile, 'POST', `/agents/terminals/${selectedDevice.agentTerminalId}/revoke`);
|
|
779
|
+
store.devices = store.devices.filter(item => item !== selectedDevice);
|
|
780
|
+
saveStore(store);
|
|
781
|
+
console.log('Terminal registration removed.');
|
|
782
|
+
return;
|
|
783
|
+
}
|
|
784
|
+
if (command === 'status') {
|
|
785
|
+
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
786
|
+
console.log(JSON.stringify({ devices: listing.devices.map(item => ({ agentTerminalId: item.agentTerminalId, status: item.status, mode: item.mode })) }, null, 2));
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
if (command !== 'connect')
|
|
790
|
+
throw new Error(`Unknown command: ${command}`);
|
|
791
|
+
if (process.platform !== 'darwin' && process.platform !== 'linux')
|
|
792
|
+
throw new Error('Runner supports macOS and Linux.');
|
|
793
|
+
if (device) {
|
|
794
|
+
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
795
|
+
if (!listing.devices.some(item => item.agentTerminalId === device.agentTerminalId && item.status !== 'revoked')) {
|
|
796
|
+
store.devices = store.devices.filter(item => item !== device);
|
|
797
|
+
saveStore(store);
|
|
798
|
+
device = undefined;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
if (!device) {
|
|
802
|
+
const currentUser = me || await api(profile, 'GET', '/me');
|
|
803
|
+
const rt = option(argv, 'realtime-url') || profile.realtimeUrl || currentUser.instance?.endpoints?.realtime;
|
|
804
|
+
if (!rt)
|
|
805
|
+
throw new Error('Realtime endpoint unavailable. Pass --realtime-url.');
|
|
806
|
+
const secret = randomBytes(32).toString('hex');
|
|
807
|
+
device = { agentTerminalId: randomUUID(), secret, workspace, name: option(argv, 'name') || os.hostname(),
|
|
808
|
+
baseUrl: profile.baseUrl, instance: profile.instance, realtimeUrl: realtimeUrl(rt) };
|
|
809
|
+
await api(profile, 'POST', '/agents/terminals/pair', { agentTerminalId: device.agentTerminalId,
|
|
810
|
+
secretHash: createHash('sha256').update(Buffer.from(secret, 'hex')).digest('hex'),
|
|
811
|
+
name: device.name, workspace });
|
|
812
|
+
store.devices.push(device);
|
|
813
|
+
saveStore(store);
|
|
814
|
+
console.log(`Pending approval in AI Agents → Terminals: ${device.name} (${device.agentTerminalId}).`);
|
|
815
|
+
}
|
|
816
|
+
for (;;) {
|
|
817
|
+
const listing = await api(profile, 'GET', '/agents/terminals');
|
|
818
|
+
const grant = listing.devices.find(item => item.agentTerminalId === device.agentTerminalId);
|
|
819
|
+
if (grant?.status === 'approved')
|
|
820
|
+
break;
|
|
821
|
+
if (!grant || grant.status === 'revoked')
|
|
822
|
+
throw new Error('Terminal grant revoked or missing.');
|
|
823
|
+
await new Promise(resolve => setTimeout(resolve, 2_000));
|
|
824
|
+
}
|
|
825
|
+
await connect(profile, device);
|
|
826
|
+
}
|