@revoengine/cli 1.0.15 → 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 (49) hide show
  1. package/README.md +45 -9
  2. package/dist/src/cli.js +5 -1
  3. package/dist/src/client.d.ts +25 -3
  4. package/dist/src/client.js +67 -2
  5. package/dist/src/commands/component.js +1 -0
  6. package/dist/src/commands/index.d.ts +1 -0
  7. package/dist/src/commands/index.js +1 -0
  8. package/dist/src/commands/migrate.js +12 -2
  9. package/dist/src/commands/service-accounts.d.ts +2 -0
  10. package/dist/src/commands/service-accounts.js +149 -0
  11. package/dist/src/commands/terminal-browser.d.ts +29 -2
  12. package/dist/src/commands/terminal-browser.js +144 -35
  13. package/dist/src/commands/terminal-file.d.ts +21 -0
  14. package/dist/src/commands/terminal-file.js +160 -0
  15. package/dist/src/commands/terminal-operational-log.js +2 -2
  16. package/dist/src/commands/terminal-policy.d.ts +5 -2
  17. package/dist/src/commands/terminal-policy.js +10 -4
  18. package/dist/src/commands/terminal-reconnect-grace.js +1 -1
  19. package/dist/src/commands/terminal-sandbox.js +7 -0
  20. package/dist/src/commands/terminal-secure-browser.d.ts +1 -0
  21. package/dist/src/commands/terminal-secure-browser.js +2 -1
  22. package/dist/src/commands/terminal-service.js +4 -4
  23. package/dist/src/commands/terminal.d.ts +12 -0
  24. package/dist/src/commands/terminal.js +134 -45
  25. package/dist/src/component-lock.d.ts +4 -0
  26. package/dist/src/component-lock.js +21 -2
  27. package/dist/src/metadata-backfill.js +50 -1
  28. package/dist/src/migration.d.ts +10 -2
  29. package/dist/src/migration.js +159 -68
  30. package/dist/src/resource-inventory.d.ts +3 -2
  31. package/dist/src/resource-inventory.js +6 -1
  32. package/dist/src/resource-syncs/account-principal.d.ts +22 -0
  33. package/dist/src/resource-syncs/account-principal.js +86 -0
  34. package/dist/src/resource-syncs/group-sync.d.ts +10 -0
  35. package/dist/src/resource-syncs/group-sync.js +92 -20
  36. package/dist/src/resource-syncs/identity-migration.d.ts +19 -0
  37. package/dist/src/resource-syncs/identity-migration.js +108 -0
  38. package/dist/src/resource-syncs/job-template-sync.d.ts +4 -0
  39. package/dist/src/resource-syncs/job-template-sync.js +55 -12
  40. package/dist/src/resource-syncs/service-account-sync.d.ts +98 -0
  41. package/dist/src/resource-syncs/service-account-sync.js +620 -0
  42. package/dist/src/sync-output.js +3 -0
  43. package/dist/src/tracked-resources.d.ts +1 -1
  44. package/dist/src/tracked-resources.js +5 -1
  45. package/dist/src/types.d.ts +12 -0
  46. package/dist/src/ui.js +4 -1
  47. package/dist/src/workspace-diff.d.ts +1 -0
  48. package/dist/src/workspace-diff.js +4 -1
  49. package/package.json +2 -2
@@ -2,7 +2,8 @@ import fs from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { randomUUID } from 'node:crypto';
4
4
  const MAX_BROWSER_SESSIONS = 4;
5
- const BROWSER_SESSION_IDLE_MS = 10 * 60_000;
5
+ const BROWSER_SESSION_IDLE_MS = 60 * 60_000;
6
+ const MAX_BROWSER_TABS = 16;
6
7
  const browserSessions = new Map();
7
8
  const creatingSessions = new Set();
8
9
  const sessionQueues = new Map();
