turno-browser 0.2.0 → 0.4.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 (121) hide show
  1. package/CHANGELOG.md +228 -0
  2. package/README.md +205 -16
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +116 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +599 -0
  7. package/dist/api.d.ts +96 -0
  8. package/dist/api.js +88 -0
  9. package/dist/argv.d.ts +55 -3
  10. package/dist/argv.js +190 -10
  11. package/dist/batch.d.ts +19 -0
  12. package/dist/batch.js +148 -0
  13. package/dist/bench.d.ts +1 -1
  14. package/dist/bench.js +21 -5
  15. package/dist/bin/mcp.js +108 -12
  16. package/dist/captcha.d.ts +77 -0
  17. package/dist/captcha.js +333 -0
  18. package/dist/cdp-relay.d.ts +20 -0
  19. package/dist/cdp-relay.js +101 -0
  20. package/dist/chrome-features.d.ts +23 -0
  21. package/dist/chrome-features.js +44 -0
  22. package/dist/detectors.d.ts +11 -0
  23. package/dist/detectors.js +46 -4
  24. package/dist/diagnose.d.ts +45 -0
  25. package/dist/diagnose.js +326 -0
  26. package/dist/doctor.d.ts +85 -0
  27. package/dist/doctor.js +556 -0
  28. package/dist/engine-attach.d.ts +27 -0
  29. package/dist/engine-attach.js +165 -0
  30. package/dist/engine-camoufox.d.ts +32 -0
  31. package/dist/engine-camoufox.js +270 -0
  32. package/dist/engine-lightpanda.d.ts +72 -0
  33. package/dist/engine-lightpanda.js +292 -0
  34. package/dist/engine.d.ts +119 -0
  35. package/dist/engine.js +355 -0
  36. package/dist/flows.d.ts +127 -0
  37. package/dist/flows.js +294 -0
  38. package/dist/governor.d.ts +119 -0
  39. package/dist/governor.js +325 -0
  40. package/dist/health.d.ts +60 -0
  41. package/dist/health.js +86 -0
  42. package/dist/host.d.ts +95 -0
  43. package/dist/host.js +1181 -0
  44. package/dist/human-input.d.ts +84 -0
  45. package/dist/human-input.js +443 -0
  46. package/dist/humanize.d.ts +123 -0
  47. package/dist/humanize.js +241 -0
  48. package/dist/identities.d.ts +23 -10
  49. package/dist/identities.js +45 -37
  50. package/dist/idle-timer.d.ts +12 -0
  51. package/dist/idle-timer.js +25 -0
  52. package/dist/ids.d.ts +9 -0
  53. package/dist/ids.js +34 -0
  54. package/dist/index.d.ts +21 -6
  55. package/dist/index.js +19 -18
  56. package/dist/lifecycle.d.ts +99 -0
  57. package/dist/lifecycle.js +172 -0
  58. package/dist/live-client.d.ts +22 -0
  59. package/dist/live-client.js +93 -0
  60. package/dist/live-page.d.ts +11 -0
  61. package/dist/live-page.js +143 -0
  62. package/dist/live-server.d.ts +173 -0
  63. package/dist/live-server.js +640 -0
  64. package/dist/live.d.ts +120 -0
  65. package/dist/live.js +203 -0
  66. package/dist/login-tool.d.ts +45 -0
  67. package/dist/login-tool.js +233 -0
  68. package/dist/login.d.ts +8 -3
  69. package/dist/login.js +65 -26
  70. package/dist/network-chrome.d.ts +74 -0
  71. package/dist/network-chrome.js +178 -0
  72. package/dist/network.d.ts +125 -0
  73. package/dist/network.js +263 -0
  74. package/dist/opt-in-settings.d.ts +69 -0
  75. package/dist/opt-in-settings.js +151 -0
  76. package/dist/patchright.d.ts +4 -2
  77. package/dist/patchright.js +4 -2
  78. package/dist/recorder.d.ts +88 -0
  79. package/dist/recorder.js +538 -0
  80. package/dist/recordings.d.ts +116 -0
  81. package/dist/recordings.js +474 -0
  82. package/dist/redact.d.ts +34 -0
  83. package/dist/redact.js +135 -0
  84. package/dist/replay.d.ts +20 -0
  85. package/dist/replay.js +382 -0
  86. package/dist/reputation.d.ts +89 -0
  87. package/dist/reputation.js +203 -0
  88. package/dist/resources.d.ts +76 -0
  89. package/dist/resources.js +341 -0
  90. package/dist/runtime-lock.d.ts +59 -0
  91. package/dist/runtime-lock.js +131 -0
  92. package/dist/sealed.d.ts +8 -0
  93. package/dist/sealed.js +96 -0
  94. package/dist/session-export.d.ts +67 -0
  95. package/dist/session-export.js +194 -0
  96. package/dist/session.d.ts +20 -0
  97. package/dist/session.js +30 -0
  98. package/dist/settings.d.ts +246 -0
  99. package/dist/settings.js +530 -0
  100. package/dist/sharing.d.ts +96 -0
  101. package/dist/sharing.js +269 -0
  102. package/dist/snippet.d.ts +8 -0
  103. package/dist/snippet.js +22 -0
  104. package/dist/tab-locks.d.ts +63 -0
  105. package/dist/tab-locks.js +179 -0
  106. package/dist/tools.d.ts +111 -0
  107. package/dist/tools.js +59 -0
  108. package/dist/totp.d.ts +32 -0
  109. package/dist/totp.js +82 -0
  110. package/dist/tuning.d.ts +76 -0
  111. package/dist/tuning.js +69 -0
  112. package/dist/units.d.ts +8 -0
  113. package/dist/units.js +20 -0
  114. package/dist/upstream.d.ts +243 -0
  115. package/dist/upstream.js +46 -0
  116. package/dist/vault.d.ts +91 -0
  117. package/dist/vault.js +273 -0
  118. package/npm-shrinkwrap.json +1074 -3
  119. package/package.json +5 -4
  120. package/dist/paths.d.ts +0 -17
  121. package/dist/paths.js +0 -17
