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.
Files changed (70) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +92 -149
  3. package/dist/act-model.js +4 -3
  4. package/dist/act.js +2 -1
  5. package/dist/api.d.ts +63 -2
  6. package/dist/api.js +14 -4
  7. package/dist/background-state.d.ts +54 -0
  8. package/dist/background-state.js +97 -0
  9. package/dist/background.d.ts +69 -0
  10. package/dist/background.js +458 -0
  11. package/dist/bin/mcp.js +48 -8
  12. package/dist/captcha.js +3 -2
  13. package/dist/cli/background.d.ts +11 -0
  14. package/dist/cli/background.js +132 -0
  15. package/dist/cli/commands.d.ts +16 -0
  16. package/dist/cli/commands.js +515 -0
  17. package/dist/cli/context.d.ts +75 -0
  18. package/dist/cli/context.js +44 -0
  19. package/dist/cli/do-background.d.ts +27 -0
  20. package/dist/cli/do-background.js +212 -0
  21. package/dist/cli/do.d.ts +85 -0
  22. package/dist/cli/do.js +558 -0
  23. package/dist/cli/flows.d.ts +28 -0
  24. package/dist/cli/flows.js +303 -0
  25. package/dist/cli/identity.d.ts +37 -0
  26. package/dist/cli/identity.js +906 -0
  27. package/dist/cli/live.d.ts +7 -0
  28. package/dist/cli/live.js +99 -0
  29. package/dist/cli/main.d.ts +16 -0
  30. package/dist/cli/main.js +171 -0
  31. package/dist/cli/secret.d.ts +4 -0
  32. package/dist/cli/secret.js +151 -0
  33. package/dist/cli/session.d.ts +6 -0
  34. package/dist/cli/session.js +106 -0
  35. package/dist/cli/setup.d.ts +7 -0
  36. package/dist/cli/setup.js +180 -0
  37. package/dist/cli/vault.d.ts +5 -0
  38. package/dist/cli/vault.js +192 -0
  39. package/dist/client.d.ts +82 -0
  40. package/dist/client.js +303 -0
  41. package/dist/doctor.js +34 -1
  42. package/dist/engine-camoufox.js +5 -4
  43. package/dist/engine-lightpanda.js +3 -2
  44. package/dist/engine.js +2 -1
  45. package/dist/health.js +2 -1
  46. package/dist/host.d.ts +21 -0
  47. package/dist/host.js +75 -15
  48. package/dist/human-input.js +7 -2
  49. package/dist/identities.js +2 -1
  50. package/dist/index.d.ts +5 -1
  51. package/dist/index.js +2 -0
  52. package/dist/lifecycle.d.ts +2 -0
  53. package/dist/lifecycle.js +2 -1
  54. package/dist/live-client.js +8 -6
  55. package/dist/live-page.d.ts +0 -7
  56. package/dist/live-page.js +3 -2
  57. package/dist/live-server.js +6 -3
  58. package/dist/live.js +2 -1
  59. package/dist/login-tool.js +3 -2
  60. package/dist/login.js +2 -1
  61. package/dist/names.d.ts +28 -0
  62. package/dist/names.js +25 -0
  63. package/dist/network.d.ts +1 -1
  64. package/dist/network.js +4 -3
  65. package/dist/opt-in-settings.js +3 -2
  66. package/dist/replay.js +4 -3
  67. package/dist/runtime-lock.js +3 -2
  68. package/dist/vault.js +5 -4
  69. package/npm-shrinkwrap.json +6 -5
  70. package/package.json +13 -7