@@ -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)
@@ -148,12 +167,19 @@ export async function closeBrowserSessions() {
148
167
  cleanupTimer = undefined;
149
168
  await Promise.all([...browserSessions.keys()].map(id => closeSession(id)));
150
169
  }
151
- export async function reconcileBrowserSessions(networkMode) {
170
+ export async function reconcileBrowserSessions(networkMode, policyGrantRevision) {
152
171
  permanentNetworkMode = networkMode;
153
172
  const now = Date.now();
154
173
  const closed = [...browserSessions].filter(([id, session]) => {
155
174
  const permanent = session.localOnly ? networkMode !== 'restricted' : networkMode === 'external';
156
- if (!permanent && (session.networkAccessExpiresAt === null || session.networkAccessExpiresAt <= now))
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))
157
183
  return true;
158
184
  setNetworkLease(id, session, session.networkAccessExpiresAt);
159
185
  return false;
@@ -161,8 +187,17 @@ export async function reconcileBrowserSessions(networkMode) {
161
187
  await Promise.all(closed.map(id => closeSession(id)));
162
188
  return closed.length;
163
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()]; }
164
199
  export function hasBrowserSessions() { return browserSessions.size > 0; }
165
- async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt) {
200
+ async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt, actionTimeoutMs) {
166
201
  await pruneIdleSessions();
167
202
  if (browserSessions.size + creatingSessions.size >= MAX_BROWSER_SESSIONS)
168
203
  throw new Error('browser_session_limit');
@@ -224,9 +259,11 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
224
259
  'WebTransport', 'Worker', 'SharedWorker'].every(name => typeof Reflect.get(globalThis, name) === 'undefined'
225
260
  && Object.getOwnPropertyDescriptor(globalThis, name)?.configurable === false)))
226
261
  throw new Error('browser_local_network_guard_unavailable');
227
- const session = { browser, context, page, localOnly,
262
+ const session = { browser, context, page, localOnly, tabs: new Map(),
228
263
  lastUsedAt: Date.now(), active: false, networkAccessExpiresAt: null };
264
+ registerTab(session, page);
229
265
  context.on('page', opened => {
266
+ registerTab(session, opened);
230
267
  session.page = opened;
231
268
  opened.on('close', () => {
232
269
  if (session.page !== opened)
@@ -242,7 +279,7 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
242
279
  await opened.waitForLoadState('domcontentloaded', { timeout: 5_000 }).catch(() => undefined);
243
280
  }).catch(() => undefined);
244
281
  onNavigationAttempt?.();
245
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
282
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: actionTimeoutMs ?? 30_000 });
246
283
  (localOnly ? localBrowserUrl : browserUrl)(page.url());
247
284
  const hasContent = await page.evaluate(() => Boolean(document.body?.innerText.trim()
248
285
  || document.querySelector('input, textarea, select, button, a[href], [role], [contenteditable]')));
@@ -265,6 +302,30 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
265
302
  creatingSessions.delete(id);
266
303
  }
267
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
+ }
268
329
  function activePage(session) {
269
330
  if (!session.page.isClosed())
270
331
  return session.page;
@@ -346,27 +407,43 @@ async function runForSession(input) {
346
407
  if (input.signal?.aborted)
347
408
  throw new Error('browser_cancelled');
348
409
  validateBrowserActionInput(input);
349
- 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);
350
411
  const width = input.width ?? 1440;
351
412
  const height = input.height ?? 900;
352
413
  let session = browserSessions.get(input.browserSessionId);
353
- 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()
354
415
  || session.context.pages().every(page => page.isClosed())
355
416
  || Date.now() - session.lastUsedAt >= BROWSER_SESSION_IDLE_MS)) {
356
417
  await closeSession(input.browserSessionId);
357
418
  session = undefined;
358
419
  }
359
- 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'))
360
430
  throw new Error('browser_session_missing');
361
431
  const created = !session;
362
432
  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;
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
+ }
370
447
  }
