@revoengine/cli 1.0.30 → 1.0.33

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 (54) hide show
  1. package/README.md +70 -17
  2. package/dist/src/automation-contract.generated.d.ts +55 -21
  3. package/dist/src/automation-contract.generated.js +67 -25
  4. package/dist/src/client.d.ts +32 -2
  5. package/dist/src/client.js +54 -13
  6. package/dist/src/commands/component.js +4 -1
  7. package/dist/src/commands/database-tables.js +10 -3
  8. package/dist/src/commands/migrate.js +2 -0
  9. package/dist/src/commands/terminal-browser-central-profile.d.ts +65 -0
  10. package/dist/src/commands/terminal-browser-central-profile.js +203 -0
  11. package/dist/src/commands/terminal-browser-human-input.d.ts +3 -1
  12. package/dist/src/commands/terminal-browser-human-input.js +3 -1
  13. package/dist/src/commands/terminal-browser-interaction.js +1 -1
  14. package/dist/src/commands/terminal-browser-live-protocol.d.ts +34 -2
  15. package/dist/src/commands/terminal-browser-live-protocol.js +28 -12
  16. package/dist/src/commands/terminal-browser-live-transport.d.ts +1 -0
  17. package/dist/src/commands/terminal-browser-live-transport.js +9 -5
  18. package/dist/src/commands/terminal-browser-live.d.ts +24 -3
  19. package/dist/src/commands/terminal-browser-live.js +199 -30
  20. package/dist/src/commands/terminal-browser-page-input.d.ts +4 -1
  21. package/dist/src/commands/terminal-browser-page-input.js +46 -1
  22. package/dist/src/commands/terminal-browser-profile-crypto.d.ts +30 -0
  23. package/dist/src/commands/terminal-browser-profile-crypto.js +101 -0
  24. package/dist/src/commands/terminal-browser-profile-import-runner.d.ts +31 -0
  25. package/dist/src/commands/terminal-browser-profile-import-runner.js +112 -0
  26. package/dist/src/commands/terminal-browser-profile-import.d.ts +28 -0
  27. package/dist/src/commands/terminal-browser-profile-import.js +125 -0
  28. package/dist/src/commands/terminal-browser-profile-import.protocol.d.ts +50 -0
  29. package/dist/src/commands/terminal-browser-profile-import.protocol.js +52 -0
  30. package/dist/src/commands/terminal-browser-profile-preferences.d.ts +1 -0
  31. package/dist/src/commands/terminal-browser-profile-preferences.js +16 -0
  32. package/dist/src/commands/terminal-browser-profile-sync.d.ts +14 -0
  33. package/dist/src/commands/terminal-browser-profile-sync.js +169 -0
  34. package/dist/src/commands/terminal-browser-profile-sync.protocol.d.ts +50 -0
  35. package/dist/src/commands/terminal-browser-profile-sync.protocol.js +19 -0
  36. package/dist/src/commands/terminal-browser-profile.d.ts +10 -1
  37. package/dist/src/commands/terminal-browser-profile.js +30 -4
  38. package/dist/src/commands/terminal-browser-recording.d.ts +39 -0
  39. package/dist/src/commands/terminal-browser-recording.js +74 -0
  40. package/dist/src/commands/terminal-browser-recording.protocol.d.ts +49 -0
  41. package/dist/src/commands/terminal-browser-recording.protocol.js +16 -0
  42. package/dist/src/commands/terminal-browser.d.ts +14 -1
  43. package/dist/src/commands/terminal-browser.js +98 -33
  44. package/dist/src/commands/terminal-output-buffer.d.ts +18 -1
  45. package/dist/src/commands/terminal-output-buffer.js +95 -8
  46. package/dist/src/commands/terminal.d.ts +3 -1
  47. package/dist/src/commands/terminal.js +257 -54
  48. package/dist/src/component-lock.js +6 -0
  49. package/dist/src/env-sync.js +3 -0
  50. package/dist/src/resource-syncs/database-table-sync.d.ts +8 -1
  51. package/dist/src/resource-syncs/database-table-sync.js +34 -11
  52. package/dist/src/sync-output.d.ts +3 -3
  53. package/dist/src/ui.js +1 -0
  54. package/package.json +5 -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,22 @@ 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';
9
12
  import { getActiveEnvironmentName, getConfigDir, getEnvironmentProfile, loadStoredConfig, resolveRuntimeConfig } from "../config.js";
10
13
  import { installTerminalService, terminalServiceInstalled, uninstallTerminalService } from "./terminal-service.js";
11
14
  import { createSandboxScratchDirectory, isTerminalSandbox, sandboxCommand, shellQuote, requiresElevatedCommand } from "./terminal-sandbox.js";
12
15
  import { executionAllowedByGrant, executionPolicyDeadline, remainingPolicyDeadline, validateExecutePolicy } from "./terminal-policy.js";
13
- import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
16
+ import { closeThreadBrowserSession, threadBrowserScopes, browserSessionIds, closeBrowserSessions, fillBrowserSecret, hasBrowserSessions, reconcileBrowserSessions, revokeBrowserProfileSession, runBrowserAction, validateBrowserActionInput } from "./terminal-browser.js";
14
17
  import { transferWorkspaceFile, validateFileTransfer } from "./terminal-file.js";
15
18
  import { uploadWorkspaceImages } from "./terminal-image.js";
