turno-browser 0.3.0 → 0.5.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 (131) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +95 -123
  3. package/dist/act-model.d.ts +85 -0
  4. package/dist/act-model.js +117 -0
  5. package/dist/act.d.ts +37 -0
  6. package/dist/act.js +600 -0
  7. package/dist/api.d.ts +90 -2
  8. package/dist/api.js +41 -4
  9. package/dist/argv.d.ts +16 -2
  10. package/dist/argv.js +100 -3
  11. package/dist/background-state.d.ts +54 -0
  12. package/dist/background-state.js +97 -0
  13. package/dist/background.d.ts +69 -0
  14. package/dist/background.js +458 -0
  15. package/dist/batch.d.ts +5 -0
  16. package/dist/batch.js +3 -3
  17. package/dist/bin/mcp.js +103 -6
  18. package/dist/captcha.d.ts +77 -0
  19. package/dist/captcha.js +334 -0
  20. package/dist/cdp-relay.d.ts +20 -0
  21. package/dist/cdp-relay.js +101 -0
  22. package/dist/chrome-features.d.ts +23 -0
  23. package/dist/chrome-features.js +44 -0
  24. package/dist/cli/background.d.ts +11 -0
  25. package/dist/cli/background.js +132 -0
  26. package/dist/cli/commands.d.ts +16 -0
  27. package/dist/cli/commands.js +515 -0
  28. package/dist/cli/context.d.ts +75 -0
  29. package/dist/cli/context.js +44 -0
  30. package/dist/cli/do-background.d.ts +27 -0
  31. package/dist/cli/do-background.js +212 -0
  32. package/dist/cli/do.d.ts +85 -0
  33. package/dist/cli/do.js +558 -0
  34. package/dist/cli/flows.d.ts +28 -0
  35. package/dist/cli/flows.js +303 -0
  36. package/dist/cli/identity.d.ts +37 -0
  37. package/dist/cli/identity.js +906 -0
  38. package/dist/cli/live.d.ts +7 -0
  39. package/dist/cli/live.js +99 -0
  40. package/dist/cli/main.d.ts +16 -0
  41. package/dist/cli/main.js +171 -0
  42. package/dist/cli/secret.d.ts +4 -0
  43. package/dist/cli/secret.js +151 -0
  44. package/dist/cli/session.d.ts +6 -0
  45. package/dist/cli/session.js +106 -0
  46. package/dist/cli/setup.d.ts +7 -0
  47. package/dist/cli/setup.js +180 -0
  48. package/dist/cli/vault.d.ts +5 -0
  49. package/dist/cli/vault.js +192 -0
  50. package/dist/client.d.ts +82 -0
  51. package/dist/client.js +303 -0
  52. package/dist/diagnose.d.ts +7 -0
  53. package/dist/diagnose.js +61 -6
  54. package/dist/doctor.d.ts +37 -3
  55. package/dist/doctor.js +264 -6
  56. package/dist/engine-attach.d.ts +27 -0
  57. package/dist/engine-attach.js +165 -0
  58. package/dist/engine-camoufox.d.ts +32 -0
  59. package/dist/engine-camoufox.js +271 -0
  60. package/dist/engine-lightpanda.d.ts +72 -0
  61. package/dist/engine-lightpanda.js +293 -0
  62. package/dist/engine.d.ts +63 -11
  63. package/dist/engine.js +106 -29
  64. package/dist/flows.d.ts +127 -0
  65. package/dist/flows.js +294 -0
  66. package/dist/governor.d.ts +42 -7
  67. package/dist/governor.js +82 -32
  68. package/dist/health.js +2 -1
  69. package/dist/host.d.ts +38 -2
  70. package/dist/host.js +689 -52
  71. package/dist/human-input.d.ts +84 -0
  72. package/dist/human-input.js +448 -0
  73. package/dist/humanize.d.ts +123 -0
  74. package/dist/humanize.js +241 -0
  75. package/dist/identities.js +4 -1
  76. package/dist/idle-timer.d.ts +12 -0
  77. package/dist/idle-timer.js +25 -0
  78. package/dist/index.d.ts +13 -4
  79. package/dist/index.js +7 -1
  80. package/dist/lifecycle.d.ts +11 -1
  81. package/dist/lifecycle.js +11 -2
  82. package/dist/live-client.d.ts +22 -0
  83. package/dist/live-client.js +95 -0
  84. package/dist/live-page.d.ts +4 -0
  85. package/dist/live-page.js +144 -0
  86. package/dist/live-server.d.ts +173 -0
  87. package/dist/live-server.js +643 -0
  88. package/dist/live.d.ts +120 -0
  89. package/dist/live.js +204 -0
  90. package/dist/login-tool.d.ts +13 -0
  91. package/dist/login-tool.js +8 -3
  92. package/dist/login.d.ts +4 -1
  93. package/dist/login.js +12 -2
  94. package/dist/names.d.ts +28 -0
  95. package/dist/names.js +25 -0
  96. package/dist/network-chrome.d.ts +74 -0
  97. package/dist/network-chrome.js +178 -0
  98. package/dist/network.d.ts +125 -0
  99. package/dist/network.js +264 -0
  100. package/dist/opt-in-settings.d.ts +69 -0
  101. package/dist/opt-in-settings.js +152 -0
  102. package/dist/recorder.d.ts +88 -0
  103. package/dist/recorder.js +538 -0
  104. package/dist/recordings.d.ts +116 -0
  105. package/dist/recordings.js +474 -0
  106. package/dist/redact.d.ts +7 -0
  107. package/dist/redact.js +18 -0
  108. package/dist/replay.d.ts +20 -0
  109. package/dist/replay.js +383 -0
  110. package/dist/reputation.d.ts +24 -2
  111. package/dist/reputation.js +63 -17
  112. package/dist/runtime-lock.js +3 -2
  113. package/dist/session-export.js +1 -1
  114. package/dist/session.d.ts +10 -2
  115. package/dist/session.js +10 -2
  116. package/dist/settings.d.ts +104 -2
  117. package/dist/settings.js +204 -6
  118. package/dist/sharing.d.ts +96 -0
  119. package/dist/sharing.js +269 -0
  120. package/dist/snippet.d.ts +8 -2
  121. package/dist/snippet.js +10 -4
  122. package/dist/tab-locks.d.ts +63 -0
  123. package/dist/tab-locks.js +179 -0
  124. package/dist/tools.d.ts +38 -0
  125. package/dist/tools.js +20 -1
  126. package/dist/tuning.d.ts +14 -0
  127. package/dist/tuning.js +9 -0
  128. package/dist/upstream.d.ts +11 -0
  129. package/dist/vault.js +5 -4
  130. package/npm-shrinkwrap.json +6 -5
  131. package/package.json +13 -7
