@revoengine/cli 1.0.14 → 1.0.16

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 (58) hide show
  1. package/README.md +57 -21
  2. package/dist/src/cli.js +5 -1
  3. package/dist/src/client.d.ts +25 -14
  4. package/dist/src/client.js +67 -34
  5. package/dist/src/commands/component.js +1 -0
  6. package/dist/src/commands/env.js +1 -5
  7. package/dist/src/commands/index.d.ts +1 -0
  8. package/dist/src/commands/index.js +1 -0
  9. package/dist/src/commands/migrate.js +12 -2
  10. package/dist/src/commands/service-accounts.d.ts +2 -0
  11. package/dist/src/commands/service-accounts.js +149 -0
  12. package/dist/src/commands/terminal-browser.d.ts +29 -1
  13. package/dist/src/commands/terminal-browser.js +165 -34
  14. package/dist/src/commands/terminal-file.d.ts +21 -0
  15. package/dist/src/commands/terminal-file.js +160 -0
  16. package/dist/src/commands/terminal-operational-log.js +2 -2
  17. package/dist/src/commands/terminal-policy.d.ts +11 -2
  18. package/dist/src/commands/terminal-policy.js +27 -2
  19. package/dist/src/commands/terminal-pty.js +2 -0
  20. package/dist/src/commands/terminal-reconnect-grace.d.ts +19 -0
  21. package/dist/src/commands/terminal-reconnect-grace.js +59 -1
  22. package/dist/src/commands/terminal-sandbox.js +7 -0
  23. package/dist/src/commands/terminal-secure-browser.d.ts +1 -0
  24. package/dist/src/commands/terminal-secure-browser.js +2 -1
  25. package/dist/src/commands/terminal-service.d.ts +4 -3
  26. package/dist/src/commands/terminal-service.js +23 -19
  27. package/dist/src/commands/terminal.d.ts +29 -1
  28. package/dist/src/commands/terminal.js +508 -107
  29. package/dist/src/component-lock.d.ts +4 -0
  30. package/dist/src/component-lock.js +21 -2
  31. package/dist/src/config.d.ts +0 -3
  32. package/dist/src/config.js +0 -2
  33. package/dist/src/metadata-backfill.js +50 -1
  34. package/dist/src/migration.d.ts +10 -2
  35. package/dist/src/migration.js +159 -69
  36. package/dist/src/resource-inventory.d.ts +3 -2
  37. package/dist/src/resource-inventory.js +6 -1
  38. package/dist/src/resource-syncs/account-principal.d.ts +22 -0
  39. package/dist/src/resource-syncs/account-principal.js +86 -0
  40. package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
  41. package/dist/src/resource-syncs/database-view-sync.js +1 -12
  42. package/dist/src/resource-syncs/group-sync.d.ts +10 -0
  43. package/dist/src/resource-syncs/group-sync.js +92 -20
  44. package/dist/src/resource-syncs/identity-migration.d.ts +19 -0
  45. package/dist/src/resource-syncs/identity-migration.js +108 -0
  46. package/dist/src/resource-syncs/job-template-sync.d.ts +4 -0
  47. package/dist/src/resource-syncs/job-template-sync.js +55 -12
  48. package/dist/src/resource-syncs/service-account-sync.d.ts +98 -0
  49. package/dist/src/resource-syncs/service-account-sync.js +620 -0
  50. package/dist/src/sync-output.js +3 -0
  51. package/dist/src/tracked-resources.d.ts +1 -1
  52. package/dist/src/tracked-resources.js +5 -1
  53. package/dist/src/types.d.ts +12 -0
  54. package/dist/src/ui.js +4 -1
  55. package/dist/src/workspace-diff.d.ts +1 -0
  56. package/dist/src/workspace-diff.js +4 -1
  57. package/package.json +6 -5
  58. package/scripts/ensure-pty-helper.mjs +0 -9
@@ -6,16 +6,49 @@ import { createHash, randomBytes, randomUUID } from 'node:crypto';
6
6
  import { spawn } from 'node:child_process';
7
7
  import WebSocket from 'ws';
8
8
  import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
9
- import { promptConfirm } from "../prompt.js";
10
9
  import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
