@revoengine/cli 1.0.14 → 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +57 -21
  2. package/dist/src/cli.js +5 -1
  3. package/dist/src/client.d.ts +25 -14
  4. package/dist/src/client.js +67 -34
  5. package/dist/src/commands/component.js +1 -0
  6. package/dist/src/commands/env.js +1 -5
  7. package/dist/src/commands/index.d.ts +1 -0
  8. package/dist/src/commands/index.js +1 -0
  9. package/dist/src/commands/migrate.js +12 -2
  10. package/dist/src/commands/service-accounts.d.ts +2 -0
  11. package/dist/src/commands/service-accounts.js +149 -0
  12. package/dist/src/commands/terminal-browser.d.ts +29 -1
  13. package/dist/src/commands/terminal-browser.js +165 -34
  14. package/dist/src/commands/terminal-file.d.ts +21 -0
  15. package/dist/src/commands/terminal-file.js +160 -0
  16. package/dist/src/commands/terminal-operational-log.js +2 -2
  17. package/dist/src/commands/terminal-policy.d.ts +11 -2
  18. package/dist/src/commands/terminal-policy.js +27 -2
  19. package/dist/src/commands/terminal-pty.js +2 -0
  20. package/dist/src/commands/terminal-reconnect-grace.d.ts +19 -0
  21. package/dist/src/commands/terminal-reconnect-grace.js +59 -1
  22. package/dist/src/commands/terminal-sandbox.js +7 -0
  23. package/dist/src/commands/terminal-secure-browser.d.ts +1 -0
  24. package/dist/src/commands/terminal-secure-browser.js +2 -1
  25. package/dist/src/commands/terminal-service.d.ts +4 -3
  26. package/dist/src/commands/terminal-service.js +23 -19
  27. package/dist/src/commands/terminal.d.ts +29 -1
  28. package/dist/src/commands/terminal.js +508 -107
  29. package/dist/src/component-lock.d.ts +4 -0
  30. package/dist/src/component-lock.js +21 -2
  31. package/dist/src/config.d.ts +0 -3
  32. package/dist/src/config.js +0 -2
  33. package/dist/src/metadata-backfill.js +50 -1
  34. package/dist/src/migration.d.ts +10 -2
  35. package/dist/src/migration.js +159 -69
  36. package/dist/src/resource-inventory.d.ts +3 -2
  37. package/dist/src/resource-inventory.js +6 -1
  38. package/dist/src/resource-syncs/account-principal.d.ts +22 -0
  39. package/dist/src/resource-syncs/account-principal.js +86 -0
  40. package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
  41. package/dist/src/resource-syncs/database-view-sync.js +1 -12
  42. package/dist/src/resource-syncs/group-sync.d.ts +10 -0
  43. package/dist/src/resource-syncs/group-sync.js +92 -20
  44. package/dist/src/resource-syncs/identity-migration.d.ts +19 -0
  45. package/dist/src/resource-syncs/identity-migration.js +108 -0
  46. package/dist/src/resource-syncs/job-template-sync.d.ts +4 -0
  47. package/dist/src/resource-syncs/job-template-sync.js +55 -12
  48. package/dist/src/resource-syncs/service-account-sync.d.ts +98 -0
  49. package/dist/src/resource-syncs/service-account-sync.js +620 -0
  50. package/dist/src/sync-output.js +3 -0
  51. package/dist/src/tracked-resources.d.ts +1 -1
  52. package/dist/src/tracked-resources.js +5 -1
  53. package/dist/src/types.d.ts +12 -0
  54. package/dist/src/ui.js +4 -1
  55. package/dist/src/workspace-diff.d.ts +1 -0
  56. package/dist/src/workspace-diff.js +4 -1
  57. package/package.json +6 -5
  58. package/scripts/ensure-pty-helper.mjs +0 -9