16
19
  import { ensurePtyHelperExecutable, normalizePtyStartError } from "./terminal-pty.js";
17
20
  import { TerminalReconnectGrace, TerminalTransportRecovery, isRunnerTransportHeartbeat } from "./terminal-reconnect-grace.js";
18
- import { TerminalOutputBuffer } from "./terminal-output-buffer.js";
21
+ import { CentralBrowserProfileLease } from "./terminal-browser-central-profile.js";
22
+ import { BrowserProfileRunnerRpc } from "./terminal-browser-profile-sync.js";
23
+ import { LegacyBrowserProfileImporter } from "./terminal-browser-profile-import.js";
24
+ import { BrowserProfileImportRunner } from "./terminal-browser-profile-import-runner.js";
25
+ import { TerminalOutputBuffer, TERMINAL_CAPTURE_MAX_BYTES as MAX_CAPTURE_OUTPUT_BYTES } from "./terminal-output-buffer.js";
19
26
  import { TerminalOperationalLog } from "./terminal-operational-log.js";
20
27
  import { createSecureBrowserIdentity, decryptSecureBrowserInput } from "./terminal-secure-browser.js";
21
28
  import { BrowserAuthProfileStore, macOSBrowserProfileKeyStore, validateBrowserProfileName } from "./terminal-browser-profile.js";
@@ -65,7 +72,7 @@ const configDir = getConfigDir;
65
72
  const runnerConfig = () => path.join(configDir(), 'runner.json');
66
73
  const MAX_MODEL_OUTPUT_BYTES = 100_000;
67
74
  const MAX_LOCAL_LOG_BYTES = 10_000_000;
68
- const OUTPUT_FRAME_CHARS = 1_000;
75
+ const OUTPUT_FRAME_BYTES = 12_000;
69
76
  const LOG_RETENTION_MS = 24 * 60 * 60 * 1_000;