11
10
  import { createSandboxScratchDirectory, isTerminalSandbox, sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
12
- import { executionPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
13
- import { closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
11
+ import { executionAllowedByGrant, executionPolicyDeadline, remainingPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
12
+ import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
13
+ import { transferWorkspaceFile, validateFileTransfer } from "./terminal-file.js";
14
14
  import { uploadWorkspaceImages } from "./terminal-image.js";
15
15
  import { ensurePtyHelperExecutable, normalizePtyStartError } from "./terminal-pty.js";
16
- import { TerminalReconnectGrace } from "./terminal-reconnect-grace.js";
16
+ import { TerminalReconnectGrace, TerminalTransportRecovery, isRunnerTransportHeartbeat } from "./terminal-reconnect-grace.js";
17
17
  import { TerminalOperationalLog } from "./terminal-operational-log.js";
18
18
  import { createSecureBrowserIdentity, decryptSecureBrowserInput } from "./terminal-secure-browser.js";
19
+ class TerminalRunnerFatalError extends Error {
20
+ }
21
+ export function selectRegisteredTerminal(devices, grants, name, terminalId) {
22
+ const matching = devices.filter(device => terminalId
23
+ ? device.agentTerminalId === terminalId : device.name === name);
24
+ const statuses = new Map(grants.map(grant => [grant.agentTerminalId, grant.status]));
25
+ for (const status of ['approved', 'pending']) {
26
+ const candidates = matching.filter(device => statuses.get(device.agentTerminalId) === status);
27
+ if (candidates.length > 1)
28
+ throw new Error(`Multiple ${status} terminals match ${name} (${candidates.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
29
+ if (candidates.length)
30
+ return candidates[0];
31
+ }
32
+ return undefined;
33
+ }
34
+ function terminalSelector(argv) {
35
+ const named = argv.includes('--name') || argv.some(value => value.startsWith('--name='));
36
+ const identified = argv.includes('--terminal-id') || argv.some(value => value.startsWith('--terminal-id='));
37
+ const requestedName = option(argv, 'name');
38
+ const requestedId = option(argv, 'terminal-id');
39
+ if (named && (!requestedName || requestedName.startsWith('--'))
40
+ || identified && (!requestedId || requestedId.startsWith('--')))
41
+ throw new Error('--name and --terminal-id require a value.');
42
+ const name = requestedName ?? os.hostname();
43
+ const terminalId = requestedId?.toLowerCase();
44
+ if (identified && named)
45
+ throw new Error('Use either --name or --terminal-id, not both.');
46
+ if (!name.trim() || name.length > 128 || name !== name.trim() || /[\u0000-\u001f\u007f]/u.test(name))
47
+ throw new Error('--name must be a nonempty terminal name of at most 128 characters.');
48
+ 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))
49
+ throw new Error('--terminal-id must be a terminal UUID.');
50
+ return { name, terminalId };
51
+ }
19
52
  export const MAX_TERMINAL_PROCESS_MS = 59 * 60_000;
20
53
  const configDir = getConfigDir;
21
54
  const runnerConfig = () => path.join(configDir(), 'runner.json');
@@ -26,7 +59,8 @@ const LOG_RETENTION_MS = 24 * 60 * 60 * 1_000;
26
59
  const OPERATIONAL_ERROR_CODES = new Set([
27
60
  'browser_binary_unavailable', 'browser_cancelled', 'browser_failed', 'browser_localhost_only',
28
61
  'browser_local_network_guard_unavailable',
29
- 'browser_session_missing', 'browser_session_limit', 'browser_selector_missing', 'browser_selector_ambiguous',
62
+ 'browser_session_missing', 'browser_session_limit', 'browser_tab_missing', 'browser_tab_limit',
63
+ 'invalid_browser_tab', 'browser_selector_missing', 'browser_selector_ambiguous',
30
64
  'browser_secret_input_requires_secure_reference', 'browser_full_page_too_large',
31
65
  'browser_element_too_large', 'browser_screenshot_too_large', 'browser_output_outside_workspace',
32
66
  'browser_image_upload_unavailable', 'destructive_command_requires_approval',
@@ -94,6 +128,113 @@ function saveStore(store) {
94
128
  }
95
129
  }
96
130
  }
131
+ async function updateStore(update) {
132
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
133
+ const lock = `${runnerConfig()}.lock`;
134
+ const deadline = Date.now() + 10_000;
135
+ let descriptor;
136
+ while (descriptor === undefined) {
137
+ try {
138
+ descriptor = fs.openSync(lock, 'wx', 0o600);
139
+ try {
140
+ fs.writeFileSync(descriptor, String(process.pid));
141
+ }
142
+ catch (error) {
143
+ fs.closeSync(descriptor);
144
+ fs.unlinkSync(lock);
145
+ throw error;
146
+ }
147
+ }
148
+ catch (error) {
149
+ if (error.code !== 'EEXIST')
150
+ throw error;
151
+ try {
152
+ const age = Date.now() - fs.statSync(lock).mtimeMs;
153
+ if (age > 120_000) {
154
+ const pid = Number(fs.readFileSync(lock, 'utf8'));
155
+ let alive = Number.isSafeInteger(pid) && pid > 0;
156
+ if (alive)
157
+ try {
158
+ process.kill(pid, 0);
159
+ }
160
+ catch (probeError) {
161
+ if (probeError.code === 'ESRCH')
162
+ alive = false;
163
+ }
164
+ if (!alive) {
165
+ fs.unlinkSync(lock);
166
+ continue;
167
+ }
168
+ }
169
+ }
170
+ catch (statError) {
171
+ if (statError.code !== 'ENOENT')
172
+ throw statError;
173
+ }
174
+ if (Date.now() >= deadline)
175
+ throw new Error('Terminal registration store is busy. Retry the command.');
176
+ await new Promise(resolve => setTimeout(resolve, 50));
177
+ }
178
+ }
179
+ try {
180
+ const current = readStore();
181
+ update(current);
182
+ saveStore(current);
183
+ }
184
+ finally {
185
+ fs.closeSync(descriptor);
186
+ fs.unlinkSync(lock);
187
+ }
188
+ }
189
+ export function acquireRunnerLock(agentTerminalId) {
190
+ fs.mkdirSync(configDir(), { recursive: true, mode: 0o700 });
191
+ const lock = path.join(configDir(), `runner-${agentTerminalId}.lock`);
192
+ let descriptor;
193
+ for (;;) {
194
+ try {
195
+ descriptor = fs.openSync(lock, 'wx', 0o600);
196
+ break;
197
+ }
198
+ catch (error) {
199
+ if (error.code !== 'EEXIST')
200
+ throw error;
201
+ let pid;
202
+ try {
203
+ pid = Number(fs.readFileSync(lock, 'utf8'));
204
+ }
205
+ catch (readError) {
206
+ if (readError.code === 'ENOENT')
207
+ continue;
208
+ throw readError;
209
+ }
210
+ if ((!Number.isSafeInteger(pid) || pid <= 0) && Date.now() - fs.statSync(lock).mtimeMs > 5_000) {
211
+ fs.unlinkSync(lock);
212
+ continue;
213
+ }
214
+ if (Number.isSafeInteger(pid) && pid > 0) {
215
+ try {
216
+ process.kill(pid, 0);
217
+ }
218
+ catch (probeError) {
219
+ if (probeError.code === 'ESRCH') {
220
+ fs.unlinkSync(lock);
221
+ continue;
222
+ }
223
+ }
224
+ }
225
+ throw new Error(`Terminal ${agentTerminalId} is already connected by another local CLI process. Use a different --name or --terminal-id.`);
226
+ }
227
+ }
228
+ try {
229
+ fs.writeFileSync(descriptor, String(process.pid));
230
+ }
231
+ catch (error) {
232
+ fs.closeSync(descriptor);
233
+ fs.unlinkSync(lock);
234
+ throw error;
235
+ }
236
+ return () => { fs.closeSync(descriptor); fs.unlinkSync(lock); };
237
+ }
97
238
  export function resolveWorkspaceDirectory(root, requested) {
98
239
  const workspace = fs.realpathSync(root);
99
240
  const workdir = fs.realpathSync(requested);
@@ -128,7 +269,7 @@ function resolveProfile(argv) {
128
269
  throw new Error('A personal Revo API key is required. Run revo auth login or select a CLI profile.');
129
270
  return { baseUrl: configured.baseUrl.replace(/\/$/, ''), token,
130
271
  instance: option(argv, 'instance') || (urlOverride || tokenOverride ? undefined : configured.instance),
131
- realtimeUrl: option(argv, 'realtime-url'), production: configured.production };
272
+ realtimeUrl: option(argv, 'realtime-url') };
132
273
  }
133
274
  function apiUrl(profile, route) {
134
275
  const base = profile.baseUrl.replace(/\/(?:api\/)?v1\/?$/, '');
@@ -138,12 +279,6 @@ function apiUrl(profile, route) {
138
279
  return `${base}/api/v1${route}`;
139
280
  }
140
281
  async function api(profile, method, route, body) {
141
- if (profile.production && !profile.productionWriteConfirmed && ['POST', 'PUT', 'PATCH', 'DELETE'].includes(method)) {
142
- const confirmed = await promptConfirm(`PRODUCTION: send ${method} ${apiUrl(profile, route)}?`, false);
143
- if (!confirmed)
144
- throw new Error('Production write cancelled. Confirm the operation in an interactive terminal.');
145
- profile.productionWriteConfirmed = true;
146
- }
147
282
  const response = await fetch(apiUrl(profile, route), {
148
283
  method,
149
284
  redirect: 'manual',
@@ -155,6 +290,8 @@ async function api(profile, method, route, body) {
155
290
  if (response.status >= 300 && response.status < 400)
156
291
  throw new Error(`Revo API ${method} ${route} redirected; refusing to forward credentials.`);
157
292
  const value = await response.json().catch(() => ({}));
293
+ if ([401, 403].includes(response.status))
294
+ throw new TerminalRunnerFatalError('Terminal authentication or authorization was rejected. Renew the CLI credentials or grant before connecting.');
158
295
  if (!response.ok)
159
296
  throw new Error(`Revo API ${method} ${route} returned ${response.status}: ${String(value?.message || 'request failed')}`);
160
297
  return (value?.data ?? value);
@@ -175,12 +312,15 @@ function send(socket, frame) {
175
312
  socket.send(JSON.stringify(frame));
176
313
  }
177
314
  export function boundResultFrame(frame) {
178
- const bounded = { ...frame, stdout: String(frame.stdout || ''), stderr: String(frame.stderr || '') };
179
- while (Buffer.byteLength(JSON.stringify(bounded)) > 90_000) {
315
+ const bounded = { ...frame, stdout: String(frame.stdout || ''), stderr: String(frame.stderr || ''),
316
+ truncated: frame.truncated === true };
317
+ while (Buffer.byteLength(bounded.stdout) + Buffer.byteLength(bounded.stderr) > 80_000
318
+ || Buffer.byteLength(JSON.stringify(bounded)) > 90_000) {
180
319
  if (bounded.stdout.length >= bounded.stderr.length)
181
320
  bounded.stdout = bounded.stdout.slice(0, Math.floor(bounded.stdout.length * 0.75));
182
321
  else
183
322
  bounded.stderr = bounded.stderr.slice(0, Math.floor(bounded.stderr.length * 0.75));
323
+ bounded.truncated = true;
184
324
  }
185
325
  return bounded;
186
326
  }
@@ -226,8 +366,8 @@ export async function runCommand(input, onDone, onChunk) {
226
366
  let terminal;
227
367
  try {
228
368
  if (tty) {
229
- ensurePtyHelperExecutable();
230
369
  const pty = await import('node-pty');
370
+ ensurePtyHelperExecutable();
231
371
  terminal = pty.spawn(launch.file, launch.args, {
232
372
  cwd: workdir, env, name: 'xterm-256color', cols: input.cols || 80, rows: input.rows || 24,
233
373
  });
@@ -282,13 +422,19 @@ export async function runCommand(input, onDone, onChunk) {
282
422
  }, 2_000);
283
423
  hardStop.unref?.();
284
424
  };
285
- const timer = setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), MAX_TERMINAL_PROCESS_MS));
286
- const policyTimer = input.policyDeadlineMs == null ? undefined : setTimeout(() => {
287
- if (finished)
288
- return;
289
- policyExpired = true;
290
- terminate();
291
- }, Math.max(0, input.policyDeadlineMs - Date.now()));
425
+ const timer = input.background === true ? undefined : setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), MAX_TERMINAL_PROCESS_MS));
426
+ let policyTimer;
427
+ const updatePolicyDeadline = (deadline) => {
428
+ if (policyTimer)
429
+ clearTimeout(policyTimer);
430
+ policyTimer = deadline == null ? undefined : setTimeout(() => {
431
+ if (finished)
432
+ return;
433
+ policyExpired = true;
434
+ terminate();
435
+ }, Math.max(0, deadline - Date.now()));
436
+ };
437
+ updatePolicyDeadline(input.policyDeadlineMs ?? null);
292
438
  const append = (chunk, kind) => {
293
439
  const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
294
440
  if (logPart.length && logFd !== undefined) {
@@ -332,13 +478,17 @@ export async function runCommand(input, onDone, onChunk) {
332
478
  child?.stdout?.on('data', (chunk) => append(chunk, 'stdout'));
333
479
  child?.stderr?.on('data', (chunk) => append(chunk, 'stderr'));
334
480
  terminal?.onData(text => append(Buffer.from(text), 'stdout'));
335
- const finish = (exitCode, error) => {
481
+ const finish = (exitCode, error, signal) => {
336
482
  if (finished)
337
483
  return;
338
484
  finished = true;
339
- clearTimeout(timer);
485
+ if (timer)
486
+ clearTimeout(timer);
340
487
  if (policyTimer)
341
488
  clearTimeout(policyTimer);
489
+ const diagnostic = [error?.message, policyExpired ? 'terminal_policy_expired' : null].filter(Boolean).join('\n');
490
+ if (diagnostic)
491
+ append(Buffer.from(`${stderr && !stderr.endsWith('\n') ? '\n' : ''}${diagnostic}`), 'stderr');
342
492
  if (scratch) {
343
493
  try {
344
494
  fs.rmSync(scratch, { recursive: true, force: true });
@@ -354,15 +504,15 @@ export async function runCommand(input, onDone, onChunk) {
354
504
  }
355
505
  }
356
506
  onDone({ executed: !error, exitCode: (timedOut || policyExpired) && exitCode === 0 ? null : exitCode,
357
- stdout, stderr: [stderr, error?.message, policyExpired ? 'terminal_policy_expired' : null]
358
- .filter(Boolean).join('\n'),
507
+ stdout, stderr,
359
508
  timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath,
509
+ ...(signal ? { signal } : {}),
360
510
  ...(policyExpired ? { policyExpired: true } : {}) });
361
511
  };
362
- child?.on('close', code => finish(code));
512
+ child?.on('close', (code, signal) => finish(code, undefined, signal));
363
513
  child?.on('error', error => finish(null, error));
364
514
  terminal?.onExit(({ exitCode }) => finish(exitCode));
365
- return { pid, terminate,
515
+ return { pid, terminate, updatePolicyDeadline,
366
516
  write: chars => { if (terminal)
367
517
  terminal.write(chars);
368
518
  else
@@ -408,14 +558,20 @@ export function runWorkspacePatch(input, onDone) {
408
558
  }
409
559
  catch { /* exited */ }
410
560
  }, 60_000);
411
- const policyTimer = input.policyDeadlineMs == null ? undefined : setTimeout(() => {
412
- policyExpired = true;
413
- if (child.pid)
414
- try {
415
- process.kill(-child.pid, 'SIGKILL');
416
- }
417
- catch { /* exited */ }
418
- }, Math.max(0, input.policyDeadlineMs - Date.now()));
561
+ let policyTimer;
562
+ const updatePolicyDeadline = (deadline) => {
563
+ if (policyTimer)
564
+ clearTimeout(policyTimer);
565
+ policyTimer = deadline == null ? undefined : setTimeout(() => {
566
+ policyExpired = true;
567
+ if (child.pid)
568
+ try {
569
+ process.kill(-child.pid, 'SIGKILL');
570
+ }
571
+ catch { /* exited */ }
572
+ }, Math.max(0, deadline - Date.now()));
573
+ };
574
+ updatePolicyDeadline(input.policyDeadlineMs ?? null);
419
575
  child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8').slice(0, 4_000 - stdout.length); });
420
576
  child.stderr?.on('data', (chunk) => { stderr += chunk.toString('utf8').slice(0, 4_000 - stderr.length); });
421
577
  child.stdin?.on('error', () => { });
@@ -437,7 +593,7 @@ export function runWorkspacePatch(input, onDone) {
437
593
  };
438
594
  child.on('close', code => finish(code));
439
595
  child.on('error', error => finish(null, error));
440
- return child;
596
+ return Object.assign(child, { updatePolicyDeadline });
441
597
  }
442
598
  async function connect(profile, device) {
443
599
  const logDeviceId = /^[A-Za-z0-9_-]{1,128}$/u.test(device.agentTerminalId)
@@ -450,6 +606,7 @@ async function connect(profile, device) {
450
606
  let activeConnectionId = '';
451
607
  const activeChildren = new Set();
452
608
  const children = new Map();
609
+ const activePolicies = new Map();
453
610
  const cancelledExecutions = new Set();
454
611
  const outputByExecution = new Map();
455
612
  const completed = new Map();
@@ -464,9 +621,32 @@ async function connect(profile, device) {
464
621
  let minimumPolicyGrantRevision = 0;
465
622
  let policyRevisionUnavailable = false;
466
623
  let securePolicyEpoch = 0;
624
+ const updateGrantPolicy = async (revision, grant) => {
625
+ if (revision < minimumPolicyGrantRevision)
626
+ return;
627
+ minimumPolicyGrantRevision = revision;
628
+ policyRevisionUnavailable = false;
629
+ let stopped = 0;
630
+ for (const [executionId, child] of children) {
631
+ const policy = activePolicies.get(executionId);
632
+ if (!policy || (policy.agentTerminalWorkspaceId
633
+ && policy.policyGrantRevision !== revision) || (policy.commandAccessForThread || policy.networkAccessForThread)
634
+ && policy.policyGrantRevision !== revision || !executionAllowedByGrant(policy, grant)) {
635
+ cancelledExecutions.add(executionId);
636
+ child.terminate();
637
+ stopped++;
638
+ }
639
+ else
640
+ child.updatePolicyDeadline?.(remainingPolicyDeadline(policy, grant));
641
+ }
642
+ const closed = await reconcileBrowserSessions(grant.networkMode, revision);
643
+ operationalLog.write(stopped || closed ? 'WARN' : 'INFO', {}, 'terminal.policy_updated', { stoppedExecutions: stopped, closedBrowserSessions: closed });
644
+ };
467
645
  const sendCurrent = (frame) => {
468
646
  if (activeConnectionId && activeSocket?.readyState === WebSocket.OPEN)
469
- send(activeSocket, { ...frame, connectionId: activeConnectionId });
647
+ send(activeSocket, frame.type === 'result'
648
+ ? boundResultFrame({ ...frame, connectionId: activeConnectionId })
649
+ : { ...frame, connectionId: activeConnectionId });
470
650
  };
471
651
  const flushExecution = (executionId) => {
472
652
  if (!resumed.has(executionId))
@@ -500,53 +680,102 @@ async function connect(profile, device) {
500
680
  headers: { Authorization: `Bearer ${profile.token}`,
501
681
  ...(profile.instance ? { instance: profile.instance } : {}) },
502
682
  perMessageDeflate: false,
683
+ handshakeTimeout: 10_000,
503
684
  });
504
685
  activeSocket = socket;
505
686
  let connectionId = '';
506
- let workspace = device.workspace;
687
+ let defaultWorkspace = device.workspace;
507
688
  let heartbeat;
508
689
  let lastHeartbeat = Date.now();
509
690
  let incoming = Promise.resolve();
691
+ const recovery = new TerminalTransportRecovery(() => socket.terminate(), () => {
692
+ backoffMs = 1_000;
693
+ reconnectGrace.clear();
694
+ });
510
695
  socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
511
696
  secret: device.secret, capabilities: ['workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
512
- 'terminal_policy_v2',
697
+ 'terminal_policy_v2', 'terminal_policy_selective_v1', 'background_shell_v1', 'terminal_thread_scope_v1',
513
698
  'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
514
- 'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'save_image_v1',
699
+ 'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'browser_tabs_v1', 'save_image_v1',
700
+ 'browser_timeout_v1', 'terminal_workspaces_v1', 'file_transfer_v1', 'browser_control_v1',
515
701
  ...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])],
516
702
  secureBrowserPublicKey: secureIdentity.publicKey, secureBrowserKeyId: secureIdentity.keyId }));
517
703
  socket.on('message', raw => {
704
+ let frame;
705
+ try {
706
+ frame = JSON.parse(raw.toString());
707
+ }
708
+ catch {
709
+ socket.terminate();
710
+ return;
711
+ }
712
+ // A queued browser action or output processing must not hide a live transport.
713
+ if (isRunnerTransportHeartbeat(frame, connectionId)) {
714
+ lastHeartbeat = Date.now();
715
+ return;
716
+ }
518
717
  incoming = incoming.then(async () => {
519
718
  if (stopping || socket.readyState !== WebSocket.OPEN)
520
719
  return;
521
- const frame = JSON.parse(raw.toString());
522
720
  if (frame.type === 'ready' && frame.connectionId) {
721
+ if (connectionId) {
722
+ socket.terminate();
723
+ return;
724
+ }
725
+ lastHeartbeat = Date.now();
523
726
  securePolicyEpoch++;
524
727
  connectionId = frame.connectionId;
525
728
  activeConnectionId = connectionId;
526
- workspace = frame.workspace || device.workspace;
729
+ defaultWorkspace = frame.workspace || device.workspace;
527
730
  if (Number.isSafeInteger(frame.policyGrantRevision) && frame.policyGrantRevision >= 0) {
528
731
  minimumPolicyGrantRevision = Math.max(minimumPolicyGrantRevision, frame.policyGrantRevision);
529
732
  policyRevisionUnavailable = false;
530
733
  }
531
734
  else
532
735
  policyRevisionUnavailable = true;
533
- backoffMs = 1_000;
534
- reconnectGrace.clear();
736
+ const ready = frame;
737
+ if (ready.grantMode && ready.networkMode && Number.isSafeInteger(ready.policyGrantRevision))
738
+ await updateGrantPolicy(ready.policyGrantRevision, { mode: ready.grantMode, networkMode: ready.networkMode });
535
739
  console.log(`Connected ${device.name} (${device.agentTerminalId}).`);
536
740
  operationalLog.write('INFO', {}, 'socket.ready', { resumedExecutions: children.size + completed.size });
537
- for (const executionId of new Set([...children.keys(), ...completed.keys()]))
741
+ const pendingResumes = new Set([...children.keys(), ...completed.keys()]);
742
+ recovery.ready(pendingResumes);
743
+ for (const executionId of pendingResumes) {
538
744
  send(socket, { type: 'resume', connectionId, executionId });
745
+ }
539
746
  heartbeat = setInterval(() => {
540
747
  if (Date.now() - lastHeartbeat > 45_000) {
541
748
  socket.terminate();
542
749
  return;
543
750
  }
544
- send(socket, { type: 'heartbeat', connectionId });
751
+ send(socket, { type: 'heartbeat', connectionId, threadBrowserScopes: threadBrowserScopes(), browserSessionIds: browserSessionIds() });
545
752
  }, 15_000);
546
753
  return;
547
754
  }
548
- if (frame.type === 'heartbeat') {
549
- lastHeartbeat = Date.now();
755
+ if (frame.type === 'heartbeat')
756
+ return;
757
+ if (frame.type === 'browser_scope_revoked') {
758
+ if (frame.connectionId === connectionId && typeof frame.browserSessionId === 'string'
759
+ && /^[a-f0-9]{64}$/u.test(frame.browserSessionId)) {
760
+ securePolicyEpoch++;
761
+ await closeThreadBrowserSession(frame.browserSessionId);
762
+ }
763
+ return;
764
+ }
765
+ if (frame.type === 'policy_updated') {
766
+ const update = frame;
767
+ if (update.connectionId !== connectionId)
768
+ return;
769
+ if (!Number.isSafeInteger(update.policyGrantRevision) || update.policyGrantRevision < 0
770
+ || !['review', 'full'].includes(update.grantMode || '')
771
+ || !['restricted', 'sandbox', 'external'].includes(update.networkMode || '')) {
772
+ policyRevisionUnavailable = true;
773
+ for (const child of children.values())
774
+ child.terminate();
775
+ await closeBrowserSessions();
776
+ return;
777
+ }
778
+ await updateGrantPolicy(update.policyGrantRevision, { mode: update.grantMode, networkMode: update.networkMode });
550
779
  return;
551
780
  }
552
781
  if (frame.type === 'policy_revoked') {
@@ -589,6 +818,7 @@ async function connect(profile, device) {
589
818
  const envelope = frame;
590
819
  const value = decryptSecureBrowserInput(envelope, secureIdentity);
591
820
  await fillBrowserSecret({ browserSessionId: envelope.browserSessionId,
821
+ browserTabId: envelope.browserTabId,
592
822
  origin: envelope.origin, selector: envelope.selector,
593
823
  expiresAt: envelope.expiresAt, value,
594
824
  isAuthorized: () => requestEpoch === securePolicyEpoch && !stopping
@@ -612,11 +842,13 @@ async function connect(profile, device) {
612
842
  if (frame.connectionId !== connectionId || !frame.executionId)
613
843
  return;
614
844
  if (frame.type === 'resumed') {
845
+ recovery.accepted(frame.executionId);
615
846
  resumed.add(frame.executionId);
616
847
  flushExecution(frame.executionId);
617
848
  return;
618
849
  }
619
850
  if (frame.type === 'result_ack' || frame.type === 'resume_rejected') {
851
+ recovery.accepted(frame.executionId);
620
852
  if (frame.type === 'resume_rejected') {
621
853
  operationalLog.write('WARN', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.resume_rejected');
622
854
  children.get(frame.executionId)?.terminate();
@@ -630,7 +862,9 @@ async function connect(profile, device) {
630
862
  if (frame.type === 'cancel') {
631
863
  const child = children.get(frame.executionId);
632
864
  if (child) {
633
- operationalLog.write('WARN', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.cancel_requested');
865
+ operationalLog.write('WARN', traces.get(frame.executionId) || { executionId: frame.executionId }, 'execution.cancel_requested', { reason: ['background_execution_invalid', 'background_dispatch_invalid',
866
+ 'background_binding_invalid', 'background_authorization_invalid'].includes(frame.cancelCause || '')
867
+ ? frame.cancelCause : 'cancel_requested' });
634
868
  cancelledExecutions.add(frame.executionId);
635
869
  child.terminate();
636
870
  }
@@ -668,6 +902,12 @@ async function connect(profile, device) {
668
902
  send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
669
903
  return;
670
904
  }
905
+ const workspace = frame.agentTerminalWorkspaceId ? frame.workspace : defaultWorkspace;
906
+ if (typeof workspace !== 'string' || !path.isAbsolute(workspace)) {
907
+ sendResult(socket, { type: 'result', connectionId, executionId: frame.executionId,
908
+ executed: false, exitCode: null, stdout: '', stderr: 'workspace_unavailable', timedOut: false });
909
+ return;
910
+ }
671
911
  const operation = frame.operation || 'shell';
672
912
  const trace = { assistantThreadId: frame.assistantThreadId,
673
913
  assistantMessageId: frame.assistantMessageId, executionId: frame.executionId };
@@ -676,10 +916,11 @@ async function connect(profile, device) {
676
916
  && typeof frame.browserSessionId === 'string' && frame.browserAction) {
677
917
  try {
678
918
  validateBrowserActionInput({ url: frame.url, action: frame.browserAction,
679
- workspace, browserSessionId: frame.browserSessionId, selector: frame.selector,
919
+ workspace, browserSessionId: frame.browserSessionId, tabId: frame.tabId, selector: frame.selector,
680
920
  width: frame.width, height: frame.height, value: frame.value, checked: frame.checked,
681
921
  key: frame.key, deltaY: frame.deltaY, state: frame.state,
682
922
  waitTimeoutMs: frame.waitTimeoutMs, capture: frame.capture, clip: frame.clip,
923
+ actionTimeoutMs: frame.actionTimeoutMs,
683
924
  localOnly: frame.browserLocalOnly === true });
684
925
  validBrowserPayload = true;
685
926
  }
@@ -688,11 +929,15 @@ async function connect(profile, device) {
688
929
  const validPayload = operation === 'apply_patch'
689
930
  ? typeof frame.patch === 'string' && Buffer.byteLength(frame.patch) <= 64_000
690
931
  : operation === 'browser' ? validBrowserPayload
691
- : operation === 'save_image' ? Array.isArray(frame.files) && frame.files.length > 0 && frame.files.length <= 32
692
- : operation === 'shell' && typeof frame.cmd === 'string' && !!frame.cmd.trim() && frame.cmd.length <= 8_192;
693
- if (!validPayload || children.size >= 4 || !isTerminalSandbox(frame.sandbox)
932
+ : operation === 'upload_file' || operation === 'download_file' ? validateFileTransfer(frame.transfer)
933
+ : operation === 'save_image' ? Array.isArray(frame.files) && frame.files.length > 0 && frame.files.length <= 32
934
+ : operation === 'shell' && typeof frame.cmd === 'string' && !!frame.cmd.trim() && frame.cmd.length <= 8_192;
935
+ if (!validPayload || operation !== 'browser' && frame.actionTimeoutMs != null
936
+ || frame.background !== undefined && typeof frame.background !== 'boolean'
937
+ || frame.background === true && (operation !== 'shell' || frame.timeoutMs != null)
938
+ || children.size >= 4 || !isTerminalSandbox(frame.sandbox)
694
939
  || operation === 'apply_patch' && frame.sandbox === 'workspace-network'
695
- || (operation === 'browser' || operation === 'save_image') && frame.sandbox !== 'workspace-network'
940
+ || (operation === 'browser' || operation === 'save_image' || operation === 'upload_file' || operation === 'download_file') && frame.sandbox !== 'workspace-network'
696
941
  || frame.tty === true && (operation !== 'shell' || !Number.isInteger(frame.cols) || !Number.isInteger(frame.rows)
697
942
  || frame.cols < 20 || frame.cols > 240 || frame.rows < 10 || frame.rows > 100)) {
698
943
  operationalLog.write('WARN', trace, 'execution.rejected', { operation,
@@ -709,37 +954,50 @@ async function connect(profile, device) {
709
954
  return;
710
955
  }
711
956
  try {
957
+ activePolicies.set(frame.executionId, frame);
712
958
  traces.set(frame.executionId, trace);
713
959
  operationalLog.write('INFO', trace, 'execution.started', { operation, sandbox: frame.sandbox });
714
960
  resumed.add(frame.executionId);
715
961
  outputByExecution.set(frame.executionId, []);
716
- if (operation === 'save_image') {
962
+ if (operation === 'save_image' || operation === 'upload_file' || operation === 'download_file') {
717
963
  const controller = new AbortController();
718
964
  const policyDeadline = executionPolicyDeadline(frame);
719
- const policyTimer = policyDeadline == null ? undefined : setTimeout(() => controller.abort(), Math.max(0, policyDeadline - Date.now()));
720
- policyTimer?.unref?.();
965
+ let policyTimer;
966
+ const updatePolicyDeadline = (deadline) => {
967
+ if (policyTimer)
968
+ clearTimeout(policyTimer);
969
+ policyTimer = deadline == null ? undefined : setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
970
+ policyTimer?.unref?.();
971
+ };
972
+ updatePolicyDeadline(policyDeadline);
721
973
  const child = { pid: undefined, write: () => undefined,
722
974
  closeStdin: () => undefined, resize: () => undefined,
723
- terminate: () => controller.abort() };
975
+ terminate: () => controller.abort(),
976
+ updatePolicyDeadline };
724
977
  children.set(frame.executionId, child);
725
978
  activeChildren.add(child);
726
979
  send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
727
- void uploadWorkspaceImages(workspace, frame.files, controller.signal).then(count => {
980
+ const transfer = operation === 'save_image' ? uploadWorkspaceImages(workspace, frame.files, controller.signal)
981
+ : transferWorkspaceFile(workspace, operation, frame.transfer, controller.signal);
982
+ void transfer.then(count => {
728
983
  if (policyTimer)
729
984
  clearTimeout(policyTimer);
730
985
  children.delete(frame.executionId);
986
+ activePolicies.delete(frame.executionId);
731
987
  activeChildren.delete(child);
732
- completed.set(frame.executionId, { executed: true, exitCode: 0, stdout: `Uploaded ${count} image(s).`, stderr: '' });
733
- operationalLog.write('INFO', trace, 'execution.completed', { operation, exitCode: 0, images: count });
988
+ completed.set(frame.executionId, { executed: true, exitCode: 0, stdout: operation === 'save_image' ? `Uploaded ${count} image(s).` : JSON.stringify(count), stderr: '' });
989
+ operationalLog.write('INFO', trace, 'execution.completed', { operation, exitCode: 0, images: operation === 'save_image' ? count : undefined });
734
990
  if (resumed.has(frame.executionId))
735
991
  flushExecution(frame.executionId);
736
992
  }).catch(error => {
737
993
  if (policyTimer)
738
994
  clearTimeout(policyTimer);
739
995
  children.delete(frame.executionId);
996
+ activePolicies.delete(frame.executionId);
740
997
  activeChildren.delete(child);
741
- completed.set(frame.executionId, { executed: false, exitCode: null, stdout: '',
742
- stderr: error instanceof Error ? error.message : 'image_upload_failed' });
998
+ completed.set(frame.executionId, { executed: operation === 'upload_file' && error instanceof Error
999
+ && ['file_transfer_transport_failed', 'file_transfer_source_changed'].includes(error.message), exitCode: null, stdout: '',
1000
+ stderr: error instanceof Error && /^[a-z][a-z_0-9]+$/u.test(error.message) ? error.message : 'file_transfer_failed' });
743
1001
  operationalLog.write('ERROR', trace, 'execution.failed', { operation,
744
1002
  errorCode: 'image_upload_failed' });
745
1003
  if (resumed.has(frame.executionId))
@@ -750,24 +1008,35 @@ async function connect(profile, device) {
750
1008
  if (operation === 'browser') {
751
1009
  const controller = new AbortController();
752
1010
  const policyDeadline = executionPolicyDeadline(frame);
753
- const policyTimer = policyDeadline == null ? undefined : setTimeout(() => controller.abort(), Math.max(0, policyDeadline - Date.now()));
754
- policyTimer?.unref?.();
1011
+ let policyTimer;
1012
+ const updatePolicyDeadline = (deadline) => {
1013
+ if (policyTimer)
1014
+ clearTimeout(policyTimer);
1015
+ policyTimer = deadline == null ? undefined : setTimeout(() => controller.abort(), Math.max(0, deadline - Date.now()));
1016
+ policyTimer?.unref?.();
1017
+ };
1018
+ updatePolicyDeadline(policyDeadline);
755
1019
  let actionAttempted = false;
756
1020
  const child = { pid: undefined, write: () => undefined,
757
1021
  closeStdin: () => undefined, resize: () => undefined,
758
- terminate: () => controller.abort() };
1022
+ terminate: () => controller.abort(),
1023
+ updatePolicyDeadline };
759
1024
  children.set(frame.executionId, child);
760
1025
  activeChildren.add(child);
761
1026
  send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
762
- void runBrowserAction({ url: frame.url, action: frame.browserAction, workspace,
763
- browserSessionId: frame.browserSessionId, onActionAttempt: () => { actionAttempted = true; },
1027
+ void runBrowserAction({ url: frame.url, action: frame.browserAction, workspace, agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId,
1028
+ browserSessionId: frame.browserSessionId, tabId: frame.tabId,
1029
+ onActionAttempt: () => { actionAttempted = true; },
764
1030
  selector: frame.selector, width: frame.width, height: frame.height,
765
1031
  value: frame.value, checked: frame.checked, key: frame.key, deltaY: frame.deltaY,
766
1032
  state: frame.state, waitTimeoutMs: frame.waitTimeoutMs,
1033
+ actionTimeoutMs: frame.actionTimeoutMs,
767
1034
  capture: frame.capture, clip: frame.clip,
768
1035
  localOnly: frame.browserLocalOnly === true,
769
1036
  networkAccessExpiresAt: frame.networkAccessExpiresAt,
770
1037
  networkAccessOnce: frame.networkAccessOnce,
1038
+ networkAccessForThread: frame.networkAccessForThread, actorUserId: frame.actorUserId,
1039
+ threadId: frame.browserTargetThreadId || frame.assistantThreadId, policyGrantRevision: frame.policyGrantRevision,
771
1040
  signal: controller.signal })
772
1041
  .then(async (browserResult) => {
773
1042
  if (frame.browserAction === 'screenshot') {
@@ -778,10 +1047,13 @@ async function connect(profile, device) {
778
1047
  if (policyTimer)
779
1048
  clearTimeout(policyTimer);
780
1049
  children.delete(frame.executionId);
1050
+ activePolicies.delete(frame.executionId);
781
1051
  activeChildren.delete(child);
782
1052
  completed.set(frame.executionId, { executed: true, exitCode: 0,
783
1053
  stdout: browserResult.dom, stderr: '', screenshotPath: browserResult.screenshotPath || null,
784
1054
  pageUrl: browserResult.pageUrl,
1055
+ browserSessionId: browserResult.browserSessionId, activeTabId: browserResult.activeTabId,
1056
+ tabs: browserResult.tabs, sessionCreated: browserResult.sessionCreated,
785
1057
  cancelled: cancelledExecutions.delete(frame.executionId) });
786
1058
  operationalLog.write('INFO', trace, 'execution.completed', { operation,
787
1059
  browserAction: frame.browserAction, exitCode: 0, screenshot: frame.browserAction === 'screenshot' });
@@ -791,6 +1063,7 @@ async function connect(profile, device) {
791
1063
  if (policyTimer)
792
1064
  clearTimeout(policyTimer);
793
1065
  children.delete(frame.executionId);
1066
+ activePolicies.delete(frame.executionId);
794
1067
  activeChildren.delete(child);
795
1068
  const code = error instanceof Error && /^[a-z][a-z_]+$/u.test(error.message)
796
1069
  ? error.message : 'browser_failed';
@@ -811,6 +1084,7 @@ async function connect(profile, device) {
811
1084
  allowDelete: frame.sandbox === 'unrestricted',
812
1085
  policyDeadlineMs: executionPolicyDeadline(frame) }, result => {
813
1086
  children.delete(frame.executionId);
1087
+ activePolicies.delete(frame.executionId);
814
1088
  activeChildren.delete(child);
815
1089
  completed.set(frame.executionId, { ...result, cancelled: cancelledExecutions.delete(frame.executionId) });
816
1090
  operationalLog.write(result.exitCode === 0 ? 'INFO' : 'ERROR', trace, result.exitCode === 0 ? 'execution.completed' : 'execution.failed', { operation, exitCode: result.exitCode ?? 'none', executed: result.executed });
@@ -826,6 +1100,7 @@ async function connect(profile, device) {
826
1100
  process.kill(-patchChild.pid, 'SIGTERM');
827
1101
  }
828
1102
  catch { /* exited */ } },
1103
+ updatePolicyDeadline: deadline => patchChild.updatePolicyDeadline(deadline),
829
1104
  };
830
1105
  children.set(frame.executionId, child);
831
1106
  activeChildren.add(child);
@@ -835,15 +1110,17 @@ async function connect(profile, device) {
835
1110
  const child = await runCommand({ cmd: frame.cmd, workdir: frame.workdir || workspace,
836
1111
  workspace, sandbox: frame.sandbox, networkAccess: frame.networkAccess,
837
1112
  policyDeadlineMs: executionPolicyDeadline(frame),
838
- timeoutMs: frame.timeoutMs || 60_000, tty: frame.tty,
1113
+ timeoutMs: frame.timeoutMs || 60_000, background: frame.background === true, tty: frame.tty,
839
1114
  cols: frame.cols, rows: frame.rows,
840
1115
  executionId: frame.executionId }, result => {
841
1116
  children.delete(frame.executionId);
1117
+ activePolicies.delete(frame.executionId);
842
1118
  activeChildren.delete(child);
843
1119
  const { stdout, stderr, ...completion } = result;
844
1120
  completed.set(frame.executionId, { ...completion,
845
1121
  cancelled: cancelledExecutions.delete(frame.executionId), stdout: '', stderr: '' });
846
- operationalLog.write(completion.exitCode === 0 ? 'INFO' : 'ERROR', trace, completion.exitCode === 0 ? 'execution.completed' : 'execution.failed', { operation, exitCode: completion.exitCode ?? 'none', executed: completion.executed,
1122
+ operationalLog.write(completion.exitCode === 0 ? 'INFO' : 'ERROR', trace, completion.exitCode === 0 ? 'execution.completed' : 'execution.failed', { operation, exitCode: completion.exitCode ?? 'none', signal: completion.signal,
1123
+ executed: completion.executed,
847
1124
  timedOut: completion.timedOut, truncated: completion.truncated });
848
1125
  if (resumed.has(frame.executionId))
849
1126
  sendCurrent({ type: 'result', executionId: frame.executionId,
@@ -861,6 +1138,7 @@ async function connect(profile, device) {
861
1138
  send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
862
1139
  }
863
1140
  catch (error) {
1141
+ activePolicies.delete(frame.executionId);
864
1142
  resumed.delete(frame.executionId);
865
1143
  outputByExecution.delete(frame.executionId);
866
1144
  traces.delete(frame.executionId);
@@ -876,6 +1154,7 @@ async function connect(profile, device) {
876
1154
  operationalLog.write(code === 1000 ? 'INFO' : 'WARN', {}, 'socket.closed', { code, activeExecutions: children.size, policyViolation: code === 1008 });
877
1155
  if (heartbeat)
878
1156
  clearInterval(heartbeat);
1157
+ recovery.close();
879
1158
  if (activeSocket === socket)
880
1159
  activeConnectionId = '';
881
1160
  resumed.clear();
@@ -890,18 +1169,30 @@ async function connect(profile, device) {
890
1169
  if (activeSocket === socket)
891
1170
  activeSocket = undefined;
892
1171
  if (code === 1008 && reason.toString() !== 'heartbeat_timeout')
893
- reject(new Error(`Runner rejected by Realtime: ${reason.toString() || 'policy violation'}.`));
1172
+ reject(new TerminalRunnerFatalError(`Runner rejected by Realtime: ${reason.toString() || 'policy violation'}.`));
894
1173
  else
895
1174
  resolve();
896
1175
  });
1176
+ socket.on('unexpected-response', (_request, response) => {
1177
+ response.resume();
1178
+ if ([401, 403].includes(response.statusCode || 0)) {
1179
+ stopping = true;
1180
+ socket.terminate();
1181
+ reject(new TerminalRunnerFatalError('Runner authentication was rejected. Renew the CLI credentials before connecting.'));
1182
+ }
1183
+ else
1184
+ socket.terminate();
1185
+ });
897
1186
  socket.on('error', () => {
1187
+ if (stopping)
1188
+ return;
898
1189
  operationalLog.write('WARN', {}, 'socket.error');
899
1190
  console.error('Realtime connection failed; terminal will retry.');
900
1191
  });
901
1192
  });
902
1193
  }
903
1194
  catch (error) {
904
- if (error instanceof Error && error.message.startsWith('Runner rejected by Realtime:'))
1195
+ if (error instanceof TerminalRunnerFatalError)
905
1196
  throw error;
906
1197
  operationalLog.write('WARN', {}, 'runner.connect_failed', { errorCode: operationalErrorCode(error) });
907
1198
  console.error('Terminal connection failed; retrying.');
@@ -919,16 +1210,16 @@ async function connect(profile, device) {
919
1210
  process.off('SIGTERM', stop);
920
1211
  }
921
1212
  }
922
- export async function handleTerminalCommand(argv) {
1213
+ async function runTerminalCommand(argv) {
923
1214
  const command = argv[0] || 'help';
924
1215
  if (command === 'help' || argv.includes('--help')) {
925
- console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME] [--url URL] [--realtime-url URL]\nrevo terminal service install|uninstall --workspace PATH [--project NAME]');
1216
+ console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID] [--url URL] [--realtime-url URL]\nrevo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]');
926
1217
  return;
927
1218
  }
928
1219
  if (command === 'service') {
929
1220
  const action = argv[1];
930
1221
  if (!action || action === 'help') {
931
- console.log('revo terminal service install|uninstall --workspace PATH [--project NAME]');
1222
+ console.log('revo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]');
932
1223
  return;
933
1224
  }
934
1225
  if (action !== 'install' && action !== 'uninstall')
@@ -938,8 +1229,22 @@ export async function handleTerminalCommand(argv) {
938
1229
  throw new Error('Terminal service requires --workspace PATH.');
939
1230
  const workspace = fs.existsSync(requestedWorkspace) ? fs.realpathSync(requestedWorkspace) : path.resolve(requestedWorkspace);
940
1231
  const envName = selectedProject(argv) || getActiveEnvironmentName();
1232
+ const { name, terminalId } = terminalSelector(argv);
1233
+ const saved = envName === 'default' ? loadStoredConfig({ allowLegacy: false }) : getEnvironmentProfile(envName);
1234
+ const baseUrl = saved?.baseUrl?.replace(/\/$/, '');
1235
+ const devices = readStore().devices.filter(item => (item.workspace === workspace || item.workspaces?.includes(workspace)) && item.baseUrl === baseUrl
1236
+ && (!saved?.instance || item.instance === saved.instance));
1237
+ const matching = devices.filter(item => terminalId ? item.agentTerminalId === terminalId : item.name === name);
941
1238
  if (action === 'uninstall') {
942
- const result = uninstallTerminalService({ workspace, envName, configHome: process.env.XDG_CONFIG_HOME });
1239
+ if (matching.length > 1)
1240
+ throw new Error(`Multiple terminals match ${name} (${matching.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
1241
+ if (!terminalId && matching.length === 0 && option(argv, 'name'))
1242
+ throw new Error('No local terminal registration matches --name. Use --terminal-id to uninstall its service.');
1243
+ const selectedId = terminalId || matching[0]?.agentTerminalId;
1244
+ const result = uninstallTerminalService({ workspace: matching[0]?.workspace || workspace, envName,
1245
+ terminalId: selectedId && (terminalId || option(argv, 'name')
1246
+ || terminalServiceInstalled(matching[0]?.workspace || workspace, envName, selectedId)) ? selectedId : undefined,
1247
+ configHome: process.env.XDG_CONFIG_HOME });
943
1248
  console.log(result.removed ? `Terminal service stopped and removed (${result.label}). Grant remains active.`
944
1249
  : `No terminal service installed for this workspace (${result.label}).`);
945
1250
  return;
@@ -949,20 +1254,34 @@ export async function handleTerminalCommand(argv) {
949
1254
  for (const unsupported of ['token', 'url', 'instance', 'realtime-url'])
950
1255
  if (option(argv, unsupported))
951
1256
  throw new Error(`Service install cannot use --${unsupported}; use a saved CLI login/profile.`);
952
- const saved = envName === 'default' ? loadStoredConfig({ allowLegacy: false }) : getEnvironmentProfile(envName);
953
1257
  if (!saved?.token?.startsWith('sk-'))
954
1258
  throw new Error('A saved personal Revo API key is required. Run revo auth login or select a saved --project profile.');
955
- const baseUrl = saved.baseUrl.replace(/\/$/, '');
956
- const devices = readStore().devices.filter(item => item.workspace === workspace && item.baseUrl === baseUrl
957
- && (!saved.instance || item.instance === saved.instance));
958
- if (devices.length !== 1)
959
- throw new Error('Expected one registered terminal for this workspace and saved profile. Run revo terminal connect first.');
960
- const device = devices[0];
961
- const profile = { baseUrl, token: saved.token, instance: device.instance };
1259
+ if (!matching.length)
1260
+ throw new Error('No registered terminal for this workspace, name and saved profile. Run revo terminal connect first.');
1261
+ if (!saved.instance && new Set(matching.map(item => item.instance)).size !== 1)
1262
+ throw new Error('The saved profile matches terminals in multiple instances. Select an instance-bound profile.');
1263
+ const profile = { baseUrl: baseUrl, token: saved.token, instance: saved.instance || matching[0].instance };
962
1264
  const listing = await api(profile, 'GET', '/agents/terminals');
963
- if (!listing.devices.some(item => item.agentTerminalId === device.agentTerminalId && item.status === 'approved'))
964
- throw new Error('Terminal grant is not approved. Approve it in AI Agents → Terminals before installing the service.');
965
- const result = installTerminalService({ workspace, envName, pathValue: process.env.PATH,
1265
+ const selected = selectRegisteredTerminal(matching, listing.devices, name, terminalId);
1266
+ if (!selected || !listing.devices.some(grant => grant.agentTerminalId === selected.agentTerminalId && grant.status === 'approved'))
1267
+ throw new Error('The selected terminal is not approved.');
1268
+ const serviceWorkspace = selected.workspace;
1269
+ if (terminalServiceInstalled(serviceWorkspace, envName))
1270
+ throw new Error('Uninstall the legacy workspace service before installing a terminal-specific service.');
1271
+ if (!terminalServiceInstalled(serviceWorkspace, envName, selected.agentTerminalId)) {
1272
+ let releaseRunnerLock;
1273
+ try {
1274
+ releaseRunnerLock = acquireRunnerLock(selected.agentTerminalId);
1275
+ }
1276
+ catch (error) {
1277
+ if (error instanceof Error && error.message.includes('already connected'))
1278
+ throw new Error('Stop the selected foreground terminal runner before installing its background service.');
1279
+ throw error;
1280
+ }
1281
+ releaseRunnerLock();
1282
+ }
1283
+ const result = installTerminalService({ workspace: serviceWorkspace, envName, terminalId: selected.agentTerminalId,
1284
+ pathValue: process.env.PATH,
966
1285
  configHome: process.env.XDG_CONFIG_HOME });
967
1286
  console.log(result.installed ? `Terminal service installed and started (${result.label}).`
968
1287
  : `Terminal service already installed (${result.label}).`);
@@ -979,63 +1298,145 @@ export async function handleTerminalCommand(argv) {
979
1298
  }
980
1299
  const workspace = fs.realpathSync(option(argv, 'workspace') || process.cwd());
981
1300
  const store = readStore();
982
- let device = store.devices.find(item => item.workspace === workspace && item.baseUrl === profile.baseUrl && item.instance === profile.instance);
1301
+ const selector = terminalSelector(argv);
1302
+ let { name } = selector;
1303
+ const { terminalId } = selector;
1304
+ const profileDevices = store.devices.filter(item => (command === 'connect' || item.workspace === workspace || item.workspaces?.includes(workspace))
1305
+ && item.baseUrl === profile.baseUrl && item.instance === profile.instance);
1306
+ let matchingDevices = profileDevices.filter(item => terminalId ? item.agentTerminalId === terminalId : item.name === name);
1307
+ if (command === 'connect' && !terminalId && option(argv, 'name') === undefined
1308
+ && !matchingDevices.length
1309
+ && terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName())) {
1310
+ if (profileDevices.length !== 1)
1311
+ throw new Error('Legacy workspace service has no unique terminal registration. Uninstall it and reconnect with --name or --terminal-id.');
1312
+ name = profileDevices[0].name;
1313
+ matchingDevices = profileDevices;
1314
+ }
983
1315
  if (command === 'disconnect') {
984
- if (!device) {
985
- console.log('No local terminal registration for this workspace.');
1316
+ if (!matchingDevices.length) {
1317
+ if (terminalId)
1318
+ throw new Error('No local terminal registration for --terminal-id in this workspace and profile.');
1319
+ console.log('No local terminal registration for this workspace and name.');
986
1320
  return;
987
1321
  }
988
- if (terminalServiceInstalled(workspace, selectedProject(argv) || getActiveEnvironmentName()))
989
- throw new Error('Uninstall the terminal service before revoking this terminal grant.');
990
- const selectedDevice = device;
991
1322
  const listing = await api(profile, 'GET', '/agents/terminals');
1323
+ let selectedDevice = selectRegisteredTerminal(matchingDevices, listing.devices, name, terminalId);
1324
+ if (!selectedDevice) {
1325
+ if (matchingDevices.length !== 1)
1326
+ throw new Error(`Multiple removed terminals match ${name} (${matchingDevices.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
1327
+ selectedDevice = matchingDevices[0];
1328
+ }
1329
+ if (terminalServiceInstalled(selectedDevice.workspace, selectedProject(argv) || getActiveEnvironmentName(), selectedDevice.agentTerminalId)
1330
+ || terminalServiceInstalled(selectedDevice.workspace, selectedProject(argv) || getActiveEnvironmentName()))
1331
+ throw new Error('Uninstall the selected terminal service before revoking its grant.');
992
1332
  if (listing.devices.some(item => item.agentTerminalId === selectedDevice.agentTerminalId))
993
1333
  await api(profile, 'POST', `/agents/terminals/${selectedDevice.agentTerminalId}/revoke`);
994
- store.devices = store.devices.filter(item => item !== selectedDevice);
995
- saveStore(store);
1334
+ await updateStore(current => {
1335
+ current.devices = current.devices.filter(item => item.agentTerminalId !== selectedDevice.agentTerminalId);
1336
+ });
996
1337
  console.log('Terminal registration removed.');
997
1338
  return;
998
1339
  }
999
1340
  if (command === 'status') {
1000
1341
  const listing = await api(profile, 'GET', '/agents/terminals');
1001
- console.log(JSON.stringify({ devices: listing.devices.map(item => ({ agentTerminalId: item.agentTerminalId, status: item.status, mode: item.mode })) }, null, 2));
1342
+ console.log(JSON.stringify({ devices: listing.devices.map(item => ({ agentTerminalId: item.agentTerminalId, name: item.name, workspace: item.workspace,
1343
+ workspaces: item.workspaces, status: item.status, mode: item.mode, networkMode: item.networkMode,
1344
+ revision: item.revision, connectionRevision: item.connectionRevision, online: item.online, lastOnlineAt: item.lastOnlineAt })) }, null, 2));
1002
1345
  return;
1003
1346
  }
1004
1347
  if (command !== 'connect')
1005
1348
  throw new Error(`Unknown command: ${command}`);
1006
1349
  if (process.platform !== 'darwin' && process.platform !== 'linux')
1007
1350
  throw new Error('Runner supports macOS and Linux.');
1008
- if (device) {
1351
+ let device;
1352
+ if (matchingDevices.length) {
1009
1353
  const listing = await api(profile, 'GET', '/agents/terminals');
1010
- if (!listing.devices.some(item => item.agentTerminalId === device.agentTerminalId && item.status !== 'revoked')) {
1011
- store.devices = store.devices.filter(item => item !== device);
1012
- saveStore(store);
1013
- device = undefined;
1354
+ device = selectRegisteredTerminal(matchingDevices, listing.devices, name, terminalId);
1355
+ if (!device) {
1356
+ if (matchingDevices.length > 1)
1357
+ throw new Error(`Multiple removed terminals match ${name} (${matchingDevices.map(item => item.agentTerminalId).join(', ')}). Select one with --terminal-id.`);
1358
+ await updateStore(current => {
1359
+ current.devices = current.devices.filter(item => !matchingDevices.some(stale => stale.agentTerminalId === item.agentTerminalId));
1360
+ });
1014
1361
  }
1015
1362
  }
1363
+ if (terminalId && !device)
1364
+ throw new TerminalRunnerFatalError('No approved or pending local terminal registration matches --terminal-id.');
1016
1365
  if (!device) {
1017
1366
  const currentUser = me || await api(profile, 'GET', '/me');
1018
1367
  const rt = option(argv, 'realtime-url') || profile.realtimeUrl || currentUser.instance?.endpoints?.realtime;
1019
1368
  if (!rt)
1020
1369
  throw new Error('Realtime endpoint unavailable. Pass --realtime-url.');
1021
1370
  const secret = randomBytes(32).toString('hex');
1022
- device = { agentTerminalId: randomUUID(), secret, workspace, name: option(argv, 'name') || os.hostname(),
1371
+ device = { agentTerminalId: randomUUID(), secret, workspace, name,
1023
1372
  baseUrl: profile.baseUrl, instance: profile.instance, realtimeUrl: realtimeUrl(rt) };
1024
1373
  await api(profile, 'POST', '/agents/terminals/pair', { agentTerminalId: device.agentTerminalId,
1025
1374
  secretHash: createHash('sha256').update(Buffer.from(secret, 'hex')).digest('hex'),
1026
1375
  name: device.name, workspace });
1027
- store.devices.push(device);
1028
- saveStore(store);
1376
+ try {
1377
+ await updateStore(current => {
1378
+ if (current.devices.some(item => item.agentTerminalId === device.agentTerminalId))
1379
+ throw new Error('Terminal registration ID already exists locally.');
1380
+ current.devices.push(device);
1381
+ });
1382
+ }
1383
+ catch (error) {
1384
+ try {
1385
+ await api(profile, 'POST', `/agents/terminals/${device.agentTerminalId}/revoke`);
1386
+ }
1387
+ catch {
1388
+ throw new Error(`Could not save terminal registration; remove pending grant ${device.agentTerminalId} in AI Agents → Terminals.`);
1389
+ }
1390
+ throw error;
1391
+ }
1029
1392
  console.log(`Pending approval in AI Agents → Terminals: ${device.name} (${device.agentTerminalId}).`);
1030
1393
  }
1394
+ if (device.workspace !== workspace) {
1395
+ await api(profile, 'POST', `/agents/terminals/${device.agentTerminalId}/workspaces/register`, { path: workspace, name: path.basename(workspace) });
1396
+ await updateStore(current => {
1397
+ const saved = current.devices.find(item => item.agentTerminalId === device.agentTerminalId);
1398
+ if (saved)
1399
+ saved.workspaces = [...new Set([...(saved.workspaces || [saved.workspace]), workspace])];
1400
+ });
1401
+ console.log(`Workspace registered on ${device.name} (${device.agentTerminalId}). Approve its access in AI Agents → Terminals.`);
1402
+ }
1031
1403
  for (;;) {
1032
1404
  const listing = await api(profile, 'GET', '/agents/terminals');
1033
1405
  const grant = listing.devices.find(item => item.agentTerminalId === device.agentTerminalId);
1034
1406
  if (grant?.status === 'approved')
1035
1407
  break;
1036
1408
  if (!grant || grant.status === 'revoked')
1037
- throw new Error('Terminal grant revoked or missing.');
1409
+ throw new TerminalRunnerFatalError('Terminal grant revoked or missing.');
1038
1410
  await new Promise(resolve => setTimeout(resolve, 2_000));
1039
1411
  }
1040
- await connect(profile, device);
1412
+ let releaseRunnerLock;
1413
+ try {
1414
+ releaseRunnerLock = acquireRunnerLock(device.agentTerminalId);
1415
+ }
1416
+ catch (error) {
1417
+ if (error instanceof Error && error.message.includes('already connected')) {
1418
+ console.log(`Terminal ${device.agentTerminalId} already has a local runner; its workspace contract will refresh automatically.`);
1419
+ return;
1420
+ }
1421
+ throw error;
1422
+ }
1423
+ try {
1424
+ await connect(profile, device);
1425
+ }
1426
+ finally {
1427
+ releaseRunnerLock();
1428
+ }
1429
+ }
1430
+ /** Supervisors retry crashes, but a revoked grant or 401/403 needs a human credential/grant change. */
1431
+ export async function handleTerminalCommand(argv) {
1432
+ try {
1433
+ await runTerminalCommand(argv);
1434
+ }
1435
+ catch (error) {
1436
+ if (argv.includes('--service-runner') && error instanceof TerminalRunnerFatalError) {
1437
+ console.error(error.message);
1438
+ return;
1439
+ }
1440
+ throw error;
1441
+ }
1041
1442
  }