371
448
  if (input.signal?.aborted) {
372
449
  await closeSession(input.browserSessionId);
@@ -378,11 +455,38 @@ async function runForSession(input) {
378
455
  try {
379
456
  if (input.signal?.aborted)
380
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
+ }
381
484
  let page = activePage(session);
485
+ await page.bringToFront();
382
486
  await page.setViewportSize({ width, height });
383
487
  if (input.action === 'navigate' && !created) {
384
488
  input.onActionAttempt?.();
385
- await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });
489
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: input.actionTimeoutMs ?? 30_000 });
386
490
  }
387
491
  (input.localOnly ? localBrowserUrl : browserUrl)(page.url());
388
492
  const actionPage = page;
@@ -391,7 +495,7 @@ async function runForSession(input) {
391
495
  if (await target.count() > 1)
392
496
  throw new Error('browser_selector_ambiguous');
393
497
  try {
394
- await target.first().waitFor({ state: 'visible', timeout: 10_000 });
498
+ await target.first().waitFor({ state: 'visible', timeout: input.actionTimeoutMs ?? 10_000 });
395
499
  }
396
500
  catch (error) {
397
501
  const matchCount = await target.count();
@@ -412,26 +516,26 @@ async function runForSession(input) {
412
516
  : Promise.resolve(undefined);
413
517
  input.onActionAttempt?.();
414
518
  if (input.action === 'click') {
415
- await target.click({ timeout: 10_000 });
519
+ await target.click({ timeout: input.actionTimeoutMs ?? 10_000 });
416
520
  }
417
521
  else if (input.action === 'fill')
418
- await target.fill(input.value, { timeout: 10_000 });
522
+ await target.fill(input.value, { timeout: input.actionTimeoutMs ?? 10_000 });
419
523
  else if (input.action === 'check') {
420
524
  if (input.checked)
421
- await target.check({ timeout: 10_000 });
525
+ await target.check({ timeout: input.actionTimeoutMs ?? 10_000 });
422
526
  else
423
- await target.uncheck({ timeout: 10_000 });
527
+ await target.uncheck({ timeout: input.actionTimeoutMs ?? 10_000 });
424
528
  }
425
529
  else if (input.action === 'select')
426
- await target.selectOption(input.value, { timeout: 10_000 });
530
+ await target.selectOption(input.value, { timeout: input.actionTimeoutMs ?? 10_000 });
427
531
  else
428
- await target.press(input.key, { timeout: 10_000 });
532
+ await target.press(input.key, { timeout: input.actionTimeoutMs ?? 10_000 });
429
533
  const opened = await popup;
430
534
  if (opened && !opened.isClosed())
431
535
  session.page = opened;
432
536
  page = activePage(session);
433
537
  if (page !== actionPage)
434
- await page.waitForLoadState('domcontentloaded', { timeout: 10_000 });
538
+ await page.waitForLoadState('domcontentloaded', { timeout: input.actionTimeoutMs ?? 10_000 });
435
539
  (input.localOnly ? localBrowserUrl : browserUrl)(page.url());
436
540
  }
437
541
  else if (input.action === 'scroll') {
@@ -439,15 +543,16 @@ async function runForSession(input) {
439
543
  await page.mouse.wheel(0, input.deltaY);
440
544
  }
441
545
  else if (input.action === 'wait_for') {
442
- 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) });
443
547
  }
444
548
  const domTarget = INTERACTIVE_ACTIONS.has(input.action)
445
549
  || 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);
550
+ const bodyText = (await domTarget.innerText({ timeout: input.actionTimeoutMs ?? 10_000 })).slice(0, 25_000);
447
551
  const dom = (bodyText + await semanticControls(page)).slice(0, 40_000);
448
552
  const pageUrl = safePageUrl(page.url());
553
+ const inventory = await describeSession(input.browserSessionId, session, created);
449
554
  if (input.action !== 'screenshot')
450
- return { dom, pageUrl };
555
+ return { dom, ...inventory, pageUrl };
451
556
  const root = fs.realpathSync(input.workspace);