70
77
  const OPERATIONAL_ERROR_CODES = new Set([
71
78
  'browser_binary_unavailable', 'browser_cancelled', 'browser_failed', 'browser_localhost_only',
@@ -76,6 +83,7 @@ const OPERATIONAL_ERROR_CODES = new Set([
76
83
  'browser_element_too_large', 'browser_screenshot_too_large', 'browser_output_outside_workspace',
77
84
  'browser_image_upload_unavailable', 'destructive_command_requires_approval',
78
85
  'browser_profile_busy', 'browser_profile_changed', 'browser_profile_closed',
86
+ 'browser_profile_navigation_required', 'browser_profile_save_failed', 'browser_profile_lease_expired', 'browser_profile_state_unavailable',
79
87
  'browser_profile_corrupt', 'browser_profile_scope_invalid', 'browser_profile_scope_changed',
80
88
  'browser_profile_keystore_unavailable', 'browser_profile_keystore_unsupported',
81
89
  'browser_profile_directory_invalid', 'browser_profile_too_large',
@@ -306,7 +314,7 @@ function apiUrl(profile, route) {
306
314
  throw new Error('Remote Revo API requires HTTPS.');
307
315
  return `${base}/api/v1${route}`;
308
316
  }
309
- async function api(profile, method, route, body) {
317
+ async function api(profile, method, route, body, privateHeaders) {
310
318
  const url = apiUrl(profile, route);
311
319
  let backoffMs = 1_000;
312
320
  for (;;) {
@@ -319,7 +327,7 @@ async function api(profile, method, route, body) {
319
327
  signal: AbortSignal.any([AbortSignal.timeout(30_000), ...(profile.signal ? [profile.signal] : [])]),
320
328
  headers: { Authorization: `Bearer ${profile.token}`,
321
329
  ...(profile.instance ? { instance: profile.instance } : {}),
322
- ...(body ? { 'Content-Type': 'application/json' } : {}) },
330
+ ...(body ? { 'Content-Type': 'application/json' } : {}), ...privateHeaders },
323
331
  ...(body ? { body: JSON.stringify(body) } : {}),
324
332
  });
325
333
  }
@@ -454,12 +462,18 @@ export async function runCommand(input, onDone, onChunk) {
454
462
  let stdout = '';
455
463
  let stderr = '';
456
464
  let modelBytes = 0;
465
+ let renderedBytes = 0;
466
+ let previewBytes = 0;
467
+ let captureTruncated = false;
468
+ let captureDeliveryFailed = false;
457
469
  let logBytes = 0;
458
470
  let truncated = false;
459
471
  let logTruncated = logFd === undefined;
460
472
  let timedOut = false;
461
473
  let policyExpired = false;
462
474
  let finished = false;
475
+ const decoders = { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') };
476
+ const truncatedStreams = new Set();
463
477
  const pid = child?.pid || terminal?.pid;
464
478
  const terminate = () => {
465
479
  if (!pid)
@@ -501,6 +515,45 @@ export async function runCommand(input, onDone, onChunk) {
501
515
  }, Math.max(0, deadline - Date.now()));
502
516
  };
503
517
  updatePolicyDeadline(input.policyDeadlineMs ?? null);
518
+ const emitText = (text, kind) => {
519
+ const decoded = Buffer.from(text);
520
+ const captureLimit = input.captureOutput ? MAX_CAPTURE_OUTPUT_BYTES : MAX_MODEL_OUTPUT_BYTES;
521
+ let limit = Math.min(decoded.length, Math.max(0, captureLimit - renderedBytes));
522
+ while (limit > 0 && limit < decoded.length && (decoded[limit] & 0xc0) === 0x80)
523
+ limit--;
524
+ if (limit < decoded.length) {
525
+ truncated = true;
526
+ captureTruncated = true;
527
+ }
528
+ renderedBytes += limit;
529
+ const bytes = decoded.subarray(0, limit);
530
+ let previewEnd = Math.min(bytes.length, Math.max(0, MAX_MODEL_OUTPUT_BYTES - previewBytes));
531
+ while (previewEnd > 0 && previewEnd < bytes.length && (bytes[previewEnd] & 0xc0) === 0x80)
532
+ previewEnd--;
533
+ if (previewEnd < bytes.length)
534
+ truncated = true;
535
+ previewBytes += previewEnd;
536
+ const projected = bytes.subarray(0, previewEnd).toString('utf8');
537
+ if (kind === 'stdout')
538
+ stdout += projected;
539
+ else
540
+ stderr += projected;
541
+ if (!onChunk || !bytes.length || captureDeliveryFailed)
542
+ return;
543
+ for (let offset = 0; offset < bytes.length;) {
544
+ let end = Math.min(offset + OUTPUT_FRAME_BYTES, bytes.length);
545
+ // The decoded text is valid UTF-8; keep a complete code point in each frame.
546
+ while (end < bytes.length && (bytes[end] & 0xc0) === 0x80)
547
+ end--;
548
+ if (onChunk(kind, bytes.subarray(offset, end).toString('utf8')) === false) {
549
+ captureDeliveryFailed = true;
550
+ captureTruncated = true;
551
+ truncated = true;
552
+ break;
553
+ }
554
+ offset = end;
555
+ }
556
+ };
504
557
  const append = (chunk, kind) => {
505
558
  const logPart = chunk.subarray(0, Math.max(0, MAX_LOCAL_LOG_BYTES - logBytes));
506
559
  if (logPart.length && logFd !== undefined) {
@@ -526,20 +579,15 @@ export async function runCommand(input, onDone, onChunk) {
526
579
  }
527
580
  if (logPart.length < chunk.length)
528
581
  logTruncated = true;
529
- const available = Math.max(0, MAX_MODEL_OUTPUT_BYTES - modelBytes);
582
+ const available = Math.max(0, (input.captureOutput ? MAX_CAPTURE_OUTPUT_BYTES : MAX_MODEL_OUTPUT_BYTES) - modelBytes);
530
583
  const modelPart = chunk.subarray(0, available);
531
584
  modelBytes += modelPart.length;
532
- if (modelPart.length < chunk.length)
585
+ if (modelPart.length < chunk.length) {
533
586
  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));
587
+ captureTruncated = true;
588
+ truncatedStreams.add(kind);
542
589
  }
590
+ emitText(decoders[kind].write(modelPart), kind);
543
591
  };
544
592
  child?.stdout?.on('data', (chunk) => append(chunk, 'stdout'));
545
593
  child?.stderr?.on('data', (chunk) => append(chunk, 'stderr'));
@@ -555,6 +603,12 @@ export async function runCommand(input, onDone, onChunk) {
555
603
  const diagnostic = [error?.message, policyExpired ? 'terminal_policy_expired' : null].filter(Boolean).join('\n');
556
604
  if (diagnostic)
557
605
  append(Buffer.from(`${stderr && !stderr.endsWith('\n') ? '\n' : ''}${diagnostic}`), 'stderr');
606
+ for (const kind of ['stdout', 'stderr']) {
607
+ const tail = decoders[kind].end();
608
+ // A byte-limit cut can leave half a character; do not expand it past the limit.
609
+ if (!truncatedStreams.has(kind))
610
+ emitText(tail, kind);
611
+ }
558
612
  if (scratch) {
559
613
  try {
560
614
  fs.rmSync(scratch, { recursive: true, force: true });
@@ -572,6 +626,7 @@ export async function runCommand(input, onDone, onChunk) {
572
626
  onDone({ executed: !error, exitCode: (timedOut || policyExpired) && exitCode === 0 ? null : exitCode,
573
627
  stdout, stderr,
574
628
  timedOut, truncated, logTruncated, logPath: logFd === undefined ? '' : logPath,
629
+ ...(input.captureOutput ? { captureTruncated } : {}),
575
630
  ...(signal ? { signal } : {}),
576
631
  ...(policyExpired ? { policyExpired: true } : {}) });
577
632
  };
@@ -668,7 +723,7 @@ export function runWorkspacePatch(input, onDone) {
668
723
  child.on('error', error => finish(null, error));
669
724
  return Object.assign(child, { updatePolicyDeadline });
670
725
  }
671
- async function connect(profile, device, authProfile) {
726
+ async function connect(profile, device, legacyImportAvailable) {
672
727
  const logDeviceId = /^[A-Za-z0-9_-]{1,128}$/u.test(device.agentTerminalId)
673
728
  ? device.agentTerminalId : createHash('sha256').update(device.agentTerminalId).digest('hex');
674
729
  const operationalLog = new TerminalOperationalLog(path.join(configDir(), 'logs', 'terminal', logDeviceId));
@@ -678,6 +733,7 @@ async function connect(profile, device, authProfile) {
678
733
  let activeSocket;
679
734
  let activeConnectionId = '';
680
735
  let durableOutput = false;
736
+ let captureOutput = false;
681
737
  const activeChildren = new Set();
682
738
  const children = new Map();
683
739
  const activePolicies = new Map();
@@ -688,9 +744,10 @@ async function connect(profile, device, authProfile) {
688
744
  const completed = new Map();
689
745
  const traces = new Map();
690
746
  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
747
  const browserScopes = new Map();
748
+ const centralProfiles = new Map();
749
+ const recordingSinks = new Map();
750
+ const revokedProfileSessions = new Map();
694
751
  const resumed = new Set();
695
752
  const reconnectGrace = new TerminalReconnectGrace(() => {
696
753
  for (const child of children.values())
@@ -731,10 +788,20 @@ async function connect(profile, device, authProfile) {
731
788
  const flushExecution = (executionId) => {
732
789
  if (!resumed.has(executionId))
733
790
  return;
734
- for (const chunk of outputByExecution.get(executionId)?.pending() || [])
735
- sendCurrent({ type: 'output', executionId, ...chunk });
791
+ const buffer = outputByExecution.get(executionId);
792
+ if (!buffer)
793
+ return;
794
+ // Limit frames in flight, including on reconnect. Completion follows committed output.
795
+ do {
796
+ const chunks = buffer.takeUnsent();
797
+ for (const chunk of chunks)
798
+ sendCurrent({ type: 'output', executionId, ...chunk });
799
+ if (durableOutput || !chunks.length)
800
+ break;
801
+ buffer.acknowledge(chunks.at(-1).sequence);
802
+ } while (buffer.lastAcknowledged < buffer.lastSequence);
736
803
  const result = completed.get(executionId);
737
- if (result)
804
+ if (result && buffer.lastAcknowledged === buffer.lastSequence)
738
805
  sendCurrent({ type: 'result', executionId, ...result });
739
806
  };
740
807
  const stop = () => {
@@ -773,7 +840,7 @@ async function connect(profile, device, authProfile) {
773
840
  return { browserSessionId: frame.browserSessionId, liveSessionId: frame.liveSessionId,
774
841
  actorUserId: frame.actorUserId, threadId: frame.threadId,
775
842
  agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId, connectionId: frame.connectionId,
776
- identity: secureIdentity, profilePreferences, profileOwner: scope.owner,
843
+ identity: secureIdentity, profileOwner: scope.owner,
777
844
  initialControl: { controlEpoch: frame.controlEpoch, mode: frame.mode, private: frame.private },
778
845
  recordingDirectory: path.join(fs.realpathSync(configDir()), 'browser-recordings', device.agentTerminalId),
779
846
  isAuthorized: () => liveAuthorized(frame) };
@@ -786,6 +853,8 @@ async function connect(profile, device, authProfile) {
786
853
  });
787
854
  activeSocket = socket;
788
855
  let connectionId = '';
856
+ let profileRpc;
857
+ let profileImports;
789
858
  let defaultWorkspace = device.workspace;
790
859
  let heartbeat;
791
860
  let lastHeartbeat = Date.now();
@@ -795,12 +864,12 @@ async function connect(profile, device, authProfile) {
795
864
  reconnectGrace.clear();
796
865
  });
797
866
  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',
867
+ 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
868
  'terminal_policy_v2', 'terminal_policy_selective_v1', 'background_shell_v1', 'terminal_thread_scope_v1',
800
869
  'apply_patch_v1', 'stdin_v1', 'pty_v1', 'browser_v1', 'browser_session_v1', 'browser_forms_v1',
801
870
  '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'] : []),
871
+ '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',
872
+ 'browser_profiles_v2', ...(legacyImportAvailable ? ['browser_profile_import_v1'] : []),
804
873
  ...(process.platform === 'darwin' ? ['localhost_shell_v1'] : [])],
805
874
  secureBrowserPublicKey: secureIdentity.publicKey, secureBrowserKeyId: secureIdentity.keyId }));
806
875
  socket.on('message', raw => {
@@ -817,6 +886,20 @@ async function connect(profile, device, authProfile) {
817
886
  lastHeartbeat = Date.now();
818
887
  return;
819
888
  }
889
+ if (frame.type === 'browser_profile_sync_result') {
890
+ profileRpc?.accept(frame);
891
+ return;
892
+ }
893
+ if (frame.type === 'browser_profile_import') {
894
+ profileImports?.accept(frame);
895
+ return;
896
+ }
897
+ if (frame.type === 'browser_profile_import_ack') {
898
+ profileImports?.acceptAck(frame);
899
+ return;
900
+ }
901
+ if (frame.type === 'browser_profile_revoked' && frame.connectionId === connectionId && frame.browserProfileId)
902
+ profileImports?.revokeProfile(frame.browserProfileId);
820
903
  incoming = incoming.then(async () => {
821
904
  if (stopping || socket.readyState !== WebSocket.OPEN)
822
905
  return;
@@ -828,8 +911,22 @@ async function connect(profile, device, authProfile) {
828
911
  lastHeartbeat = Date.now();
829
912
  securePolicyEpoch++;
830
913
  connectionId = frame.connectionId;
914
+ profileRpc = new BrowserProfileRunnerRpc(connectionId, request => send(socket, request));
831
915
  activeConnectionId = connectionId;
916
+ profileImports = new BrowserProfileImportRunner({ connectionId, instanceId: profile.instance,
917
+ terminalId: device.agentTerminalId, keyId: secureIdentity.keyId, privateKey: secureIdentity.privateKey,
918
+ baseUrl: profile.baseUrl, rpc: profileRpc,
919
+ importer: new LegacyBrowserProfileImporter(legacyImportAvailable, () => new BrowserAuthProfileStore(path.join(configDir(), 'browser-profiles'), macOSBrowserProfileKeyStore())),
920
+ authorized: request => {
921
+ if (!legacyImportAvailable || stopping || policyRevisionUnavailable || activeConnectionId !== connectionId
922
+ || socket.readyState !== WebSocket.OPEN || request.grantRevision !== minimumPolicyGrantRevision)
923
+ return false;
924
+ const saved = readStore().devices.find(item => item.agentTerminalId === device.agentTerminalId
925
+ && item.baseUrl === profile.baseUrl && item.instance === profile.instance);
926
+ return [device.workspace, ...(saved?.workspaces || [])].includes(request.workspace);
927
+ }, send: reply => send(socket, reply) });
832
928
  durableOutput = Array.isArray(frame.capabilities) && frame.capabilities.includes('terminal_resume_durable_v1');
929
+ captureOutput = durableOutput && frame.capabilities.includes('terminal_output_capture_v1');
833
930
  defaultWorkspace = frame.workspace || device.workspace;
834
931
  if (Number.isSafeInteger(frame.policyGrantRevision) && frame.policyGrantRevision >= 0) {
835
932
  minimumPolicyGrantRevision = Math.max(minimumPolicyGrantRevision, frame.policyGrantRevision);
@@ -858,6 +955,19 @@ async function connect(profile, device, authProfile) {
858
955
  }
859
956
  if (frame.type === 'heartbeat')
860
957
  return;
958
+ if (frame.type === 'browser_profile_revoked') {
959
+ if (frame.connectionId === connectionId && frame.browserSessionId && frame.browserProfileId) {
960
+ for (const [id, expiresAt] of revokedProfileSessions)
961
+ if (expiresAt <= Date.now())
962
+ revokedProfileSessions.delete(id);
963
+ revokedProfileSessions.set(frame.browserSessionId, Date.now() + 60_000);
964
+ const central = centralProfiles.get(frame.browserSessionId);
965
+ centralProfiles.delete(frame.browserSessionId);
966
+ await revokeBrowserProfileSession(frame.browserSessionId, frame.browserProfileId);
967
+ await central?.lease.release();
968
+ }
969
+ return;
970
+ }
861
971
  if (frame.type === 'browser_scope_revoked') {
862
972
  if (frame.connectionId === connectionId && typeof frame.browserSessionId === 'string'
863
973
  && /^[a-f0-9]{64}$/u.test(frame.browserSessionId)) {
@@ -952,8 +1062,11 @@ async function connect(profile, device, authProfile) {
952
1062
  if (frame.connectionId !== connectionId || !frame.executionId)
953
1063
  return;
954
1064
  if (frame.type === 'output_ack') {
955
- if (durableOutput && !outputByExecution.get(frame.executionId)?.acknowledge(frame.lastOutputSequence))
1065
+ if (durableOutput && !outputByExecution.get(frame.executionId)?.acknowledge(frame.lastOutputSequence)) {
956
1066
  socket.terminate();
1067
+ return;
1068
+ }
1069
+ flushExecution(frame.executionId);
957
1070
  return;
958
1071
  }
959
1072
  if (frame.type === 'resumed') {
@@ -961,6 +1074,7 @@ async function connect(profile, device, authProfile) {
961
1074
  socket.terminate();
962
1075
  return;
963
1076
  }
1077
+ outputByExecution.get(frame.executionId)?.resetTransport();
964
1078
  recovery.accepted(frame.executionId);
965
1079
  resumed.add(frame.executionId);
966
1080
  flushExecution(frame.executionId);
@@ -981,6 +1095,7 @@ async function connect(profile, device, authProfile) {
981
1095
  retiredExecutions.delete(id);
982
1096
  nextRetiredSweep = now + 60_000;
983
1097
  }
1098
+ outputByExecution.get(frame.executionId)?.dispose();
984
1099
  outputByExecution.delete(frame.executionId);
985
1100
  resumed.delete(frame.executionId);
986
1101
  traces.delete(frame.executionId);
@@ -1090,7 +1205,7 @@ async function connect(profile, device, authProfile) {
1090
1205
  traces.set(frame.executionId, trace);
1091
1206
  operationalLog.write('INFO', trace, 'execution.started', { operation, sandbox: frame.sandbox });
1092
1207
  resumed.add(frame.executionId);
1093
- outputByExecution.set(frame.executionId, new TerminalOutputBuffer());
1208
+ outputByExecution.set(frame.executionId, new TerminalOutputBuffer({ spool: true }));
1094
1209
  if (operation === 'save_image' || operation === 'upload_file' || operation === 'download_file') {
1095
1210
  const controller = new AbortController();
1096
1211
  const policyDeadline = executionPolicyDeadline(frame);
@@ -1156,25 +1271,92 @@ async function connect(profile, device, authProfile) {
1156
1271
  children.set(frame.executionId, child);
1157
1272
  activeChildren.add(child);
1158
1273
  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 })
1274
+ void (async () => {
1275
+ if (frame.browserSessionId && revokedProfileSessions.has(frame.browserSessionId))
1276
+ throw new Error('browser_profile_lease_expired');
1277
+ let central = frame.browserSessionId ? centralProfiles.get(frame.browserSessionId) : undefined;
1278
+ const grant = frame.browserProfileGrant;
1279
+ if (grant) {
1280
+ if (!profileRpc || central || grant.profile.id !== frame.browserProfileId || grant.scope.browserProfileId !== grant.profile.id
1281
+ || grant.scope.instanceId !== device.instance || grant.scope.agentTerminalId !== device.agentTerminalId
1282
+ || grant.scope.agentTerminalWorkspaceId !== (frame.agentTerminalWorkspaceId || device.agentTerminalId)
1283
+ || grant.scope.actorUserId !== frame.actorUserId || grant.scope.assistantThreadId !== (frame.browserTargetThreadId || frame.assistantThreadId)
1284
+ || grant.scope.connectionId !== connectionId || grant.scope.keyId !== secureIdentity.keyId
1285
+ || grant.scope.browserSessionId !== frame.browserSessionId || !Number.isSafeInteger(grant.scope.generation)
1286
+ || grant.scope.generation < 1 || !Number.isSafeInteger(grant.revision) || grant.revision < 0)
1287
+ throw new Error('browser_profile_scope_changed');
1288
+ const lease = await CentralBrowserProfileLease.open({ ...grant, digest: grant.download?.digest }, secureIdentity.privateKey, profileRpc.transport(grant), async () => {
1289
+ centralProfiles.delete(grant.scope.browserSessionId);
1290
+ await revokeBrowserProfileSession(grant.scope.browserSessionId, grant.profile.id);
1291
+ });
1292
+ if (revokedProfileSessions.has(grant.scope.browserSessionId)) {
1293
+ await lease.release();
1294
+ throw new Error('browser_profile_lease_expired');
1295
+ }
1296
+ central = { ...grant.profile, lease };
1297
+ centralProfiles.set(grant.scope.browserSessionId, central);
1298
+ }
1299
+ if (frame.browserProfileId && (!central || central.id !== frame.browserProfileId))
1300
+ throw new Error('browser_profile_lease_expired');
1301
+ const recordingGrant = frame.browserRecording;
1302
+ if (recordingGrant && (!validBrowserRecordingGrant(recordingGrant)
1303
+ || recordingGrant.browserSessionId !== frame.browserSessionId))
1304
+ throw new Error('browser_recording_scope_invalid');
1305
+ const recordingDirectory = path.join(fs.realpathSync(configDir()), 'browser-recordings', device.agentTerminalId);
1306
+ for (const [id, stale] of recordingSinks)
1307
+ if (id !== frame.browserSessionId && !browserSessionIds().includes(id)) {
1308
+ void stale.settled().finally(() => { if (recordingSinks.get(id) === stale)
1309
+ recordingSinks.delete(id); });
1310
+ }
1311
+ const recordingAuthorized = () => activeConnectionId === frame.connectionId && minimumPolicyGrantRevision === frame.policyGrantRevision
1312
+ && !policyRevisionUnavailable && (frame.networkAccessExpiresAt == null || frame.networkAccessExpiresAt > Date.now());
1313
+ let sink = recordingSinks.get(frame.browserSessionId);
1314
+ if (recordingGrant && sink)
1315
+ sink.refresh(recordingGrant, recordingAuthorized);
1316
+ if (recordingGrant && !sink) {
1317
+ sink = new BrowserSessionRecordingSink({ grant: recordingGrant,
1318
+ terminalId: device.agentTerminalId, directory: recordingDirectory, isAuthorized: recordingAuthorized,
1319
+ request: (route, token, body) => api(profile, 'POST', route, body, { 'x-revo-browser-recording-token': token }),
1320
+ onStatus: (status, recordingId) => operationalLog.write(status === 'saved' ? 'INFO' : 'ERROR', trace, 'browser.recording', { status, recordingId }),
1321
+ });
1322
+ recordingSinks.set(frame.browserSessionId, sink);
1323
+ }
1324
+ return runBrowserAction({ url: frame.url, action: frame.browserAction, workspace,
1325
+ agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId ?? (recordingGrant ? device.agentTerminalId : undefined),
1326
+ browserSessionId: frame.browserSessionId, tabId: frame.tabId,
1327
+ onActionAttempt: () => { actionAttempted = true; },
1328
+ interaction: frame.browserInteraction, selector: frame.selector, width: frame.width, height: frame.height,
1329
+ value: frame.value, checked: frame.checked, key: frame.key, deltaY: frame.deltaY,
1330
+ state: frame.state, waitTimeoutMs: frame.waitTimeoutMs,
1331
+ actionTimeoutMs: frame.actionTimeoutMs,
1332
+ capture: frame.capture, clip: frame.clip,
1333
+ localOnly: frame.browserLocalOnly === true,
1334
+ networkAccessExpiresAt: frame.networkAccessExpiresAt,
1335
+ networkAccessOnce: frame.networkAccessOnce,
1336
+ networkAccessForThread: frame.networkAccessForThread, actorUserId: frame.actorUserId,
1337
+ threadId: frame.browserTargetThreadId || frame.assistantThreadId, policyGrantRevision: frame.policyGrantRevision,
1338
+ ...(central ? { centralProfile: central } : {}),
1339
+ ...(recordingGrant && sink ? { recording: { policyGrantRevision: frame.policyGrantRevision, networkAccessExpiresAt: frame.networkAccessExpiresAt ?? null,
1340
+ options: { browserSessionId: frame.browserSessionId, liveSessionId: recordingGrant.grantId,
1341
+ actorUserId: frame.actorUserId, threadId: frame.browserTargetThreadId || frame.assistantThreadId,
1342
+ agentTerminalWorkspaceId: frame.agentTerminalWorkspaceId || device.agentTerminalId, connectionId: frame.connectionId,
1343
+ identity: secureIdentity, profileOwner: { baseUrl: device.baseUrl, instanceId: device.instance,
1344
+ actorUserId: frame.actorUserId, terminalId: device.agentTerminalId, workspace },
1345
+ browserSettings: recordingGrant.settings, recordingDirectory,
1346
+ isAuthorized: () => sink.authorized, onFrame: () => undefined, onRecording: item => sink.accept(item) },
1347
+ } } : {}),
1348
+ signal: controller.signal });
1349
+ })()
1177
1350
  .then(async (browserResult) => {
1351
+ if (!browserResult.tabs.length) {
1352
+ centralProfiles.delete(browserResult.browserSessionId);
1353
+ const sink = recordingSinks.get(browserResult.browserSessionId);
1354
+ if (sink)
1355
+ void sink.settled().finally(() => {
1356
+ if (recordingSinks.get(browserResult.browserSessionId) === sink)
1357
+ recordingSinks.delete(browserResult.browserSessionId);
1358
+ });
1359
+ }
1178
1360
  if (frame.browserAction !== 'read_public')
1179
1361
  browserScopes.set(browserResult.browserSessionId, { workspace, workspaceId: frame.agentTerminalWorkspaceId || device.agentTerminalId,
1180
1362
  owner: { baseUrl: device.baseUrl, instanceId: device.instance, actorUserId: frame.actorUserId || '', terminalId: device.agentTerminalId, workspace },
@@ -1202,7 +1384,13 @@ async function connect(profile, device, authProfile) {
1202
1384
  browserAction: frame.browserAction, exitCode: 0, screenshot: frame.browserAction === 'screenshot' });
1203
1385
  if (resumed.has(frame.executionId))
1204
1386
  flushExecution(frame.executionId);
1205
- }).catch(error => {
1387
+ }).catch(async (error) => {
1388
+ if (frame.browserProfileGrant && frame.browserSessionId) {
1389
+ const central = centralProfiles.get(frame.browserSessionId);
1390
+ centralProfiles.delete(frame.browserSessionId);
1391
+ await revokeBrowserProfileSession(frame.browserSessionId, frame.browserProfileGrant.profile.id).catch(() => undefined);
1392
+ await central?.lease.release();
1393
+ }
1206
1394
  if (policyTimer)
1207
1395
  clearTimeout(policyTimer);
1208
1396
  children.delete(frame.executionId);
@@ -1251,6 +1439,7 @@ async function connect(profile, device, authProfile) {
1251
1439
  return;
1252
1440
  }
1253
1441
  const child = await runCommand({ cmd: frame.cmd, workdir: frame.workdir || workspace,
1442
+ captureOutput,
1254
1443
  workspace, sandbox: frame.sandbox, networkAccess: frame.networkAccess,
1255
1444
  policyDeadlineMs: executionPolicyDeadline(frame),
1256
1445
  timeoutMs: frame.timeoutMs || 60_000, background: frame.background === true, tty: frame.tty,
@@ -1266,15 +1455,19 @@ async function connect(profile, device, authProfile) {
1266
1455
  executed: completion.executed,
1267
1456
  timedOut: completion.timedOut, truncated: completion.truncated });
1268
1457
  if (resumed.has(frame.executionId))
1269
- sendCurrent({ type: 'result', executionId: frame.executionId,
1270
- ...completed.get(frame.executionId) });
1458
+ flushExecution(frame.executionId);
1271
1459
  }, (stream, text) => {
1272
1460
  const buffer = outputByExecution.get(frame.executionId);
1273
1461
  if (!buffer)
1274
1462
  return;
1275
- const chunk = buffer.append(stream, text);
1463
+ try {
1464
+ buffer.append(stream, text);
1465
+ }
1466
+ catch {
1467
+ return false;
1468
+ } // Capture is explicitly partial; never kill or replay the command.
1276
1469
  if (resumed.has(frame.executionId))
1277
- sendCurrent({ type: 'output', executionId: frame.executionId, ...chunk });
1470
+ flushExecution(frame.executionId);
1278
1471
  });
1279
1472
  children.set(frame.executionId, child);
1280
1473
  activeChildren.add(child);
@@ -1283,6 +1476,7 @@ async function connect(profile, device, authProfile) {
1283
1476
  catch (error) {
1284
1477
  activePolicies.delete(frame.executionId);
1285
1478
  resumed.delete(frame.executionId);
1479
+ outputByExecution.get(frame.executionId)?.dispose();
1286
1480
  outputByExecution.delete(frame.executionId);
1287
1481
  traces.delete(frame.executionId);
1288
1482
  operationalLog.write('ERROR', trace, 'execution.rejected', { operation,
@@ -1293,6 +1487,12 @@ async function connect(profile, device, authProfile) {
1293
1487
  }).catch(() => socket.terminate());
1294
1488
  });
1295
1489
  socket.on('close', (code, reason) => {
1490
+ profileImports?.dispose();
1491
+ profileRpc?.dispose();
1492
+ for (const [sessionId, central] of centralProfiles) {
1493
+ centralProfiles.delete(sessionId);
1494
+ void revokeBrowserProfileSession(sessionId, central.id).catch(() => undefined);
1495
+ }
1296
1496
  live.disconnectAll();
1297
1497
  securePolicyEpoch++;
1298
1498
  operationalLog.write(code === 1000 ? 'INFO' : 'WARN', {}, 'socket.closed', { code, activeExecutions: children.size, policyViolation: code === 1008 });
@@ -1354,6 +1554,9 @@ async function connect(profile, device, authProfile) {
1354
1554
  }
1355
1555
  finally {
1356
1556
  stop();
1557
+ for (const buffer of outputByExecution.values())
1558
+ buffer.dispose();
1559
+ outputByExecution.clear();
1357
1560
  process.off('SIGINT', stop);
1358
1561
  process.off('SIGTERM', stop);
1359
1562
  }
@@ -1362,9 +1565,11 @@ async function runTerminalCommand(argv, signal) {
1362
1565
  const command = argv[0] || 'help';
1363
1566
  const browserProfileName = selectedBrowserProfile(argv);
1364
1567
  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]');
1568
+ console.log('revo terminal connect|status|disconnect [--project NAME] [--workspace PATH] [--name NAME|--terminal-id UUID] [--url URL] [--realtime-url URL]\nBrowser profiles are assigned in Revo Vault, including Linux/service runners.\nLegacy local cleanup: revo 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]');
1366
1569
  return;
1367
1570
  }
1571
+ if (command === 'connect' && browserProfileName)
1572
+ 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
1573
  if (command === 'service') {
1369
1574
  const action = argv[1];
1370
1575
  if (!action || action === 'help') {
@@ -1585,15 +1790,13 @@ async function runTerminalCommand(argv, signal) {
1585
1790
  }
1586
1791
  catch (error) {
1587
1792
  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
1793
  console.log(`Terminal ${device.agentTerminalId} already has a local runner; its workspace contract will refresh automatically.`);
1591
1794
  return;
1592
1795
  }
1593
1796
  throw error;
1594
1797
  }
1595
1798
  try {
1596
- await connect(profile, device, authProfile);
1799
+ await connect(profile, device, process.platform === 'darwin' && !argv.includes('--service-runner'));
1597
1800
  }
1598
1801
  finally {
1599
1802
  releaseRunnerLock();
@@ -173,6 +173,12 @@ export function buildPortableComponentUpdatePayload(source, target, changedField
173
173
  return payload;
174
174
  }
175
175
  export function componentUpdateValidationError(source, target) {
176
+ const targetType = String(target.type || '').toUpperCase();
177
+ if (['CODE_JS_LIB', 'CODE_TS_LIB'].includes(targetType)
178
+ && target.elements?.some(element => element.key === '@default')
179
+ && !source.elements?.some(element => element.key === '@default')) {
180
+ return 'The target library has a permanent @default element that is missing from the local source. Pull and reconcile the migrated library, including its explicit exports, before deploying; @default cannot be deleted.';
181
+ }
176
182
  const configurationErrors = componentSourceConfigurationErrors(source);
177
183
  if (configurationErrors.length)
178
184
  return configurationErrors.join('; ');
@@ -327,6 +327,9 @@ async function applyPlanItem(targetClient, item, source, target, stableKeyName =
327
327
  if (!sourceEntry || !targetEntry) {
328
328
  throw new Error('component disappeared from the snapshot');
329
329
  }
330
+ const updateError = componentUpdateValidationError(sourceEntry.component, targetEntry.component);
331
+ if (updateError)
332
+ throw new Error(updateError);
330
333
  const configurationErrors = componentSourceConfigurationErrors(sourceEntry.component);
331
334
  if (configurationErrors.length)
332
335
  throw new Error(configurationErrors.join('; '));
@@ -83,7 +83,12 @@ export type DatabaseSchemaMigrationPolicy = {
83
83
  export type DatabaseSchemaPushResult = {
84
84
  stableKey: string;
85
85
  action: 'create' | 'update' | 'reconcile' | 'delete' | 'skipped';
86
- status: 'deployed' | 'skipped' | 'failed' | 'write-unverified';
86
+ status: 'deployed' | 'accepted' | 'skipped' | 'failed' | 'write-unverified';
87
+ operation?: {
88
+ accepted: true;
89
+ jobId: string;
90
+ status: string;
91
+ };
87
92
  targetPath: string;
88
93
  reason?: string;
89
94
  error?: string;
@@ -123,6 +128,8 @@ export declare function pushDatabaseSchemas(input: {
123
128
  pruneOrphans?: boolean;
124
129
  pruneOrphansConfirmed?: boolean;
125
130
  migrationPolicy?: DatabaseSchemaMigrationPolicy;
131
+ async?: boolean;
132
+ idempotencyKey?: string;
126
133
  }): Promise<{
127
134
  plan: DatabaseSchemasPlan;
128
135
  results: DatabaseSchemaPushResult[];