@revoengine/cli 1.0.11 → 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.
Files changed (81) hide show
  1. package/README.md +275 -479
  2. package/dist/src/cli.js +71 -5
  3. package/dist/src/client.d.ts +28 -12
  4. package/dist/src/client.js +234 -66
  5. package/dist/src/commands/component.d.ts +67 -0
  6. package/dist/src/commands/component.js +299 -27
  7. package/dist/src/commands/database-tables.d.ts +2 -0
  8. package/dist/src/commands/{database-schemas.js → database-tables.js} +21 -40
  9. package/dist/src/commands/database-views.js +21 -18
  10. package/dist/src/commands/endpoints.js +26 -16
  11. package/dist/src/commands/events.js +18 -20
  12. package/dist/src/commands/groups.js +13 -22
  13. package/dist/src/commands/index.d.ts +2 -1
  14. package/dist/src/commands/index.js +2 -1
  15. package/dist/src/commands/job-templates.js +21 -15
  16. package/dist/src/commands/metadata.js +58 -15
  17. package/dist/src/commands/migrate.d.ts +6 -0
  18. package/dist/src/commands/migrate.js +658 -0
  19. package/dist/src/commands/project.js +4 -4
  20. package/dist/src/commands/role-groups.js +14 -25
  21. package/dist/src/commands/schedules.js +19 -20
  22. package/dist/src/commands/terminal-browser.d.ts +16 -0
  23. package/dist/src/commands/terminal-browser.js +92 -0
  24. package/dist/src/commands/terminal-image.d.ts +7 -0
  25. package/dist/src/commands/terminal-image.js +40 -0
  26. package/dist/src/commands/terminal-patch-worker.d.ts +1 -0
  27. package/dist/src/commands/terminal-patch-worker.js +24 -0
  28. package/dist/src/commands/terminal-patch.d.ts +2 -0
  29. package/dist/src/commands/terminal-patch.js +156 -0
  30. package/dist/src/commands/terminal-sandbox.d.ts +8 -0
  31. package/dist/src/commands/terminal-sandbox.js +87 -0
  32. package/dist/src/commands/terminal-service.js +2 -2
  33. package/dist/src/commands/terminal.d.ts +31 -4
  34. package/dist/src/commands/terminal.js +360 -45
  35. package/dist/src/component-lock.d.ts +12 -2
  36. package/dist/src/component-lock.js +60 -1
  37. package/dist/src/diff-details.d.ts +8 -0
  38. package/dist/src/diff-details.js +152 -0
  39. package/dist/src/env-sync.js +8 -6
  40. package/dist/src/http-trace.d.ts +94 -0
  41. package/dist/src/http-trace.js +226 -0
  42. package/dist/src/metadata-backfill.d.ts +5 -4
  43. package/dist/src/metadata-backfill.js +82 -158
  44. package/dist/src/migration.d.ts +141 -0
  45. package/dist/src/migration.js +1632 -0
  46. package/dist/src/resource-inventory.d.ts +28 -0
  47. package/dist/src/resource-inventory.js +85 -0
  48. package/dist/src/resource-syncs/{database-schema-sync.d.ts → database-table-sync.d.ts} +13 -3
  49. package/dist/src/resource-syncs/{database-schema-sync.js → database-table-sync.js} +147 -62
  50. package/dist/src/resource-syncs/database-view-sync.d.ts +24 -2
  51. package/dist/src/resource-syncs/database-view-sync.js +156 -68
  52. package/dist/src/resource-syncs/endpoint-sync.d.ts +27 -0
  53. package/dist/src/resource-syncs/endpoint-sync.js +362 -82
  54. package/dist/src/resource-syncs/event-sync.d.ts +27 -0
  55. package/dist/src/resource-syncs/event-sync.js +123 -26
  56. package/dist/src/resource-syncs/group-sync.d.ts +7 -0
  57. package/dist/src/resource-syncs/group-sync.js +60 -14
  58. package/dist/src/resource-syncs/job-template-sync.d.ts +21 -0
  59. package/dist/src/resource-syncs/job-template-sync.js +91 -30
  60. package/dist/src/resource-syncs/role-group-sync.d.ts +7 -0
  61. package/dist/src/resource-syncs/role-group-sync.js +47 -9
  62. package/dist/src/resource-syncs/schedule-sync.d.ts +30 -1
  63. package/dist/src/resource-syncs/schedule-sync.js +114 -20
  64. package/dist/src/resource-syncs/util.d.ts +3 -0
  65. package/dist/src/resource-syncs/util.js +8 -6
  66. package/dist/src/resource-target.d.ts +11 -0
  67. package/dist/src/resource-target.js +48 -0
  68. package/dist/src/sync-output.d.ts +29 -1
  69. package/dist/src/sync-output.js +139 -2
  70. package/dist/src/tracked-resources.d.ts +1 -1
  71. package/dist/src/tracked-resources.js +8 -6
  72. package/dist/src/types.d.ts +3 -0
  73. package/dist/src/ui.js +18 -9
  74. package/dist/src/utils.d.ts +2 -0
  75. package/dist/src/utils.js +17 -0
  76. package/dist/src/workspace-diff.d.ts +25 -0
  77. package/dist/src/workspace-diff.js +75 -0
  78. package/package.json +9 -6
  79. package/dist/src/commands/database-schemas.d.ts +0 -2
  80. /package/dist/src/{database-schema-artifacts.d.ts → database-table-artifacts.d.ts} +0 -0
  81. /package/dist/src/{database-schema-artifacts.js → database-table-artifacts.js} +0 -0
