turno-cli 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.
Files changed (116) hide show
  1. package/CHANGELOG.md +266 -0
  2. package/README.md +134 -42
  3. package/dist/accounts/audit.js +27 -15
  4. package/dist/accounts/builtin.js +35 -7
  5. package/dist/accounts/delegate.js +30 -7
  6. package/dist/accounts/policy.js +4 -2
  7. package/dist/accounts/registry.js +3 -1
  8. package/dist/agents/adapter.js +22 -0
  9. package/dist/agents/claude.js +54 -3
  10. package/dist/agents/codex.js +94 -6
  11. package/dist/agents/copilot.js +19 -2
  12. package/dist/agents/cursor.js +19 -2
  13. package/dist/agents/index.js +1 -1
  14. package/dist/agents/snippets.js +37 -10
  15. package/dist/cli/args.js +32 -15
  16. package/dist/cli/commands/accounts.js +29 -7
  17. package/dist/cli/commands/auto.js +50 -12
  18. package/dist/cli/commands/browser-do-session.js +170 -0
  19. package/dist/cli/commands/browser-do.js +740 -0
  20. package/dist/cli/commands/browser-flows.js +300 -0
  21. package/dist/cli/commands/browser-identity.js +952 -0
  22. package/dist/cli/commands/browser-live.js +118 -0
  23. package/dist/cli/commands/browser-session.js +102 -0
  24. package/dist/cli/commands/browser-vault.js +193 -0
  25. package/dist/cli/commands/browser.js +303 -62
  26. package/dist/cli/commands/complete.js +13 -3
  27. package/dist/cli/commands/completion.js +4 -0
  28. package/dist/cli/commands/config.js +90 -13
  29. package/dist/cli/commands/demo.js +36 -7
  30. package/dist/cli/commands/doctor.js +170 -36
  31. package/dist/cli/commands/identity.js +101 -12
  32. package/dist/cli/commands/init.js +42 -10
  33. package/dist/cli/commands/limit.js +65 -9
  34. package/dist/cli/commands/mcp-call.js +240 -0
  35. package/dist/cli/commands/mcp-oauth.js +33 -6
  36. package/dist/cli/commands/mcp-observe.js +128 -23
  37. package/dist/cli/commands/mcp-share.js +201 -0
  38. package/dist/cli/commands/mcp.js +203 -42
  39. package/dist/cli/commands/mcpd.js +76 -12
  40. package/dist/cli/commands/open.js +26 -3
  41. package/dist/cli/commands/profile.js +212 -30
  42. package/dist/cli/commands/resolve.js +8 -1
  43. package/dist/cli/commands/run.js +24 -4
  44. package/dist/cli/commands/secret.js +23 -38
  45. package/dist/cli/commands/session.js +16 -5
  46. package/dist/cli/commands/sessions.js +7 -1
  47. package/dist/cli/commands/setup.js +83 -11
  48. package/dist/cli/commands/status.js +67 -15
  49. package/dist/cli/commands/statusline.js +7 -2
  50. package/dist/cli/commands/ui.js +17 -5
  51. package/dist/cli/commands/undo.js +39 -7
  52. package/dist/cli/commands/uninstall.js +24 -5
  53. package/dist/cli/commands/upgrade.js +113 -76
  54. package/dist/cli/commands/usage.js +11 -10
  55. package/dist/cli/commands/version.js +20 -8
  56. package/dist/cli/commands/which.js +5 -3
  57. package/dist/cli/diagnostics.js +184 -0
  58. package/dist/cli/exit.js +65 -0
  59. package/dist/cli/group.js +20 -8
  60. package/dist/cli/help.js +6 -1
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +24 -8
  63. package/dist/cli/launch.js +31 -2
  64. package/dist/cli/launchers.js +25 -10
  65. package/dist/cli/main.js +52 -18
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +17 -5
  69. package/dist/cli/registry.js +20 -2
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +31 -9
  73. package/dist/cli/style.js +35 -5
  74. package/dist/cli/topics.js +155 -0
  75. package/dist/core/config.js +39 -3
  76. package/dist/core/fsutil.js +2 -10
  77. package/dist/core/journal.js +19 -11
  78. package/dist/core/manifest.js +28 -1
  79. package/dist/core/paths.js +6 -112
  80. package/dist/core/profiles.js +28 -8
  81. package/dist/core/resolve.js +13 -3
  82. package/dist/core/secrets.js +4 -154
  83. package/dist/core/state-file.js +107 -0
  84. package/dist/core/update.js +14 -11
  85. package/dist/core/version.js +57 -10
  86. package/dist/demo/server.js +10 -2
  87. package/dist/mcpd/cache.js +6 -7
  88. package/dist/mcpd/calllog.js +10 -9
  89. package/dist/mcpd/client-names.js +8 -13
  90. package/dist/mcpd/connectors.js +42 -3
  91. package/dist/mcpd/daemon.js +29 -8
  92. package/dist/mcpd/folder-sets.js +5 -2
  93. package/dist/mcpd/gateway.js +57 -29
  94. package/dist/mcpd/health.js +70 -26
  95. package/dist/mcpd/importer.js +106 -9
  96. package/dist/mcpd/instances.js +70 -32
  97. package/dist/mcpd/jsonrpc.js +3 -1
  98. package/dist/mcpd/middleware.js +156 -0
  99. package/dist/mcpd/modern.js +57 -19
  100. package/dist/mcpd/oauth.js +71 -17
  101. package/dist/mcpd/peerpid.js +63 -17
  102. package/dist/mcpd/pressure.js +4 -1
  103. package/dist/mcpd/rss.js +34 -19
  104. package/dist/mcpd/service.js +28 -4
  105. package/dist/mcpd/share.js +217 -0
  106. package/dist/mcpd/state.js +16 -16
  107. package/dist/mcpd/sync.js +22 -12
  108. package/dist/mcpd/systemd.js +4 -1
  109. package/dist/mcpd/tokens.js +4 -8
  110. package/dist/mcpd/upstream.js +12 -5
  111. package/dist/statusline/cost.js +17 -4
  112. package/dist/statusline/input.js +15 -3
  113. package/dist/ui/fonts.js +1 -1
  114. package/dist/ui/settings.js +6 -1
  115. package/npm-shrinkwrap.json +12 -3
  116. package/package.json +7 -6