package/dist/api.d.ts CHANGED
@@ -6,10 +6,16 @@ import { assertIdentityId, identityDir } from "./ids.js";
6
6
  import { loginIdentity } from "./login.js";
7
7
  import { reputationReport } from "./reputation.js";
8
8
  import { exportSession, importSession, readSessionExport } from "./session-export.js";
9
+ import { flowsDir, listFlows, readFlow, removeFlow } from "./flows.js";
10
+ import { listRecordings, openTraceViewer, recordingsDir, traceViewerCommand } from "./recordings.js";
11
+ import { replayFlow } from "./replay.js";
12
+ import { liveLink, livePause, liveResume, liveStatus } from "./live-client.js";
9
13
  import { parseTotpSecret } from "./totp.js";
10
14
  import { vaultAdd, vaultClear, vaultList, vaultRemove, vaultSetSubmit } from "./vault.js";
11
15
  import { checkIdentitySettings, identitySettingsPath, writeIdentitySettings } from "./settings.js";
12
16
  import { manifestSnippet } from "./snippet.js";
17
+ import { backgroundStatus, openBackgroundSession, startBackground, stopBackground } from "./client.js";
18
+ import { browserCli } from "./cli/commands.js";
13
19
  /**
14
20
  * The contract between turno-browser and turno-cli. turno-cli installs this package
15
21
  * apart, types it with `import type` (erased at build, so the package stays optional) and,
@@ -24,7 +30,7 @@ import { manifestSnippet } from "./snippet.js";
24
30
  */
25
31
  export declare const API_VERSION: Readonly<{
26
32
  readonly major: 1;
27
- readonly minor: 2;
33
+ readonly minor: 12;
28
34
  }>;
29
35
  /** What `API_VERSION` looks like to a reader that does not know this package's version. */
