turno-browser 0.3.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 (94) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/README.md +32 -3
  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 +29 -2
  8. package/dist/api.js +29 -2
  9. package/dist/argv.d.ts +16 -2
  10. package/dist/argv.js +100 -3
  11. package/dist/batch.d.ts +5 -0
  12. package/dist/batch.js +3 -3
  13. package/dist/bin/mcp.js +58 -1
  14. package/dist/captcha.d.ts +77 -0
  15. package/dist/captcha.js +333 -0
  16. package/dist/cdp-relay.d.ts +20 -0
  17. package/dist/cdp-relay.js +101 -0
  18. package/dist/chrome-features.d.ts +23 -0
  19. package/dist/chrome-features.js +44 -0
  20. package/dist/diagnose.d.ts +7 -0
  21. package/dist/diagnose.js +61 -6
  22. package/dist/doctor.d.ts +37 -3
  23. package/dist/doctor.js +230 -5
  24. package/dist/engine-attach.d.ts +27 -0
  25. package/dist/engine-attach.js +165 -0
  26. package/dist/engine-camoufox.d.ts +32 -0
  27. package/dist/engine-camoufox.js +270 -0
  28. package/dist/engine-lightpanda.d.ts +72 -0
  29. package/dist/engine-lightpanda.js +292 -0
  30. package/dist/engine.d.ts +63 -11
  31. package/dist/engine.js +104 -28
  32. package/dist/flows.d.ts +127 -0
  33. package/dist/flows.js +294 -0
  34. package/dist/governor.d.ts +42 -7
  35. package/dist/governor.js +82 -32
  36. package/dist/host.d.ts +17 -2
  37. package/dist/host.js +618 -41
  38. package/dist/human-input.d.ts +84 -0
  39. package/dist/human-input.js +443 -0
  40. package/dist/humanize.d.ts +123 -0
  41. package/dist/humanize.js +241 -0
  42. package/dist/identities.js +2 -0
  43. package/dist/idle-timer.d.ts +12 -0
  44. package/dist/idle-timer.js +25 -0
  45. package/dist/index.d.ts +8 -3
  46. package/dist/index.js +5 -1
  47. package/dist/lifecycle.d.ts +9 -1
  48. package/dist/lifecycle.js +9 -1
  49. package/dist/live-client.d.ts +22 -0
  50. package/dist/live-client.js +93 -0
  51. package/dist/live-page.d.ts +11 -0
  52. package/dist/live-page.js +143 -0
  53. package/dist/live-server.d.ts +173 -0
  54. package/dist/live-server.js +640 -0
  55. package/dist/live.d.ts +120 -0
  56. package/dist/live.js +203 -0
  57. package/dist/login-tool.d.ts +13 -0
  58. package/dist/login-tool.js +5 -1
  59. package/dist/login.d.ts +4 -1
  60. package/dist/login.js +11 -2
  61. package/dist/network-chrome.d.ts +74 -0
  62. package/dist/network-chrome.js +178 -0
  63. package/dist/network.d.ts +125 -0
  64. package/dist/network.js +263 -0
  65. package/dist/opt-in-settings.d.ts +69 -0
  66. package/dist/opt-in-settings.js +151 -0
  67. package/dist/recorder.d.ts +88 -0
  68. package/dist/recorder.js +538 -0
  69. package/dist/recordings.d.ts +116 -0
  70. package/dist/recordings.js +474 -0
  71. package/dist/redact.d.ts +7 -0
  72. package/dist/redact.js +18 -0
  73. package/dist/replay.d.ts +20 -0
  74. package/dist/replay.js +382 -0
  75. package/dist/reputation.d.ts +24 -2
  76. package/dist/reputation.js +63 -17
  77. package/dist/session-export.js +1 -1
  78. package/dist/session.d.ts +10 -2
  79. package/dist/session.js +10 -2
  80. package/dist/settings.d.ts +104 -2
  81. package/dist/settings.js +204 -6
  82. package/dist/sharing.d.ts +96 -0
  83. package/dist/sharing.js +269 -0
  84. package/dist/snippet.d.ts +8 -2
  85. package/dist/snippet.js +10 -4
  86. package/dist/tab-locks.d.ts +63 -0
  87. package/dist/tab-locks.js +179 -0
  88. package/dist/tools.d.ts +38 -0
  89. package/dist/tools.js +20 -1
  90. package/dist/tuning.d.ts +14 -0
  91. package/dist/tuning.js +9 -0
  92. package/dist/upstream.d.ts +11 -0
  93. package/npm-shrinkwrap.json +2 -2
  94. package/package.json +1 -1