package/dist/cli/args.js CHANGED
@@ -1,6 +1,5 @@
1
1
  import { parseArgs } from "node:util";
2
- import { highlightJson } from "./highlight.js";
3
- import { colors, fail } from "./io.js";
2
+ import { fail } from "./io.js";
4
3
  /** Flags shared by every command, so the same words mean the same thing everywhere. */
5
4
  export const JSON_FLAG = { json: { type: "boolean" } };
6
5
  export const DRY_RUN = { "dry-run": { type: "boolean" } };
@@ -14,17 +13,46 @@ export const WATCH = { watch: { type: "boolean" } };
14
13
  export function flagsOf(...specs) {
15
14
  return specs.flatMap((s) => Object.keys(s)).map((k) => `--${k}`);
16
15
  }
16
+ /**
17
+ * Take `--json=<value>` out of `args` when the spec has a boolean --json: it turns
18
+ * --json on and keeps the value for `emit`. Only a command's own flags count, not those after --.
19
+ */
20
+ function takeJsonValue(args, spec) {
21
+ if (spec.json?.type !== "boolean")
22
+ return { args };
23
+ let json;
24
+ const out = [];
25
+ let i = 0;
26
+ for (; i < args.length && args[i] !== "--"; i++) {
27
+ const a = args[i];
28
+ if (a.startsWith("--json=")) {
29
+ json = a.slice("--json=".length);
30
+ out.push("--json");
31
+ }
32
+ else {
33
+ if (a === "--json")
34
+ json ??= "";
35
+ out.push(a);
36
+ }
37
+ }
38
+ return { args: [...out, ...args.slice(i)], ...(json !== undefined ? { json } : {}) };
39
+ }
17
40
  /**
18
41
  * Parse `args` against `spec` (long flags, `--flag=value`, short aliases). Unknown flags and
19
42
  * positionals beyond `max` are usage errors with a plain message.
20
43
  */
