reasonally 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,157 @@
1
+ /**
2
+ * The companion's HTTP server (protocol v1). Only the Reasonally app's origin, on 127.0.0.1, with a
3
+ * paired token may drive a browser; see `protocol.ts` for the shapes.
4
+ */
5
+ import { createServer } from "node:http";
6
+ import { bearerToken } from "./pairing.js";
7
+ import { BodyError, isChatId, parseAction, PROTOCOL_VERSION, readJsonBody, } from "./protocol.js";
8
+ const ALLOWED_METHODS = "GET, POST, DELETE, OPTIONS";
9
+ /** Runs tasks for the same key one after another; different keys run in parallel. */
10
+ export function createQueue() {
11
+ const tails = new Map();
12
+ return function enqueue(key, task) {
13
+ const previous = tails.get(key) ?? Promise.resolve();
14
+ const run = previous.then(task, task);
15
+ const tail = run.catch(() => { });
16
+ tails.set(key, tail);
17
+ void tail.then(() => {
18
+ if (tails.get(key) === tail)
19
+ tails.delete(key);
20
+ });
21
+ return run;
22
+ };
23
+ }
24
+ /** `Host` must name this server on loopback: anything else is DNS rebinding or a stray request. */
25
+ export function isAllowedHost(host, port) {
26
+ const value = host?.toLowerCase();
27
+ return value === `127.0.0.1:${port}` || value === `localhost:${port}`;
28
+ }
29
+ export function createCompanionServer(options) {
30
+ const { origin, version, pairing, sessions, log = () => { } } = options;
31
+ const enqueue = createQueue();
32
+ const server = createServer((req, res) => {
33
+ handle(req, res).catch((error) => {
34
+ log(`Unexpected error: ${error?.stack ?? error}`);
35
+ if (!res.headersSent)
36
+ send(res, 500, { ok: false, error: "The browser companion hit an error." });
37
+ else
38
+ res.end();
39
+ });
40
+ });
41
+ function send(res, status, body, headers = {}) {
42
+ res.writeHead(status, {
43
+ "content-type": "application/json; charset=utf-8",
44
+ "cache-control": "no-store",
45
+ ...headers,
46
+ });
47
+ res.end(JSON.stringify(body));
48
+ }
49
+ const fail = (res, status, error, headers) => send(res, status, { ok: false, error }, headers);
50
+ async function handle(req, res) {
51
+ const { port } = server.address();
52
+ if (!isAllowedHost(req.headers.host, port))
53
+ return fail(res, 403, "Forbidden host.");
54
+ if (req.headers.origin !== origin)
55
+ return fail(res, 403, "Forbidden origin.");
56
+ const cors = { "access-control-allow-origin": origin, vary: "Origin" };
57
+ if (req.method === "OPTIONS") {
58
+ res.writeHead(204, {
59
+ ...cors,
60
+ "access-control-allow-methods": ALLOWED_METHODS,
61
+ "access-control-allow-headers": "authorization, content-type",
62
+ "access-control-allow-private-network": "true",
63
+ "access-control-max-age": "600",
64
+ vary: "Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
65
+ });
66
+ return res.end();
67
+ }
68
+ const reply = (status, body) => send(res, status, body, cors);
69
+ const replyError = (status, error) => fail(res, status, error, cors);
70
+ const methodNotAllowed = (allow) => fail(res, 405, "Method not allowed.", { ...cors, allow });
71
+ const path = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
72
+ const token = bearerToken(req.headers.authorization);
73
+ if (path === "/v1/status") {
74
+ if (req.method !== "GET")
75
+ return methodNotAllowed("GET");
76
+ const paired = await pairing.verify(token, origin);
77
+ const status = {
78
+ app: "reasonally-browser",
79
+ protocol: PROTOCOL_VERSION,
80
+ version,
81
+ paired,
82
+ sessions: paired ? sessions.list() : [],
83
+ };
84
+ return reply(200, status);
85
+ }
86
+ if (path === "/v1/pair") {
87
+ if (req.method !== "POST")
88
+ return methodNotAllowed("POST");
89
+ const gone = new AbortController();
90
+ res.on("close", () => {
91
+ if (!res.writableFinished)
92
+ gone.abort();
93
+ });
94
+ const outcome = await pairing.request(origin, gone.signal);
95
+ switch (outcome.kind) {
96
+ case "approved":
97
+ log(`Paired with ${origin}.`);
98
+ return reply(200, { token: outcome.token });
99
+ case "busy":
100
+ return replyError(409, "Another pairing request is waiting for an answer in the terminal.");
101
+ case "timeout":
102
+ return replyError(403, "Nobody answered in the terminal within 60 seconds.");
103
+ default:
104
+ return replyError(403, "The request was declined in the terminal.");
105
+ }
106
+ }
107
+ const match = path.match(/^\/v1\/sessions\/([^/]+)(\/actions)?$/);
108
+ if (!match)
109
+ return replyError(404, "Not found.");
110
+ const chatId = safeDecode(match[1]);
111
+ if (!chatId || !isChatId(chatId))
112
+ return replyError(400, "Invalid chat id.");
113
+ if (!(await pairing.verify(token, origin))) {
114
+ return replyError(401, "This chat isn't paired with the browser companion. Pair again.");
115
+ }
116
+ if (match[2]) {
117
+ if (req.method !== "POST")
118
+ return methodNotAllowed("POST");
119
+ let body;
120
+ try {
121
+ body = await readJsonBody(req);
122
+ }
123
+ catch (error) {
124
+ if (error instanceof BodyError) {
125
+ return fail(res, error.status, error.message, { ...cors, connection: "close" });
126
+ }
127
+ throw error;
128
+ }
129
+ const parsed = parseAction(body);
130
+ if (!parsed.ok) {
131
+ // A stale ref is an ordinary action failure the model should see and recover from.
132
+ return parsed.staleRef
133
+ ? reply(200, { ok: false, error: parsed.error })
134
+ : replyError(400, parsed.error);
135
+ }
136
+ const result = await enqueue(chatId, () => sessions.run(chatId, parsed.action));
137
+ log(`[${chatId.slice(0, 8)}] ${result.ok ? result.summary : `${parsed.action.action}: ${result.error}`}`);
138
+ return reply(200, result);
139
+ }
140
+ if (req.method === "GET")
141
+ return reply(200, await sessions.info(chatId));
142
+ if (req.method === "DELETE") {
143
+ await sessions.close(chatId);
144
+ return reply(200, { ok: true });
145
+ }
146
+ return methodNotAllowed("GET, DELETE");
147
+ }
148
+ return server;
149
+ }
150
+ function safeDecode(segment) {
151
+ try {
152
+ return decodeURIComponent(segment);
153
+ }
154
+ catch {
155
+ return null;
156
+ }
157
+ }
@@ -0,0 +1,478 @@
1
+ /**
2
+ * One visible browser window per chat, driven with Playwright. Each chat gets a fresh,
3
+ * non-persistent context, so logins last until its window closes.
4
+ *
5
+ * `playwright-core` is only `import type`d here and loaded with `import()` on first use, so the
6
+ * rest of the CLI never pays for it.
7
+ */
8
+ import { lookup } from "node:dns/promises";
9
+ import { isIP } from "node:net";
10
+ import { checkPressTarget, checkTypeTarget, checkUrl, isAllowedPageUrl, isNonPublicAddress, LOCAL_BLOCKED, } from "./guards.js";
11
+ import { capSnapshot, nameForRef, STALE_REF, } from "./protocol.js";
12
+ const ACTION_TIMEOUT_MS = 10_000;
13
+ const NAVIGATION_TIMEOUT_MS = 30_000;
14
+ /** Lets a click start its navigation (or open its tab) before we wait for the page. */
15
+ const SETTLE_MS = 500;
16
+ export const IDLE_CLOSE_MS = 30 * 60 * 1000;
17
+ export const WINDOW_REOPENED = "The window was closed; opened a new one — you may need to log in again";
18
+ const IDLE_REOPENED = "The window was closed after 30 minutes without activity; opened a new one — you may need to log in again";
19
+ export const NO_BROWSER_LINE = "Couldn't start a browser: install Google Chrome, or run `npx playwright install chromium`.";
20
+ const NO_BROWSER = "Couldn't open a browser on this computer. Ask the person to install Google Chrome " +
21
+ "(or run `npx playwright install chromium`), then try again.";
22
+ const LOCAL_PAGE = "This window is showing an address on this computer or the local network, which the browser " +
23
+ "companion doesn't read or control. Navigate somewhere else or go back.";
24
+ /** An error whose message is already written for the chat. */
25
+ export class UserError extends Error {
26
+ }
27
+ /** The page as the model sees it: Playwright's AI-mode aria snapshot, with `[ref=e12]` handles. */
28
+ export function snapshotForAI(page) {
29
+ return page.ariaSnapshot({ mode: "ai", timeout: ACTION_TIMEOUT_MS });
30
+ }
31
+ /** The element behind a ref from the latest snapshot of its frame (`aria-ref=e12`). */
32
+ export function refLocator(page, ref) {
33
+ return page.getByRef(ref);
34
+ }
35
+ /** Customer-facing wording for whatever Playwright or the network threw. Never a stack trace. */
36
+ export function friendlyError(error, action) {
37
+ if (error instanceof UserError)
38
+ return error.message;
39
+ const message = String(error?.message ?? error);
40
+ const has = (pattern) => pattern.test(message);
41
+ if (has(/has been closed|Target closed|Browser closed|browser has disconnected/i)) {
42
+ return "The window was closed during the action. Try again to open a new one.";
43
+ }
44
+ if (has(/ERR_NAME_NOT_RESOLVED/))
45
+ return "Couldn't find that site. Check the address.";
46
+ if (has(/ERR_INTERNET_DISCONNECTED/))
47
+ return "This computer seems to be offline.";
48
+ if (has(/ERR_CERT_|ERR_SSL_/)) {
49
+ return "The site's security certificate isn't valid, so the page wasn't opened.";
50
+ }
51
+ if (has(/ERR_TOO_MANY_REDIRECTS/))
52
+ return "The site redirected too many times.";
53
+ if (has(/ERR_CONNECTION_|ERR_TIMED_OUT|ERR_ADDRESS_UNREACHABLE|ERR_EMPTY_RESPONSE/)) {
54
+ return "Couldn't connect to that site.";
55
+ }
56
+ if (has(/ERR_ABORTED/)) {
57
+ return "The page stopped loading (it may have started a download, which isn't supported).";
58
+ }
59
+ if (has(/Unknown key/i)) {
60
+ return "Unknown key. Use names like Enter, Tab, Escape, ArrowDown or Control+A.";
61
+ }
62
+ if (has(/not a <select> element|Element is not a <select>/i))
63
+ return "That element isn't a dropdown.";
64
+ if (has(/did not find some options/i))
65
+ return "That option isn't in the list.";
66
+ if (has(/not an <input>|not an? (input|textarea)|cannot type|Element is not editable/i)) {
67
+ return "That element can't be typed into.";
68
+ }
69
+ if (has(/Timeout \d+ms exceeded|TimeoutError/)) {
70
+ if (action === "navigate" || action === "back")
71
+ return "The page took too long to load.";
72
+ if (action === "click" || action === "type" || action === "select") {
73
+ return "That element didn't respond (it may be hidden, disabled or covered). Take a new snapshot and try again.";
74
+ }
75
+ return "The page took too long to respond.";
76
+ }
77
+ return UNKNOWN_FAILURE;
78
+ }
79
+ const UNKNOWN_FAILURE = "The browser couldn't do that. Take a new snapshot and try again.";
80
+ const quote = (text) => `"${text.length > 60 ? `${text.slice(0, 57)}…` : text}"`;
81
+ const DIALOGS = {
82
+ alert: "an alert",
83
+ confirm: "a confirmation",
84
+ prompt: "a prompt",
85
+ beforeunload: "a leave-page warning",
86
+ };
87
+ export function dialogNote(type, message) {
88
+ const what = DIALOGS[type] ?? "a dialog";
89
+ const text = message.trim() ? `: ${quote(message.trim())}` : "";
90
+ return `The page showed ${what}${text} (${type === "beforeunload" ? "left the page" : "dismissed it"}).`;
91
+ }
92
+ /**
93
+ * The focused field of every frame (cross-origin frames included). Without window focus no frame
94
+ * "has" focus, so each frame's active element counts.
95
+ */
96
+ async function focusedFields(page) {
97
+ const fields = await Promise.all(page.frames().map((frame) => frame
98
+ .evaluate(() => {
99
+ const doc = globalThis
100
+ .document;
101
+ const el = doc.activeElement;
102
+ if (!el || ["BODY", "HTML", "IFRAME", "FRAME"].includes(el.tagName))
103
+ return null;
104
+ return {
105
+ tagName: el.tagName,
106
+ type: el.getAttribute("type"),
107
+ autocomplete: el.getAttribute("autocomplete"),
108
+ };
109
+ })
110
+ .catch(() => null)));
111
+ return fields.filter((f) => f !== null);
112
+ }
113
+ /** Whether a public-looking hostname resolves to this computer or the local network. */
114
+ async function resolvesLocally(hostname) {
115
+ if (isIP(hostname.replace(/^\[|\]$/g, "")))
116
+ return false; // checked by checkUrl already
117
+ const timeout = new Promise((resolve) => setTimeout(resolve, 3000, null).unref());
118
+ const addresses = await Promise.race([
119
+ lookup(hostname, { all: true }).catch(() => null),
120
+ timeout,
121
+ ]);
122
+ return addresses?.some((a) => isNonPublicAddress(a.address)) ?? false;
123
+ }
124
+ async function launchBrowser(log) {
125
+ const { chromium } = await import("playwright-core");
126
+ // The person's Chrome, then Edge, then a Chromium from `npx playwright install chromium`.
127
+ for (const channel of ["chrome", "msedge", undefined]) {
128
+ try {
129
+ return await chromium.launch({
130
+ channel,
131
+ headless: false,
132
+ // We close windows ourselves on Ctrl+C; Playwright's handlers would exit mid-way.
133
+ handleSIGINT: false,
134
+ handleSIGTERM: false,
135
+ handleSIGHUP: false,
136
+ });
137
+ }
138
+ catch {
139
+ // try the next one
140
+ }
141
+ }
142
+ log(NO_BROWSER_LINE);
143
+ throw new UserError(NO_BROWSER);
144
+ }
145
+ export function createPlaywrightSessions({ allowLocal, log, }) {
146
+ const sessions = new Map();
147
+ /** Why a chat's last window went away, told to the chat when its next one opens. */
148
+ const reopenNotes = new Map();
149
+ let browser = null;
150
+ let opening = 0;
151
+ function getBrowser() {
152
+ if (browser)
153
+ return browser;
154
+ const launching = launchBrowser(log);
155
+ browser = launching;
156
+ launching.then((b) => b.on("disconnected", () => {
157
+ if (browser === launching)
158
+ browser = null;
159
+ // Only this browser's windows: a newer one may already be running other chats.
160
+ for (const [chatId, session] of [...sessions]) {
161
+ if (session.context.browser() === b)
162
+ void forget(chatId, WINDOW_REOPENED);
163
+ }
164
+ }), () => {
165
+ if (browser === launching)
166
+ browser = null;
167
+ });
168
+ return launching;
169
+ }
170
+ /** Drops a chat's window and context (cookies, logins) and quits the browser once none are left. */
171
+ function forget(chatId, note) {
172
+ const session = sessions.get(chatId);
173
+ if (!session)
174
+ return;
175
+ session.closing = true;
176
+ clearTimeout(session.idleTimer);
177
+ sessions.delete(chatId);
178
+ if (note)
179
+ reopenNotes.set(chatId, note);
180
+ const closed = session.context.close().catch(() => { });
181
+ if (sessions.size === 0 && opening === 0 && browser) {
182
+ const current = browser;
183
+ browser = null;
184
+ void closed.then(() => current.then((b) => b.close()).catch(() => { }));
185
+ }
186
+ return closed;
187
+ }
188
+ function touch(chatId, session) {
189
+ clearTimeout(session.idleTimer);
190
+ session.idleTimer = setTimeout(() => {
191
+ log(`[${chatId.slice(0, 8)}] Closed the window after 30 minutes without activity.`);
192
+ void forget(chatId, IDLE_REOPENED);
193
+ }, IDLE_CLOSE_MS);
194
+ }
195
+ function watchPage(chatId, session, page) {
196
+ page.on("dialog", (dialog) => {
197
+ session.notes.push(dialogNote(dialog.type(), dialog.message()));
198
+ const answer = dialog.type() === "beforeunload" ? dialog.accept() : dialog.dismiss();
199
+ answer.catch(() => { });
200
+ });
201
+ page.on("close", () => {
202
+ if (session.closing)
203
+ return;
204
+ const open = session.context.pages().filter((p) => !p.isClosed());
205
+ if (open.length > 0) {
206
+ if (session.page === page)
207
+ session.page = open[open.length - 1];
208
+ return;
209
+ }
210
+ // The person closed the chat's window: its logins go with it.
211
+ void forget(chatId, WINDOW_REOPENED);
212
+ });
213
+ }
214
+ async function open(chatId) {
215
+ const existing = sessions.get(chatId);
216
+ if (existing)
217
+ return existing;
218
+ opening++;
219
+ try {
220
+ const context = await (await getBrowser()).newContext({ viewport: null });
221
+ const session = {
222
+ context,
223
+ page: undefined,
224
+ snapshot: "",
225
+ notes: [],
226
+ closing: false,
227
+ };
228
+ const note = reopenNotes.get(chatId);
229
+ if (note) {
230
+ session.notes.push(note);
231
+ reopenNotes.delete(chatId);
232
+ }
233
+ const watched = new WeakSet();
234
+ context.on("page", (page) => {
235
+ if (watched.has(page))
236
+ return;
237
+ watched.add(page);
238
+ watchPage(chatId, session, page);
239
+ // A tab the page opened (or the person opened) becomes the one we work in.
240
+ if (session.page)
241
+ session.notes.push("That opened a new tab; continuing there.");
242
+ session.page = page;
243
+ });
244
+ context.on("close", () => {
245
+ if (!session.closing && sessions.get(chatId) === session)
246
+ void forget(chatId, WINDOW_REOPENED);
247
+ });
248
+ const page = await context.newPage();
249
+ if (!watched.has(page)) {
250
+ watched.add(page);
251
+ watchPage(chatId, session, page);
252
+ }
253
+ session.page = page;
254
+ sessions.set(chatId, session);
255
+ return session;
256
+ }
257
+ finally {
258
+ opening--;
259
+ }
260
+ }
261
+ async function target(page, ref) {
262
+ const locator = refLocator(page, ref);
263
+ if ((await locator.count().catch(() => 0)) === 0)
264
+ throw new UserError(STALE_REF);
265
+ return locator;
266
+ }
267
+ /** Runs one action and returns its one-line summary. */
268
+ async function perform(session, action) {
269
+ const page = session.page;
270
+ const name = (ref) => nameForRef(session.snapshot, ref);
271
+ switch (action.action) {
272
+ case "navigate": {
273
+ const check = checkUrl(action.args.url, { allowLocal });
274
+ if (!check.ok)
275
+ throw new UserError(check.error);
276
+ if (!allowLocal && (await resolvesLocally(new URL(check.url).hostname))) {
277
+ throw new UserError(LOCAL_BLOCKED);
278
+ }
279
+ const response = await page.goto(check.url, {
280
+ waitUntil: "domcontentloaded",
281
+ timeout: NAVIGATION_TIMEOUT_MS,
282
+ });
283
+ if (response && response.status() >= 400) {
284
+ session.notes.push(`The site answered with HTTP ${response.status()}.`);
285
+ }
286
+ return `Opened ${check.url}`;
287
+ }
288
+ case "snapshot":
289
+ return "Read the page";
290
+ case "click": {
291
+ await (await target(page, action.args.ref)).click({ timeout: ACTION_TIMEOUT_MS });
292
+ return `Clicked ${name(action.args.ref)}`;
293
+ }
294
+ case "type": {
295
+ const field = await target(page, action.args.ref);
296
+ // Runs in the page: the attributes the typing guard needs, following a <label> to its control.
297
+ const info = await field.evaluate((node) => {
298
+ const element = node;
299
+ const el = element.tagName === "LABEL" && element.control ? element.control : element;
300
+ return {
301
+ tagName: el.tagName,
302
+ type: el.getAttribute("type"),
303
+ autocomplete: el.getAttribute("autocomplete"),
304
+ };
305
+ });
306
+ const refusal = checkTypeTarget(info);
307
+ if (refusal)
308
+ throw new UserError(refusal);
309
+ await field.fill(action.args.text, { timeout: ACTION_TIMEOUT_MS });
310
+ if (action.args.submit)
311
+ await field.press("Enter", { timeout: ACTION_TIMEOUT_MS });
312
+ return `Typed into ${name(action.args.ref)}${action.args.submit ? " and pressed Enter" : ""}`;
313
+ }
314
+ case "select": {
315
+ const field = await target(page, action.args.ref);
316
+ // Name a missing option right away (with the real ones) instead of timing out on it.
317
+ const options = await field.evaluate((node) => {
318
+ const el = node;
319
+ return el.tagName === "SELECT" && el.options
320
+ ? Array.from(el.options, (o) => ({ value: o.value, label: o.label.trim() }))
321
+ : null;
322
+ });
323
+ const missing = options
324
+ ? action.args.values.filter((v) => !options.some((o) => o.value === v || o.label === v.trim()))
325
+ : [];
326
+ if (options && missing.length) {
327
+ const list = options.slice(0, 30).map((o) => quote(o.label || o.value));
328
+ throw new UserError(`${missing.map(quote).join(", ")} isn't in the list. The options are: ${list.join(", ")}` +
329
+ (options.length > 30 ? ", …" : "."));
330
+ }
331
+ await field.selectOption(action.args.values, { timeout: ACTION_TIMEOUT_MS });
332
+ return `Selected ${action.args.values.map(quote).join(", ")} in ${name(action.args.ref)}`;
333
+ }
334
+ case "press": {
335
+ for (const field of await focusedFields(page)) {
336
+ const refusal = checkPressTarget(action.args.key, field);
337
+ if (refusal)
338
+ throw new UserError(refusal);
339
+ }
340
+ await page.keyboard.press(action.args.key);
341
+ return `Pressed ${action.args.key}`;
342
+ }
343
+ case "scroll": {
344
+ const { width, height } = await page.evaluate(() => ({
345
+ width: globalThis.innerWidth,
346
+ height: globalThis.innerHeight,
347
+ }));
348
+ // Wheel over the middle of the window, so pages that scroll an inner panel scroll too.
349
+ await page.mouse.move(width / 2, height / 2);
350
+ const distance = Math.round(height * 0.8);
351
+ await page.mouse.wheel(0, action.args.direction === "down" ? distance : -distance);
352
+ return `Scrolled ${action.args.direction}`;
353
+ }
354
+ case "back": {
355
+ const before = page.url();
356
+ const response = await page.goBack({
357
+ waitUntil: "domcontentloaded",
358
+ timeout: NAVIGATION_TIMEOUT_MS,
359
+ });
360
+ if (!response && page.url() === before) {
361
+ throw new UserError("There's no previous page in this window.");
362
+ }
363
+ return "Went back";
364
+ }
365
+ case "wait": {
366
+ const { text, seconds } = action.args;
367
+ if (text !== undefined) {
368
+ const limit = seconds ?? 10;
369
+ try {
370
+ await page
371
+ .getByText(text)
372
+ .first()
373
+ .waitFor({ state: "visible", timeout: limit * 1000 });
374
+ }
375
+ catch (error) {
376
+ if (/Timeout \d+ms exceeded/.test(String(error?.message))) {
377
+ throw new UserError(`${quote(text)} didn't appear within ${limit} seconds.`);
378
+ }
379
+ throw error;
380
+ }
381
+ return `Waited for ${quote(text)}`;
382
+ }
383
+ await page.waitForTimeout((seconds ?? 1) * 1000);
384
+ return `Waited ${seconds} second${seconds === 1 ? "" : "s"}`;
385
+ }
386
+ case "focus":
387
+ await page.bringToFront();
388
+ return "Brought the window to the front";
389
+ }
390
+ }
391
+ async function snapshotOf(page) {
392
+ try {
393
+ return await snapshotForAI(page);
394
+ }
395
+ catch (error) {
396
+ if (page.isClosed())
397
+ throw error;
398
+ // Usually the page navigated mid-snapshot; take it again once it has loaded.
399
+ await page
400
+ .waitForLoadState("domcontentloaded", { timeout: ACTION_TIMEOUT_MS })
401
+ .catch(() => { });
402
+ return await snapshotForAI(page);
403
+ }
404
+ }
405
+ const isLocalPage = (page) => !isAllowedPageUrl(page.url(), { allowLocal });
406
+ return {
407
+ async run(chatId, action) {
408
+ let session;
409
+ try {
410
+ session = await open(chatId);
411
+ }
412
+ catch (error) {
413
+ if (!(error instanceof UserError))
414
+ log(`Couldn't open a window: ${error?.message}`);
415
+ return { ok: false, error: friendlyError(error, action.action) };
416
+ }
417
+ touch(chatId, session);
418
+ try {
419
+ const leavesPage = action.action === "navigate" || action.action === "back" || action.action === "focus";
420
+ if (!leavesPage && isLocalPage(session.page))
421
+ throw new UserError(LOCAL_PAGE);
422
+ const summary = await perform(session, action);
423
+ if (action.action !== "snapshot" && action.action !== "focus" && action.action !== "wait") {
424
+ await new Promise((resolve) => setTimeout(resolve, SETTLE_MS));
425
+ await session.page
426
+ .waitForLoadState("domcontentloaded", { timeout: ACTION_TIMEOUT_MS })
427
+ .catch(() => { });
428
+ }
429
+ const page = session.page;
430
+ if (isLocalPage(page)) {
431
+ throw new UserError("That led to an address on this computer or the local network, which the browser " +
432
+ "companion doesn't read or control. Navigate somewhere else or go back.");
433
+ }
434
+ const snapshot = capSnapshot(await snapshotOf(page));
435
+ session.snapshot = snapshot;
436
+ const title = await page.title().catch(() => "");
437
+ const notes = session.notes.splice(0);
438
+ const result = { ok: true, url: page.url(), title, summary, snapshot };
439
+ if (notes.length)
440
+ result.notes = notes;
441
+ return result;
442
+ }
443
+ catch (error) {
444
+ const worded = friendlyError(error, action.action);
445
+ // The server logs the worded error; the raw one only helps when we had no wording for it.
446
+ if (worded === UNKNOWN_FAILURE) {
447
+ log(`[${chatId.slice(0, 8)}] ${error?.message?.split("\n")[0]}`);
448
+ }
449
+ return { ok: false, error: worded };
450
+ }
451
+ finally {
452
+ if (sessions.get(chatId) === session)
453
+ touch(chatId, session);
454
+ }
455
+ },
456
+ async info(chatId) {
457
+ const session = sessions.get(chatId);
458
+ if (!session || session.page.isClosed())
459
+ return { open: false };
460
+ const title = await Promise.race([
461
+ session.page.title().catch(() => undefined),
462
+ new Promise((resolve) => setTimeout(resolve, 2000, undefined).unref()),
463
+ ]);
464
+ return { open: true, url: session.page.url(), ...(title !== undefined ? { title } : {}) };
465
+ },
466
+ async close(chatId) {
467
+ reopenNotes.delete(chatId);
468
+ await forget(chatId);
469
+ },
470
+ list: () => [...sessions.keys()],
471
+ async closeAll() {
472
+ const current = browser;
473
+ browser = null;
474
+ await Promise.all([...sessions.keys()].map((chatId) => forget(chatId)));
475
+ await current?.then((b) => b.close()).catch(() => { });
476
+ },
477
+ };
478
+ }