@@ -44,7 +44,7 @@ export function renderTerminalSystemdUnit(options) {
44
44
  if (!entrypoint || !path.isAbsolute(node) || !path.isAbsolute(entrypoint))
45
45
  throw new Error('Cannot resolve absolute Node.js and revo executable paths for systemd.');
46
46
  const args = [node, entrypoint, 'terminal', 'connect', '--workspace', options.workspace,
47
- ...(options.envName && options.envName !== 'default' ? ['--env', options.envName] : [])];
47
+ ...(options.envName && options.envName !== 'default' ? ['--project', options.envName] : [])];
48
48
  const env = [
49
49
  ...(options.pathValue ? [`Environment=${systemdQuote(`PATH=${options.pathValue}`)}`] : []),
50
50
  ...(options.configHome ? [`Environment=${systemdQuote(`XDG_CONFIG_HOME=${options.configHome}`)}`] : []),
@@ -58,7 +58,7 @@ export function renderTerminalServicePlist(options) {
58
58
  if (!entrypoint || !path.isAbsolute(node) || !path.isAbsolute(entrypoint))
59
59
  throw new Error('Cannot resolve absolute Node.js and revo executable paths for LaunchAgent.');
60
60
  const args = [node, entrypoint, 'terminal', 'connect', '--workspace', options.workspace,
61
- ...(options.envName && options.envName !== 'default' ? ['--env', options.envName] : [])];
61
+ ...(options.envName && options.envName !== 'default' ? ['--project', options.envName] : [])];
62
62
  const lines = args.map(arg => ` <string>${xml(arg)}</string>`).join('\n');
63
63
  const env = [];
64
64
  if (options.pathValue)
@@ -1,4 +1,23 @@
1
1
  import { type ChildProcess } from 'node:child_process';
2
+ import { type TerminalSandbox } from './terminal-sandbox.ts';
3
+ export declare const MAX_TERMINAL_PROCESS_MS: number;
4
+ type CommandResult = {
5
+ executed: boolean;
6
+ exitCode: number | null;
7
+ stdout: string;
8
+ stderr: string;
9
+ timedOut: boolean;
10
+ truncated: boolean;
11
+ logTruncated: boolean;
12
+ logPath: string;
13
+ };
14
+ export type RunningProcess = {
15
+ pid: number | undefined;
16
+ write: (chars: string) => void;
17
+ closeStdin: (chars: string) => void;
18
+ resize: (cols: number, rows: number) => void;
19
+ terminate: () => void;
20
+ };
2
21
  export declare function childEnvironment(source: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
3
22
  export declare function resolveWorkspaceDirectory(root: string, requested: string): string;
4
23
  export declare function boundResultFrame(frame: Record<string, unknown>): Record<string, unknown>;
@@ -7,16 +26,24 @@ export declare function runCommand(input: {
7
26
  workdir: string;
8
27
  workspace: string;
9
28
  timeoutMs: number;
29
+ sandbox?: TerminalSandbox;
30
+ networkAllowed?: boolean;
31
+ tty?: boolean;
32
+ cols?: number;
33
+ rows?: number;
10
34
  executionId?: string;
11
35
  logDir?: string;
36
+ }, onDone: (result: CommandResult) => void, onChunk?: (stream: 'stdout' | 'stderr', text: string) => void): Promise<RunningProcess>;
37
+ export declare function runWorkspacePatch(input: {
38
+ patch: string;
39
+ workspace: string;
40
+ allowDelete: boolean;
12
41
  }, onDone: (result: {
13
42
  executed: boolean;
14
43
  exitCode: number | null;
15
44
  stdout: string;
16
45
  stderr: string;
17
46
  timedOut: boolean;
18
- truncated: boolean;
19
- logTruncated: boolean;
20
- logPath: string;
21
- }) => void, onChunk?: (stream: 'stdout' | 'stderr', text: string) => void): Promise<ChildProcess>;
47
+ }) => void): ChildProcess;
22
48
  export declare function handleTerminalCommand(argv: string[]): Promise<void>;