21
- export function parseFlags(args, spec, max = Number.POSITIVE_INFINITY) {
44
+ export function parseFlags(given, spec, max = Number.POSITIVE_INFINITY) {
45
+ const { args, json } = takeJsonValue(given, spec);
22
46
  let parsed;
23
47
  try {
24
48
  parsed = parseArgs({ args, options: spec, allowPositionals: true, strict: true });
49
+ if (json !== undefined)
50
+ parsed.json = json;
25
51
  }
26
52
  catch (err) {
27
- const msg = err.message.replace(/^Unknown option '(.+?)'.*$/s, "unknown option $1").replace(/\. To specify.*$/s, "");
53
+ const msg = err.message
54
+ .replace(/^Unknown option '(.+?)'.*$/s, "unknown option $1")
55
+ .replace(/\. To specify.*$/s, "");
28
56
  return fail(msg.replace(/^Option '(--[\w-]+)(?: <value>)?' argument missing$/, "$1 needs a value"));
29
57
  }
30
58
  if (parsed.positionals.length > max)
@@ -48,15 +76,4 @@ export function count(p, name, fallback) {
48
76
  fail(`--${name} must be a positive integer`);
49
77
  return n;
50
78
  }
51
- /**
52
- * Print a value as indented JSON, colored on a terminal without NO_COLOR (never in a pipe,
53
- * even with FORCE_COLOR, since programs read it).
54
- * Given only an output function it prints plain JSON.
55
- */
56
- export function printJson(io, value) {
57
- const text = JSON.stringify(value, null, 2);
58
- const out = typeof io === "function" ? io : io.out;
59
- // Only on a real terminal: --json is read by programs, so FORCE_COLOR never colors a pipe here.
60
- out(text !== undefined && typeof io !== "function" && io.isTty && colors(io) ? highlightJson(text) : text);
61
- }
62
79
  //# sourceMappingURL=args.js.map
@@ -2,11 +2,12 @@ import { resolve } from "node:path";
2
2
  import { readAudit, verifyAudit } from "../../accounts/audit.js";
3
3
  import { launcherExists } from "../../accounts/delegate.js";
4
4
  import { effectivePolicy } from "../../accounts/policy.js";
5
- import { isValidService, loadRegistry, makeAccount, parseAccountId, saveRegistry } from "../../accounts/registry.js";
5
+ import { isValidService, loadRegistry, makeAccount, parseAccountId, saveRegistry, } from "../../accounts/registry.js";
6
6
  import { Journal } from "../../core/journal.js";
7
7
  import { expandHome, paths, tildify } from "../../core/paths.js";
8
- import { DRY_RUN, JSON_FLAG, bool, count, parseFlags, printJson, str } from "../args.js";
8
+ import { DRY_RUN, JSON_FLAG, bool, count, parseFlags, str } from "../args.js";
9
9
  import { fail, paint } from "../io.js";
10
+ import { emit, jsonOutput } from "../output.js";
10
11
  const USAGE = `Usage:
11
12
  turno accounts list accounts, owners and folder preferences
12
13
  turno accounts add <service:label> --profile <p> --tools <pattern>[,<pattern>]
@@ -34,16 +35,37 @@ const ADD_SPEC = {
34
35
  ...DRY_RUN,
35
36
  };
36
37
  export const LOG_SPEC = { tail: { type: "string", short: "n" }, verify: { type: "boolean" }, ...JSON_FLAG };
38
+ /** `log --json`: one element per audit line; `log --verify --json`: the chain check. */
39
+ const AUDIT_JSON = jsonOutput([
40
+ "ts",
41
+ "caller",
42
+ "account",
43
+ "owner",
44
+ "write",
45
+ "task",
46
+ "outcome",
47
+ "detail",
48
+ "durationMs",
49
+ "costUsd",
50
+ "decision",
51
+ "prev",
52
+ ]);
53
+ const VERIFY_JSON = jsonOutput(["file", "ok", "lines", "legacy", "line", "reason"]);
54
+ export const LOG_JSON = jsonOutput([
55
+ ...AUDIT_JSON.fields,
56
+ ...VERIFY_JSON.fields.filter((f) => !AUDIT_JSON.fields.includes(f)),
57
+ ]);
37
58
  /**
38
- * `log --verify`: check the hash chain of audit.jsonl (ADR 0018). It shows accidents and naive
59
+ * `log --verify`: check the hash chain of audit.jsonl. It shows accidents and naive
39
60
  * edits (a changed, inserted, removed or reordered line), not a determined attacker who can
40
61
  * rewrite the whole file, and it cannot see lines cut from the end.
41
62
  */
42
- function verifyLog(io, json) {
63
+ function verifyLog(io, p) {
64
+ const json = bool(p, "json");
43
65
  const v = verifyAudit(io.env);
44
66
  const file = tildify(paths(io.env).auditLog, io.env);
45
67
  if (json) {
46
- printJson(io, { file, ...v, line: v.line ?? null, reason: v.reason ?? null });
68
+ emit(io, p, VERIFY_JSON, { file, ...v, line: v.line ?? null, reason: v.reason ?? null });
47
69
  return v.ok ? 0 : 1;
48
70
  }
49
71
  if (!v.ok) {
@@ -205,11 +227,11 @@ export function prefer(rawArgs, io) {
205
227
  export function log(args, io) {
206
228
  const p = parseFlags(args, LOG_SPEC, 0);
207
229
  if (bool(p, "verify"))
208
- return verifyLog(io, bool(p, "json"));
230
+ return verifyLog(io, p);
209
231
  const n = count(p, "tail", 20);
210
232
  const entries = readAudit(n, io.env);
211
233
  if (bool(p, "json")) {
212
- printJson(io, entries);
234
+ emit(io, p, AUDIT_JSON, entries);
213
235
  return 0;
214
236
  }
215
237
  if (!entries.length) {
@@ -4,8 +4,9 @@ import { loadConfig } from "../../core/config.js";
4
4
  import { paths, tildify } from "../../core/paths.js";
5
5
  import { listProfiles } from "../../core/profiles.js";
6
6
  import { resolveProfile } from "../../core/resolve.js";
7
+ import { Exit } from "../exit.js";
7
8
  import { CliError, fail } from "../io.js";
8
- import { execLauncher, findOnPath, launcherPath } from "../launch.js";
9
+ import { execLauncher, findOnPath, launcherPath, wantsSafe } from "../launch.js";
9
10
  import { launcherName } from "../launchers.js";
10
11
  /**
11
12
  * Decide what `turno auto` runs in `cwd`. It never falls back to another account in silence:
@@ -28,7 +29,7 @@ export function planAuto(argv, io, cwd = process.cwd()) {
28
29
  const plain = () => {
29
30
  const file = findOnPath(a.command, env);
30
31
  if (!file)
31
- throw new CliError(`${a.command} is not installed (${a.install})`, 127);
32
+ throw new CliError(`${a.command} is not installed (${a.install})`, Exit.notInstalled);
32
33
  return file;
33
34
  };
34
35
  let config;
@@ -38,7 +39,13 @@ export function planAuto(argv, io, cwd = process.cwd()) {
38
39
  catch (err) {
39
40
  const msg = err.message;
40
41
  if (env.TURNO_ALLOW_PLAIN === "1")
41
- return { file: plain(), args, notice: `turno: ${msg}; running plain ${a.command} (TURNO_ALLOW_PLAIN=1)`, always: true };
42
+ return {
43
+ file: plain(),
44
+ agent,
45
+ args,
46
+ notice: `turno: ${msg}; running plain ${a.command} (TURNO_ALLOW_PLAIN=1)`,
47
+ always: true,
48
+ };
42
49
  throw new CliError(`${msg}\nturno auto does not guess an account while config.toml is broken. Fix it (turno config edit), or run plain ${a.command} once with TURNO_ALLOW_PLAIN=1.`);
43
50
  }
44
51
  const where = tildify(cwd, env);
@@ -48,29 +55,46 @@ export function planAuto(argv, io, cwd = process.cwd()) {
48
55
  if (!launcher) {
49
56
  if (!listProfiles(config, env).includes(r.chosen)) {
50
57
  const add = `turno profile add ${r.chosen}${agent === DEFAULT_AGENT ? "" : ` --agent ${agent}`}`;
51
- throw new CliError(`${where} uses the ${r.chosen} profile (${r.reason}), but there is no such profile. Run: ${add}, or change the rule (turno profile which)`);
58
+ throw new CliError(`${where} uses the ${r.chosen} profile (${r.reason}), but there is no such profile. Run: ${add}, or change the rule (turno profile which)`, Exit.noProfile);
52
59
  }
53
60
  const missing = tildify(join(paths(env).bin, launcherName(r.chosen, agent)), env);
54
61
  throw new CliError(`${where} uses the ${r.chosen} profile, but its launcher ${missing} is missing. Run: turno profile repair ${r.chosen}`);
55
62
  }
56
63
  return {
57
64
  file: launcher,
65
+ agent,
66
+ profile: r.chosen,
58
67
  args,
59
- notice: r.note ? `turno: ${r.assigned} ${r.note} → using ${r.chosen} (${r.reason})` : `turno: account ${r.chosen} (${r.reason})`,
68
+ notice: r.note
69
+ ? `turno: ${r.assigned} ${r.note} → using ${r.chosen} (${r.reason})`
70
+ : `turno: account ${r.chosen} (${r.reason})`,
60
71
  };
61
72
  }
62
73
  if (config.system === "") {
63
- throw new CliError(`${where} has no rule and no default profile, and system = "" says there is no default account. Assign one: turno profile assign ${where} <profile>`);
74
+ throw new CliError(`${where} has no rule and no default profile, and system = "" says there is no default account. Assign one: turno profile assign ${where} <profile>`, Exit.noProfile);
64
75
  }
65
76
  if (agent !== DEFAULT_AGENT && listProfiles(config, env, agent).length === 0) {
66
- return { file: plain(), args, notice: `turno: no ${a.label} profile yet, so this runs plain ${a.command} with ${hub} (turno profile add <name> --agent ${agent})`, always: true };
77
+ return {
78
+ file: plain(),
79
+ agent,
80
+ args,
81
+ notice: `turno: no ${a.label} profile yet, so this runs plain ${a.command} with ${hub} (turno profile add <name> --agent ${agent})`,
82
+ always: true,
83
+ };
67
84
  }
68
- return { file: plain(), args, notice: `turno: no rule or default for ${where}; running plain ${a.command} with ${hub}` };
85
+ return {
86
+ file: plain(),
87
+ agent,
88
+ args,
89
+ notice: `turno: no rule or default for ${where}; running plain ${a.command} with ${hub}`,
90
+ };
69
91
  }
70
92
  export const command = {
71
93
  summary: "open the agent with the account assigned to this folder (turno-auto)",
72
94
  usage: [
73
- "Usage: turno auto [--agent claude|codex|copilot|cursor] [agent args]",
95
+ "Usage: turno auto [--agent <agent>] [--no-gateway] [agent args]",
96
+ "",
97
+ "<agent> is claude (the default), codex, copilot or cursor.",
74
98
  "",
75
99
  "Resolves the profile of that agent (Claude Code by default) for the current",
76
100
  "folder (a git worktree counts as its main repository), switches to the fallback",
@@ -78,16 +102,30 @@ export const command = {
78
102
  "Without a rule or a default, runs the agent's own command (claude, codex,",
79
103
  "copilot, cursor-agent).",
80
104
  "",
81
- "It never switches accounts in silence: when the chosen profile or its launcher",
82
- "is missing, or config.toml does not parse, it exits 1 and says how to fix it.",
105
+ "It never switches accounts in silence: it exits 3 when the folder's profile does",
106
+ 'not exist (or there is no rule and system = ""), 1 when its launcher is missing',
107
+ "or config.toml does not parse, and says how to fix it (turno help exit-codes).",
83
108
  "TURNO_ALLOW_PLAIN=1 runs the plain agent despite a broken config.toml;",
84
109
  'system = "" in config.toml makes folders without a rule an error too.',
110
+ "",
111
+ "--no-gateway (or TURNO_SAFE=1) opens the same account in safe mode: no mcpd",
112
+ "entries and no status line, to tell whether a problem comes from turno (turno",
113
+ "run --help).",
114
+ "",
115
+ "Examples:",
116
+ " $ turno auto",
117
+ " $ turno auto --resume",
118
+ " $ turno auto --agent codex",
119
+ " $ turno auto --no-gateway",
85
120
  ].join("\n"),
86
121
  async run(argv, io) {
87
- const plan = planAuto(argv, io);
122
+ const safe = wantsSafe(argv, io.env);
123
+ const plan = planAuto(safe ? (await import("../safe.js")).takeSafeFlag(argv).args : argv, io);
88
124
  const quiet = plan.args[0] === "--version" || plan.args[0] === "-v";
89
125
  if (plan.notice && (plan.always || (process.stderr.isTTY && !quiet)))
90
126
  io.err(plan.notice);
127
+ if (safe)
128
+ return (await import("../safe.js")).launchSafe(plan.agent, plan.profile, plan.args, io);
91
129
  return execLauncher(plan.file, plan.args, io.env);
92
130
  },
93
131
  };
@@ -0,0 +1,170 @@
1
+ import { closeSync, openSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { ensurePrivateDir, writePrivateFile } from "turno-core/paths";
4
+ import { pidAlive } from "turno-core/process";
5
+ import { paths } from "../../core/paths.js";
6
+ import { UsageError } from "../io.js";
7
+ const SHELLS = new Set(["sh", "bash", "zsh", "dash", "fish", "ksh", "mksh", "ash", "csh", "tcsh"]);
8
+ const WRAPPERS = new Set(["env", "timeout", "gtimeout", "nice", "nohup", "stdbuf", "time", "xargs"]);
9
+ const RUNNERS = /^(pnpm|pnpx|npm|npx|yarn|bunx|corepack)(\.c?js)?$|^(npm|npx)-cli\.js$/;
10
+ function words(command) {
11
+ return command.trim().split(/\s+/);
12
+ }
13
+ function program(word) {
14
+ return basename(word ?? "").replace(/^-/, "");
15
+ }
16
+ /**
17
+ * True for a process that only passes a command on: a shell started for one command (`zsh -c`,
18
+ * `bash -lc`, as coding agents run each command), a wrapper (`env`, `timeout`) or a package
19
+ * runner (`pnpm exec`). An interactive or login shell (`-zsh`, `bash`) and a script's shell
20
+ * (`bash script.sh`) are not: a session belongs to them.
21
+ */
22
+ export function passesOn(command) {
23
+ const [first, ...rest] = words(command);
24
+ const name = program(first);
25
+ if (SHELLS.has(name))
26
+ return rest.some((w) => /^-[a-zA-Z]*c[a-zA-Z]*$/.test(w));
27
+ if (WRAPPERS.has(name))
28
+ return true;
29
+ if (RUNNERS.test(name))
30
+ return true;
31
+ if (name === "node" || name === "bun")
32
+ return RUNNERS.test(program(rest[0]));
33
+ return false;
34
+ }
35
+ /**
36
+ * The owner of a CLI session started from `start` (the parent of this process). An agent that a
37
+ * turno launcher started names itself in TURNO_SESSION_PID (`agent`), the pid its own MCP
38
+ * sessions send: when that process is up the tree, it is the owner. Otherwise the first process
39
+ * up the tree that does not only pass a command on: inside Claude Code or Codex that is the
40
+ * agent, so its commands share one session; in a terminal it is the shell. Without a process
41
+ * table (no `ps`), the parent itself.
42
+ */
43
+ export function sessionOwner(table, start = process.ppid, agent) {
44
+ if (table && agent && agent > 1) {
45
+ for (let pid = start, hops = 0; hops < 32; hops++) {
46
+ const info = table.get(pid);
47
+ if (!info)
48
+ break;
49
+ if (pid === agent)
50
+ return { pid, command: info.command };
51
+ if (info.ppid <= 1 || info.ppid === pid)
52
+ break;
53
+ pid = info.ppid;
54
+ }
55
+ }
56
+ let pid = start;
57
+ for (let hops = 0; table && hops < 16; hops++) {
58
+ const info = table.get(pid);
59
+ if (!info)
60
+ break;
61
+ const parent = table.get(info.ppid);
62
+ if (!passesOn(info.command) || info.ppid <= 1 || !parent)
63
+ return { pid, command: info.command };
64
+ pid = info.ppid;
65
+ }
66
+ return { pid: start, command: table?.get(start)?.command ?? "" };
67
+ }
68
+ /** A short name for the owner in a message: its program (`claude`, `zsh`). */
69
+ export function ownerName(owner) {
70
+ const [first, second] = words(owner.command);
71
+ const name = program(first);
72
+ if ((name === "node" || name === "bun") && second)
73
+ return program(second).replace(/\.c?js$/, "");
74
+ return name || `pid ${owner.pid}`;
75
+ }
76
+ const NAME = /^[a-z0-9][a-z0-9_-]{0,39}$/;
77
+ /** `--session <name>`, else TURNO_BROWSER_SESSION, else "default". */
78
+ export function sessionName(flag, env) {
79
+ const name = flag ?? (env.TURNO_BROWSER_SESSION || "default");
80
+ if (!NAME.test(name))
81
+ throw new UsageError(`session name "${name}" must be 1 to 40 lowercase letters, digits, "-" or "_" (--session or TURNO_BROWSER_SESSION)`);
82
+ return name;
83
+ }
84
+ /** Where CLI sessions are saved: <state>/browser-do. */
85
+ export function sessionsDir(env) {
86
+ return join(paths(env).state, "browser-do");
87
+ }
88
+ export function sessionFile(env, identity, owner, name) {
89
+ return join(sessionsDir(env), `${identity}.${owner}.${name}.json`);
90
+ }
91
+ export function readSaved(file) {
92
+ try {
93
+ const s = JSON.parse(readFileSync(file, "utf8"));
94
+ if (s.v !== 1 || typeof s.sessionId !== "string" || typeof s.port !== "number" || !s.owner)
95
+ return undefined;
96
+ return s;
97
+ }
98
+ catch {
99
+ return undefined;
100
+ }
101
+ }
102
+ export function writeSaved(file, saved, env) {
103
+ writePrivateFile(file, `${JSON.stringify(saved, null, 2)}\n`, env);
104
+ }
105
+ export function dropSaved(file) {
106
+ rmSync(file, { force: true });
107
+ }
108
+ /** Removes the saved sessions whose owner exited (mcpd dropped those sessions already). */
109
+ export function sweepSaved(env, alive = pidAlive) {
110
+ let names;
111
+ try {
112
+ names = readdirSync(sessionsDir(env));
113
+ }
114
+ catch {
115
+ return;
116
+ }
117
+ for (const n of names) {
118
+ const m = /^[^.]+\.(\d+)\.[^.]+\.json$/.exec(n);
119
+ if (m && !alive(Number(m[1])))
120
+ dropSaved(join(sessionsDir(env), n));
121
+ }
122
+ }
123
+ /**
124
+ * Runs `fn` while holding `<file>.lock`, so two commands of one session started at once open one
125
+ * mcpd session, not two. A lock older than `staleMs` is from a command that died: taken over.
126
+ */
127
+ export async function withLock(file, env, fn) {
128
+ const lock = `${file}.lock`;
129
+ const staleMs = 30_000;
130
+ const until = Date.now() + 10_000;
131
+ ensurePrivateDir(dirname(file), env);
132
+ for (;;) {
133
+ try {
134
+ closeSync(openSync(lock, "wx", 0o600));
135
+ break;
136
+ }
137
+ catch (err) {
138
+ if (err.code !== "EEXIST")
139
+ throw err;
140
+ let age = 0;
141
+ try {
142
+ age = Date.now() - statSync(lock).mtimeMs;
143
+ }
144
+ catch {
145
+ continue;
146
+ }
147
+ if (age > staleMs || Date.now() > until) {
148
+ rmSync(lock, { force: true });
149
+ continue;
150
+ }
151
+ await new Promise((r) => setTimeout(r, 50));
152
+ }
153
+ }
154
+ try {
155
+ return await fn();
156
+ }
157
+ finally {
158
+ rmSync(lock, { force: true });
159
+ }
160
+ }
161
+ /**
162
+ * The mcp.toml server that serves identity `id`: a stdio server with `--identity <id>` in its
163
+ * args (`browser-<id>` first, as `turno browser add` prints it).
164
+ */
165
+ export function identityServer(manifest, id) {
166
+ const serves = (args) => args.some((a, i) => (a === "--identity" && args[i + 1] === id) || a === `--identity=${id}`);
167
+ const found = Object.values(manifest.servers).filter((s) => s.kind === "stdio" && serves(s.args));
168
+ return found.find((s) => s.name === `browser-${id}`) ?? found.sort((a, b) => a.name.localeCompare(b.name))[0];
169
+ }
170
+ //# sourceMappingURL=browser-do-session.js.map