@@ -0,0 +1,165 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { isAbsolute, join } from "node:path";
3
+ import { browserPaths as paths } from "turno-core/paths";
4
+ import { IdleTimer, idleMs } from "./idle-timer.js";
5
+ import { playwright, upstream } from "./upstream.js";
6
+ /**
7
+ * Attach mode: the `attach` engine. Instead of launching a Chrome, turno connects over CDP to
8
+ * the Chrome the user already has open, so the agent works in the user's real, signed-in
9
+ * browser. Opt-in only, per identity (identity.json `attach`) or per server (`--attach`).
10
+ *
11
+ * How Chrome allows it today: since Chrome 136, `--remote-debugging-port` is ignored on the
12
+ * default user data dir. Since Chrome 144 the user can turn on remote debugging for the running
13
+ * browser at chrome://inspect/#remote-debugging; Chrome then listens on 127.0.0.1, writes the
14
+ * port and path to `DevToolsActivePort` in its user data dir, and asks the user to allow each new
15
+ * connection. That dialog is the consent step: turno waits for it (`CONNECT_TIMEOUT_MS`) and
16
+ * cannot answer it.
17
+ *
18
+ * The target (`parseAttachTarget`) is `auto` (the default Chrome profile of this computer),
19
+ * the absolute path of a Chrome user data dir (Beta, Canary, a profile started with
20
+ * `--remote-debugging-port` and its own `--user-data-dir`), or a loopback `http://` or `ws://`
21
+ * endpoint.
22
+ *
23
+ * turno never closes the user's browser or a tab it did not open:
24
+ *
25
+ * - at connect it opens one tab of its own and makes it the agent's current tab, so a first
26
+ * `browser_navigate` never replaces a page of the user's;
27
+ * - tabs that open during a tool call count as the agent's (`own`); tabs that were open before,
28
+ * or that the user opens between calls, are the user's;
29
+ * - closing (`browser_close`, the session ending, the idle limit) closes the agent's tabs that
30
+ * are still open and disconnects: Playwright's `Browser.close` on a CDP connection only drops
31
+ * the connection, it does not close Chrome (checked with Chrome 157);
32
+ * - the host's tab governor touches only the agent's tabs, and never closes a popup;
33
+ * - no runtime lock, orphan sweep or shutdown signal reaches this Chrome: those act on the
34
+ * identity's own profile and the Chrome turno started on it, which attach mode never starts.
35
+ */
36
+ /** How long to wait for the connection, which includes the user answering Chrome's dialog. */
37
+ const CONNECT_TIMEOUT_MS = 60_000;
38
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
39
+ /** The target an `attach` value names, or a message saying what is wrong with it. */
40
+ export function parseAttachTarget(value) {
41
+ const v = value.trim();
42
+ if (v === "auto")
43
+ return { kind: "auto" };
44
+ if (isAbsolute(v))
45
+ return { kind: "dir", dir: v };
46
+ if (/^(https?|wss?):\/\//.test(v)) {
47
+ let url;
48
+ try {
49
+ url = new URL(v);
50
+ }
51
+ catch {
52
+ return { error: `attach "${v}" is not a URL` };
53
+ }
54
+ if (!LOOPBACK.has(url.hostname))
55
+ return { error: `attach "${v}" must be on this computer (127.0.0.1, localhost or [::1])` };
56
+ return { kind: "endpoint", url: v };
57
+ }
58
+ return {
59
+ error: `attach must be "auto", the absolute path of a Chrome user data dir, or a loopback http:// or ws:// endpoint, not "${v}"`,
60
+ };
61
+ }
62
+ /** The user data dir of the installed Chrome's default profile, where Chrome writes `DevToolsActivePort`. */
63
+ export function defaultChromeUserDataDir(env = process.env, platform = process.platform) {
64
+ const home = paths(env).home;
65
+ if (platform === "darwin")
66
+ return join(home, "Library", "Application Support", "Google", "Chrome");
67
+ if (platform === "win32")
68
+ return join(env.LOCALAPPDATA ?? join(home, "AppData", "Local"), "Google", "Chrome", "User Data");
69
+ return join(env.XDG_CONFIG_HOME || join(home, ".config"), "google-chrome");
70
+ }
71
+ /** `DevToolsActivePort`: the port on the first line, the browser's WebSocket path on the second. */
72
+ export function parseDevToolsActivePort(text) {
73
+ const [rawPort, rawPath] = text
74
+ .split("\n")
75
+ .map((l) => l.trim())
76
+ .filter(Boolean);
77
+ const port = Number(rawPort);
78
+ if (!Number.isInteger(port) || port <= 0 || port > 65535 || !rawPath?.startsWith("/"))
79
+ return undefined;
80
+ return { port, path: rawPath };
81
+ }
82
+ const ENABLE = "open chrome://inspect/#remote-debugging in that Chrome and turn remote debugging on";
83
+ /**
84
+ * Where to connect for a target, without connecting: for `auto` and a dir, the endpoint in its
85
+ * `DevToolsActivePort`. Throws with what the user should do when Chrome does not listen.
86
+ */
87
+ export function resolveAttachEndpoint(target, env = process.env, platform = process.platform) {
88
+ if (target.kind === "endpoint")
89
+ return target.url;
90
+ const dir = target.kind === "dir" ? target.dir : defaultChromeUserDataDir(env, platform);
91
+ let text;
92
+ try {
93
+ text = readFileSync(join(dir, "DevToolsActivePort"), "utf8");
94
+ }
95
+ catch {
96
+ throw new Error(`attach: no Chrome with remote debugging on for ${dir} (no DevToolsActivePort). Start Chrome, then ${ENABLE}.`);
97
+ }
98
+ const parsed = parseDevToolsActivePort(text);
99
+ if (!parsed)
100
+ throw new Error(`attach: ${join(dir, "DevToolsActivePort")} is not a port and a path`);
101
+ return `ws://127.0.0.1:${parsed.port}${parsed.path}`;
102
+ }
103
+ export function createAttachEngine(target) {
104
+ return {
105
+ id: "attach",
106
+ refuse(tool) {
107
+ // Arbitrary Playwright code in the user's own browser reaches every site it is signed in to.
108
+ if (tool === "browser_run_code_unsafe")
109
+ return "browser_run_code_unsafe is refused in attach mode: it would run arbitrary code against your own Chrome and every site it is signed in to. Use the other browser tools.";
110
+ return undefined;
111
+ },
112
+ async launch({ config, identity }) {
113
+ const env = identity?.env ?? process.env;
114
+ const endpoint = resolveAttachEndpoint(target, env);
115
+ let browser;
116
+ try {
117
+ browser = await playwright().chromium.connectOverCDP(endpoint, { timeout: CONNECT_TIMEOUT_MS });
118
+ }
119
+ catch (error) {
120
+ const first = error.message.split("\n")[0];
121
+ throw new Error(`attach: could not connect to Chrome at ${endpoint.replace(/\/devtools\/browser\/.*/, "")} (${first}). ` +
122
+ `Chrome asks you to allow each new connection: click Allow in its dialog. If it did not ask, ${ENABLE}.`);
123
+ }
124
+ const context = browser.contexts()[0];
125
+ if (!context) {
126
+ await browser.close().catch(() => { });
127
+ throw new Error("attach: that Chrome has no default browser context to work in");
128
+ }
129
+ const owned = new Set();
130
+ let closing = false;
131
+ const close = async () => {
132
+ closing = true;
133
+ upstream().core.utils.gracefullyCloseSet.delete(close);
134
+ idleTimer?.dispose();
135
+ for (const page of owned)
136
+ if (!page.isClosed())
137
+ await page.close().catch(() => { });
138
+ owned.clear();
139
+ // On a CDP connection this disconnects; Chrome and the user's tabs stay.
140
+ await browser.close().catch(() => { });
141
+ };
142
+ // The exit watchdog awaits this before the process exits, so the agent's tabs close then too.
143
+ upstream().core.utils.gracefullyCloseSet.add(close);
144
+ const ms = idleMs(config);
145
+ let idleTimer;
146
+ if (ms) {
147
+ idleTimer = new IdleTimer(ms, () => void close());
148
+ browser.once("disconnected", () => idleTimer?.dispose());
149
+ }
150
+ return {
151
+ engine: "attach",
152
+ context,
153
+ userBrowser: true,
154
+ own(page) {
155
+ owned.add(page);
156
+ page.once("close", () => owned.delete(page));
157
+ },
158
+ ...(idleTimer ? { idleTimer } : {}),
159
+ isOpen: () => !closing && browser.isConnected(),
160
+ close,
161
+ };
162
+ },
163
+ };
164
+ }
165
+ //# sourceMappingURL=engine-attach.js.map
@@ -0,0 +1,32 @@
1
+ import type { Engine } from "./engine.js";
2
+ /** Why the Camoufox engine refuses this tool, or undefined when it runs it. */
3
+ export declare function camoufoxRefusal(tool: string): string | undefined;
4
+ /** How to install Camoufox, for errors and `turno browser doctor`. */
5
+ export declare function camoufoxInstallHint(platform?: NodeJS.Platform): string;
6
+ /** Where Camoufox's own installer keeps its builds (platformdirs' user cache folder). */
7
+ export declare function camoufoxCacheDir(env: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
8
+ export interface CamoufoxInfo {
9
+ path: string;
10
+ version?: string;
11
+ }
12
+ /** The Camoufox turno would run: `TURNO_CAMOUFOX_PATH`, else the newest build in Camoufox's cache folder. */
13
+ export declare function findCamoufox(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): CamoufoxInfo | undefined;
14
+ /** The minor version of Playwright that patchright-core is built on, like "1.64". */
15
+ export declare function playwrightMinor(): string;
16
+ export interface PlaywrightCoreInfo {
17
+ dir: string;
18
+ version: string;
19
+ }
20
+ /**
21
+ * The stock `playwright-core` this engine would load: `TURNO_PLAYWRIGHT_CORE` (its package
22
+ * folder), else the one Node finds from turno-browser. Undefined when there is none; `ok` is
23
+ * false when its minor version is not patchright-core's.
24
+ */
25
+ export declare function findPlaywrightCore(env?: NodeJS.ProcessEnv): (PlaywrightCoreInfo & {
26
+ ok: boolean;
27
+ }) | undefined;
28
+ /** How to install the stock Playwright this engine needs. */
29
+ export declare function playwrightCoreHint(): string;
30
+ /** Where an identity's Camoufox keeps its Firefox profile. */
31
+ export declare function camoufoxProfileDir(id: string, env: NodeJS.ProcessEnv): string;
32
+ export declare function createCamoufoxEngine(): Engine;
@@ -0,0 +1,270 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { createRequire } from "node:module";
5
+ import { dirname, isAbsolute, join } from "node:path";
6
+ import { findOnPath, browserPaths as paths } from "turno-core/paths";
7
+ import { IdleTimer, idleMs } from "./idle-timer.js";
8
+ import { identityStateDir } from "./ids.js";
9
+ import { FIREFOX_PROXY_PREFS, resolveProxy } from "./network.js";
10
+ import { acquireRuntimeLock } from "./runtime-lock.js";
11
+ import { acceptLanguages, chromeEnv, readIdentitySettings, systemTimezone } from "./settings.js";
12
+ import { upstream } from "./upstream.js";
13
+ /**
14
+ * The `camoufox` engine: Camoufox, a Firefox build with its own fingerprint handling, instead
15
+ * of Chrome. Opt-in only (identity.json `"engine": "camoufox"`, or `--engine camoufox`), off by
16
+ * default, and not recommended for the user's own accounts: a Firefox with a changed fingerprint
17
+ * is something sites look for, and the identity's Chrome profile and sign-ins do not carry over.
18
+ *
19
+ * turno never downloads it. Two things must be installed:
20
+ *
21
+ * - Camoufox itself: `TURNO_CAMOUFOX_PATH` (the executable, an absolute path), else the newest
22
+ * build Camoufox's own installer (`pip install camoufox`, then `camoufox fetch`) put in its
23
+ * cache folder.
24
+ * - Stock Playwright (`playwright-core`) of the same minor version as patchright-core.
25
+ * patchright-core drives Chromium only: with a Firefox build, evaluate fails and every action
26
+ * times out (measured with Playwright's Firefox 157). Firefox speaks Playwright's Juggler
27
+ * protocol, which stock Playwright drives. It is found next to turno-browser (`npm install -g
28
+ * playwright-core@<version>`) or at `TURNO_PLAYWRIGHT_CORE` (its package folder).
29
+ *
30
+ * The context it launches is handed to the same upstream tool backend as Chrome's, so the
31
+ * stock tools behave the same; the ones in `NOT_IN_CAMOUFOX` are refused before they run.
32
+ *
33
+ * For an identity, Camoufox keeps its own Firefox profile in
34
+ * `<state>/browser/identities/<id>/camoufox-profile`: it never opens the identity's Chrome
35
+ * profile, so a sign-in made in Chrome is not there. The identity's runtime lock is held while
36
+ * it runs, so a Chrome and a Camoufox never drive one identity at once. turno passes Camoufox no
37
+ * generated fingerprint: it presents the values its build reports for this computer.
38
+ */
39
+ /** Tools that do not run on Camoufox, with the reason. */
40
+ const NOT_IN_CAMOUFOX = {
41
+ browser_run_code_unsafe: "it runs Playwright code against the patchright-core API, and Camoufox runs on stock Playwright",
42
+ browser_solve_captcha: "it sets the token from Patchright's isolated script world and calls the widget's callback in the page's own, and Camoufox runs on stock Playwright",
43
+ };
44
+ /** Why the Camoufox engine refuses this tool, or undefined when it runs it. */
45
+ export function camoufoxRefusal(tool) {
46
+ const why = NOT_IN_CAMOUFOX[tool];
47
+ if (!why)
48
+ return undefined;
49
+ return `${tool} is not available with the Camoufox engine: ${why}. Use the Chrome engine for it (\`turno browser set <id> --engine chrome\`).`;
50
+ }
51
+ /** How to install Camoufox, for errors and `turno browser doctor`. */
52
+ export function camoufoxInstallHint(platform = process.platform) {
53
+ if (platform === "win32")
54
+ return "pip install -U camoufox, then camoufox fetch (turno-browser does not run on Windows; use WSL)";
55
+ return "pip install -U camoufox && camoufox fetch (then set TURNO_CAMOUFOX_PATH if turno does not find it)";
56
+ }
57
+ /** Where Camoufox's own installer keeps its builds (platformdirs' user cache folder). */
58
+ export function camoufoxCacheDir(env, platform = process.platform) {
59
+ const home = paths(env).home;
60
+ if (platform === "darwin")
61
+ return join(home, "Library", "Caches", "camoufox");
62
+ return join(env.XDG_CACHE_HOME || join(home, ".cache"), "camoufox");
63
+ }
64
+ /** The executable inside one Camoufox build folder, if it has one. */
65
+ function executableIn(dir, platform) {
66
+ const file = platform === "darwin" ? join(dir, "Camoufox.app", "Contents", "MacOS", "camoufox") : join(dir, "camoufox-bin");
67
+ return existsSync(file) && statSync(file).isFile() ? file : undefined;
68
+ }
69
+ /** The newest Camoufox build under its cache folder, searched a few levels deep. */
70
+ function newestBuild(root, platform) {
71
+ const found = [];
72
+ const walk = (dir, depth) => {
73
+ const exe = executableIn(dir, platform);
74
+ if (exe) {
75
+ found.push({ file: exe, mtime: statSync(exe).mtimeMs });
76
+ return;
77
+ }
78
+ if (depth === 0)
79
+ return;
80
+ let entries;
81
+ try {
82
+ entries = readdirSync(dir);
83
+ }
84
+ catch {
85
+ return;
86
+ }
87
+ for (const e of entries) {
88
+ if (e.startsWith(".") || e.endsWith(".app"))
89
+ continue;
90
+ const sub = join(dir, e);
91
+ try {
92
+ if (statSync(sub).isDirectory())
93
+ walk(sub, depth - 1);
94
+ }
95
+ catch {
96
+ /* gone */
97
+ }
98
+ }
99
+ };
100
+ walk(root, 4);
101
+ return found.sort((a, b) => b.mtime - a.mtime)[0]?.file;
102
+ }
103
+ /** The Camoufox turno would run: `TURNO_CAMOUFOX_PATH`, else the newest build in Camoufox's cache folder. */
104
+ export function findCamoufox(env = process.env, platform = process.platform) {
105
+ const configured = env.TURNO_CAMOUFOX_PATH?.trim();
106
+ const path = configured
107
+ ? isAbsolute(configured) && findOnPath(configured, env) && statSync(configured).isFile()
108
+ ? configured
109
+ : undefined
110
+ : newestBuild(camoufoxCacheDir(env, platform), platform);
111
+ if (!path)
112
+ return undefined;
113
+ try {
114
+ const out = execFileSync(path, ["--version"], {
115
+ encoding: "utf8",
116
+ timeout: 5000,
117
+ stdio: ["ignore", "pipe", "ignore"],
118
+ env: { ...env, MOZ_HEADLESS: "1" },
119
+ }).trim();
120
+ return out ? { path, version: out.split("\n")[0].trim() } : { path };
121
+ }
122
+ catch {
123
+ return { path };
124
+ }
125
+ }
126
+ /** The error when Camoufox is missing, with the install command. */
127
+ function camoufoxMissing(env) {
128
+ const configured = env.TURNO_CAMOUFOX_PATH?.trim();
129
+ const where = configured
130
+ ? `TURNO_CAMOUFOX_PATH (${configured}) is not an executable file with an absolute path`
131
+ : `no Camoufox build is in ${camoufoxCacheDir(env)}`;
132
+ return new Error(`the camoufox engine needs Camoufox, and ${where}. Install it: ${camoufoxInstallHint()}. turno never downloads it for you; \`turno browser doctor\` checks it.`);
133
+ }
134
+ /** The minor version of Playwright that patchright-core is built on, like "1.64". */
135
+ export function playwrightMinor() {
136
+ return upstream().version.split(".").slice(0, 2).join(".");
137
+ }
138
+ const require = createRequire(import.meta.url);
139
+ /**
140
+ * The stock `playwright-core` this engine would load: `TURNO_PLAYWRIGHT_CORE` (its package
141
+ * folder), else the one Node finds from turno-browser. Undefined when there is none; `ok` is
142
+ * false when its minor version is not patchright-core's.
143
+ */
144
+ export function findPlaywrightCore(env = process.env) {
145
+ let manifest;
146
+ const configured = env.TURNO_PLAYWRIGHT_CORE?.trim();
147
+ if (configured)
148
+ manifest = isAbsolute(configured) ? join(configured, "package.json") : undefined;
149
+ else {
150
+ try {
151
+ manifest = require.resolve("playwright-core/package.json");
152
+ }
153
+ catch {
154
+ manifest = undefined;
155
+ }
156
+ }
157
+ if (!manifest || !existsSync(manifest))
158
+ return undefined;
159
+ try {
160
+ const pkg = JSON.parse(readFileSync(manifest, "utf8"));
161
+ if (pkg.name !== "playwright-core" || typeof pkg.version !== "string")
162
+ return undefined;
163
+ const minor = pkg.version.split(".").slice(0, 2).join(".");
164
+ return { dir: dirname(manifest), version: pkg.version, ok: minor === playwrightMinor() };
165
+ }
166
+ catch {
167
+ return undefined;
168
+ }
169
+ }
170
+ /** How to install the stock Playwright this engine needs. */
171
+ export function playwrightCoreHint() {
172
+ return `npm install -g playwright-core@${playwrightMinor()} (next to turno-browser), or set TURNO_PLAYWRIGHT_CORE to its folder`;
173
+ }
174
+ function loadFirefox(env) {
175
+ const found = findPlaywrightCore(env);
176
+ if (!found)
177
+ throw new Error(`the camoufox engine needs stock Playwright (playwright-core ${playwrightMinor()}): patchright-core drives Chromium only. Install it: ${playwrightCoreHint()}`);
178
+ if (!found.ok)
179
+ throw new Error(`the camoufox engine needs playwright-core ${playwrightMinor()}.x, the version patchright-core is built on, and found ${found.version} at ${found.dir}. Install it: ${playwrightCoreHint()}`);
180
+ return require(found.dir).firefox;
181
+ }
182
+ /** Where an identity's Camoufox keeps its Firefox profile. */
183
+ export function camoufoxProfileDir(id, env) {
184
+ return join(identityStateDir(id, env), "camoufox-profile");
185
+ }
186
+ export function createCamoufoxEngine() {
187
+ return {
188
+ id: "camoufox",
189
+ refuse: camoufoxRefusal,
190
+ async launch({ config, identity, secret }) {
191
+ const env = identity?.env ?? process.env;
192
+ const found = findCamoufox(env);
193
+ if (!found)
194
+ throw camoufoxMissing(env);
195
+ const firefox = loadFirefox(env);
196
+ const settings = identity ? readIdentitySettings(identity.id, identity.env) : undefined;
197
+ const proxy = settings?.proxy ? await resolveProxy(settings.proxy, env, secret ?? (() => { })) : undefined;
198
+ const languages = settings ? acceptLanguages(settings) : undefined;
199
+ const tz = settings?.timezone && settings.timezone !== systemTimezone() ? settings.timezone : undefined;
200
+ const held = identity ? acquireRuntimeLock(identity.id, identity.env, { holder: "mcp" }) : undefined;
201
+ // Without an identity, a throwaway profile removed when the browser closes.
202
+ const temporary = identity ? undefined : mkdtempSync(join(env.TMPDIR || tmpdir(), "turno-camoufox-"));
203
+ // Firefox may still be writing to it as the context closes: retry, and never throw from
204
+ // a close handler (that would end the server).
205
+ const removeTemporary = () => {
206
+ if (!temporary)
207
+ return;
208
+ try {
209
+ rmSync(temporary, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
210
+ }
211
+ catch {
212
+ /* left in the temp folder; the OS clears it */
213
+ }
214
+ };
215
+ let context;
216
+ try {
217
+ const dir = identity ? camoufoxProfileDir(identity.id, identity.env) : temporary;
218
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
219
+ const prefs = {
220
+ ...(languages ? { "intl.accept_languages": languages.join(",") } : {}),
221
+ ...(proxy ? FIREFOX_PROXY_PREFS : {}),
222
+ };
223
+ context = await firefox.launchPersistentContext(dir, {
224
+ executablePath: found.path,
225
+ headless: config.browser.launchOptions.headless ?? false,
226
+ ...(config.browser.contextOptions ?? {}),
227
+ ...(proxy ? { proxy } : {}),
228
+ ...(tz ? { timezoneId: tz } : {}),
229
+ ...(Object.keys(prefs).length ? { firefoxUserPrefs: prefs } : {}),
230
+ handleSIGINT: false,
231
+ handleSIGTERM: false,
232
+ env: chromeEnv(env),
233
+ });
234
+ }
235
+ catch (error) {
236
+ held?.release();
237
+ removeTemporary();
238
+ throw new Error(`could not start Camoufox: ${error.message.split("\n")[0]}`);
239
+ }
240
+ let closing = false;
241
+ context.once("close", () => {
242
+ closing = true;
243
+ held?.release();
244
+ removeTemporary();
245
+ });
246
+ let idleTimer;
247
+ const close = async () => {
248
+ upstream().core.utils.gracefullyCloseSet.delete(close);
249
+ idleTimer?.dispose();
250
+ closing = true;
251
+ await context.close().catch(() => { });
252
+ held?.release();
253
+ };
254
+ // This Playwright is not patchright-core's, so its exit hooks do not see the browser:
255
+ // upstream's exit watchdog awaits this close before the process exits.
256
+ upstream().core.utils.gracefullyCloseSet.add(close);
257
+ const ms = idleMs(config);
258
+ if (ms)
259
+ idleTimer = new IdleTimer(ms, () => void close());
260
+ return {
261
+ engine: "camoufox",
262
+ context,
263
+ ...(idleTimer ? { idleTimer } : {}),
264
+ isOpen: () => !closing,
265
+ close,
266
+ };
267
+ },
268
+ };
269
+ }
270
+ //# sourceMappingURL=engine-camoufox.js.map
@@ -0,0 +1,72 @@
1
+ import { type ProcTable } from "turno-core/process";
2
+ import type { Engine } from "./engine.js";
3
+ import { type StopOptions } from "./lifecycle.js";
4
+ /**
5
+ * Read mode: the `lightpanda` engine. Lightpanda is a headless browser written from
6
+ * scratch for automation (no rendering, a small fraction of Chrome's memory) that speaks CDP.
7
+ * turno never downloads it: it runs the `lightpanda` found through `TURNO_LIGHTPANDA_PATH` or
8
+ * on PATH, and `turno browser doctor` says how to install it.
9
+ *
10
+ * Per launch turno starts `lightpanda serve` on a Unix socket in a fresh private folder (no TCP
11
+ * port), with Lightpanda's telemetry off, and connects Patchright to it through the CDP relay
12
+ * (`cdp-relay.ts`), in a new browser context: Lightpanda's default context holds a startup
13
+ * target that cannot navigate. Closing the session closes the context and stops the process.
14
+ *
15
+ * For an identity, Lightpanda keeps its own cookies in `<state>/browser/identities/<id>/
16
+ * lightpanda-cookies.json` (loaded at start, saved when the context closes). It never reads or
17
+ * writes the identity's Chrome profile, so read mode takes no runtime lock and runs no health
18
+ * check, challenge log, resource blocking or cache: those belong to the Chrome profile.
19
+ *
20
+ * Only the tools in `READ_MODE_TOOLS` run (the docs list them). Every other tool is refused
21
+ * before it reaches the browser, with the reason and a pointer to the Chrome engine.
22
+ */
23
+ /**
24
+ * The tools read mode runs: each was checked against Lightpanda 1.1 (nightly) through
25
+ * Patchright with local pages. Clicks follow links, but a link that opens a new tab
26
+ * (`target="_blank"`) does nothing there.
27
+ */
28
+ export declare const READ_MODE_TOOLS: ReadonlySet<string>;
29
+ /** Why read mode refuses this tool, or undefined when it runs it. */
30
+ export declare function readModeRefusal(tool: string): string | undefined;
31
+ /**
32
+ * How to install Lightpanda on this platform, for errors and `turno browser doctor`: one command
33
+ * a person runs on macOS (Homebrew) and Linux (Lightpanda's own nightly download), the reason
34
+ * there is none elsewhere.
35
+ */
36
+ export declare function lightpandaInstallHint(platform?: NodeJS.Platform, arch?: string): string;
37
+ export interface LightpandaInfo {
38
+ path: string;
39
+ version?: string;
40
+ }
41
+ /** The Lightpanda binary turno would run: `TURNO_LIGHTPANDA_PATH`, else `lightpanda` on PATH. */
42
+ export declare function findLightpanda(env?: NodeJS.ProcessEnv): LightpandaInfo | undefined;
43
+ /** The error when Lightpanda is missing, with the install command. */
44
+ export declare function lightpandaMissing(env: NodeJS.ProcessEnv): Error;
45
+ /** Where an identity's read mode keeps its cookies. */
46
+ export declare function lightpandaCookieJar(id: string, env: NodeJS.ProcessEnv): string;
47
+ export interface OrphanLightpanda {
48
+ pid: number;
49
+ /** The private folder of its sockets (`turno-lightpanda-*`), removed once it is gone. */
50
+ socketDir: string;
51
+ }
52
+ /**
53
+ * The `lightpanda serve` processes an earlier turno-browser-mcp left running: started by turno
54
+ * (a `cdp.sock` in a `turno-lightpanda-*` folder), for this identity's cookie jar (or with no
55
+ * jar, for a server without an identity), and with no parent left (reparented to init), so a
56
+ * Lightpanda that a live server drives is never touched. `"any"` finds them for every jar
57
+ * (`turno browser doctor`).
58
+ */
59
+ export declare function findOrphanLightpandas(jar: string | undefined | "any", table: ProcTable): OrphanLightpanda[];
60
+ export interface LightpandaSweep {
61
+ pid: number;
62
+ action: "exited" | "killed" | "survived";
63
+ }
64
+ /**
65
+ * Stops the Lightpanda a server killed with SIGKILL left behind (its exit handler never ran), as
66
+ * the Chrome sweep does for a profile: SIGTERM first, so it writes the identity's cookie jar,
67
+ * then SIGKILL. Runs when a server that may use read mode starts.
68
+ */
69
+ export declare function sweepOrphanLightpandas(jar: string | undefined, opts?: StopOptions & {
70
+ table?: ProcTable;
71
+ }): Promise<LightpandaSweep[]>;
72
+ export declare function createLightpandaEngine(): Engine;