turno-browser 0.4.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.
- package/CHANGELOG.md +24 -0
- package/README.md +92 -149
- package/dist/act-model.js +4 -3
- package/dist/act.js +2 -1
- package/dist/api.d.ts +63 -2
- package/dist/api.js +14 -4
- package/dist/background-state.d.ts +54 -0
- package/dist/background-state.js +97 -0
- package/dist/background.d.ts +69 -0
- package/dist/background.js +458 -0
- package/dist/bin/mcp.js +48 -8
- package/dist/captcha.js +3 -2
- package/dist/cli/background.d.ts +11 -0
- package/dist/cli/background.js +132 -0
- package/dist/cli/commands.d.ts +16 -0
- package/dist/cli/commands.js +515 -0
- package/dist/cli/context.d.ts +75 -0
- package/dist/cli/context.js +44 -0
- package/dist/cli/do-background.d.ts +27 -0
- package/dist/cli/do-background.js +212 -0
- package/dist/cli/do.d.ts +85 -0
- package/dist/cli/do.js +558 -0
- package/dist/cli/flows.d.ts +28 -0
- package/dist/cli/flows.js +303 -0
- package/dist/cli/identity.d.ts +37 -0
- package/dist/cli/identity.js +906 -0
- package/dist/cli/live.d.ts +7 -0
- package/dist/cli/live.js +99 -0
- package/dist/cli/main.d.ts +16 -0
- package/dist/cli/main.js +171 -0
- package/dist/cli/secret.d.ts +4 -0
- package/dist/cli/secret.js +151 -0
- package/dist/cli/session.d.ts +6 -0
- package/dist/cli/session.js +106 -0
- package/dist/cli/setup.d.ts +7 -0
- package/dist/cli/setup.js +180 -0
- package/dist/cli/vault.d.ts +5 -0
- package/dist/cli/vault.js +192 -0
- package/dist/client.d.ts +82 -0
- package/dist/client.js +303 -0
- package/dist/doctor.js +34 -1
- package/dist/engine-camoufox.js +5 -4
- package/dist/engine-lightpanda.js +3 -2
- package/dist/engine.js +2 -1
- package/dist/health.js +2 -1
- package/dist/host.d.ts +21 -0
- package/dist/host.js +75 -15
- package/dist/human-input.js +7 -2
- package/dist/identities.js +2 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.js +2 -0
- package/dist/lifecycle.d.ts +2 -0
- package/dist/lifecycle.js +2 -1
- package/dist/live-client.js +8 -6
- package/dist/live-page.d.ts +0 -7
- package/dist/live-page.js +3 -2
- package/dist/live-server.js +6 -3
- package/dist/live.js +2 -1
- package/dist/login-tool.js +3 -2
- package/dist/login.js +2 -1
- package/dist/names.d.ts +28 -0
- package/dist/names.js +25 -0
- package/dist/network.d.ts +1 -1
- package/dist/network.js +4 -3
- package/dist/opt-in-settings.js +3 -2
- package/dist/replay.js +4 -3
- package/dist/runtime-lock.js +3 -2
- package/dist/vault.js +5 -4
- package/npm-shrinkwrap.json +6 -5
- package/package.json +13 -7
package/dist/client.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { closeSync, openSync, readFileSync, statSync, truncateSync } from "node:fs";
|
|
3
|
+
import { request as httpRequest } from "node:http";
|
|
4
|
+
import { Readable } from "node:stream";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
7
|
+
import { StreamableHTTPClientTransport, StreamableHTTPError } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
8
|
+
import { ensurePrivateDir } from "turno-core/paths";
|
|
9
|
+
import { pidAlive } from "turno-core/process";
|
|
10
|
+
import { BackgroundError, OWNER_HEADER } from "./background.js";
|
|
11
|
+
import { backgroundDir, backgroundLogPath, liveBackground, readBackgroundState, removeBackgroundFiles, } from "./background-state.js";
|
|
12
|
+
import { assertIdentityId } from "./ids.js";
|
|
13
|
+
/**
|
|
14
|
+
* The client of an identity's background server (`background.ts`): start it when it is not
|
|
15
|
+
* running, open or continue an MCP session on it, call tools, end the session, stop the server.
|
|
16
|
+
* `turno-browser do` uses it when turno's gateway is not there.
|
|
17
|
+
*
|
|
18
|
+
* A session is the unit that keeps a tab: with `"sharing": "tabs"` each session has its own tabs,
|
|
19
|
+
* with `"sharing": "session"` one session at a time holds the browser. To continue a session from
|
|
20
|
+
* another process, save `id` and `protocolVersion` of an open one and pass them as `session`; a
|
|
21
|
+
* session the server no longer knows (it restarted) is replaced by a new one (`resumed: false`).
|
|
22
|
+
*/
|
|
23
|
+
export { BackgroundError } from "./background.js";
|
|
24
|
+
const DEFAULT_START_TIMEOUT_MS = 30_000;
|
|
25
|
+
const DEFAULT_CALL_TIMEOUT_MS = 120_000;
|
|
26
|
+
/** A log longer than this is cut when a server starts. */
|
|
27
|
+
const MAX_LOG_BYTES = 1024 * 1024;
|
|
28
|
+
function envOf(options) {
|
|
29
|
+
return options?.env ?? process.env;
|
|
30
|
+
}
|
|
31
|
+
/** The running background server of the identity, or undefined (a state left by a killed one is removed). */
|
|
32
|
+
export function backgroundStatus(id, options) {
|
|
33
|
+
assertIdentityId(id);
|
|
34
|
+
const state = liveBackground(id, envOf(options));
|
|
35
|
+
return state?.transport ? state : undefined;
|
|
36
|
+
}
|
|
37
|
+
function defaultBin() {
|
|
38
|
+
return fileURLToPath(new URL("./bin/mcp.js", import.meta.url));
|
|
39
|
+
}
|
|
40
|
+
function logTail(file, lines = 8) {
|
|
41
|
+
try {
|
|
42
|
+
return readFileSync(file, "utf8").trimEnd().split("\n").slice(-lines).join("\n");
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return "";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
49
|
+
/**
|
|
50
|
+
* Starts the identity's background server unless it runs: detached from this process, its
|
|
51
|
+
* output in `server.log` of its folder. Resolves when it is ready; rejects with what it wrote
|
|
52
|
+
* when it exits first (the identity is in use, a bad flag) or after the timeout.
|
|
53
|
+
*/
|
|
54
|
+
export async function startBackground(id, options = {}) {
|
|
55
|
+
assertIdentityId(id);
|
|
56
|
+
const env = envOf(options);
|
|
57
|
+
const running = backgroundStatus(id, options);
|
|
58
|
+
if (running)
|
|
59
|
+
return { state: running, started: false };
|
|
60
|
+
// Files the server saves (snapshots, downloads) land in its private folder, not where it was started.
|
|
61
|
+
const dir = ensurePrivateDir(backgroundDir(id, env), env);
|
|
62
|
+
const logFile = backgroundLogPath(id, env);
|
|
63
|
+
try {
|
|
64
|
+
if (statSync(logFile).size > MAX_LOG_BYTES)
|
|
65
|
+
truncateSync(logFile, 0);
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
/* no log yet */
|
|
69
|
+
}
|
|
70
|
+
const fd = openSync(logFile, "a", 0o600);
|
|
71
|
+
const offset = (() => {
|
|
72
|
+
try {
|
|
73
|
+
return statSync(logFile).size;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
return 0;
|
|
77
|
+
}
|
|
78
|
+
})();
|
|
79
|
+
let exited;
|
|
80
|
+
try {
|
|
81
|
+
const child = spawn(process.execPath, [options.bin ?? defaultBin(), "--identity", id, "--background", ...(options.args ?? [])], { detached: true, stdio: ["ignore", fd, fd], env, cwd: dir });
|
|
82
|
+
child.once("exit", (code, signal) => {
|
|
83
|
+
exited = code ?? (signal ? -1 : null);
|
|
84
|
+
});
|
|
85
|
+
child.once("error", () => {
|
|
86
|
+
exited = -1;
|
|
87
|
+
});
|
|
88
|
+
child.unref();
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
closeSync(fd);
|
|
92
|
+
}
|
|
93
|
+
const deadline = Date.now() + (options.timeoutMs ?? DEFAULT_START_TIMEOUT_MS);
|
|
94
|
+
for (;;) {
|
|
95
|
+
// Ready: this call's server, or one another call started at the same time.
|
|
96
|
+
const state = backgroundStatus(id, options);
|
|
97
|
+
if (state)
|
|
98
|
+
return { state, started: true };
|
|
99
|
+
if (exited !== undefined) {
|
|
100
|
+
const said = (() => {
|
|
101
|
+
try {
|
|
102
|
+
return readFileSync(logFile, "utf8").slice(offset).trim();
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
return "";
|
|
106
|
+
}
|
|
107
|
+
})();
|
|
108
|
+
throw new BackgroundError(said
|
|
109
|
+
? said.replace(/^turno-browser-mcp: /gm, "")
|
|
110
|
+
: `the background server of "${id}" exited at start (code ${exited}); see ${logFile}`);
|
|
111
|
+
}
|
|
112
|
+
if (Date.now() > deadline)
|
|
113
|
+
throw new BackgroundError(`the background server of "${id}" was not ready in time; see ${logFile}${logTail(logFile) ? `:\n${logTail(logFile)}` : ""}`);
|
|
114
|
+
await sleep(50);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Stops the identity's background server (SIGTERM: it closes its sessions and Chrome, then
|
|
119
|
+
* exits). Resolves true when one ran, false when none did.
|
|
120
|
+
*/
|
|
121
|
+
export async function stopBackground(id, options = {}) {
|
|
122
|
+
assertIdentityId(id);
|
|
123
|
+
const env = envOf(options);
|
|
124
|
+
const state = liveBackground(id, env);
|
|
125
|
+
if (!state)
|
|
126
|
+
return false;
|
|
127
|
+
try {
|
|
128
|
+
process.kill(state.pid, "SIGTERM");
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
/* exited meanwhile */
|
|
132
|
+
}
|
|
133
|
+
const deadline = Date.now() + (options.timeoutMs ?? 10_000);
|
|
134
|
+
while (pidAlive(state.pid) && Date.now() < deadline)
|
|
135
|
+
await sleep(50);
|
|
136
|
+
if (pidAlive(state.pid)) {
|
|
137
|
+
try {
|
|
138
|
+
process.kill(state.pid, "SIGKILL"); // its Chrome is swept by the next start
|
|
139
|
+
}
|
|
140
|
+
catch {
|
|
141
|
+
/* gone */
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
if (readBackgroundState(id, env)?.pid === state.pid && !pidAlive(state.pid))
|
|
145
|
+
removeBackgroundFiles(id, env);
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
/** A fetch over the server's Unix socket. */
|
|
149
|
+
function socketFetch(socketPath) {
|
|
150
|
+
return (url, init = {}) => new Promise((resolve, reject) => {
|
|
151
|
+
const target = new URL(url);
|
|
152
|
+
const headers = {};
|
|
153
|
+
new Headers(init.headers).forEach((value, key) => {
|
|
154
|
+
headers[key] = value;
|
|
155
|
+
});
|
|
156
|
+
const req = httpRequest({ socketPath, path: `${target.pathname}${target.search}`, method: init.method ?? "GET", headers }, (res) => {
|
|
157
|
+
const out = new Headers();
|
|
158
|
+
for (const [key, value] of Object.entries(res.headers)) {
|
|
159
|
+
if (Array.isArray(value))
|
|
160
|
+
for (const v of value)
|
|
161
|
+
out.append(key, v);
|
|
162
|
+
else if (value !== undefined)
|
|
163
|
+
out.set(key, value);
|
|
164
|
+
}
|
|
165
|
+
const status = res.statusCode ?? 500;
|
|
166
|
+
const empty = status === 204 || status === 304 || init.method === "HEAD";
|
|
167
|
+
if (empty)
|
|
168
|
+
res.resume();
|
|
169
|
+
resolve(new Response(empty ? null : Readable.toWeb(res), {
|
|
170
|
+
status,
|
|
171
|
+
statusText: res.statusMessage ?? "",
|
|
172
|
+
headers: out,
|
|
173
|
+
}));
|
|
174
|
+
});
|
|
175
|
+
const signal = init.signal;
|
|
176
|
+
const abort = () => req.destroy(signal?.reason instanceof Error ? signal.reason : new Error("aborted"));
|
|
177
|
+
if (signal?.aborted) {
|
|
178
|
+
abort();
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
182
|
+
req.once("error", reject);
|
|
183
|
+
if (typeof init.body === "string" || init.body instanceof Uint8Array)
|
|
184
|
+
req.end(init.body);
|
|
185
|
+
else
|
|
186
|
+
req.end();
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
function transportFor(state, owner, session) {
|
|
190
|
+
const headers = owner !== undefined ? { [OWNER_HEADER]: String(owner) } : {};
|
|
191
|
+
let url;
|
|
192
|
+
let fetch;
|
|
193
|
+
if (state.transport === "socket") {
|
|
194
|
+
url = new URL("http://localhost/mcp");
|
|
195
|
+
fetch = socketFetch(state.socket);
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
url = new URL(`http://127.0.0.1:${state.port}/mcp`);
|
|
199
|
+
headers.Authorization = `Bearer ${readFileSync(state.tokenFile, "utf8").trim()}`;
|
|
200
|
+
}
|
|
201
|
+
const transport = new StreamableHTTPClientTransport(url, {
|
|
202
|
+
...(fetch ? { fetch } : {}),
|
|
203
|
+
...(session ? { sessionId: session.id } : {}),
|
|
204
|
+
requestInit: { headers },
|
|
205
|
+
});
|
|
206
|
+
if (session?.protocolVersion)
|
|
207
|
+
transport.setProtocolVersion(session.protocolVersion);
|
|
208
|
+
return transport;
|
|
209
|
+
}
|
|
210
|
+
function gone(err) {
|
|
211
|
+
return ((err instanceof StreamableHTTPError && err.code === 404) ||
|
|
212
|
+
/session not found/i.test(String(err?.message ?? "")));
|
|
213
|
+
}
|
|
214
|
+
function unreachable(err) {
|
|
215
|
+
const text = `${err?.message ?? ""} ${String(err?.cause ?? "")}`;
|
|
216
|
+
return /ECONNREFUSED|ENOENT|ECONNRESET|fetch failed|socket hang up/i.test(text);
|
|
217
|
+
}
|
|
218
|
+
async function connect(state, options) {
|
|
219
|
+
const name = options.clientName ?? "turno-browser";
|
|
220
|
+
if (options.session) {
|
|
221
|
+
const transport = transportFor(state, options.owner, options.session);
|
|
222
|
+
const client = new Client({ name, version: state.version }, { capabilities: {} });
|
|
223
|
+
await client.connect(transport); // a session id set: no initialize, it continues
|
|
224
|
+
try {
|
|
225
|
+
await client.ping();
|
|
226
|
+
return { client, transport, resumed: true };
|
|
227
|
+
}
|
|
228
|
+
catch (err) {
|
|
229
|
+
await client.close().catch(() => { });
|
|
230
|
+
if (!gone(err))
|
|
231
|
+
throw err;
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
const transport = transportFor(state, options.owner);
|
|
235
|
+
const client = new Client({ name, version: state.version }, { capabilities: {} });
|
|
236
|
+
await client.connect(transport);
|
|
237
|
+
return { client, transport, resumed: false };
|
|
238
|
+
}
|
|
239
|
+
/**
|
|
240
|
+
* Opens a session on the identity's background server, or continues `options.session`,
|
|
241
|
+
* starting the server first unless `start` is false.
|
|
242
|
+
*/
|
|
243
|
+
export async function openBackgroundSession(id, options = {}) {
|
|
244
|
+
assertIdentityId(id);
|
|
245
|
+
const startOptions = options.start === false
|
|
246
|
+
? undefined
|
|
247
|
+
: { ...(typeof options.start === "object" ? options.start : {}), ...(options.env ? { env: options.env } : {}) };
|
|
248
|
+
const find = async () => {
|
|
249
|
+
if (startOptions)
|
|
250
|
+
return (await startBackground(id, startOptions)).state;
|
|
251
|
+
const state = backgroundStatus(id, options);
|
|
252
|
+
if (!state)
|
|
253
|
+
throw new BackgroundError(`the background server of browser identity "${id}" is not running`);
|
|
254
|
+
return state;
|
|
255
|
+
};
|
|
256
|
+
let state = await find();
|
|
257
|
+
let conn;
|
|
258
|
+
try {
|
|
259
|
+
conn = await connect(state, options);
|
|
260
|
+
}
|
|
261
|
+
catch (err) {
|
|
262
|
+
if (!unreachable(err))
|
|
263
|
+
throw new BackgroundError(`the background server of "${id}" refused the session: ${err.message}`);
|
|
264
|
+
// It exited between the status and the connection (its idle limit): once more, from the start.
|
|
265
|
+
await sleep(100);
|
|
266
|
+
state = await find();
|
|
267
|
+
conn = await connect(state, options).catch((again) => {
|
|
268
|
+
throw new BackgroundError(`cannot reach the background server of "${id}": ${again.message}`);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
const { client, transport, resumed } = conn;
|
|
272
|
+
const sessionId = transport.sessionId;
|
|
273
|
+
if (!sessionId) {
|
|
274
|
+
await client.close().catch(() => { });
|
|
275
|
+
throw new BackgroundError(`the background server of "${id}" gave no session id`);
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
id: sessionId,
|
|
279
|
+
get protocolVersion() {
|
|
280
|
+
return transport.protocolVersion;
|
|
281
|
+
},
|
|
282
|
+
resumed,
|
|
283
|
+
state,
|
|
284
|
+
async listTools() {
|
|
285
|
+
return (await client.listTools()).tools;
|
|
286
|
+
},
|
|
287
|
+
async callTool(name, args = {}, call = {}) {
|
|
288
|
+
return (await client.callTool({ name, arguments: args }, undefined, {
|
|
289
|
+
timeout: call.timeoutMs ?? DEFAULT_CALL_TIMEOUT_MS,
|
|
290
|
+
resetTimeoutOnProgress: true,
|
|
291
|
+
...(call.signal ? { signal: call.signal } : {}),
|
|
292
|
+
}));
|
|
293
|
+
},
|
|
294
|
+
async end() {
|
|
295
|
+
await transport.terminateSession().catch(() => { });
|
|
296
|
+
await client.close().catch(() => { });
|
|
297
|
+
},
|
|
298
|
+
async close() {
|
|
299
|
+
await client.close().catch(() => { });
|
|
300
|
+
},
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
//# sourceMappingURL=client.js.map
|
package/dist/doctor.js
CHANGED
|
@@ -5,6 +5,7 @@ import { dirname, join } from "node:path";
|
|
|
5
5
|
import { browserPaths as paths } from "turno-core/paths";
|
|
6
6
|
import { readProcTable, signalProcess } from "turno-core/process";
|
|
7
7
|
import { secretStore } from "turno-core/secrets";
|
|
8
|
+
import { backgroundAlive, readBackgroundState } from "./background-state.js";
|
|
8
9
|
import { readHealth } from "./health.js";
|
|
9
10
|
import { identityDir, isValidIdentityId } from "./ids.js";
|
|
10
11
|
import { defaultChromeUserDataDir, parseAttachTarget, resolveAttachEndpoint } from "./engine-attach.js";
|
|
@@ -14,6 +15,7 @@ import { findProfileChrome, sweepOrphan } from "./lifecycle.js";
|
|
|
14
15
|
import { readChallenges, summarizeChallenges } from "./reputation.js";
|
|
15
16
|
import { inUseMessage, readRuntimeLock, runtimeLockAlive, runtimeLockPath } from "./runtime-lock.js";
|
|
16
17
|
import { acceptLanguages, checkIdentitySettings, systemTimezone } from "./settings.js";
|
|
18
|
+
import { names } from "./names.js";
|
|
17
19
|
const FIX = "turno browser doctor --fix";
|
|
18
20
|
const CHROME_PATHS = (env, platform) => {
|
|
19
21
|
const home = paths(env).home;
|
|
@@ -220,6 +222,17 @@ function identityChecks(id, env, now, servers = []) {
|
|
|
220
222
|
else {
|
|
221
223
|
add({ level: "ok", text: "free: no process holds it" });
|
|
222
224
|
}
|
|
225
|
+
// The background server `turno-browser do` starts: while it runs, an agent's server of this
|
|
226
|
+
// identity refuses to launch the browser, so say it runs and how to stop it.
|
|
227
|
+
const background = readBackgroundState(id, env);
|
|
228
|
+
if (background?.transport && backgroundAlive(background)) {
|
|
229
|
+
const idle = background.idleMs > 0 ? `; it exits after ${Math.round(background.idleMs / 60_000)}m without a request` : "";
|
|
230
|
+
add({
|
|
231
|
+
level: "info",
|
|
232
|
+
text: `background server (pid ${background.pid}) since ${background.startedAt} serves it to turno-browser do; an agent's server of this identity cannot open the browser until it stops${idle}`,
|
|
233
|
+
fix: `turno-browser background stop ${id}`,
|
|
234
|
+
});
|
|
235
|
+
}
|
|
223
236
|
const check = settings?.health;
|
|
224
237
|
const health = readHealth(id, env);
|
|
225
238
|
if (!check) {
|
|
@@ -551,6 +564,26 @@ export async function runDoctor(opts = {}) {
|
|
|
551
564
|
return smoke ? again.map((c) => (c.area === "chrome" && /^smoke launch/.test(c.text) ? smoke : c)) : again;
|
|
552
565
|
});
|
|
553
566
|
}
|
|
554
|
-
return { checks, fixed };
|
|
567
|
+
return { checks: checks.map(named), fixed };
|
|
568
|
+
}
|
|
569
|
+
/**
|
|
570
|
+
* A check's fix and text with the commands named the way this process's host types them: the
|
|
571
|
+
* checks are written with turno's names (the troubleshooting docs are generated from them), and
|
|
572
|
+
* turno-browser on its own prints `turno-browser set <id> ...` instead.
|
|
573
|
+
*/
|
|
574
|
+
function named(check) {
|
|
575
|
+
const n = names();
|
|
576
|
+
if (n.browser === "turno browser")
|
|
577
|
+
return check;
|
|
578
|
+
const swap = (s) => s
|
|
579
|
+
.replace(/turno identity (\w+) browser:(\S+)/g, (_m, sub, id) => n.identity(sub, id))
|
|
580
|
+
.replace(/turno secret set (\S+)/g, (_m, item) => n.secretSet(item))
|
|
581
|
+
.replace(/turno browser /g, `${n.browser} `);
|
|
582
|
+
return {
|
|
583
|
+
...check,
|
|
584
|
+
text: swap(check.text),
|
|
585
|
+
...(check.fix ? { fix: swap(check.fix) } : {}),
|
|
586
|
+
...(check.manual ? { manual: swap(check.manual) } : {}),
|
|
587
|
+
};
|
|
555
588
|
}
|
|
556
589
|
//# sourceMappingURL=doctor.js.map
|
package/dist/engine-camoufox.js
CHANGED
|
@@ -10,11 +10,12 @@ import { FIREFOX_PROXY_PREFS, resolveProxy } from "./network.js";
|
|
|
10
10
|
import { acquireRuntimeLock } from "./runtime-lock.js";
|
|
11
11
|
import { acceptLanguages, chromeEnv, readIdentitySettings, systemTimezone } from "./settings.js";
|
|
12
12
|
import { upstream } from "./upstream.js";
|
|
13
|
+
import { names } from "./names.js";
|
|
13
14
|
/**
|
|
14
15
|
* The `camoufox` engine: Camoufox, a Firefox build with its own fingerprint handling, instead
|
|
15
16
|
* of Chrome. Opt-in only (identity.json `"engine": "camoufox"`, or `--engine camoufox`), off by
|
|
16
|
-
* default
|
|
17
|
-
*
|
|
17
|
+
* default and the user's choice. A Firefox with a changed fingerprint is something sites look
|
|
18
|
+
* for, and the identity's Chrome profile and sign-ins do not carry over.
|
|
18
19
|
*
|
|
19
20
|
* turno never downloads it. Two things must be installed:
|
|
20
21
|
*
|
|
@@ -46,7 +47,7 @@ export function camoufoxRefusal(tool) {
|
|
|
46
47
|
const why = NOT_IN_CAMOUFOX[tool];
|
|
47
48
|
if (!why)
|
|
48
49
|
return undefined;
|
|
49
|
-
return `${tool} is not available with the Camoufox engine: ${why}. Use the Chrome engine for it (
|
|
50
|
+
return `${tool} is not available with the Camoufox engine: ${why}. Use the Chrome engine for it (\`${names().browser} set <id> --engine chrome\`).`;
|
|
50
51
|
}
|
|
51
52
|
/** How to install Camoufox, for errors and `turno browser doctor`. */
|
|
52
53
|
export function camoufoxInstallHint(platform = process.platform) {
|
|
@@ -129,7 +130,7 @@ function camoufoxMissing(env) {
|
|
|
129
130
|
const where = configured
|
|
130
131
|
? `TURNO_CAMOUFOX_PATH (${configured}) is not an executable file with an absolute path`
|
|
131
132
|
: `no Camoufox build is in ${camoufoxCacheDir(env)}`;
|
|
132
|
-
return new Error(`the camoufox engine needs Camoufox, and ${where}. Install it: ${camoufoxInstallHint()}. turno never downloads it for you;
|
|
133
|
+
return new Error(`the camoufox engine needs Camoufox, and ${where}. Install it: ${camoufoxInstallHint()}. turno never downloads it for you; \`${names().browser} doctor\` checks it.`);
|
|
133
134
|
}
|
|
134
135
|
/** The minor version of Playwright that patchright-core is built on, like "1.64". */
|
|
135
136
|
export function playwrightMinor() {
|
|
@@ -9,6 +9,7 @@ import { IdleTimer, idleMs } from "./idle-timer.js";
|
|
|
9
9
|
import { identityStateDir } from "./ids.js";
|
|
10
10
|
import { stopChrome } from "./lifecycle.js";
|
|
11
11
|
import { playwright, upstream } from "./upstream.js";
|
|
12
|
+
import { names } from "./names.js";
|
|
12
13
|
/**
|
|
13
14
|
* Read mode: the `lightpanda` engine. Lightpanda is a headless browser written from
|
|
14
15
|
* scratch for automation (no rendering, a small fraction of Chrome's memory) that speaks CDP.
|
|
@@ -76,7 +77,7 @@ export function readModeRefusal(tool) {
|
|
|
76
77
|
return undefined;
|
|
77
78
|
const why = NOT_IN_READ_MODE[tool] ?? "it was not checked against Lightpanda";
|
|
78
79
|
return (`${tool} is not available in read mode (the Lightpanda engine): ${why}. ` +
|
|
79
|
-
|
|
80
|
+
`Use the Chrome engine for it (\`${names().browser} set <id> --engine chrome\`, or start the server without \`--engine lightpanda\`).`);
|
|
80
81
|
}
|
|
81
82
|
/**
|
|
82
83
|
* How to install Lightpanda on this platform, for errors and `turno browser doctor`: one command
|
|
@@ -121,7 +122,7 @@ export function lightpandaMissing(env) {
|
|
|
121
122
|
const where = configured
|
|
122
123
|
? `TURNO_LIGHTPANDA_PATH (${configured}) is not an executable file with an absolute path`
|
|
123
124
|
: "lightpanda is not on PATH";
|
|
124
|
-
return new Error(`read mode needs Lightpanda, and ${where}. Install it: ${lightpandaInstallHint()}. turno never downloads it for you;
|
|
125
|
+
return new Error(`read mode needs Lightpanda, and ${where}. Install it: ${lightpandaInstallHint()}. turno never downloads it for you; \`${names().browser} doctor\` checks it.`);
|
|
125
126
|
}
|
|
126
127
|
/** Where an identity's read mode keeps its cookies. */
|
|
127
128
|
export function lightpandaCookieJar(id, env) {
|
package/dist/engine.js
CHANGED
|
@@ -11,6 +11,7 @@ import { keychainArgs, launchSettings, readIdentitySettings, recordEngineClash,
|
|
|
11
11
|
import { launchTuning } from "./tuning.js";
|
|
12
12
|
import { IdleTimer, idleMs } from "./idle-timer.js";
|
|
13
13
|
import { playwright, upstream } from "./upstream.js";
|
|
14
|
+
import { names } from "./names.js";
|
|
14
15
|
/** True when the config asks for the browser the `chrome` engine launches. */
|
|
15
16
|
export function usesChromeEngine(config) {
|
|
16
17
|
const b = config.browser;
|
|
@@ -62,7 +63,7 @@ function profileInUse(identity, userDataDir) {
|
|
|
62
63
|
const chrome = findProfileChrome(userDataDir);
|
|
63
64
|
const who = chrome ? `a Chrome that turno-browser-mcp did not start (pid ${chrome.pid})` : "another Chrome";
|
|
64
65
|
return new Error(`browser identity "${identity.id}" is in use by ${who}: a Chrome opened by hand on this profile, or a login from an older turno. ` +
|
|
65
|
-
`Close it, then try again;
|
|
66
|
+
`Close it, then try again; \`${names().browser} doctor\` shows who holds each identity.`);
|
|
66
67
|
}
|
|
67
68
|
/**
|
|
68
69
|
* The installed Chrome on a persistent profile, launched by turno with the options upstream's
|
package/dist/health.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
3
|
import { identityStateDir } from "./ids.js";
|
|
4
|
+
import { names } from "./names.js";
|
|
4
5
|
/** A passing check is trusted this long before the next launch checks again. */
|
|
5
6
|
const HEALTH_TTL_MS = 30 * 60_000;
|
|
6
7
|
/** After NEEDS_AUTH, calls fail without launching Chrome for this long (no window per call). */
|
|
@@ -41,7 +42,7 @@ export function healthDue(record, check, now = new Date()) {
|
|
|
41
42
|
/** The tool error for an identity that is not signed in. Written for the agent to relay. */
|
|
42
43
|
export function needsAuthMessage(id, record) {
|
|
43
44
|
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
|
|
45
|
+
`Ask the user to run \`${names().browser} login ${id}\`, sign in and close the window, then call this tool again.`);
|
|
45
46
|
}
|
|
46
47
|
const firstLine = (e) => String(e.message ?? e).split("\n")[0];
|
|
47
48
|
/** Runs the check in a new tab of the identity's browser and closes the tab. */
|
package/dist/host.d.ts
CHANGED
|
@@ -81,6 +81,22 @@ export declare class CallIdleTimer implements IdleTimerLike {
|
|
|
81
81
|
export declare function configForSession(config: McpConfig, cliOptions: Record<string, unknown>, tuning: Tuning): McpConfig;
|
|
82
82
|
/** Builds the host for a resolved config: tool list, engine and session factory. */
|
|
83
83
|
export declare function createHost(options: HostOptions): Host;
|
|
84
|
+
/**
|
|
85
|
+
* One browser for many connections: the background server's host. Each connection gets its own
|
|
86
|
+
* MCP server, and every one of them calls the same session backend, so the connections share the
|
|
87
|
+
* identity's one Chrome the way mcpd's client sessions share one stdio server. The caller puts
|
|
88
|
+
* each connection's client session in the `_meta` of its calls (`SESSION_META_KEY`), which keys
|
|
89
|
+
* the tabs of `"sharing": "tabs"`, and ends it with `endSession`.
|
|
90
|
+
*/
|
|
91
|
+
export interface SharedHost {
|
|
92
|
+
/** Serves one connection on `transport`. Closing it leaves the browser open. */
|
|
93
|
+
connect(transport: Transport): Promise<Server>;
|
|
94
|
+
/** A client session ended: with `"sharing": "tabs"` its tabs are free at once. */
|
|
95
|
+
endSession(session: string): Promise<void>;
|
|
96
|
+
/** Closes the browser. */
|
|
97
|
+
dispose(): Promise<void>;
|
|
98
|
+
}
|
|
99
|
+
export declare function shareHost(host: Host): SharedHost;
|
|
84
100
|
/** Serves the host: stdio by turno, `--port` by upstream's HTTP server. */
|
|
85
101
|
export declare function serve(host: Host, transport?: Transport): Promise<Server | undefined>;
|
|
86
102
|
/**
|
|
@@ -92,4 +108,9 @@ export declare function runHost(args: string[], options?: {
|
|
|
92
108
|
tuning?: TuningFlags;
|
|
93
109
|
engineFlags?: EngineFlags;
|
|
94
110
|
live?: LiveFlags;
|
|
111
|
+
/**
|
|
112
|
+
* Serves the host instead of stdio or `--port` (`--background`). Such a server has no client
|
|
113
|
+
* on stdin, so upstream's watchdog, which exits when stdin closes, is not installed.
|
|
114
|
+
*/
|
|
115
|
+
serve?: (host: Host) => Promise<void>;
|
|
95
116
|
}): Promise<void>;
|
package/dist/host.js
CHANGED
|
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
|
|
|
5
5
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
6
6
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
7
7
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
8
|
+
import { refuseWhileBackground } from "./background-state.js";
|
|
8
9
|
import { coveredBeforeCall, explainFailure } from "./diagnose.js";
|
|
9
10
|
import { createEngine, engineChoice, } from "./engine.js";
|
|
10
11
|
import { TabGovernor } from "./governor.js";
|
|
@@ -242,8 +243,11 @@ class SessionBackend extends EventEmitter {
|
|
|
242
243
|
const clientInfo = this.info();
|
|
243
244
|
const { config, cliOptions, stock, engine, identity } = this.host;
|
|
244
245
|
const promise = (async () => {
|
|
245
|
-
if (identity)
|
|
246
|
+
if (identity) {
|
|
247
|
+
// While the identity's background server runs, it alone launches its browser.
|
|
248
|
+
refuseWhileBackground(identity);
|
|
246
249
|
refuseWhileNeedsAuth(identity);
|
|
250
|
+
}
|
|
247
251
|
const settings = identity ? readIdentitySettings(identity.id, identity.env) : undefined;
|
|
248
252
|
const tuning = resolveTuning(settings, this.host.tuning);
|
|
249
253
|
this.recordSettings = settings?.record;
|
|
@@ -1082,28 +1086,35 @@ function samplerFor(server, requestId) {
|
|
|
1082
1086
|
};
|
|
1083
1087
|
};
|
|
1084
1088
|
}
|
|
1085
|
-
/**
|
|
1086
|
-
|
|
1089
|
+
/**
|
|
1090
|
+
* An MCP server for one connection of this host, on any transport: with its own session
|
|
1091
|
+
* backend (stdio, one browser per connection), or on the backend of a shared host.
|
|
1092
|
+
*/
|
|
1093
|
+
function createServer(host, shared) {
|
|
1087
1094
|
// The experimental capability asks mcpd to say when a client session ends (`session.ts`).
|
|
1088
1095
|
const server = new Server(SERVER_INFO, {
|
|
1089
1096
|
capabilities: { tools: { listChanged: true }, experimental: { [SESSION_CAPABILITY]: {} } },
|
|
1090
1097
|
});
|
|
1091
|
-
let
|
|
1098
|
+
let own;
|
|
1092
1099
|
const session = () => {
|
|
1093
|
-
|
|
1100
|
+
if (shared)
|
|
1101
|
+
return shared.get(server);
|
|
1102
|
+
own ??= (async () => {
|
|
1094
1103
|
const clientInfo = await clientInfoOf(server);
|
|
1095
1104
|
const b = (await host.factory.create(clientInfo));
|
|
1096
1105
|
await b.initialize(clientInfo);
|
|
1097
1106
|
b.on("dynamictoolschange", () => void server.sendToolListChanged().catch(() => { }));
|
|
1098
1107
|
return b;
|
|
1099
1108
|
})();
|
|
1100
|
-
|
|
1101
|
-
|
|
1109
|
+
own.catch(() => {
|
|
1110
|
+
own = undefined;
|
|
1102
1111
|
});
|
|
1103
|
-
return
|
|
1112
|
+
return own;
|
|
1104
1113
|
};
|
|
1114
|
+
const existing = () => (shared ? shared.peek() : own);
|
|
1115
|
+
shared?.servers.add(server);
|
|
1105
1116
|
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
1106
|
-
const live = await
|
|
1117
|
+
const live = await existing()?.catch(() => undefined);
|
|
1107
1118
|
return { tools: [...host.listTools(), ...(live?.dynamicTools() ?? [])] };
|
|
1108
1119
|
});
|
|
1109
1120
|
server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
@@ -1118,19 +1129,62 @@ function createServer(host) {
|
|
|
1118
1129
|
}
|
|
1119
1130
|
});
|
|
1120
1131
|
server.fallbackNotificationHandler = async (notification) => {
|
|
1121
|
-
|
|
1132
|
+
// On a shared host the sessions are the connections, which the host ends itself.
|
|
1133
|
+
if (shared || notification.method !== SESSION_ENDED_METHOD)
|
|
1122
1134
|
return;
|
|
1123
1135
|
const session = sessionFromMeta({ [SESSION_META_KEY]: notification.params?.session });
|
|
1124
1136
|
if (session !== undefined)
|
|
1125
|
-
await (await
|
|
1137
|
+
await (await own?.catch(() => undefined))?.endSession(session);
|
|
1126
1138
|
};
|
|
1127
1139
|
const previous = server.onclose;
|
|
1128
1140
|
server.onclose = () => {
|
|
1129
1141
|
previous?.();
|
|
1130
|
-
|
|
1142
|
+
if (shared)
|
|
1143
|
+
shared.servers.delete(server);
|
|
1144
|
+
else
|
|
1145
|
+
void own?.then((b) => b.dispose()).catch(() => { });
|
|
1131
1146
|
};
|
|
1132
1147
|
return server;
|
|
1133
1148
|
}
|
|
1149
|
+
export function shareHost(host) {
|
|
1150
|
+
let backend;
|
|
1151
|
+
const servers = new Set();
|
|
1152
|
+
const shared = {
|
|
1153
|
+
servers,
|
|
1154
|
+
peek: () => backend,
|
|
1155
|
+
get(server) {
|
|
1156
|
+
backend ??= (async () => {
|
|
1157
|
+
const clientInfo = await clientInfoOf(server);
|
|
1158
|
+
const b = (await host.factory.create(clientInfo));
|
|
1159
|
+
await b.initialize(clientInfo);
|
|
1160
|
+
b.on("dynamictoolschange", () => {
|
|
1161
|
+
for (const s of servers)
|
|
1162
|
+
void s.sendToolListChanged().catch(() => { });
|
|
1163
|
+
});
|
|
1164
|
+
return b;
|
|
1165
|
+
})();
|
|
1166
|
+
backend.catch(() => {
|
|
1167
|
+
backend = undefined;
|
|
1168
|
+
});
|
|
1169
|
+
return backend;
|
|
1170
|
+
},
|
|
1171
|
+
};
|
|
1172
|
+
return {
|
|
1173
|
+
async connect(transport) {
|
|
1174
|
+
const server = createServer(host, shared);
|
|
1175
|
+
await server.connect(transport);
|
|
1176
|
+
return server;
|
|
1177
|
+
},
|
|
1178
|
+
async endSession(session) {
|
|
1179
|
+
await (await backend?.catch(() => undefined))?.endSession(session);
|
|
1180
|
+
},
|
|
1181
|
+
async dispose() {
|
|
1182
|
+
const b = await backend?.catch(() => undefined);
|
|
1183
|
+
backend = undefined;
|
|
1184
|
+
await b?.dispose();
|
|
1185
|
+
},
|
|
1186
|
+
};
|
|
1187
|
+
}
|
|
1134
1188
|
/** Serves the host: stdio by turno, `--port` by upstream's HTTP server. */
|
|
1135
1189
|
export async function serve(host, transport) {
|
|
1136
1190
|
if (host.config.server.port !== undefined && !transport) {
|
|
@@ -1148,11 +1202,13 @@ export async function serve(host, transport) {
|
|
|
1148
1202
|
export async function runHost(args, options = {}) {
|
|
1149
1203
|
const { utils, core, version } = upstream();
|
|
1150
1204
|
const { identity, tuning, engineFlags, live } = options;
|
|
1205
|
+
const serveWith = options.serve;
|
|
1151
1206
|
const Command = utils.program.constructor;
|
|
1152
1207
|
const program = new Command().version(`Version ${version}`).name("Playwright MCP");
|
|
1153
1208
|
upstream().tools.decorateMCPCommand(program);
|
|
1154
1209
|
program.action(async (options) => {
|
|
1155
|
-
|
|
1210
|
+
if (!serveWith)
|
|
1211
|
+
upstream().tools.setupExitWatchdog();
|
|
1156
1212
|
if (options.vision) {
|
|
1157
1213
|
console.error("The --vision option is deprecated, use --caps=vision instead");
|
|
1158
1214
|
options.caps ??= [];
|
|
@@ -1161,14 +1217,18 @@ export async function runHost(args, options = {}) {
|
|
|
1161
1217
|
if (options.caps?.includes("tracing"))
|
|
1162
1218
|
options.caps.push("devtools");
|
|
1163
1219
|
const config = await upstream().tools.resolveCLIConfigForMCP(options);
|
|
1164
|
-
|
|
1220
|
+
const host = createHost({
|
|
1165
1221
|
config,
|
|
1166
1222
|
cliOptions: options,
|
|
1167
1223
|
...(identity ? { identity } : {}),
|
|
1168
1224
|
...(tuning ? { tuning } : {}),
|
|
1169
1225
|
...(engineFlags ? { engineFlags } : {}),
|
|
1170
1226
|
...(live ? { live } : {}),
|
|
1171
|
-
})
|
|
1227
|
+
});
|
|
1228
|
+
if (serveWith)
|
|
1229
|
+
await serveWith(host);
|
|
1230
|
+
else
|
|
1231
|
+
await serve(host);
|
|
1172
1232
|
});
|
|
1173
1233
|
try {
|
|
1174
1234
|
await program.parseAsync(args, { from: "user" });
|