turno-browser 0.5.0 → 0.7.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.
@@ -0,0 +1,11 @@
1
+ /**
2
+ * What a login saved, in words: the sites the person opened (the agent starts with their
3
+ * cookies), or that nothing was opened, so nothing new was signed in.
4
+ */
5
+ export function loginSummary(c, id, sites) {
6
+ if (!sites.length)
7
+ return `Closed. No site was opened, so no new sign-in was saved. Open one directly with ${c.names.identity("login", id)} --url https://mail.example.com`;
8
+ const shown = sites.length > 4 ? `${sites.slice(0, 4).join(", ")} and ${sites.length - 4} more` : sites.join(", ");
9
+ return `Saved. Sites you opened: ${shown}. The agent starts with the same cookies on them.`;
10
+ }
11
+ //# sourceMappingURL=login-summary.js.map
package/dist/cli/main.js CHANGED
@@ -5,6 +5,7 @@ import { CliError, Exit, UsageError, columns, confirm, defaultIo, exitName, fail
5
5
  import { api } from "../api.js";
6
6
  import { browserCli } from "./commands.js";
7
7
  import { standaloneHost } from "./context.js";
8
+ import { COMPLETION_USAGE, complete, completionScript } from "./completion.js";
8
9
  /**
9
10
  * `turno-browser <command>`: the identity commands on their own, without turno-cli. The same
10
11
  * commands run inside turno as `turno browser <command>`; only the names in help and hints
@@ -13,6 +14,7 @@ import { standaloneHost } from "./context.js";
13
14
  const PROGRAM = "turno-browser";
14
15
  /** The sections of `turno-browser --help`, in order. */
15
16
  const SECTIONS = [
17
+ { title: "Start here", commands: ["init"] },
16
18
  { title: "Identities", commands: ["list", "add", "show", "set", "login", "remove"] },
17
19
  { title: "Connect an agent", commands: ["setup"] },
18
20
  { title: "Sign-ins and sessions", commands: ["vault", "secret", "export", "import"] },
@@ -35,11 +37,14 @@ export function renderHelp(io, cli) {
35
37
  out.push(s.color ? `${s.bold(s.accent(PROGRAM))}${s.bold(first[0].slice(PROGRAM.length))}` : first[0]);
36
38
  for (const l of first.slice(1))
37
39
  out.push(s.bold(l));
40
+ if (cli.subs.init)
41
+ out.push("", `New here? ${s.accent(`${PROGRAM} init`)} sets it up step by step: an identity, a sign-in, your agent.`);
38
42
  out.push("", s.header("Usage"));
39
43
  out.push(columns([
40
44
  [`${PROGRAM} <command> [flags]`, "manage identities: persistent Chrome profiles your agents sign in with"],
41
45
  [`${PROGRAM} <command> --help`, "the flags and examples of one command"],
42
46
  ["turno-browser-mcp --identity <id>", "the MCP server an agent runs for one identity (--help)"],
47
+ [`${PROGRAM} completion <zsh|bash|fish>`, "shell completion for commands, identities and flags (--help)"],
43
48
  ]));
44
49
  const left = Math.max(...SECTIONS.flatMap((x) => x.commands.map((n) => n.length)));
45
50
  for (const section of SECTIONS) {
@@ -142,6 +147,27 @@ export async function main(args, io = defaultIo()) {
142
147
  io.out(`${PROGRAM} ${version()}`);
143
148
  return Exit.ok;
144
149
  }
150
+ if (head === "__complete") {
151
+ const words = tail[0] === "--" ? tail.slice(1) : tail;
152
+ for (const c of complete(words.length ? words : [""], cli.subs, io.env))
153
+ io.out(c);
154
+ return Exit.ok;
155
+ }
156
+ if (head === "completion") {
157
+ if (tail[0] === "--help" || tail[0] === "-h") {
158
+ io.out(COMPLETION_USAGE(PROGRAM));
159
+ return Exit.ok;
160
+ }
161
+ const script = completionScript(PROGRAM, tail[0]);
162
+ if (!script || tail.length > 1)
163
+ throw new UsageError(`usage: ${PROGRAM} completion <zsh|bash|fish>`);
164
+ io.out(script.trimEnd());
165
+ return Exit.ok;
166
+ }
167
+ if (head === "help" && tail[0] === "completion") {
168
+ io.out(COMPLETION_USAGE(PROGRAM));
169
+ return Exit.ok;
170
+ }
145
171
  if (head === "help")
146
172
  return await cli.command.run([...tail, "--help"], io);
147
173
  if (head.startsWith("-"))
@@ -1,7 +1,45 @@
1
1
  import { type Io } from "turno-core/cli";
2
2
  import type { Ctx } from "./context.js";
3
+ /**
4
+ * `turno-browser setup <agent> [--identity <id>]`: the MCP config that gives a coding agent one
5
+ * identity's browser, printed for the person to run or paste. It never writes a file: an
6
+ * agent's config is the person's (inside turno, `turno mcp sync` writes it from mcp.toml).
7
+ */
8
+ export declare const SETUP_AGENTS: readonly ["claude-code", "codex", "cursor", "copilot", "gemini", "json"];
9
+ export type SetupAgent = (typeof SETUP_AGENTS)[number];
3
10
  /** `setup --json`: one object. */
4
11
  export declare const SETUP_JSON: import("turno-core/cli").JsonOutput;
12
+ /** What `setup` prints for one agent. */
13
+ export interface SetupConfig {
14
+ agent: SetupAgent;
15
+ identity: string;
16
+ /** The server's name in the agent's config: `browser-<id>`. */
17
+ server: string;
18
+ command: string;
19
+ args: string[];
20
+ /** The file the config block goes in, when the agent reads one. */
21
+ file: string | null;
22
+ /** A command that adds the server, when the agent has one. */
23
+ shell: string | null;
24
+ /** The block to paste into `file`. */
25
+ config: string | null;
26
+ notes: string[];
27
+ }
28
+ /**
29
+ * The command an agent runs: `turno-browser-mcp` when it is on the PATH, else this install's
30
+ * full path (a `pnpm add` or a local checkout puts it nowhere on the PATH).
31
+ */
32
+ export declare function mcpCommand(env: NodeJS.ProcessEnv): {
33
+ command: string;
34
+ onPath: boolean;
35
+ };
36
+ /** The config of `agent` for identity `id`, run as `command`. */
37
+ export declare function setupConfig(agent: SetupAgent, id: string, command: string): SetupConfig;
38
+ export declare const AGENT_NAMES: Record<SetupAgent, string>;
5
39
  export declare const SETUP_DETAILS = "Prints how a coding agent gets one identity's browser: the command to run, or the block to\npaste into its config file. It writes nothing; run or paste it yourself.\n\nAgents:\n claude-code a claude mcp add command\n codex a [mcp_servers] block for ~/.codex/config.toml, and the codex mcp add command\n cursor an mcpServers entry for ~/.cursor/mcp.json\n copilot an mcpServers entry for ~/.copilot/mcp-config.json, and the copilot mcp add command\n gemini an mcpServers entry for ~/.gemini/settings.json, and the gemini mcp add command\n json the generic mcpServers entry other MCP clients read\n\nWithout --identity it uses the only identity there is. The agent then starts turno-browser-mcp\nfor the identity when it needs the browser.";
40
+ /** "unknown agent", with the agent the person most likely meant: claude for claude-code, cursr for cursor. */
41
+ export declare function unknownAgent(agent: string): string;
42
+ /** What `setup` prints for one config, before the closing line. */
43
+ export declare function setupLines(cfg: SetupConfig): string[];
6
44
  /** `<browser> setup <agent> [--identity <id>] [--json]`. */
7
45
  export declare function setup(c: Ctx, args: string[], io: Io): number;
package/dist/cli/setup.js CHANGED
@@ -1,12 +1,12 @@
1
1
  import { fileURLToPath } from "node:url";
2
- import { JSON_FLAG, bool, emit, fail, jsonOutput, parseFlags, str } from "turno-core/cli";
2
+ import { JSON_FLAG, bool, closest, emit, fail, jsonOutput, parseFlags, str, } from "turno-core/cli";
3
3
  import { findOnPath } from "turno-core/paths";
4
4
  /**
5
5
  * `turno-browser setup <agent> [--identity <id>]`: the MCP config that gives a coding agent one
6
6
  * identity's browser, printed for the person to run or paste. It never writes a file: an
7
7
  * agent's config is the person's (inside turno, `turno mcp sync` writes it from mcp.toml).
8
8
  */
9
- const SETUP_AGENTS = ["claude-code", "codex", "cursor", "copilot", "gemini", "json"];
9
+ export const SETUP_AGENTS = ["claude-code", "codex", "cursor", "copilot", "gemini", "json"];
10
10
  /** `setup --json`: one object. */
11
11
  export const SETUP_JSON = jsonOutput([
12
12
  "agent",
@@ -34,13 +34,13 @@ function json(v) {
34
34
  * The command an agent runs: `turno-browser-mcp` when it is on the PATH, else this install's
35
35
  * full path (a `pnpm add` or a local checkout puts it nowhere on the PATH).
36
36
  */
37
- function mcpCommand(env) {
37
+ export function mcpCommand(env) {
38
38
  if (findOnPath("turno-browser-mcp", env))
39
39
  return { command: "turno-browser-mcp", onPath: true };
40
40
  return { command: fileURLToPath(new URL("../bin/mcp.js", import.meta.url)), onPath: false };
41
41
  }
42
42
  /** The config of `agent` for identity `id`, run as `command`. */
43
- function setupConfig(agent, id, command) {
43
+ export function setupConfig(agent, id, command) {
44
44
  const server = `browser-${id}`;
45
45
  const args = ["--identity", id];
46
46
  const base = { agent, identity: id, server, command, args };
@@ -96,7 +96,7 @@ function setupConfig(agent, id, command) {
96
96
  };
97
97
  }
98
98
  }
99
- const AGENT_NAMES = {
99
+ export const AGENT_NAMES = {
100
100
  "claude-code": "Claude Code",
101
101
  codex: "Codex",
102
102
  cursor: "Cursor",
@@ -117,6 +117,12 @@ Agents:
117
117
 
118
118
  Without --identity it uses the only identity there is. The agent then starts turno-browser-mcp
119
119
  for the identity when it needs the browser.`;
120
+ /** "unknown agent", with the agent the person most likely meant: claude for claude-code, cursr for cursor. */
121
+ export function unknownAgent(agent) {
122
+ const prefix = SETUP_AGENTS.find((a) => a.startsWith(agent.toLowerCase()) && agent.length >= 3);
123
+ const guess = prefix ?? closest(agent.toLowerCase(), SETUP_AGENTS);
124
+ return `unknown agent "${agent}"${guess ? `; did you mean ${guess}?` : ""} (agents: ${SETUP_AGENTS.join(", ")})`;
125
+ }
120
126
  /** The identity `setup` is for: --identity, or the only one there is. */
121
127
  function pickIdentity(c, flag, io) {
122
128
  const b = c.names.browser;
@@ -138,6 +144,25 @@ function pickIdentity(c, flag, io) {
138
144
  return fail(`no identity yet: create one with ${b} add <id>, then ${b} setup <agent> --identity <id>`);
139
145
  return fail(`pick an identity with --identity: ${ids.join(", ")}`);
140
146
  }
147
+ /** What `setup` prints for one config, before the closing line. */
148
+ export function setupLines(cfg) {
149
+ const name = AGENT_NAMES[cfg.agent];
150
+ const id = cfg.identity;
151
+ const out = [];
152
+ if (cfg.agent === "claude-code") {
153
+ out.push(`Run this once to give ${name} the browser identity "${id}":`, "", cfg.shell);
154
+ }
155
+ else if (cfg.file) {
156
+ out.push(`Add this to ${cfg.file} to give ${name} the browser identity "${id}":`, "", cfg.config);
157
+ if (cfg.shell)
158
+ out.push("", `Or run: ${cfg.shell}`);
159
+ }
160
+ else {
161
+ out.push(`The browser identity "${id}" for ${name}:`, "", cfg.config);
162
+ }
163
+ out.push("", ...cfg.notes);
164
+ return out;
165
+ }
141
166
  /** `<browser> setup <agent> [--identity <id>] [--json]`. */
142
167
  export function setup(c, args, io) {
143
168
  const p = parseFlags(args, SETUP_FLAGS, 1);
@@ -146,7 +171,7 @@ export function setup(c, args, io) {
146
171
  if (!agent)
147
172
  return fail(`setup needs an agent: ${b} setup <${SETUP_AGENTS.join("|")}> [--identity <id>]`);
148
173
  if (!SETUP_AGENTS.includes(agent))
149
- return fail(`unknown agent "${agent}" (agents: ${SETUP_AGENTS.join(", ")})`);
174
+ return fail(unknownAgent(agent));
150
175
  const id = pickIdentity(c, str(p, "identity"), io);
151
176
  const { command, onPath } = mcpCommand(io.env);
152
177
  const cfg = setupConfig(agent, id, command);
@@ -156,24 +181,8 @@ export function setup(c, args, io) {
156
181
  emit(io, p, SETUP_JSON, cfg);
157
182
  return 0;
158
183
  }
159
- const name = AGENT_NAMES[cfg.agent];
160
- if (cfg.agent === "claude-code") {
161
- io.out(`Run this once to give ${name} the browser identity "${id}":\n`);
162
- io.out(cfg.shell);
163
- }
164
- else if (cfg.file) {
165
- io.out(`Add this to ${cfg.file} to give ${name} the browser identity "${id}":\n`);
166
- io.out(cfg.config);
167
- if (cfg.shell)
168
- io.out(`\nOr run: ${cfg.shell}`);
169
- }
170
- else {
171
- io.out(`The browser identity "${id}" for ${name}:\n`);
172
- io.out(cfg.config);
173
- }
174
- io.out("");
175
- for (const n of cfg.notes)
176
- io.out(n);
184
+ for (const l of setupLines(cfg))
185
+ io.out(l);
177
186
  io.out(`Start a new agent session to load it. Sign in to your sites once with ${b} login ${id}.`);
178
187
  return 0;
179
188
  }
package/dist/doctor.js CHANGED
@@ -6,6 +6,7 @@ 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
8
  import { backgroundAlive, readBackgroundState } from "./background-state.js";
9
+ import { profileHasCookies, readLoginRecord } from "./login.js";
9
10
  import { readHealth } from "./health.js";
10
11
  import { identityDir, isValidIdentityId } from "./ids.js";
11
12
  import { defaultChromeUserDataDir, parseAttachTarget, resolveAttachEndpoint } from "./engine-attach.js";
@@ -121,7 +122,13 @@ function describeSettings(s) {
121
122
  parts.push(`languages ${langs.join(", ")}`);
122
123
  if (s.region)
123
124
  parts.push(`region ${s.region}`);
124
- return parts.length ? parts.join(", ") : "no fixed time zone or languages";
125
+ const base = parts.length ? parts.join(", ") : "no fixed time zone or languages";
126
+ // The agent cursor is on when the browser can be seen (auto): say so only when set otherwise.
127
+ if (s.cursor === "on")
128
+ return `${base}; agent cursor always shown`;
129
+ if (s.cursor === "off")
130
+ return `${base}; agent cursor off`;
131
+ return base;
125
132
  }
126
133
  /** The `turno identity set` flag that replaces the value a problem is about. */
127
134
  function settingsFix(id, problem) {
@@ -131,6 +138,7 @@ function settingsFix(id, problem) {
131
138
  ["languages", "--languages <tag,...>"],
132
139
  ["region", "--region <CC>"],
133
140
  ["health", "--health-url <url> --health-text <text>"],
141
+ ["cursor", "--cursor auto|on|off"],
134
142
  ].find(([key]) => problem.startsWith(key))?.[1];
135
143
  return flag ? `turno identity set browser:${id} ${flag}` : undefined;
136
144
  }
@@ -220,7 +228,7 @@ function identityChecks(id, env, now, servers = []) {
220
228
  });
221
229
  }
222
230
  else {
223
- add({ level: "ok", text: "free: no process holds it" });
231
+ add({ level: "ok", text: "not in use: no process holds it" });
224
232
  }
225
233
  // The background server `turno-browser do` starts: while it runs, an agent's server of this
226
234
  // identity refuses to launch the browser, so say it runs and how to stop it.
@@ -233,6 +241,14 @@ function identityChecks(id, env, now, servers = []) {
233
241
  fix: `turno-browser background stop ${id}`,
234
242
  });
235
243
  }
244
+ // A profile nobody signed in to by hand starts signed out everywhere: say so before an agent finds out.
245
+ if (!readLoginRecord(id, env) && !profileHasCookies(id, env)) {
246
+ add({
247
+ level: "info",
248
+ text: "never signed in by hand here: the agent starts signed out on every site",
249
+ fix: `turno browser login ${id}`,
250
+ });
251
+ }
236
252
  const check = settings?.health;
237
253
  const health = readHealth(id, env);
238
254
  if (!check) {
package/dist/host.js CHANGED
@@ -10,6 +10,7 @@ import { coveredBeforeCall, explainFailure } from "./diagnose.js";
10
10
  import { createEngine, engineChoice, } from "./engine.js";
11
11
  import { TabGovernor } from "./governor.js";
12
12
  import { NEEDS_AUTH_HOLD_MS, healthDue, needsAuthMessage, readHealth, runHealthCheck, writeHealth, } from "./health.js";
13
+ import { AgentCursor, CursorInput, cursorTools, resolveCursor } from "./agent-cursor.js";
13
14
  import { HumanInput, adaptiveSites, humanizeTools } from "./human-input.js";
14
15
  import { identityStateDir } from "./ids.js";
15
16
  import { idleMs } from "./idle-timer.js";
@@ -313,8 +314,18 @@ class SessionBackend extends EventEmitter {
313
314
  };
314
315
  const sessionConfig = configForSession(config, cliOptions, tuning);
315
316
  const idle = launched.idleTimer ? new CallIdleTimer(launched.idleTimer, () => launched.isOpen()) : undefined;
317
+ // The agent cursor (on when someone can see this browser): the input tools move it, under
318
+ // humanize, so humanize's pointer path goes through it too.
319
+ const cursor = resolveCursor(tuning.cursor, {
320
+ headless: config.browser?.launchOptions?.headless === true && !launched.userBrowser,
321
+ live: this.host.live !== undefined,
322
+ engine: launched.engine,
323
+ })
324
+ ? new AgentCursor({ title, ...(identity ? { identity: identity.id } : {}) })
325
+ : undefined;
326
+ const marked = cursor ? cursorTools(stock, new CursorInput(cursor, input !== undefined)) : stock;
316
327
  // Every backend of this browser (each session's too, with "sharing": "tabs") runs these tools.
317
- const tools = input ? humanizeTools(stock, input) : stock;
328
+ const tools = input ? humanizeTools(marked, input) : marked;
318
329
  const backend = new BrowserBackend(sessionConfig, launched.context, tools, {
319
330
  ...(idle ? { idleTimer: idle } : {}),
320
331
  dispose: async () => {
@@ -405,12 +416,14 @@ class SessionBackend extends EventEmitter {
405
416
  onPause: async () => {
406
417
  tabs.beginCall();
407
418
  endIdle = idle?.begin();
419
+ await cursor?.setPaused(launched.context.pages(), true);
408
420
  await recording?.pauseForUser();
409
421
  },
410
422
  onResume: () => {
411
423
  endIdle?.();
412
424
  endIdle = undefined;
413
425
  tabs.endCall();
426
+ void cursor?.setPaused(launched.context.pages(), false);
414
427
  },
415
428
  });
416
429
  }
@@ -434,6 +447,7 @@ class SessionBackend extends EventEmitter {
434
447
  ...(sharing ? { sharing } : {}),
435
448
  ...(recording ? { recording } : {}),
436
449
  ...(input ? { input } : {}),
450
+ ...(cursor ? { cursor } : {}),
437
451
  };
438
452
  })();
439
453
  promise.catch(() => {
@@ -666,10 +680,13 @@ class SessionBackend extends EventEmitter {
666
680
  ?.page.bringToFront()
667
681
  .catch(() => { });
668
682
  const page = backendContext(backend)?.currentTab()?.page;
683
+ const key = session ?? DIRECT_SESSION;
684
+ await running.cursor?.begin(page, key);
669
685
  result =
670
686
  (launched.engine === "lightpanda" ? undefined : await coveredBeforeCall(page, name, args, json)) ??
671
- (await backend.callTool(name, args, signal));
672
- this.host.live?.follow(session ?? DIRECT_SESSION, backendContext(backend)?.currentTab()?.page);
687
+ (await this.withCursor(running, name, page, () => backend.callTool(name, args, signal)));
688
+ void running.cursor?.end(backendContext(backend)?.currentTab()?.page, key);
689
+ this.host.live?.follow(key, backendContext(backend)?.currentTab()?.page);
673
690
  if (result.isError)
674
691
  result = await explainFailure(backendContext(backend)?.currentTab()?.page, name, args, result, json);
675
692
  await this.afterStock(running, session, name, args, pending, result, backendContext(backend)?.currentTab()?.page);
@@ -728,11 +745,13 @@ class SessionBackend extends EventEmitter {
728
745
  .current()
729
746
  ?.bringToFront()
730
747
  .catch(() => { });
748
+ await running.cursor?.begin(tabs.current(), key);
731
749
  result =
732
750
  (running.launched.engine === "lightpanda"
733
751
  ? undefined
734
752
  : await coveredBeforeCall(tabs.current(), name, args, json)) ??
735
- (await backend.callTool(name, args, signal));
753
+ (await this.withCursor(running, name, tabs.current(), () => backend.callTool(name, args, signal)));
754
+ void running.cursor?.end(tabs.current(), key);
736
755
  this.host.live?.follow(key, tabs.current());
737
756
  if (result.isError)
738
757
  result = await explainFailure(tabs.current(), name, args, result, json);
@@ -762,6 +781,12 @@ class SessionBackend extends EventEmitter {
762
781
  const text = sharing.annotate(first.text, key, view);
763
782
  return { ...annotated, content: [{ ...first, text }, ...annotated.content.slice(1)] };
764
783
  }
784
+ /** A stock call, with the agent cursor hidden while it takes the model's screenshot. */
785
+ async withCursor(running, name, page, call) {
786
+ if (!running.cursor || name !== "browser_take_screenshot")
787
+ return await call();
788
+ return await running.cursor.hiddenDuring(page, call);
789
+ }
765
790
  /**
766
791
  * Before a stock call: the flow step it may become (`recorder.ts`), and a trace stopped and
767
792
  * saved before a value goes into a secret field, as before a vault fill (`recordings.ts`).
@@ -28,6 +28,11 @@ export interface HumanInputOptions {
28
28
  sleep?: (ms: number) => Promise<void>;
29
29
  now?: () => number;
30
30
  }
31
+ /**
32
+ * A view of `target` where the names in `overrides` are replaced. Every other method is bound
33
+ * to the target itself, so private fields and `this` inside Playwright's classes keep working.
34
+ */
35
+ export declare function overlay<T extends object>(target: T, overrides: Record<string, unknown>): T;
31
36
  export declare class HumanInput {
32
37
  readonly settings: HumanizeSettings;
33
38
  readonly persona: Persona;
@@ -56,7 +56,7 @@ export function adaptiveSites(id, env, now = Date.now()) {
56
56
  * A view of `target` where the names in `overrides` are replaced. Every other method is bound
57
57
  * to the target itself, so private fields and `this` inside Playwright's classes keep working.
58
58
  */
59
- function overlay(target, overrides) {
59
+ export function overlay(target, overrides) {
60
60
  return new Proxy(target, {
61
61
  get(t, prop) {
62
62
  if (typeof prop === "string" && Object.hasOwn(overrides, prop))
package/dist/index.d.ts CHANGED
@@ -13,7 +13,7 @@ export { type ChromeInfo, type DoctorCheck, type DoctorOptions, type DoctorRepor
13
13
  export { type BuiltArgv, type PlaywrightMcpConfig, buildArgv, extractIdentity } from "./argv.js";
14
14
  export { type BenchOptions, type BenchReport, DETECTORS, ENGINES, ENGINE_ALIASES, type EngineName, type EngineReport, type TargetResult, defaultEngines, engineId, formatBenchTable, runBench, unavailableReason, } from "./bench.js";
15
15
  export { CHALLENGE_MARKERS, type ChallengeKind, classifyChallenge, detectChallenge, parseRebrowser, parseSannysoft, } from "./detectors.js";
16
- export { type LoginOptions, loginIdentity } from "./login.js";
16
+ export { type LoginOptions, type LoginRecord, type LoginResult, loginIdentity, profileHasCookies, readLoginRecord, } from "./login.js";
17
17
  export { LiveError, liveLink, livePause, liveResume, liveStatus } from "./live-client.js";
18
18
  export { BackgroundError, type BackgroundSession, type BackgroundState, type CallOptions, type OpenSessionOptions, type StartBackgroundOptions, type StartedBackground, backgroundStatus, openBackgroundSession, startBackground, stopBackground, } from "./client.js";
19
19
  export type { LiveStatus } from "./live-server.js";
package/dist/index.js CHANGED
@@ -12,7 +12,7 @@ export { findChrome, runDoctor, } from "./doctor.js";
12
12
  export { buildArgv, extractIdentity } from "./argv.js";
13
13
  export { DETECTORS, ENGINES, ENGINE_ALIASES, defaultEngines, engineId, formatBenchTable, runBench, unavailableReason, } from "./bench.js";
14
14
  export { CHALLENGE_MARKERS, classifyChallenge, detectChallenge, parseRebrowser, parseSannysoft, } from "./detectors.js";
15
- export { loginIdentity } from "./login.js";
15
+ export { loginIdentity, profileHasCookies, readLoginRecord, } from "./login.js";
16
16
  export { LiveError, liveLink, livePause, liveResume, liveStatus } from "./live-client.js";
17
17
  export { BackgroundError, backgroundStatus, openBackgroundSession, startBackground, stopBackground, } from "./client.js";
18
18
  export { TotpError, parseTotpSecret, totp } from "./totp.js";
package/dist/login.d.ts CHANGED
@@ -1,8 +1,28 @@
1
1
  export interface LoginOptions {
2
2
  env?: NodeJS.ProcessEnv;
3
- /** Page to open first (default: a blank tab). */
3
+ /** Page to open first (default: a short page that says what to do). */
4
4
  url?: string;
5
5
  }
6
+ /** What a login did: the sites the person opened in the window, by host name. */
7
+ export interface LoginResult {
8
+ sites: string[];
9
+ }
10
+ /** The last login of an identity: when it ended and the sites opened in it. */
11
+ export interface LoginRecord {
12
+ at: string;
13
+ sites: string[];
14
+ }
15
+ /** The last login, or undefined when the identity was never signed in by hand (or before this was kept). */
16
+ export declare function readLoginRecord(id: string, env?: NodeJS.ProcessEnv): LoginRecord | undefined;
17
+ /**
18
+ * Whether the profile holds cookies at all: a profile signed in before turno-browser kept a
19
+ * login record has no record but has cookies, and is not "never signed in".
20
+ */
21
+ export declare function profileHasCookies(id: string, env?: NodeJS.ProcessEnv): boolean;
22
+ /** The host of a page the person opened, without "www."; undefined for blank and internal pages. */
23
+ export declare function siteOf(url: string): string | undefined;
24
+ /** The page a login opens without --url: what this window is and what to do in it. Works offline. */
25
+ export declare function welcomePage(id: string, loginCommand?: string): string;
6
26
  /**
7
27
  * Opens the identity's persistent Chrome headed, with the same launch settings as the MCP
8
28
  * server (Chrome channel, no fixed viewport, the identity's languages and time zone), and
@@ -13,4 +33,4 @@ export interface LoginOptions {
13
33
  * With identity.json `proxy`, the sign-in goes through the same proxy as the agent's sessions,
14
34
  * so the site sees one network for both. A Camoufox identity is refused: it keeps its own profile.
15
35
  */
16
- export declare function loginIdentity(id: string, options?: LoginOptions): Promise<void>;
36
+ export declare function loginIdentity(id: string, options?: LoginOptions): Promise<LoginResult>;
package/dist/login.js CHANGED
@@ -1,11 +1,83 @@
1
- import { mkdirSync } from "node:fs";
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
2
3
  import { clearHealth } from "./health.js";
4
+ import { identityStateDir } from "./ids.js";
3
5
  import { IdentityError, identityDir, inUseBy, isInUse } from "./identities.js";
4
6
  import { readLockPid } from "./lifecycle.js";
5
7
  import { CHROME_PROXY_ARGS, resolveProxy } from "./network.js";
6
8
  import { acquireRuntimeLock } from "./runtime-lock.js";
7
9
  import { chromeEnv, keychainArgs, launchSettings, readIdentitySettings, systemTimezone } from "./settings.js";
8
10
  import { names } from "./names.js";
11
+ function loginRecordPath(id, env = process.env) {
12
+ return join(identityStateDir(id, env), "login.json");
13
+ }
14
+ /** The last login, or undefined when the identity was never signed in by hand (or before this was kept). */
15
+ export function readLoginRecord(id, env = process.env) {
16
+ try {
17
+ const v = JSON.parse(readFileSync(loginRecordPath(id, env), "utf8"));
18
+ if (typeof v.at === "string" && Array.isArray(v.sites))
19
+ return { at: v.at, sites: v.sites.map(String) };
20
+ }
21
+ catch {
22
+ /* none */
23
+ }
24
+ return undefined;
25
+ }
26
+ /**
27
+ * Whether the profile holds cookies at all: a profile signed in before turno-browser kept a
28
+ * login record has no record but has cookies, and is not "never signed in".
29
+ */
30
+ export function profileHasCookies(id, env = process.env) {
31
+ const dir = identityDir(id, env);
32
+ return ["Default/Cookies", "Default/Network/Cookies"].some((f) => existsSync(join(dir, f)));
33
+ }
34
+ function writeLoginRecord(id, env, record) {
35
+ const file = loginRecordPath(id, env);
36
+ mkdirSync(identityStateDir(id, env), { recursive: true, mode: 0o700 });
37
+ const tmp = `${file}.${process.pid}.tmp`;
38
+ writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
39
+ renameSync(tmp, file);
40
+ }
41
+ /** The host of a page the person opened, without "www."; undefined for blank and internal pages. */
42
+ export function siteOf(url) {
43
+ try {
44
+ const u = new URL(url);
45
+ if (u.protocol !== "http:" && u.protocol !== "https:")
46
+ return undefined;
47
+ return u.hostname.replace(/^www\./, "") || undefined;
48
+ }
49
+ catch {
50
+ return undefined;
51
+ }
52
+ }
53
+ function escapeHtml(text) {
54
+ return text.replace(/[&<>"]/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[ch]);
55
+ }
56
+ /** The page a login opens without --url: what this window is and what to do in it. Works offline. */
57
+ export function welcomePage(id, loginCommand = names().identity("login", id)) {
58
+ const name = escapeHtml(id);
59
+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Sign in: ${name}</title>
60
+ <style>
61
+ :root{color-scheme:light dark;--fg:#111;--muted:#555;--bg:#fff;--line:#ddd;--accent:#2b55e6}
62
+ @media (prefers-color-scheme:dark){:root{--fg:#eee;--muted:#aaa;--bg:#141414;--line:#333;--accent:#7d9bff}}
63
+ body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}
64
+ main{max-width:560px;margin:12vh auto;padding:0 24px}
65
+ .tag{font:12px ui-monospace,Menlo,monospace;letter-spacing:.08em;text-transform:uppercase;color:var(--muted)}
66
+ h1{font-size:28px;line-height:1.2;margin:8px 0 16px}
67
+ code{font:14px ui-monospace,Menlo,monospace;color:var(--accent)}
68
+ ol{padding-left:20px}li{margin:8px 0}
69
+ p.note{color:var(--muted);border-top:1px solid var(--line);padding-top:16px;margin-top:28px;font-size:14px}
70
+ </style></head><body><main>
71
+ <div class="tag">turno-browser &middot; identity <code>${name}</code></div>
72
+ <h1>This is the Chrome your agent will use.</h1>
73
+ <ol>
74
+ <li>Type the address of a site your agent needs in the bar above, and sign in as you always do.</li>
75
+ <li>Do the same for every site it needs, in this window or in new tabs.</li>
76
+ <li>Close the window when you are done. The cookies stay in this profile, and the agent starts signed in.</li>
77
+ </ol>
78
+ <p class="note">Next time you can open a site directly: <code>${escapeHtml(loginCommand)} --url https://mail.example.com</code></p>
79
+ </main></body></html>`;
80
+ }
9
81
  /**
10
82
  * Opens the identity's persistent Chrome headed, with the same launch settings as the MCP
11
83
  * server (Chrome channel, no fixed viewport, the identity's languages and time zone), and
@@ -45,17 +117,28 @@ export async function loginIdentity(id, options = {}) {
45
117
  // Chrome gets the caller's environment (HOME, XDG dirs), not this process's.
46
118
  env: chromeEnv(env),
47
119
  });
120
+ const sites = new Set();
48
121
  const pid = readLockPid(dir);
49
122
  if (pid !== undefined)
50
123
  held.update({ chromePid: pid, pgid: pid });
51
124
  const closed = new Promise((resolve) => ctx.on("close", () => resolve()));
52
125
  // On macOS Chrome keeps running with no windows, so treat "last page closed" as done.
53
- const watch = (page) => page.on("close", () => {
54
- setTimeout(() => {
55
- if (ctx.pages().length === 0)
56
- void ctx.close().catch(() => undefined);
57
- }, 250);
58
- });
126
+ const watch = (page) => {
127
+ // The sites the person opens, from the main frame of each tab: what the summary names.
128
+ page.on("framenavigated", (frame) => {
129
+ if (frame !== page.mainFrame())
130
+ return;
131
+ const site = siteOf(frame.url());
132
+ if (site)
133
+ sites.add(site);
134
+ });
135
+ page.on("close", () => {
136
+ setTimeout(() => {
137
+ if (ctx.pages().length === 0)
138
+ void ctx.close().catch(() => undefined);
139
+ }, 250);
140
+ });
141
+ };
59
142
  ctx.pages().forEach(watch);
60
143
  ctx.on("page", watch);
61
144
  const stop = () => void ctx.close().catch(() => undefined);
@@ -65,8 +148,13 @@ export async function loginIdentity(id, options = {}) {
65
148
  const page = ctx.pages()[0] ?? (await ctx.newPage());
66
149
  if (options.url)
67
150
  await page.goto(options.url).catch(() => undefined);
151
+ else
152
+ await page.setContent(welcomePage(id)).catch(() => undefined);
68
153
  await closed;
69
154
  clearHealth(id, env);
155
+ const result = { sites: [...sites].sort() };
156
+ writeLoginRecord(id, env, { at: new Date().toISOString(), sites: result.sites });
157
+ return result;
70
158
  }
71
159
  finally {
72
160
  process.off("SIGINT", stop);
@@ -48,6 +48,9 @@ import { type ProxySettings, type UserAgentMode } from "./network.js";
48
48
  * - `userAgent`, `proxy` (format 11), and the `"camoufox"` value of `engine`: opt-in network and
49
49
  * user agent settings (`network.ts`) and Camoufox as an alternate engine
50
50
  * (`engine-camoufox.ts`), all off by default.
51
+ * - `cursor` (format 12): the agent cursor (`agent-cursor.ts`): `"auto"` (the default) draws it
52
+ * when someone can see the browser (a Chrome window, or the live view), `"on"` always, `"off"`
53
+ * never.
51
54
  *
52
55
  * A missing file means Chrome's own defaults, as before identity.json existed.
53
56
  */
@@ -58,7 +61,7 @@ import { type ProxySettings, type UserAgentMode } from "./network.js";
58
61
  * only when it uses one of them, so an older turno-browser keeps reading every other file and
59
62
  * refuses one it would misread with "update turno-browser".
60
63
  */
61
- export declare const IDENTITY_FORMAT_VERSION = 11;
64
+ export declare const IDENTITY_FORMAT_VERSION = 12;
62
65
  /** The keys format 2 added. */
63
66
  declare const FORMAT_2_KEYS: readonly ["tabs", "backgroundThrottling", "settle", "block", "cache"];
64
67
  /** The keys format 3 added. */
@@ -94,6 +97,11 @@ export declare const MIN_LIVE_WAIT_MS = 5000;
94
97
  export declare const MAX_LIVE_WAIT_MS: number;
95
98
  /** The keys format 11 added (the `"camoufox"` engine also writes format 11). */
96
99
  declare const FORMAT_11_KEYS: readonly ["userAgent", "proxy"];
100
+ /** The keys format 12 added. */
101
+ declare const FORMAT_12_KEYS: readonly ["cursor"];
102
+ /** The values of `cursor` (the agent cursor, `agent-cursor.ts`). */
103
+ export declare const CURSOR_MODES: readonly ["auto", "on", "off"];
104
+ export type CursorMode = (typeof CURSOR_MODES)[number];
97
105
  /** The values of `engine`: `"chrome"` (the default), read mode, and Camoufox (format 11). */
98
106
  declare const ENGINE_VALUES: readonly ["chrome", "lightpanda", "camoufox"];
99
107
  /** What turno-browser records for an identity (`recorder.ts`, `recordings.ts`); all off by default. */
@@ -182,13 +190,15 @@ export interface IdentitySettings {
182
190
  userAgent?: UserAgentMode;
183
191
  /** A proxy for the identity's traffic; credentials only as `keychain:` references. */
184
192
  proxy?: ProxySettings;
193
+ /** The agent cursor: `"auto"` (the default, when the browser can be seen), `"on"` or `"off"`. */
194
+ cursor?: CursorMode;
185
195
  /** ISO dates. */
186
196
  created: string;
187
197
  updated: string;
188
198
  }
189
199
  /** A change to identity.json: a value sets the key, `null` removes it. */
190
200
  export type SettingsPatch = {
191
- [K in "timezone" | "locale" | "languages" | "region" | "health" | (typeof FORMAT_2_KEYS)[number] | (typeof FORMAT_3_KEYS)[number] | (typeof FORMAT_4_KEYS)[number] | (typeof FORMAT_5_KEYS)[number] | (typeof FORMAT_6_KEYS)[number] | (typeof FORMAT_7_KEYS)[number] | (typeof FORMAT_8_KEYS)[number] | (typeof FORMAT_9_KEYS)[number] | (typeof FORMAT_10_KEYS)[number] | (typeof FORMAT_11_KEYS)[number]]?: IdentitySettings[K] | null;
201
+ [K in "timezone" | "locale" | "languages" | "region" | "health" | (typeof FORMAT_2_KEYS)[number] | (typeof FORMAT_3_KEYS)[number] | (typeof FORMAT_4_KEYS)[number] | (typeof FORMAT_5_KEYS)[number] | (typeof FORMAT_6_KEYS)[number] | (typeof FORMAT_7_KEYS)[number] | (typeof FORMAT_8_KEYS)[number] | (typeof FORMAT_9_KEYS)[number] | (typeof FORMAT_10_KEYS)[number] | (typeof FORMAT_11_KEYS)[number] | (typeof FORMAT_12_KEYS)[number]]?: IdentitySettings[K] | null;
192
202
  };
193
203
  /**
194
204
  * The Chrome switches to drop for this identity's keychain setting, as Playwright launch