@revoengine/cli 1.0.31 → 1.0.34

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 (113) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +152 -24
  3. package/dist/src/argument-contract.d.ts +17 -0
  4. package/dist/src/argument-contract.js +359 -0
  5. package/dist/src/automation-contract.generated.d.ts +56 -22
  6. package/dist/src/automation-contract.generated.js +68 -26
  7. package/dist/src/cli.js +15 -13
  8. package/dist/src/client.d.ts +34 -2
  9. package/dist/src/client.js +76 -13
  10. package/dist/src/commands/agents.js +5 -1
  11. package/dist/src/commands/auth.js +2 -0
  12. package/dist/src/commands/component.js +34 -17
  13. package/dist/src/commands/database-tables.js +15 -4
  14. package/dist/src/commands/database-views.js +5 -1
  15. package/dist/src/commands/endpoints.js +5 -1
  16. package/dist/src/commands/env.js +5 -1
  17. package/dist/src/commands/events.js +5 -1
  18. package/dist/src/commands/groups.js +5 -1
  19. package/dist/src/commands/info.js +2 -0
  20. package/dist/src/commands/job-templates.js +5 -1
  21. package/dist/src/commands/metadata.js +2 -0
  22. package/dist/src/commands/migrate.d.ts +2 -2
  23. package/dist/src/commands/migrate.js +33 -7
  24. package/dist/src/commands/project.js +19 -14
  25. package/dist/src/commands/request.js +2 -0
  26. package/dist/src/commands/role-groups.js +5 -1
  27. package/dist/src/commands/schedules.js +5 -1
  28. package/dist/src/commands/search.js +2 -0
  29. package/dist/src/commands/service-accounts.js +5 -1
  30. package/dist/src/commands/studio.js +2 -0
  31. package/dist/src/commands/terminal-browser-central-profile.d.ts +65 -0
  32. package/dist/src/commands/terminal-browser-central-profile.js +203 -0
  33. package/dist/src/commands/terminal-browser-human-input.d.ts +3 -1
  34. package/dist/src/commands/terminal-browser-human-input.js +3 -1
  35. package/dist/src/commands/terminal-browser-interaction.js +1 -1
  36. package/dist/src/commands/terminal-browser-live-protocol.d.ts +34 -2
  37. package/dist/src/commands/terminal-browser-live-protocol.js +28 -12
  38. package/dist/src/commands/terminal-browser-live-transport.d.ts +1 -0
  39. package/dist/src/commands/terminal-browser-live-transport.js +9 -5
  40. package/dist/src/commands/terminal-browser-live.d.ts +24 -3
  41. package/dist/src/commands/terminal-browser-live.js +199 -30
  42. package/dist/src/commands/terminal-browser-page-input.d.ts +4 -1
  43. package/dist/src/commands/terminal-browser-page-input.js +46 -1
  44. package/dist/src/commands/terminal-browser-profile-crypto.d.ts +30 -0
  45. package/dist/src/commands/terminal-browser-profile-crypto.js +101 -0
  46. package/dist/src/commands/terminal-browser-profile-import-runner.d.ts +31 -0
  47. package/dist/src/commands/terminal-browser-profile-import-runner.js +112 -0
  48. package/dist/src/commands/terminal-browser-profile-import.d.ts +28 -0
  49. package/dist/src/commands/terminal-browser-profile-import.js +125 -0
  50. package/dist/src/commands/terminal-browser-profile-import.protocol.d.ts +50 -0
  51. package/dist/src/commands/terminal-browser-profile-import.protocol.js +52 -0
  52. package/dist/src/commands/terminal-browser-profile-preferences.d.ts +1 -0
  53. package/dist/src/commands/terminal-browser-profile-preferences.js +16 -0
  54. package/dist/src/commands/terminal-browser-profile-sync.d.ts +14 -0
  55. package/dist/src/commands/terminal-browser-profile-sync.js +169 -0
  56. package/dist/src/commands/terminal-browser-profile-sync.protocol.d.ts +50 -0
  57. package/dist/src/commands/terminal-browser-profile-sync.protocol.js +19 -0
  58. package/dist/src/commands/terminal-browser-profile.d.ts +10 -1
  59. package/dist/src/commands/terminal-browser-profile.js +30 -4
  60. package/dist/src/commands/terminal-browser-recording.d.ts +39 -0
  61. package/dist/src/commands/terminal-browser-recording.js +74 -0
  62. package/dist/src/commands/terminal-browser-recording.protocol.d.ts +49 -0
  63. package/dist/src/commands/terminal-browser-recording.protocol.js +16 -0
  64. package/dist/src/commands/terminal-browser.d.ts +14 -1
  65. package/dist/src/commands/terminal-browser.js +98 -33
  66. package/dist/src/commands/terminal-file-descriptor.d.ts +9 -0
  67. package/dist/src/commands/terminal-file-descriptor.js +39 -0
  68. package/dist/src/commands/terminal-file.js +41 -6
  69. package/dist/src/commands/terminal-image.js +3 -31
  70. package/dist/src/commands/terminal-output-buffer.d.ts +18 -1
  71. package/dist/src/commands/terminal-output-buffer.js +95 -8
  72. package/dist/src/commands/terminal-process-group.d.ts +25 -0
  73. package/dist/src/commands/terminal-process-group.js +144 -0
  74. package/dist/src/commands/terminal.d.ts +3 -1
  75. package/dist/src/commands/terminal.js +366 -80
  76. package/dist/src/commands/tests.js +2 -0
  77. package/dist/src/component-lock.d.ts +15 -1
  78. package/dist/src/component-lock.js +96 -10
  79. package/dist/src/env-sync.js +12 -6
  80. package/dist/src/migration.d.ts +7 -0
  81. package/dist/src/migration.js +39 -21
  82. package/dist/src/planning-snapshot.d.ts +3 -0
  83. package/dist/src/planning-snapshot.js +60 -2
  84. package/dist/src/project.d.ts +1 -0
  85. package/dist/src/project.js +7 -8
  86. package/dist/src/resource-syncs/agent-sync.js +76 -24
  87. package/dist/src/resource-syncs/database-table-sync.d.ts +8 -1
  88. package/dist/src/resource-syncs/database-table-sync.js +66 -32
  89. package/dist/src/resource-syncs/database-view-sync.js +41 -28
  90. package/dist/src/resource-syncs/endpoint-sync.js +90 -18
  91. package/dist/src/resource-syncs/event-sync.js +33 -14
  92. package/dist/src/resource-syncs/group-sync.js +21 -11
  93. package/dist/src/resource-syncs/job-template-sync.js +98 -37
  94. package/dist/src/resource-syncs/role-group-sync.js +22 -11
  95. package/dist/src/resource-syncs/schedule-sync.js +26 -11
  96. package/dist/src/resource-syncs/service-account-sync.js +22 -11
  97. package/dist/src/reviewed-plan.js +3 -0
  98. package/dist/src/runtime-view.js +2 -18
  99. package/dist/src/sync-omit-command.d.ts +6 -0
  100. package/dist/src/sync-omit-command.js +49 -0
  101. package/dist/src/sync-omit-write-fence.d.ts +10 -0
  102. package/dist/src/sync-omit-write-fence.js +134 -0
  103. package/dist/src/sync-omit.d.ts +59 -0
  104. package/dist/src/sync-omit.js +469 -0
  105. package/dist/src/sync-output.d.ts +3 -3
  106. package/dist/src/ui.js +11 -5
  107. package/dist/src/update-notifier.d.ts +1 -1
  108. package/dist/src/update-notifier.js +2 -1
  109. package/dist/src/utils.js +46 -17
  110. package/dist/src/workspace-prune.js +11 -3
  111. package/dist/src/workspace-write-lock.d.ts +7 -0
  112. package/dist/src/workspace-write-lock.js +144 -0
  113. package/package.json +6 -5