49
+ export {};
@@ -1,12 +1,18 @@
1
1
  import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
5
6
  import { spawn } from 'node:child_process';
7
+ import * as pty from 'node-pty';
6
8
  import WebSocket from 'ws';
7
9
  import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
8
10
  import { promptConfirm } from "../prompt.js";
9
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;
10
16
  const configDir = getConfigDir;
11
17
  const runnerConfig = () => path.join(configDir(), 'runner.json');
12
18
  const MAX_MODEL_OUTPUT_BYTES = 100_000;
@@ -85,11 +91,21 @@ function option(argv, name) {
85
91
  return argv[index + 1];
86
92
  return argv.find(value => value.startsWith(`--${name}=`))?.slice(name.length + 3);
87
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
+ }
88
104
  function resolveProfile(argv) {
89
105
  const urlOverride = option(argv, 'url');
90
106
  const tokenOverride = option(argv, 'token');
91
107
  const configured = resolveRuntimeConfig({ baseUrl: urlOverride,
92
- token: tokenOverride, instance: option(argv, 'instance'), envName: option(argv, 'env') });
108
+ token: tokenOverride, instance: option(argv, 'instance'), envName: selectedProject(argv) });
93
109
  const token = configured.token;
94
110
  if (!token || !token.startsWith('sk-'))
95
111
  throw new Error('A personal Revo API key is required. Run revo auth login or select a CLI profile.');
@@ -156,6 +172,20 @@ function sendResult(socket, frame) {
156
172
  }
157
173
  export async function runCommand(input, onDone, onChunk) {
158
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
+ }
159
189
  const directory = input.logDir || logDirectory();
160
190
  const logPath = path.join(directory, `${input.executionId || randomUUID()}.log`);
161
191
  let logFd;
@@ -166,9 +196,31 @@ export async function runCommand(input, onDone, onChunk) {
166
196
  catch (error) {
167
197
  console.error(`Runner log unavailable: ${error.message}`);
168
198
  }
169
- const child = spawn(process.platform === 'darwin' ? '/bin/zsh' : '/bin/sh', ['-lc', input.cmd], {
170
- cwd: workdir, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: childEnvironment(process.env),
171
- });
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
+ }
172
224
  let stdout = '';
173
225
  let stderr = '';
174
226
  let modelBytes = 0;