452
557
  const privateDirectory = path.join(root, '.revo');
453
558
  fs.mkdirSync(privateDirectory, { recursive: true, mode: 0o700 });
@@ -469,22 +574,22 @@ async function runForSession(input) {
469
574
  const box = await target.boundingBox();
470
575
  if (!box || box.width * box.height > 8_000_000)
471
576
  throw new Error('browser_element_too_large');
472
- bytes = await target.first().screenshot({ timeout: 20_000 });
577
+ bytes = await target.first().screenshot({ timeout: input.actionTimeoutMs ?? 20_000 });
473
578
  }
474
579
  else if (capture === 'crop') {
475
580
  const scroll = await page.evaluate(() => ({ x: window.scrollX, y: window.scrollY }));
476
- bytes = await page.screenshot({ timeout: 20_000,
581
+ bytes = await page.screenshot({ timeout: input.actionTimeoutMs ?? 20_000,
477
582
  clip: { x: scroll.x + input.clip.x, y: scroll.y + input.clip.y,
478
583
  width: input.clip.width, height: input.clip.height } });
479
584
  }
480
585
  else {
481
- bytes = await page.screenshot({ timeout: 20_000,
586
+ bytes = await page.screenshot({ timeout: input.actionTimeoutMs ?? 20_000,
482
587
  fullPage: capture === 'full_page' });
483
588
  }
484
589
  if (bytes.length > 30 * 1024 * 1024)
485
590
  throw new Error('browser_screenshot_too_large');
486
591
  writePrivateScreenshot(screenshotPath, bytes);
487
- return { dom, pageUrl, screenshotPath };
592
+ return { dom, ...inventory, pageUrl, screenshotPath };
488
593
  }
489
594
  finally {
490
595
  input.signal?.removeEventListener('abort', onAbort);
@@ -535,6 +640,8 @@ export async function fillBrowserSecret(input) {
535
640
  session.active = true;
536
641
  try {
537
642
  const page = activePage(session);
643
+ if (input.browserTabId && session.tabs.get(input.browserTabId) !== page)
644
+ throw new Error('secure_input_session_missing');
538
645
  if (new URL(browserUrl(page.url())).origin !== input.origin)
539
646
  throw new Error('secure_input_origin_changed');
540
647
  const target = page.locator(input.selector);
@@ -546,6 +653,8 @@ export async function fillBrowserSecret(input) {
546
653
  throw new Error('secure_input_not_secret_control');
547
654
  if (new URL(browserUrl(page.url())).origin !== input.origin || activePage(session) !== page)
548
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');
549
658
  if (input.isAuthorized?.() === false)
550
659
  throw new Error('secure_input_session_missing');
551
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>;
@@ -0,0 +1,160 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import https from 'node:https';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { pipeline } from 'node:stream/promises';
6
+ const HEADERS = new Set(['content-type', 'content-length', 'content-range', 'range', 'if-match', 'if-none-match',
7
+ 'x-goog-if-generation-match', 'x-goog-if-metageneration-match']);
8
+ /** URLs and headers are credentials. Never include them in errors or operational logs. */
9
+ export function validateFileTransfer(value) {
10
+ const item = value;
11
+ if (!item || typeof item.path !== 'string' || !path.isAbsolute(item.path) || item.path.includes('\0')
12
+ || item.path.length > 2048 || typeof item.url !== 'string' || item.url.length > 16_384
13
+ || typeof item.overwrite !== 'boolean' || !Array.isArray(item.headers) || item.headers.length > 16
14
+ || [item.offset, item.length].some(number => number !== null && (!Number.isSafeInteger(number) || number < 0)))
15
+ return false;
16
+ try {
17
+ const url = new URL(item.url);
18
+ if (url.protocol !== 'https:' || url.username || url.password || url.port && url.port !== '443'
19
+ || !(url.hostname === 'storage.googleapis.com' || url.hostname.endsWith('.storage.googleapis.com')))
20
+ return false;
21
+ }
22
+ catch {
23
+ return false;
24
+ }
25
+ return item.headers.every(header => header && typeof header.name === 'string' && HEADERS.has(header.name.toLowerCase())
26
+ && typeof header.value === 'string' && header.value.length <= 2048 && !/[\r\n]/u.test(header.value))
27
+ && new Set(item.headers.map(header => header.name.toLowerCase())).size === item.headers.length;
28
+ }
29
+ function inside(root, file) {
30
+ const relative = path.relative(root, file);
31
+ return !!relative && !relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative);
32
+ }
33
+ function transferError(status) {
34
+ return new Error(status ? `file_transfer_http_${status}` : 'file_transfer_transport_failed');
35
+ }
36
+ async function request(url, method, headers, signal, source) {
37
+ let written = Promise.resolve();
38
+ const response = new Promise((resolve, reject) => {
39
+ const req = https.request(url, { method, headers, signal }, resolve);
40
+ req.setTimeout(90_000, () => req.destroy(new Error('file_transfer_idle_timeout')));
41
+ req.on('error', () => reject(transferError()));
42
+ if (source)
43
+ written = pipeline(source, req, { signal }).catch(() => { throw transferError(); });
44
+ else
45
+ req.end();
46
+ });
47
+ // Observe both promises immediately, even when a server rejects a request before reading its body.
48
+ const [received] = await Promise.all([response, written]);
49
+ return received;
50
+ }
51
+ function drain(response) { response.on('error', () => undefined); response.resume(); }
52
+ function nextOffset(response) {
53
+ const range = /^bytes=0-(\d+)$/u.exec(String(response.headers.range || ''));
54
+ return range ? Number(range[1]) + 1 : 0;
55
+ }
56
+ export async function transferWorkspaceFile(workspace, operation, transfer, signal) {
57
+ if (!validateFileTransfer(transfer))
58
+ throw new Error('invalid_file_transfer');
59
+ if (operation === 'download_file' && (transfer.offset !== null || transfer.length !== null))
60
+ throw new Error('invalid_file_transfer_range');
61
+ if (signal.aborted)
62
+ throw new Error('file_transfer_cancelled');
63
+ const root = await fs.promises.realpath(workspace);
64
+ const parent = await fs.promises.realpath(path.dirname(transfer.path));
65
+ const target = path.join(parent, path.basename(transfer.path));
66
+ if (!inside(root, target) || path.resolve(transfer.path) !== target)
67
+ throw new Error('file_transfer_outside_workspace');
68
+ const headers = Object.fromEntries(transfer.headers.map(header => [header.name.toLowerCase(), header.value]));
69
+ if (operation === 'upload_file') {
70
+ const file = await fs.promises.open(target, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW);
71
+ try {
72
+ const stat = await file.stat();
73
+ if (!stat.isFile() || !Number.isSafeInteger(stat.size))
74
+ throw new Error('file_transfer_not_regular');
75
+ const resumable = new URL(transfer.url).searchParams.has('upload_id');
76
+ let offset = transfer.offset ?? 0;
77
+ if (resumable && transfer.offset === null) {
78
+ const status = await request(transfer.url, 'PUT', { ...headers, 'content-length': '0',
79
+ 'content-range': `bytes */${stat.size}` }, signal);
80
+ if ([200, 201].includes(status.statusCode || 0)) {
81
+ drain(status);
82
+ return { bytes: 0, complete: true, status: status.statusCode, nextOffset: stat.size };
83
+ }
84
+ if (status.statusCode !== 308) {
85
+ drain(status);
86
+ throw transferError(status.statusCode);
87
+ }
88
+ offset = nextOffset(status);
89
+ drain(status);
90
+ }
91
+ const length = transfer.length ?? stat.size - offset;
92
+ if (offset > stat.size || length > stat.size - offset || !resumable && (offset !== 0 || length !== stat.size))
93
+ throw new Error('invalid_file_transfer_range');
94
+ if (resumable && offset + length < stat.size && (!length || length % (256 * 1024)))
95
+ throw new Error('invalid_file_transfer_chunk_size');
96
+ if (headers['content-length'] !== undefined && Number(headers['content-length']) !== length)
97
+ throw new Error('invalid_file_transfer_range');
98
+ headers['content-length'] = String(length);
99
+ if (resumable)
100
+ headers['content-range'] = stat.size ? `bytes ${offset}-${offset + length - 1}/${stat.size}` : 'bytes */0';
101
+ else if (headers['content-range'])
102
+ throw new Error('invalid_file_transfer_range');
103
+ const source = length ? file.createReadStream({ start: offset, end: offset + length - 1, autoClose: false }) : undefined;
104
+ const response = await request(transfer.url, 'PUT', headers, signal, source);
105
+ const status = response.statusCode || 0;
106
+ if (![200, 201, 204, 308].includes(status) || status === 308 && !resumable) {
107
+ source?.destroy();
108
+ drain(response);
109
+ throw transferError(status);
110
+ }
111
+ const changed = await file.stat();
112
+ if (changed.size !== stat.size || changed.mtimeMs !== stat.mtimeMs) {
113
+ drain(response);
114
+ throw new Error('file_transfer_source_changed');
115
+ }
116
+ const result = { bytes: length, complete: status !== 308, status,
117
+ ...(status === 308 ? { nextOffset: nextOffset(response) } : { nextOffset: offset + length }),
118
+ ...(typeof response.headers.etag === 'string' ? { etag: response.headers.etag } : {}) };
119
+ drain(response);
120
+ return result;
121
+ }
122
+ finally {
123
+ await file.close();
124
+ }
125
+ }
126
+ if (transfer.offset !== null || transfer.length !== null || headers.range)
127
+ throw new Error('file_download_range_not_supported');
128
+ const temporary = path.join(parent, `.revo-transfer-${randomUUID()}.part`);
129
+ try {
130
+ const existing = await fs.promises.lstat(target).catch(error => {
131
+ if (error.code === 'ENOENT')
132
+ return null;
133
+ throw error;
134
+ });
135
+ if (existing && (!transfer.overwrite || !existing.isFile() || existing.isSymbolicLink()))
136
+ throw new Error('file_transfer_target_exists');
137
+ const response = await request(transfer.url, 'GET', headers, signal);
138
+ if (response.statusCode !== 200) {
139
+ drain(response);
140
+ throw transferError(response.statusCode);
141
+ }
142
+ await pipeline(response, fs.createWriteStream(temporary, { flags: 'wx', mode: 0o600 }), { signal });
143
+ const stat = await fs.promises.stat(temporary);
144
+ if (response.headers['content-length'] !== undefined && Number(response.headers['content-length']) !== stat.size)
145
+ throw new Error('file_transfer_incomplete');
146
+ if (await fs.promises.realpath(path.dirname(transfer.path)) !== parent)
147
+ throw new Error('file_transfer_outside_workspace');
148
+ if (transfer.overwrite)
149
+ await fs.promises.rename(temporary, target);
150
+ else {
151
+ await fs.promises.link(temporary, target);
152
+ await fs.promises.unlink(temporary);
153
+ }
154
+ return { bytes: stat.size, complete: true, status: 200,
155
+ ...(typeof response.headers.etag === 'string' ? { etag: response.headers.etag } : {}) };
156
+ }
157
+ finally {
158
+ await fs.promises.rm(temporary, { force: true });
159
+ }
160
+ }
@@ -5,8 +5,8 @@ import { gunzipSync, gzipSync } from 'node:zlib';
5
5
  const ARCHIVE_RETENTION_MS = 30 * 24 * 60 * 60 * 1_000;
6
6
  const SAFE_ATOM = /^[A-Za-z0-9_.:-]{1,120}$/u;
7
7
  const DETAIL_KEYS = new Set(['operation', 'sandbox', 'reason', 'errorCode', 'browserAction',
8
- 'exitCode', 'images', 'screenshot', 'executed', 'timedOut', 'truncated', 'activeExecutions',
9
- 'resumedExecutions', 'bytes', 'close', 'code', 'policyViolation', 'milliseconds']);
8
+ 'exitCode', 'signal', 'images', 'screenshot', 'executed', 'timedOut', 'truncated', 'activeExecutions',
9
+ 'resumedExecutions', 'stoppedExecutions', 'closedBrowserSessions', 'bytes', 'close', 'code', 'policyViolation', 'milliseconds']);
10
10
  function atom(value) {
11
11
  return typeof value === 'string' && SAFE_ATOM.test(value) ? value : '-';
12
12
  }
@@ -7,6 +7,8 @@ export type TerminalExecutePolicy = {
7
7
  commandAccessExpiresAt: number | null;
8
8
  networkAccessExpiresAt: number | null;
9
9
  networkAccessOnce?: boolean;
10
+ commandAccessForThread?: boolean;
11
+ networkAccessForThread?: boolean;
10
12
  policyGrantRevision: number;
11
13
  };
12
14
  export type TerminalGrantPolicy = {
@@ -16,14 +18,15 @@ export type TerminalGrantPolicy = {
16
18
  export declare function executionAllowedByGrant(policy: TerminalExecutePolicy, grant: TerminalGrantPolicy, now?: number): boolean;
17
19
  export declare function remainingPolicyDeadline(policy: TerminalExecutePolicy, grant: TerminalGrantPolicy): number | null;
18
20
  type PolicyFrame = Partial<TerminalExecutePolicy> & {
19
- operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image';
21
+ operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image' | 'upload_file' | 'download_file';
20
22
  sandbox?: TerminalSandbox;
23
+ browserAction?: string;
21
24
  browserLocalOnly?: boolean;
22
25
  };
23
26
  /** The connected Realtime process must send a complete, current policy for every execution. */
24
27
  export declare function validateExecutePolicy(frame: PolicyFrame, now?: number): string | null;
25
28
  export declare function executionPolicyDeadline(frame: TerminalExecutePolicy & {
26
- operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image';
29
+ operation?: 'shell' | 'apply_patch' | 'browser' | 'save_image' | 'upload_file' | 'download_file';
27
30
  sandbox?: TerminalSandbox;
28
31
  }): number | null;
29
32
  export {};
@@ -2,9 +2,9 @@ export function executionAllowedByGrant(policy, grant, now = Date.now()) {
2
2
  const networkRank = { none: 0, local: 1, full: 2 };
3
3
  const permanentNetwork = grant.networkMode === 'external' ? 2 : grant.networkMode === 'sandbox' ? 1 : 0;
4
4
  const commandAllowed = policy.commandAccess !== 'host' || grant.mode === 'full'
5
- || policy.commandAccessExpiresAt !== null && policy.commandAccessExpiresAt > now;
5
+ || policy.commandAccessForThread === true || policy.commandAccessExpiresAt !== null && policy.commandAccessExpiresAt > now;
6
6
  const networkAllowed = networkRank[policy.networkAccess] <= permanentNetwork
7
- || policy.networkAccessExpiresAt !== null && policy.networkAccessExpiresAt > now;
7
+ || policy.networkAccessForThread === true || policy.networkAccessExpiresAt !== null && policy.networkAccessExpiresAt > now;
8
8
  return commandAllowed && networkAllowed;
9
9
  }
10
10
  export function remainingPolicyDeadline(policy, grant) {
@@ -28,6 +28,12 @@ export function validateExecutePolicy(frame, now = Date.now()) {
28
28
  || !validDeadline(frame.networkAccessExpiresAt)
29
29
  || !Number.isSafeInteger(frame.policyGrantRevision) || frame.policyGrantRevision < 0)
30
30
  return 'terminal_policy_v2_required';
31
+ if (frame.commandAccessForThread !== undefined && typeof frame.commandAccessForThread !== 'boolean'
32
+ || frame.networkAccessForThread !== undefined && typeof frame.networkAccessForThread !== 'boolean'
33
+ || frame.commandAccessForThread === true && (frame.commandAccess !== 'host' || frame.commandAccessExpiresAt !== null)
34
+ || frame.networkAccessForThread === true && (frame.networkAccess === 'none' || frame.networkAccessExpiresAt !== null
35
+ || frame.networkAccessOnce === true))
36
+ return 'terminal_policy_invalid';
31
37
  if (frame.commandAccessExpiresAt !== null && frame.commandAccessExpiresAt <= now
32
38
  || frame.networkAccessExpiresAt !== null && frame.networkAccessExpiresAt <= now)
33
39
  return 'terminal_policy_expired';
@@ -42,7 +48,7 @@ export function validateExecutePolicy(frame, now = Date.now()) {
42
48
  if (frame.operation === 'apply_patch' && frame.networkAccess !== 'none')
43
49
  return 'terminal_policy_invalid';
44
50
  if (frame.operation === 'browser') {
45
- if (frame.networkAccess === 'none')
51
+ if (frame.networkAccess === 'none' && !['tabs', 'close', 'close_tab'].includes(frame.browserAction || ''))
46
52
  return 'terminal_network_disabled';
47
53
  if (frame.browserLocalOnly !== (frame.networkAccess === 'local'))
48
54
  return 'terminal_policy_invalid';
@@ -51,7 +57,7 @@ export function validateExecutePolicy(frame, now = Date.now()) {
51
57
  || frame.networkAccessOnce === true && (frame.operation !== 'browser'
52
58
  || frame.networkAccessExpiresAt === null))
53
59
  return 'terminal_policy_invalid';
54
- if (frame.operation === 'save_image' && frame.networkAccess !== 'full')
60
+ if (['save_image', 'upload_file', 'download_file'].includes(frame.operation || '') && frame.networkAccess !== 'full')
55
61
  return 'terminal_network_disabled';
56
62
  return null;
57
63
  }
@@ -5,7 +5,7 @@ export class TerminalReconnectGrace {
5
5
  delayMs;
6
6
  scheduleTimer;
7
7
  clearTimer;
8
- constructor(onExpire, delayMs = 120_000, scheduleTimer = setTimeout, clearTimer = clearTimeout) {
8
+ constructor(onExpire, delayMs = 180_000, scheduleTimer = setTimeout, clearTimer = clearTimeout) {
9
9
  this.onExpire = onExpire;
10
10
  this.delayMs = delayMs;
11
11
  this.scheduleTimer = scheduleTimer;
@@ -67,6 +67,13 @@ export function sandboxCommand(workspace, workdir, command, sandbox, platform =
67
67
  const profile = [
68
68
  '(version 1)', '(allow default)',
69
69
  ...(sandbox === 'workspace' ? ['(deny network*)',
70
+ // Build workers need local IPC. Keep it inside this command's private scratch;
71
+ // sockets in the workspace, other commands and host services remain denied.
72
+ ...(scratchDir ? [
73
+ `(allow network-bind (local unix-socket (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))})))`,
74
+ `(allow network-inbound (local unix-socket (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))})))`,
75
+ `(allow network-outbound (remote unix-socket (subpath ${seatbeltLiteral(fs.realpathSync(scratchDir))})))`,
76
+ ] : []),
70
77
  ...(networkAccess !== 'none' ? ['(allow network-outbound (remote ip "localhost:*"))',
71
78
  '(allow network-inbound (local ip "localhost:*"))'] : [])] : []),
72
79
  '(deny file-write*)',
@@ -5,6 +5,7 @@ export type SecureBrowserInputEnvelope = {
5
5
  threadId: string;
6
6
  agentTerminalId: string;
7
7
  browserSessionId: string;
8
+ browserTabId?: string;
8
9
  origin: string;
9
10
  selector: string;
10
11
  connectionId: string;