@@ -1,3 +1,5 @@
1
+ import { BrowserSessionRecordingSink } from "./terminal-browser-recording.js";
2
+ import { validBrowserRecordingGrant } from "./terminal-browser-recording.protocol.js";
1
3
  import fs from 'node:fs';
2
4
  import { setTimeout as delay } from 'node:timers/promises';
3
5
  import os from 'node:os';
@@ -5,17 +7,24 @@ import path from 'node:path';
5
7
  import { fileURLToPath } from 'node:url';
6
8
  import { createHash, randomBytes, randomUUID } from 'node:crypto';
7
9
  import { spawn } from 'node:child_process';
10
+ import { StringDecoder } from 'node:string_decoder';
8
11
  import WebSocket from 'ws';
12
+ import { validateTerminalArguments } from "../argument-contract.js";
9
13
  import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
10
14
  import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
11
15
  import { createSandboxScratchDirectory, isTerminalSandbox, sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
12
16
  import { executionAllowedByGrant, executionPolicyDeadline, remainingPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
13
- import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
17
+ import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, revokeBrowserProfileSession, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
14
18
  import { transferWorkspaceFile, validateFileTransfer } from "./terminal-file.js";
15
19
  import { uploadWorkspaceImages } from "./terminal-image.js";
16
20
  import { ensurePtyHelperExecutable, normalizePtyStartError } from "./terminal-pty.js";
21
+ import { assertTerminalProcessProbeAvailable, ControlledTerminalProcessGroup } from "./terminal-process-group.js";
17
22
  import { TerminalReconnectGrace, TerminalTransportRecovery, isRunnerTransportHeartbeat } from "./terminal-reconnect-grace.js";
18
- import { TerminalOutputBuffer } from "./terminal-output-buffer.js";
23
+ import { CentralBrowserProfileLease } from "./terminal-browser-central-profile.js";
24
+ import { BrowserProfileRunnerRpc } from "./terminal-browser-profile-sync.js";
25
+ import { LegacyBrowserProfileImporter } from "./terminal-browser-profile-import.js";
26
+ import { BrowserProfileImportRunner } from "./terminal-browser-profile-import-runner.js";
27
+ import { TerminalOutputBuffer, TERMINAL_CAPTURE_MAX_BYTES as MAX_CAPTURE_OUTPUT_BYTES } from "./terminal-output-buffer.js";
19
28
  import { TerminalOperationalLog } from "./terminal-operational-log.js";
20
29
  import { createSecureBrowserIdentity, decryptSecureBrowserInput } from "./terminal-secure-browser.js";
21
30
  import { BrowserAuthProfileStore, macOSBrowserProfileKeyStore, validateBrowserProfileName } from "./terminal-browser-profile.js";
@@ -65,7 +74,7 @@ const configDir = getConfigDir;
65
74
  const runnerConfig = () => path.join(configDir(), 'runner.json');
66
75
  const MAX_MODEL_OUTPUT_BYTES = 100_000;
67
76
  const MAX_LOCAL_LOG_BYTES = 10_000_000;
68
- const OUTPUT_FRAME_CHARS = 1_000;
77
+ const OUTPUT_FRAME_BYTES = 12_000;
69
78
  const LOG_RETENTION_MS = 24 * 60 * 60 * 1_000;
70
79
  const OPERATIONAL_ERROR_CODES = new Set([
71
80
  'browser_binary_unavailable', 'browser_cancelled', 'browser_failed', 'browser_localhost_only',
@@ -76,10 +85,11 @@ const OPERATIONAL_ERROR_CODES = new Set([
76
85
  'browser_element_too_large', 'browser_screenshot_too_large', 'browser_output_outside_workspace',
77
86
  'browser_image_upload_unavailable', 'destructive_command_requires_approval',
78
87
  'browser_profile_busy', 'browser_profile_changed', 'browser_profile_closed',
88
+ 'browser_profile_navigation_required', 'browser_profile_save_failed', 'browser_profile_lease_expired', 'browser_profile_state_unavailable',
79
89
  'browser_profile_corrupt', 'browser_profile_scope_invalid', 'browser_profile_scope_changed',
80
90
  'browser_profile_keystore_unavailable', 'browser_profile_keystore_unsupported',
81
91
  'browser_profile_directory_invalid', 'browser_profile_too_large',
82
- 'pty_unavailable', 'sandbox_unavailable',
92
+ 'pty_unavailable', 'sandbox_unavailable', 'terminal_process_identity_unavailable', 'file_transfer_path_unverifiable',
83
93
  ]);
84
94
  const CHILD_ENV_KEYS = ['HOME', 'PATH', 'USER', 'LOGNAME', 'SHELL', 'TMPDIR', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TERM'];
85
95
  export function childEnvironment(source) {
@@ -306,7 +316,7 @@ function apiUrl(profile, route) {
306
316
  throw new Error('Remote Revo API requires HTTPS.');
307
317
  return `${base}/api/v1${route}`;
308
318
  }
309
- async function api(profile, method, route, body) {
319
+ async function api(profile, method, route, body, privateHeaders) {
310
320
  const url = apiUrl(profile, route);
311
321
  let backoffMs = 1_000;
312
322
  for (;;) {
@@ -319,7 +329,7 @@ async function api(profile, method, route, body) {
319
329
  signal: AbortSignal.any([AbortSignal.timeout(30_000), ...(profile.signal ? [profile.signal] : [])]),
320
330
  headers: { Authorization: `Bearer ${profile.token}`,
321
331
  ...(profile.instance ? { instance: profile.instance } : {}),
322
- ...(body ? { 'Content-Type': 'application/json' } : {}) },
332
+ ...(body ? { 'Content-Type': 'application/json' } : {}), ...privateHeaders },
323
333
  ...(body ? { body: JSON.stringify(body) } : {}),
324
334
  });
325
335
  }
@@ -401,6 +411,7 @@ export async function runCommand(input, onDone, onChunk) {
401
411
  throw new Error('terminal_policy_expired');
402
412
  if (sandbox !== 'unrestricted' && requiresElevatedCommand(input.cmd))
403
413
  throw new Error('destructive_command_requires_approval');
414
+ assertTerminalProcessProbeAvailable();
404
415
  const scratch = sandbox !== 'unrestricted' ? createSandboxScratchDirectory() : undefined;
405
416
  const scratchRoot = scratch ? fs.realpathSync(scratch) : undefined;
406
417
  let launch;
@@ -454,39 +465,67 @@ export async function runCommand(input, onDone, onChunk) {
454
465
  let stdout = '';
455
466
  let stderr = '';
456
467
  let modelBytes = 0;
468
+ let renderedBytes = 0;
469
+ let deliveredBytes = 0;
470
+ const deliveryTail = [];
471
+ const diagnosticReserveBytes = 512;
472
+ let previewBytes = 0;
473
+ let captureTruncated = false;
474
+ let captureDeliveryFailed = false;
457
475
  let logBytes = 0;
458
476
  let truncated = false;
459
477
  let logTruncated = logFd === undefined;
460
478
  let timedOut = false;
461
479
  let policyExpired = false;
462
480
  let finished = false;
481
+ let acceptingOutput = true;
482
+ let terminationRequested = false;
483
+ let terminationSettled = false;
484
+ let cleanupUnverified = false;
485
+ let pendingCompletion;
486
+ let terminationTimer;
487
+ const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
488
+ const truncatedStreams = new Set();
463
489
  const pid = child?.pid || terminal?.pid;
490
+ const processGroup = pid ? new ControlledTerminalProcessGroup(pid) : undefined;
491
+ const settleTermination = (unverified) => {
492
+ if (terminationSettled)
493
+ return;
494
+ terminationSettled = true;
495
+ cleanupUnverified = unverified;
496
+ if (terminationTimer)
497
+ clearTimeout(terminationTimer);
498
+ if (pendingCompletion)
499
+ finish(pendingCompletion.exitCode, pendingCompletion.error, pendingCompletion.signal);
500
+ else if (unverified)
501
+ finish(null);
502
+ };
464
503
  const terminate = () => {
465
- if (!pid)
504
+ if (finished || terminationRequested)
505
+ return;
506
+ terminationRequested = true;
507
+ const state = processGroup?.signal('SIGTERM') ?? 'stopped';
508
+ if (state === 'stopped') {
509
+ settleTermination(false);
466
510
  return;
467
- try {
468
- process.kill(-pid, 'SIGTERM');
469
- }
470
- catch {
471
- try {
472
- process.kill(pid, 'SIGTERM');
473
- }
474
- catch { /* exited */ }
475
511
  }
476
- const hardStop = setTimeout(() => {
477
- if (finished)
512
+ terminationTimer = setTimeout(() => {
513
+ const stopped = processGroup?.signal('SIGKILL') ?? 'stopped';
514
+ if (stopped !== 'owned') {
515
+ settleTermination(stopped === 'unverified');
478
516
  return;
479
- try {
480
- process.kill(-pid, 'SIGKILL');
481
517
  }
482
- catch {
483
- try {
484
- process.kill(pid, 'SIGKILL');
518
+ const deadline = Date.now() + 500;
519
+ const awaitStopped = () => {
520
+ const remaining = processGroup?.state() ?? 'stopped';
521
+ if (remaining !== 'owned' || Date.now() >= deadline) {
522
+ settleTermination(remaining !== 'stopped');
523
+ return;
485
524
  }
486
- catch { /* exited */ }
487
- }
525
+ terminationTimer = setTimeout(awaitStopped, 25);
526
+ };
527
+ awaitStopped();
488
528
  }, 2_000);
489
- hardStop.unref?.();
490
529
  };
491
530
  const timer = input.background === true ? undefined : setTimeout(() => { timedOut = true; terminate(); }, Math.min(Math.max(input.timeoutMs, 1_000), MAX_TERMINAL_PROCESS_MS));
492
531
  let policyTimer;
@@ -501,7 +540,60 @@ export async function runCommand(input, onDone, onChunk) {
501
540
  }, Math.max(0, deadline - Date.now()));
502
541
  };
503
542
  updatePolicyDeadline(input.policyDeadlineMs ?? null);
504
- const append = (chunk, kind) => {
543
+ const deliverBytes = (bytes, kind) => {
544
+ if (!onChunk || captureDeliveryFailed)
545
+ return;
546
+ for (let offset = 0; offset < bytes.length;) {
547
+ let end = Math.min(offset + OUTPUT_FRAME_BYTES, bytes.length);
548
+ while (end < bytes.length && (bytes[end] & 0xc0) === 0x80)
549
+ end--;
550
+ if (onChunk(kind, bytes.subarray(offset, end).toString('utf8')) === false) {
551
+ captureDeliveryFailed = true;
552
+ captureTruncated = true;
553
+ truncated = true;
554
+ break;
555
+ }
556
+ deliveredBytes += end - offset;
557
+ offset = end;
558
+ }
559
+ };
560
+ const emitText = (text, kind) => {
561
+ const decoded = Buffer.from(text);
562
+ const captureLimit = input.captureOutput ? MAX_CAPTURE_OUTPUT_BYTES : MAX_MODEL_OUTPUT_BYTES;
563
+ let limit = Math.min(decoded.length, Math.max(0, captureLimit - renderedBytes));
564
+ while (limit > 0 && limit < decoded.length && (decoded[limit] & 0xc0) === 0x80)
565
+ limit--;
566
+ if (limit < decoded.length) {
567
+ truncated = true;
568
+ captureTruncated = true;
569
+ }
570
+ renderedBytes += limit;
571
+ const bytes = decoded.subarray(0, limit);
572
+ let previewEnd = Math.min(bytes.length, Math.max(0, MAX_MODEL_OUTPUT_BYTES - previewBytes));
573
+ while (previewEnd > 0 && previewEnd < bytes.length && (bytes[previewEnd] & 0xc0) === 0x80)
574
+ previewEnd--;
575
+ if (previewEnd < bytes.length)
576
+ truncated = true;
577
+ previewBytes += previewEnd;
578
+ const projected = bytes.subarray(0, previewEnd).toString('utf8');
579
+ if (kind === 'stdout')
580
+ stdout += projected;
581
+ else
582
+ stderr += projected;
583
+ if (!onChunk || !bytes.length || captureDeliveryFailed)
584
+ return;
585
+ // Reserve only the final bytes at the capture boundary. Interactive output
586
+ // remains immediate; successful completion flushes the held tail unchanged.
587
+ let immediate = Math.min(bytes.length, Math.max(0, captureLimit - diagnosticReserveBytes - deliveredBytes));
588
+ while (immediate > 0 && immediate < bytes.length && (bytes[immediate] & 0xc0) === 0x80)
589
+ immediate--;
590
+ deliverBytes(bytes.subarray(0, immediate), kind);
591
+ if (immediate < bytes.length)
592
+ deliveryTail.push({ kind, bytes: Buffer.from(bytes.subarray(immediate)) });
593
+ };
594
+ const append = (chunk, kind, render = true) => {
595
+ if (!acceptingOutput)
596
+ return;
505
597
  const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
506
598
  if (logPart.length && logFd !== undefined) {
507
599
  const header = Buffer.from(`[${kind}] `);
@@ -526,36 +618,72 @@ export async function runCommand(input, onDone, onChunk) {
526
618
  }
527
619
  if (logPart.length < chunk.length)
528
620
  logTruncated = true;
529
- const available = Math.max(0, MAX_MODEL_OUTPUT_BYTES - modelBytes);
621
+ if (!render)
622
+ return;
623
+ const available = Math.max(0, (input.captureOutput ? MAX_CAPTURE_OUTPUT_BYTES : MAX_MODEL_OUTPUT_BYTES) - modelBytes);
530
624
  const modelPart = chunk.subarray(0, available);
531
625
  modelBytes += modelPart.length;
532
- if (modelPart.length < chunk.length)
626
+ if (modelPart.length < chunk.length) {
533
627
  truncated = true;
534
- const text = modelPart.toString('utf8');
535
- if (kind === 'stdout')
536
- stdout += text;
537
- else
538
- stderr += text;
539
- if (onChunk && text) {
540
- for (let offset = 0; offset < text.length; offset += OUTPUT_FRAME_CHARS)
541
- onChunk(kind, text.slice(offset, offset + OUTPUT_FRAME_CHARS));
628
+ captureTruncated = true;
629
+ truncatedStreams.add(kind);
542
630
  }
631
+ emitText(decoders[kind].write(modelPart), kind);
543
632
  };
544
633
  child?.stdout?.on('data', (chunk) => append(chunk, 'stdout'));
545
634
  child?.stderr?.on('data', (chunk) => append(chunk, 'stderr'));
546
635
  terminal?.onData(text => append(Buffer.from(text), 'stdout'));
547
- const finish = (exitCode, error, signal) => {
636
+ function finish(exitCode, error, signal) {
548
637
  if (finished)
549
638
  return;
550
- finished = true;
551
639
  if (timer)
552
640
  clearTimeout(timer);
553
641
  if (policyTimer)
554
642
  clearTimeout(policyTimer);
643
+ if (!terminationSettled) {
644
+ const state = processGroup?.state() ?? 'stopped';
645
+ if (terminationRequested || state !== 'stopped') {
646
+ pendingCompletion = { exitCode, error, signal };
647
+ if (state === 'stopped')
648
+ settleTermination(false);
649
+ else
650
+ terminate();
651
+ return;
652
+ }
653
+ }
654
+ finished = true;
655
+ if (terminationTimer)
656
+ clearTimeout(terminationTimer);
657
+ const cleanupDiagnostic = 'terminal_process_cleanup_unverified: command may have run; do not automatically rerun. Controlled processes could not be confirmed stopped.';
555
658
  const diagnostic = [error?.message, policyExpired ? 'terminal_policy_expired' : null].filter(Boolean).join('\n');
556
659
  if (diagnostic)
557
660
  append(Buffer.from(`${stderr && !stderr.endsWith('\n') ? '\n' : ''}${diagnostic}`), 'stderr');
558
- if (scratch) {
661
+ for (const kind of ['stdout', 'stderr']) {
662
+ const tail = decoders[kind].end();
663
+ // A byte-limit cut can leave half a character; do not expand it past the limit.
664
+ if (!truncatedStreams.has(kind))
665
+ emitText(tail, kind);
666
+ }
667
+ if (cleanupUnverified) {
668
+ append(Buffer.from(`\n${cleanupDiagnostic}\n`), 'stderr', false);
669
+ if (deliveryTail.length) {
670
+ captureTruncated = true;
671
+ truncated = true;
672
+ }
673
+ deliveryTail.length = 0;
674
+ deliverBytes(Buffer.from(`${cleanupDiagnostic}\n`), 'stderr');
675
+ // Cleanup uncertainty must survive a full preview and result-frame
676
+ // truncation. A missing execution cannot safely be inferred or replayed.
677
+ const bounded = boundResultFrame({ stdout, stderr: `${cleanupDiagnostic}\n${stderr.replace(cleanupDiagnostic, '')}`, truncated });
678
+ stdout = String(bounded.stdout);
679
+ stderr = String(bounded.stderr);
680
+ truncated = bounded.truncated === true;
681
+ }
682
+ else
683
+ for (const tail of deliveryTail)
684
+ deliverBytes(tail.bytes, tail.kind);
685
+ acceptingOutput = false;
686
+ if (scratch && !cleanupUnverified) {
559
687
  try {
560
688
  fs.rmSync(scratch, { recursive: true, force: true });
561
689
  }
@@ -569,12 +697,13 @@ export async function runCommand(input, onDone, onChunk) {
569
697
  logTruncated = true;
570
698
  }
571
699
  }
572
- onDone({ executed: !error, exitCode: (timedOut || policyExpired) && exitCode === 0 ? null : exitCode,
700
+ onDone({ executed: cleanupUnverified || !error, exitCode: cleanupUnverified || (timedOut || policyExpired) && exitCode === 0 ? null : exitCode,
573
701
  stdout, stderr,
574
702
  timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath,
703
+ ...(input.captureOutput ? { captureTruncated } : {}),
575
704
  ...(signal ? { signal } : {}),
576
705
  ...(policyExpired ? { policyExpired: true } : {}) });
577
- };
706
+ }
578
707
  child?.on('close', (code, signal) => finish(code, undefined, signal));
579
708
  child?.on('error', error => finish(null, error));
580
709
  terminal?.onExit(({ exitCode }) => finish(exitCode));
@@ -668,7 +797,7 @@ export function runWorkspacePatch(input, onDone) {
668
797
  child.on('error', error => finish(null, error));
669
798
  return Object.assign(child, { updatePolicyDeadline });
670
799
  }
671
- async function connect(profile, device, authProfile) {
800
+ async function connect(profile, device, legacyImportAvailable) {
672
801
  const logDeviceId = /^[A-Za-z0-9_-]{1,128}$/u.test(device.agentTerminalId)
673
802
  ? device.agentTerminalId : createHash('sha256').update(device.agentTerminalId).digest('hex');
674
803
  const operationalLog = new TerminalOperationalLog(path.join(configDir(), 'logs', 'terminal', logDeviceId));
@@ -678,6 +807,7 @@ async function connect(profile, device, authProfile) {
678
807
  let activeSocket;
679
808
  let activeConnectionId = '';
680
809
  let durableOutput = false;
810
+ let captureOutput = false;
681
811
  const activeChildren = new Set();
682
812
  const children = new Map();
683
813
  const activePolicies = new Map();
@@ -688,9 +818,10 @@ async function connect(profile, device, authProfile) {
688
818
  const completed = new Map();
689
819
  const traces = new Map();
690
820
  const secureRequests = new Map();
691
- const profilePreferences = process.platform === 'darwin' && !process.argv.includes('--service-runner')
692
- ? new BrowserProfilePreferences(authProfile?.store || new BrowserAuthProfileStore(path.join(configDir(), 'browser-profiles'), macOSBrowserProfileKeyStore())) : undefined;
693
821
  const browserScopes = new Map();
822
+ const centralProfiles = new Map();
823
+ const recordingSinks = new Map();
824
+ const revokedProfileSessions = new Map();
694
825
  const resumed = new Set();
695
826
  const reconnectGrace = new TerminalReconnectGrace(() => {
696
827
  for (const child of children.values())
@@ -731,10 +862,20 @@ async function connect(profile, device, authProfile) {
731
862
  const flushExecution = (executionId) => {
732
863
  if (!resumed.has(executionId))
733
864
  return;
734
- for (const chunk of outputByExecution.get(executionId)?.pending() || [])
735
- sendCurrent({ type: 'output', executionId, ...chunk });
865
+ const buffer = outputByExecution.get(executionId);
866
+ if (!buffer)
867
+ return;
868
+ // Limit frames in flight, including on reconnect. Completion follows committed output.
869
+ do {
870
+ const chunks = buffer.takeUnsent();
871
+ for (const chunk of chunks)
872
+ sendCurrent({ type: 'output', executionId, ...chunk });
873
+ if (durableOutput || !chunks.length)
874
+ break;
875
+ buffer.acknowledge(chunks.at(-1).sequence);
876
+ } while (buffer.lastAcknowledged < buffer.lastSequence);
736
877
  const result = completed.get(executionId);
737
- if (result)
878
+ if (result && buffer.lastAcknowledged === buffer.lastSequence)
738
879
  sendCurrent({ type: 'result', executionId, ...result });
739
880
  };
740
881
  const stop = () => {
@@ -773,7 +914,7 @@ async function connect(profile, device, authProfile) {
773
914
  return { browserSessionId: frame.browserSessionId, liveSessionId: frame.liveSessionId,
774
915
  actorUserId: frame.actorUserId, threadId: frame.threadId,
775
916
  agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId, connectionId: frame.connectionId,
776
- identity: secureIdentity, profilePreferences, profileOwner: scope.owner,
917
+ identity: secureIdentity, profileOwner: scope.owner,
777
918
  initialControl: { controlEpoch: frame.controlEpoch, mode: frame.mode, private: frame.private },
778
919
  recordingDirectory: path.join(fs.realpathSync(configDir()), 'browser-recordings', device.agentTerminalId),
779
920
  isAuthorized: () => liveAuthorized(frame) };
@@ -786,6 +927,8 @@ async function connect(profile, device, authProfile) {
786
927
  });
787
928
  activeSocket = socket;
788
929
  let connectionId = '';
930
+ let profileRpc;
931
+ let profileImports;
789
932
  let defaultWorkspace = device.workspace;
790
933
  let heartbeat;
791
934
  let lastHeartbeat = Date.now();
@@ -795,12 +938,12 @@ async function connect(profile, device, authProfile) {
795
938
  reconnectGrace.clear();
796
939
  });
797
940
  socket.on('open', () => send(socket, { type: 'hello', protocol: 1, agentTerminalId: device.agentTerminalId,
798
- secret: device.secret, browserSessionIds: browserSessionIds(), capabilities: ['terminal_resume_durable_v1', 'grant_refresh_v1', 'workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
941
+ secret: device.secret, browserSessionIds: browserSessionIds(), capabilities: ['terminal_output_capture_v1', 'terminal_resume_durable_v1', 'grant_refresh_v1', 'workspace_sandbox_v1', 'workspace_network_v1', 'network_policy_v1',
799
942
  'terminal_policy_v2', 'terminal_policy_selective_v1', 'background_shell_v1', 'terminal_thread_scope_v1',
800
943
  'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
801
944
  'browser_local_v1', 'browser_once_v1', 'browser_secure_input_v1', 'browser_tabs_v1', 'save_image_v1',
802
- 'browser_timeout_v1', 'browser_public_read_v1', 'terminal_workspaces_v1', 'file_transfer_v1', 'browser_control_v1', 'browser_live_v1', 'browser_interaction_v1', 'browser_recording_v1',
803
- ...(profilePreferences ? ['browser_profiles_v1'] : []),
945
+ 'browser_timeout_v1', 'browser_public_read_v1', 'terminal_workspaces_v1', 'file_transfer_v1', 'browser_control_v1', 'browser_live_v1', 'browser_interaction_v1', 'browser_controls_v2', 'browser_recording_v1', 'browser_recording_session_v1',
946
+ 'browser_profiles_v2', ...(legacyImportAvailable ? ['browser_profile_import_v1'] : []),
804
947
  ...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])],
805
948
  secureBrowserPublicKey: secureIdentity.publicKey, secureBrowserKeyId: secureIdentity.keyId }));
806
949
  socket.on('message', raw => {
@@ -817,6 +960,20 @@ async function connect(profile, device, authProfile) {
817
960
  lastHeartbeat = Date.now();
818
961
  return;
819
962
  }
963
+ if (frame.type === 'browser_profile_sync_result') {
964
+ profileRpc?.accept(frame);
965
+ return;
966
+ }
967
+ if (frame.type === 'browser_profile_import') {
968
+ profileImports?.accept(frame);
969
+ return;
970
+ }
971
+ if (frame.type === 'browser_profile_import_ack') {
972
+ profileImports?.acceptAck(frame);
973
+ return;
974
+ }
975
+ if (frame.type === 'browser_profile_revoked' && frame.connectionId === connectionId && frame.browserProfileId)
976
+ profileImports?.revokeProfile(frame.browserProfileId);
820
977
  incoming = incoming.then(async () => {
821
978
  if (stopping || socket.readyState !== WebSocket.OPEN)
822
979
  return;
@@ -828,8 +985,22 @@ async function connect(profile, device, authProfile) {
828
985
  lastHeartbeat = Date.now();
829
986
  securePolicyEpoch++;
830
987
  connectionId = frame.connectionId;
988
+ profileRpc = new BrowserProfileRunnerRpc(connectionId, request => send(socket, request));
831
989
  activeConnectionId = connectionId;
990
+ profileImports = new BrowserProfileImportRunner({ connectionId, instanceId: profile.instance,
991
+ terminalId: device.agentTerminalId, keyId: secureIdentity.keyId, privateKey: secureIdentity.privateKey,
992
+ baseUrl: profile.baseUrl, rpc: profileRpc,
993
+ importer: new LegacyBrowserProfileImporter(legacyImportAvailable, () => new BrowserAuthProfileStore(path.join(configDir(), 'browser-profiles'), macOSBrowserProfileKeyStore())),
994
+ authorized: request => {
995
+ if (!legacyImportAvailable || stopping || policyRevisionUnavailable || activeConnectionId !== connectionId
996
+ || socket.readyState !== WebSocket.OPEN || request.grantRevision !== minimumPolicyGrantRevision)
997
+ return false;
998
+ const saved = readStore().devices.find(item => item.agentTerminalId === device.agentTerminalId
999
+ && item.baseUrl === profile.baseUrl && item.instance === profile.instance);
1000
+ return [device.workspace, ...(saved?.workspaces || [])].includes(request.workspace);
1001
+ }, send: reply => send(socket, reply) });
832
1002
  durableOutput = Array.isArray(frame.capabilities) && frame.capabilities.includes('terminal_resume_durable_v1');
1003
+ captureOutput = durableOutput && frame.capabilities.includes('terminal_output_capture_v1');
833
1004
  defaultWorkspace = frame.workspace || device.workspace;
834
1005
  if (Number.isSafeInteger(frame.policyGrantRevision) && frame.policyGrantRevision >= 0) {
835
1006
  minimumPolicyGrantRevision = Math.max(minimumPolicyGrantRevision, frame.policyGrantRevision);
@@ -858,6 +1029,19 @@ async function connect(profile, device, authProfile) {
858
1029
  }
859
1030
  if (frame.type === 'heartbeat')
860
1031
  return;
1032
+ if (frame.type === 'browser_profile_revoked') {
1033
+ if (frame.connectionId === connectionId && frame.browserSessionId && frame.browserProfileId) {
1034
+ for (const [id, expiresAt] of revokedProfileSessions)
1035
+ if (expiresAt <= Date.now())
1036
+ revokedProfileSessions.delete(id);
1037
+ revokedProfileSessions.set(frame.browserSessionId, Date.now() + 60_000);
1038
+ const central = centralProfiles.get(frame.browserSessionId);
1039
+ centralProfiles.delete(frame.browserSessionId);
1040
+ await revokeBrowserProfileSession(frame.browserSessionId, frame.browserProfileId);
1041
+ await central?.lease.release();
1042
+ }
1043
+ return;
1044
+ }
861
1045
  if (frame.type === 'browser_scope_revoked') {
862
1046
  if (frame.connectionId === connectionId && typeof frame.browserSessionId === 'string'
863
1047
  && /^[a-f0-9]{64}$/u.test(frame.browserSessionId)) {
@@ -952,8 +1136,11 @@ async function connect(profile, device, authProfile) {
952
1136
  if (frame.connectionId !== connectionId || !frame.executionId)
953
1137
  return;
954
1138
  if (frame.type === 'output_ack') {
955
- if (durableOutput && !outputByExecution.get(frame.executionId)?.acknowledge(frame.lastOutputSequence))
1139
+ if (durableOutput && !outputByExecution.get(frame.executionId)?.acknowledge(frame.lastOutputSequence)) {
956
1140
  socket.terminate();
1141
+ return;
1142
+ }
1143
+ flushExecution(frame.executionId);
957
1144
  return;
958
1145
  }
959
1146
  if (frame.type === 'resumed') {
@@ -961,6 +1148,7 @@ async function connect(profile, device, authProfile) {
961
1148
  socket.terminate();
962
1149
  return;
963
1150
  }
1151
+ outputByExecution.get(frame.executionId)?.resetTransport();
964
1152
  recovery.accepted(frame.executionId);
965
1153
  resumed.add(frame.executionId);
966
1154
  flushExecution(frame.executionId);
@@ -981,6 +1169,7 @@ async function connect(profile, device, authProfile) {
981
1169
  retiredExecutions.delete(id);
982
1170
  nextRetiredSweep = now + 60_000;
983
1171
  }
1172
+ outputByExecution.get(frame.executionId)?.dispose();
984
1173
  outputByExecution.delete(frame.executionId);
985
1174
  resumed.delete(frame.executionId);
986
1175
  traces.delete(frame.executionId);
@@ -1090,7 +1279,7 @@ async function connect(profile, device, authProfile) {
1090
1279
  traces.set(frame.executionId, trace);
1091
1280
  operationalLog.write('INFO', trace, 'execution.started', { operation, sandbox: frame.sandbox });
1092
1281
  resumed.add(frame.executionId);
1093
- outputByExecution.set(frame.executionId, new TerminalOutputBuffer());
1282
+ outputByExecution.set(frame.executionId, new TerminalOutputBuffer({ spool: true }));
1094
1283
  if (operation === 'save_image' || operation === 'upload_file' || operation === 'download_file') {
1095
1284
  const controller = new AbortController();
1096
1285
  const policyDeadline = executionPolicyDeadline(frame);
@@ -1156,25 +1345,92 @@ async function connect(profile, device, authProfile) {
1156
1345
  children.set(frame.executionId, child);
1157
1346
  activeChildren.add(child);
1158
1347
  send(socket, { type: 'ack', connectionId, executionId: frame.executionId });
1159
- void runBrowserAction({ url: frame.url, action: frame.browserAction, workspace, agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId,
1160
- browserSessionId: frame.browserSessionId, tabId: frame.tabId,
1161
- onActionAttempt: () => { actionAttempted = true; },
1162
- interaction: frame.browserInteraction, selector: frame.selector, width: frame.width, height: frame.height,
1163
- value: frame.value, checked: frame.checked, key: frame.key, deltaY: frame.deltaY,
1164
- state: frame.state, waitTimeoutMs: frame.waitTimeoutMs,
1165
- actionTimeoutMs: frame.actionTimeoutMs,
1166
- capture: frame.capture, clip: frame.clip,
1167
- localOnly: frame.browserLocalOnly === true,
1168
- networkAccessExpiresAt: frame.networkAccessExpiresAt,
1169
- networkAccessOnce: frame.networkAccessOnce,
1170
- networkAccessForThread: frame.networkAccessForThread, actorUserId: frame.actorUserId,
1171
- threadId: frame.browserTargetThreadId || frame.assistantThreadId, policyGrantRevision: frame.policyGrantRevision,
1172
- ...(profilePreferences && frame.actorUserId ? { resolveAuthProfile: () => profilePreferences.resolveAsync({
1173
- baseUrl: device.baseUrl, instanceId: device.instance, actorUserId: frame.actorUserId,
1174
- terminalId: device.agentTerminalId, workspace
1175
- }, authProfile?.name) } : {}),
1176
- signal: controller.signal })
1348
+ void (async () => {
1349
+ if (frame.browserSessionId && revokedProfileSessions.has(frame.browserSessionId))
1350
+ throw new Error('browser_profile_lease_expired');
1351
+ let central = frame.browserSessionId ? centralProfiles.get(frame.browserSessionId) : undefined;
1352
+ const grant = frame.browserProfileGrant;
1353
+ if (grant) {
1354
+ if (!profileRpc || central || grant.profile.id !== frame.browserProfileId || grant.scope.browserProfileId !== grant.profile.id
1355
+ || grant.scope.instanceId !== device.instance || grant.scope.agentTerminalId !== device.agentTerminalId
1356
+ || grant.scope.agentTerminalWorkspaceId !== (frame.agentTerminalWorkspaceId || device.agentTerminalId)
1357
+ || grant.scope.actorUserId !== frame.actorUserId || grant.scope.assistantThreadId !== (frame.browserTargetThreadId || frame.assistantThreadId)
1358
+ || grant.scope.connectionId !== connectionId || grant.scope.keyId !== secureIdentity.keyId
1359
+ || grant.scope.browserSessionId !== frame.browserSessionId || !Number.isSafeInteger(grant.scope.generation)
1360
+ || grant.scope.generation < 1 || !Number.isSafeInteger(grant.revision) || grant.revision < 0)
1361
+ throw new Error('browser_profile_scope_changed');
1362
+ const lease = await CentralBrowserProfileLease.open({ ...grant, digest: grant.download?.digest }, secureIdentity.privateKey, profileRpc.transport(grant), async () => {
1363
+ centralProfiles.delete(grant.scope.browserSessionId);
1364
+ await revokeBrowserProfileSession(grant.scope.browserSessionId, grant.profile.id);
1365
+ });
1366
+ if (revokedProfileSessions.has(grant.scope.browserSessionId)) {
1367
+ await lease.release();
1368
+ throw new Error('browser_profile_lease_expired');
1369
+ }
1370
+ central = { ...grant.profile, lease };
1371
+ centralProfiles.set(grant.scope.browserSessionId, central);
1372
+ }
1373
+ if (frame.browserProfileId && (!central || central.id !== frame.browserProfileId))
1374
+ throw new Error('browser_profile_lease_expired');
1375
+ const recordingGrant = frame.browserRecording;
1376
+ if (recordingGrant && (!validBrowserRecordingGrant(recordingGrant)
1377
+ || recordingGrant.browserSessionId !== frame.browserSessionId))
1378
+ throw new Error('browser_recording_scope_invalid');
1379
+ const recordingDirectory = path.join(fs.realpathSync(configDir()), 'browser-recordings', device.agentTerminalId);
1380
+ for (const [id, stale] of recordingSinks)
1381
+ if (id !== frame.browserSessionId && !browserSessionIds().includes(id)) {
1382
+ void stale.settled().finally(() => { if (recordingSinks.get(id) === stale)
1383
+ recordingSinks.delete(id); });
1384
+ }
1385
+ const recordingAuthorized = () => activeConnectionId === frame.connectionId && minimumPolicyGrantRevision === frame.policyGrantRevision
1386
+ && !policyRevisionUnavailable && (frame.networkAccessExpiresAt == null || frame.networkAccessExpiresAt > Date.now());
1387
+ let sink = recordingSinks.get(frame.browserSessionId);
1388
+ if (recordingGrant && sink)
1389
+ sink.refresh(recordingGrant, recordingAuthorized);
1390
+ if (recordingGrant && !sink) {
1391
+ sink = new BrowserSessionRecordingSink({ grant: recordingGrant,
1392
+ terminalId: device.agentTerminalId, directory: recordingDirectory, isAuthorized: recordingAuthorized,
1393
+ request: (route, token, body) => api(profile, 'POST', route, body, { 'x-revo-browser-recording-token': token }),
1394
+ onStatus: (status, recordingId) => operationalLog.write(status === 'saved' ? 'INFO' : 'ERROR', trace, 'browser.recording', { status, recordingId }),
1395
+ });
1396
+ recordingSinks.set(frame.browserSessionId, sink);
1397
+ }
1398
+ return runBrowserAction({ url: frame.url, action: frame.browserAction, workspace,
1399
+ agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId ?? (recordingGrant ? device.agentTerminalId : undefined),
1400
+ browserSessionId: frame.browserSessionId, tabId: frame.tabId,
1401
+ onActionAttempt: () => { actionAttempted = true; },
1402
+ interaction: frame.browserInteraction, selector: frame.selector, width: frame.width, height: frame.height,
1403
+ value: frame.value, checked: frame.checked, key: frame.key, deltaY: frame.deltaY,
1404
+ state: frame.state, waitTimeoutMs: frame.waitTimeoutMs,
1405
+ actionTimeoutMs: frame.actionTimeoutMs,
1406
+ capture: frame.capture, clip: frame.clip,
1407
+ localOnly: frame.browserLocalOnly === true,
1408
+ networkAccessExpiresAt: frame.networkAccessExpiresAt,
1409
+ networkAccessOnce: frame.networkAccessOnce,
1410
+ networkAccessForThread: frame.networkAccessForThread, actorUserId: frame.actorUserId,
1411
+ threadId: frame.browserTargetThreadId || frame.assistantThreadId, policyGrantRevision: frame.policyGrantRevision,
1412
+ ...(central ? { centralProfile: central } : {}),
1413
+ ...(recordingGrant && sink ? { recording: { policyGrantRevision: frame.policyGrantRevision, networkAccessExpiresAt: frame.networkAccessExpiresAt ?? null,
1414
+ options: { browserSessionId: frame.browserSessionId, liveSessionId: recordingGrant.grantId,
1415
+ actorUserId: frame.actorUserId, threadId: frame.browserTargetThreadId || frame.assistantThreadId,
1416
+ agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId || device.agentTerminalId, connectionId: frame.connectionId,
1417
+ identity: secureIdentity, profileOwner: { baseUrl: device.baseUrl, instanceId: device.instance,
1418
+ actorUserId: frame.actorUserId, terminalId: device.agentTerminalId, workspace },
1419
+ browserSettings: recordingGrant.settings, recordingDirectory,
1420
+ isAuthorized: () => sink.authorized, onFrame: () => undefined, onRecording: item => sink.accept(item) },
1421
+ } } : {}),
1422
+ signal: controller.signal });
1423
+ })()
1177
1424
  .then(async (browserResult) => {
1425
+ if (!browserResult.tabs.length) {
1426
+ centralProfiles.delete(browserResult.browserSessionId);
1427
+ const sink = recordingSinks.get(browserResult.browserSessionId);
1428
+ if (sink)
1429
+ void sink.settled().finally(() => {
1430
+ if (recordingSinks.get(browserResult.browserSessionId) === sink)
1431
+ recordingSinks.delete(browserResult.browserSessionId);
1432
+ });
1433
+ }
1178
1434
  if (frame.browserAction !== 'read_public')
1179
1435
  browserScopes.set(browserResult.browserSessionId, { workspace, workspaceId: frame.agentTerminalWorkspaceId || device.agentTerminalId,
1180
1436
  owner: { baseUrl: device.baseUrl, instanceId: device.instance, actorUserId: frame.actorUserId || '', terminalId: device.agentTerminalId, workspace },
@@ -1202,7 +1458,13 @@ async function connect(profile, device, authProfile) {
1202
1458
  browserAction: frame.browserAction, exitCode: 0, screenshot: frame.browserAction === 'screenshot' });
1203
1459
  if (resumed.has(frame.executionId))
1204
1460
  flushExecution(frame.executionId);
1205
- }).catch(error => {
1461
+ }).catch(async (error) => {
1462
+ if (frame.browserProfileGrant && frame.browserSessionId) {
1463
+ const central = centralProfiles.get(frame.browserSessionId);
1464
+ centralProfiles.delete(frame.browserSessionId);
1465
+ await revokeBrowserProfileSession(frame.browserSessionId, frame.browserProfileGrant.profile.id).catch(() => undefined);
1466
+ await central?.lease.release();
1467
+ }
1206
1468
  if (policyTimer)
1207
1469
  clearTimeout(policyTimer);
1208
1470
  children.delete(frame.executionId);
@@ -1251,6 +1513,7 @@ async function connect(profile, device, authProfile) {
1251
1513
  return;
1252
1514
  }
1253
1515
  const child = await runCommand({ cmd: frame.cmd, workdir: frame.workdir || workspace,
1516
+ captureOutput,
1254
1517
  workspace, sandbox: frame.sandbox, networkAccess: frame.networkAccess,
1255
1518
  policyDeadlineMs: executionPolicyDeadline(frame),
1256
1519
  timeoutMs: frame.timeoutMs || 60_000, background: frame.background === true, tty: frame.tty,
@@ -1266,15 +1529,19 @@ async function connect(profile, device, authProfile) {
1266
1529
  executed: completion.executed,
1267
1530
  timedOut: completion.timedOut, truncated: completion.truncated });
1268
1531
  if (resumed.has(frame.executionId))
1269
- sendCurrent({ type: 'result', executionId: frame.executionId,
1270
- ...completed.get(frame.executionId) });
1532
+ flushExecution(frame.executionId);
1271
1533
  }, (stream, text) => {
1272
1534
  const buffer = outputByExecution.get(frame.executionId);
1273
1535
  if (!buffer)
1274
1536
  return;
1275
- const chunk = buffer.append(stream, text);
1537
+ try {
1538
+ buffer.append(stream, text);
1539
+ }
1540
+ catch {
1541
+ return false;
1542
+ } // Capture is explicitly partial; never kill or replay the command.
1276
1543
  if (resumed.has(frame.executionId))
1277
- sendCurrent({ type: 'output', executionId: frame.executionId, ...chunk });
1544
+ flushExecution(frame.executionId);
1278
1545
  });
1279
1546
  children.set(frame.executionId, child);
1280
1547
  activeChildren.add(child);
@@ -1283,6 +1550,7 @@ async function connect(profile, device, authProfile) {
1283
1550
  catch (error) {
1284
1551
  activePolicies.delete(frame.executionId);
1285
1552
  resumed.delete(frame.executionId);
1553
+ outputByExecution.get(frame.executionId)?.dispose();
1286
1554
  outputByExecution.delete(frame.executionId);
1287
1555
  traces.delete(frame.executionId);
1288
1556
  operationalLog.write('ERROR', trace, 'execution.rejected', { operation,
@@ -1293,6 +1561,12 @@ async function connect(profile, device, authProfile) {
1293
1561
  }).catch(() => socket.terminate());
1294
1562
  });
1295
1563
  socket.on('close', (code, reason) => {
1564
+ profileImports?.dispose();
1565
+ profileRpc?.dispose();
1566
+ for (const [sessionId, central] of centralProfiles) {
1567
+ centralProfiles.delete(sessionId);
1568
+ void revokeBrowserProfileSession(sessionId, central.id).catch(() => undefined);
1569
+ }
1296
1570
  live.disconnectAll();
1297
1571
  securePolicyEpoch++;
1298
1572
  operationalLog.write(code === 1000 ? 'INFO' : 'WARN', {}, 'socket.closed', { code, activeExecutions: children.size, policyViolation: code === 1008 });
@@ -1354,6 +1628,9 @@ async function connect(profile, device, authProfile) {
1354
1628
  }
1355
1629
  finally {
1356
1630
  stop();
1631
+ for (const buffer of outputByExecution.values())
1632
+ buffer.dispose();
1633
+ outputByExecution.clear();
1357
1634
  process.off('SIGINT', stop);
1358
1635
  process.off('SIGTERM', stop);
1359
1636
  }
@@ -1362,9 +1639,19 @@ async function runTerminalCommand(argv, signal) {
1362
1639
  const command = argv[0] || 'help';
1363
1640
  const browserProfileName = selectedBrowserProfile(argv);
1364
1641
  if (command === 'help' || argv.includes('--help')) {
1365
- console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID] [--url URL] [--realtime-url URL]\nrevo terminal connect [--browser-profile NAME] (macOS foreground only)\nrevo terminal browser-profile forget --browser-profile NAME --workspace PATH --terminal-id UUID [--project NAME]\nrevo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]');
1642
+ console.log([
1643
+ 'revo terminal connect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID] [--realtime-url URL]',
1644
+ 'revo terminal status [--project NAME]',
1645
+ 'revo terminal disconnect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID]',
1646
+ 'API connection overrides: --url URL --token API_KEY --instance UUID (not service install/uninstall).',
1647
+ 'Browser profiles are assigned in Revo Vault, including Linux/service runners.',
1648
+ 'Legacy local cleanup: revo terminal browser-profile forget --browser-profile NAME --workspace PATH --terminal-id UUID [--project NAME]',
1649
+ 'revo terminal service install|uninstall --workspace PATH [--project NAME] [--name NAME|--terminal-id UUID]',
1650
+ ].join('\n'));
1366
1651
  return;
1367
1652
  }
1653
+ if (command === 'connect' && browserProfileName)
1654
+ throw new Error('Browser profiles are managed in Revo Vault. --browser-profile is no longer a connect option. Existing local profiles are not deleted.');
1368
1655
  if (command === 'service') {
1369
1656
  const action = argv[1];
1370
1657
  if (!action || action === 'help') {
@@ -1585,15 +1872,13 @@ async function runTerminalCommand(argv, signal) {
1585
1872
  }
1586
1873
  catch (error) {
1587
1874
  if (error instanceof Error && error.message.includes('already connected')) {
1588
- if (authProfile)
1589
- throw new Error('Stop the existing terminal runner before selecting --browser-profile.');
1590
1875
  console.log(`Terminal ${device.agentTerminalId} already has a local runner; its workspace contract will refresh automatically.`);
1591
1876
  return;
1592
1877
  }
1593
1878
  throw error;
1594
1879
  }
1595
1880
  try {
1596
- await connect(profile, device, authProfile);
1881
+ await connect(profile, device, process.platform === 'darwin' && !argv.includes('--service-runner'));
1597
1882
  }
1598
1883
  finally {
1599
1884
  releaseRunnerLock();
@@ -1601,6 +1886,7 @@ async function runTerminalCommand(argv, signal) {
1601
1886
  }
1602
1887
  /** Supervisors retry crashes, but a revoked grant or 401/403 needs a human credential/grant change. */
1603
1888
  export async function handleTerminalCommand(argv) {
1889
+ argv = validateTerminalArguments(argv);
1604
1890
  const controller = argv[0] === 'connect' ? new AbortController() : undefined;
1605
1891
  const stopSetup = () => controller?.abort();
1606
1892
  if (controller) {