camoucore 0.3.0 → 0.6.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.
Files changed (171) hide show
  1. package/LICENSE +4 -3
  2. package/dist/camoufox/__main__.d.ts +10 -0
  3. package/dist/camoufox/__main__.js +1175 -0
  4. package/dist/camoufox/__version__.d.ts +31 -0
  5. package/dist/camoufox/__version__.js +32 -0
  6. package/dist/camoufox/_humanize_playwright.d.ts +54 -0
  7. package/dist/camoufox/_humanize_playwright.js +429 -0
  8. package/dist/camoufox/addons.d.ts +21 -0
  9. package/dist/camoufox/addons.js +56 -0
  10. package/dist/camoufox/async_api.d.ts +9 -0
  11. package/dist/camoufox/async_api.js +9 -0
  12. package/dist/camoufox/browser-pin.d.ts +46 -0
  13. package/dist/camoufox/browser-pin.js +96 -0
  14. package/dist/camoufox/cli.d.ts +7 -0
  15. package/dist/camoufox/cli.js +20 -0
  16. package/dist/camoufox/coherence.d.ts +141 -0
  17. package/dist/camoufox/coherence.js +708 -0
  18. package/dist/camoufox/data-files/audio-output-latency.json +15 -0
  19. package/dist/camoufox/data-files/browser-pin.json +7 -0
  20. package/dist/camoufox/data-files/display-profiles.json +6 -0
  21. package/dist/camoufox/data-files/essential-fonts.json +5 -0
  22. package/dist/camoufox/data-files/fingerprint-presets-v150.json +14544 -0
  23. package/dist/camoufox/data-files/fingerprint-presets.json +5192 -0
  24. package/dist/camoufox/data-files/font-bases.json +1888 -0
  25. package/dist/camoufox/data-files/font-groups.json +716 -0
  26. package/dist/camoufox/data-files/font-prefs.json +1046 -0
  27. package/dist/camoufox/data-files/fonts.json +240 -0
  28. package/dist/camoufox/data-files/fpgen.yml +44 -0
  29. package/dist/camoufox/data-files/launcher-constants.json +136 -0
  30. package/dist/camoufox/data-files/media-devices.json +180 -0
  31. package/dist/camoufox/data-files/repos.yml +40 -0
  32. package/dist/camoufox/data-files/voice-manifests.json +1864 -0
  33. package/dist/camoufox/data-files/voice-uris.json +188 -0
  34. package/dist/camoufox/data-files/warnings.yml +146 -0
  35. package/dist/camoufox/display_profile.d.ts +21 -0
  36. package/dist/camoufox/display_profile.js +129 -0
  37. package/dist/camoufox/driver_defaults.d.ts +27 -0
  38. package/dist/camoufox/driver_defaults.js +119 -0
  39. package/dist/camoufox/exceptions.d.ts +68 -0
  40. package/dist/camoufox/exceptions.js +122 -0
  41. package/dist/camoufox/fingerprints.d.ts +434 -0
  42. package/dist/camoufox/fingerprints.js +1936 -0
  43. package/dist/camoufox/gpudisplay.d.ts +158 -0
  44. package/dist/camoufox/gpudisplay.js +695 -0
  45. package/dist/camoufox/host_rendering.d.ts +38 -0
  46. package/dist/camoufox/host_rendering.js +180 -0
  47. package/dist/camoufox/humanize.d.ts +89 -0
  48. package/dist/camoufox/humanize.js +143 -0
  49. package/dist/camoufox/index.d.ts +21 -0
  50. package/dist/camoufox/index.js +21 -0
  51. package/dist/camoufox/ip.d.ts +45 -0
  52. package/dist/camoufox/ip.js +114 -0
  53. package/dist/camoufox/multiversion.d.ts +131 -0
  54. package/dist/camoufox/multiversion.js +490 -0
  55. package/dist/camoufox/node-floor.d.ts +5 -0
  56. package/dist/camoufox/node-floor.js +17 -0
  57. package/dist/camoufox/paths.d.ts +45 -0
  58. package/dist/camoufox/paths.js +62 -0
  59. package/dist/camoufox/pkgman.d.ts +361 -0
  60. package/dist/camoufox/pkgman.js +1066 -0
  61. package/dist/camoufox/product.d.ts +8 -0
  62. package/dist/camoufox/product.js +8 -0
  63. package/dist/camoufox/pycompat.d.ts +97 -0
  64. package/dist/camoufox/pycompat.js +458 -0
  65. package/dist/camoufox/server.d.ts +36 -0
  66. package/dist/camoufox/server.js +82 -0
  67. package/dist/camoufox/sync_api.d.ts +77 -0
  68. package/dist/camoufox/sync_api.js +207 -0
  69. package/dist/camoufox/utils.d.ts +638 -0
  70. package/dist/camoufox/utils.js +2507 -0
  71. package/dist/camoufox/warnings.d.ts +16 -0
  72. package/dist/camoufox/warnings.js +65 -0
  73. package/dist/camoufox/webgl.d.ts +52 -0
  74. package/dist/camoufox/webgl.js +264 -0
  75. package/dist/camouwolf/__main__.d.ts +10 -0
  76. package/dist/camouwolf/__main__.js +1180 -0
  77. package/dist/camouwolf/__version__.d.ts +31 -0
  78. package/dist/camouwolf/__version__.js +32 -0
  79. package/dist/camouwolf/_humanize_playwright.d.ts +53 -0
  80. package/dist/camouwolf/_humanize_playwright.js +427 -0
  81. package/dist/camouwolf/addons.d.ts +42 -0
  82. package/dist/camouwolf/addons.js +113 -0
  83. package/dist/camouwolf/async_api.d.ts +9 -0
  84. package/dist/camouwolf/async_api.js +9 -0
  85. package/dist/camouwolf/browser-pin.d.ts +46 -0
  86. package/dist/camouwolf/browser-pin.js +96 -0
  87. package/dist/camouwolf/cli.d.ts +7 -0
  88. package/dist/camouwolf/cli.js +20 -0
  89. package/dist/camouwolf/clienthints.d.ts +61 -0
  90. package/dist/camouwolf/clienthints.js +176 -0
  91. package/dist/camouwolf/coherence.d.ts +152 -0
  92. package/dist/camouwolf/coherence.js +554 -0
  93. package/dist/camouwolf/data-files/browser-pin.json +7 -0
  94. package/dist/camouwolf/data-files/camouwolf.defaults.json +118 -0
  95. package/dist/camouwolf/data-files/data/bundle-fonts.json +1983 -0
  96. package/dist/camouwolf/data-files/data/chrome-languages.json +517 -0
  97. package/dist/camouwolf/data-files/data/properties.json +321 -0
  98. package/dist/camouwolf/data-files/data/system-colors.json +35 -0
  99. package/dist/camouwolf/data-files/data/ubo.json +6 -0
  100. package/dist/camouwolf/data-files/fpgen.yml +41 -0
  101. package/dist/camouwolf/data-files/launcher-constants.json +26 -0
  102. package/dist/camouwolf/data-files/repos.yml +23 -0
  103. package/dist/camouwolf/data-files/warnings.yml +96 -0
  104. package/dist/camouwolf/driver_defaults.d.ts +25 -0
  105. package/dist/camouwolf/driver_defaults.js +114 -0
  106. package/dist/camouwolf/exceptions.d.ts +95 -0
  107. package/dist/camouwolf/exceptions.js +150 -0
  108. package/dist/camouwolf/fingerprints.d.ts +227 -0
  109. package/dist/camouwolf/fingerprints.js +753 -0
  110. package/dist/camouwolf/gpudisplay.d.ts +171 -0
  111. package/dist/camouwolf/gpudisplay.js +711 -0
  112. package/dist/camouwolf/host_rendering.d.ts +18 -0
  113. package/dist/camouwolf/host_rendering.js +114 -0
  114. package/dist/camouwolf/humanize.d.ts +84 -0
  115. package/dist/camouwolf/humanize.js +128 -0
  116. package/dist/camouwolf/index.d.ts +22 -0
  117. package/dist/camouwolf/index.js +21 -0
  118. package/dist/camouwolf/multiversion.d.ts +131 -0
  119. package/dist/camouwolf/multiversion.js +491 -0
  120. package/dist/camouwolf/node-floor.d.ts +5 -0
  121. package/dist/camouwolf/node-floor.js +17 -0
  122. package/dist/camouwolf/paths.d.ts +34 -0
  123. package/dist/camouwolf/paths.js +58 -0
  124. package/dist/camouwolf/pkgman.d.ts +331 -0
  125. package/dist/camouwolf/pkgman.js +972 -0
  126. package/dist/camouwolf/product.d.ts +3 -0
  127. package/dist/camouwolf/product.js +3 -0
  128. package/dist/camouwolf/pycompat.d.ts +92 -0
  129. package/dist/camouwolf/pycompat.js +461 -0
  130. package/dist/camouwolf/server.d.ts +36 -0
  131. package/dist/camouwolf/server.js +81 -0
  132. package/dist/camouwolf/switches.d.ts +77 -0
  133. package/dist/camouwolf/switches.js +222 -0
  134. package/dist/camouwolf/sync_api.d.ts +84 -0
  135. package/dist/camouwolf/sync_api.js +173 -0
  136. package/dist/camouwolf/utils.d.ts +644 -0
  137. package/dist/camouwolf/utils.js +2057 -0
  138. package/dist/camouwolf/warnings.d.ts +14 -0
  139. package/dist/camouwolf/warnings.js +59 -0
  140. package/dist/camouwolf/webgl.d.ts +41 -0
  141. package/dist/camouwolf/webgl.js +198 -0
  142. package/dist/data.d.ts +1 -1
  143. package/dist/data.js +3 -3
  144. package/dist/download.js +1 -1
  145. package/dist/exceptions.d.ts +1 -1
  146. package/dist/exceptions.js +1 -1
  147. package/dist/geolocation.js +1 -1
  148. package/dist/host.js +1 -1
  149. package/dist/ip.js +1 -1
  150. package/dist/locales.js +1 -1
  151. package/dist/mcp/cli.d.ts +15 -0
  152. package/dist/mcp/cli.js +108 -0
  153. package/dist/mcp/index.d.ts +8 -0
  154. package/dist/mcp/index.js +8 -0
  155. package/dist/mcp/main.d.ts +2 -0
  156. package/dist/mcp/main.js +8 -0
  157. package/dist/mcp/secrets.d.ts +50 -0
  158. package/dist/mcp/secrets.js +193 -0
  159. package/dist/mcp/server.d.ts +48 -0
  160. package/dist/mcp/server.js +653 -0
  161. package/dist/mcp/tree.d.ts +10 -0
  162. package/dist/mcp/tree.js +36 -0
  163. package/dist/passthrough.d.ts +1 -1
  164. package/dist/product.js +1 -1
  165. package/dist/settings.js +1 -1
  166. package/dist/telemetry.d.ts +0 -1
  167. package/dist/telemetry.js +5 -4
  168. package/dist/virtdisplay.d.ts +1 -1
  169. package/dist/virtdisplay.js +1 -1
  170. package/dist/warnings.js +1 -1
  171. package/package.json +57 -13