@@ -0,0 +1,212 @@
1
+ import { readFileSync, readdirSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { CliError, ownerName, sessionName, sessionOwner, str, withLock } from "turno-core/cli";
4
+ import { tildify, writePrivateFile } from "turno-core/paths";
5
+ import { pidAlive, readProcTable } from "turno-core/process";
6
+ import { backgroundDir } from "../background-state.js";
7
+ import { backgroundStatus, openBackgroundSession } from "../client.js";
8
+ import { identityExists } from "../identities.js";
9
+ export const defaultBackgroundDoDeps = {
10
+ owner: (env) => sessionOwner(readProcTable(), process.ppid, Number(env.TURNO_SESSION_PID) || undefined),
11
+ identityExists,
12
+ backgroundStatus,
13
+ openBackgroundSession,
14
+ };
15
+ const HELP = {
16
+ intro: `Runs one action on the identity's browser through its background server, a turno-browser-mcp
17
+ that serves the identity to the shell (turno-browser background shows it). The first action starts
18
+ it; it exits after 15 minutes without a request (TURNO_BROWSER_BACKGROUND_IDLE changes that). While
19
+ it runs it alone drives the identity's browser: an agent's turno-browser-mcp for the same identity
20
+ answers with an error that names it. With turno installed, turno browser do goes through mcpd
21
+ instead.`,
22
+ session: `Session: the commands one agent or one terminal shell runs are one session, so they keep their
23
+ tab and their place in the tab locks ("sharing": "tabs") or hold the identity's one-session lease
24
+ ("sharing": "session"). The session belongs to the process that runs the commands: the coding
25
+ agent (each of its shell commands passes through a short-lived shell) or your terminal's shell.
26
+ It ends when that process exits, with 'end' or 'close', or when the background server exits.
27
+ --session <name> (or TURNO_BROWSER_SESSION) keeps several sessions apart under one owner, for
28
+ example two subagents each in its own tab.`,
29
+ output: `Output: url: and title: lines, then what the action returned; errors go to stderr with exit 1.
30
+ --snapshot after an action prints the snapshot too; --json prints one object.
31
+ --timeout <seconds> (default 120) bounds one action; attach mode can wait for Chrome's consent
32
+ dialog.`,
33
+ };
34
+ /** Where the sessions of `do` are saved: the background server's private folder. */
35
+ function sessionsDir(id, env) {
36
+ return join(backgroundDir(id, env), "do");
37
+ }
38
+ function readSaved(file) {
39
+ try {
40
+ const s = JSON.parse(readFileSync(file, "utf8"));
41
+ if (s.v !== 1 || typeof s.sessionId !== "string" || typeof s.serverPid !== "number" || !s.owner)
42
+ return undefined;
43
+ return s;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ function dropSaved(file) {
50
+ rmSync(file, { force: true });
51
+ }
52
+ /** Removes the saved sessions whose owner exited (the server ended those sessions already). */
53
+ function sweepSaved(dir) {
54
+ let files;
55
+ try {
56
+ files = readdirSync(dir);
57
+ }
58
+ catch {
59
+ return;
60
+ }
61
+ for (const f of files) {
62
+ const m = /^(\d+)\.[^.]+\.json$/.exec(f);
63
+ if (m && !pidAlive(Number(m[1])))
64
+ dropSaved(join(dir, f));
65
+ }
66
+ }
67
+ function message(err) {
68
+ return (err?.message ?? String(err)).replace(/^(Error: )?/, "");
69
+ }
70
+ /** The background transport of `turno-browser do`. */
71
+ export function backgroundTransport(deps = defaultBackgroundDoDeps) {
72
+ return {
73
+ help: HELP,
74
+ flags: {},
75
+ async target(id, p, io) {
76
+ const api = deps;
77
+ const env = io.env;
78
+ if (!api.identityExists(id, env))
79
+ throw new CliError(`browser identity "${id}" does not exist (turno-browser add ${id})`);
80
+ const owner = deps.owner(env);
81
+ const name = sessionName(str(p, "session"), env);
82
+ const dir = sessionsDir(id, env);
83
+ const file = join(dir, `${owner.pid}.${name}.json`);
84
+ sweepSaved(dir);
85
+ /** The saved session when its server still runs, and that server's pid. */
86
+ const current = () => {
87
+ const saved = readSaved(file);
88
+ const server = api.backgroundStatus(id, { env });
89
+ return saved && server && saved.serverPid === server.pid && saved.owner.pid === owner.pid ? saved : undefined;
90
+ };
91
+ /** Open the saved session again (or a new one), without starting a server. */
92
+ const reopen = async (saved) => await api
93
+ .openBackgroundSession(id, {
94
+ env,
95
+ owner: owner.pid,
96
+ start: false,
97
+ session: {
98
+ id: saved.sessionId,
99
+ ...(saved.protocolVersion ? { protocolVersion: saved.protocolVersion } : {}),
100
+ },
101
+ })
102
+ .catch(() => undefined);
103
+ return {
104
+ head: { identity: id, server: "background", profile: null },
105
+ info: (resumed) => ({ name, ownerPid: owner.pid, owner: ownerName(owner), resumed }),
106
+ describe() {
107
+ const saved = current();
108
+ const server = api.backgroundStatus(id, { env });
109
+ return {
110
+ open: saved !== undefined,
111
+ lines: [
112
+ `identity: ${id}`,
113
+ server
114
+ ? `server: background server (pid ${server.pid}) since ${server.startedAt}`
115
+ : "server: not running; the next action starts it",
116
+ `session: ${name}, owned by ${ownerName(owner)} (pid ${owner.pid})`,
117
+ saved
118
+ ? `state: open since ${saved.createdAt}, last used ${saved.usedAt}`
119
+ : "state: none yet; the next action opens it",
120
+ `ends: when pid ${owner.pid} exits, with 'end' or 'close', or when the background server exits`,
121
+ `file: ${tildify(file, env)}`,
122
+ ],
123
+ };
124
+ },
125
+ async end() {
126
+ const saved = readSaved(file);
127
+ if (!saved)
128
+ return false;
129
+ const live = current();
130
+ if (live)
131
+ await (await reopen(live))?.end();
132
+ dropSaved(file);
133
+ return true;
134
+ },
135
+ session: (fn) => withLock(file, env, async () => {
136
+ let saved = current();
137
+ if (!saved)
138
+ dropSaved(file); // another server, or none: that session is gone
139
+ let s;
140
+ try {
141
+ s = await api.openBackgroundSession(id, {
142
+ env,
143
+ owner: owner.pid,
144
+ clientName: "turno-browser-do",
145
+ ...(saved
146
+ ? {
147
+ session: {
148
+ id: saved.sessionId,
149
+ ...(saved.protocolVersion ? { protocolVersion: saved.protocolVersion } : {}),
150
+ },
151
+ }
152
+ : {}),
153
+ });
154
+ }
155
+ catch (err) {
156
+ throw new CliError(message(err));
157
+ }
158
+ if (!s.resumed)
159
+ saved = undefined;
160
+ let used = false;
161
+ let ended = false;
162
+ const session = {
163
+ resumed: s.resumed,
164
+ async call(tool, args, timeoutMs) {
165
+ let result;
166
+ try {
167
+ result = await s.callTool(tool, args, { timeoutMs });
168
+ }
169
+ catch (err) {
170
+ // A session this command opened and could not use goes at once.
171
+ if (!s.resumed && !used)
172
+ await s.end();
173
+ throw new CliError(`${tool}: ${message(err)}`);
174
+ }
175
+ if (!used && !ended) {
176
+ const now = new Date().toISOString();
177
+ const next = {
178
+ v: 1,
179
+ identity: id,
180
+ serverPid: s.state.pid,
181
+ sessionId: s.id,
182
+ ...(s.protocolVersion ? { protocolVersion: s.protocolVersion } : {}),
183
+ owner,
184
+ name,
185
+ createdAt: saved?.createdAt ?? now,
186
+ usedAt: now,
187
+ };
188
+ writePrivateFile(file, `${JSON.stringify(next, null, 2)}\n`, env);
189
+ }
190
+ used = true;
191
+ return result;
192
+ },
193
+ async end() {
194
+ ended = true;
195
+ await s.end();
196
+ dropSaved(file);
197
+ },
198
+ };
199
+ try {
200
+ return await fn(session);
201
+ }
202
+ finally {
203
+ // Never end the session here: the next command of this owner continues it.
204
+ if (!ended)
205
+ await s.close();
206
+ }
207
+ }),
208
+ };
209
+ },
210
+ };
211
+ }
212
+ //# sourceMappingURL=do-background.js.map
@@ -0,0 +1,85 @@
1
+ import { type FlagSpec, type Io, type Parsed } from "turno-core/cli";
2
+ import type { Ctx } from "./context.js";
3
+ /**
4
+ * `<browser> do <id> <action>`: one browser action on an identity's browser from the shell, for
5
+ * coding agents that prefer commands over MCP tools. Each action is one stock (or turno) tool call
6
+ * to the identity's turno-browser-mcp, the server agents use, so every rule of the identity
7
+ * applies as it does to an agent: the tab locks or the one-session lease, attach mode, read mode's
8
+ * refusals, humanize, recordings, the vault. How the call reaches the server, and what makes
9
+ * several commands one session, is the host's transport (`DoTransport`): inside turno, mcpd.
10
+ *
11
+ * The output is short and stable: `url:` and `title:` lines, then what the action returned. The
12
+ * code upstream ran and the snapshot file an action saves on the server are left out; a snapshot
13
+ * comes from `snapshot` (or `--snapshot` after an action).
14
+ */
15
+ /** `do --json`: one object per command. */
16
+ export declare const DO_JSON: import("turno-core/cli").JsonOutput;
17
+ /** A tool call's result as an MCP client returns it. */
18
+ export interface ToolResult {
19
+ content?: unknown;
20
+ isError?: boolean | undefined;
21
+ }
22
+ /** The `session` field of `do --json`. */
23
+ export interface DoSessionInfo {
24
+ name: string;
25
+ ownerPid: number;
26
+ owner: string;
27
+ /** True when the command continued a saved session, false when it opened one, null for `end`. */
28
+ resumed: boolean | null;
29
+ }
30
+ /** One session of `do`, open for one command. */
31
+ export interface DoSession {
32
+ /** True when this continues a session an earlier command opened. */
33
+ readonly resumed: boolean;
34
+ /**
35
+ * Call one tool in the session, within `timeoutMs`. A call the server refuses or cannot take
36
+ * throws a CliError that names the tool; the session is kept for the next command.
37
+ */
38
+ call(tool: string, args: Record<string, unknown>, timeoutMs: number): Promise<ToolResult>;
39
+ /** End the session now (after `close`): the next command opens a new one. */
40
+ end(): Promise<void>;
41
+ }
42
+ /** The server of one identity and the session the commands of this shell or agent belong to. */
43
+ export interface DoTarget {
44
+ /** What every `--json` object starts with: the identity, and the server and profile when there are. */
45
+ head: {
46
+ identity: string;
47
+ server: string | null;
48
+ profile: string | null;
49
+ };
50
+ /** The `session` field of `--json`. */
51
+ info(resumed: boolean | null): DoSessionInfo;
52
+ /** `do <id> session`: whether a session is saved, and the lines that describe it. */
53
+ describe(io: Io): {
54
+ open: boolean;
55
+ lines: string[];
56
+ };
57
+ /** `do <id> end`: end the saved session at once; false when there was none. */
58
+ end(): Promise<boolean>;
59
+ /** Open a session, or continue the saved one, run `fn` in it, and keep it for the next command. */
60
+ session<T>(fn: (s: DoSession) => Promise<T>): Promise<T>;
61
+ }
62
+ /**
63
+ * How `do` reaches an identity's server: inside turno, mcpd (each command one gateway session of
64
+ * the profile); on its own, a background server per identity.
65
+ */
66
+ export interface DoTransport {
67
+ /** Help paragraphs: how an action reaches the server, how a session lives, the output and flags. */
68
+ help: {
69
+ intro: string;
70
+ session: string;
71
+ output: string;
72
+ };
73
+ /** Flags of its own (turno's `--profile`), parsed with the action's. */
74
+ flags: FlagSpec;
75
+ /** The server that serves identity `id`, and this caller's session; throws when there is none. */
76
+ target(id: string, p: Parsed, io: Io): Promise<DoTarget>;
77
+ }
78
+ /** Every action name, for the short form and for completion. */
79
+ export declare const ACTION_NAMES: readonly string[];
80
+ /** The flags of `do`, for completion: the common ones, the transport's, then the actions'. */
81
+ export declare function doFlagNames(c: Ctx): string[];
82
+ export declare function doSynopsis(_c: Ctx): string;
83
+ export declare function doDetails(c: Ctx): string;
84
+ /** `<browser> do <id> <action> [args]`. */
85
+ export declare function browserDo(c: Ctx, args: string[], io: Io): Promise<number>;