package/dist/doctor.d.ts CHANGED
@@ -1,17 +1,26 @@
1
+ import { type ProcTable } from "turno-core/process";
2
+ import { type SecretStore } from "turno-core/secrets";
3
+ import { type LightpandaInfo } from "./engine-lightpanda.js";
4
+ import { type CamoufoxInfo, type PlaywrightCoreInfo } from "./engine-camoufox.js";
1
5
  /**
2
6
  * `turno browser doctor`: what a browser identity needs to work, one check per row,
3
7
  * each problem with the command that fixes it, like `turno doctor`.
4
8
  *
5
9
  * - Chrome: found, its version, and a smoke launch on a throwaway profile (headless).
6
10
  * - System: a headed Chrome needs the desktop session (macOS) or a display (Linux).
11
+ * - Engines: Lightpanda for read mode and Camoufox with the stock Playwright it runs on (both
12
+ * optional; a failure only when an identity uses them), and a Lightpanda an earlier server
13
+ * left running.
7
14
  * - Per identity: identity.json, who holds it (runtime lock and Chrome's profile lock), session
8
- * health, and challenges in the last 7 days.
15
+ * health, challenges in the last 7 days, and the opt-in network settings (`proxy`: whether
16
+ * the secret store has its credentials, never their value; `userAgent`).
9
17
  *
10
18
  * `--fix` removes runtime locks whose process is gone and stops a Chrome an earlier run left
11
- * behind on an identity's profile (the same sweep a server start does).
19
+ * behind on an identity's profile (the same sweep a server start does), and stops a Lightpanda
20
+ * an earlier server left running.
12
21
  */
