@revoengine/cli 1.0.31 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +68 -17
  2. package/dist/src/automation-contract.generated.d.ts +55 -21
  3. package/dist/src/automation-contract.generated.js +67 -25
  4. package/dist/src/client.d.ts +32 -2
  5. package/dist/src/client.js +54 -13
  6. package/dist/src/commands/database-tables.js +10 -3
  7. package/dist/src/commands/migrate.js +2 -0
  8. package/dist/src/commands/terminal-browser-central-profile.d.ts +65 -0
  9. package/dist/src/commands/terminal-browser-central-profile.js +203 -0
  10. package/dist/src/commands/terminal-browser-human-input.d.ts +3 -1
  11. package/dist/src/commands/terminal-browser-human-input.js +3 -1
  12. package/dist/src/commands/terminal-browser-interaction.js +1 -1
  13. package/dist/src/commands/terminal-browser-live-protocol.d.ts +34 -2
  14. package/dist/src/commands/terminal-browser-live-protocol.js +28 -12
  15. package/dist/src/commands/terminal-browser-live-transport.d.ts +1 -0
  16. package/dist/src/commands/terminal-browser-live-transport.js +9 -5
  17. package/dist/src/commands/terminal-browser-live.d.ts +24 -3
  18. package/dist/src/commands/terminal-browser-live.js +199 -30
  19. package/dist/src/commands/terminal-browser-page-input.d.ts +4 -1
  20. package/dist/src/commands/terminal-browser-page-input.js +46 -1
  21. package/dist/src/commands/terminal-browser-profile-crypto.d.ts +30 -0
  22. package/dist/src/commands/terminal-browser-profile-crypto.js +101 -0
  23. package/dist/src/commands/terminal-browser-profile-import-runner.d.ts +31 -0
  24. package/dist/src/commands/terminal-browser-profile-import-runner.js +112 -0
  25. package/dist/src/commands/terminal-browser-profile-import.d.ts +28 -0
  26. package/dist/src/commands/terminal-browser-profile-import.js +125 -0
  27. package/dist/src/commands/terminal-browser-profile-import.protocol.d.ts +50 -0
  28. package/dist/src/commands/terminal-browser-profile-import.protocol.js +52 -0
  29. package/dist/src/commands/terminal-browser-profile-preferences.d.ts +1 -0
  30. package/dist/src/commands/terminal-browser-profile-preferences.js +16 -0
  31. package/dist/src/commands/terminal-browser-profile-sync.d.ts +14 -0
  32. package/dist/src/commands/terminal-browser-profile-sync.js +169 -0
  33. package/dist/src/commands/terminal-browser-profile-sync.protocol.d.ts +50 -0
  34. package/dist/src/commands/terminal-browser-profile-sync.protocol.js +19 -0
  35. package/dist/src/commands/terminal-browser-profile.d.ts +10 -1
  36. package/dist/src/commands/terminal-browser-profile.js +30 -4
  37. package/dist/src/commands/terminal-browser-recording.d.ts +39 -0
  38. package/dist/src/commands/terminal-browser-recording.js +74 -0
  39. package/dist/src/commands/terminal-browser-recording.protocol.d.ts +49 -0
  40. package/dist/src/commands/terminal-browser-recording.protocol.js +16 -0
  41. package/dist/src/commands/terminal-browser.d.ts +14 -1
  42. package/dist/src/commands/terminal-browser.js +98 -33
  43. package/dist/src/commands/terminal-output-buffer.d.ts +18 -1
  44. package/dist/src/commands/terminal-output-buffer.js +95 -8
  45. package/dist/src/commands/terminal.d.ts +3 -1
  46. package/dist/src/commands/terminal.js +257 -54
  47. package/dist/src/resource-syncs/database-table-sync.d.ts +8 -1
  48. package/dist/src/resource-syncs/database-table-sync.js +34 -11
  49. package/dist/src/sync-output.d.ts +3 -3
  50. package/dist/src/ui.js +1 -0
  51. package/package.json +5 -5
@@ -6,7 +6,7 @@ import { browserProfileScopeId } from "./terminal-browser-profile.js";
6
6
  import { validBrowserInteraction } from "./terminal-browser-interaction.js";