@@ -0,0 +1,653 @@
1
+ /**
2
+ * A launcher's browser as MCP tools: open a session, read the page as an
3
+ * accessibility tree with refs, act on those refs, type secrets the agent
4
+ * never sees, and hand the window to a person for the rest.
5
+ *
6
+ * One session is one launch, so one identity. Nothing is pooled behind a
7
+ * session id: two tasks sharing a browser would share its fingerprint and its
8
+ * cookies. Input goes through the launcher's `humanize` engines, which plan the
9
+ * pointer paths, key timing and scrolling in this process.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import fs from "node:fs";
13
+ import { createRequire } from "node:module";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
17
+ import { z } from "zod";
18
+ import { redactValue, Secrets, UrlPattern } from "./secrets.js";
19
+ import { findInTree } from "./tree.js";
20
+ // dist/mcp/ in the package, src/mcp/ in the repo: the package root either way.
21
+ const VERSION = createRequire(import.meta.url)("../../package.json").version;
22
+ /**
23
+ * Imports a launcher by package name or path, and the Playwright browser type
24
+ * it launches, from the Playwright the launcher itself resolves.
25
+ */
26
+ export async function loadLauncher(specifier) {
27
+ const module = await import(specifier);
28
+ if (!module.PRODUCT?.engine || typeof module.NewBrowser !== "function") {
29
+ throw new Error(`${specifier} does not export PRODUCT and NewBrowser, so it is not a launcher this server can drive.`);
30
+ }
31
+ const launcher = module;
32
+ const playwright = createRequire(import.meta.resolve(specifier))("playwright-core");
33
+ return { launcher, browserType: playwright[launcher.PRODUCT.engine.name] };
34
+ }
35
+ /**
36
+ * A file at the top of each engine's profile directory, so a Chromium profile
37
+ * given to a Firefox launcher (or no profile at all) is refused before launch.
38
+ */
39
+ const PROFILE_MARKER = {
40
+ firefox: "prefs.js",
41
+ chromium: "Local State",
42
+ };
43
+ /**
44
+ * What a running browser leaves in its profile to keep a second one out, and
45
+ * caches the copy does not need. Skipping the locks is what lets a session
46
+ * open a profile the person's own browser has open.
47
+ */
48
+ const PROFILE_SKIP = new Set([
49
+ "lock",
50
+ ".parentlock",
51
+ "parent.lock",
52
+ "SingletonLock",
53
+ "SingletonSocket",
54
+ "SingletonCookie",
55
+ "cache2",
56
+ "startupCache",
57
+ "Cache",
58
+ "Code Cache",
59
+ "GPUCache",
60
+ ]);
61
+ /**
62
+ * A private copy of the person's profile for one session. The browser writes
63
+ * to its profile (Playwright adds its own prefs), so the original is never
64
+ * launched; what the session changes is thrown away with the copy.
65
+ */
66
+ function copyProfile(source, engine) {
67
+ const marker = PROFILE_MARKER[engine];
68
+ if (!fs.existsSync(path.join(source, marker))) {
69
+ throw new Error(`${source} has no ${marker}, so it is not a ${engine} profile directory.`);
70
+ }
71
+ // mkdtemp makes the directory 0700: the copy holds the person's cookies.
72
+ const copy = fs.mkdtempSync(path.join(os.tmpdir(), "camoucore-mcp-profile-"));
73
+ fs.cpSync(source, copy, {
74
+ recursive: true,
75
+ filter: (from) => !PROFILE_SKIP.has(path.basename(from)),
76
+ });
77
+ return copy;
78
+ }
79
+ /**
80
+ * The file `name` names inside `dir`, refused if it is anything else: a path
81
+ * out of it, a link out of it, or not a file. A path out of it is refused
82
+ * before it is looked at, so the refusal never says what exists elsewhere.
83
+ */
84
+ function uploadable(dir, name) {
85
+ const root = fs.realpathSync(dir);
86
+ const outside = (file) => {
87
+ const inside = path.relative(root, file);
88
+ return (!inside ||
89
+ inside === ".." ||
90
+ inside.startsWith(`..${path.sep}`) ||
91
+ path.isAbsolute(inside));
92
+ };
93
+ const refuseOutside = () => new Error(`${name} is outside the uploads directory.`);
94
+ const named = path.resolve(root, name);
95
+ if (outside(named))
96
+ throw refuseOutside();
97
+ let file;
98
+ try {
99
+ file = fs.realpathSync(named);
100
+ }
101
+ catch {
102
+ throw new Error(`There is no ${name} in the uploads directory.`);
103
+ }
104
+ if (outside(file))
105
+ throw refuseOutside();
106
+ if (!fs.statSync(file).isFile())
107
+ throw new Error(`${name} is not a file.`);
108
+ return file;
109
+ }
110
+ /**
111
+ * The page's accessibility tree, with what any password field holds hidden: a
112
+ * field's value is in the tree, masked or not, and one the person typed during
113
+ * a hand_off, or the browser filled in, is no configured secret to redact.
114
+ */
115
+ async function treeOf(page, secrets, { ref, depth } = {}) {
116
+ const root = ref ? page.locator(`aria-ref=${ref}`) : page;
117
+ let tree = await root.ariaSnapshot({
118
+ mode: "ai",
119
+ ...(depth === undefined ? {} : { depth }),
120
+ });
121
+ for (const frame of page.frames()) {
122
+ for (const field of await frame.locator("input[type=password]").all()) {
123
+ const value = await field.inputValue().catch(() => "");
124
+ // A configured secret keeps its name, from the redaction of every result.
125
+ if (value && !secrets.contains(value)) {
126
+ tree = redactValue(tree, value, "<hidden password>");
127
+ }
128
+ }
129
+ }
130
+ return tree;
131
+ }
132
+ export function createServer(launcher, browserType, { secrets = new Secrets({}), allowedDomains = [], profile, uploads, } = {}) {
133
+ const { PRODUCT } = launcher;
134
+ const sessions = new Map();
135
+ const allowed = allowedDomains.map((pattern) => new UrlPattern(pattern));
136
+ const isAllowed = (url) => !allowed.length ||
137
+ url === "about:blank" ||
138
+ allowed.some((pattern) => pattern.matches(url));
139
+ // Every result passes through redaction, so a secret the page shows back
140
+ // (a field's value in the snapshot, an echo in an error) reaches the model
141
+ // as <secret:name>.
142
+ const answer = (value, extra = []) => ({
143
+ content: [
144
+ { type: "text", text: secrets.redact(JSON.stringify(value, null, 2)) },
145
+ ...extra,
146
+ ],
147
+ });
148
+ const refuse = (error) => {
149
+ const failure = error;
150
+ const text = JSON.stringify({ error: failure.name, message: failure.message }, null, 2);
151
+ return {
152
+ content: [{ type: "text", text: secrets.redact(text) }],
153
+ isError: true,
154
+ };
155
+ };
156
+ /** Tracks a tab and keeps its main frame inside the allowed domains. */
157
+ function watch(session, page) {
158
+ session.pages.push(page);
159
+ page.on("close", () => {
160
+ session.pages = session.pages.filter((open) => open !== page);
161
+ if (session.page === page && session.pages.length) {
162
+ session.page = session.pages[session.pages.length - 1];
163
+ }
164
+ });
165
+ page.on("framenavigated", (frame) => {
166
+ if (frame !== page.mainFrame() || isAllowed(frame.url()))
167
+ return;
168
+ session.blocked = frame.url();
169
+ page.goto("about:blank").catch(() => { });
170
+ });
171
+ }
172
+ /** A tool on an open session: an unknown id and any failure are refusals. */
173
+ function onSession(work) {
174
+ return async (args) => {
175
+ const session = sessions.get(args.session_id);
176
+ if (!session) {
177
+ return refuse(new Error(`No open session ${args.session_id}. session_open starts one.`));
178
+ }
179
+ try {
180
+ // Before and after, since a click's navigation can commit after the
181
+ // click returns: no tool reads or acts on a page outside the domains.
182
+ await keepInside(session);
183
+ const result = await work(session, args);
184
+ await keepInside(session);
185
+ return result;
186
+ }
187
+ catch (error) {
188
+ // A navigation off the domains that commits during the work detaches
189
+ // the frames it was reading; that, not the detach, is what failed.
190
+ try {
191
+ await keepInside(session);
192
+ }
193
+ catch (outside) {
194
+ return refuse(outside);
195
+ }
196
+ return refuse(error);
197
+ }
198
+ };
199
+ }
200
+ async function keepInside(session) {
201
+ const url = session.page.url();
202
+ const blocked = session.blocked ?? (isAllowed(url) ? undefined : url);
203
+ if (!blocked)
204
+ return;
205
+ session.blocked = undefined;
206
+ if (!isAllowed(url))
207
+ await session.page.goto("about:blank");
208
+ throw new Error(`The page went to ${blocked}, outside the allowed domains, and was sent back to about:blank.`);
209
+ }
210
+ const locate = (session, ref) => session.page.locator(`aria-ref=${ref}`);
211
+ const sessionId = z.string().describe("From session_open.");
212
+ const ref = z
213
+ .string()
214
+ .describe("An element ref, like e12, from the latest snapshot.");
215
+ const server = new McpServer({ name: `${PRODUCT.name}-mcp`, version: VERSION }, {
216
+ instructions: `A ${PRODUCT.title} browser. session_open, then navigate, snapshot to read the page and ` +
217
+ "get refs, and click, type, select, scroll and hover by ref. On a large page, snapshot " +
218
+ "with `find` or `ref` to read only the part you need. Type a password or " +
219
+ "one-time code only with type_secret, by name: you never see the values, and the " +
220
+ "person must never be asked to paste one into the chat. For a secret that is not " +
221
+ "configured, payment details, or anything you should not do yourself, hand_off the " +
222
+ "window to the person. Always session_close when done." +
223
+ (secrets.empty
224
+ ? " No secrets are configured."
225
+ : ` Secrets, by the URLs they may be typed on: ${JSON.stringify(secrets.names())}.`) +
226
+ (allowed.length
227
+ ? ` Pages may load only: ${allowedDomains.join(", ")}.`
228
+ : "") +
229
+ (uploads
230
+ ? ` upload_file attaches files from ${uploads}, by name.`
231
+ : ""),
232
+ });
233
+ server.registerTool("session_open", {
234
+ title: "Open a browser session",
235
+ description: "Launch one browser with a fresh identity. `os` is the identity's OS; left out, the " +
236
+ "launcher draws one. `visible` opens a window a person can see and take over with " +
237
+ "hand_off. `humanize` (default true) moves, types and scrolls like a person; false " +
238
+ "sends each action as Playwright does, which is faster and easier to detect. " +
239
+ "`passthrough` launches with this machine's own fingerprint instead of a drawn one." +
240
+ (profile
241
+ ? " `profile` runs on a copy of the person's own browser profile, signed in where " +
242
+ "they are; nothing the session changes is saved back. Use passthrough with it, " +
243
+ "since the sites know that profile with this machine's fingerprint."
244
+ : ""),
245
+ inputSchema: {
246
+ os: z.enum(["windows", "macos", "linux"]).optional(),
247
+ visible: z.boolean().optional(),
248
+ humanize: z.boolean().optional(),
249
+ passthrough: z.boolean().optional(),
250
+ ...(profile ? { profile: z.boolean().optional() } : {}),
251
+ },
252
+ annotations: { title: "Open a browser session", openWorldHint: true },
253
+ }, async (args) => {
254
+ const { os: identityOs, visible = false, humanize = true, passthrough = false, } = args;
255
+ let copy;
256
+ let closing = false;
257
+ /**
258
+ * Never throws: it runs from the browser's own events, where a throw
259
+ * would take the server down. A copy left behind holds the person's
260
+ * cookies, so it is named.
261
+ */
262
+ const removeCopy = async () => {
263
+ const dir = copy;
264
+ if (!dir)
265
+ return;
266
+ copy = undefined;
267
+ await fs.promises
268
+ .rm(dir, {
269
+ recursive: true,
270
+ force: true,
271
+ maxRetries: 5,
272
+ retryDelay: 200,
273
+ })
274
+ .catch((error) => console.error(`camoucore-mcp: could not remove the profile copy ${dir}: ${error.message}`));
275
+ };
276
+ try {
277
+ if (passthrough && !launcher.PASSTHROUGH) {
278
+ throw new Error(`This ${PRODUCT.title} launcher does not take passthrough, so it would launch ` +
279
+ "with an injected fingerprint. A release that exports PASSTHROUGH does.");
280
+ }
281
+ if (passthrough && identityOs !== undefined) {
282
+ throw new Error("passthrough launches with this machine's own OS, so it takes no `os`.");
283
+ }
284
+ if (args.profile) {
285
+ if (!profile)
286
+ throw new Error("No profile is configured.");
287
+ copy = copyProfile(profile, PRODUCT.engine.name);
288
+ }
289
+ const launched = await launcher.NewBrowser(browserType, {
290
+ headless: !visible,
291
+ humanize,
292
+ ...(identityOs === undefined ? {} : { os: identityOs }),
293
+ ...(passthrough ? { passthrough: true } : {}),
294
+ ...(copy ? { persistent_context: true, user_data_dir: copy } : {}),
295
+ });
296
+ // A persistent launch is its profile's context, and opens with a tab.
297
+ const context = copy
298
+ ? launched
299
+ : undefined;
300
+ const browser = context ? undefined : launched;
301
+ const page = context
302
+ ? (context.pages()[0] ?? (await context.newPage()))
303
+ : await browser.newPage();
304
+ const session = {
305
+ id: randomUUID(),
306
+ // The copy goes once close() returns, when the browser has
307
+ // stopped writing to it.
308
+ close: async () => {
309
+ closing = true;
310
+ try {
311
+ await (context ?? browser).close();
312
+ }
313
+ finally {
314
+ await removeCopy();
315
+ }
316
+ },
317
+ pages: [],
318
+ page,
319
+ visible,
320
+ };
321
+ watch(session, page);
322
+ // A link or script that opens a tab adds it; switch_tab moves to it.
323
+ page.context().on("page", (opened) => watch(session, opened));
324
+ sessions.set(session.id, session);
325
+ const ended = () => {
326
+ sessions.delete(session.id);
327
+ if (!closing)
328
+ void removeCopy();
329
+ };
330
+ if (context)
331
+ context.on("close", ended);
332
+ else
333
+ browser.on("disconnected", ended);
334
+ return answer({ session_id: session.id });
335
+ }
336
+ catch (error) {
337
+ await removeCopy();
338
+ return refuse(error);
339
+ }
340
+ });
341
+ // A web page only: file:, about:, data: and javascript: URLs would hand the
342
+ // agent the machine's files and the browser's own internals.
343
+ const webUrl = z
344
+ .string()
345
+ .url()
346
+ .refine((url) => ["http:", "https:"].includes(new URL(url).protocol), {
347
+ message: "navigate takes an http or https URL",
348
+ });
349
+ server.registerTool("navigate", {
350
+ title: "Navigate",
351
+ description: "Go to an http or https URL and wait for it to load.",
352
+ inputSchema: { session_id: sessionId, url: webUrl },
353
+ annotations: { title: "Navigate", openWorldHint: true },
354
+ }, onSession(async (session, { url }) => {
355
+ if (!isAllowed(url)) {
356
+ throw new Error(`${url} is outside the allowed domains: ${allowedDomains.join(", ")}.`);
357
+ }
358
+ const response = await session.page.goto(url);
359
+ return answer({
360
+ url: session.page.url(),
361
+ title: await session.page.title(),
362
+ status: response?.status() ?? null,
363
+ });
364
+ }));
365
+ server.registerTool("snapshot", {
366
+ title: "Snapshot",
367
+ description: "The page as an accessibility tree, with a ref on every element: read this rather " +
368
+ "than a screenshot. Refs last until the next snapshot or navigation. Read only what " +
369
+ "you need: `ref` gives one element's subtree, `depth` stops that many levels down, " +
370
+ "and `find` keeps only the lines containing its text (ignoring case), under their " +
371
+ "named ancestors.",
372
+ inputSchema: {
373
+ session_id: sessionId,
374
+ ref: z
375
+ .string()
376
+ .optional()
377
+ .describe("Only this element and what is inside it."),
378
+ depth: z.number().int().min(1).optional(),
379
+ find: z.string().min(1).optional(),
380
+ },
381
+ annotations: {
382
+ title: "Snapshot",
383
+ readOnlyHint: true,
384
+ openWorldHint: true,
385
+ },
386
+ }, onSession(async (session, args) => {
387
+ const url = session.page.url();
388
+ // Searched once redacted, so `find` cannot test for a secret's value.
389
+ let snapshot = secrets.redact(await treeOf(session.page, secrets, args));
390
+ if (args.find !== undefined) {
391
+ snapshot =
392
+ findInTree(snapshot, args.find) ||
393
+ `Nothing here contains ${JSON.stringify(args.find)}.`;
394
+ }
395
+ return answer({
396
+ url,
397
+ title: await session.page.title(),
398
+ ...(session.pages.length > 1 ? { tabs: session.pages.length } : {}),
399
+ ...(secrets.empty ? {} : { secrets_here: secrets.namesFor(url) }),
400
+ snapshot,
401
+ });
402
+ }));
403
+ server.registerTool("click", {
404
+ title: "Click",
405
+ description: "Click an element by ref.",
406
+ inputSchema: { session_id: sessionId, ref },
407
+ annotations: { title: "Click", openWorldHint: true },
408
+ }, onSession(async (session, args) => {
409
+ await locate(session, args.ref).click();
410
+ return answer({ clicked: args.ref, url: session.page.url() });
411
+ }));
412
+ server.registerTool("type", {
413
+ title: "Type",
414
+ description: "Type into an element by ref, key by key. `submit` presses Enter afterwards.",
415
+ inputSchema: {
416
+ session_id: sessionId,
417
+ ref,
418
+ text: z.string(),
419
+ submit: z.boolean().optional(),
420
+ },
421
+ annotations: { title: "Type", openWorldHint: true },
422
+ }, onSession(async (session, args) => {
423
+ if (/<secret[:>]/.test(args.text)) {
424
+ throw new Error("type sends its text as written. type_secret types a secret by name.");
425
+ }
426
+ const target = locate(session, args.ref);
427
+ await target.click();
428
+ await target.pressSequentially(args.text);
429
+ if (args.submit)
430
+ await target.press("Enter");
431
+ return answer({ typed: args.ref, url: session.page.url() });
432
+ }));
433
+ if (!secrets.empty) {
434
+ server.registerTool("type_secret", {
435
+ title: "Type a secret",
436
+ description: "Type a configured secret into an element by ref, key by key, without seeing it. " +
437
+ "Only on a field whose frame is at a URL the secret is configured for; a one-time " +
438
+ "code secret types the current code. `submit` presses Enter afterwards.",
439
+ inputSchema: {
440
+ session_id: sessionId,
441
+ ref,
442
+ name: z.string().describe("The secret's name, as configured."),
443
+ submit: z.boolean().optional(),
444
+ },
445
+ annotations: { title: "Type a secret", openWorldHint: true },
446
+ }, onSession(async (session, args) => {
447
+ const target = locate(session, args.ref);
448
+ // The frame the keys go to, which for a field in an iframe is
449
+ // not the page's URL.
450
+ const handle = await target.elementHandle();
451
+ const frame = await handle.ownerFrame();
452
+ await handle.dispose();
453
+ if (!frame)
454
+ throw new Error(`${args.ref} is no longer in the page.`);
455
+ const value = secrets.valueFor(args.name, frame.url());
456
+ await target.click();
457
+ await target.pressSequentially(value);
458
+ if (args.submit)
459
+ await target.press("Enter");
460
+ return answer({ typed_secret: args.name, ref: args.ref });
461
+ }));
462
+ }
463
+ server.registerTool("select_option", {
464
+ title: "Select an option",
465
+ description: "Choose options in a <select> by ref, by their label or value. Several for a multiple select.",
466
+ inputSchema: {
467
+ session_id: sessionId,
468
+ ref,
469
+ options: z.array(z.string()).min(1),
470
+ },
471
+ annotations: { title: "Select an option", openWorldHint: true },
472
+ }, onSession(async (session, args) => {
473
+ const selected = await locate(session, args.ref).selectOption(args.options);
474
+ return answer({ selected });
475
+ }));
476
+ server.registerTool("press_key", {
477
+ title: "Press a key",
478
+ description: "Press a key or chord on the focused element, such as Enter, Escape, ArrowDown, Tab or Control+a.",
479
+ inputSchema: { session_id: sessionId, key: z.string() },
480
+ annotations: { title: "Press a key", openWorldHint: true },
481
+ }, onSession(async (session, args) => {
482
+ await session.page.keyboard.press(args.key);
483
+ return answer({ pressed: args.key, url: session.page.url() });
484
+ }));
485
+ server.registerTool("go_back", {
486
+ title: "Go back",
487
+ description: "Go back one page in the tab's history.",
488
+ inputSchema: { session_id: sessionId },
489
+ annotations: { title: "Go back", openWorldHint: true },
490
+ }, onSession(async (session) => {
491
+ await session.page.goBack();
492
+ return answer({
493
+ url: session.page.url(),
494
+ title: await session.page.title(),
495
+ });
496
+ }));
497
+ server.registerTool("tabs", {
498
+ title: "List tabs",
499
+ description: "The session's open tabs, by index, and which one the tools act on.",
500
+ inputSchema: { session_id: sessionId },
501
+ annotations: { title: "List tabs", readOnlyHint: true },
502
+ }, onSession(async (session) => answer({
503
+ tabs: await Promise.all(session.pages.map(async (page, index) => ({
504
+ index,
505
+ url: page.url(),
506
+ title: await page.title(),
507
+ current: page === session.page,
508
+ }))),
509
+ })));
510
+ server.registerTool("switch_tab", {
511
+ title: "Switch tab",
512
+ description: "Act on another tab, by its index from tabs; `close` closes the current one first.",
513
+ inputSchema: {
514
+ session_id: sessionId,
515
+ index: z.number().int().min(0),
516
+ close: z.boolean().optional(),
517
+ },
518
+ annotations: { title: "Switch tab" },
519
+ }, onSession(async (session, args) => {
520
+ const target = session.pages[args.index];
521
+ if (!target) {
522
+ throw new Error(`There is no tab ${args.index}; the session has ${session.pages.length}.`);
523
+ }
524
+ if (args.close && target !== session.page)
525
+ await session.page.close();
526
+ session.page = target;
527
+ if (session.visible)
528
+ await target.bringToFront();
529
+ return answer({ url: target.url(), title: await target.title() });
530
+ }));
531
+ server.registerTool("scroll", {
532
+ title: "Scroll",
533
+ description: "Scroll an element into view by ref; with `delta_y`, then wheel that many pixels " +
534
+ "from it (positive is down).",
535
+ inputSchema: {
536
+ session_id: sessionId,
537
+ ref,
538
+ delta_y: z.number().optional(),
539
+ },
540
+ annotations: { title: "Scroll", openWorldHint: true },
541
+ }, onSession(async (session, args) => {
542
+ const target = locate(session, args.ref);
543
+ await target.scrollIntoViewIfNeeded();
544
+ if (args.delta_y !== undefined) {
545
+ await target.hover();
546
+ await session.page.mouse.wheel(0, args.delta_y);
547
+ }
548
+ return answer({ scrolled: args.ref });
549
+ }));
550
+ server.registerTool("hover", {
551
+ title: "Hover",
552
+ description: "Move the pointer over an element by ref.",
553
+ inputSchema: { session_id: sessionId, ref },
554
+ annotations: { title: "Hover", openWorldHint: true },
555
+ }, onSession(async (session, args) => {
556
+ await locate(session, args.ref).hover();
557
+ return answer({ hovered: args.ref });
558
+ }));
559
+ server.registerTool("screenshot", {
560
+ title: "Screenshot",
561
+ description: "A PNG of the viewport. Use snapshot unless the pixels themselves matter.",
562
+ inputSchema: { session_id: sessionId },
563
+ annotations: {
564
+ title: "Screenshot",
565
+ readOnlyHint: true,
566
+ openWorldHint: true,
567
+ },
568
+ }, onSession(async (session) => {
569
+ // Pixels cannot be redacted, so no screenshot while the page holds a
570
+ // secret: the tree has every field's value, masked ones included.
571
+ if (!secrets.empty &&
572
+ secrets.contains(await session.page.ariaSnapshot({ mode: "ai" }))) {
573
+ throw new Error("The page holds a secret, so it cannot be shown as pixels. snapshot shows it redacted.");
574
+ }
575
+ const image = await session.page.screenshot({ type: "png" });
576
+ return answer({ url: session.page.url() }, [
577
+ {
578
+ type: "image",
579
+ data: image.toString("base64"),
580
+ mimeType: "image/png",
581
+ },
582
+ ]);
583
+ }));
584
+ if (uploads) {
585
+ server.registerTool("upload_file", {
586
+ title: "Upload files",
587
+ description: "Attach files from the uploads directory, by name, to a file input by ref, or to " +
588
+ "the button or field that opens the page's file picker. Several for a multiple input.",
589
+ inputSchema: {
590
+ session_id: sessionId,
591
+ ref,
592
+ files: z
593
+ .array(z.string())
594
+ .min(1)
595
+ .describe("Names inside the uploads directory."),
596
+ },
597
+ annotations: { title: "Upload files", openWorldHint: true },
598
+ }, onSession(async (session, args) => {
599
+ const paths = args.files.map((name) => uploadable(uploads, name));
600
+ const target = locate(session, args.ref);
601
+ const isInput = await target.evaluate((element) => element instanceof HTMLInputElement && element.type === "file");
602
+ if (isInput) {
603
+ await target.setInputFiles(paths);
604
+ }
605
+ else {
606
+ // Listening takes the picker over, so no dialog opens.
607
+ const [chooser] = await Promise.all([
608
+ session.page.waitForEvent("filechooser", { timeout: 10_000 }),
609
+ target.click(),
610
+ ]);
611
+ await chooser.setFiles(paths);
612
+ }
613
+ return answer({ uploaded: args.files, ref: args.ref });
614
+ }));
615
+ }
616
+ server.registerTool("hand_off", {
617
+ title: "Hand the window to the person",
618
+ description: "Bring a visible session's window to the front for the person to act in: a secret " +
619
+ "that is not configured, a payment, a captcha. Then stop, tell them `reason`, and wait until " +
620
+ "they say they are done; snapshot again before acting, since the page has changed.",
621
+ inputSchema: {
622
+ session_id: sessionId,
623
+ reason: z.string().describe("What the person needs to do."),
624
+ },
625
+ annotations: { title: "Hand the window to the person" },
626
+ }, onSession(async (session, args) => {
627
+ if (!session.visible) {
628
+ throw new Error("This session has no window. session_open with visible: true opens one a person can use.");
629
+ }
630
+ await session.page.bringToFront();
631
+ return answer({ handed_off: true, reason: args.reason });
632
+ }));
633
+ server.registerTool("session_close", {
634
+ title: "Close a browser session",
635
+ description: "Close the browser.",
636
+ inputSchema: { session_id: sessionId },
637
+ annotations: {
638
+ title: "Close a browser session",
639
+ destructiveHint: true,
640
+ openWorldHint: true,
641
+ },
642
+ }, onSession(async (session) => {
643
+ sessions.delete(session.id);
644
+ await session.close();
645
+ return answer({ closed: true });
646
+ }));
647
+ return {
648
+ server,
649
+ closeAll: async () => {
650
+ await Promise.allSettled([...sessions.values()].map((session) => session.close()));
651
+ },
652
+ };
653
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Narrowing an accessibility tree to what the agent asked for, so a large page
3
+ * is not read whole for every question about it.
4
+ */
5
+ /**
6
+ * The lines of `tree` that contain `needle`, ignoring case, each under its
7
+ * ancestors so it is clear where it sits. Ancestors that are only containers
8
+ * are left out, since they say nothing and a deep page has many of them.
9
+ */
10
+ export declare function findInTree(tree: string, needle: string): string;