13
22
  export interface DoctorCheck {
14
- /** "chrome", "system", "identities" or "identity <id>". */
23
+ /** "chrome", "system", "engines", "identities" or "identity <id>". */
15
24
  area: string;
16
25
  level: "ok" | "warn" | "fail" | "info";
17
26
  text: string;
@@ -37,8 +46,33 @@ export interface DoctorOptions {
37
46
  chrome?: (env: NodeJS.ProcessEnv, platform: NodeJS.Platform) => ChromeInfo | undefined;
38
47
  /** Starts and closes Chrome on a temporary profile; resolves with the milliseconds it took. */
39
48
  smoke?: (env: NodeJS.ProcessEnv) => Promise<number>;
49
+ /** Finds Lightpanda (tests inject one). */
50
+ lightpanda?: (env: NodeJS.ProcessEnv) => LightpandaInfo | undefined;
51
+ /** Finds Camoufox and the stock Playwright it runs on (tests inject them). */
52
+ camoufox?: (env: NodeJS.ProcessEnv) => CamoufoxInfo | undefined;
53
+ playwrightCore?: (env: NodeJS.ProcessEnv) => (PlaywrightCoreInfo & {
54
+ ok: boolean;
55
+ }) | undefined;
56
+ /** The secret store proxy credentials come from (tests inject a fake); default: this machine's. */
57
+ secrets?: SecretStore;
58
+ /** The process table, for a Lightpanda left running (tests inject one). */
59
+ procTable?: () => ProcTable | undefined;
60
+ /** The mcp.toml servers that run turno-browser-mcp for an identity (turno-cli reads mcp.toml). */
61
+ servers?: readonly ServedIdentity[];
40
62
  now?: Date;
41
63
  }
64
+ /** One mcp.toml server of an identity, as mcpd runs it. */
65
+ export interface ServedIdentity {
66
+ /** The server's name in mcp.toml (`browser-work`). */
67
+ name: string;
68
+ identity: string;
69
+ /** mcp.toml `exclusive`: one client session at a time. */
70
+ exclusive: boolean;
71
+ /** mcp.toml `scope`: with "session" every client session gets its own server. */
72
+ scope: string;
73
+ /** A `--sharing` flag in the server's args, which wins over identity.json. */
74
+ sharing?: string;
75
+ }
42
76
  export interface DoctorReport {
43
77
  checks: DoctorCheck[];
44
78
  /** What `--fix` did. */
package/dist/doctor.js CHANGED
@@ -3,8 +3,13 @@ import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node
3
3
  import { tmpdir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { browserPaths as paths } from "turno-core/paths";
6
+ import { readProcTable, signalProcess } from "turno-core/process";
7
+ import { secretStore } from "turno-core/secrets";
6
8
  import { readHealth } from "./health.js";
7
9
  import { identityDir, isValidIdentityId } from "./ids.js";
10
+ import { defaultChromeUserDataDir, parseAttachTarget, resolveAttachEndpoint } from "./engine-attach.js";
11
+ import { findLightpanda, findOrphanLightpandas, lightpandaCookieJar, lightpandaInstallHint, } from "./engine-lightpanda.js";
12
+ import { camoufoxInstallHint, camoufoxProfileDir, findCamoufox, findPlaywrightCore, playwrightCoreHint, } from "./engine-camoufox.js";
8
13
  import { findProfileChrome, sweepOrphan } from "./lifecycle.js";
9
14
  import { readChallenges, summarizeChallenges } from "./reputation.js";
10
15
  import { inUseMessage, readRuntimeLock, runtimeLockAlive, runtimeLockPath } from "./runtime-lock.js";
@@ -127,7 +132,27 @@ function settingsFix(id, problem) {
127
132
  ].find(([key]) => problem.startsWith(key))?.[1];
128
133
  return flag ? `turno identity set browser:${id} ${flag}` : undefined;
129
134
  }
130
- function identityChecks(id, env, now) {
135
+ /**
136
+ * A server that lets several client sessions in (`exclusive = false`, one server for all of
137
+ * them) on an identity that serves one session at a time: those sessions silently share one
138
+ * current tab, and one agent's navigation replaces the page another is reading.
139
+ */
140
+ function servingRows(id, settings, servers) {
141
+ const out = [];
142
+ for (const server of servers) {
143
+ if (server.identity !== id || server.exclusive || server.scope === "session")
144
+ continue;
145
+ if ((server.sharing ?? settings?.sharing ?? "session") !== "session")
146
+ continue;
147
+ out.push({
148
+ level: "warn",
149
+ text: `[server.${server.name}] in mcp.toml lets several sessions in (exclusive = false), but this identity serves one at a time ("sharing": "session"), so those sessions share one current tab`,
150
+ fix: `turno browser set ${id} --sharing tabs`,
151
+ });
152
+ }
153
+ return out;
154
+ }
155
+ function identityChecks(id, env, now, servers = []) {
131
156
  const area = `identity ${id}`;
132
157
  const out = [];
133
158
  const add = (c) => out.push({ area, ...c });
@@ -153,6 +178,12 @@ function identityChecks(id, env, now) {
153
178
  else {
154
179
  add({ level: "ok", text: `identity.json: ${describeSettings(settings)}` });
155
180
  }
181
+ if (settings)
182
+ for (const c of engineRows(id, settings, env))
183
+ add(c);
184
+ if (!problems.length)
185
+ for (const c of servingRows(id, settings, servers))
186
+ add(c);
156
187
  const lock = readRuntimeLock(id, env);
157
188
  const chrome = findProfileChrome(identityDir(id, env));
158
189
  if (lock && runtimeLockAlive(lock)) {
@@ -233,6 +264,195 @@ function identityChecks(id, env, now) {
233
264
  }
234
265
  return out;
235
266
  }
267
+ const ENABLE_DEBUGGING = "start Chrome, open chrome://inspect/#remote-debugging and turn remote debugging on";
268
+ /** What an identity's engine needs (identity.json `engine`, `attach`); none for Chrome. */
269
+ function engineRows(id, settings, env) {
270
+ if (settings.engine === "camoufox")
271
+ return [
272
+ {
273
+ level: "info",
274
+ text: `Camoufox: its own Firefox profile in ${camoufoxProfileDir(id, env)}, not the Chrome profile (sign-ins do not carry over)`,
275
+ fix: `turno browser set ${id} --engine chrome`,
276
+ },
277
+ ];
278
+ if (settings.engine === "lightpanda")
279
+ return [
280
+ {
281
+ level: "info",
282
+ text: `read mode on Lightpanda: its own cookies in ${lightpandaCookieJar(id, env)}, not the Chrome profile`,
283
+ fix: `turno browser set ${id} --engine chrome`,
284
+ },
285
+ ];
286
+ if (settings.attach === undefined)
287
+ return [];
288
+ const target = parseAttachTarget(settings.attach);
289
+ if ("error" in target)
290
+ return [];
291
+ try {
292
+ const endpoint = resolveAttachEndpoint(target, env);
293
+ return [
294
+ {
295
+ level: "ok",
296
+ text: `attach: a Chrome listens at ${endpoint.replace(/\/devtools\/.*$/, "")}; it asks you to allow each new connection, and the agent then sees every window of that profile`,
297
+ },
298
+ ];
299
+ }
300
+ catch {
301
+ const dir = target.kind === "dir" ? target.dir : target.kind === "auto" ? defaultChromeUserDataDir(env) : undefined;
302
+ return [
303
+ {
304
+ level: "warn",
305
+ text: `attach: no Chrome with remote debugging on${dir ? ` for ${dir}` : ""}, so the next tool call fails`,
306
+ manual: ENABLE_DEBUGGING,
307
+ },
308
+ ];
309
+ }
310
+ }
311
+ /** A `lightpanda serve` that a turno-browser-mcp started and that outlived it. */
312
+ function strayLightpandas(table) {
313
+ return table ? findOrphanLightpandas("any", table).map((o) => o.pid) : [];
314
+ }
315
+ function engineChecks(opts, env, ids) {
316
+ const out = [];
317
+ const area = "engines";
318
+ const lightpanda = (opts.lightpanda ?? findLightpanda)(env);
319
+ const users = ids.filter((id) => checkIdentitySettings(id, env).settings?.engine === "lightpanda");
320
+ const platform = opts.platform ?? process.platform;
321
+ const hint = lightpandaInstallHint(platform);
322
+ const install = platform === "darwin" || platform === "linux" ? { fix: hint } : { manual: hint };
323
+ if (lightpanda)
324
+ out.push({
325
+ area,
326
+ level: "ok",
327
+ text: `Lightpanda${lightpanda.version ? ` ${lightpanda.version}` : ""} at ${lightpanda.path} (read mode)`,
328
+ });
329
+ else if (users.length)
330
+ out.push({
331
+ area,
332
+ level: "fail",
333
+ text: `Lightpanda not found, and read mode needs it for ${users.map((u) => `browser:${u}`).join(", ")}`,
334
+ ...install,
335
+ });
336
+ else
337
+ out.push({
338
+ area,
339
+ level: "info",
340
+ text: "Lightpanda not found: only read mode (--engine lightpanda) needs it, and turno never downloads it",
341
+ ...install,
342
+ });
343
+ out.push(...camoufoxChecks(opts, env, ids, platform));
344
+ const stray = strayLightpandas((opts.procTable ?? readProcTable)());
345
+ if (stray.length)
346
+ out.push({
347
+ area,
348
+ level: "warn",
349
+ text: `Lightpanda pid ${stray.join(", ")} was left running by a server that is gone`,
350
+ fix: FIX,
351
+ auto: true,
352
+ });
353
+ return out;
354
+ }
355
+ /** Camoufox and the stock Playwright it runs on: a failure only when an identity uses the engine. */
356
+ function camoufoxChecks(opts, env, ids, platform) {
357
+ const out = [];
358
+ const area = "engines";
359
+ const users = ids.filter((id) => checkIdentitySettings(id, env).settings?.engine === "camoufox");
360
+ const needed = users.length > 0;
361
+ const who = users.map((u) => `browser:${u}`).join(", ");
362
+ const camoufox = (opts.camoufox ?? findCamoufox)(env);
363
+ const fix = camoufoxInstallHint(platform);
364
+ if (camoufox)
365
+ out.push({
366
+ area,
367
+ level: "ok",
368
+ text: `Camoufox${camoufox.version ? ` (${camoufox.version})` : ""} at ${camoufox.path}`,
369
+ });
370
+ else if (needed)
371
+ out.push({ area, level: "fail", text: `Camoufox not found, and the camoufox engine needs it for ${who}`, fix });
372
+ else
373
+ out.push({
374
+ area,
375
+ level: "info",
376
+ text: "Camoufox not found: only the camoufox engine (--engine camoufox) needs it, and turno never downloads it",
377
+ fix,
378
+ });
379
+ const pw = (opts.playwrightCore ?? findPlaywrightCore)(env);
380
+ const pwFix = playwrightCoreHint();
381
+ if (pw?.ok)
382
+ out.push({ area, level: "ok", text: `playwright-core ${pw.version} at ${pw.dir} (for Camoufox)` });
383
+ else if (pw)
384
+ out.push({
385
+ area,
386
+ level: needed ? "fail" : "warn",
387
+ text: `playwright-core ${pw.version} at ${pw.dir} is not the version patchright-core is built on, so Camoufox cannot run on it`,
388
+ fix: pwFix,
389
+ });
390
+ else if (needed)
391
+ out.push({
392
+ area,
393
+ level: "fail",
394
+ text: `playwright-core not found, and Camoufox runs on stock Playwright (patchright-core drives Chromium only): needed for ${who}`,
395
+ fix: pwFix,
396
+ });
397
+ else if (camoufox)
398
+ out.push({
399
+ area,
400
+ level: "info",
401
+ text: "playwright-core not found: the camoufox engine runs on stock Playwright, since patchright-core drives Chromium only",
402
+ fix: pwFix,
403
+ });
404
+ return out;
405
+ }
406
+ /**
407
+ * The opt-in network settings of an identity: where its traffic goes, and whether the secret
408
+ * store holds the proxy credentials (it asks whether the item exists, never reads its value).
409
+ */
410
+ async function networkRows(id, env, opts) {
411
+ const settings = checkIdentitySettings(id, env).settings;
412
+ const out = [];
413
+ const area = `identity ${id}`;
414
+ if (settings?.userAgent === "coherent")
415
+ out.push({
416
+ area,
417
+ level: "info",
418
+ text: "userAgent coherent: the installed Chrome's own user agent and client hints, with the identity's languages and time zone, checked at every launch",
419
+ });
420
+ const proxy = settings?.proxy;
421
+ if (!proxy)
422
+ return out;
423
+ out.push({
424
+ area,
425
+ level: "info",
426
+ text: `proxy ${proxy.server}: the proxy's operator sees where this identity goes (and the content of plain http:// pages), and sites see the proxy's address`,
427
+ });
428
+ const refs = [proxy.username, proxy.password].filter((r) => r?.startsWith("keychain:") === true);
429
+ if (!refs.length)
430
+ return out;
431
+ const store = opts.secrets ?? secretStore(env);
432
+ if (!store) {
433
+ out.push({
434
+ area,
435
+ level: "fail",
436
+ text: "the proxy credentials are in the secret store, and this machine has none",
437
+ manual: "install libsecret (secret-tool), or use a proxy without a password",
438
+ });
439
+ return out;
440
+ }
441
+ for (const ref of refs) {
442
+ const item = ref.slice("keychain:".length);
443
+ const has = await store.has(item).catch(() => false);
444
+ if (has)
445
+ out.push({ area, level: "ok", text: `proxy credentials: ${store.label} item "${item}" is there` });
446
+ else
447
+ out.push({
448
+ area,
449
+ level: "fail",
450
+ text: `proxy credentials: ${store.label} has no item "${item}", so the browser does not start`,
451
+ fix: `turno secret set ${item}`,
452
+ });
453
+ }
454
+ return out;
455
+ }
236
456
  /** Every identity id, including profile dirs with an identity.json only. */
237
457
  function identityIds(env) {
238
458
  try {
@@ -284,6 +504,7 @@ async function collect(opts, env, platform, now) {
284
504
  }
285
505
  checks.push(...systemChecks(env, platform));
286
506
  const ids = identityIds(env);
507
+ checks.push(...engineChecks(opts, env, ids));
287
508
  if (!ids.length)
288
509
  checks.push({
289
510
  area: "identities",
@@ -292,12 +513,16 @@ async function collect(opts, env, platform, now) {
292
513
  fix: "turno identity add browser:<id>",
293
514
  });
294
515
  for (const id of ids)
295
- checks.push(...identityChecks(id, env, now));
516
+ checks.push(...identityChecks(id, env, now, opts.servers), ...(await networkRows(id, env, opts)));
296
517
  return checks;
297
518
  }
298
- /** Repairs what is safe: stale runtime locks and a Chrome left running with no server. */
299
- async function repair(env) {
519
+ /** Repairs what is safe: stale runtime locks, a Chrome left running with no server, a stray Lightpanda. */
520
+ async function repair(env, opts) {
300
521
  const done = [];
522
+ for (const pid of strayLightpandas((opts.procTable ?? readProcTable)())) {
523
+ signalProcess(pid, "SIGTERM");
524
+ done.push(`stopped Lightpanda pid ${pid}, left running by a server that is gone`);
525
+ }
301
526
  for (const id of identityIds(env)) {
302
527
  const lock = readRuntimeLock(id, env);
303
528
  if (lock && !runtimeLockAlive(lock)) {
@@ -319,7 +544,7 @@ export async function runDoctor(opts = {}) {
319
544
  let checks = await collect(opts, env, platform, now);
320
545
  const fixed = [];
321
546
  if (opts.fix && checks.some((c) => c.auto && (c.level === "warn" || c.level === "fail"))) {
322
- fixed.push(...(await repair(env)));
547
+ fixed.push(...(await repair(env, opts)));
323
548
  checks = await collect({ ...opts, launch: false }, env, platform, now).then((again) => {
324
549
  // Keep the smoke launch result of the first pass: it does not change with a repair.
325
550
  const smoke = checks.find((c) => c.area === "chrome" && /^smoke launch/.test(c.text));
@@ -0,0 +1,27 @@
1
+ import type { Engine } from "./engine.js";
2
+ export type AttachTarget = {
3
+ kind: "auto";
4
+ } | {
5
+ kind: "dir";
6
+ dir: string;
7
+ } | {
8
+ kind: "endpoint";
9
+ url: string;
10
+ };
11
+ /** The target an `attach` value names, or a message saying what is wrong with it. */
12
+ export declare function parseAttachTarget(value: string): AttachTarget | {
13
+ error: string;
14
+ };
15
+ /** The user data dir of the installed Chrome's default profile, where Chrome writes `DevToolsActivePort`. */
16
+ export declare function defaultChromeUserDataDir(env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
17
+ /** `DevToolsActivePort`: the port on the first line, the browser's WebSocket path on the second. */
18
+ export declare function parseDevToolsActivePort(text: string): {
19
+ port: number;
20
+ path: string;
21
+ } | undefined;
22
+ /**
23
+ * Where to connect for a target, without connecting: for `auto` and a dir, the endpoint in its
24
+ * `DevToolsActivePort`. Throws with what the user should do when Chrome does not listen.
25
+ */
26
+ export declare function resolveAttachEndpoint(target: AttachTarget, env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform): string;
27
+ export declare function createAttachEngine(target: AttachTarget): Engine;
@@ -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;