7
7
  import { BrowserObservations } from "./terminal-browser-observation.js";
8
8
  import { BrowserLiveHandle, browserAuthPage } from "./terminal-browser-live.js";
9
- import { applyPageInteraction, clearSecretInputs, releasePageInput, pageHasSecretFocus, secretControlAttributes } from "./terminal-browser-page-input.js";
9
+ import { applyPageInteraction, clearSecretInputs, releasePageInput, describeFocusedField, pageHasSecretFocus, secretControlAttributes } from "./terminal-browser-page-input.js";
10
10
  const MAX_BROWSER_SESSIONS = 4;
11
11
  const BROWSER_SESSION_IDLE_MS = 60 * 60_000;
12
12
  const MAX_BROWSER_TABS = 16;
@@ -130,19 +130,21 @@ export function validateBrowserActionInput(input) {
130
130
  || input.clip.x + input.clip.width > width || input.clip.y + input.clip.height > height))
131
131
  throw new Error('invalid_browser_capture');
132
132
  }
133
- async function closeSession(id) {
133
+ async function closeSession(id, options = {}) {
134
134
  const session = browserSessions.get(id);
135
135
  if (!session)
136
136
  return;
137
137
  browserSessions.delete(id);
138
- session.live?.disconnect();
138
+ session.live?.close();
139
+ await session.live?.settled();
139
140
  if (session.networkLeaseTimer)
140
141
  clearTimeout(session.networkLeaseTimer);
141
142
  try {
142
143
  await session.browser.close().catch(() => undefined);
143
144
  }
144
145
  finally {
145
- session.authProfile?.release();
146
+ if (!options.retainProfileLease)
147
+ await session.authProfile?.release();
146
148
  }
147
149
  }
148
150
  async function checkpointProfile(session) {
@@ -150,7 +152,7 @@ async function checkpointProfile(session) {
150
152
  return;
151
153
  session.snapshotting = true;
152
154
  try {
153
- session.authProfile.save(await session.context.storageState({ indexedDB: true }));
155
+ await session.authProfile.save(await session.context.storageState({ indexedDB: true }));
154
156
  }
155
157
  finally {
156
158
  session.snapshotting = false;
@@ -240,39 +242,44 @@ export async function closeThreadBrowserSession(browserSessionId) {
240
242
  }
241
243
  export function browserSessionIds() { return [...browserSessions.keys()]; }
242
244
  export function hasBrowserSessions() { return browserSessions.size > 0; }
243
- async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt, actionTimeoutMs, authProfile) {
245
+ /** Revocation closes only this central context and never checkpoints its authentication. */
246
+ export async function revokeBrowserProfileSession(browserSessionId, profileId) {
247
+ if (browserSessions.get(browserSessionId)?.centralProfile?.id === profileId)
248
+ await closeSession(browserSessionId);
249
+ }
250
+ async function createSession(id, url, localOnly, width, height, signal, onNavigationAttempt, actionTimeoutMs, authProfile, centralProfile, recording) {
244
251
  await pruneIdleSessions();
245
252
  if (browserSessions.size + creatingSessions.size >= MAX_BROWSER_SESSIONS)
246
253
  throw new Error('browser_session_limit');
247
254
  creatingSessions.add(id);
248
255
  let profileLease;
249
256
  try {
250
- profileLease = authProfile ? await authProfile.store.openAsync(authProfile.scope) : undefined;
257
+ profileLease = centralProfile?.lease ?? (authProfile ? await authProfile.store.openAsync(authProfile.scope) : undefined);
251
258
  }
252
259
  catch (error) {
253
260
  creatingSessions.delete(id);
254
261
  throw error;
255
262
  }
256
263
  const epoch = sessionEpoch;
257
- const { chromium } = await import('playwright-core').catch(error => {
258
- profileLease?.release();
264
+ const { chromium } = await import('playwright-core').catch(async (error) => {
265
+ await profileLease?.release();
259
266
  creatingSessions.delete(id);
260
267
  throw error;
261
268
  });
262
- const browser = await chromium.launch({ headless: true,
269
+ const browser = await chromium.launch({ channel: 'chromium', headless: true, ignoreDefaultArgs: ['--hide-scrollbars'],
263
270
  args: localOnly ? ['--disable-background-networking',
264
271
  '--host-resolver-rules=MAP localhost 127.0.0.1'] : [] }).catch(error => {
265
272
  if (error instanceof Error && error.message.includes("Executable doesn't exist at"))
266
273
  throw new Error('browser_binary_unavailable');
267
274
  throw error;
268
- }).catch(error => { profileLease?.release(); creatingSessions.delete(id); throw error; });
275
+ }).catch(async (error) => { await profileLease?.release(); creatingSessions.delete(id); throw error; });
269
276
  const onAbort = () => { void browser.close(); };
270
277
  signal?.addEventListener('abort', onAbort, { once: true });
271
278
  try {
272
279
  if (signal?.aborted)
273
280
  throw new Error('browser_cancelled');
274
281
  const context = await browser.newContext({ viewport: { width, height }, acceptDownloads: false,
275
- serviceWorkers: 'block' });
282
+ serviceWorkers: localOnly ? 'block' : 'allow' });
276
283
  const geometryBinding = 'revoGeometry_' + randomUUID().replaceAll('-', '');
277
284
  await context.exposeBinding(geometryBinding, ({ page }) => {
278
285
  const session = browserSessions.get(id);
@@ -295,9 +302,14 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
295
302
  });
296
303
  }
297
304
  });
298
- await context.route('**/*', route => {
305
+ await context.route('**/*', async (route) => {
299
306
  try {
300
307
  (localOnly ? localBrowserUrl : browserUrl)(route.request().url());
308
+ const live = browserSessions.get(id)?.live;
309
+ // Do not evaluate the page while holding a navigation route: evaluation can
310
+ // wait for that very navigation. Fence capture, then let the request continue.
311
+ if (route.request().isNavigationRequest() && browserAuthPage(route.request().url()) && live && !live.private)
312
+ await live.pauseRecording(false);
301
313
  return route.continue();
302
314
  }
303
315
  catch {
@@ -326,8 +338,17 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
326
338
  throw new Error('browser_local_network_guard_unavailable');
327
339
  const session = { browser, context, page, localOnly, tabs: new Map(),
328
340
  observations: new BrowserObservations(), control: { epoch: 0, mode: 'observe', private: false, connected: false },
329
- ...(profileLease ? { authProfile: profileLease, profileScopeId: browserProfileScopeId(authProfile.scope), profileScope: authProfile.scope } : {}),
341
+ ...(profileLease ? { authProfile: profileLease, profileScopeId: centralProfile?.id ?? browserProfileScopeId(authProfile.scope),
342
+ ...(centralProfile ? { centralProfile: { id: centralProfile.id, name: centralProfile.name } } : { profileScope: authProfile.scope }) } : {}),
330
343
  lastUsedAt: Date.now(), active: false, networkAccessExpiresAt: null };
344
+ if (recording) {
345
+ session.owner = { actorUserId: recording.options.actorUserId, threadId: recording.options.threadId,
346
+ workspaceId: recording.options.agentTerminalWorkspaceId, workspace: fs.realpathSync(recording.options.profileOwner.workspace) };
347
+ session.workspace = session.owner.workspace;
348
+ session.policyGrantRevision = recording.policyGrantRevision;
349
+ setNetworkLease(id, session, recording.networkAccessExpiresAt);
350
+ browserSessions.set(id, session);
351
+ }
331
352
  registerTab(session, page);
332
353
  context.on('page', opened => {
333
354
  if (session.snapshotting)
@@ -340,6 +361,10 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
340
361
  session.page = opened;
341
362
  await opened.waitForLoadState('domcontentloaded', { timeout: 5_000 }).catch(() => undefined);
342
363
  }).catch(() => undefined);
364
+ if (recording)
365
+ await attachBrowserLive({ ...recording.options, sessionOwned: true });
366
+ if (browserAuthPage(url))
367
+ await session.live?.pauseRecording();
343
368
  onNavigationAttempt?.();
344
369
  await page.goto(url, { waitUntil: 'domcontentloaded', timeout: actionTimeoutMs ?? 30_000 });
345
370
  (localOnly ? localBrowserUrl : browserUrl)(page.url());
@@ -351,13 +376,20 @@ async function createSession(id, url, localOnly, width, height, signal, onNaviga
351
376
  }
352
377
  if (epoch !== sessionEpoch)
353
378
  throw new Error('browser_session_closed');
379
+ // Reading the lease also checks expiry after slow navigation/context construction.
380
+ if (centralProfile)
381
+ void profileLease.state;
354
382
  browserSessions.set(id, session);
355
383
  startIdleCleanup();
356
384
  return session;
357
385
  }
358
386
  catch (error) {
359
- await browser.close().catch(() => undefined);
360
- profileLease?.release();
387
+ if (browserSessions.get(id)?.browser === browser)
388
+ await closeSession(id);
389
+ else {
390
+ await browser.close().catch(() => undefined);
391
+ await profileLease?.release();
392
+ }
361
393
  throw error;
362
394
  }
363
395
  finally {
@@ -377,7 +409,7 @@ function registerTab(session, page) {
377
409
  page.on('framenavigated', frame => {
378
410
  session.observations.invalidate();
379
411
  if (frame === page.mainFrame() && browserAuthPage(page.url()))
380
- void session.live?.pauseRecording();
412
+ void session.live?.pauseRecording().catch(() => session.live?.block());
381
413
  });
382
414
  session.observations.invalidate();
383
415
  page.on('close', () => {
@@ -398,13 +430,14 @@ async function describeSession(id, session, sessionCreated) {
398
430
  continue;
399
431
  const rawUrl = page.url();
400
432
  tabs.push({ id: tabId, title: (await page.title().catch(() => '')).slice(0, 200),
401
- url: rawUrl === 'about:blank' ? rawUrl : safePageUrl(rawUrl), active: session?.page === page });
433
+ url: rawUrl === 'about:blank' ? rawUrl : safePageUrl(rawUrl), popup: !!await page.opener(), active: session?.page === page });
402
434
  }
403
435
  const active = tabs.find(tab => tab.active);
404
436
  return { browserSessionId: id, activeTabId: active?.id || null,
405
437
  tabs, pageUrl: active?.url || '', sessionCreated,
406
438
  ...(active && session ? { browserObservation: session.observations.fresh(activePage(session), active.id) } : {}),
407
- ...(session?.profileScope ? { browserProfile: { id: session.profileScopeId, name: session.profileScope.name, persistent: true, default: false } } : {}) };
439
+ ...(session?.centralProfile ? { browserProfile: { ...session.centralProfile, persistent: true, default: false } }
440
+ : session?.profileScope ? { browserProfile: { id: session.profileScopeId, name: session.profileScope.name, persistent: true, default: false } } : {}) };
408
441
  }
409
442
  function activePage(session) {
410
443
  if (!session.page.isClosed())
@@ -508,11 +541,26 @@ async function runForSession(input) {
508
541
  throw new Error('browser_cancelled');
509
542
  validateBrowserActionInput(input);
510
543
  const url = input.localOnly && !['tabs', 'close', 'close_tab'].includes(input.action) ? localBrowserUrl(input.url) : browserUrl(input.url);
511
- const width = input.width ?? 1440;
512
- const height = input.height ?? 900;
544
+ let width = input.width ?? existing?.page.viewportSize()?.width ?? input.recording?.options.browserSettings?.width ?? 1440;
545
+ let height = input.height ?? existing?.page.viewportSize()?.height ?? input.recording?.options.browserSettings?.height ?? 900;
513
546
  let session = browserSessions.get(input.browserSessionId);
514
- if (session && !input.resolveAuthProfile && session.profileScopeId !== (input.authProfile ? browserProfileScopeId(input.authProfile.scope) : undefined))
547
+ if (input.centralProfile && (input.authProfile || input.resolveAuthProfile))
515
548
  throw new Error('browser_profile_scope_changed');
549
+ if (session && !input.resolveAuthProfile && session.profileScopeId !== (input.centralProfile?.id ?? (input.authProfile ? browserProfileScopeId(input.authProfile.scope) : undefined)))
550
+ throw new Error('browser_profile_scope_changed');
551
+ if (session?.centralProfile && !['tabs', 'close', 'close_tab'].includes(input.action)
552
+ && session.localOnly !== (input.localOnly === true)) {
553
+ // A new network boundary requires fresh navigation, never a replayed click/form action.
554
+ if (input.action !== 'navigate' || input.tabId)
555
+ throw new Error('browser_profile_navigation_required');
556
+ await checkpointSession(input.browserSessionId, session);
557
+ const viewport = session.page.viewportSize();
558
+ width = input.width ?? viewport?.width ?? width;
559
+ height = input.height ?? viewport?.height ?? height;
560
+ // The authorized central writer stays fenced to this session while Chromium is replaced.
561
+ await closeSession(input.browserSessionId, { retainProfileLease: true });
562
+ session = undefined;
563
+ }
516
564
  if (session && (!['tabs', 'close', 'close_tab'].includes(input.action) && session.localOnly !== (input.localOnly === true) || !session.browser.isConnected()
517
565
  || session.context.pages().every(page => page.isClosed())
518
566
  || Date.now() - session.lastUsedAt >= BROWSER_SESSION_IDLE_MS)) {
@@ -534,7 +582,7 @@ async function runForSession(input) {
534
582
  throw new Error('browser_session_missing');
535
583
  const created = !session;
536
584
  if (!session)
537
- session = await createSession(input.browserSessionId, url, input.localOnly === true, width, height, input.signal, input.onActionAttempt, input.actionTimeoutMs, input.resolveAuthProfile ? await input.resolveAuthProfile() : input.authProfile);
585
+ session = await createSession(input.browserSessionId, url, input.localOnly === true, width, height, input.signal, input.onActionAttempt, input.actionTimeoutMs, input.resolveAuthProfile ? await input.resolveAuthProfile() : input.authProfile, input.centralProfile, input.recording);
538
586
  if (input.actorUserId && input.threadId) {
539
587
  const owner = { actorUserId: input.actorUserId, threadId: input.threadId,
540
588
  workspaceId: input.agentTerminalWorkspaceId, workspace: fs.realpathSync(input.workspace) };
@@ -560,6 +608,8 @@ async function runForSession(input) {
560
608
  await closeSession(input.browserSessionId);
561
609
  throw new Error('browser_cancelled');
562
610
  }
611
+ if (input.recording && session.live?.sessionOwned)
612
+ session.live.refreshRecordingAuthority(input.recording.options);
563
613
  const onAbort = () => { void closeSession(input.browserSessionId); };
564
614
  input.signal?.addEventListener('abort', onAbort, { once: true });
565
615
  session.active = true;
@@ -702,6 +752,7 @@ async function runForSession(input) {
702
752
  const bodyText = (await domTarget.innerText({ timeout: input.actionTimeoutMs ?? 10_000 })).slice(0, 25_000);
703
753
  const dom = (bodyText + await semanticControls(page)).slice(0, 40_000);
704
754
  const pageUrl = safePageUrl(page.url());
755
+ await session.live?.resumeRecordingIfPublic();
705
756
  const inventory = await describeSession(input.browserSessionId, session, created);
706
757
  if (session.control.mode !== 'observe')
707
758
  throw new Error('browser_human_control_active');
@@ -780,7 +831,9 @@ export async function runBrowserAction(input) {
780
831
  const task = previous.catch(() => undefined).then(() => runForSession(input));
781
832
  sessionQueues.set(input.browserSessionId, task);
782
833
  try {
783
- return await task;
834
+ const result = await task;
835
+ return input.networkAccessOnce ? { ...result, tabs: [], activeTabId: null, sessionCreated: false,
836
+ browserObservation: undefined, screenshotTransform: undefined } : result;
784
837
  }
785
838
  finally {
786
839
  if (sessionQueues.get(input.browserSessionId) === task)
@@ -872,9 +925,6 @@ export async function attachBrowserLive(options) {
872
925
  || !options.isAuthorized() || !session.browser.isConnected())
873
926
  throw new Error('browser_live_scope_invalid');
874
927
  const previous = session.live;
875
- previous?.disconnect();
876
- if (previous)
877
- await previous.settled();
878
928
  if (options.initialControl && options.initialControl.controlEpoch >= session.control.epoch) {
879
929
  session.control.epoch = options.initialControl.controlEpoch;
880
930
  if (options.initialControl.mode !== 'observe') {
@@ -883,6 +933,16 @@ export async function attachBrowserLive(options) {
883
933
  }
884
934
  // A reconnect never auto-releases an existing local human/blocked fence.
885
935
  }
936
+ if (previous?.sessionOwned) {
937
+ previous.attachViewer(options);
938
+ if (options.initialControl?.mode && options.initialControl.mode !== 'observe')
939
+ await previous.pauseRecording();
940
+ await previous.start();
941
+ return previous;
942
+ }
943
+ previous?.disconnect();
944
+ if (previous)
945
+ await previous.settled();
886
946
  const authorized = () => browserSessions.get(options.browserSessionId) === session && session.browser.isConnected()
887
947
  && (session.networkAccessExpiresAt === null || session.networkAccessExpiresAt > Date.now());
888
948
  const handle = new BrowserLiveHandle(options, {
@@ -919,7 +979,10 @@ export async function attachBrowserLive(options) {
919
979
  sessionQueues.delete(options.browserSessionId);
920
980
  }
921
981
  },
922
- state: async () => ({ ...await describeSession(options.browserSessionId, session, false) }),
982
+ state: async () => {
983
+ const focusId = await describeFocusedField(activePage(session));
984
+ return { ...await describeSession(options.browserSessionId, session, false), focusEditable: !!focusId, focusId };
985
+ },
923
986
  selectTab: async (tabId) => {
924
987
  const page = session.tabs.get(tabId);
925
988
  if (!page || page.isClosed())
@@ -938,6 +1001,8 @@ export async function attachBrowserLive(options) {
938
1001
  await checkpointSession(options.browserSessionId, session);
939
1002
  },
940
1003
  profile: async (choice, liveOptions) => {
1004
+ if (session.centralProfile)
1005
+ throw new Error('browser_profile_new_session_required');
941
1006
  const preferences = liveOptions.profilePreferences;
942
1007
  const owner = liveOptions.profileOwner;
943
1008
  if (!preferences || !owner || owner.actorUserId !== session.owner.actorUserId
@@ -961,12 +1026,12 @@ export async function attachBrowserLive(options) {
961
1026
  let next = same ? session.authProfile : (resolved ? await resolved.store.openAsync(resolved.scope) : undefined);
962
1027
  if (!authorized() || !options.isAuthorized()) {
963
1028
  if (next && next !== session.authProfile)
964
- next.release();
1029
+ await next.release();
965
1030
  throw new Error('browser_live_scope_expired');
966
1031
  }
967
1032
  if (choice.reset && resolved) {
968
1033
  if (same) {
969
- session.authProfile?.release();
1034
+ await session.authProfile?.release();
970
1035
  session.authProfile = undefined;
971
1036
  }
972
1037
  else
@@ -985,7 +1050,7 @@ export async function attachBrowserLive(options) {
985
1050
  if (saveCurrent) {
986
1051
  session.snapshotting = true;
987
1052
  try {
988
- next.save(await session.context.storageState({ indexedDB: true }));
1053
+ await next.save(await session.context.storageState({ indexedDB: true }));
989
1054
  }
990
1055
  finally {
991
1056
  session.snapshotting = false;
@@ -997,7 +1062,7 @@ export async function attachBrowserLive(options) {
997
1062
  else
998
1063
  await session.context.setStorageState(next?.state || { cookies: [], origins: [] });
999
1064
  if (!same || choice.reset) {
1000
- session.authProfile?.release();
1065
+ await session.authProfile?.release();
1001
1066
  session.authProfile = next;
1002
1067
  session.profileScope = resolved?.scope;
1003
1068
  session.profileScopeId = resolved ? browserProfileScopeId(resolved.scope) : undefined;
@@ -1011,7 +1076,7 @@ export async function attachBrowserLive(options) {
1011
1076
  }
1012
1077
  catch (error) {
1013
1078
  if (next && next !== session.authProfile)
1014
- next.release();
1079
+ await next.release();
1015
1080
  throw error;
1016
1081
  }
1017
1082
  },
@@ -3,14 +3,31 @@ export type TerminalOutputChunk = {
3
3
  stream: 'stdout' | 'stderr';
4
4
  text: string;
5
5
  };
6
- /** Only a committed server ACK removes output. Sequence identity survives buffer pruning. */
6
+ export declare const TERMINAL_CAPTURE_MAX_BYTES = 1000000000;
7
+ export declare const TERMINAL_CAPTURE_MAX_CHUNKS = 1000000;
8
+ /** Private, process-local replay spool. Only a committed server ACK prunes its index. */
7
9
  export declare class TerminalOutputBuffer {
8
10
  private readonly chunks;
9
11
  private sequence;
10
12
  private acknowledged;
13
+ private sentThrough;
14
+ private inFlightBytes;
15
+ private bytes;
16
+ private directory?;
17
+ private fd?;
18
+ private disposed;
19
+ private readonly options;
20
+ constructor(options?: {
21
+ spool?: boolean;
22
+ });
11
23
  get lastSequence(): number;
12
24
  get lastAcknowledged(): number;
13
25
  append(stream: TerminalOutputChunk['stream'], text: string): TerminalOutputChunk;
14
26
  acknowledge(sequence: unknown): boolean;
27
+ private read;
15
28
  pending(): readonly TerminalOutputChunk[];
29
+ private page;
30
+ takeUnsent(): readonly TerminalOutputChunk[];
31
+ resetTransport(): void;
32
+ dispose(): void;
16
33
  }
@@ -1,24 +1,111 @@
1
- /** Only a committed server ACK removes output. Sequence identity survives buffer pruning. */
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ export const TERMINAL_CAPTURE_MAX_BYTES = 1_000_000_000;
5
+ export const TERMINAL_CAPTURE_MAX_CHUNKS = 1_000_000;
6
+ const WINDOW_BYTES = 256_000;
7
+ /** Private, process-local replay spool. Only a committed server ACK prunes its index. */
2
8
  export class TerminalOutputBuffer {
3
- chunks = [];
9
+ chunks = new Map();
4
10
  sequence = 0;
5
11
  acknowledged = 0;
12
+ sentThrough = 0;
13
+ inFlightBytes = 0;
14
+ bytes = 0;
15
+ directory;
16
+ fd;
17
+ disposed = false;
18
+ options;
19
+ constructor(options = {}) { this.options = options; }
6
20
  get lastSequence() { return this.sequence; }
7
21
  get lastAcknowledged() { return this.acknowledged; }
8
22
  append(stream, text) {
9
- const chunk = { sequence: ++this.sequence, stream, text };
10
- this.chunks.push(chunk);
11
- return chunk;
23
+ if (this.disposed)
24
+ throw new Error('terminal_output_disposed');
25
+ const bytes = Buffer.byteLength(text);
26
+ if (bytes > 12_000 || this.bytes + bytes > TERMINAL_CAPTURE_MAX_BYTES || this.sequence >= TERMINAL_CAPTURE_MAX_CHUNKS)
27
+ throw new Error('terminal_output_capture_limit');
28
+ if (this.options.spool) {
29
+ if (this.fd === undefined) {
30
+ this.directory = fs.mkdtempSync(path.join(os.tmpdir(), 'revo-output-'));
31
+ fs.chmodSync(this.directory, 0o700);
32
+ this.fd = fs.openSync(path.join(this.directory, 'output'), 'wx+', 0o600);
33
+ }
34
+ const data = Buffer.from(text);
35
+ for (let written = 0; written < bytes;) {
36
+ const count = fs.writeSync(this.fd, data, written, bytes - written, this.bytes + written);
37
+ if (!count)
38
+ throw new Error('terminal_output_spool_write_failed');
39
+ written += count;
40
+ }
41
+ }
42
+ const sequence = ++this.sequence;
43
+ this.chunks.set(sequence, { stream, offset: this.bytes, bytes, ...(this.options.spool ? {} : { text }) });
44
+ this.bytes += bytes;
45
+ return { sequence, stream, text };
12
46
  }
13
47
  acknowledge(sequence) {
14
48
  if (!Number.isSafeInteger(sequence) || sequence < 0 || sequence > this.sequence)
15
49
  return false;
16
50
  if (sequence <= this.acknowledged)
17
51
  return true;
52
+ for (let cursor = this.acknowledged + 1; cursor <= sequence; cursor++) {
53
+ const entry = this.chunks.get(cursor);
54
+ if (entry && cursor <= this.sentThrough)
55
+ this.inFlightBytes -= entry.bytes + 256;
56
+ this.chunks.delete(cursor);
57
+ }
18
58
  this.acknowledged = sequence;
19
- while (this.chunks.length && this.chunks[0].sequence <= this.acknowledged)
20
- this.chunks.shift();
59
+ this.sentThrough = Math.max(this.sentThrough, this.acknowledged);
21
60
  return true;
22
61
  }
23
- pending() { return this.chunks; }
62
+ read(sequence, entry) {
63
+ if (entry.text !== undefined)
64
+ return { sequence, stream: entry.stream, text: entry.text };
65
+ const bytes = Buffer.allocUnsafe(entry.bytes);
66
+ for (let read = 0; read < bytes.length;) {
67
+ const count = fs.readSync(this.fd, bytes, read, bytes.length - read, entry.offset + read);
68
+ if (!count)
69
+ throw new Error('terminal_output_spool_read_failed');
70
+ read += count;
71
+ }
72
+ return { sequence, stream: entry.stream, text: bytes.toString('utf8') };
73
+ }
74
+ pending() { return this.page(this.acknowledged, WINDOW_BYTES); }
75
+ page(after, budget) {
76
+ const result = [];
77
+ let bytes = 0;
78
+ for (let cursor = after + 1; cursor <= this.sequence; cursor++) {
79
+ const entry = this.chunks.get(cursor);
80
+ if (!entry)
81
+ continue;
82
+ if (bytes + entry.bytes + 256 > budget)
83
+ break;
84
+ result.push(this.read(cursor, entry));
85
+ bytes += entry.bytes + 256;
86
+ }
87
+ return result;
88
+ }
89
+ takeUnsent() {
90
+ const chunks = this.page(this.sentThrough, WINDOW_BYTES - this.inFlightBytes);
91
+ for (const chunk of chunks)
92
+ this.inFlightBytes += Buffer.byteLength(chunk.text) + 256;
93
+ if (chunks.length)
94
+ this.sentThrough = chunks.at(-1).sequence;
95
+ return chunks;
96
+ }
97
+ resetTransport() { this.sentThrough = this.acknowledged; this.inFlightBytes = 0; }
98
+ dispose() {
99
+ this.disposed = true;
100
+ this.chunks.clear();
101
+ try {
102
+ if (this.fd !== undefined)
103
+ fs.closeSync(this.fd);
104
+ }
105
+ finally {
106
+ this.fd = undefined;
107
+ if (this.directory)
108
+ fs.rmSync(this.directory, { recursive: true, force: true });
109
+ }
110
+ }
24
111
  }
@@ -35,6 +35,7 @@ type CommandResult = {
35
35
  logTruncated: boolean;
36
36
  logPath: string;
37
37
  policyExpired?: boolean;
38
+ captureTruncated?: boolean;
38
39
  };
39
40
  export type RunningProcess = {
40
41
  pid: number | undefined;
@@ -54,6 +55,7 @@ export declare function runCommand(input: {
54
55
  workdir: string;
55
56
  workspace: string;
56
57
  timeoutMs: number;
58
+ captureOutput?: boolean;
57
59
  background?: boolean;
58
60
  sandbox?: TerminalSandbox;
59
61
  networkAccess?: TerminalNetworkAccess;
@@ -63,7 +65,7 @@ export declare function runCommand(input: {
63
65
  rows?: number;
64
66
  executionId?: string;
65
67
  logDir?: string;
66
- }, onDone: (result: CommandResult) => void, onChunk?: (stream: 'stdout' | 'stderr', text: string) => void): Promise<RunningProcess>;
68
+ }, onDone: (result: CommandResult) => void, onChunk?: (stream: 'stdout' | 'stderr', text: string) => unknown): Promise<RunningProcess>;
67
69
  export declare function runWorkspacePatch(input: {
68
70
  patch: string;
69
71
  workspace: string;