@@ -0,0 +1,149 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { resolveProjectRoot, readProjectStableKeyName } from "../project.js";
4
+ import { resolveResourceTarget } from "../resource-target.js";
5
+ import { buildServiceAccountsPlan, pullServiceAccountsToWorkspace, pushServiceAccounts } from "../resource-syncs/service-account-sync.js";
6
+ import { isInteractiveTerminal, promptConfirm } from "../prompt.js";
7
+ import { printSyncPlan, printSyncStatus, printSyncSummary } from "../sync-output.js";
8
+ import { readBoolFlag } from "../utils.js";
9
+ function warnAboutExperimentalState(context) {
10
+ const projectRoot = resolveProjectRoot(context.cwd) || path.resolve(context.cwd);
11
+ const legacyPaths = [
12
+ path.join(projectRoot, '.revoengine', 'resources'),
13
+ path.join(projectRoot, '.revoengine', 'resources.lock.json'),
14
+ path.join(projectRoot, '.revoengine', 'plans'),
15
+ ].filter((candidate) => fs.existsSync(candidate));
16
+ if (legacyPaths.length > 0) {
17
+ const warning = `Ignoring experimental ${legacyPaths.map((candidate) => path.relative(projectRoot, candidate)).join(', ')}; service-accounts use workspace/ServiceAccounts and .revoengine/revo.lock.json.`;
18
+ if (readBoolFlag(context.args, ['json'])) {
19
+ (context.warn || context.error)(warning);
20
+ }
21
+ else {
22
+ context.println(warning);
23
+ }
24
+ }
25
+ }
26
+ async function handlePull(context) {
27
+ if (!readBoolFlag(context.args, ['all', 'a'])) {
28
+ throw new Error('Service-account pull currently requires --all.');
29
+ }
30
+ const { client, envName } = await resolveResourceTarget(context, { resource: 'Service-account', allowDefaultProfile: true });
31
+ const startedAt = Date.now();
32
+ const result = await pullServiceAccountsToWorkspace({
33
+ client,
34
+ cwd: context.cwd,
35
+ envName,
36
+ stableKeyName: readProjectStableKeyName(context.cwd),
37
+ force: readBoolFlag(context.args, ['force', 'f']),
38
+ });
39
+ if (readBoolFlag(context.args, ['json'])) {
40
+ context.print(result);
41
+ return;
42
+ }
43
+ const outputResults = [];
44
+ for (const pulled of result.pulled) {
45
+ printSyncStatus(context.println, { status: 'Pulled', direction: 'pull', targetPath: pulled.targetPath });
46
+ outputResults.push({ status: 'pulled', targetPath: pulled.targetPath });
47
+ }
48
+ for (const skipped of result.skipped) {
49
+ printSyncStatus(context.println, { status: 'Skipped', direction: 'pull', targetPath: skipped.targetPath, reason: skipped.reason });
50
+ outputResults.push({ status: 'skipped', targetPath: skipped.targetPath, reason: skipped.reason });
51
+ }
52
+ printSyncSummary(context.println, 'Pulled', outputResults, Date.now() - startedAt);
53
+ }
54
+ async function handlePlan(context) {
55
+ if (!readBoolFlag(context.args, ['all', 'a'])) {
56
+ throw new Error('Service-account plan currently requires --all.');
57
+ }
58
+ if (readBoolFlag(context.args, ['prune'])) {
59
+ throw new Error('Service-account prune is disabled until the backend soft-delete contract is confirmed.');
60
+ }
61
+ const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Service-account', allowDefaultProfile: true });
62
+ const plan = await buildServiceAccountsPlan({
63
+ client,
64
+ cwd: context.cwd,
65
+ envName,
66
+ stableKeyName: readProjectStableKeyName(context.cwd),
67
+ });
68
+ if (readBoolFlag(context.args, ['json'])) {
69
+ context.print(plan);
70
+ }
71
+ else {
72
+ printSyncPlan(context.println, {
73
+ title: 'Service-account',
74
+ environment: displayName,
75
+ counts: plan.counts,
76
+ showHints: readBoolFlag(context.args, ['hints']),
77
+ items: plan.items.map((item) => ({
78
+ ...item,
79
+ details: [],
80
+ })),
81
+ blockers: plan.blockers,
82
+ warnings: plan.exclusions,
83
+ });
84
+ }
85
+ if (readBoolFlag(context.args, ['strict'])) {
86
+ const drift = plan.items.filter((item) => !['clean', 'orphan', 'skipped'].includes(item.status));
87
+ if (plan.blockers.length > 0 || drift.length > 0) {
88
+ throw new Error(`Service-account plan is not clean: ${drift.length} drift item(s), ${plan.blockers.length} blocker(s).`);
89
+ }
90
+ }
91
+ }
92
+ async function handlePush(context) {
93
+ if (!readBoolFlag(context.args, ['all', 'a'])) {
94
+ throw new Error('Service-account push currently requires --all.');
95
+ }
96
+ if (readBoolFlag(context.args, ['prune'])) {
97
+ throw new Error('Service-account prune is disabled until the backend soft-delete contract is confirmed.');
98
+ }
99
+ const { client, envName, displayName } = await resolveResourceTarget(context, { resource: 'Service-account', allowDefaultProfile: true });
100
+ if (!readBoolFlag(context.args, ['yes', 'y'])) {
101
+ if (!isInteractiveTerminal() || !await promptConfirm(`Push service-accounts to "${displayName}"?`, false)) {
102
+ throw new Error('Service-account push requires confirmation. Re-run with --yes or use an interactive terminal.');
103
+ }
104
+ }
105
+ const startedAt = Date.now();
106
+ const result = await pushServiceAccounts({
107
+ client,
108
+ cwd: context.cwd,
109
+ envName,
110
+ stableKeyName: readProjectStableKeyName(context.cwd),
111
+ force: readBoolFlag(context.args, ['force', 'f']),
112
+ });
113
+ if (readBoolFlag(context.args, ['json'])) {
114
+ context.print(result);
115
+ }
116
+ else {
117
+ for (const item of result.results) {
118
+ const label = item.status === 'deployed' ? 'Deployed' : item.status === 'failed' ? 'Failed' : 'Skipped';
119
+ printSyncStatus(context.println, {
120
+ status: label,
121
+ direction: 'push',
122
+ targetPath: item.targetPath,
123
+ reason: item.error || item.reason,
124
+ });
125
+ }
126
+ printSyncSummary(context.println, 'Deployed', result.results, Date.now() - startedAt);
127
+ }
128
+ const failed = result.results.filter((item) => item.status === 'failed');
129
+ if (failed.length > 0) {
130
+ throw new Error(`Service-account push finished with ${failed.length} failure(s).`);
131
+ }
132
+ }
133
+ export async function handleServiceAccountsCommand(context) {
134
+ warnAboutExperimentalState(context);
135
+ const subcommand = context.args._[1] || '';
136
+ if (subcommand === 'pull') {
137
+ await handlePull(context);
138
+ return;
139
+ }
140
+ if (subcommand === 'plan') {
141
+ await handlePlan(context);
142
+ return;
143
+ }
144
+ if (subcommand === 'push') {
145
+ await handlePush(context);
146
+ return;
147
+ }
148
+ throw new Error('Unknown service-accounts command. Usage: revo service-accounts <pull|plan|push> --all [--env <name>]');
149
+ }
@@ -1,4 +1,4 @@
1
- export type BrowserAction = 'navigate' | 'dom' | 'click' | 'fill' | 'check' | 'select' | 'press' | 'scroll' | 'wait_for' | 'screenshot';
1
+ export type BrowserAction = 'navigate' | 'dom' | 'click' | 'fill' | 'check' | 'select' | 'press' | 'scroll' | 'wait_for' | 'screenshot' | 'tabs' | 'new_tab' | 'select_tab' | 'close_tab' | 'close';
2
2
  export type BrowserCapture = 'viewport' | 'full_page' | 'element' | 'crop';
