@revoengine/cli 1.0.13 → 1.0.15

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 (37) hide show
  1. package/README.md +26 -12
  2. package/dist/src/cli.js +4 -0
  3. package/dist/src/client.d.ts +5 -11
  4. package/dist/src/client.js +41 -74
  5. package/dist/src/commands/component.js +26 -25
  6. package/dist/src/commands/env.js +1 -5
  7. package/dist/src/commands/migrate.js +10 -0
  8. package/dist/src/commands/terminal-browser.d.ts +41 -6
  9. package/dist/src/commands/terminal-browser.js +503 -20
  10. package/dist/src/commands/terminal-image.js +59 -1
  11. package/dist/src/commands/terminal-operational-log.d.ts +18 -0
  12. package/dist/src/commands/terminal-operational-log.js +119 -0
  13. package/dist/src/commands/terminal-policy.d.ts +29 -0
  14. package/dist/src/commands/terminal-policy.js +67 -0
  15. package/dist/src/commands/terminal-pty.d.ts +4 -0
  16. package/dist/src/commands/terminal-pty.js +41 -0
  17. package/dist/src/commands/terminal-reconnect-grace.d.ts +30 -0
  18. package/dist/src/commands/terminal-reconnect-grace.js +87 -0
  19. package/dist/src/commands/terminal-sandbox.d.ts +5 -1
  20. package/dist/src/commands/terminal-sandbox.js +19 -5
  21. package/dist/src/commands/terminal-secure-browser.d.ts +25 -0
  22. package/dist/src/commands/terminal-secure-browser.js +58 -0
  23. package/dist/src/commands/terminal-service.d.ts +4 -3
  24. package/dist/src/commands/terminal-service.js +19 -15
  25. package/dist/src/commands/terminal.d.ts +22 -3
  26. package/dist/src/commands/terminal.js +622 -95
  27. package/dist/src/config.d.ts +0 -3
  28. package/dist/src/config.js +0 -2
  29. package/dist/src/migration.js +10 -11
  30. package/dist/src/request-queue.d.ts +20 -0
  31. package/dist/src/request-queue.js +80 -0
  32. package/dist/src/resource-inventory.js +9 -10
  33. package/dist/src/resource-syncs/database-view-sync.d.ts +0 -1
  34. package/dist/src/resource-syncs/database-view-sync.js +1 -12
  35. package/dist/src/resource-syncs/endpoint-sync.js +12 -46
  36. package/dist/src/types.d.ts +2 -0
  37. package/package.json +5 -3
