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.
- package/CHANGELOG.md +228 -0
- package/README.md +205 -16
- package/dist/act-model.d.ts +85 -0
- package/dist/act-model.js +116 -0
- package/dist/act.d.ts +37 -0
- package/dist/act.js +599 -0
- package/dist/api.d.ts +96 -0
- package/dist/api.js +88 -0
- package/dist/argv.d.ts +55 -3
- package/dist/argv.js +190 -10
- package/dist/batch.d.ts +19 -0
- package/dist/batch.js +148 -0
- package/dist/bench.d.ts +1 -1
- package/dist/bench.js +21 -5
- package/dist/bin/mcp.js +108 -12
- package/dist/captcha.d.ts +77 -0
- package/dist/captcha.js +333 -0
- package/dist/cdp-relay.d.ts +20 -0
- package/dist/cdp-relay.js +101 -0
- package/dist/chrome-features.d.ts +23 -0
- package/dist/chrome-features.js +44 -0
- package/dist/detectors.d.ts +11 -0
- package/dist/detectors.js +46 -4
- package/dist/diagnose.d.ts +45 -0
- package/dist/diagnose.js +326 -0
- package/dist/doctor.d.ts +85 -0
- package/dist/doctor.js +556 -0
- package/dist/engine-attach.d.ts +27 -0
- package/dist/engine-attach.js +165 -0
- package/dist/engine-camoufox.d.ts +32 -0
- package/dist/engine-camoufox.js +270 -0
- package/dist/engine-lightpanda.d.ts +72 -0
- package/dist/engine-lightpanda.js +292 -0
- package/dist/engine.d.ts +119 -0
- package/dist/engine.js +355 -0
- package/dist/flows.d.ts +127 -0
- package/dist/flows.js +294 -0
- package/dist/governor.d.ts +119 -0
- package/dist/governor.js +325 -0
- package/dist/health.d.ts +60 -0
- package/dist/health.js +86 -0
- package/dist/host.d.ts +95 -0
- package/dist/host.js +1181 -0
- package/dist/human-input.d.ts +84 -0
- package/dist/human-input.js +443 -0
- package/dist/humanize.d.ts +123 -0
- package/dist/humanize.js +241 -0
- package/dist/identities.d.ts +23 -10
- package/dist/identities.js +45 -37
- package/dist/idle-timer.d.ts +12 -0
- package/dist/idle-timer.js +25 -0
- package/dist/ids.d.ts +9 -0
- package/dist/ids.js +34 -0
- package/dist/index.d.ts +21 -6
- package/dist/index.js +19 -18
- package/dist/lifecycle.d.ts +99 -0
- package/dist/lifecycle.js +172 -0
- package/dist/live-client.d.ts +22 -0
- package/dist/live-client.js +93 -0
- package/dist/live-page.d.ts +11 -0
- package/dist/live-page.js +143 -0
- package/dist/live-server.d.ts +173 -0
- package/dist/live-server.js +640 -0
- package/dist/live.d.ts +120 -0
- package/dist/live.js +203 -0
- package/dist/login-tool.d.ts +45 -0
- package/dist/login-tool.js +233 -0
- package/dist/login.d.ts +8 -3
- package/dist/login.js +65 -26
- package/dist/network-chrome.d.ts +74 -0
- package/dist/network-chrome.js +178 -0
- package/dist/network.d.ts +125 -0
- package/dist/network.js +263 -0
- package/dist/opt-in-settings.d.ts +69 -0
- package/dist/opt-in-settings.js +151 -0
- package/dist/patchright.d.ts +4 -2
- package/dist/patchright.js +4 -2
- package/dist/recorder.d.ts +88 -0
- package/dist/recorder.js +538 -0
- package/dist/recordings.d.ts +116 -0
- package/dist/recordings.js +474 -0
- package/dist/redact.d.ts +34 -0
- package/dist/redact.js +135 -0
- package/dist/replay.d.ts +20 -0
- package/dist/replay.js +382 -0
- package/dist/reputation.d.ts +89 -0
- package/dist/reputation.js +203 -0
- package/dist/resources.d.ts +76 -0
- package/dist/resources.js +341 -0
- package/dist/runtime-lock.d.ts +59 -0
- package/dist/runtime-lock.js +131 -0
- package/dist/sealed.d.ts +8 -0
- package/dist/sealed.js +96 -0
- package/dist/session-export.d.ts +67 -0
- package/dist/session-export.js +194 -0
- package/dist/session.d.ts +20 -0
- package/dist/session.js +30 -0
- package/dist/settings.d.ts +246 -0
- package/dist/settings.js +530 -0
- package/dist/sharing.d.ts +96 -0
- package/dist/sharing.js +269 -0
- package/dist/snippet.d.ts +8 -0
- package/dist/snippet.js +22 -0
- package/dist/tab-locks.d.ts +63 -0
- package/dist/tab-locks.js +179 -0
- package/dist/tools.d.ts +111 -0
- package/dist/tools.js +59 -0
- package/dist/totp.d.ts +32 -0
- package/dist/totp.js +82 -0
- package/dist/tuning.d.ts +76 -0
- package/dist/tuning.js +69 -0
- package/dist/units.d.ts +8 -0
- package/dist/units.js +20 -0
- package/dist/upstream.d.ts +243 -0
- package/dist/upstream.js +46 -0
- package/dist/vault.d.ts +91 -0
- package/dist/vault.js +273 -0
- package/npm-shrinkwrap.json +1074 -3
- package/package.json +5 -4
- package/dist/paths.d.ts +0 -17
- package/dist/paths.js +0 -17
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { type ProcTable } from "turno-core/process";
|
|
2
|
+
/**
|
|
3
|
+
* The life of the Chrome behind one profile.
|
|
4
|
+
*
|
|
5
|
+
* Playwright launches Chrome as the leader of its own process group and only kills that group
|
|
6
|
+
* from exit handlers, which never run when the server is killed with SIGKILL. So
|
|
7
|
+
* turno-browser-mcp
|
|
8
|
+
*
|
|
9
|
+
* - sweeps a Chrome that an earlier run left behind for the same profile before it starts
|
|
10
|
+
* (`sweepOrphan`): the profile's `SingletonLock` names the PID, the process table confirms it
|
|
11
|
+
* is a Chrome browser process for exactly that `--user-data-dir`, and its parent must be gone
|
|
12
|
+
* (reparented to init), so a Chrome another live process drives is never touched;
|
|
13
|
+
* - puts a deadline on its own shutdown (`installShutdownGuard`): when stdin closes or a
|
|
14
|
+
* signal arrives the program closes the browser gracefully, and if that has not finished in
|
|
15
|
+
* time Chrome gets SIGTERM and then the whole group SIGKILL, inside the 4 seconds the MCP SDK
|
|
16
|
+
* gives a server before it kills it.
|
|
17
|
+
*/
|
|
18
|
+
export { type ProcTable, parseProcTable } from "turno-core/process";
|
|
19
|
+
/** The PID in the profile's `SingletonLock` (`<host>-<pid>`), if there is one. */
|
|
20
|
+
export declare function readLockPid(userDataDir: string): number | undefined;
|
|
21
|
+
/**
|
|
22
|
+
* True when the command line passes exactly this profile as `--user-data-dir=<dir>` (the form
|
|
23
|
+
* Playwright gives Chrome and its helpers; the wrapper's own `--user-data-dir <dir>` never
|
|
24
|
+
* matches). Spaces in the path are fine; `<dir>-2` or `<dir>/sub` are other profiles.
|
|
25
|
+
*/
|
|
26
|
+
export declare function usesProfile(command: string, userDataDir: string): boolean;
|
|
27
|
+
/** The browser process itself, not a renderer, GPU or utility helper (those carry `--type=`). */
|
|
28
|
+
export declare function isBrowserProcess(command: string): boolean;
|
|
29
|
+
/** Who drives the Chrome behind a profile: this process, nobody (an orphan), or someone else. */
|
|
30
|
+
type ChromeOwner = "self" | "orphan" | "other";
|
|
31
|
+
export interface ProfileChrome {
|
|
32
|
+
/** The PID in the lock: the browser process, and the leader of its process group. */
|
|
33
|
+
pid: number;
|
|
34
|
+
pgid: number;
|
|
35
|
+
/** False when only helpers are left in the group. */
|
|
36
|
+
leaderAlive: boolean;
|
|
37
|
+
owner: ChromeOwner;
|
|
38
|
+
}
|
|
39
|
+
type Alive = (pid: number) => boolean;
|
|
40
|
+
type Signal = (pid: number, signal: NodeJS.Signals) => void;
|
|
41
|
+
export interface FindOptions {
|
|
42
|
+
/** The process table to use (tests); read with `ps` when missing. */
|
|
43
|
+
table?: ProcTable;
|
|
44
|
+
readTable?: () => ProcTable | undefined;
|
|
45
|
+
alive?: Alive;
|
|
46
|
+
/** The PID that counts as "self" (default: this process). */
|
|
47
|
+
selfPid?: number;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The Chrome that holds this profile, after checking that the PID in the lock really is a
|
|
51
|
+
* Chrome browser process for this exact profile dir. Undefined when there is none, or when the
|
|
52
|
+
* lock points at some other program (a reused PID).
|
|
53
|
+
*/
|
|
54
|
+
export declare function findProfileChrome(userDataDir: string, opts?: FindOptions): ProfileChrome | undefined;
|
|
55
|
+
/**
|
|
56
|
+
* How long `stopChrome` waits for the group to go after SIGKILL. A SIGKILL is delivered at
|
|
57
|
+
* once, but the group is gone only when the kernel has torn down every member and init (or a
|
|
58
|
+
* subreaper) has reaped each one: until then `kill(-pgid, 0)` still finds the zombies. On a
|
|
59
|
+
* loaded two-core CI runner with several Chromes that took more than 2 seconds, and the sweep
|
|
60
|
+
* then reported a Chrome that "did not stop" while it was already dying.
|
|
61
|
+
*/
|
|
62
|
+
export declare const KILL_WAIT_MS = 5000;
|
|
63
|
+
export interface StopOptions {
|
|
64
|
+
/** How long the browser gets to quit after SIGTERM. */
|
|
65
|
+
graceMs?: number;
|
|
66
|
+
/** How long to wait for the group to go after SIGKILL (default `KILL_WAIT_MS`). */
|
|
67
|
+
killMs?: number;
|
|
68
|
+
signal?: Signal;
|
|
69
|
+
alive?: Alive;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Gracefully, then forcefully: SIGTERM to the browser process alone (it shuts its helpers down
|
|
73
|
+
* and writes the profile, cookies included; a SIGTERM to the whole group would kill the network
|
|
74
|
+
* process that holds the cookie store at the same moment), then SIGKILL to the whole group.
|
|
75
|
+
* A group is only signalled when the browser process leads it.
|
|
76
|
+
*/
|
|
77
|
+
export declare function stopChrome(target: ProfileChrome, opts?: StopOptions): Promise<"exited" | "killed" | "survived">;
|
|
78
|
+
export interface SweepResult {
|
|
79
|
+
/** `none`: nothing holds the profile; `in-use`: a live process drives it, left alone. */
|
|
80
|
+
action: "none" | "in-use" | "exited" | "killed" | "survived";
|
|
81
|
+
pid?: number;
|
|
82
|
+
}
|
|
83
|
+
/** Stop a Chrome that an earlier run left behind on this profile (see the module comment). */
|
|
84
|
+
export declare function sweepOrphan(userDataDir: string, opts?: FindOptions & StopOptions): Promise<SweepResult>;
|
|
85
|
+
export interface ShutdownOptions {
|
|
86
|
+
/** Time the program gets to close the browser gracefully before Chrome gets SIGTERM. */
|
|
87
|
+
graceMs?: number;
|
|
88
|
+
/** Time Chrome gets after SIGTERM before this process exits and its group gets SIGKILL. */
|
|
89
|
+
termMs?: number;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Bound the shutdown of this server. The program's own watchdog closes the browser when stdin
|
|
93
|
+
* closes or on SIGINT and SIGTERM, but it allows itself 15 seconds, while the MCP SDK sends
|
|
94
|
+
* SIGTERM 2 seconds after closing stdin and SIGKILL 2 seconds later. After `graceMs` the Chrome
|
|
95
|
+
* this process started gets SIGTERM; after `termMs` more this process exits, and the exit
|
|
96
|
+
* handler SIGKILLs the group if it is still there. SIGHUP is turned into SIGTERM so the
|
|
97
|
+
* program closes the browser instead of the process dying with it open.
|
|
98
|
+
*/
|
|
99
|
+
export declare function installShutdownGuard(userDataDir: string, opts?: ShutdownOptions): void;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { readlinkSync, realpathSync } from "node:fs";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { parentIsInit, pidAlive as processAlive, readProcTable, signalProcess as sendSignal, } from "turno-core/process";
|
|
4
|
+
import { parseSingletonLock } from "./identities.js";
|
|
5
|
+
/**
|
|
6
|
+
* The life of the Chrome behind one profile.
|
|
7
|
+
*
|
|
8
|
+
* Playwright launches Chrome as the leader of its own process group and only kills that group
|
|
9
|
+
* from exit handlers, which never run when the server is killed with SIGKILL. So
|
|
10
|
+
* turno-browser-mcp
|
|
11
|
+
*
|
|
12
|
+
* - sweeps a Chrome that an earlier run left behind for the same profile before it starts
|
|
13
|
+
* (`sweepOrphan`): the profile's `SingletonLock` names the PID, the process table confirms it
|
|
14
|
+
* is a Chrome browser process for exactly that `--user-data-dir`, and its parent must be gone
|
|
15
|
+
* (reparented to init), so a Chrome another live process drives is never touched;
|
|
16
|
+
* - puts a deadline on its own shutdown (`installShutdownGuard`): when stdin closes or a
|
|
17
|
+
* signal arrives the program closes the browser gracefully, and if that has not finished in
|
|
18
|
+
* time Chrome gets SIGTERM and then the whole group SIGKILL, inside the 4 seconds the MCP SDK
|
|
19
|
+
* gives a server before it kills it.
|
|
20
|
+
*/
|
|
21
|
+
export { parseProcTable } from "turno-core/process";
|
|
22
|
+
/** The PID in the profile's `SingletonLock` (`<host>-<pid>`), if there is one. */
|
|
23
|
+
export function readLockPid(userDataDir) {
|
|
24
|
+
try {
|
|
25
|
+
return parseSingletonLock(readlinkSync(join(userDataDir, "SingletonLock")));
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* True when the command line passes exactly this profile as `--user-data-dir=<dir>` (the form
|
|
33
|
+
* Playwright gives Chrome and its helpers; the wrapper's own `--user-data-dir <dir>` never
|
|
34
|
+
* matches). Spaces in the path are fine; `<dir>-2` or `<dir>/sub` are other profiles.
|
|
35
|
+
*/
|
|
36
|
+
export function usesProfile(command, userDataDir) {
|
|
37
|
+
const dirs = new Set([userDataDir]);
|
|
38
|
+
try {
|
|
39
|
+
dirs.add(realpathSync(userDataDir));
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
/* the profile is gone: only the given path can match */
|
|
43
|
+
}
|
|
44
|
+
for (const dir of dirs) {
|
|
45
|
+
const flag = `--user-data-dir=${dir}`;
|
|
46
|
+
for (let i = command.indexOf(flag); i >= 0; i = command.indexOf(flag, i + 1)) {
|
|
47
|
+
const end = i + flag.length;
|
|
48
|
+
if (end === command.length || command[end] === " ")
|
|
49
|
+
return true;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
/** The browser process itself, not a renderer, GPU or utility helper (those carry `--type=`). */
|
|
55
|
+
export function isBrowserProcess(command) {
|
|
56
|
+
return !/(^|\s)--type=/.test(command);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The Chrome that holds this profile, after checking that the PID in the lock really is a
|
|
60
|
+
* Chrome browser process for this exact profile dir. Undefined when there is none, or when the
|
|
61
|
+
* lock points at some other program (a reused PID).
|
|
62
|
+
*/
|
|
63
|
+
export function findProfileChrome(userDataDir, opts = {}) {
|
|
64
|
+
const pid = readLockPid(userDataDir);
|
|
65
|
+
if (pid === undefined)
|
|
66
|
+
return undefined;
|
|
67
|
+
const alive = opts.alive ?? processAlive;
|
|
68
|
+
if (!opts.table && !alive(pid) && !alive(-pid))
|
|
69
|
+
return undefined;
|
|
70
|
+
const table = opts.table ?? (opts.readTable ?? readProcTable)();
|
|
71
|
+
if (!table)
|
|
72
|
+
return undefined;
|
|
73
|
+
const self = opts.selfPid ?? process.pid;
|
|
74
|
+
const leader = table.get(pid);
|
|
75
|
+
if (leader) {
|
|
76
|
+
if (!usesProfile(leader.command, userDataDir) || !isBrowserProcess(leader.command))
|
|
77
|
+
return undefined;
|
|
78
|
+
const owner = leader.ppid === self ? "self" : parentIsInit(leader.ppid, table) ? "orphan" : "other";
|
|
79
|
+
return { pid, pgid: leader.pgid, leaderAlive: true, owner };
|
|
80
|
+
}
|
|
81
|
+
// The browser process died but helpers of its group may still run.
|
|
82
|
+
const members = [...table.values()].filter((p) => p.pgid === pid && usesProfile(p.command, userDataDir));
|
|
83
|
+
if (!members.length)
|
|
84
|
+
return undefined;
|
|
85
|
+
const orphaned = members.every((m) => parentIsInit(m.ppid, table) || table.get(m.ppid)?.pgid === pid);
|
|
86
|
+
return { pid, pgid: pid, leaderAlive: false, owner: orphaned ? "orphan" : "other" };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* How long `stopChrome` waits for the group to go after SIGKILL. A SIGKILL is delivered at
|
|
90
|
+
* once, but the group is gone only when the kernel has torn down every member and init (or a
|
|
91
|
+
* subreaper) has reaped each one: until then `kill(-pgid, 0)` still finds the zombies. On a
|
|
92
|
+
* loaded two-core CI runner with several Chromes that took more than 2 seconds, and the sweep
|
|
93
|
+
* then reported a Chrome that "did not stop" while it was already dying.
|
|
94
|
+
*/
|
|
95
|
+
export const KILL_WAIT_MS = 5_000;
|
|
96
|
+
async function waitUntil(cond, ms) {
|
|
97
|
+
const end = Date.now() + ms;
|
|
98
|
+
while (!cond()) {
|
|
99
|
+
if (Date.now() >= end)
|
|
100
|
+
return false;
|
|
101
|
+
await new Promise((r) => setTimeout(r, 50));
|
|
102
|
+
}
|
|
103
|
+
return true;
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Gracefully, then forcefully: SIGTERM to the browser process alone (it shuts its helpers down
|
|
107
|
+
* and writes the profile, cookies included; a SIGTERM to the whole group would kill the network
|
|
108
|
+
* process that holds the cookie store at the same moment), then SIGKILL to the whole group.
|
|
109
|
+
* A group is only signalled when the browser process leads it.
|
|
110
|
+
*/
|
|
111
|
+
export async function stopChrome(target, opts = {}) {
|
|
112
|
+
const signal = opts.signal ?? sendSignal;
|
|
113
|
+
const alive = opts.alive ?? processAlive;
|
|
114
|
+
const leadsGroup = target.pgid === target.pid;
|
|
115
|
+
const handle = leadsGroup ? -target.pid : target.pid;
|
|
116
|
+
const gone = () => !alive(handle);
|
|
117
|
+
signal(target.leaderAlive ? target.pid : handle, "SIGTERM");
|
|
118
|
+
if (await waitUntil(gone, opts.graceMs ?? 3000))
|
|
119
|
+
return "exited";
|
|
120
|
+
signal(handle, "SIGKILL");
|
|
121
|
+
return (await waitUntil(gone, opts.killMs ?? KILL_WAIT_MS)) ? "killed" : "survived";
|
|
122
|
+
}
|
|
123
|
+
/** Stop a Chrome that an earlier run left behind on this profile (see the module comment). */
|
|
124
|
+
export async function sweepOrphan(userDataDir, opts = {}) {
|
|
125
|
+
const found = findProfileChrome(userDataDir, opts);
|
|
126
|
+
if (!found)
|
|
127
|
+
return { action: "none" };
|
|
128
|
+
if (found.owner !== "orphan")
|
|
129
|
+
return { action: "in-use", pid: found.pid };
|
|
130
|
+
return { action: await stopChrome(found, opts), pid: found.pid };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Bound the shutdown of this server. The program's own watchdog closes the browser when stdin
|
|
134
|
+
* closes or on SIGINT and SIGTERM, but it allows itself 15 seconds, while the MCP SDK sends
|
|
135
|
+
* SIGTERM 2 seconds after closing stdin and SIGKILL 2 seconds later. After `graceMs` the Chrome
|
|
136
|
+
* this process started gets SIGTERM; after `termMs` more this process exits, and the exit
|
|
137
|
+
* handler SIGKILLs the group if it is still there. SIGHUP is turned into SIGTERM so the
|
|
138
|
+
* program closes the browser instead of the process dying with it open.
|
|
139
|
+
*/
|
|
140
|
+
export function installShutdownGuard(userDataDir, opts = {}) {
|
|
141
|
+
const graceMs = opts.graceMs ?? 1500;
|
|
142
|
+
const termMs = opts.termMs ?? 1000;
|
|
143
|
+
const ours = () => {
|
|
144
|
+
const c = findProfileChrome(userDataDir);
|
|
145
|
+
return c && c.owner !== "other" ? c : undefined;
|
|
146
|
+
};
|
|
147
|
+
let started = false;
|
|
148
|
+
const begin = () => {
|
|
149
|
+
if (started)
|
|
150
|
+
return;
|
|
151
|
+
started = true;
|
|
152
|
+
setTimeout(() => {
|
|
153
|
+
const c = ours();
|
|
154
|
+
if (c?.leaderAlive)
|
|
155
|
+
sendSignal(c.pid, "SIGTERM");
|
|
156
|
+
setTimeout(() => process.exit(0), termMs).unref();
|
|
157
|
+
}, graceMs).unref();
|
|
158
|
+
};
|
|
159
|
+
process.stdin.once("close", begin);
|
|
160
|
+
process.on("SIGTERM", begin);
|
|
161
|
+
process.on("SIGINT", begin);
|
|
162
|
+
process.on("SIGHUP", () => {
|
|
163
|
+
begin();
|
|
164
|
+
process.kill(process.pid, "SIGTERM");
|
|
165
|
+
});
|
|
166
|
+
process.on("exit", () => {
|
|
167
|
+
const c = ours();
|
|
168
|
+
if (c)
|
|
169
|
+
sendSignal(c.pgid === c.pid ? -c.pid : c.pid, "SIGKILL");
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=lifecycle.js.map
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type LiveFile } from "./live.js";
|
|
2
|
+
import type { LiveStatus } from "./live-server.js";
|
|
3
|
+
/**
|
|
4
|
+
* What `turno browser live|pause|resume` use: the running server's live view, reached over its
|
|
5
|
+
* control socket (`live-server.ts`). Nothing here holds a token; a link for the view comes
|
|
6
|
+
* from the server with a code that works once.
|
|
7
|
+
*/
|
|
8
|
+
export declare class LiveError extends Error {
|
|
9
|
+
name: string;
|
|
10
|
+
}
|
|
11
|
+
/** The live.json of a running server, or undefined (a stale one is removed). */
|
|
12
|
+
export declare function readLiveFile(id: string, env?: NodeJS.ProcessEnv): LiveFile | undefined;
|
|
13
|
+
/** The live view's state, or undefined when no server serves it. */
|
|
14
|
+
export declare function liveStatus(id: string, env?: NodeJS.ProcessEnv): Promise<LiveStatus | undefined>;
|
|
15
|
+
/** Pauses the agent of `id`: its next call waits until `liveResume`. */
|
|
16
|
+
export declare function livePause(id: string, env?: NodeJS.ProcessEnv): Promise<LiveStatus>;
|
|
17
|
+
export declare function liveResume(id: string, env?: NodeJS.ProcessEnv): Promise<LiveStatus>;
|
|
18
|
+
/**
|
|
19
|
+
* A link that opens the view once, within two minutes. It carries a one-time code: open it,
|
|
20
|
+
* do not print or log it.
|
|
21
|
+
*/
|
|
22
|
+
export declare function liveLink(id: string, env?: NodeJS.ProcessEnv): Promise<string>;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
2
|
+
import { request } from "node:http";
|
|
3
|
+
import { pidAlive } from "turno-core/process";
|
|
4
|
+
import { assertIdentityId } from "./ids.js";
|
|
5
|
+
import { liveFilePath } from "./live.js";
|
|
6
|
+
/**
|
|
7
|
+
* What `turno browser live|pause|resume` use: the running server's live view, reached over its
|
|
8
|
+
* control socket (`live-server.ts`). Nothing here holds a token; a link for the view comes
|
|
9
|
+
* from the server with a code that works once.
|
|
10
|
+
*/
|
|
11
|
+
export class LiveError extends Error {
|
|
12
|
+
name = "LiveError";
|
|
13
|
+
}
|
|
14
|
+
/** The live.json of a running server, or undefined (a stale one is removed). */
|
|
15
|
+
export function readLiveFile(id, env = process.env) {
|
|
16
|
+
assertIdentityId(id);
|
|
17
|
+
const file = liveFilePath(id, env);
|
|
18
|
+
let data;
|
|
19
|
+
try {
|
|
20
|
+
data = JSON.parse(readFileSync(file, "utf8"));
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
if (data.version !== 1 || typeof data.pid !== "number" || typeof data.socket !== "string")
|
|
26
|
+
return undefined;
|
|
27
|
+
if (!pidAlive(data.pid)) {
|
|
28
|
+
rmSync(file, { force: true });
|
|
29
|
+
return undefined;
|
|
30
|
+
}
|
|
31
|
+
return data;
|
|
32
|
+
}
|
|
33
|
+
function call(socket, method, path) {
|
|
34
|
+
return new Promise((resolve, reject) => {
|
|
35
|
+
const req = request({ socketPath: socket, method, path, headers: { host: "turno-live" }, timeout: 10_000 }, (res) => {
|
|
36
|
+
const chunks = [];
|
|
37
|
+
res.on("data", (c) => chunks.push(c));
|
|
38
|
+
res.on("end", () => {
|
|
39
|
+
let body;
|
|
40
|
+
try {
|
|
41
|
+
body = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
body = undefined;
|
|
45
|
+
}
|
|
46
|
+
resolve({ status: res.statusCode ?? 0, body });
|
|
47
|
+
});
|
|
48
|
+
});
|
|
49
|
+
req.on("timeout", () => req.destroy(new Error("the live view server did not answer in 10s")));
|
|
50
|
+
req.on("error", reject);
|
|
51
|
+
if (method === "POST")
|
|
52
|
+
req.end("{}");
|
|
53
|
+
else
|
|
54
|
+
req.end();
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
async function ask(id, method, path, env) {
|
|
58
|
+
const live = readLiveFile(id, env);
|
|
59
|
+
if (!live)
|
|
60
|
+
throw new LiveError(`no turno-browser-mcp serves "${id}" with the live view right now. It is off by default: turn it on with turno browser set ${id} --live true, and it starts with the next server (an agent session starts one).`);
|
|
61
|
+
let out;
|
|
62
|
+
try {
|
|
63
|
+
out = await call(live.socket, method, path);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
throw new LiveError(`cannot reach the live view of "${id}" (pid ${live.pid}): ${error.message}`);
|
|
67
|
+
}
|
|
68
|
+
const error = out.body?.error;
|
|
69
|
+
if (out.status !== 200)
|
|
70
|
+
throw new LiveError(typeof error === "string" ? error : `the live view answered ${out.status}`);
|
|
71
|
+
return out.body;
|
|
72
|
+
}
|
|
73
|
+
/** The live view's state, or undefined when no server serves it. */
|
|
74
|
+
export async function liveStatus(id, env = process.env) {
|
|
75
|
+
if (!readLiveFile(id, env))
|
|
76
|
+
return undefined;
|
|
77
|
+
return (await ask(id, "GET", "/state", env));
|
|
78
|
+
}
|
|
79
|
+
/** Pauses the agent of `id`: its next call waits until `liveResume`. */
|
|
80
|
+
export async function livePause(id, env = process.env) {
|
|
81
|
+
return (await ask(id, "POST", "/pause", env));
|
|
82
|
+
}
|
|
83
|
+
export async function liveResume(id, env = process.env) {
|
|
84
|
+
return (await ask(id, "POST", "/resume", env));
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* A link that opens the view once, within two minutes. It carries a one-time code: open it,
|
|
88
|
+
* do not print or log it.
|
|
89
|
+
*/
|
|
90
|
+
export async function liveLink(id, env = process.env) {
|
|
91
|
+
return (await ask(id, "POST", "/link", env)).url;
|
|
92
|
+
}
|
|
93
|
+
//# sourceMappingURL=live-client.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live view page: one HTML document with its style and script inline, allowed by a nonce
|
|
3
|
+
* in the Content-Security-Policy. It reads the server's events (`/events`: the state and the
|
|
4
|
+
* frames of the tab it shows), and posts Pause, Resume, the tab to show and, while the agent is
|
|
5
|
+
* paused, the user's clicks, keys and scrolls. Text from pages (titles, URLs) only ever goes into
|
|
6
|
+
* `textContent`, never into HTML.
|
|
7
|
+
*/
|
|
8
|
+
/** The page, with the nonce the response's Content-Security-Policy allows. */
|
|
9
|
+
export declare function livePage(nonce: string): string;
|
|
10
|
+
/** What a browser without the view's cookie sees. */
|
|
11
|
+
export declare function deniedPage(identity: string): string;
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The live view page: one HTML document with its style and script inline, allowed by a nonce
|
|
3
|
+
* in the Content-Security-Policy. It reads the server's events (`/events`: the state and the
|
|
4
|
+
* frames of the tab it shows), and posts Pause, Resume, the tab to show and, while the agent is
|
|
5
|
+
* paused, the user's clicks, keys and scrolls. Text from pages (titles, URLs) only ever goes into
|
|
6
|
+
* `textContent`, never into HTML.
|
|
7
|
+
*/
|
|
8
|
+
const STYLE = `
|
|
9
|
+
:root { color-scheme: light dark; --bg: #f6f6f4; --fg: #1c1c1a; --muted: #6b6b66; --line: #d9d9d4; --accent: #2b5fd9; --warn: #b4561a; }
|
|
10
|
+
@media (prefers-color-scheme: dark) { :root { --bg: #151514; --fg: #ecece8; --muted: #9a9a94; --line: #34342f; --accent: #7aa2ff; --warn: #f0a060; } }
|
|
11
|
+
* { box-sizing: border-box; }
|
|
12
|
+
body { margin: 0; font: 14px/1.4 system-ui, sans-serif; background: var(--bg); color: var(--fg); }
|
|
13
|
+
header { display: flex; flex-wrap: wrap; gap: 8px 12px; align-items: center; padding: 10px 16px; border-bottom: 1px solid var(--line); }
|
|
14
|
+
header strong { font-weight: 600; }
|
|
15
|
+
#status { color: var(--muted); flex: 1 1 200px; }
|
|
16
|
+
#status.paused { color: var(--warn); }
|
|
17
|
+
button { font: inherit; padding: 4px 12px; border: 1px solid var(--line); border-radius: 6px; background: transparent; color: var(--fg); cursor: pointer; }
|
|
18
|
+
button:disabled { opacity: .4; cursor: default; }
|
|
19
|
+
button.on { border-color: var(--accent); color: var(--accent); }
|
|
20
|
+
nav { display: flex; flex-wrap: wrap; gap: 6px; padding: 8px 16px; border-bottom: 1px solid var(--line); }
|
|
21
|
+
nav button { max-width: 280px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; }
|
|
22
|
+
main { padding: 12px 16px; }
|
|
23
|
+
#notice { color: var(--warn); margin-bottom: 8px; min-height: 1.4em; }
|
|
24
|
+
#frame { display: block; max-width: 100%; height: auto; border: 1px solid var(--line); outline: none; }
|
|
25
|
+
#frame:focus { border-color: var(--accent); }
|
|
26
|
+
#frame:not([src]) { display: none; }
|
|
27
|
+
footer { padding: 0 16px 16px; color: var(--muted); font-size: 13px; }
|
|
28
|
+
`;
|
|
29
|
+
const SCRIPT = `
|
|
30
|
+
const $ = (id) => document.getElementById(id);
|
|
31
|
+
const frame = $("frame");
|
|
32
|
+
let state = null;
|
|
33
|
+
let size = { w: 0, h: 0 };
|
|
34
|
+
function note(text) { $("notice").textContent = text || ""; }
|
|
35
|
+
async function post(path, body) {
|
|
36
|
+
try {
|
|
37
|
+
const res = await fetch(path, { method: "POST", headers: { "content-type": "application/json", "x-turno-live": "1" }, body: JSON.stringify(body || {}) });
|
|
38
|
+
const data = await res.json();
|
|
39
|
+
if (data.error) note(data.error);
|
|
40
|
+
else if (data.identity) render(data);
|
|
41
|
+
} catch (error) { note(String(error)); }
|
|
42
|
+
}
|
|
43
|
+
function render(s) {
|
|
44
|
+
state = s;
|
|
45
|
+
$("id").textContent = s.identity;
|
|
46
|
+
const status = $("status");
|
|
47
|
+
status.className = s.paused ? "paused" : "";
|
|
48
|
+
status.textContent = s.paused
|
|
49
|
+
? "Paused (" + s.paused.by + "). " + (s.waiting ? s.waiting + " agent call" + (s.waiting === 1 ? " is" : "s are") + " waiting. " : "") + (s.busy ? "A call that started before the pause is still running." : "You have the controls.")
|
|
50
|
+
: (s.busy ? "The agent is working." : "The agent is idle.") + (s.browser ? "" : " The browser is not running.");
|
|
51
|
+
$("pause").disabled = !!s.paused;
|
|
52
|
+
$("resume").disabled = !s.paused;
|
|
53
|
+
const tabs = $("tabs");
|
|
54
|
+
tabs.replaceChildren();
|
|
55
|
+
const follow = document.createElement("button");
|
|
56
|
+
follow.textContent = "Follow the agent";
|
|
57
|
+
follow.className = s.pinned ? "" : "on";
|
|
58
|
+
follow.onclick = () => post("/follow", { tab: null });
|
|
59
|
+
tabs.append(follow);
|
|
60
|
+
for (const t of s.tabs) {
|
|
61
|
+
const b = document.createElement("button");
|
|
62
|
+
b.textContent = (t.session ? "[" + t.session + "] " : "") + (t.title || t.url || "(blank)");
|
|
63
|
+
b.title = t.url;
|
|
64
|
+
b.className = t.id === s.showing ? "on" : "";
|
|
65
|
+
b.onclick = () => post("/follow", { tab: t.id });
|
|
66
|
+
tabs.append(b);
|
|
67
|
+
}
|
|
68
|
+
let why = "";
|
|
69
|
+
if (!s.view.available) why = s.view.reason;
|
|
70
|
+
else if (s.hidden) why = "Hidden: this page holds a vault or sensitive value. It shows again after the page navigates.";
|
|
71
|
+
else if (!s.browser) why = "Nothing to show until the agent opens the browser.";
|
|
72
|
+
if (why) frame.removeAttribute("src");
|
|
73
|
+
note(why);
|
|
74
|
+
$("help").textContent = s.view.available
|
|
75
|
+
? (s.paused ? "Click, scroll and type on the picture to act on the page. Resume when you are done; the agent is told what changed." : "Pause to take the controls: the agent's next call waits until you resume (up to " + Math.round(s.wait / 1000) + " s per call).")
|
|
76
|
+
: "Pause and resume still work: the agent's next call waits until you resume.";
|
|
77
|
+
}
|
|
78
|
+
const events = new EventSource("/events");
|
|
79
|
+
events.addEventListener("state", (e) => render(JSON.parse(e.data)));
|
|
80
|
+
events.addEventListener("frame", (e) => {
|
|
81
|
+
const f = JSON.parse(e.data);
|
|
82
|
+
if (!state || !state.view.available || state.hidden) return;
|
|
83
|
+
size = { w: f.w, h: f.h };
|
|
84
|
+
frame.src = "data:image/jpeg;base64," + f.data;
|
|
85
|
+
});
|
|
86
|
+
events.onerror = () => { $("status").textContent = "Disconnected: the server stopped or restarted. Open the view again with turno browser live."; };
|
|
87
|
+
$("pause").onclick = () => post("/pause");
|
|
88
|
+
$("resume").onclick = () => post("/resume");
|
|
89
|
+
function point(e) {
|
|
90
|
+
const r = frame.getBoundingClientRect();
|
|
91
|
+
return { x: Math.round(((e.clientX - r.left) * size.w) / r.width), y: Math.round(((e.clientY - r.top) * size.h) / r.height) };
|
|
92
|
+
}
|
|
93
|
+
function canAct() {
|
|
94
|
+
if (state && state.paused) return true;
|
|
95
|
+
note("Pause first: your input goes to the page only while the agent waits.");
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
frame.addEventListener("click", (e) => { frame.focus(); if (canAct()) post("/input", { type: "click", ...point(e) }); });
|
|
99
|
+
frame.addEventListener("dblclick", (e) => { if (canAct()) post("/input", { type: "dblclick", ...point(e) }); });
|
|
100
|
+
let wheel = null;
|
|
101
|
+
frame.addEventListener("wheel", (e) => {
|
|
102
|
+
if (!state || !state.paused) return;
|
|
103
|
+
e.preventDefault();
|
|
104
|
+
if (wheel) { wheel.dx += e.deltaX; wheel.dy += e.deltaY; return; }
|
|
105
|
+
wheel = { type: "wheel", ...point(e), dx: e.deltaX, dy: e.deltaY };
|
|
106
|
+
setTimeout(() => { const w = wheel; wheel = null; post("/input", { ...w, dx: Math.round(w.dx), dy: Math.round(w.dy) }); }, 80);
|
|
107
|
+
}, { passive: false });
|
|
108
|
+
const KEYS = new Set(["Enter", "Backspace", "Tab", "Escape", "Delete", "ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "Home", "End", "PageUp", "PageDown"]);
|
|
109
|
+
frame.addEventListener("keydown", (e) => {
|
|
110
|
+
if (!state || !state.paused || e.metaKey || e.ctrlKey || e.altKey) return;
|
|
111
|
+
if (e.key.length === 1) { e.preventDefault(); post("/input", { type: "text", text: e.key }); }
|
|
112
|
+
else if (KEYS.has(e.key)) { e.preventDefault(); post("/input", { type: "key", key: e.key }); }
|
|
113
|
+
});
|
|
114
|
+
`;
|
|
115
|
+
/** The page, with the nonce the response's Content-Security-Policy allows. */
|
|
116
|
+
export function livePage(nonce) {
|
|
117
|
+
return `<!doctype html>
|
|
118
|
+
<html lang="en">
|
|
119
|
+
<head>
|
|
120
|
+
<meta charset="utf-8">
|
|
121
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
122
|
+
<meta name="referrer" content="no-referrer">
|
|
123
|
+
<title>turno live view</title>
|
|
124
|
+
<style nonce="${nonce}">${STYLE}</style>
|
|
125
|
+
</head>
|
|
126
|
+
<body>
|
|
127
|
+
<header><strong>turno live</strong><span id="id"></span><span id="status">Connecting...</span><button id="pause" type="button">Pause</button><button id="resume" type="button" disabled>Resume</button></header>
|
|
128
|
+
<nav id="tabs" aria-label="Tabs"></nav>
|
|
129
|
+
<main><div id="notice" role="status"></div><img id="frame" alt="The agent's tab" tabindex="0"></main>
|
|
130
|
+
<footer id="help"></footer>
|
|
131
|
+
<script nonce="${nonce}">${SCRIPT}</script>
|
|
132
|
+
</body>
|
|
133
|
+
</html>
|
|
134
|
+
`;
|
|
135
|
+
}
|
|
136
|
+
/** What a browser without the view's cookie sees. */
|
|
137
|
+
export function deniedPage(identity) {
|
|
138
|
+
return `<!doctype html>
|
|
139
|
+
<html lang="en"><head><meta charset="utf-8"><title>turno live view</title></head>
|
|
140
|
+
<body><p>This live view needs a fresh link. Run <code>turno browser live ${identity}</code>: it opens one that works once.</p></body></html>
|
|
141
|
+
`;
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=live-page.js.map
|