3
3
  export type BrowserClip = {
4
4
  x: number;
@@ -10,7 +10,9 @@ export type BrowserActionInput = {
10
10
  url: string;
11
11
  action: BrowserAction;
12
12
  workspace: string;
13
+ agentTerminalWorkspaceId?: string;
13
14
  browserSessionId: string;
15
+ tabId?: string;
14
16
  selector?: string | null;
15
17
  width?: number;
16
18
  height?: number;
@@ -20,28 +22,54 @@ export type BrowserActionInput = {
20
22
  deltaY?: number;
21
23
  state?: 'visible' | 'hidden';
22
24
  waitTimeoutMs?: number;
25
+ actionTimeoutMs?: number;
23
26
  capture?: BrowserCapture;
24
27
  clip?: BrowserClip;
25
28
  localOnly?: boolean;
26
29
  networkAccessExpiresAt?: number | null;
27
30
  networkAccessOnce?: boolean;
31
+ networkAccessForThread?: boolean;
32
+ actorUserId?: string;
33
+ threadId?: string;
34
+ policyGrantRevision?: number;
28
35
  signal?: AbortSignal;
29
36
  onActionAttempt?: () => void;
30
37
  };
38
+ export type BrowserTab = {
39
+ id: string;
40
+ title: string;
41
+ url: string;
42
+ active: boolean;
43
+ };
31
44
  export type BrowserActionResult = {
32
45
  dom: string;
33
46
  pageUrl: string;
34
47
  screenshotPath?: string;
48
+ browserSessionId: string;
49
+ activeTabId: string | null;
50
+ tabs: BrowserTab[];
51
+ sessionCreated: boolean;
35
52
  };
36
53
  export declare function browserUrl(value: string): string;
37
54
  export declare function localBrowserUrl(value: string): string;
38
55
  export declare function validateBrowserActionInput(input: BrowserActionInput): void;
39
56
  export declare function closeBrowserSessions(): Promise<void>;
57
+ export declare function reconcileBrowserSessions(networkMode: 'restricted' | 'sandbox' | 'external', policyGrantRevision?: number): Promise<number>;
58
+ export declare function threadBrowserScopes(): Array<{
59
+ browserSessionId: string;
60
+ actorUserId: string;
61
+ threadId: string;
62
+ policyGrantRevision: number;
63
+ networkAccess: 'local' | 'full';
64
+ }>;
65
+ export declare function closeThreadBrowserSession(browserSessionId: string): Promise<void>;
66
+ export declare function browserSessionIds(): string[];
40
67
  export declare function hasBrowserSessions(): boolean;
41
68
  export declare function writePrivateScreenshot(file: string, bytes: Buffer): void;
42
69
  export declare function runBrowserAction(input: BrowserActionInput): Promise<BrowserActionResult>;
43
70
  export declare function fillBrowserSecret(input: {
44
71
  browserSessionId: string;
72
+ browserTabId?: string;
45
73
  origin: string;
46
74
  selector: string;
47
75
  value: string;
@@ -1,9 +1,9 @@
1
1
  import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
- import { chromium } from 'playwright-core';
5
4
  const MAX_BROWSER_SESSIONS = 4;
6
- const BROWSER_SESSION_IDLE_MS = 10 * 60_000;
5
+ const BROWSER_SESSION_IDLE_MS = 60 * 60_000;
6
+ const MAX_BROWSER_TABS = 16;
7
7
  const browserSessions = new Map();
8
8
  const creatingSessions = new Set();
9
9
  const sessionQueues = new Map();
@@ -13,6 +13,7 @@ const PRESS_KEYS = new Set(['Enter', 'Tab', 'Escape', 'Backspace',
13
13
  'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);
14
14
  let cleanupTimer;
15
15
  let sessionEpoch = 0;
16
+ let permanentNetworkMode;
16
17
  export function browserUrl(value) {
17
18
  const parsed = new URL(value);
18
19
  if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
@@ -32,16 +33,34 @@ function safePageUrl(value) {
32
33
  return parsed.toString();
33
34
  }
34
35
  export function validateBrowserActionInput(input) {
35
- (input.localOnly ? localBrowserUrl : browserUrl)(input.url);
36
+ (input.localOnly && !['tabs', 'close', 'close_tab'].includes(input.action) ? localBrowserUrl : browserUrl)(input.url);
37
+ if (input.actionTimeoutMs !== undefined && (!Number.isInteger(input.actionTimeoutMs)
38
+ || input.actionTimeoutMs < 1 || input.actionTimeoutMs > 120_000))
39
+ throw new Error('invalid_browser_timeout');
36
40
  if (input.networkAccessOnce !== undefined && typeof input.networkAccessOnce !== 'boolean'
37
41
  || input.networkAccessOnce === true && (!Number.isSafeInteger(input.networkAccessExpiresAt)
38
42
  || input.networkAccessExpiresAt <= Date.now()))
39
43
  throw new Error('terminal_policy_invalid');
40
- if (!['navigate', 'dom', 'click', 'fill', 'check', 'select', 'press', 'scroll', 'wait_for', 'screenshot']
44
+ if (input.networkAccessForThread !== undefined && typeof input.networkAccessForThread !== 'boolean'
45
+ || input.networkAccessForThread === true && (input.networkAccessExpiresAt != null || input.networkAccessOnce === true
46
+ || typeof input.actorUserId !== 'string' || !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/iu.test(input.actorUserId)
47
+ || typeof input.threadId !== 'string' || !input.threadId || input.threadId.length > 128
48
+ || !Number.isSafeInteger(input.policyGrantRevision) || input.policyGrantRevision < 0))
49
+ throw new Error('terminal_policy_invalid');
50
+ if (!['navigate', 'dom', 'click', 'fill', 'check', 'select', 'press', 'scroll', 'wait_for', 'screenshot',
51
+ 'tabs', 'new_tab', 'select_tab', 'close_tab', 'close']
41
52
  .includes(input.action))
42
53
  throw new Error('invalid_browser_action');
43
54
  if (!/^[a-f0-9]{64}$/u.test(input.browserSessionId))
44
55
  throw new Error('invalid_browser_session');
56
+ if (input.tabId !== undefined && !/^[a-f0-9]{8}-[a-f0-9]{4}-[1-8][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/iu.test(input.tabId)
57
+ || ['select_tab', 'close_tab'].includes(input.action) && !input.tabId)
58
+ throw new Error('invalid_browser_tab');
59
+ if (['tabs', 'new_tab', 'select_tab', 'close_tab', 'close'].includes(input.action)
60
+ && (input.selector != null || input.value !== undefined || input.checked !== undefined
61
+ || input.key !== undefined || input.deltaY !== undefined || input.state !== undefined
62
+ || input.waitTimeoutMs !== undefined || input.capture !== undefined || input.clip !== undefined))
63
+ throw new Error('invalid_browser_action_options');
45
64
  const width = input.width ?? 1440;
46
65
  const height = input.height ?? 900;
47
66
  if (!Number.isInteger(width) || width < 320 || width > 1920
@@ -78,7 +97,7 @@ export function validateBrowserActionInput(input) {
78
97
  throw new Error('invalid_browser_scroll');
79
98
  if (input.action === 'wait_for') {
80
99
  if (!['visible', 'hidden'].includes(input.state || '') || !Number.isInteger(input.waitTimeoutMs)
81
- || input.waitTimeoutMs < 1 || input.waitTimeoutMs > 10_000)
100
+ || input.waitTimeoutMs < 1 || input.waitTimeoutMs > 120_000)
82
101
  throw new Error('invalid_browser_wait');
83
102
  }
84
103
  else if (input.state !== undefined || input.waitTimeoutMs !== undefined)
@@ -114,6 +133,10 @@ function setNetworkLease(id, session, expiresAt) {
114
133
  clearTimeout(session.networkLeaseTimer);
115
134
  session.networkLeaseTimer = undefined;
116
135
  session.networkAccessExpiresAt = expiresAt;
136
+ const permanent = session.localOnly ? permanentNetworkMode === 'sandbox' || permanentNetworkMode === 'external'
137
+ : permanentNetworkMode === 'external';
138
+ if (permanent)
139
+ return;
117
140
  if (expiresAt === null)
118
141
  return;
119
142
  if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now())
@@ -138,18 +161,52 @@ function startIdleCleanup() {
138
161
  }
139
162
  export async function closeBrowserSessions() {
140
163
  sessionEpoch++;
164
+ permanentNetworkMode = undefined;
141
165
  if (cleanupTimer)
142
166
  clearInterval(cleanupTimer);
143
167
  cleanupTimer = undefined;
144
168
  await Promise.all([...browserSessions.keys()].map(id => closeSession(id)));
145
169
  }
170
+ export async function reconcileBrowserSessions(networkMode, policyGrantRevision) {
171
+ permanentNetworkMode = networkMode;
172
+ const now = Date.now();
173
+ const closed = [...browserSessions].filter(([id, session]) => {
174
+ const permanent = session.localOnly ? networkMode !== 'restricted' : networkMode === 'external';
175
+ if (session.workspace && session.policyGrantRevision !== undefined && policyGrantRevision !== undefined
176
+ && session.policyGrantRevision !== policyGrantRevision)
177
+ return true;
178
+ if (session.threadScope && policyGrantRevision !== undefined
179
+ && session.threadScope.policyGrantRevision !== policyGrantRevision)
180
+ return true;
181
+ if (!permanent && !session.threadScope
182
+ && (session.networkAccessExpiresAt === null || session.networkAccessExpiresAt <= now))
183
+ return true;
184
+ setNetworkLease(id, session, session.networkAccessExpiresAt);
185
+ return false;
186
+ }).map(([id]) => id);
187
+ await Promise.all(closed.map(id => closeSession(id)));
188
+ return closed.length;
189
+ }
190
+ export function threadBrowserScopes() {
191
+ return [...browserSessions].flatMap(([browserSessionId, session]) => session.threadScope
192
+ ? [{ browserSessionId, ...session.threadScope, networkAccess: session.localOnly ? 'local' : 'full' }] : []);
193
+ }
194
+ export async function closeThreadBrowserSession(browserSessionId) {
195
+ if (browserSessions.get(browserSessionId)?.threadScope)
196
+ await closeSession(browserSessionId);
197
+ }
198
+ export function browserSessionIds() { return [...browserSessions.keys()]; }
146
199
  export function hasBrowserSessions() { return browserSessions.size > 0; }
147
- async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt) {
200
+ async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt, actionTimeoutMs) {
148
201
  await pruneIdleSessions();
149
202
  if (browserSessions.size + creatingSessions.size >= MAX_BROWSER_SESSIONS)
150
203
  throw new Error('browser_session_limit');
151
204
  creatingSessions.add(id);
152
205
  const epoch = sessionEpoch;
206
+ const { chromium } = await import('playwright-core').catch(error => {
207
+ creatingSessions.delete(id);
208
+ throw error;
209
+ });
153
210
  const browser = await chromium.launch({ headless: true,
154
211
  args: localOnly ? ['--disable-background-networking',
155
212
  '--host-resolver-rules=MAP localhost 127.0.0.1'] : [] }).catch(error => {
@@ -202,9 +259,11 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
202
259
  'WebTransport', 'Worker', 'SharedWorker'].every(name => typeof Reflect.get(globalThis, name) === 'undefined'
203
260
  && Object.getOwnPropertyDescriptor(globalThis, name)?.configurable === false)))
204
261
  throw new Error('browser_local_network_guard_unavailable');
205
- const session = { browser, context, page, localOnly,
262
+ const session = { browser, context, page, localOnly, tabs: new Map(),
206
263
  lastUsedAt: Date.now(), active: false, networkAccessExpiresAt: null };
264
+ registerTab(session, page);
207
265
  context.on('page', opened => {
266
+ registerTab(session, opened);
208
267
  session.page = opened;
209
268
  opened.on('close', () => {
210
269
  if (session.page !== opened)
@@ -220,7 +279,7 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
220
279
  await opened.waitForLoadState('domcontentloaded', { timeout: 5_000 }).catch(() => undefined);
221
280
  }).catch(() => undefined);
222
281
  onNavigationAttempt?.();
223
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
282
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: actionTimeoutMs ?? 30_000 });
224
283
  (localOnly ? localBrowserUrl : browserUrl)(page.url());
225
284
  const hasContent = await page.evaluate(() => Boolean(document.body?.innerText.trim()
226
285
  || document.querySelector('input, textarea, select, button, a[href], [role], [contenteditable]')));
@@ -243,6 +302,30 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
243
302
  creatingSessions.delete(id);
244
303
  }
245
304
  }
305
+ function registerTab(session, page) {
306
+ if ([...session.tabs.values()].includes(page))
307
+ return;
308
+ if (session.tabs.size >= MAX_BROWSER_TABS) {
309
+ void page.close();
310
+ return;
311
+ }
312
+ const id = randomUUID();
313
+ session.tabs.set(id, page);
314
+ page.on('close', () => { session.tabs.delete(id); });
315
+ }
316
+ async function describeSession(id, session, sessionCreated) {
317
+ const tabs = [];
318
+ for (const [tabId, page] of session?.tabs || []) {
319
+ if (page.isClosed())
320
+ continue;
321
+ const rawUrl = page.url();
322
+ tabs.push({ id: tabId, title: (await page.title().catch(() => '')).slice(0, 200),
323
+ url: rawUrl === 'about:blank' ? rawUrl : safePageUrl(rawUrl), active: session?.page === page });
324
+ }
325
+ const active = tabs.find(tab => tab.active);
326
+ return { browserSessionId: id, activeTabId: active?.id || null,
327
+ tabs, pageUrl: active?.url || '', sessionCreated };
328
+ }
246
329
  function activePage(session) {
247
330
  if (!session.page.isClosed())
248
331
  return session.page;
@@ -324,27 +407,43 @@ async function runForSession(input) {
324
407
  if (input.signal?.aborted)
325
408
  throw new Error('browser_cancelled');
326
409
  validateBrowserActionInput(input);
327
- const url = input.localOnly ? localBrowserUrl(input.url) : browserUrl(input.url);
410
+ const url = input.localOnly && !['tabs', 'close', 'close_tab'].includes(input.action) ? localBrowserUrl(input.url) : browserUrl(input.url);
328
411
  const width = input.width ?? 1440;
329
412
  const height = input.height ?? 900;
330
413
  let session = browserSessions.get(input.browserSessionId);
331
- if (session && (session.localOnly !== (input.localOnly === true) || !session.browser.isConnected()
414
+ if (session && (!['tabs', 'close', 'close_tab'].includes(input.action) && session.localOnly !== (input.localOnly === true) || !session.browser.isConnected()
332
415
  || session.context.pages().every(page => page.isClosed())
333
416
  || Date.now() - session.lastUsedAt >= BROWSER_SESSION_IDLE_MS)) {
334
417
  await closeSession(input.browserSessionId);
335
418
  session = undefined;
336
419
  }
337
- if (!session && (INTERACTIVE_ACTIONS.has(input.action) || input.action === 'wait_for'))
420
+ if (input.action === 'close') {
421
+ await closeSession(input.browserSessionId);
422
+ return { dom: '', ...await describeSession(input.browserSessionId, undefined, false) };
423
+ }
424
+ if (!session && input.action === 'tabs')
425
+ return { dom: '', ...await describeSession(input.browserSessionId, undefined, false) };
426
+ if (!session && input.tabId)
427
+ throw new Error('browser_session_missing');
428
+ if (!session && (INTERACTIVE_ACTIONS.has(input.action) || input.action === 'wait_for'
429
+ || input.action === 'select_tab' || input.action === 'close_tab'))
338
430
  throw new Error('browser_session_missing');
339
431
  const created = !session;
340
432
  if (!session)
341
- session = await createSession(input.browserSessionId, url, input.localOnly === true, width, height, input.signal, input.onActionAttempt);
342
- try {
343
- setNetworkLease(input.browserSessionId, session, input.networkAccessExpiresAt ?? null);
344
- }
345
- catch (error) {
346
- await closeSession(input.browserSessionId);
347
- throw error;
433
+ session = await createSession(input.browserSessionId, url, input.localOnly === true, width, height, input.signal, input.onActionAttempt, input.actionTimeoutMs);
434
+ // Inventory and cleanup cannot renew, remove or widen an existing network lease.
435
+ if (!['tabs', 'close_tab'].includes(input.action)) {
436
+ session.workspace = input.agentTerminalWorkspaceId ? input.workspace : undefined;
437
+ session.policyGrantRevision = input.policyGrantRevision;
438
+ session.threadScope = input.networkAccessForThread === true ? { actorUserId: input.actorUserId,
439
+ threadId: input.threadId, ...(input.agentTerminalWorkspaceId ? { agentTerminalWorkspaceId: input.agentTerminalWorkspaceId } : {}), policyGrantRevision: input.policyGrantRevision } : undefined;
440
+ try {
441
+ setNetworkLease(input.browserSessionId, session, input.networkAccessExpiresAt ?? null);
442
+ }
443
+ catch (error) {
444
+ await closeSession(input.browserSessionId);
445
+ throw error;
446
+ }
348
447
  }
349
448
  if (input.signal?.aborted) {
350
449
  await closeSession(input.browserSessionId);
@@ -356,11 +455,38 @@ async function runForSession(input) {
356
455
  try {
357
456
  if (input.signal?.aborted)
358
457
  throw new Error('browser_cancelled');
458
+ if (input.tabId) {
459
+ const selected = session.tabs.get(input.tabId);
460
+ if (!selected || selected.isClosed())
461
+ throw new Error('browser_tab_missing');
462
+ session.page = selected;
463
+ }
464
+ if (input.action === 'tabs')
465
+ return { dom: '', ...await describeSession(input.browserSessionId, session, created) };
466
+ if (input.action === 'close_tab') {
467
+ input.onActionAttempt?.();
468
+ await activePage(session).close();
469
+ const remaining = session.context.pages().filter(page => !page.isClosed());
470
+ if (!remaining.length) {
471
+ await closeSession(input.browserSessionId);
472
+ return { dom: '', ...await describeSession(input.browserSessionId, undefined, false) };
473
+ }
474
+ session.page = remaining[remaining.length - 1];
475
+ return { dom: '', ...await describeSession(input.browserSessionId, session, false) };
476
+ }
477
+ if (input.action === 'new_tab' && !created) {
478
+ if (session.tabs.size >= MAX_BROWSER_TABS)
479
+ throw new Error('browser_tab_limit');
480
+ session.page = await session.context.newPage();
481
+ input.onActionAttempt?.();
482
+ await session.page.goto(url, { waitUntil: 'domcontentloaded', timeout: input.actionTimeoutMs ?? 30_000 });
483
+ }
359
484
  let page = activePage(session);
485
+ await page.bringToFront();
360
486
  await page.setViewportSize({ width, height });
361
487
  if (input.action === 'navigate' && !created) {
362
488
  input.onActionAttempt?.();
363
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
489
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: input.actionTimeoutMs ?? 30_000 });
364
490
  }
365
491
  (input.localOnly ? localBrowserUrl : browserUrl)(page.url());
366
492
  const actionPage = page;
@@ -369,7 +495,7 @@ async function runForSession(input) {
369
495
  if (await target.count() > 1)
370
496
  throw new Error('browser_selector_ambiguous');
371
497
  try {
372
- await target.first().waitFor({ state: 'visible', timeout: 10_000 });
498
+ await target.first().waitFor({ state: 'visible', timeout: input.actionTimeoutMs ?? 10_000 });
373
499
  }
374
500
  catch (error) {
375
501
  const matchCount = await target.count();
@@ -390,26 +516,26 @@ async function runForSession(input) {
390
516
  : Promise.resolve(undefined);
391
517
  input.onActionAttempt?.();
392
518
  if (input.action === 'click') {
393
- await target.click({ timeout: 10_000 });
519
+ await target.click({ timeout: input.actionTimeoutMs ?? 10_000 });
394
520
  }
395
521
  else if (input.action === 'fill')
396
- await target.fill(input.value, { timeout: 10_000 });
522
+ await target.fill(input.value, { timeout: input.actionTimeoutMs ?? 10_000 });
397
523
  else if (input.action === 'check') {
398
524
  if (input.checked)
399
- await target.check({ timeout: 10_000 });
525
+ await target.check({ timeout: input.actionTimeoutMs ?? 10_000 });
400
526
  else
401
- await target.uncheck({ timeout: 10_000 });
527
+ await target.uncheck({ timeout: input.actionTimeoutMs ?? 10_000 });
402
528
  }
403
529
  else if (input.action === 'select')
404
- await target.selectOption(input.value, { timeout: 10_000 });
530
+ await target.selectOption(input.value, { timeout: input.actionTimeoutMs ?? 10_000 });
405
531
  else
406
- await target.press(input.key, { timeout: 10_000 });
532
+ await target.press(input.key, { timeout: input.actionTimeoutMs ?? 10_000 });
407
533
  const opened = await popup;
408
534
  if (opened && !opened.isClosed())
409
535
  session.page = opened;
410
536
  page = activePage(session);
411
537
  if (page !== actionPage)
412
- await page.waitForLoadState('domcontentloaded', { timeout: 10_000 });
538
+ await page.waitForLoadState('domcontentloaded', { timeout: input.actionTimeoutMs ?? 10_000 });
413
539
  (input.localOnly ? localBrowserUrl : browserUrl)(page.url());
414
540
  }
415
541
  else if (input.action === 'scroll') {
@@ -417,15 +543,16 @@ async function runForSession(input) {
417
543
  await page.mouse.wheel(0, input.deltaY);
418
544
  }
419
545
  else if (input.action === 'wait_for') {
420
- await target.waitFor({ state: input.state, timeout: input.waitTimeoutMs });
546
+ await target.waitFor({ state: input.state, timeout: Math.min(input.waitTimeoutMs, input.actionTimeoutMs ?? input.waitTimeoutMs) });
421
547
  }
422
548
  const domTarget = INTERACTIVE_ACTIONS.has(input.action)
423
549
  || input.action === 'wait_for' && input.state === 'hidden' ? page.locator('body') : target.first();
424
- const bodyText = (await domTarget.innerText({ timeout: 10_000 })).slice(0, 25_000);
550
+ const bodyText = (await domTarget.innerText({ timeout: input.actionTimeoutMs ?? 10_000 })).slice(0, 25_000);
425
551
  const dom = (bodyText + await semanticControls(page)).slice(0, 40_000);
426
552
  const pageUrl = safePageUrl(page.url());
553
+ const inventory = await describeSession(input.browserSessionId, session, created);
427
554
  if (input.action !== 'screenshot')
428
- return { dom, pageUrl };
555
+ return { dom, ...inventory, pageUrl };
429
556
  const root = fs.realpathSync(input.workspace);
430
557
  const privateDirectory = path.join(root, '.revo');
431
558
  fs.mkdirSync(privateDirectory, { recursive: true, mode: 0o700 });
@@ -447,22 +574,22 @@ async function runForSession(input) {
447
574
  const box = await target.boundingBox();
448
575
  if (!box || box.width * box.height > 8_000_000)
449
576
  throw new Error('browser_element_too_large');
450
- bytes = await target.first().screenshot({ timeout: 20_000 });
577
+ bytes = await target.first().screenshot({ timeout: input.actionTimeoutMs ?? 20_000 });
451
578
  }
452
579
  else if (capture === 'crop') {
453
580
  const scroll = await page.evaluate(() => ({ x: window.scrollX, y: window.scrollY }));
454
- bytes = await page.screenshot({ timeout: 20_000,
581
+ bytes = await page.screenshot({ timeout: input.actionTimeoutMs ?? 20_000,
455
582
  clip: { x: scroll.x + input.clip.x, y: scroll.y + input.clip.y,
456
583
  width: input.clip.width, height: input.clip.height } });
457
584
  }
458
585
  else {
459
- bytes = await page.screenshot({ timeout: 20_000,
586
+ bytes = await page.screenshot({ timeout: input.actionTimeoutMs ?? 20_000,
460
587
  fullPage: capture === 'full_page' });
461
588
  }
462
589
  if (bytes.length > 30 * 1024 * 1024)
463
590
  throw new Error('browser_screenshot_too_large');
464
591
  writePrivateScreenshot(screenshotPath, bytes);
465
- return { dom, pageUrl, screenshotPath };
592
+ return { dom, ...inventory, pageUrl, screenshotPath };
466
593
  }
467
594
  finally {
468
595
  input.signal?.removeEventListener('abort', onAbort);
@@ -513,6 +640,8 @@ export async function fillBrowserSecret(input) {
513
640
  session.active = true;
514
641
  try {
515
642
  const page = activePage(session);
643
+ if (input.browserTabId && session.tabs.get(input.browserTabId) !== page)
644
+ throw new Error('secure_input_session_missing');
516
645
  if (new URL(browserUrl(page.url())).origin !== input.origin)
517
646
  throw new Error('secure_input_origin_changed');
518
647
  const target = page.locator(input.selector);
@@ -524,6 +653,8 @@ export async function fillBrowserSecret(input) {
524
653
  throw new Error('secure_input_not_secret_control');
525
654
  if (new URL(browserUrl(page.url())).origin !== input.origin || activePage(session) !== page)
526
655
  throw new Error('secure_input_origin_changed');
656
+ if (input.browserTabId && session.tabs.get(input.browserTabId) !== page)
657
+ throw new Error('secure_input_session_missing');
527
658
  if (input.isAuthorized?.() === false)
528
659
  throw new Error('secure_input_session_missing');
529
660
  if (session.networkAccessExpiresAt !== null && session.networkAccessExpiresAt <= Date.now())
@@ -0,0 +1,21 @@
1
+ export type FileTransfer = {
2
+ path: string;
3
+ url: string;
4
+ headers: Array<{
5
+ name: string;
6
+ value: string;
7
+ }>;
8
+ overwrite: boolean;
9
+ offset: number | null;
10
+ length: number | null;
11
+ };
12
+ export type FileTransferResult = {
13
+ bytes: number;
14
+ complete: boolean;
15
+ status: number;
16
+ nextOffset?: number;
17
+ etag?: string;
18
+ };
19
+ /** URLs and headers are credentials. Never include them in errors or operational logs. */
20
+ export declare function validateFileTransfer(value: unknown): value is FileTransfer;
21
+ export declare function transferWorkspaceFile(workspace: string, operation: 'upload_file' | 'download_file', transfer: FileTransfer, signal: AbortSignal): Promise<FileTransferResult>;