@@ -1,16 +1,51 @@
1
- export type BrowserAction = 'navigate' | 'dom' | 'screenshot';
2
- export declare function browserUrl(value: string): string;
3
- export declare function localBrowserUrl(value: string): string;
4
- export declare function runBrowserAction(input: {
1
+ export type BrowserAction = 'navigate' | 'dom' | 'click' | 'fill' | 'check' | 'select' | 'press' | 'scroll' | 'wait_for' | 'screenshot';
2
+ export type BrowserCapture = 'viewport' | 'full_page' | 'element' | 'crop';
3
+ export type BrowserClip = {
4
+ x: number;
5
+ y: number;
6
+ width: number;
7
+ height: number;
8
+ };
9
+ export type BrowserActionInput = {
5
10
  url: string;
6
11
  action: BrowserAction;
7
12
  workspace: string;
13
+ browserSessionId: string;
8
14
  selector?: string | null;
9
15
  width?: number;
10
16
  height?: number;
17
+ value?: string;
18
+ checked?: boolean;
19
+ key?: string;
20
+ deltaY?: number;
21
+ state?: 'visible' | 'hidden';
22
+ waitTimeoutMs?: number;
23
+ capture?: BrowserCapture;
24
+ clip?: BrowserClip;
11
25
  localOnly?: boolean;
26
+ networkAccessExpiresAt?: number | null;
27
+ networkAccessOnce?: boolean;
12
28
  signal?: AbortSignal;
13
- }): Promise<{
29
+ onActionAttempt?: () => void;
30
+ };
31
+ export type BrowserActionResult = {
14
32
  dom: string;
33
+ pageUrl: string;
15
34
  screenshotPath?: string;
16
- }>;
35
+ };
36
+ export declare function browserUrl(value: string): string;
37
+ export declare function localBrowserUrl(value: string): string;
38
+ export declare function validateBrowserActionInput(input: BrowserActionInput): void;
39
+ export declare function closeBrowserSessions(): Promise<void>;
40
+ export declare function reconcileBrowserSessions(networkMode: 'restricted' | 'sandbox' | 'external'): Promise<number>;
41
+ export declare function hasBrowserSessions(): boolean;
42
+ export declare function writePrivateScreenshot(file: string, bytes: Buffer): void;
43
+ export declare function runBrowserAction(input: BrowserActionInput): Promise<BrowserActionResult>;
44
+ export declare function fillBrowserSecret(input: {
45
+ browserSessionId: string;
46
+ origin: string;
47
+ selector: string;
48
+ value: string;
49
+ expiresAt: number;
50
+ isAuthorized?: () => boolean;
51
+ }): Promise<void>;
@@ -1,7 +1,18 @@
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';
4
+ const MAX_BROWSER_SESSIONS = 4;
5
+ const BROWSER_SESSION_IDLE_MS = 10 * 60_000;
6
+ const browserSessions = new Map();
7
+ const creatingSessions = new Set();
8
+ const sessionQueues = new Map();
9
+ const FORM_ACTIONS = new Set(['click', 'fill', 'check', 'select', 'press']);
10
+ const INTERACTIVE_ACTIONS = new Set([...FORM_ACTIONS, 'scroll']);
11
+ const PRESS_KEYS = new Set(['Enter', 'Tab', 'Escape', 'Backspace',
12
+ 'ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight']);
13
+ let cleanupTimer;
14
+ let sessionEpoch = 0;
15
+ let permanentNetworkMode;
5
16
  export function browserUrl(value) {
6
17
  const parsed = new URL(value);
7
18
  if (!['http:', 'https:'].includes(parsed.protocol) || parsed.username || parsed.password)
@@ -14,41 +25,188 @@ export function localBrowserUrl(value) {
14
25
  throw new Error('browser_localhost_only');
15
26
  return parsed.toString();
16
27
  }
17
- export async function runBrowserAction(input) {
18
- const url = input.localOnly ? localBrowserUrl(input.url) : browserUrl(input.url);
19
- if (!['navigate', 'dom', 'screenshot'].includes(input.action))
28
+ function safePageUrl(value) {
29
+ const parsed = new URL(browserUrl(value));
30
+ parsed.search = '';
31
+ parsed.hash = '';
32
+ return parsed.toString();
33
+ }
34
+ export function validateBrowserActionInput(input) {
35
+ (input.localOnly ? localBrowserUrl : browserUrl)(input.url);
36
+ if (input.networkAccessOnce !== undefined && typeof input.networkAccessOnce !== 'boolean'
37
+ || input.networkAccessOnce === true && (!Number.isSafeInteger(input.networkAccessExpiresAt)
38
+ || input.networkAccessExpiresAt <= Date.now()))
39
+ throw new Error('terminal_policy_invalid');
40
+ if (!['navigate', 'dom', 'click', 'fill', 'check', 'select', 'press', 'scroll', 'wait_for', 'screenshot']
41
+ .includes(input.action))
20
42
  throw new Error('invalid_browser_action');
43
+ if (!/^[a-f0-9]{64}$/u.test(input.browserSessionId))
44
+ throw new Error('invalid_browser_session');
21
45
  const width = input.width ?? 1440;
22
46
  const height = input.height ?? 900;
23
47
  if (!Number.isInteger(width) || width < 320 || width > 1920
24
48
  || !Number.isInteger(height) || height < 240 || height > 1080)
25
49
  throw new Error('invalid_browser_viewport');
26
- if (input.selector && (input.selector.length > 500 || input.action === 'navigate'))
50
+ if (input.selector !== undefined && input.selector !== null
51
+ && (typeof input.selector !== 'string' || !input.selector.trim() || input.selector.length > 500)
52
+ || input.selector && (input.action === 'navigate' || input.action === 'scroll')
53
+ || (FORM_ACTIONS.has(input.action) || input.action === 'wait_for') && !input.selector)
27
54
  throw new Error('invalid_browser_selector');
55
+ if (input.action === 'fill' || input.action === 'select') {
56
+ if (typeof input.value !== 'string' || input.value.length > 4_096)
57
+ throw new Error('invalid_browser_value');
58
+ }
59
+ else if (input.value !== undefined)
60
+ throw new Error('invalid_browser_value');
61
+ if (input.action === 'check') {
62
+ if (typeof input.checked !== 'boolean')
63
+ throw new Error('invalid_browser_checked');
64
+ }
65
+ else if (input.checked !== undefined)
66
+ throw new Error('invalid_browser_checked');
67
+ if (input.action === 'press') {
68
+ if (!PRESS_KEYS.has(input.key || ''))
69
+ throw new Error('invalid_browser_key');
70
+ }
71
+ else if (input.key !== undefined)
72
+ throw new Error('invalid_browser_key');
73
+ if (input.action === 'scroll') {
74
+ if (!Number.isInteger(input.deltaY) || input.deltaY === 0 || Math.abs(input.deltaY) > 3_000)
75
+ throw new Error('invalid_browser_scroll');
76
+ }
77
+ else if (input.deltaY !== undefined)
78
+ throw new Error('invalid_browser_scroll');
79
+ if (input.action === 'wait_for') {
80
+ if (!['visible', 'hidden'].includes(input.state || '') || !Number.isInteger(input.waitTimeoutMs)
81
+ || input.waitTimeoutMs < 1 || input.waitTimeoutMs > 10_000)
82
+ throw new Error('invalid_browser_wait');
83
+ }
84
+ else if (input.state !== undefined || input.waitTimeoutMs !== undefined)
85
+ throw new Error('invalid_browser_wait');
86
+ if (input.action !== 'screenshot') {
87
+ if (input.capture !== undefined || input.clip !== undefined)
88
+ throw new Error('invalid_browser_capture');
89
+ return;
90
+ }
91
+ const capture = input.capture ?? 'viewport';
92
+ if (!['viewport', 'full_page', 'element', 'crop'].includes(capture)
93
+ || capture === 'element' && !input.selector
94
+ || (capture === 'full_page' || capture === 'crop') && input.selector
95
+ || capture !== 'crop' && input.clip !== undefined
96
+ || capture === 'crop' && (!input.clip || ![input.clip.x, input.clip.y, input.clip.width, input.clip.height]
97
+ .every(Number.isInteger) || input.clip.x < 0 || input.clip.y < 0
98
+ || input.clip.width < 1 || input.clip.height < 1
99
+ || input.clip.width * input.clip.height > 8_000_000
100
+ || input.clip.x + input.clip.width > width || input.clip.y + input.clip.height > height))
101
+ throw new Error('invalid_browser_capture');
102
+ }
103
+ async function closeSession(id) {
104
+ const session = browserSessions.get(id);
105
+ if (!session)
106
+ return;
107
+ browserSessions.delete(id);
108
+ if (session.networkLeaseTimer)
109
+ clearTimeout(session.networkLeaseTimer);
110
+ await session.browser.close().catch(() => undefined);
111
+ }
112
+ function setNetworkLease(id, session, expiresAt) {
113
+ if (session.networkLeaseTimer)
114
+ clearTimeout(session.networkLeaseTimer);
115
+ session.networkLeaseTimer = undefined;
116
+ session.networkAccessExpiresAt = expiresAt;
117
+ const permanent = session.localOnly ? permanentNetworkMode === 'sandbox' || permanentNetworkMode === 'external'
118
+ : permanentNetworkMode === 'external';
119
+ if (permanent)
120
+ return;
121
+ if (expiresAt === null)
122
+ return;
123
+ if (!Number.isSafeInteger(expiresAt) || expiresAt <= Date.now())
124
+ throw new Error('terminal_policy_expired');
125
+ session.networkLeaseTimer = setTimeout(() => { void closeSession(id); }, expiresAt - Date.now());
126
+ session.networkLeaseTimer.unref?.();
127
+ }
128
+ async function pruneIdleSessions() {
129
+ const now = Date.now();
130
+ await Promise.all([...browserSessions].filter(([, session]) => !session.active
131
+ && now - session.lastUsedAt >= BROWSER_SESSION_IDLE_MS).map(([id]) => closeSession(id)));
132
+ if (!browserSessions.size && cleanupTimer) {
133
+ clearInterval(cleanupTimer);
134
+ cleanupTimer = undefined;
135
+ }
136
+ }
137
+ function startIdleCleanup() {
138
+ if (cleanupTimer)
139
+ return;
140
+ cleanupTimer = setInterval(() => { void pruneIdleSessions(); }, 60_000);
141
+ cleanupTimer.unref?.();
142
+ }
143
+ export async function closeBrowserSessions() {
144
+ sessionEpoch++;
145
+ permanentNetworkMode = undefined;
146
+ if (cleanupTimer)
147
+ clearInterval(cleanupTimer);
148
+ cleanupTimer = undefined;
149
+ await Promise.all([...browserSessions.keys()].map(id => closeSession(id)));
150
+ }
151
+ export async function reconcileBrowserSessions(networkMode) {
152
+ permanentNetworkMode = networkMode;
153
+ const now = Date.now();
154
+ const closed = [...browserSessions].filter(([id, session]) => {
155
+ const permanent = session.localOnly ? networkMode !== 'restricted' : networkMode === 'external';
156
+ if (!permanent && (session.networkAccessExpiresAt === null || session.networkAccessExpiresAt <= now))
157
+ return true;
158
+ setNetworkLease(id, session, session.networkAccessExpiresAt);
159
+ return false;
160
+ }).map(([id]) => id);
161
+ await Promise.all(closed.map(id => closeSession(id)));
162
+ return closed.length;
163
+ }
164
+ export function hasBrowserSessions() { return browserSessions.size > 0; }
165
+ async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt) {
166
+ await pruneIdleSessions();
167
+ if (browserSessions.size + creatingSessions.size >= MAX_BROWSER_SESSIONS)
168
+ throw new Error('browser_session_limit');
169
+ creatingSessions.add(id);
170
+ const epoch = sessionEpoch;
171
+ const { chromium } = await import('playwright-core').catch(error => {
172
+ creatingSessions.delete(id);
173
+ throw error;
174
+ });
28
175
  const browser = await chromium.launch({ headless: true,
29
- args: input.localOnly ? ['--disable-background-networking',
176
+ args: localOnly ? ['--disable-background-networking',
30
177
  '--host-resolver-rules=MAP localhost 127.0.0.1'] : [] }).catch(error => {
31
178
  if (error instanceof Error && error.message.includes("Executable doesn't exist at"))
32
179
  throw new Error('browser_binary_unavailable');
33
180
  throw error;
34
- });
181
+ }).catch(error => { creatingSessions.delete(id); throw error; });
35
182
  const onAbort = () => { void browser.close(); };
36
- input.signal?.addEventListener('abort', onAbort, { once: true });
183
+ signal?.addEventListener('abort', onAbort, { once: true });
37
184
  try {
38
- if (input.signal?.aborted)
185
+ if (signal?.aborted)
39
186
  throw new Error('browser_cancelled');
40
187
  const context = await browser.newContext({ viewport: { width, height }, acceptDownloads: false,
41
188
  serviceWorkers: 'block' });
189
+ if (localOnly)
190
+ await context.addInitScript(() => {
191
+ // These APIs can open sockets outside Playwright's HTTP and WebSocket routes.
192
+ // Workers do not receive context init scripts, so prevent them from restoring access.
193
+ for (const name of ['RTCPeerConnection', 'webkitRTCPeerConnection', 'WebTransport',
194
+ 'Worker', 'SharedWorker']) {
195
+ Object.defineProperty(globalThis, name, {
196
+ value: undefined, writable: false, configurable: false,
197
+ });
198
+ }
199
+ });
42
200
  await context.route('**/*', route => {
43
201
  try {
44
- (input.localOnly ? localBrowserUrl : browserUrl)(route.request().url());
202
+ (localOnly ? localBrowserUrl : browserUrl)(route.request().url());
45
203
  return route.continue();
46
204
  }
47
205
  catch {
48
206
  return route.abort();
49
207
  }
50
208
  });
51
- if (input.localOnly)
209
+ if (localOnly)
52
210
  await context.routeWebSocket('**/*', socket => {
53
211
  try {
54
212
  const parsed = new URL(socket.url());
@@ -62,12 +220,234 @@ export async function runBrowserAction(input) {
62
220
  }
63
221
  });
64
222
  const page = await context.newPage();
223
+ if (localOnly && !await page.evaluate(() => ['RTCPeerConnection', 'webkitRTCPeerConnection',
224
+ 'WebTransport', 'Worker', 'SharedWorker'].every(name => typeof Reflect.get(globalThis, name) === 'undefined'
225
+ && Object.getOwnPropertyDescriptor(globalThis, name)?.configurable === false)))
226
+ throw new Error('browser_local_network_guard_unavailable');
227
+ const session = { browser, context, page, localOnly,
228
+ lastUsedAt: Date.now(), active: false, networkAccessExpiresAt: null };
229
+ context.on('page', opened => {
230
+ session.page = opened;
231
+ opened.on('close', () => {
232
+ if (session.page !== opened)
233
+ return;
234
+ const remaining = context.pages().filter(candidate => !candidate.isClosed());
235
+ if (remaining.length)
236
+ session.page = remaining[remaining.length - 1];
237
+ });
238
+ });
239
+ const initialPopup = page.waitForEvent('popup', { timeout: 5_000 })
240
+ .then(async (opened) => {
241
+ session.page = opened;
242
+ await opened.waitForLoadState('domcontentloaded', { timeout: 5_000 }).catch(() => undefined);
243
+ }).catch(() => undefined);
244
+ onNavigationAttempt?.();
65
245
  await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
246
+ (localOnly ? localBrowserUrl : browserUrl)(page.url());
247
+ const hasContent = await page.evaluate(() => Boolean(document.body?.innerText.trim()
248
+ || document.querySelector('input, textarea, select, button, a[href], [role], [contenteditable]')));
249
+ if (session.page === page && !hasContent) {
250
+ await Promise.race([initialPopup, page.waitForFunction(() => Boolean(document.body?.innerText.trim()
251
+ || document.querySelector('input, textarea, select, button, a[href], [role], [contenteditable]')), undefined, { timeout: 5_000 }).catch(() => undefined)]);
252
+ }
253
+ if (epoch !== sessionEpoch)
254
+ throw new Error('browser_session_closed');
255
+ browserSessions.set(id, session);
256
+ startIdleCleanup();
257
+ return session;
258
+ }
259
+ catch (error) {
260
+ await browser.close().catch(() => undefined);
261
+ throw error;
262
+ }
263
+ finally {
264
+ signal?.removeEventListener('abort', onAbort);
265
+ creatingSessions.delete(id);
266
+ }
267
+ }
268
+ function activePage(session) {
269
+ if (!session.page.isClosed())
270
+ return session.page;
271
+ const remaining = session.context.pages().filter(page => !page.isClosed());
272
+ if (!remaining.length)
273
+ throw new Error('browser_session_missing');
274
+ session.page = remaining[remaining.length - 1];
275
+ return session.page;
276
+ }
277
+ async function semanticControls(page) {
278
+ const controls = await page.locator('input:not([type="hidden"]), textarea, select, button, a[href],'
279
+ + ' [role], [contenteditable="true"]').evaluateAll(elements => elements.slice(0, 120).map(element => {
280
+ const tag = element.tagName.toLowerCase();
281
+ const attribute = (name) => element.getAttribute(name)?.slice(0, 120) || undefined;
282
+ const id = attribute('id');
283
+ const testId = attribute('data-testid');
284
+ const name = attribute('name');
285
+ const ariaLabel = attribute('aria-label');
286
+ const placeholder = attribute('placeholder');
287
+ const type = attribute('type');
288
+ const label = element instanceof HTMLInputElement || element instanceof HTMLSelectElement
289
+ || element instanceof HTMLTextAreaElement
290
+ ? [...(element.labels || [])].map(item => item.innerText.trim()).filter(Boolean).join(' ').slice(0, 120)
291
+ : undefined;
292
+ const selector = id ? `#${CSS.escape(id)}`
293
+ : testId ? `[data-testid=${CSS.escape(testId)}]`
294
+ : name ? `${tag}[name=${CSS.escape(name)}]`
295
+ : ariaLabel ? `${tag}[aria-label=${CSS.escape(ariaLabel)}]`
296
+ : placeholder ? `${tag}[placeholder=${CSS.escape(placeholder)}]` : undefined;
297
+ const item = { tag, selector, role: attribute('role'), type,
298
+ id, name, testId, ariaLabel, placeholder, label,
299
+ text: tag === 'input' || tag === 'textarea' || tag === 'select' ? undefined
300
+ : element.textContent?.trim().slice(0, 100) || undefined,
301
+ checked: element instanceof HTMLInputElement && ['checkbox', 'radio'].includes(element.type)
302
+ ? element.checked : undefined,
303
+ disabled: 'disabled' in element ? Boolean(element.disabled) : undefined };
304
+ return Object.fromEntries(Object.entries(item).filter(([, value]) => value !== undefined && value !== ''));
305
+ }));
306
+ if (!controls.length)
307
+ return '';
308
+ return '\n\nInteractive elements (field values omitted):\n'
309
+ + controls.map((item, index) => `${index + 1}. ${JSON.stringify(item)}`).join('\n').slice(0, 12_000);
310
+ }
311
+ async function guardSecretFill(page, selector) {
312
+ if (await isSecretControl(page, selector))
313
+ throw new Error('browser_secret_input_requires_secure_reference');
314
+ }
315
+ async function isSecretControl(page, selector) {
316
+ const target = page.locator(selector);
317
+ const attributes = await Promise.all(['type', 'id', 'name', 'autocomplete', 'aria-label', 'placeholder']
318
+ .map(name => target.getAttribute(name, { timeout: 10_000 })));
319
+ return attributes[0]?.toLowerCase() === 'password'
320
+ || attributes.some(value => value && /passw(or)?d|secret|api.?key|token|one.?time|\botp\b|2fa|mfa/iu.test(value));
321
+ }
322
+ export function writePrivateScreenshot(file, bytes) {
323
+ let descriptor;
324
+ try {
325
+ descriptor = fs.openSync(file, 'wx', 0o600);
326
+ fs.fchmodSync(descriptor, 0o600);
327
+ fs.writeFileSync(descriptor, bytes);
328
+ }
329
+ catch (error) {
330
+ if (descriptor !== undefined) {
331
+ try {
332
+ fs.closeSync(descriptor);
333
+ }
334
+ catch { /* Preserve the write failure. */ }
335
+ descriptor = undefined;
336
+ fs.rmSync(file, { force: true });
337
+ }
338
+ throw error;
339
+ }
340
+ finally {
341
+ if (descriptor !== undefined)
342
+ fs.closeSync(descriptor);
343
+ }
344
+ }
345
+ async function runForSession(input) {
346
+ if (input.signal?.aborted)
347
+ throw new Error('browser_cancelled');
348
+ validateBrowserActionInput(input);
349
+ const url = input.localOnly ? localBrowserUrl(input.url) : browserUrl(input.url);
350
+ const width = input.width ?? 1440;
351
+ const height = input.height ?? 900;
352
+ let session = browserSessions.get(input.browserSessionId);
353
+ if (session && (session.localOnly !== (input.localOnly === true) || !session.browser.isConnected()
354
+ || session.context.pages().every(page => page.isClosed())
355
+ || Date.now() - session.lastUsedAt >= BROWSER_SESSION_IDLE_MS)) {
356
+ await closeSession(input.browserSessionId);
357
+ session = undefined;
358
+ }
359
+ if (!session && (INTERACTIVE_ACTIONS.has(input.action) || input.action === 'wait_for'))
360
+ throw new Error('browser_session_missing');
361
+ const created = !session;
362
+ if (!session)
363
+ session = await createSession(input.browserSessionId, url, input.localOnly === true, width, height, input.signal, input.onActionAttempt);
364
+ try {
365
+ setNetworkLease(input.browserSessionId, session, input.networkAccessExpiresAt ?? null);
366
+ }
367
+ catch (error) {
368
+ await closeSession(input.browserSessionId);
369
+ throw error;
370
+ }
371
+ if (input.signal?.aborted) {
372
+ await closeSession(input.browserSessionId);
373
+ throw new Error('browser_cancelled');
374
+ }
375
+ const onAbort = () => { void closeSession(input.browserSessionId); };
376
+ input.signal?.addEventListener('abort', onAbort, { once: true });
377
+ session.active = true;
378
+ try {
379
+ if (input.signal?.aborted)
380
+ throw new Error('browser_cancelled');
381
+ let page = activePage(session);
382
+ await page.setViewportSize({ width, height });
383
+ if (input.action === 'navigate' && !created) {
384
+ input.onActionAttempt?.();
385
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
386
+ }
66
387
  (input.localOnly ? localBrowserUrl : browserUrl)(page.url());
67
- const target = input.selector ? page.locator(input.selector).first() : page.locator('body');
68
- const dom = (await target.innerText({ timeout: 10_000 })).slice(0, 30_000);
388
+ const actionPage = page;
389
+ const target = input.selector ? page.locator(input.selector) : page.locator('body');
390
+ if (FORM_ACTIONS.has(input.action)) {
391
+ if (await target.count() > 1)
392
+ throw new Error('browser_selector_ambiguous');
393
+ try {
394
+ await target.first().waitFor({ state: 'visible', timeout: 10_000 });
395
+ }
396
+ catch (error) {
397
+ const matchCount = await target.count();
398
+ if (matchCount === 0)
399
+ throw new Error('browser_selector_missing');
400
+ if (matchCount > 1)
401
+ throw new Error('browser_selector_ambiguous');
402
+ throw error;
403
+ }
404
+ const matchCount = await target.count();
405
+ if (matchCount !== 1)
406
+ throw new Error(matchCount === 0
407
+ ? 'browser_selector_missing' : 'browser_selector_ambiguous');
408
+ if (input.action === 'fill')
409
+ await guardSecretFill(page, input.selector);
410
+ const popup = input.action === 'click' || input.action === 'press'
411
+ ? actionPage.waitForEvent('popup', { timeout: 750 }).catch(() => undefined)
412
+ : Promise.resolve(undefined);
413
+ input.onActionAttempt?.();
414
+ if (input.action === 'click') {
415
+ await target.click({ timeout: 10_000 });
416
+ }
417
+ else if (input.action === 'fill')
418
+ await target.fill(input.value, { timeout: 10_000 });
419
+ else if (input.action === 'check') {
420
+ if (input.checked)
421
+ await target.check({ timeout: 10_000 });
422
+ else
423
+ await target.uncheck({ timeout: 10_000 });
424
+ }
425
+ else if (input.action === 'select')
426
+ await target.selectOption(input.value, { timeout: 10_000 });
427
+ else
428
+ await target.press(input.key, { timeout: 10_000 });
429
+ const opened = await popup;
430
+ if (opened && !opened.isClosed())
431
+ session.page = opened;
432
+ page = activePage(session);
433
+ if (page !== actionPage)
434
+ await page.waitForLoadState('domcontentloaded', { timeout: 10_000 });
435
+ (input.localOnly ? localBrowserUrl : browserUrl)(page.url());
436
+ }
437
+ else if (input.action === 'scroll') {
438
+ input.onActionAttempt?.();
439
+ await page.mouse.wheel(0, input.deltaY);
440
+ }
441
+ else if (input.action === 'wait_for') {
442
+ await target.waitFor({ state: input.state, timeout: input.waitTimeoutMs });
443
+ }
444
+ const domTarget = INTERACTIVE_ACTIONS.has(input.action)
445
+ || input.action === 'wait_for' && input.state === 'hidden' ? page.locator('body') : target.first();
446
+ const bodyText = (await domTarget.innerText({ timeout: 10_000 })).slice(0, 25_000);
447
+ const dom = (bodyText + await semanticControls(page)).slice(0, 40_000);
448
+ const pageUrl = safePageUrl(page.url());
69
449
  if (input.action !== 'screenshot')
70
- return { dom };
450
+ return { dom, pageUrl };
71
451
  const root = fs.realpathSync(input.workspace);
72
452
  const privateDirectory = path.join(root, '.revo');
73
453
  fs.mkdirSync(privateDirectory, { recursive: true, mode: 0o700 });
@@ -78,15 +458,118 @@ export async function runBrowserAction(input) {
78
458
  if (fs.realpathSync(directory) !== directory)
79
459
  throw new Error('browser_output_outside_workspace');
80
460
  const screenshotPath = path.join(directory, `${randomUUID()}.png`);
81
- await (input.selector ? target : page).screenshot({ path: screenshotPath, timeout: 20_000 });
82
- if (fs.statSync(screenshotPath).size > 30 * 1024 * 1024) {
83
- fs.rmSync(screenshotPath, { force: true });
84
- throw new Error('browser_screenshot_too_large');
461
+ const capture = input.capture ?? 'viewport';
462
+ let bytes;
463
+ if (capture === 'full_page') {
464
+ const pageHeight = await page.locator('html').evaluate(element => element.scrollHeight);
465
+ if (pageHeight > 12_000)
466
+ throw new Error('browser_full_page_too_large');
467
+ }
468
+ if (capture === 'element') {
469
+ const box = await target.boundingBox();
470
+ if (!box || box.width * box.height > 8_000_000)
471
+ throw new Error('browser_element_too_large');
472
+ bytes = await target.first().screenshot({ timeout: 20_000 });
473
+ }
474
+ else if (capture === 'crop') {
475
+ const scroll = await page.evaluate(() => ({ x: window.scrollX, y: window.scrollY }));
476
+ bytes = await page.screenshot({ timeout: 20_000,
477
+ clip: { x: scroll.x + input.clip.x, y: scroll.y + input.clip.y,
478
+ width: input.clip.width, height: input.clip.height } });
85
479
  }
86
- return { dom, screenshotPath };
480
+ else {
481
+ bytes = await page.screenshot({ timeout: 20_000,
482
+ fullPage: capture === 'full_page' });
483
+ }
484
+ if (bytes.length > 30 * 1024 * 1024)
485
+ throw new Error('browser_screenshot_too_large');
486
+ writePrivateScreenshot(screenshotPath, bytes);
487
+ return { dom, pageUrl, screenshotPath };
87
488
  }
88
489
  finally {
89
490
  input.signal?.removeEventListener('abort', onAbort);
90
- await browser.close();
491
+ session.active = false;
492
+ session.lastUsedAt = Date.now();
493
+ if (input.networkAccessOnce)
494
+ await closeSession(input.browserSessionId);
495
+ }
496
+ }
497
+ export async function runBrowserAction(input) {
498
+ const previous = sessionQueues.get(input.browserSessionId) || Promise.resolve();
499
+ const task = previous.catch(() => undefined).then(() => runForSession(input));
500
+ sessionQueues.set(input.browserSessionId, task);
501
+ try {
502
+ return await task;
503
+ }
504
+ finally {
505
+ if (sessionQueues.get(input.browserSessionId) === task)
506
+ sessionQueues.delete(input.browserSessionId);
507
+ }
508
+ }
509
+ export async function fillBrowserSecret(input) {
510
+ if (!/^[a-f0-9]{64}$/u.test(input.browserSessionId)
511
+ || typeof input.selector !== 'string' || !input.selector.trim() || input.selector.length > 500
512
+ || typeof input.value !== 'string' || Buffer.byteLength(input.value) > 4_096
513
+ || !Number.isSafeInteger(input.expiresAt))
514
+ throw new Error('secure_input_invalid');
515
+ try {
516
+ if (new URL(browserUrl(input.origin)).origin !== input.origin)
517
+ throw new Error('secure_input_invalid');
518
+ }
519
+ catch {
520
+ throw new Error('secure_input_invalid');
521
+ }
522
+ const previous = sessionQueues.get(input.browserSessionId) || Promise.resolve();
523
+ const task = previous.catch(() => undefined).then(async () => {
524
+ if (input.isAuthorized?.() === false)
525
+ throw new Error('secure_input_session_missing');
526
+ if (input.expiresAt <= Date.now())
527
+ throw new Error('secure_input_invalid');
528
+ const session = browserSessions.get(input.browserSessionId);
529
+ if (!session || !session.browser.isConnected())
530
+ throw new Error('secure_input_session_missing');
531
+ if (session.networkAccessExpiresAt !== null && session.networkAccessExpiresAt <= Date.now()) {
532
+ await closeSession(input.browserSessionId);
533
+ throw new Error('secure_input_session_missing');
534
+ }
535
+ session.active = true;
536
+ try {
537
+ const page = activePage(session);
538
+ if (new URL(browserUrl(page.url())).origin !== input.origin)
539
+ throw new Error('secure_input_origin_changed');
540
+ const target = page.locator(input.selector);
541
+ const count = await target.count();
542
+ if (count !== 1)
543
+ throw new Error('secure_input_selector_missing');
544
+ await target.waitFor({ state: 'visible', timeout: 10_000 });
545
+ if (!await isSecretControl(page, input.selector))
546
+ throw new Error('secure_input_not_secret_control');
547
+ if (new URL(browserUrl(page.url())).origin !== input.origin || activePage(session) !== page)
548
+ throw new Error('secure_input_origin_changed');
549
+ if (input.isAuthorized?.() === false)
550
+ throw new Error('secure_input_session_missing');
551
+ if (session.networkAccessExpiresAt !== null && session.networkAccessExpiresAt <= Date.now())
552
+ throw new Error('secure_input_session_missing');
553
+ if (input.expiresAt <= Date.now())
554
+ throw new Error('secure_input_invalid');
555
+ try {
556
+ await target.fill(input.value, { timeout: 10_000 });
557
+ }
558
+ catch {
559
+ throw new Error('secure_input_fill_failed');
560
+ }
561
+ }
562
+ finally {
563
+ session.active = false;
564
+ session.lastUsedAt = Date.now();
565
+ }
566
+ });
567
+ sessionQueues.set(input.browserSessionId, task);
568
+ try {
569
+ await task;
570
+ }
571
+ finally {
572
+ if (sessionQueues.get(input.browserSessionId) === task)
573
+ sessionQueues.delete(input.browserSessionId);
91
574
  }
92
575
  }