turno-browser 0.6.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.
@@ -64,6 +64,14 @@ function sweepSaved(dir) {
64
64
  dropSaved(join(dir, f));
65
65
  }
66
66
  }
67
+ /** An idle limit in words: 15m, 1h, 90s. */
68
+ export function formatIdle(ms) {
69
+ if (ms % 3_600_000 === 0)
70
+ return `${ms / 3_600_000}h`;
71
+ if (ms % 60_000 === 0)
72
+ return `${ms / 60_000}m`;
73
+ return `${Math.round(ms / 1000)}s`;
74
+ }
67
75
  function message(err) {
68
76
  return (err?.message ?? String(err)).replace(/^(Error: )?/, "");
69
77
  }
@@ -132,6 +140,13 @@ export function backgroundTransport(deps = defaultBackgroundDoDeps) {
132
140
  dropSaved(file);
133
141
  return true;
134
142
  },
143
+ afterEnd() {
144
+ const server = api.backgroundStatus(id, { env });
145
+ if (!server)
146
+ return undefined;
147
+ const idle = server.idleMs > 0 ? `until it has been idle for ${formatIdle(server.idleMs)}` : "until you stop it";
148
+ return `Chrome stays open in the background server ${idle}; turno-browser background stop ${id} closes it now.`;
149
+ },
135
150
  session: (fn) => withLock(file, env, async () => {
136
151
  let saved = current();
137
152
  if (!saved)
package/dist/cli/do.d.ts CHANGED
@@ -56,6 +56,8 @@ export interface DoTarget {
56
56
  };
57
57
  /** `do <id> end`: end the saved session at once; false when there was none. */
58
58
  end(): Promise<boolean>;
59
+ /** After `end`: what still runs (the server and its Chrome) and how to close it now, when anything does. */
60
+ afterEnd?(): string | undefined;
59
61
  /** Open a session, or continue the saved one, run `fn` in it, and keep it for the next command. */
60
62
  session<T>(fn: (s: DoSession) => Promise<T>): Promise<T>;
61
63
  }
@@ -75,6 +77,8 @@ export interface DoTransport {
75
77
  /** The server that serves identity `id`, and this caller's session; throws when there is none. */
76
78
  target(id: string, p: Parsed, io: Io): Promise<DoTarget>;
77
79
  }
80
+ /** A next step for the errors a first `do` meets most: a ref from an old snapshot, or text where a ref goes. */
81
+ export declare function errorHint(error: string, browser: string, id: string): string | undefined;
78
82
  /** Every action name, for the short form and for completion. */
79
83
  export declare const ACTION_NAMES: readonly string[];
80
84
  /** The flags of `do`, for completion: the common ones, the transport's, then the actions'. */
package/dist/cli/do.js CHANGED
@@ -287,8 +287,17 @@ function errorText(parts, whole) {
287
287
  return raw
288
288
  .replace(ANSI, "")
289
289
  .replace(/^(Error: )?browserBackend\.callTool: (Error: )?/, "")
290
+ .replace(/^Error: /, "")
290
291
  .trim();
291
292
  }
293
+ /** A next step for the errors a first `do` meets most: a ref from an old snapshot, or text where a ref goes. */
294
+ export function errorHint(error, browser, id) {
295
+ if (/^Ref \S+ not found/.test(error))
296
+ return `refs change with the page: \`${browser} do ${id} snapshot\` prints the current ones`;
297
+ if (/does not match any elements/.test(error))
298
+ return `pass a ref from \`${browser} do ${id} snapshot\` (like e12), or find one by its text with \`${browser} do ${id} find "<text>"\``;
299
+ return undefined;
300
+ }
292
301
  /**
293
302
  * Notes worth a line: a pause by the user (the live view: how long, what changed while the
294
303
  * command waited), a dialog, new tabs and downloads, what the tab governor did.
@@ -512,8 +521,12 @@ export async function browserDo(c, args, io) {
512
521
  const { name } = t.info(null);
513
522
  if (json)
514
523
  emit(io, p, DO_JSON, { ...head, session: t.info(null), action, ...blank, result: ended ? "ended" : "none" });
515
- else
524
+ else {
516
525
  io.out(ended ? `ended session ${name} of ${head.identity}` : `no session ${name} of ${head.identity} to end`);
526
+ const note = t.afterEnd?.();
527
+ if (note)
528
+ io.out(note);
529
+ }
517
530
  return Exit.ok;
518
531
  }
519
532
  const cl = call;
@@ -552,6 +565,9 @@ export async function browserDo(c, args, io) {
552
565
  error: r.error,
553
566
  });
554
567
  printText(io, r, json, c.names.program);
568
+ const hint = !json && r.error ? errorHint(r.error, b, id) : undefined;
569
+ if (hint)
570
+ io.err(`hint: ${hint}`);
555
571
  return r.ok ? Exit.ok : Exit.failure;
556
572
  });
557
573
  }
@@ -24,6 +24,8 @@ export declare function settingsPatch(p: Parsed, current?: IdentitySettings): Se
24
24
  /** What an identity records, in a few words: "flows, traces (up to 200MB)". */
25
25
  export declare function describeRecord(r: RecordSettings | undefined): string | undefined;
26
26
  export declare function hasSettings(patch: SettingsPatch): boolean;
27
+ /** An ISO time as this machine's local time, to the minute: 2026-11-19 23:46. Anything else as it is. */
28
+ export declare function localTime(iso: string | undefined): string;
27
29
  export declare function show(c: Ctx, id: string, args: string[], io: Io): number;
28
30
  /** The arguments of `set` after the identity, for the usage line. */
29
31
  export declare const SET_SYNOPSIS: string;
@@ -4,7 +4,17 @@ import { dirname, join } from "node:path";
4
4
  import { Exit, JSON_FLAG, bool, emit, fail, jsonOutput, parseFlags, str, style, } from "turno-core/cli";
5
5
  import { tildify } from "turno-core/paths";
6
6
  /** `show --json` (`turno identity show browser:<id> --json` in turno). */
7
- export const SHOW_JSON = jsonOutput(["id", "dir", "settingsFile", "settings", "problems", "inUse", "holder", "health"]);
7
+ export const SHOW_JSON = jsonOutput([
8
+ "id",
9
+ "dir",
10
+ "settingsFile",
11
+ "settings",
12
+ "problems",
13
+ "inUse",
14
+ "holder",
15
+ "health",
16
+ "login",
17
+ ]);
8
18
  /** `set --json`: what changed, or would. */
9
19
  export const SET_JSON = jsonOutput(["id", "settingsFile", "dryRun", "changes", "settings"]);
10
20
  /** `doctor --json`: the shape of `turno doctor --json`. */
@@ -79,6 +89,8 @@ export const SETTINGS_FLAGS = {
79
89
  "proxy-username": { type: "string" },
80
90
  "proxy-password": { type: "string" },
81
91
  "no-proxy": { type: "boolean" },
92
+ // The agent cursor (format 12): auto, on or off.
93
+ cursor: { type: "string" },
82
94
  };
83
95
  /** The identity.json key behind each tuning flag, so the package's messages name the flag. */
84
96
  const KEY_FLAGS = [
@@ -94,6 +106,7 @@ const KEY_FLAGS = [
94
106
  ["cache.maxSize", "--cache-max-size"],
95
107
  ["humanize.level", "--humanize"],
96
108
  ["sharing", "--sharing"],
109
+ ["cursor", "--cursor"],
97
110
  ["tabLocks.wait", "--tab-lock-wait"],
98
111
  ["tabLocks.release", "--tab-lock-release"],
99
112
  ["engine", "--engine"],
@@ -302,6 +315,10 @@ function tuningPatch(p, value, patch, current) {
302
315
  const sharing = value("sharing");
303
316
  if (sharing !== undefined)
304
317
  patch.sharing = sharing;
318
+ // Checked by the package too: an unknown value comes back as `--cursor must be ...`.
319
+ const cursor = value("cursor");
320
+ if (cursor !== undefined)
321
+ patch.cursor = cursor;
305
322
  const locks = { wait: value("tab-lock-wait"), release: value("tab-lock-release") };
306
323
  if (locks.wait !== undefined || locks.release !== undefined)
307
324
  patch.tabLocks = mergeGroup(current?.tabLocks, locks);
@@ -451,6 +468,22 @@ const HUMANIZE_TEXT = {
451
468
  full: "human-like pointer, typing and scrolling (full)",
452
469
  adaptive: "light, full on sites that showed a challenge (adaptive)",
453
470
  };
471
+ /** An ISO time as this machine's local time, to the minute: 2026-11-19 23:46. Anything else as it is. */
472
+ export function localTime(iso) {
473
+ if (!iso)
474
+ return "";
475
+ const d = new Date(iso);
476
+ if (Number.isNaN(d.getTime()))
477
+ return iso;
478
+ const two = (n) => String(n).padStart(2, "0");
479
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
480
+ }
481
+ /** What each agent cursor mode does, for `show`. */
482
+ const CURSOR_TEXT = {
483
+ auto: "shown when the browser can be seen: a window, or the live view (auto)",
484
+ on: "always shown (on)",
485
+ off: "never shown: pages stay as they are (off)",
486
+ };
454
487
  export function show(c, id, args, io) {
455
488
  const m = c.api;
456
489
  const p = parseFlags(args, JSON_FLAG, 1);
@@ -459,6 +492,7 @@ export function show(c, id, args, io) {
459
492
  const { path, settings, problems } = m.checkIdentitySettings(id, io.env);
460
493
  const holder = m.inUseBy(id, io.env);
461
494
  const health = m.readHealth(id, io.env);
495
+ const login = m.readLoginRecord(id, io.env);
462
496
  if (bool(p, "json")) {
463
497
  emit(io, p, SHOW_JSON, {
464
498
  id: `browser:${id}`,
@@ -469,6 +503,7 @@ export function show(c, id, args, io) {
469
503
  inUse: holder !== undefined,
470
504
  holder: holder ?? null,
471
505
  health: health ?? null,
506
+ login: login ?? null,
472
507
  });
473
508
  return Exit.ok;
474
509
  }
@@ -490,7 +525,12 @@ export function show(c, id, args, io) {
490
525
  ]);
491
526
  if (settings.region)
492
527
  rows.push(["region", settings.region]);
493
- rows.push(["health check", settings.health ? describeHealth(settings.health) : s.muted("(none)")]);
528
+ rows.push([
529
+ "health check",
530
+ settings.health
531
+ ? describeHealth(settings.health)
532
+ : s.muted(`off (to turn on: ${c.names.browser} set ${id} --health-url <url> --health-text <text>)`),
533
+ ]);
494
534
  if (settings.tabs)
495
535
  rows.push(["tabs", `${describeTabs(settings.tabs)}${s.muted(" (the rest as default)")}`]);
496
536
  if (settings.backgroundThrottling !== undefined)
@@ -513,6 +553,7 @@ export function show(c, id, args, io) {
513
553
  ]);
514
554
  if (settings.sharing === "tabs")
515
555
  rows.push(["sharing", "every agent session at once, each in its own tabs"]);
556
+ rows.push(["agent cursor", CURSOR_TEXT[settings.cursor ?? "auto"] ?? String(settings.cursor)]);
516
557
  if (settings.tabLocks)
517
558
  rows.push([
518
559
  "tab locks",
@@ -546,8 +587,8 @@ export function show(c, id, args, io) {
546
587
  "live view",
547
588
  `on (${c.names.browser} live ${id}); a paused call waits up to ${settings.live.wait ?? "2m"}`,
548
589
  ]);
549
- rows.push(["created", settings.created]);
550
- rows.push(["updated", settings.updated]);
590
+ rows.push(["created", localTime(settings.created)]);
591
+ rows.push(["updated", localTime(settings.updated)]);
551
592
  }
552
593
  if (health) {
553
594
  const state = health.status === "ok"
@@ -555,11 +596,22 @@ export function show(c, id, args, io) {
555
596
  : health.status === "needs_auth"
556
597
  ? s.err("NEEDS_AUTH")
557
598
  : s.warn("check failed");
558
- rows.push(["last check", `${state} ${s.muted(`${health.checkedAt}${health.detail ? `: ${health.detail}` : ""}`)}`]);
599
+ rows.push([
600
+ "last check",
601
+ `${state} ${s.muted(`${localTime(health.checkedAt)}${health.detail ? `: ${health.detail}` : ""}`)}`,
602
+ ]);
559
603
  }
604
+ rows.push([
605
+ "last sign-in",
606
+ login
607
+ ? `${localTime(login.at)}${login.sites.length ? s.muted(` (${login.sites.join(", ")})`) : s.muted(" (no site opened)")}`
608
+ : m.profileHasCookies(id, io.env)
609
+ ? s.muted(`no record yet (the next ${c.names.identity("login", id)} keeps one)`)
610
+ : s.warn(`never by hand (${c.names.identity("login", id)})`),
611
+ ]);
560
612
  rows.push([
561
613
  "state",
562
- holder ? s.warn(holder.replace(/^browser identity "[^"]+" is /, "").replace(/\. .*$/, "")) : s.ok("free"),
614
+ holder ? s.warn(holder.replace(/^browser identity "[^"]+" is /, "").replace(/\. .*$/, "")) : s.ok("not in use"),
563
615
  ]);
564
616
  io.out(s.bold(`browser:${id}`));
565
617
  const width = Math.max(...rows.map(([k]) => k.length));
@@ -575,7 +627,7 @@ const SET_FLAGS = { ...SETTINGS_FLAGS, "dry-run": { type: "boolean" }, ...JSON_F
575
627
  /** The arguments of `set` after the identity, for the usage line. */
576
628
  export const SET_SYNOPSIS = "[--timezone <zone>] [--locale <tag>] [--languages <tag,...>] [--region <CC>] [--health-url <url>] [--health-text <text>] [--health-selector <css>] [--no-health] " +
577
629
  "[--tabs-max <n>] [--tabs-popups close|keep] [--tabs-park <duration>] [--tabs-close <duration>] [--no-tabs] [--background-throttling true|false] [--settle <duration>] " +
578
- "[--block-trackers true|false] [--block-types image,media,font] [--block-patterns <host|glob>,...] [--no-block] [--cache] [--cache-max-size <size>] [--no-cache] [--humanize off|light|full|adaptive] [--sharing session|tabs] [--tab-lock-wait <duration>] [--tab-lock-release <duration>] " +
630
+ "[--block-trackers true|false] [--block-types image,media,font] [--block-patterns <host|glob>,...] [--no-block] [--cache] [--cache-max-size <size>] [--no-cache] [--humanize off|light|full|adaptive] [--cursor auto|on|off] [--sharing session|tabs] [--tab-lock-wait <duration>] [--tab-lock-release <duration>] " +
579
631
  "[--engine chrome|lightpanda] [--attach auto|<dir>|<url>] [--record-flows true|false] [--record-traces true|false] [--record-screenshots true|false] [--record-max-size <size>] [--no-record] " +
580
632
  "[--act] [--act-sampling true|false] [--act-provider chat-completions] [--act-endpoint <url>] [--act-model <name>] [--act-key keychain:<item>] [--act-max-steps <n>] [--act-max-tokens <n>] [--act-timeout <duration>] [--no-act] " +
581
633
  "[--captcha-provider task-api] [--captcha-endpoint <url>] [--captcha-key keychain:<item>] [--captcha-timeout <duration>] [--no-captcha] [--live true|false] [--live-wait <duration>] [--no-live] " +
@@ -614,6 +666,11 @@ Input:
614
666
  inside the target, keys typed with human delays), full (plus
615
667
  overshoot, reading pauses, wheel scrolling) or adaptive
616
668
  (light, full on a site after a challenge page there)
669
+ --cursor auto|on|off the agent cursor: an arrow with the agent's name that glides to
670
+ what it acts on, a ring, click ripples, and a frame with a badge
671
+ while it works. auto (default): when the browser can be seen (a
672
+ window, or the live view). It is an element in each page that a
673
+ page script can see: off leaves pages exactly as they are
617
674
 
618
675
  Which engine runs this identity (all off by default):
619
676
  --engine lightpanda read mode: Lightpanda instead of Chrome, for reading pages;
@@ -0,0 +1,12 @@
1
+ import { type Io } from "turno-core/cli";
2
+ import type { Ctx } from "./context.js";
3
+ import { type SetupAgent } from "./setup.js";
4
+ export declare const INIT_SYNOPSIS = "[--identity <id>] [--agent <claude-code|codex|cursor|copilot|gemini|json|none>] [--url <url>] [--no-login] [--yes] [--dry-run]";
5
+ export declare const INIT_DETAILS = "Sets up a browser identity and gives it to your agent, asking at each step:\n 1. the identity's name (a new one is created; an existing one is used as it is)\n 2. signing in by hand: Chrome opens on the identity's profile (--url opens a first site)\n 3. the agent: the agents found on this machine; its mcp add command runs only if you say yes,\n and an agent without one (cursor, json) gets the block to paste\n\n--yes answers yes to every step, --no-login skips the sign-in, --agent none skips the agent.\nWithout a terminal (--no-input, a pipe or an agent session) it needs --identity and --agent,\nskips the sign-in and prints the agent's command instead of running it.";
6
+ /** Runs an agent's `mcp add` command; tests replace it. Resolves to the exit code. */
7
+ export type RunCommand = (command: string, args: readonly string[], io: Io) => Promise<number>;
8
+ /** The agents installed here, in the order the question lists them. */
9
+ export declare function detectAgents(env: NodeJS.ProcessEnv): SetupAgent[];
10
+ /** Split a printed shell line back into words: setup only quotes with single quotes. */
11
+ export declare function shellWords(line: string): string[];
12
+ export declare function init(c: Ctx, args: string[], io: Io, run?: RunCommand): Promise<number>;
@@ -0,0 +1,217 @@
1
+ import { spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { bool, fail, needsAnswer, paint, parseFlags, str } from "turno-core/cli";
5
+ import { findOnPath, tildify } from "turno-core/paths";
6
+ import { loginSummary } from "./login-summary.js";
7
+ import { AGENT_NAMES, SETUP_AGENTS, mcpCommand, setupConfig, setupLines, unknownAgent, } from "./setup.js";
8
+ /**
9
+ * `turno-browser init`: the first setup, step by step. It does what the three commands of the
10
+ * docs do (`add`, `login`, `setup`) and asks before each step that opens a window or changes an
11
+ * agent's config:
12
+ *
13
+ * 1. the identity: a name, created, or the existing one reused;
14
+ * 2. the sign-in: Chrome opens on the identity's profile, on a first site when given;
15
+ * 3. the agent: the agents found on this machine, and its `mcp add` command, run only on a yes
16
+ * (an agent without one gets the block to paste).
17
+ *
18
+ * Without a person to answer (`--no-input`, a pipe, an agent session) it needs `--identity` and
19
+ * `--agent`, skips the sign-in (only a person can sign in) and runs nothing: it prints.
20
+ */
21
+ const INIT_FLAGS = {
22
+ identity: { type: "string" },
23
+ agent: { type: "string" },
24
+ url: { type: "string" },
25
+ "no-login": { type: "boolean" },
26
+ yes: { type: "boolean", short: "y" },
27
+ "dry-run": { type: "boolean" },
28
+ };
29
+ export const INIT_SYNOPSIS = "[--identity <id>] [--agent <claude-code|codex|cursor|copilot|gemini|json|none>] [--url <url>] [--no-login] [--yes] [--dry-run]";
30
+ export const INIT_DETAILS = `Sets up a browser identity and gives it to your agent, asking at each step:
31
+ 1. the identity's name (a new one is created; an existing one is used as it is)
32
+ 2. signing in by hand: Chrome opens on the identity's profile (--url opens a first site)
33
+ 3. the agent: the agents found on this machine; its mcp add command runs only if you say yes,
34
+ and an agent without one (cursor, json) gets the block to paste
35
+
36
+ --yes answers yes to every step, --no-login skips the sign-in, --agent none skips the agent.
37
+ Without a terminal (--no-input, a pipe or an agent session) it needs --identity and --agent,
38
+ skips the sign-in and prints the agent's command instead of running it.`;
39
+ const runCommand = (command, args, io) => new Promise((resolve) => {
40
+ const child = spawn(command, [...args], { stdio: "inherit", env: io.env });
41
+ child.on("error", () => resolve(127));
42
+ child.on("exit", (code) => resolve(code ?? 1));
43
+ });
44
+ /** The program each agent's own `mcp add` runs as: the one to look for on the PATH. */
45
+ const AGENT_PROGRAMS = {
46
+ "claude-code": "claude",
47
+ codex: "codex",
48
+ copilot: "copilot",
49
+ gemini: "gemini",
50
+ };
51
+ /** The agents installed here, in the order the question lists them. */
52
+ export function detectAgents(env) {
53
+ const home = env.HOME ?? "";
54
+ return SETUP_AGENTS.filter((a) => {
55
+ if (a === "json")
56
+ return false;
57
+ if (a === "cursor")
58
+ return Boolean(findOnPath("cursor-agent", env)) || (home !== "" && existsSync(join(home, ".cursor")));
59
+ const program = AGENT_PROGRAMS[a];
60
+ return program !== undefined && Boolean(findOnPath(program, env));
61
+ });
62
+ }
63
+ /** Split a printed shell line back into words: setup only quotes with single quotes. */
64
+ export function shellWords(line) {
65
+ const words = [];
66
+ const re = /'((?:[^']|'\\'')*)'|(\S+)/g;
67
+ for (let m = re.exec(line); m; m = re.exec(line))
68
+ words.push(m[1] !== undefined ? m[1].replace(/'\\''/g, "'") : m[2]);
69
+ return words;
70
+ }
71
+ async function askYes(io, question, yes) {
72
+ if (yes)
73
+ return true;
74
+ const answer = (await io.ask(`${question} [Y/n] `)).trim().toLowerCase();
75
+ return answer === "" || answer === "y" || answer === "yes";
76
+ }
77
+ async function askText(io, question, fallback) {
78
+ const answer = (await io.ask(fallback ? `${question} [${fallback}]: ` : `${question}: `)).trim();
79
+ return answer || fallback;
80
+ }
81
+ export async function init(c, args, io, run = runCommand) {
82
+ const p = parseFlags(args, INIT_FLAGS, 0);
83
+ const b = c.names.browser;
84
+ const api = c.api;
85
+ const yes = bool(p, "yes");
86
+ const dry = bool(p, "dry-run");
87
+ const interactive = c.deps.interactive(io) && !dry;
88
+ const step = (n, title) => io.out(`\n${paint(io, `Step ${n} of 3`, "2")} ${paint(io, title, "1")}`);
89
+ const url = str(p, "url");
90
+ if (url !== undefined && !/^https?:\/\//.test(url))
91
+ return fail(`--url must start with http:// or https://: ${url}`);
92
+ const agentFlag = str(p, "agent");
93
+ if (agentFlag !== undefined && agentFlag !== "none" && !SETUP_AGENTS.includes(agentFlag))
94
+ return fail(unknownAgent(agentFlag));
95
+ if (!interactive && !dry && (str(p, "identity") === undefined || agentFlag === undefined)) {
96
+ return needsAnswer(`${b} init`, "--identity and --agent");
97
+ }
98
+ io.out(`Set up ${b}: a browser identity, signed in once, given to your agent.`);
99
+ io.out(paint(io, "Ctrl-C stops at any step; each step that is done stays done.", "2"));
100
+ // 1. The identity.
101
+ step(1, "the identity");
102
+ const existing = api.listIdentities(io.env).map((i) => i.id);
103
+ if (existing.length)
104
+ io.out(`Identities here: ${existing.join(", ")}`);
105
+ io.out("An identity is one Chrome profile your agent uses, with your sign-ins. Name it after what it is for.");
106
+ let id = str(p, "identity");
107
+ while (id === undefined) {
108
+ const answer = await askText(io, "Name", existing.length === 1 ? existing[0] : "personal");
109
+ try {
110
+ api.assertIdentityId(answer);
111
+ id = answer;
112
+ }
113
+ catch (err) {
114
+ io.err(err.message);
115
+ }
116
+ }
117
+ try {
118
+ api.assertIdentityId(id);
119
+ }
120
+ catch (err) {
121
+ return fail(err.message);
122
+ }
123
+ if (api.identityExists(id, io.env))
124
+ io.out(`Using the identity "${id}" that is already here.`);
125
+ else if (dry)
126
+ io.out(`(dry run) would create the identity "${id}"`);
127
+ else {
128
+ const info = api.addIdentity(id, io.env);
129
+ io.out(`Created "${id}" at ${tildify(info.dir, io.env)}`);
130
+ }
131
+ // 2. The sign-in.
132
+ step(2, "sign in by hand once");
133
+ let firstSite = url;
134
+ if (bool(p, "no-login"))
135
+ io.out(`Skipped. Sign in later with ${b} login ${id}.`);
136
+ else if (dry)
137
+ io.out(`(dry run) would open Chrome for "${id}"${url ? ` on ${url}` : ""} so you sign in`);
138
+ else if (!interactive)
139
+ io.out(`Skipped: only a person can sign in. Run ${b} login ${id} on a terminal.`);
140
+ else if (api.isInUse(id, io.env))
141
+ io.out(`Skipped: "${id}" is in use right now. Sign in later with ${b} login ${id}.`);
142
+ else {
143
+ io.out("Chrome opens on this identity's profile. Sign in to the sites your agent needs, then close the window.");
144
+ if (firstSite === undefined && !yes) {
145
+ const answer = await askText(io, "First site to open (Enter for none)", "");
146
+ if (answer)
147
+ firstSite = /^https?:\/\//.test(answer) ? answer : `https://${answer}`;
148
+ }
149
+ if (await askYes(io, "Open Chrome now?", yes)) {
150
+ const result = await api.loginIdentity(id, { env: io.env, ...(firstSite ? { url: firstSite } : {}) });
151
+ io.out(loginSummary(c, id, result?.sites ?? []));
152
+ }
153
+ else
154
+ io.out(`Skipped. Sign in later with ${b} login ${id}.`);
155
+ }
156
+ // 3. The agent.
157
+ step(3, "give it to your agent");
158
+ const found = detectAgents(io.env);
159
+ let agent = agentFlag;
160
+ if (agent === undefined) {
161
+ io.out(found.length
162
+ ? `Agents found here: ${found.map((a) => `${a} (${AGENT_NAMES[a]})`).join(", ")}`
163
+ : "No agent found on the PATH.");
164
+ io.out(`Agents: ${SETUP_AGENTS.join(", ")}, or none.`);
165
+ while (agent === undefined) {
166
+ const answer = (await askText(io, "Agent", found[0] ?? "json")).toLowerCase();
167
+ if (answer === "none" || SETUP_AGENTS.includes(answer))
168
+ agent = answer;
169
+ else
170
+ io.err(unknownAgent(answer));
171
+ }
172
+ }
173
+ let connected = false;
174
+ if (agent === "none")
175
+ io.out(`Skipped. ${b} setup <agent> --identity ${id} prints it later.`);
176
+ else {
177
+ const { command, onPath } = mcpCommand(io.env);
178
+ const cfg = setupConfig(agent, id, command);
179
+ if (!onPath)
180
+ cfg.notes.push("turno-browser-mcp is not on the PATH here, so this names it by its full path.");
181
+ const program = AGENT_PROGRAMS[agent];
182
+ const runnable = cfg.shell !== null && program !== undefined && Boolean(findOnPath(program, io.env));
183
+ if (runnable && interactive && !dry) {
184
+ io.out(`This adds the browser to ${AGENT_NAMES[agent]}:`);
185
+ io.out(` ${cfg.shell}`);
186
+ if (await askYes(io, "Run it now?", yes)) {
187
+ const [bin, ...rest] = shellWords(cfg.shell);
188
+ const code = await run(bin, rest, io);
189
+ if (code === 0) {
190
+ connected = true;
191
+ io.out(`Done: ${AGENT_NAMES[agent]} has the browser "${id}".`);
192
+ }
193
+ else
194
+ io.err(`That command ended with code ${code}; run it yourself, or ${b} setup ${agent} --identity ${id}.`);
195
+ }
196
+ else
197
+ for (const l of setupLines(cfg))
198
+ io.out(l);
199
+ }
200
+ else {
201
+ if (dry && runnable)
202
+ io.out(`(dry run) would ask to run: ${cfg.shell}`);
203
+ else
204
+ for (const l of setupLines(cfg))
205
+ io.out(l);
206
+ }
207
+ }
208
+ // What is left.
209
+ io.out(`\n${paint(io, "Next", "1")}`);
210
+ if (agent !== "none") {
211
+ const who = agent === undefined ? "your agent" : AGENT_NAMES[agent];
212
+ io.out(`${connected ? "Start" : "Once it is added, start"} a new ${who} session and ask it to open ${firstSite ?? "a site you signed in to"}.`);
213
+ }
214
+ io.out(`${b} doctor checks Chrome and the identity; ${b} show ${id} shows its settings.`);
215
+ return 0;
216
+ }
217
+ //# sourceMappingURL=init.js.map
@@ -0,0 +1,6 @@
1
+ import type { Ctx } from "./context.js";
2
+ /**
3
+ * What a login saved, in words: the sites the person opened (the agent starts with their
4
+ * cookies), or that nothing was opened, so nothing new was signed in.
5
+ */
6
+ export declare function loginSummary(c: Ctx, id: string, sites: readonly string[]): string;
@@ -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
@@ -14,6 +14,7 @@ import { COMPLETION_USAGE, complete, completionScript } from "./completion.js";
14
14
  const PROGRAM = "turno-browser";
15
15
  /** The sections of `turno-browser --help`, in order. */
16
16
  const SECTIONS = [
17
+ { title: "Start here", commands: ["init"] },
17
18
  { title: "Identities", commands: ["list", "add", "show", "set", "login", "remove"] },
18
19
  { title: "Connect an agent", commands: ["setup"] },
19
20
  { title: "Sign-ins and sessions", commands: ["vault", "secret", "export", "import"] },
@@ -36,6 +37,8 @@ export function renderHelp(io, cli) {
36
37
  out.push(s.color ? `${s.bold(s.accent(PROGRAM))}${s.bold(first[0].slice(PROGRAM.length))}` : first[0]);
37
38
  for (const l of first.slice(1))
38
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.`);
39
42
  out.push("", s.header("Usage"));
40
43
  out.push(columns([
41
44
  [`${PROGRAM} <command> [flags]`, "manage identities: persistent Chrome profiles your agents sign in with"],
@@ -6,8 +6,40 @@ import type { Ctx } from "./context.js";
6
6
  * agent's config is the person's (inside turno, `turno mcp sync` writes it from mcp.toml).
7
7
  */
8
8
  export declare const SETUP_AGENTS: readonly ["claude-code", "codex", "cursor", "copilot", "gemini", "json"];
9
+ export type SetupAgent = (typeof SETUP_AGENTS)[number];
9
10
  /** `setup --json`: one object. */
10
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>;
11
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[];
12
44
  /** `<browser> setup <agent> [--identity <id>] [--json]`. */
13
45
  export declare function setup(c: Ctx, args: string[], io: Io): number;