@@ -177,13 +229,35 @@ export async function runCommand(input, onDone, onChunk) {
177
229
  let logTruncated = logFd === undefined;
178
230
  let timedOut = false;
179
231
  let finished = false;
180
- const terminate = () => { if (child.pid) {
232
+ const pid = child?.pid || terminal?.pid;
233
+ const terminate = () => {
234
+ if (!pid)
235
+ return;
181
236
  try {
182
- process.kill(-child.pid, 'SIGKILL');
237
+ process.kill(-pid, 'SIGTERM');
238
+ }
239
+ catch {
240
+ try {
241
+ process.kill(pid, 'SIGTERM');
242
+ }
243
+ catch { /* exited */ }
183
244
  }
184
- catch { /* exited */ }
185
- } };
186
- const timer = setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), 600_000));
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));
187
261
  const append = (chunk, kind) => {
188
262
  const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
189
263
  if (logPart.length && logFd !== undefined) {
@@ -224,13 +298,20 @@ export async function runCommand(input, onDone, onChunk) {
224
298
  onChunk(kind, text.slice(offset, offset + OUTPUT_FRAME_CHARS));
225
299
  }
226
300
  };
227
- child.stdout?.on('data', (chunk) => append(chunk, 'stdout'));
228
- child.stderr?.on('data', (chunk) => append(chunk, 'stderr'));
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'));
229
304
  const finish = (exitCode, error) => {
230
305
  if (finished)
231
306
  return;
232
307
  finished = true;
233
308
  clearTimeout(timer);
309
+ if (scratch) {
310
+ try {
311
+ fs.rmSync(scratch, { recursive: true, force: true });
312
+ }
313
+ catch { /* temporary cleanup */ }
314
+ }
234
315
  if (logFd !== undefined) {
235
316
  try {
236
317
  fs.closeSync(logFd);
@@ -239,9 +320,71 @@ export async function runCommand(input, onDone, onChunk) {
239
320
  logTruncated = true;
240
321
  }
241
322
  }
242
- onDone({ executed: !error, exitCode, stdout, stderr: error ? `${stderr}\n${error.message}` : stderr,
323
+ onDone({ executed: !error, exitCode: timedOut && exitCode === 0 ? null : exitCode,
324
+ stdout, stderr: error ? `${stderr}\n${error.message}` : stderr,
243
325
  timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath });
244
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
+ };
245
388
  child.on('close', code => finish(code));
246
389
  child.on('error', error => finish(null, error));
247
390
  return child;
@@ -250,27 +393,42 @@ async function connect(profile, device) {
250
393
  let backoffMs = 1_000;
251
394
  let stopping = false;
252
395
  let activeSocket;
396
+ let activeConnectionId = '';
253
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
+ };
254
417
  const stop = () => {
255
418
  stopping = true;
419
+ if (reconnectGrace)
420
+ clearTimeout(reconnectGrace);
256
421
  if (activeSocket?.readyState === WebSocket.CONNECTING)
257
422
  activeSocket.terminate();
258
423
  else
259
424
  activeSocket?.close();
260
425
  for (const child of activeChildren)
261
- if (child.pid) {
262
- try {
263
- process.kill(-child.pid, 'SIGKILL');
264
- }
265
- catch { /* exited */ }
266
- }
426
+ child.terminate();
267
427
  };
268
428
  process.on('SIGINT', stop);
269
429
  process.on('SIGTERM', stop);
270
430
  try {
271
431
  while (!stopping) {
272
- const children = new Map();
273
- const cancelledExecutions = new Set();
274
432
  try {
275
433
  await new Promise((resolve, reject) => {
276
434
  const socket = new WebSocket(device.realtimeUrl, {
@@ -284,7 +442,10 @@ async function connect(profile, device) {
284
442
  let heartbeat;
285
443
  let lastHeartbeat = Date.now();
286
444
  let incoming = Promise.resolve();
287
- socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId, secret: device.secret }));
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'] : [])] }));
288
449
  socket.on('message', raw => {
289
450
  incoming = incoming.then(async () => {
290
451
  if (stopping || socket.readyState !== WebSocket.OPEN)
@@ -292,9 +453,16 @@ async function connect(profile, device) {
292
453
  const frame = JSON.parse(raw.toString());
293
454
  if (frame.type === 'ready' && frame.connectionId) {
294
455
  connectionId = frame.connectionId;
456
+ activeConnectionId = connectionId;
295
457
  workspace = frame.workspace || device.workspace;
296
458
  backoffMs = 1_000;
459
+ if (reconnectGrace) {
460
+ clearTimeout(reconnectGrace);
461
+ reconnectGrace = undefined;
462
+ }
297
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 });
298
466
  heartbeat = setInterval(() => {
299
467
  if (Date.now() - lastHeartbeat > 45_000) {
300
468
  socket.terminate();
@@ -310,39 +478,183 @@ async function connect(profile, device) {
310
478
  }
311
479
  if (frame.connectionId !== connectionId || !frame.executionId)
312
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
+ }
313
494
  if (frame.type === 'cancel') {
314
495
  const child = children.get(frame.executionId);
315
- if (child?.pid) {
496
+ if (child) {
316
497
  cancelledExecutions.add(frame.executionId);
317
- try {
318
- process.kill(-child.pid, 'SIGKILL');
319
- }
320
- catch { /* exited */ }
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);
321
510
  }
322
511
  return;
323
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
+ }
324
520
  if (frame.type !== 'execute')
325
521
  return;
326
- if (typeof frame.cmd !== 'string' || !frame.cmd.trim() || frame.cmd.length > 8_192 || children.size >= 4) {
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)) {
327
540
  sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
328
541
  executed: false, exitCode: null, stdout: '', stderr: children.size >= 4 ? 'runner_busy' : 'invalid_command', timedOut: false });
329
542
  return;
330
543
  }
331
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
+ }
332
630
  const child = await runCommand({ cmd: frame.cmd, workdir: frame.workdir || workspace,
333
- workspace, timeoutMs: frame.timeoutMs || 60_000, executionId: frame.executionId }, result => {
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 => {
334
635
  children.delete(frame.executionId);
335
636
  activeChildren.delete(child);
336
637
  const { stdout, stderr, ...completion } = result;
337
- send(socket, { type: 'result', connectionId, executionId: frame.executionId,
338
- ...completion, cancelled: cancelledExecutions.delete(frame.executionId), stdout: '', stderr: '' });
339
- }, (stream, text) => send(socket, { type: 'output', connectionId,
340
- executionId: frame.executionId, stream, text }));
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
+ });
341
651
  children.set(frame.executionId, child);
342
652
  activeChildren.add(child);
343
653
  send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
344
654
  }
345
655
  catch (error) {
656
+ resumed.delete(frame.executionId);
657
+ outputByExecution.delete(frame.executionId);
346
658
  sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
347
659
  executed: false, exitCode: null, stdout: '', stderr: error instanceof Error ? error.message : 'Command rejected.', timedOut: false });
348
660
  }
@@ -351,17 +663,20 @@ async function connect(profile, device) {
351
663
  socket.on('close', (code, reason) => {
352
664
  if (heartbeat)
353
665
  clearInterval(heartbeat);
354
- for (const child of children.values())
355
- if (child.pid) {
356
- try {
357
- process.kill(-child.pid, 'SIGKILL');
358
- }
359
- catch { /* exited */ }
360
- }
361
- for (const child of children.values())
362
- activeChildren.delete(child);
363
- children.clear();
364
- cancelledExecutions.clear();
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
+ }
365
680
  if (activeSocket === socket)
366
681
  activeSocket = undefined;
367
682
  if (code === 1008 && reason.toString() !== 'heartbeat_timeout')
@@ -407,7 +722,7 @@ export async function handleTerminalCommand(argv) {
407
722
  if (!requestedWorkspace)
408
723
  throw new Error('Terminal service requires --workspace PATH.');
409
724
  const workspace = fs.existsSync(requestedWorkspace) ? fs.realpathSync(requestedWorkspace) : path.resolve(requestedWorkspace);
410
- const envName = option(argv, 'env') || getActiveEnvironmentName();
725
+ const envName = selectedProject(argv) || getActiveEnvironmentName();
411
726
  if (action === 'uninstall') {
412
727
  const result = uninstallTerminalService({ workspace, envName, configHome: process.env.XDG_CONFIG_HOME });
413
728
  console.log(result.removed ? `Terminal service stopped and removed (${result.label}). Grant remains active.`
@@ -455,7 +770,7 @@ export async function handleTerminalCommand(argv) {
455
770
  console.log('No local terminal registration for this workspace.');
456
771
  return;
457
772
  }
458
- if (terminalServiceInstalled(workspace, option(argv, 'env') || getActiveEnvironmentName()))
773
+ if (terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName()))
459
774
  throw new Error('Uninstall the terminal service before revoking this terminal grant.');
460
775
  const selectedDevice = device;
461
776
  const listing = await api(profile, 'GET', '/agents/terminals');