30
36
  export interface ApiVersion {
@@ -33,8 +39,71 @@ export interface ApiVersion {
33
39
  }
34
40
  /**
35
41
  * The functions turno-cli calls: identities, their settings, login, doctor, reputation, bench
36
- * (1.1) the credential vault and (1.2) session export and import.
42
+ * (1.1) the credential vault, (1.2) session export and import, (1.3) the `humanize` key of
43
+ * identity.json (no new member: `writeIdentitySettings` accepts it, an older package refuses it)
44
+ * (1.4) the `sharing` key of identity.json and `manifestSnippet(id, { sharing })`, (1.5) the
45
+ * `engine` and `attach` keys of identity.json and the engine checks of `runDoctor`, (1.6) the
46
+ * `record` key of identity.json, saved flows, replay and recordings, (1.7) the `act` and
47
+ * `captcha` keys of identity.json (no new member) and `solved` in each site of
48
+ * `reputationReport`, (1.8) the `tabLocks` key of identity.json and
49
+ * `runDoctor({ servers })`, the mcp.toml servers of each identity, (1.9) the `live` key of
50
+ * identity.json and the live view of a running server (status, pause, resume, a one-time link),
51
+ * and (1.10) the `userAgent` and `proxy` keys and the `"camoufox"` engine of identity.json, and
52
+ * the Camoufox and network checks of `runDoctor` (no new member: an older package refuses them),
53
+ * and (1.11) the background server of an identity: start, status, stop, and its sessions.
54
+ * and (1.12) `cli`, the identity commands themselves (`turno-browser <cmd>`), which turno-cli runs
55
+ * as `turno browser <cmd>` and `turno identity ... browser:<id>` with a host of its own.
37
56
  */
57
+ declare const functions: {
58
+ ENGINES: readonly ["chrome-headed", "chrome-headless", "chrome-baseline", "firefox"];
59
+ engineId: typeof engineId;
60
+ listIdentities: typeof listIdentities;
61
+ addIdentity: typeof addIdentity;
62
+ removeIdentity: typeof removeIdentity;
63
+ identityExists: typeof identityExists;
64
+ identityDir: typeof identityDir;
65
+ identitySettingsPath: typeof identitySettingsPath;
66
+ isInUse: typeof isInUse;
67
+ inUseBy: typeof inUseBy;
68
+ assertIdentityId: typeof assertIdentityId;
69
+ manifestSnippet: typeof manifestSnippet;
70
+ loginIdentity: typeof loginIdentity;
71
+ checkIdentitySettings: typeof checkIdentitySettings;
72
+ writeIdentitySettings: typeof writeIdentitySettings;
73
+ readHealth: typeof readHealth;
74
+ runDoctor: typeof runDoctor;
75
+ reputationReport: typeof reputationReport;
76
+ runBench: typeof runBench;
77
+ formatBenchTable: typeof formatBenchTable;
78
+ vaultAdd: typeof vaultAdd;
79
+ vaultList: typeof vaultList;
80
+ vaultRemove: typeof vaultRemove;
81
+ vaultClear: typeof vaultClear;
82
+ vaultSetSubmit: typeof vaultSetSubmit;
83
+ parseTotpSecret: typeof parseTotpSecret;
84
+ exportSession: typeof exportSession;
85
+ readSessionExport: typeof readSessionExport;
86
+ importSession: typeof importSession;
87
+ flowsDir: typeof flowsDir;
88
+ listFlows: typeof listFlows;
89
+ readFlow: typeof readFlow;
90
+ removeFlow: typeof removeFlow;
91
+ replayFlow: typeof replayFlow;
92
+ listRecordings: typeof listRecordings;
93
+ recordingsDir: typeof recordingsDir;
94
+ traceViewerCommand: typeof traceViewerCommand;
95
+ openTraceViewer: typeof openTraceViewer;
96
+ liveStatus: typeof liveStatus;
97
+ livePause: typeof livePause;
98
+ liveResume: typeof liveResume;
99
+ liveLink: typeof liveLink;
100
+ startBackground: typeof startBackground;
101
+ backgroundStatus: typeof backgroundStatus;
102
+ stopBackground: typeof stopBackground;
103
+ openBackgroundSession: typeof openBackgroundSession;
104
+ };
105
+ /** The functions the identity commands call; tests of the commands pass fakes of them. */
106
+ export type BrowserFunctions = typeof functions;
38
107
  export declare const api: Readonly<{
39
108
  ENGINES: readonly ["chrome-headed", "chrome-headless", "chrome-baseline", "firefox"];
40
109
  engineId: typeof engineId;
@@ -65,5 +134,24 @@ export declare const api: Readonly<{
65
134
  exportSession: typeof exportSession;
66
135
  readSessionExport: typeof readSessionExport;
67
136
  importSession: typeof importSession;
137
+ flowsDir: typeof flowsDir;
138
+ listFlows: typeof listFlows;
139
+ readFlow: typeof readFlow;
140
+ removeFlow: typeof removeFlow;
141
+ replayFlow: typeof replayFlow;
142
+ listRecordings: typeof listRecordings;
143
+ recordingsDir: typeof recordingsDir;
144
+ traceViewerCommand: typeof traceViewerCommand;
145
+ openTraceViewer: typeof openTraceViewer;
146
+ liveStatus: typeof liveStatus;
147
+ livePause: typeof livePause;
148
+ liveResume: typeof liveResume;
149
+ liveLink: typeof liveLink;
150
+ startBackground: typeof startBackground;
151
+ backgroundStatus: typeof backgroundStatus;
152
+ stopBackground: typeof stopBackground;
153
+ openBackgroundSession: typeof openBackgroundSession;
154
+ cli: typeof browserCli;
68
155
  }>;
69
156
  export type BrowserApi = typeof api;
157
+ export {};
package/dist/api.js CHANGED
@@ -6,10 +6,16 @@ import { assertIdentityId, identityDir } from "./ids.js";
6
6
  import { loginIdentity } from "./login.js";
7
7
  import { reputationReport } from "./reputation.js";
8
8
  import { exportSession, importSession, readSessionExport } from "./session-export.js";
9
+ import { flowsDir, listFlows, readFlow, removeFlow } from "./flows.js";
10
+ import { listRecordings, openTraceViewer, recordingsDir, traceViewerCommand } from "./recordings.js";
11
+ import { replayFlow } from "./replay.js";
12
+ import { liveLink, livePause, liveResume, liveStatus } from "./live-client.js";
9
13
  import { parseTotpSecret } from "./totp.js";
10
14
  import { vaultAdd, vaultClear, vaultList, vaultRemove, vaultSetSubmit } from "./vault.js";
11
15
  import { checkIdentitySettings, identitySettingsPath, writeIdentitySettings } from "./settings.js";
12
16
  import { manifestSnippet } from "./snippet.js";
17
+ import { backgroundStatus, openBackgroundSession, startBackground, stopBackground } from "./client.js";
18
+ import { browserCli } from "./cli/commands.js";
13
19
  /**
14
20
  * The contract between turno-browser and turno-cli. turno-cli installs this package
15
21
  * apart, types it with `import type` (erased at build, so the package stays optional) and,
@@ -22,12 +28,25 @@ import { manifestSnippet } from "./snippet.js";
22
28
  *
23
29
  * `test/api.test.ts` lists the members, so a change here cannot ship without the version.
24
30
  */
25
- export const API_VERSION = Object.freeze({ major: 1, minor: 2 });
31
+ export const API_VERSION = Object.freeze({ major: 1, minor: 12 });
26
32
  /**
27
33
  * The functions turno-cli calls: identities, their settings, login, doctor, reputation, bench
28
- * (1.1) the credential vault and (1.2) session export and import.
34
+ * (1.1) the credential vault, (1.2) session export and import, (1.3) the `humanize` key of
35
+ * identity.json (no new member: `writeIdentitySettings` accepts it, an older package refuses it)
36
+ * (1.4) the `sharing` key of identity.json and `manifestSnippet(id, { sharing })`, (1.5) the
37
+ * `engine` and `attach` keys of identity.json and the engine checks of `runDoctor`, (1.6) the
38
+ * `record` key of identity.json, saved flows, replay and recordings, (1.7) the `act` and
39
+ * `captcha` keys of identity.json (no new member) and `solved` in each site of
40
+ * `reputationReport`, (1.8) the `tabLocks` key of identity.json and
41
+ * `runDoctor({ servers })`, the mcp.toml servers of each identity, (1.9) the `live` key of
42
+ * identity.json and the live view of a running server (status, pause, resume, a one-time link),
43
+ * and (1.10) the `userAgent` and `proxy` keys and the `"camoufox"` engine of identity.json, and
44
+ * the Camoufox and network checks of `runDoctor` (no new member: an older package refuses them),
45
+ * and (1.11) the background server of an identity: start, status, stop, and its sessions.
46
+ * and (1.12) `cli`, the identity commands themselves (`turno-browser <cmd>`), which turno-cli runs
47
+ * as `turno browser <cmd>` and `turno identity ... browser:<id>` with a host of its own.
29
48
  */
30
- export const api = Object.freeze({
49
+ const functions = {
31
50
  ENGINES,
32
51
  engineId,
33
52
  listIdentities,
@@ -57,5 +76,23 @@ export const api = Object.freeze({
57
76
  exportSession,
58
77
  readSessionExport,
59
78
  importSession,
60
- });
79
+ flowsDir,
80
+ listFlows,
81
+ readFlow,
82
+ removeFlow,
83
+ replayFlow,
84
+ listRecordings,
85
+ recordingsDir,
86
+ traceViewerCommand,
87
+ openTraceViewer,
88
+ liveStatus,
89
+ livePause,
90
+ liveResume,
91
+ liveLink,
92
+ startBackground,
93
+ backgroundStatus,
94
+ stopBackground,
95
+ openBackgroundSession,
96
+ };
97
+ export const api = Object.freeze({ ...functions, cli: browserCli });
61
98
  //# sourceMappingURL=api.js.map
package/dist/argv.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import type { EngineFlags } from "./engine.js";
2
+ import type { LiveFlags } from "./live.js";
1
3
  import type { TuningFlags } from "./tuning.js";
2
4
  /**
3
5
  * Turns `turno-browser-mcp [--identity <id>] [playwright-mcp flags]` into the argv for the
@@ -16,8 +18,9 @@ import type { TuningFlags } from "./tuning.js";
16
18
  * Headed mode and `viewport: null` are already the program's defaults for headed runs, so
17
19
  * nothing is added for them; no init scripts are ever added.
18
20
  *
19
- * The tab governor and background throttling flags (`TUNING_FLAGS`) are turno's: they are
20
- * taken out here and win over identity.json.
21
+ * The tab governor, background throttling, humanize and sharing flags (`TUNING_FLAGS`) are turno's: they are
22
+ * taken out here and win over identity.json. So are `--engine <chrome|lightpanda|camoufox>` and `--attach <target>` (`engine.ts`); with either and
23
+ * no identity there is no Chrome profile to create. So are `--live` and `--live-wait <duration>` (`live.ts`), which need an identity.
21
24
  *
22
25
  * An identity holds saved logins, so serving it over HTTP (`--port`, `--host`) lets any local
23
26
  * process drive a signed-in browser without the stdio pipe or mcpd's token. That needs
@@ -38,6 +41,10 @@ export interface BuiltArgv {
38
41
  };
39
42
  /** turno's own flags for the host, when any was given. */
40
43
  tuning?: TuningFlags;
44
+ /** `--engine` and `--attach`, when given. */
45
+ engineFlags?: EngineFlags;
46
+ /** `--live` and `--live-wait`, when given. */
47
+ live?: LiveFlags;
41
48
  }
42
49
  /** The keys of the Playwright MCP config file that turno sets (pinned by the contract test). */
43
50
  export interface PlaywrightMcpConfig {
@@ -61,12 +68,19 @@ export declare const TUNING_FLAGS: {
61
68
  readonly "--park-after": "<duration>";
62
69
  readonly "--close-after": "<duration>";
63
70
  readonly "--background-throttling": "";
71
+ readonly "--humanize": "<off|light|full|adaptive>";
72
+ readonly "--sharing": "<session|tabs>";
64
73
  };
65
74
  /** Removes turno's tuning flags (`TUNING_FLAGS`) from args and returns their values. */
66
75
  export declare function extractTuning(args: string[]): {
67
76
  tuning?: TuningFlags;
68
77
  rest: string[];
69
78
  };
79
+ /** Removes `--engine` and `--attach` from args and returns their values, checked. */
80
+ export declare function extractEngine(args: string[]): {
81
+ engineFlags?: EngineFlags;
82
+ rest: string[];
83
+ };
70
84
  /** Removes `--identity <id>` / `--identity=<id>` from args and returns the id. */
71
85
  export declare function extractIdentity(args: string[]): {
72
86
  identity?: string;
package/dist/argv.js CHANGED
@@ -2,7 +2,10 @@ import { mkdtempSync } from "node:fs";
2
2
  import { tmpdir } from "node:os";
3
3
  import { join } from "node:path";
4
4
  import { browserPaths as paths } from "turno-core/paths";
5
+ import { HUMANIZE_LEVELS } from "./humanize.js";
5
6
  import { assertIdentityId, identityDir } from "./identities.js";
7
+ import { MAX_LIVE_WAIT_MS, MIN_LIVE_WAIT_MS } from "./settings.js";
8
+ import { parseAttachTarget } from "./engine-attach.js";
6
9
  import { parseDuration } from "./units.js";
7
10
  /** How long Chrome stays open without a tool call, unless TURNO_BROWSER_IDLE says otherwise. */
8
11
  export const DEFAULT_BROWSER_IDLE_MS = 15 * 60_000;
@@ -69,6 +72,8 @@ export const TUNING_FLAGS = {
69
72
  "--park-after": "<duration>",
70
73
  "--close-after": "<duration>",
71
74
  "--background-throttling": "",
75
+ "--humanize": "<off|light|full|adaptive>",
76
+ "--sharing": "<session|tabs>",
72
77
  };
73
78
  function tuningValue(flag, value, out) {
74
79
  if (flag === "--max-tabs") {
@@ -76,11 +81,21 @@ function tuningValue(flag, value, out) {
76
81
  throw new Error(`--max-tabs must be a whole number from 0 (no cap) to 100, not "${value}"`);
77
82
  out.maxTabs = Number(value);
78
83
  }
84
+ else if (flag === "--humanize") {
85
+ if (!HUMANIZE_LEVELS.includes(value))
86
+ throw new Error(`--humanize must be ${HUMANIZE_LEVELS.join(", ")}, not "${value}"`);
87
+ out.humanize = value;
88
+ }
79
89
  else if (flag === "--popups") {
80
90
  if (value !== "close" && value !== "keep")
81
91
  throw new Error(`--popups must be "close" or "keep", not "${value}"`);
82
92
  out.popups = value;
83
93
  }
94
+ else if (flag === "--sharing") {
95
+ if (value !== "session" && value !== "tabs")
96
+ throw new Error(`--sharing must be "session" (one agent session at a time) or "tabs", not "${value}"`);
97
+ out.sharing = value;
98
+ }
84
99
  else {
85
100
  const ms = parseDuration(value);
86
101
  if (ms === undefined)
@@ -124,6 +139,70 @@ export function extractTuning(args) {
124
139
  }
125
140
  return any ? { tuning: out, rest } : { rest };
126
141
  }
142
+ /** The value of `--flag v` or `--flag=v` at `args[i]`, and how many items it took. */
143
+ function valueAt(args, i, flag) {
144
+ const a = args[i];
145
+ if (a.startsWith(`${flag}=`))
146
+ return { value: a.slice(flag.length + 1), used: 1 };
147
+ if (a !== flag)
148
+ return undefined;
149
+ const v = args[i + 1];
150
+ if (v === undefined || v.startsWith("--"))
151
+ throw new Error(`${flag} needs a value`);
152
+ return { value: v, used: 2 };
153
+ }
154
+ /** Removes `--engine` and `--attach` from args and returns their values, checked. */
155
+ export function extractEngine(args) {
156
+ const rest = [];
157
+ const out = {};
158
+ for (let i = 0; i < args.length; i++) {
159
+ const engine = valueAt(args, i, "--engine");
160
+ const attach = engine ? undefined : valueAt(args, i, "--attach");
161
+ if (engine) {
162
+ if (engine.value !== "chrome" && engine.value !== "lightpanda" && engine.value !== "camoufox")
163
+ throw new Error(`--engine must be "chrome", "lightpanda" (read mode) or "camoufox", not "${engine.value}"`);
164
+ out.engine = engine.value;
165
+ i += engine.used - 1;
166
+ }
167
+ else if (attach) {
168
+ const target = parseAttachTarget(attach.value);
169
+ if ("error" in target)
170
+ throw new Error(target.error.replace(/^attach/, "--attach"));
171
+ out.attach = attach.value.trim();
172
+ i += attach.used - 1;
173
+ }
174
+ else
175
+ rest.push(args[i]);
176
+ }
177
+ if ((out.engine === "lightpanda" || out.engine === "camoufox") && out.attach !== undefined)
178
+ throw new Error(`--attach and --engine ${out.engine} do not go together: pick one`);
179
+ return out.engine !== undefined || out.attach !== undefined ? { engineFlags: out, rest } : { rest };
180
+ }
181
+ /** Removes `--live` and `--live-wait <duration>` from args and returns their values, checked. */
182
+ function extractLive(args) {
183
+ const rest = [];
184
+ const out = {};
185
+ for (let i = 0; i < args.length; i++) {
186
+ const a = args[i];
187
+ if (a === "--live") {
188
+ out.live = true;
189
+ continue;
190
+ }
191
+ if (a.startsWith("--live="))
192
+ throw new Error("--live takes no value");
193
+ const wait = valueAt(args, i, "--live-wait");
194
+ if (!wait) {
195
+ rest.push(a);
196
+ continue;
197
+ }
198
+ const ms = parseDuration(wait.value);
199
+ if (ms === undefined || ms < MIN_LIVE_WAIT_MS || ms > MAX_LIVE_WAIT_MS)
200
+ throw new Error(`--live-wait must be a duration from "5s" to "30m", like "2m", not "${wait.value}"`);
201
+ out.waitMs = ms;
202
+ i += wait.used - 1;
203
+ }
204
+ return out.live !== undefined || out.waitMs !== undefined ? { live: out, rest } : { rest };
205
+ }
127
206
  /** Removes `--identity <id>` / `--identity=<id>` from args and returns the id. */
128
207
  export function extractIdentity(args) {
129
208
  const rest = [];
@@ -154,12 +233,28 @@ function defaultTempDir() {
154
233
  export function buildArgv(rawArgs, options = {}) {
155
234
  const env = options.env ?? process.env;
156
235
  const { identity, rest: afterIdentity } = extractIdentity(rawArgs);
157
- const { tuning, rest } = extractTuning(afterIdentity);
236
+ const { tuning, rest: afterTuning } = extractTuning(afterIdentity);
237
+ const { engineFlags, rest: afterEngine } = extractEngine(afterTuning);
238
+ const { live, rest } = extractLive(afterEngine);
239
+ // The live view's control socket and live.json belong to the identity's state folder.
240
+ if (live && identity === undefined)
241
+ throw new Error("--live and --live-wait apply only with --identity");
158
242
  const allowHttp = rest.includes(ALLOW_HTTP_IDENTITY);
159
243
  const args = rest.filter((a) => a !== ALLOW_HTTP_IDENTITY);
160
244
  guardHttp(args, identity, allowHttp);
161
245
  const external = hasAny(args, EXTERNAL_BROWSER);
162
- const out = { args, ...(tuning ? { tuning } : {}) };
246
+ const out = {
247
+ args,
248
+ ...(tuning ? { tuning } : {}),
249
+ ...(engineFlags ? { engineFlags } : {}),
250
+ ...(live ? { live } : {}),
251
+ };
252
+ const otherEngine = engineFlags?.engine === "lightpanda" || engineFlags?.engine === "camoufox" || engineFlags?.attach !== undefined;
253
+ if (otherEngine) {
254
+ const clash = ["--isolated", "--user-data-dir", ...EXTERNAL_BROWSER].find((f) => hasFlag(args, f));
255
+ if (clash)
256
+ throw new Error(`${engineFlags?.attach !== undefined ? "--attach" : `--engine ${engineFlags?.engine}`} cannot be combined with ${clash}`);
257
+ }
163
258
  if (identity !== undefined) {
164
259
  const clash = ["--user-data-dir", "--isolated", ...EXTERNAL_BROWSER].find((f) => hasFlag(args, f));
165
260
  if (clash)
@@ -172,7 +267,9 @@ export function buildArgv(rawArgs, options = {}) {
172
267
  out.tempDir ??= (options.makeTempDir ?? defaultTempDir)();
173
268
  return out.tempDir;
174
269
  };
175
- if (!external && !hasFlag(args, "--user-data-dir") && !hasFlag(args, "--isolated")) {
270
+ // Read mode, Camoufox and attach mode without an identity start no Chrome, so they need no profile.
271
+ const needsProfile = !(otherEngine && identity === undefined);
272
+ if (!external && needsProfile && !hasFlag(args, "--user-data-dir") && !hasFlag(args, "--isolated")) {
176
273
  out.userDataDir = identity !== undefined ? identityDir(identity, env) : join(makeTemp(), "profile");
177
274
  args.push("--user-data-dir", out.userDataDir);
178
275
  }
@@ -0,0 +1,54 @@
1
+ import type { IdentityRef } from "./engine.js";
2
+ /**
3
+ * Where the background server of an identity (`turno-browser-mcp --identity <id> --background`)
4
+ * says it runs, and the rule it keeps with the other servers of that identity.
5
+ *
6
+ * Everything lives in `<state>/browser/identities/<id>/background/`, a folder only the user can
7
+ * enter (0700): `server.json` (pid, address, version, mode 600), the Unix socket `sock`, or on a
8
+ * system without one, `token` (the per-server bearer token of the loopback port, mode 600), and
9
+ * `server.log`, where a server started by the client module writes its output.
10
+ *
11
+ * The rule: while a background server runs, it is the one owner of the identity's browser. A
12
+ * stdio server of the same identity refuses every call that would launch the browser, with a
13
+ * message that names the background server and how to stop it, and a background server does not
14
+ * start while another process holds the identity's runtime lock (its Chrome is open). Calls are
15
+ * never forwarded from one server to the other: either way there is one Chrome, never a wait.
16
+ */
17
+ export interface BackgroundState {
18
+ v: 1;
19
+ pid: number;
20
+ identity: string;
21
+ /** turno-browser's version. */
22
+ version: string;
23
+ startedAt: string;
24
+ /** Exits after this long without a request; 0 never. */
25
+ idleMs: number;
26
+ /** Absent while the server starts; then where it listens. */
27
+ transport?: "socket" | "tcp";
28
+ /** `transport: "socket"`: the Unix socket. */
29
+ socket?: string;
30
+ /** `transport: "tcp"`: the loopback port, and the file that holds its bearer token. */
31
+ port?: number;
32
+ tokenFile?: string;
33
+ }
34
+ export declare function backgroundDir(id: string, env?: NodeJS.ProcessEnv): string;
35
+ export declare function backgroundStatePath(id: string, env?: NodeJS.ProcessEnv): string;
36
+ export declare function backgroundSocketPath(id: string, env?: NodeJS.ProcessEnv): string;
37
+ export declare function backgroundTokenPath(id: string, env?: NodeJS.ProcessEnv): string;
38
+ export declare function backgroundLogPath(id: string, env?: NodeJS.ProcessEnv): string;
39
+ /** The state file's content, undefined when there is none or it is not one. */
40
+ export declare function readBackgroundState(id: string, env?: NodeJS.ProcessEnv): BackgroundState | undefined;
41
+ /**
42
+ * True while the state's process runs and, when the process table can be read, is a background
43
+ * server (a pid the system gave to another program after a kill is not one).
44
+ */
45
+ export declare function backgroundAlive(state: BackgroundState): boolean;
46
+ /** Removes what a background server that is gone left behind (state, socket, token). */
47
+ export declare function removeBackgroundFiles(id: string, env?: NodeJS.ProcessEnv): void;
48
+ /** The running background server of the identity, undefined when none runs (a stale state is removed). */
49
+ export declare function liveBackground(id: string, env?: NodeJS.ProcessEnv): BackgroundState | undefined;
50
+ /**
51
+ * Throws when another process runs the identity's background server: called before a server
52
+ * launches the identity's browser. The background server itself passes.
53
+ */
54
+ export declare function refuseWhileBackground(identity: IdentityRef): void;
@@ -0,0 +1,97 @@
1
+ import { readFileSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { pidAlive, readProcTable } from "turno-core/process";
4
+ import { IdentityError, identityStateDir } from "./ids.js";
5
+ export function backgroundDir(id, env = process.env) {
6
+ return join(identityStateDir(id, env), "background");
7
+ }
8
+ export function backgroundStatePath(id, env = process.env) {
9
+ return join(backgroundDir(id, env), "server.json");
10
+ }
11
+ export function backgroundSocketPath(id, env = process.env) {
12
+ return join(backgroundDir(id, env), "sock");
13
+ }
14
+ export function backgroundTokenPath(id, env = process.env) {
15
+ return join(backgroundDir(id, env), "token");
16
+ }
17
+ export function backgroundLogPath(id, env = process.env) {
18
+ return join(backgroundDir(id, env), "server.log");
19
+ }
20
+ function isState(v, id) {
21
+ const s = v;
22
+ if (typeof s !== "object" || s === null || s.v !== 1 || s.identity !== id)
23
+ return false;
24
+ if (typeof s.pid !== "number" || !Number.isSafeInteger(s.pid) || s.pid <= 0)
25
+ return false;
26
+ if (typeof s.startedAt !== "string" || typeof s.version !== "string" || typeof s.idleMs !== "number")
27
+ return false;
28
+ if (s.transport === "socket")
29
+ return typeof s.socket === "string";
30
+ if (s.transport === "tcp")
31
+ return typeof s.port === "number" && typeof s.tokenFile === "string";
32
+ return s.transport === undefined;
33
+ }
34
+ /** The state file's content, undefined when there is none or it is not one. */
35
+ export function readBackgroundState(id, env = process.env) {
36
+ try {
37
+ const v = JSON.parse(readFileSync(backgroundStatePath(id, env), "utf8"));
38
+ return isState(v, id) ? v : undefined;
39
+ }
40
+ catch {
41
+ return undefined;
42
+ }
43
+ }
44
+ /**
45
+ * True while the state's process runs and, when the process table can be read, is a background
46
+ * server (a pid the system gave to another program after a kill is not one).
47
+ */
48
+ export function backgroundAlive(state) {
49
+ if (state.pid === process.pid)
50
+ return true;
51
+ if (!pidAlive(state.pid))
52
+ return false;
53
+ const command = readProcTable()?.get(state.pid)?.command;
54
+ return command === undefined || command.includes("--background");
55
+ }
56
+ /** Removes what a background server that is gone left behind (state, socket, token). */
57
+ export function removeBackgroundFiles(id, env = process.env) {
58
+ for (const file of [backgroundStatePath(id, env), backgroundSocketPath(id, env), backgroundTokenPath(id, env)])
59
+ rmSync(file, { force: true });
60
+ }
61
+ /** The running background server of the identity, undefined when none runs (a stale state is removed). */
62
+ export function liveBackground(id, env = process.env) {
63
+ const state = readBackgroundState(id, env);
64
+ if (!state)
65
+ return undefined;
66
+ if (backgroundAlive(state))
67
+ return state;
68
+ if (readBackgroundState(id, env)?.pid === state.pid)
69
+ removeBackgroundFiles(id, env);
70
+ return undefined;
71
+ }
72
+ function duration(ms) {
73
+ if (ms % 3_600_000 === 0)
74
+ return `${ms / 3_600_000}h`;
75
+ if (ms % 60_000 === 0)
76
+ return `${ms / 60_000}m`;
77
+ return `${Math.round(ms / 1000)}s`;
78
+ }
79
+ /** Why a server other than the background one may not launch the identity's browser now. */
80
+ function backgroundOwnsMessage(id, state) {
81
+ const idle = state.idleMs > 0 ? `, or wait: it exits after ${duration(state.idleMs)} without a request` : "";
82
+ return (`browser identity "${id}" is served by its background server (pid ${state.pid}) since ${state.startedAt}, ` +
83
+ `which owns the identity's browser while it runs. Stop it with \`turno-browser background stop ${id}\` ` +
84
+ `(or \`kill ${state.pid}\`; it closes its Chrome first)${idle}; ` +
85
+ "then try again.");
86
+ }
87
+ /**
88
+ * Throws when another process runs the identity's background server: called before a server
89
+ * launches the identity's browser. The background server itself passes.
90
+ */
91
+ export function refuseWhileBackground(identity) {
92
+ const state = readBackgroundState(identity.id, identity.env);
93
+ if (!state || state.pid === process.pid || !backgroundAlive(state))
94
+ return;
95
+ throw new IdentityError(backgroundOwnsMessage(identity.id, state));
96
+ }
97
+ //# sourceMappingURL=background-state.js.map
@@ -0,0 +1,69 @@
1
+ import { type BackgroundState } from "./background-state.js";
2
+ import type { IdentityRef } from "./engine.js";
3
+ import { type Host } from "./host.js";
4
+ import type { SharingMode } from "./sharing.js";
5
+ /**
6
+ * The background server of an identity: `turno-browser-mcp --identity <id> --background`.
7
+ *
8
+ * It serves the identity over MCP streamable HTTP, for shell use without turno's gateway
9
+ * (`client.ts` starts it, connects and calls tools). Only the user reaches it: a Unix socket in
10
+ * a folder only the user can enter, or, where a socket cannot be used (Windows, or a path longer
11
+ * than the system allows), a loopback port that asks for a random per-server bearer token kept
12
+ * in a file only the user can read. It writes `server.json` (pid, address, version) when it is
13
+ * ready and removes it when it exits.
14
+ *
15
+ * Every connection is one client session, and they all drive the identity's one browser
16
+ * (`shareHost`), as mcpd's sessions share one stdio server: with `"sharing": "tabs"` each session
17
+ * has its own tabs; with `"sharing": "session"` one session at a time holds the browser (a lease
18
+ * that ends with the session, when its owner process exits, or after `leaseMs` without a call),
19
+ * and another session's calls get an error that says so. A session continues across connections
20
+ * and processes: a client that sends its `Mcp-Session-Id` again keeps its session and its tab.
21
+ *
22
+ * It exits after `idleMs` without a request (default 15 minutes), on SIGTERM, SIGINT and SIGHUP,
23
+ * closing Chrome first. Coexistence with the stdio servers of the identity: `background-state.ts`.
24
+ */
25
+ /** Exits after this long without a request, unless the flag or TURNO_BROWSER_BACKGROUND_IDLE says otherwise. */
26
+ export declare const DEFAULT_BACKGROUND_IDLE_MS: number;
27
+ /** The request header a client names the process its session belongs to with (as mcpd's). */
28
+ export declare const OWNER_HEADER = "x-turno-pid";
29
+ export declare class BackgroundError extends Error {
30
+ constructor(message: string);
31
+ }
32
+ export interface BackgroundFlags {
33
+ /** `--background`. */
34
+ background: boolean;
35
+ /** `--background-idle <duration>` or TURNO_BROWSER_BACKGROUND_IDLE, in ms; 0 never. */
36
+ idleMs: number;
37
+ rest: string[];
38
+ }
39
+ /** Removes `--background` and `--background-idle <duration>` from args and checks them. */
40
+ export declare function extractBackground(args: string[], env?: NodeJS.ProcessEnv): BackgroundFlags;
41
+ export interface BackgroundOptions {
42
+ identity: IdentityRef;
43
+ /** Exit after this long without a request; 0 never. */
44
+ idleMs: number;
45
+ /** The identity's sharing mode now (the flag, else identity.json, else "session"). */
46
+ sharing: () => SharingMode;
47
+ /** "auto" (default): a Unix socket where it can, else loopback with a token. */
48
+ transport?: "auto" | "socket" | "tcp";
49
+ /** With `"sharing": "session"`, how long an idle session keeps the browser. */
50
+ leaseMs?: number;
51
+ /** How often sessions whose owner exited are ended and the idle limit is checked. */
52
+ sweepMs?: number;
53
+ /** Runs once the server closed; default: exit the process. */
54
+ onClosed?: (reason: string) => void;
55
+ /** Answer SIGTERM, SIGINT and SIGHUP (default true; tests in process pass false). */
56
+ signals?: boolean;
57
+ log?: (line: string) => void;
58
+ }
59
+ export interface BackgroundServer {
60
+ state: BackgroundState;
61
+ /** Closes every session and the browser, removes the state file. */
62
+ close(reason?: string): Promise<void>;
63
+ /** Resolves once closed. */
64
+ closed: Promise<void>;
65
+ }
66
+ /** Serves `host` as the identity's background server until it closes. */
67
+ export declare function serveBackground(host: Host, options: BackgroundOptions): Promise<BackgroundServer>;
68
+ /** The identity's sharing mode for the lease: `--sharing`, else identity.json, else "session". */
69
+ export declare function sharingOf(flag: SharingMode | undefined, read: () => SharingMode | undefined): () => SharingMode;