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,325 @@
1
+ /**
2
+ * The tab governor. Chrome keeps every page an agent or a site opened, and each one
3
+ * keeps running scripts, timers and network until somebody closes it; after a long session that
4
+ * is most of the browser's memory and CPU. Per session's browser context it:
5
+ *
6
+ * - caps the pages open at once (`max`): when a new page goes past it, the least recently used
7
+ * page closes, never the agent's current tab or the new page;
8
+ * - closes a popup (a page with an opener) that opened while no tool call was running, nor in
9
+ * the moments after one: ads and pop-unders, not the window a click of the agent opened
10
+ * (`popups: "close"`);
11
+ * - parks a page nobody used for `parkMs`: it goes to about:blank, which stops its scripts, and
12
+ * keeps its URL; the next call that uses that page (it is the current tab, or `browser_tabs`
13
+ * selects it) loads the URL again first. After `closeMs` unused the page closes.
14
+ *
15
+ * A page counts as used when it is the current tab at the end of a tool call, and when its main
16
+ * frame navigates (a person using a headed window). The current tab is never parked or closed,
17
+ * and neither is the last page.
18
+ *
19
+ * With `"sharing": "tabs"` several sessions work in one browser: the cap counts each session's
20
+ * pages apart (`owner`) and closes only that session's least recently used page, no session's
21
+ * current tab is parked or closed (`protected`), and each note goes to the session whose page it
22
+ * is about.
23
+ *
24
+ * With `ownedOnly` (attach mode, the user's own Chrome) it governs only the agent's pages:
25
+ * the ones handed to `own` and the ones that open during a tool call or in the moments after
26
+ * one. Pages that were open before, or that open between calls, are the user's: never counted,
27
+ * parked or closed, and no popup is closed.
28
+ */
29
+ /** A popup that opens this long after a tool call ended still counts as the call's. */
30
+ export const POPUP_GRACE_MS = 2_000;
31
+ /** A URL short enough for one line of a tool result. */
32
+ function shortUrl(url) {
33
+ return url.length > 100 ? `${url.slice(0, 97)}...` : url;
34
+ }
35
+ function minutes(ms) {
36
+ if (ms < 60_000)
37
+ return `${Math.round(ms / 1000)} seconds`;
38
+ const m = Math.round(ms / 60_000);
39
+ return m === 1 ? "1 minute" : `${m} minutes`;
40
+ }
41
+ export class TabGovernor {
42
+ context;
43
+ policy;
44
+ options;
45
+ pages = new Map();
46
+ calls = 0;
47
+ lastCallEnd = Number.NEGATIVE_INFINITY;
48
+ /** Notes for the next result, per owner of the page they are about (undefined: whoever calls next). */
49
+ notes = new Map();
50
+ timer;
51
+ sweeping;
52
+ now;
53
+ adopting = new Set();
54
+ /** Pages opened during a call: the cap is applied once the call returns (`afterCall`). */
55
+ opened = new Set();
56
+ onPage = (page) => {
57
+ const done = this.adopt(page)
58
+ .catch(() => { })
59
+ .finally(() => this.adopting.delete(done));
60
+ this.adopting.add(done);
61
+ };
62
+ constructor(context, policy, options) {
63
+ this.context = context;
64
+ this.policy = policy;
65
+ this.options = options;
66
+ this.now = options.now ?? Date.now;
67
+ }
68
+ start() {
69
+ if (!this.options.ownedOnly)
70
+ for (const page of this.context.pages())
71
+ this.track(page);
72
+ this.context.on("page", this.onPage);
73
+ const stages = [this.policy.parkMs, this.policy.closeMs].filter((ms) => ms > 0);
74
+ if (stages.length && this.options.timer !== false) {
75
+ const every = Math.min(60_000, Math.max(1_000, Math.min(...stages) / 5));
76
+ this.timer = setInterval(() => void this.sweep().catch(() => { }), every);
77
+ this.timer.unref();
78
+ }
79
+ }
80
+ dispose() {
81
+ clearInterval(this.timer);
82
+ this.timer = undefined;
83
+ this.context.off("page", this.onPage);
84
+ }
85
+ /** Resolves once every page opened so far has been looked at (popup check, cap). */
86
+ async settled() {
87
+ await Promise.all([...this.adopting]);
88
+ }
89
+ /**
90
+ * The stock call returned: apply the cap to the pages it opened. Not during the call, since
91
+ * upstream reads every tab (title, console) to build the result and a page closed under it
92
+ * fails the call.
93
+ */
94
+ async afterCall() {
95
+ await this.settled();
96
+ const opened = [...this.opened];
97
+ this.opened.clear();
98
+ for (const page of opened)
99
+ if (!page.isClosed())
100
+ await this.enforceCap(page);
101
+ }
102
+ /** A tool call starts: nothing is swept and popups count as asked for until it ends. */
103
+ beginCall() {
104
+ this.calls++;
105
+ }
106
+ /**
107
+ * Resolves once nothing the governor started before the call is still in flight: a popup
108
+ * check or a sweep may be closing a page right now, and upstream reads every tab (title,
109
+ * console) to build a result, so a page closing under the call fails it with "Target page,
110
+ * context or browser has been closed". Call after `beginCall`, which keeps new work from
111
+ * starting.
112
+ */
113
+ async quiet() {
114
+ await Promise.all([...this.adopting, this.sweeping]);
115
+ }
116
+ /** A tool call ended: its current tab (of `view`, by default the governor's) was used now. */
117
+ endCall(view = this.options) {
118
+ this.calls = Math.max(0, this.calls - 1);
119
+ this.lastCallEnd = this.now();
120
+ const current = view.current();
121
+ if (!current || current.isClosed())
122
+ return;
123
+ // A tab of the user's that the agent selected stays the user's.
124
+ if (this.options.ownedOnly && !this.pages.has(current))
125
+ return;
126
+ this.track(current).lastUsed = this.now();
127
+ }
128
+ /** Counts a page as the agent's (attach mode: the tab the host opens at connect). */
129
+ own(page) {
130
+ this.track(page);
131
+ this.options.onOwn?.(page);
132
+ }
133
+ /** What the governor did since the last call, one line each, for the next tool result of `owner`. */
134
+ takeNotes(owner) {
135
+ const out = [...(this.notes.get(owner) ?? []), ...(owner === undefined ? [] : (this.notes.get(undefined) ?? []))];
136
+ this.notes.delete(owner);
137
+ this.notes.delete(undefined);
138
+ return out;
139
+ }
140
+ /** The URL a parked page will load again, or undefined when it is not parked. */
141
+ parkedUrl(page) {
142
+ return this.pages.get(page)?.parkedUrl;
143
+ }
144
+ /**
145
+ * Before a stock tool runs: when the page it is about to use is parked, load its URL again.
146
+ * That page is the tab `browser_tabs` is about to select, else the current tab.
147
+ */
148
+ async prepare(name, args, view = this.options) {
149
+ if (name === "browser_tabs") {
150
+ if (args.action !== "select" || typeof args.index !== "number")
151
+ return;
152
+ const page = view.tabs()[args.index];
153
+ if (page)
154
+ await this.restore(page);
155
+ return;
156
+ }
157
+ const current = view.current();
158
+ if (!current)
159
+ return;
160
+ if (name === "browser_navigate") {
161
+ // The call replaces the page anyway.
162
+ const state = this.pages.get(current);
163
+ if (state)
164
+ state.parkedUrl = undefined;
165
+ return;
166
+ }
167
+ await this.restore(current);
168
+ }
169
+ /** Marks parked tabs in a tab list of a tool result (`- 2: [](about:blank)`). */
170
+ annotateTabs(text, view = this.options) {
171
+ if (!text.includes("](about:blank)"))
172
+ return text;
173
+ const tabs = view.tabs();
174
+ return text.replace(/^(- (\d+):.*\]\(about:blank\))$/gm, (line, _all, index) => {
175
+ const page = tabs[Number(index)];
176
+ const url = page ? this.parkedUrl(page) : undefined;
177
+ return url ? `${line} (parked, was ${shortUrl(url)}: selecting it loads that page again)` : line;
178
+ });
179
+ }
180
+ /** Parks and closes pages that went unused too long. Never while a tool call runs. */
181
+ async sweep() {
182
+ if (this.sweeping)
183
+ return this.sweeping;
184
+ this.sweeping = this.sweepOnce().finally(() => {
185
+ this.sweeping = undefined;
186
+ });
187
+ return this.sweeping;
188
+ }
189
+ async sweepOnce() {
190
+ const { parkMs, closeMs } = this.policy;
191
+ const kept = this.protectedPages();
192
+ for (const [page, state] of [...this.pages]) {
193
+ if (this.calls > 0)
194
+ return;
195
+ if (kept.includes(page) || page.isClosed() || state.moving)
196
+ continue;
197
+ const unused = this.now() - state.lastUsed;
198
+ if (closeMs > 0 && unused >= closeMs && this.openPages().length > 1) {
199
+ const url = state.parkedUrl ?? page.url();
200
+ const owner = this.options.owner?.(page);
201
+ await page.close().catch(() => { });
202
+ this.note(`closed a tab unused for ${minutes(unused)} (${shortUrl(url)})`, owner);
203
+ continue;
204
+ }
205
+ if (parkMs > 0 && unused >= parkMs && state.parkedUrl === undefined)
206
+ await this.park(page, state, unused);
207
+ }
208
+ }
209
+ openPages() {
210
+ return [...this.pages.keys()].filter((p) => !p.isClosed());
211
+ }
212
+ protectedPages() {
213
+ if (this.options.protected)
214
+ return this.options.protected();
215
+ const current = this.options.current();
216
+ return current ? [current] : [];
217
+ }
218
+ track(page) {
219
+ let state = this.pages.get(page);
220
+ if (state)
221
+ return state;
222
+ const created = { lastUsed: this.now() };
223
+ state = created;
224
+ this.pages.set(page, created);
225
+ page.once("close", () => this.pages.delete(page));
226
+ page.on("framenavigated", (frame) => {
227
+ if (created.moving || frame !== page.mainFrame())
228
+ return;
229
+ // Navigated by someone else (the agent through a stock tool, or a person): in use again.
230
+ created.lastUsed = this.now();
231
+ created.parkedUrl = undefined;
232
+ });
233
+ return created;
234
+ }
235
+ /** A page Chrome just opened. */
236
+ async adopt(page) {
237
+ const asked = this.calls > 0 || this.now() - this.lastCallEnd < POPUP_GRACE_MS;
238
+ if (this.options.ownedOnly) {
239
+ if (!asked)
240
+ return;
241
+ this.own(page);
242
+ }
243
+ else
244
+ this.track(page);
245
+ if (this.options.adopt)
246
+ await this.options.adopt(page);
247
+ if (this.policy.popups === "close" && !asked) {
248
+ const opener = await page.opener().catch(() => null);
249
+ if (opener) {
250
+ await page.close().catch(() => { });
251
+ this.note(`closed a popup that ${shortUrl(opener.url())} opened while no tool call was running`);
252
+ return;
253
+ }
254
+ }
255
+ if (this.calls > 0)
256
+ this.opened.add(page);
257
+ else
258
+ await this.enforceCap(page);
259
+ }
260
+ async enforceCap(added) {
261
+ const { max } = this.policy;
262
+ if (max <= 0)
263
+ return;
264
+ const owner = this.options.owner?.(added);
265
+ const open = this.openPages().filter((p) => this.options.owner?.(p) === owner);
266
+ const excess = open.length - max;
267
+ if (excess <= 0)
268
+ return;
269
+ const kept = this.protectedPages();
270
+ const lastUsed = (p) => this.pages.get(p)?.lastUsed ?? 0;
271
+ const victims = open
272
+ .filter((p) => !kept.includes(p) && p !== added)
273
+ .sort((a, b) => lastUsed(a) - lastUsed(b))
274
+ .slice(0, excess);
275
+ for (const page of victims) {
276
+ const url = this.pages.get(page)?.parkedUrl ?? page.url();
277
+ await page.close().catch(() => { });
278
+ this.note(`closed the least recently used tab (${shortUrl(url)}): more than ${max} were open; tab numbers changed, list them again before selecting one`, owner);
279
+ }
280
+ }
281
+ async park(page, state, unused) {
282
+ const url = page.url();
283
+ if (!url || url.startsWith("about:"))
284
+ return;
285
+ state.moving = true;
286
+ try {
287
+ await page.goto("about:blank", { timeout: 5_000 });
288
+ state.parkedUrl = url;
289
+ this.note(`parked a tab unused for ${minutes(unused)} on about:blank (${shortUrl(url)}); using it again loads that page`, this.options.owner?.(page));
290
+ }
291
+ catch {
292
+ /* the page would not leave (a slow unload): try again on the next sweep */
293
+ }
294
+ finally {
295
+ state.moving = false;
296
+ }
297
+ }
298
+ async restore(page) {
299
+ const state = this.pages.get(page);
300
+ const url = state?.parkedUrl;
301
+ if (!state || url === undefined || page.isClosed())
302
+ return;
303
+ state.moving = true;
304
+ try {
305
+ await page.goto(url, { waitUntil: "domcontentloaded", timeout: 30_000 });
306
+ this.note(`loaded ${shortUrl(url)} again in a tab that was parked`, this.options.owner?.(page));
307
+ }
308
+ catch (error) {
309
+ this.note(`could not load ${shortUrl(url)} again in a parked tab: ${String(error.message ?? error).split("\n")[0]}`, this.options.owner?.(page));
310
+ }
311
+ finally {
312
+ state.moving = false;
313
+ state.parkedUrl = undefined;
314
+ state.lastUsed = this.now();
315
+ }
316
+ }
317
+ note(text, owner) {
318
+ const list = this.notes.get(owner) ?? [];
319
+ list.push(text);
320
+ if (list.length > 20)
321
+ list.splice(0, list.length - 20);
322
+ this.notes.set(owner, list);
323
+ }
324
+ }
325
+ //# sourceMappingURL=governor.js.map
@@ -0,0 +1,60 @@
1
+ import type { HealthCheck } from "./settings.js";
2
+ /**
3
+ * Session health: whether an identity is still signed in where it matters. The check
4
+ * in identity.json is a URL plus a text or selector that only a signed-in page shows, as in
5
+ * agent-browser's `--restore-check-text` and Kernel's health checks. The host runs it in the
6
+ * identity's own browser when it launches Chrome (at most every 30 minutes while it passes); a
7
+ * page without the proof marks the identity NEEDS_AUTH, every tool call then fails with a
8
+ * message that tells the user to sign in again (`turno browser login <id>`), and
9
+ * `turno browser doctor` shows it. A page that does not load is an error, not NEEDS_AUTH.
10
+ *
11
+ * The result is kept in `<state>/browser/identities/<id>/health.json`; a login clears it.
12
+ */
13
+ type HealthStatus = "ok" | "needs_auth" | "error";
14
+ export interface HealthRecord {
15
+ status: HealthStatus;
16
+ url: string;
17
+ checkedAt: string;
18
+ /** Why it is not ok. */
19
+ detail?: string;
20
+ }
21
+ /** After NEEDS_AUTH, calls fail without launching Chrome for this long (no window per call). */
22
+ export declare const NEEDS_AUTH_HOLD_MS = 60000;
23
+ export declare function healthPath(id: string, env?: NodeJS.ProcessEnv): string;
24
+ export declare function readHealth(id: string, env?: NodeJS.ProcessEnv): HealthRecord | undefined;
25
+ export declare function writeHealth(id: string, env: NodeJS.ProcessEnv, record: HealthRecord): void;
26
+ /** Forget the last result (after a login), so the next launch checks again. */
27
+ export declare function clearHealth(id: string, env?: NodeJS.ProcessEnv): void;
28
+ /** Whether a launch should run the check: no result, a failure, another URL, or an old pass. */
29
+ export declare function healthDue(record: HealthRecord | undefined, check: HealthCheck, now?: Date): boolean;
30
+ /** The tool error for an identity that is not signed in. Written for the agent to relay. */
31
+ export declare function needsAuthMessage(id: string, record: HealthRecord): string;
32
+ interface LocatorLike {
33
+ first(): LocatorLike;
34
+ waitFor(options: {
35
+ state: "visible" | "attached";
36
+ timeout: number;
37
+ }): Promise<void>;
38
+ }
39
+ interface PageLike {
40
+ goto(url: string, options: {
41
+ waitUntil: "domcontentloaded";
42
+ timeout: number;
43
+ }): Promise<unknown>;
44
+ getByText(text: string): LocatorLike;
45
+ locator(selector: string): LocatorLike;
46
+ close(): Promise<void>;
47
+ }
48
+ /** The part of a Playwright BrowserContext the check uses. */
49
+ export interface HealthContext {
50
+ newPage(): Promise<PageLike>;
51
+ }
52
+ export interface HealthOptions {
53
+ navigationTimeoutMs?: number;
54
+ /** How long the proof may take to show after the page loaded. */
55
+ waitMs?: number;
56
+ now?: () => Date;
57
+ }
58
+ /** Runs the check in a new tab of the identity's browser and closes the tab. */
59
+ export declare function runHealthCheck(context: HealthContext, check: HealthCheck, opts?: HealthOptions): Promise<HealthRecord>;
60
+ export {};
package/dist/health.js ADDED
@@ -0,0 +1,86 @@
1
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { identityStateDir } from "./ids.js";
4
+ /** A passing check is trusted this long before the next launch checks again. */
5
+ const HEALTH_TTL_MS = 30 * 60_000;
6
+ /** After NEEDS_AUTH, calls fail without launching Chrome for this long (no window per call). */
7
+ export const NEEDS_AUTH_HOLD_MS = 60_000;
8
+ export function healthPath(id, env = process.env) {
9
+ return join(identityStateDir(id, env), "health.json");
10
+ }
11
+ export function readHealth(id, env = process.env) {
12
+ try {
13
+ const v = JSON.parse(readFileSync(healthPath(id, env), "utf8"));
14
+ if ((v.status === "ok" || v.status === "needs_auth" || v.status === "error") &&
15
+ typeof v.url === "string" &&
16
+ typeof v.checkedAt === "string")
17
+ return v;
18
+ }
19
+ catch {
20
+ /* none, or not a record */
21
+ }
22
+ return undefined;
23
+ }
24
+ export function writeHealth(id, env, record) {
25
+ const file = healthPath(id, env);
26
+ mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 });
27
+ const tmp = `${file}.${process.pid}.tmp`;
28
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
29
+ renameSync(tmp, file);
30
+ }
31
+ /** Forget the last result (after a login), so the next launch checks again. */
32
+ export function clearHealth(id, env = process.env) {
33
+ rmSync(healthPath(id, env), { force: true });
34
+ }
35
+ /** Whether a launch should run the check: no result, a failure, another URL, or an old pass. */
36
+ export function healthDue(record, check, now = new Date()) {
37
+ if (!record || record.status !== "ok" || record.url !== check.url)
38
+ return true;
39
+ return now.getTime() - Date.parse(record.checkedAt) > HEALTH_TTL_MS;
40
+ }
41
+ /** The tool error for an identity that is not signed in. Written for the agent to relay. */
42
+ export function needsAuthMessage(id, record) {
43
+ return (`NEEDS_AUTH: browser identity "${id}" is not signed in: ${record.detail ?? "the check failed"} at ${record.url} (checked ${record.checkedAt}). ` +
44
+ `Ask the user to run \`turno browser login ${id}\`, sign in and close the window, then call this tool again.`);
45
+ }
46
+ const firstLine = (e) => String(e.message ?? e).split("\n")[0];
47
+ /** Runs the check in a new tab of the identity's browser and closes the tab. */
48
+ export async function runHealthCheck(context, check, opts = {}) {
49
+ const now = opts.now ?? (() => new Date());
50
+ const done = (status, detail) => ({
51
+ status,
52
+ url: check.url,
53
+ checkedAt: now().toISOString(),
54
+ ...(detail ? { detail } : {}),
55
+ });
56
+ const page = await context.newPage();
57
+ try {
58
+ try {
59
+ await page.goto(check.url, { waitUntil: "domcontentloaded", timeout: opts.navigationTimeoutMs ?? 20_000 });
60
+ }
61
+ catch (err) {
62
+ return done("error", `could not load the page: ${firstLine(err)}`);
63
+ }
64
+ const waitMs = opts.waitMs ?? 10_000;
65
+ const proofs = [];
66
+ if (check.text)
67
+ proofs.push([page.getByText(check.text), "visible", `the page did not show "${check.text}"`]);
68
+ if (check.selector)
69
+ proofs.push([page.locator(check.selector), "attached", `no element matched ${check.selector}`]);
70
+ for (const [locator, state, missing] of proofs) {
71
+ try {
72
+ await locator.first().waitFor({ state, timeout: waitMs });
73
+ }
74
+ catch (err) {
75
+ if (err.name === "TimeoutError")
76
+ return done("needs_auth", missing);
77
+ return done("error", firstLine(err));
78
+ }
79
+ }
80
+ return done("ok");
81
+ }
82
+ finally {
83
+ await page.close().catch(() => { });
84
+ }
85
+ }
86
+ //# sourceMappingURL=health.js.map
package/dist/host.d.ts ADDED
@@ -0,0 +1,95 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
3
+ import type { SecretStore } from "turno-core/secrets";
4
+ import { type Engine, type EngineFlags, type IdentityRef } from "./engine.js";
5
+ import { type LiveFlags } from "./live.js";
6
+ import { LiveServer } from "./live-server.js";
7
+ import { type TabLockPolicy } from "./tab-locks.js";
8
+ import { type Providers, type TurnoTool } from "./tools.js";
9
+ import { type Tuning, type TuningFlags } from "./tuning.js";
10
+ import { type IdleTimerLike, type McpConfig, type ServerBackendFactory, type ToolResult, type ToolSchemaJson } from "./upstream.js";
11
+ /** The name and version the server reports in `initialize`. */
12
+ export declare const SERVER_INFO: {
13
+ name: string;
14
+ version: string;
15
+ };
16
+ export interface HostOptions {
17
+ config: McpConfig;
18
+ cliOptions: Record<string, unknown>;
19
+ /** Turno tools of this host (default: `TURNO_TOOLS`). */
20
+ turnoTools?: readonly TurnoTool[];
21
+ /** The engine for every launch, instead of the one the config selects (tests inject a fake). */
22
+ engine?: Engine;
23
+ /** The identity served (`--identity`): its runtime lock, settings, session health and reputation log. */
24
+ identity?: IdentityRef;
25
+ /** The `turno-browser-mcp` tab governor and throttling flags; they win over identity.json. */
26
+ tuning?: TuningFlags;
27
+ /** The secret store the vault reads (tests inject a fake); default: this machine's. */
28
+ vaultStore?: SecretStore;
29
+ /** With `"sharing": "tabs"`: how long a call waits for a held tab, and when an idle session lets go. */
30
+ tabLocks?: Partial<TabLockPolicy>;
31
+ /** `--engine` and `--attach`; they win over identity.json. */
32
+ engineFlags?: EngineFlags;
33
+ /** Stand-ins for the opt-in providers (tests inject fakes). */
34
+ providers?: Providers;
35
+ /** `--live` and `--live-wait`; they win over identity.json `live`. */
36
+ live?: LiveFlags;
37
+ }
38
+ export interface Host {
39
+ config: McpConfig;
40
+ /** Stock tools first, in upstream's order, then turno's. */
41
+ listTools(): ToolSchemaJson[];
42
+ factory: ServerBackendFactory;
43
+ /** Hides vault values in a text this server is about to send. */
44
+ redact(text: string): string;
45
+ /** The live view server, when the live view is on for the identity served. */
46
+ live?: LiveServer;
47
+ }
48
+ /** Upstream joins the text parts of a result into one (`mergeTextParts`). */
49
+ export declare function mergeTextParts(result: ToolResult): ToolResult;
50
+ /**
51
+ * One MCP session. Implements upstream's server backend contract, so upstream's HTTP server
52
+ * can serve it as well as turno's stdio server.
53
+ */
54
+ /** A session's running browser, as the host drives it. */
55
+ /**
56
+ * The idle limit as a session sees it: it counts from the end of the last tool call and never
57
+ * while one runs. Upstream's `BrowserBackend` pokes the timer at the start of a call only, so a
58
+ * call that took longer than the limit (a slow page, a busy machine, a short `TURNO_BROWSER_IDLE`)
59
+ * had Chrome closed under it and failed with "Target page, context or browser has been closed".
60
+ */
61
+ export declare class CallIdleTimer implements IdleTimerLike {
62
+ private readonly inner;
63
+ /** False once the browser closed: counting again would only close it a second time. */
64
+ private readonly open;
65
+ private calls;
66
+ constructor(inner: IdleTimerLike,
67
+ /** False once the browser closed: counting again would only close it a second time. */
68
+ open: () => boolean);
69
+ /** Upstream's poke at the start of a call: ignored while a call holds the timer. */
70
+ poke(): void;
71
+ /** Stops the countdown until the returned function runs (once) at the end of the call. */
72
+ begin(): () => void;
73
+ dispose(): void;
74
+ }
75
+ /**
76
+ * The config of one launch: a copy, so a change for this session (a batch's snapshot-free
77
+ * steps) does not reach another, with the identity's `settle` unless the user set
78
+ * Playwright's own `--timeout-settle`, `PLAYWRIGHT_MCP_TIMEOUT_SETTLE` or `timeouts.settle` in a
79
+ * config file, which win.
80
+ */
81
+ export declare function configForSession(config: McpConfig, cliOptions: Record<string, unknown>, tuning: Tuning): McpConfig;
82
+ /** Builds the host for a resolved config: tool list, engine and session factory. */
83
+ export declare function createHost(options: HostOptions): Host;
84
+ /** Serves the host: stdio by turno, `--port` by upstream's HTTP server. */
85
+ export declare function serve(host: Host, transport?: Transport): Promise<Server | undefined>;
86
+ /**
87
+ * Parses the Playwright MCP flags with upstream's definitions and serves them with turno's
88
+ * host. Mirrors the action of upstream's program: exit watchdog, `--vision`, `tracing`, config.
89
+ */
90
+ export declare function runHost(args: string[], options?: {
91
+ identity?: IdentityRef;
92
+ tuning?: TuningFlags;
93
+ engineFlags?: EngineFlags;
94
+ live?: LiveFlags;
95
+ }): Promise<void>;