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