turno-cli 0.2.0 → 0.3.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 (112) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.md +127 -39
  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-identity.js +514 -0
  19. package/dist/cli/commands/browser-session.js +102 -0
  20. package/dist/cli/commands/browser-vault.js +193 -0
  21. package/dist/cli/commands/browser.js +159 -59
  22. package/dist/cli/commands/complete.js +13 -3
  23. package/dist/cli/commands/completion.js +4 -0
  24. package/dist/cli/commands/config.js +90 -13
  25. package/dist/cli/commands/demo.js +36 -7
  26. package/dist/cli/commands/doctor.js +170 -36
  27. package/dist/cli/commands/identity.js +99 -12
  28. package/dist/cli/commands/init.js +42 -10
  29. package/dist/cli/commands/limit.js +65 -9
  30. package/dist/cli/commands/mcp-call.js +240 -0
  31. package/dist/cli/commands/mcp-oauth.js +33 -6
  32. package/dist/cli/commands/mcp-observe.js +128 -23
  33. package/dist/cli/commands/mcp-share.js +201 -0
  34. package/dist/cli/commands/mcp.js +203 -42
  35. package/dist/cli/commands/mcpd.js +76 -12
  36. package/dist/cli/commands/open.js +26 -3
  37. package/dist/cli/commands/profile.js +212 -30
  38. package/dist/cli/commands/resolve.js +8 -1
  39. package/dist/cli/commands/run.js +24 -4
  40. package/dist/cli/commands/secret.js +23 -38
  41. package/dist/cli/commands/session.js +16 -5
  42. package/dist/cli/commands/sessions.js +7 -1
  43. package/dist/cli/commands/setup.js +83 -11
  44. package/dist/cli/commands/status.js +67 -15
  45. package/dist/cli/commands/statusline.js +7 -2
  46. package/dist/cli/commands/ui.js +17 -5
  47. package/dist/cli/commands/undo.js +39 -7
  48. package/dist/cli/commands/uninstall.js +24 -5
  49. package/dist/cli/commands/upgrade.js +113 -76
  50. package/dist/cli/commands/usage.js +11 -10
  51. package/dist/cli/commands/version.js +20 -8
  52. package/dist/cli/commands/which.js +5 -3
  53. package/dist/cli/diagnostics.js +184 -0
  54. package/dist/cli/exit.js +65 -0
  55. package/dist/cli/group.js +20 -8
  56. package/dist/cli/help.js +6 -1
  57. package/dist/cli/hints.js +30 -0
  58. package/dist/cli/io.js +24 -8
  59. package/dist/cli/launch.js +31 -2
  60. package/dist/cli/launchers.js +25 -10
  61. package/dist/cli/main.js +52 -18
  62. package/dist/cli/optional.js +144 -0
  63. package/dist/cli/output.js +123 -0
  64. package/dist/cli/picker.js +17 -5
  65. package/dist/cli/registry.js +20 -2
  66. package/dist/cli/safe.js +87 -0
  67. package/dist/cli/secret-input.js +63 -0
  68. package/dist/cli/security.js +31 -9
  69. package/dist/cli/style.js +35 -5
  70. package/dist/cli/topics.js +142 -0
  71. package/dist/core/config.js +39 -3
  72. package/dist/core/fsutil.js +2 -10
  73. package/dist/core/journal.js +19 -11
  74. package/dist/core/manifest.js +28 -1
  75. package/dist/core/paths.js +6 -112
  76. package/dist/core/profiles.js +28 -8
  77. package/dist/core/resolve.js +13 -3
  78. package/dist/core/secrets.js +4 -154
  79. package/dist/core/state-file.js +107 -0
  80. package/dist/core/update.js +14 -11
  81. package/dist/core/version.js +57 -10
  82. package/dist/demo/server.js +10 -2
  83. package/dist/mcpd/cache.js +6 -7
  84. package/dist/mcpd/calllog.js +10 -9
  85. package/dist/mcpd/client-names.js +8 -13
  86. package/dist/mcpd/connectors.js +42 -3
  87. package/dist/mcpd/daemon.js +29 -8
  88. package/dist/mcpd/folder-sets.js +5 -2
  89. package/dist/mcpd/gateway.js +57 -29
  90. package/dist/mcpd/health.js +69 -25
  91. package/dist/mcpd/importer.js +106 -9
  92. package/dist/mcpd/instances.js +59 -31
  93. package/dist/mcpd/jsonrpc.js +3 -1
  94. package/dist/mcpd/middleware.js +144 -0
  95. package/dist/mcpd/modern.js +57 -19
  96. package/dist/mcpd/oauth.js +71 -17
  97. package/dist/mcpd/peerpid.js +15 -3
  98. package/dist/mcpd/pressure.js +4 -1
  99. package/dist/mcpd/rss.js +34 -19
  100. package/dist/mcpd/service.js +28 -4
  101. package/dist/mcpd/share.js +217 -0
  102. package/dist/mcpd/state.js +16 -16
  103. package/dist/mcpd/sync.js +22 -12
  104. package/dist/mcpd/systemd.js +4 -1
  105. package/dist/mcpd/tokens.js +4 -8
  106. package/dist/mcpd/upstream.js +12 -5
  107. package/dist/statusline/cost.js +17 -4
  108. package/dist/statusline/input.js +15 -3
  109. package/dist/ui/fonts.js +1 -1
  110. package/dist/ui/settings.js +6 -1
  111. package/npm-shrinkwrap.json +12 -3
  112. package/package.json +7 -6
package/dist/cli/group.js CHANGED
@@ -1,17 +1,25 @@
1
- import { closest, columns, fail } from "./io.js";
2
- /** Usage text of a group: one line per visible subcommand, then an optional footer. */
3
- function groupUsage(name, subs, footer) {
1
+ import { closest, columns, examplesBlock, fail } from "./io.js";
2
+ import { answerFields } from "./output.js";
3
+ /** Usage text of a group: one line per visible subcommand, then an optional footer and examples. */
4
+ function groupUsage(name, subs, footer, examples = []) {
4
5
  const rows = Object.entries(subs)
5
6
  .filter(([, s]) => !s.hidden)
6
7
  .map(([n, s]) => [`turno ${name} ${n}${s.synopsis ? ` ${s.synopsis}` : ""}`, s.summary]);
7
- return `Usage:\n${columns(rows, 2, 36)}${footer ? `\n\n${footer}` : ""}`;
8
+ return `Usage:\n${columns(rows, 2, 36)}${footer ? `\n\n${footer}` : ""}${examples.length ? `\n\n${examplesBlock(examples)}` : ""}`;
9
+ }
10
+ /** The group's examples that run `turno <name> <sub>`, for that subcommand's help. */
11
+ function subExamples(name, sub, examples) {
12
+ const head = `turno ${name} ${sub}`;
13
+ return examples.filter((e) => e === head || e.startsWith(`${head} `));
8
14
  }
9
15
  /**
10
16
  * A command made of subcommands: `turno <name> <sub> [args]`. `fallback` runs when no
11
- * subcommand is given (usually `list` or `show`). `--help` after a subcommand prints its usage.
17
+ * subcommand is given (usually `list` or `show`). `--help` after a subcommand prints its usage,
18
+ * with the group's examples for it.
12
19
  */
13
20
  export function group(name, summary, subs, opts = {}) {
14
- const usage = groupUsage(name, subs, opts.footer);
21
+ const examples = opts.examples ?? [];
22
+ const usage = groupUsage(name, subs, opts.footer, examples);
15
23
  const subcommands = Object.fromEntries(Object.entries(subs)
16
24
  .filter(([, s]) => !s.hidden)
17
25
  .map(([n, s]) => [n, { ...(s.args ? { args: s.args } : {}), ...(s.flags ? { flags: s.flags } : {}) }]));
@@ -37,12 +45,16 @@ export function group(name, summary, subs, opts = {}) {
37
45
  const s = subs[sub];
38
46
  if (!s) {
39
47
  const near = closest(sub, Object.keys(subs).filter((n) => !subs[n].hidden));
40
- return fail(near ? `unknown ${name} command '${sub}'. Did you mean 'turno ${name} ${near}'?` : `unknown ${name} command '${sub}'\n\n${usage}`);
48
+ return fail(near
49
+ ? `unknown ${name} command '${sub}'. Did you mean 'turno ${name} ${near}'?`
50
+ : `unknown ${name} command '${sub}'\n\n${usage}`);
41
51
  }
42
52
  if (!s.ownHelp && (rest.includes("--help") || rest.includes("-h"))) {
43
- io.out(groupUsage(name, { [sub]: s }, s.details));
53
+ io.out(groupUsage(name, { [sub]: s }, s.details, subExamples(name, sub, examples)));
44
54
  return 0;
45
55
  }
56
+ if (answerFields(rest, s.json, io))
57
+ return 0;
46
58
  return s.run(rest, io);
47
59
  },
48
60
  };
package/dist/cli/help.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /** The main `turno help` screen: drawn from static rows, so it loads nothing but the style. */
2
2
  import { wrap } from "./io.js";
3
+ import { HELP_TOPICS } from "./registry.js";
3
4
  import { padEnd, style } from "./style.js";
4
5
  const EXAMPLES = [
5
6
  ["turno init", "find your agents, accounts and MCP servers, and set them up"],
@@ -40,7 +41,10 @@ export function renderHelp(io, sections) {
40
41
  out.push(`${s.lead("next", "Start here:")} ${s.bold(s.accent("turno init"))}, or ${s.accent("turno demo")} to try turno in a throwaway HOME.`);
41
42
  const usage = ["turno <command> [flags]", "turno <profile> [args...]"];
42
43
  out.push("", s.header("Usage"));
43
- out.push(...rows(usage, ["a command below; turno <command> --help shows its flags", "open that profile with its agent; the arguments after it go to the agent"], Math.max(...usage.map((u) => u.length)), width, (l) => `${s.muted("turno")}${l.slice("turno".length)}`, (r) => r));
44
+ out.push(...rows(usage, [
45
+ "a command below; turno <command> --help shows its flags",
46
+ "open that profile with its agent; the arguments after it go to the agent",
47
+ ], Math.max(...usage.map((u) => u.length)), width, (l) => `${s.muted("turno")}${l.slice("turno".length)}`, (r) => r));
44
48
  const w = Math.max(...sections.flatMap((x) => x.rows.map(([n]) => n.length)));
45
49
  for (const sec of sections) {
46
50
  out.push("", s.header(sec.title));
@@ -50,6 +54,7 @@ export function renderHelp(io, sections) {
50
54
  out.push("", s.header("Examples"));
51
55
  out.push(...rows(EXAMPLES.map(([c]) => `$ ${c}`), EXAMPLES.map(([, why]) => why), ew, width, (l) => `${s.muted("$")}${l.slice(1)}`, (r) => s.muted(r)));
52
56
  out.push("", `Run ${s.bold("turno <command> --help")}, or ${s.bold("turno help <command>")}, for details.`);
57
+ out.push(`Topics: ${HELP_TOPICS.map((t) => s.bold(`turno help ${t}`)).join(", ")}.`);
53
58
  out.push(s.muted("Scripts and agents: --no-input or TURNO_NO_INPUT=1 never asks (exit 2 instead)."));
54
59
  out.push(s.muted("Colors: --color auto|always|never or TURNO_COLOR, then NO_COLOR and FORCE_COLOR."));
55
60
  return out;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The next step after a command that writes: one `Next: ...` line, so a person knows what to run
3
+ * after `profile add`, `mcp import --write` and the like. `hints = false` in config.toml turns
4
+ * them off; they are never printed under --json, where stdout is data.
5
+ */
6
+ import { loadConfig } from "../core/config.js";
7
+ /** Whether hints are on: config.toml's `hints`, true when the file is missing or does not parse. */
8
+ function hintsOn(env) {
9
+ try {
10
+ return loadConfig(env).hints;
11
+ }
12
+ catch {
13
+ return true;
14
+ }
15
+ }
16
+ /**
17
+ * Print `Next: <steps joined by "; ">`. `stream: "err"` keeps stdout clean for commands whose
18
+ * stdout is a file (`turno mcp export > file.toml`).
19
+ */
20
+ export function nextStep(io, steps, opts = {}) {
21
+ const list = (typeof steps === "string" ? [steps] : steps).filter(Boolean);
22
+ if (!list.length || opts.json || !hintsOn(io.env))
23
+ return;
24
+ const line = `Next: ${list.join("; ")}`;
25
+ if (opts.stream === "err")
26
+ io.err(line);
27
+ else
28
+ io.out(line);
29
+ }
30
+ //# sourceMappingURL=hints.js.map
package/dist/cli/io.js CHANGED
@@ -1,14 +1,16 @@
1
1
  /** Small helpers shared by command modules. Keep this file free of heavy imports. */
2
+ import { Exit } from "./exit.js";
3
+ /** A wrong command line: main prints `turno: <message>` and exits 2 (Exit.usage). */
2
4
  export class UsageError extends Error {
3
5
  constructor(message) {
4
6
  super(message);
5
7
  this.name = "UsageError";
6
8
  }
7
9
  }
8
- /** A plain error with its exit code: main prints `turno: <message>` and returns `code`. */
10
+ /** A plain error with its exit code (see exit.ts): main prints `turno: <message>` and returns `code`. */
9
11
  export class CliError extends Error {
10
12
  code;
11
- constructor(message, code = 1) {
13
+ constructor(message, code = Exit.failure) {
12
14
  super(message);
13
15
  this.code = code;
14
16
  this.name = "CliError";
@@ -35,7 +37,7 @@ export function defaultIo() {
35
37
  }
36
38
  /**
37
39
  * The variables each coding agent sets for the commands it runs, by agent id: inside them nobody
38
- * reads a question, so turno never asks one. Sources are in ADR 0033. Kept here rather than in
40
+ * reads a question, so turno never asks one. Kept here rather than in
39
41
  * the adapters because every run loads io.ts and it stays free of heavy imports; a test keeps the
40
42
  * ids in step with src/agents.
41
43
  */
@@ -84,16 +86,18 @@ export function isColorMode(v) {
84
86
  return v !== undefined && COLOR_MODES.includes(v);
85
87
  }
86
88
  /**
87
- * Whether output gets ANSI colors. The first rule that applies wins (ADR 0037):
89
+ * Whether output gets ANSI colors. The first rule that applies wins:
88
90
  *
89
91
  * 1. `--color always|never` on the command line;
90
92
  * 2. TURNO_COLOR=always|never (any other value counts as auto; --color auto sets it aside);
91
93
  * 3. NO_COLOR set and not empty: off (https://no-color.org, which lets a flag or a tool's own
92
94
  * setting override it);
93
95
  * 4. FORCE_COLOR: 0 or false turns colors off, anything else turns them on, also in a pipe;
94
- * 5. auto: on when output is a terminal.
96
+ * 5. CLICOLOR_FORCE set and not 0: on, also in a pipe (https://bixense.com/clicolors);
97
+ * 6. CLICOLOR=0, or TERM=dumb: off;
98
+ * 7. auto: on when output is a terminal.
95
99
  *
96
- * `--json` output is never colored outside a terminal, whatever this says (printJson).
100
+ * `--json` output is never colored outside a terminal, whatever this says (output.ts).
97
101
  */
98
102
  export function colors(io) {
99
103
  // An explicit --color auto also sets TURNO_COLOR aside.
@@ -102,11 +106,16 @@ export function colors(io) {
102
106
  return true;
103
107
  if (own === "never")
104
108
  return false;
105
- if (io.env.NO_COLOR)
109
+ const env = io.env;
110
+ if (env.NO_COLOR)
106
111
  return false;
107
- const force = io.env.FORCE_COLOR;
112
+ const force = env.FORCE_COLOR;
108
113
  if (force !== undefined && force !== "")
109
114
  return force !== "0" && force !== "false";
115
+ if (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")
116
+ return true;
117
+ if (env.CLICOLOR === "0" || env.TERM === "dumb")
118
+ return false;
110
119
  return io.isTty;
111
120
  }
112
121
  export function paint(io, text, code) {
@@ -164,6 +173,13 @@ export function columns(rows, indent = 2, maxLeft = 32, left) {
164
173
  }
165
174
  return out.join("\n");
166
175
  }
176
+ /**
177
+ * The `Examples:` block that ends a command's help: one `$ command` per line, with an optional
178
+ * ` # why` after it.
179
+ */
180
+ export function examplesBlock(examples) {
181
+ return ["Examples:", ...examples.map((e) => ` $ ${e}`)].join("\n");
182
+ }
167
183
  /** Edit distance with adjacent transpositions (so "stauts" is 1 away from "status"). */
168
184
  export function distance(a, b) {
169
185
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
@@ -14,6 +14,14 @@ export function launcherPath(name, env = process.env, agent = profileAgent(name,
14
14
  const file = join(paths(env).bin, launcherName(name, agent));
15
15
  return executable(file) ? file : undefined;
16
16
  }
17
+ /** `--no-gateway` before any `--`, or TURNO_SAFE on: safe mode (cli/safe.ts holds the rest). */
18
+ export function wantsSafe(args, env) {
19
+ const end = args.indexOf("--");
20
+ if ((end < 0 ? args : args.slice(0, end)).includes("--no-gateway"))
21
+ return true;
22
+ const v = env.TURNO_SAFE;
23
+ return v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
24
+ }
17
25
  /** Terminal signals already reach the child (same process group); these are passed on. */
18
26
  const FORWARDED = ["SIGTERM", "SIGHUP"];
19
27
  const IGNORED = ["SIGINT", "SIGQUIT"];
@@ -57,8 +65,29 @@ export async function execLauncher(file, args, env = process.env) {
57
65
  });
58
66
  });
59
67
  }
60
- /** `turno <profile> [args]`: exec the profile's launcher. */
61
- export async function launchProfile(name, args, io) {
68
+ /**
69
+ * `turno <profile> [args]`: exec the profile's launcher. `--no-gateway` among turno's arguments,
70
+ * or TURNO_SAFE=1, opens it in safe mode instead (cli/safe.ts).
71
+ */
72
+ export async function launchProfile(name, given, io) {
73
+ let args = given;
74
+ // Checked here without loading safe.ts, so a normal launch pays nothing for it.
75
+ if (wantsSafe(given, io.env)) {
76
+ const { launchSafe, takeSafeFlag } = await import("./safe.js");
77
+ args = takeSafeFlag(given).args;
78
+ if (!isValidProfileName(name))
79
+ throw new UsageError(`unknown command '${name}' (turno --help)`);
80
+ let config;
81
+ try {
82
+ config = loadConfig(io.env);
83
+ }
84
+ catch (err) {
85
+ throw new CliError(err.message);
86
+ }
87
+ if (!listProfiles(config, io.env).includes(name))
88
+ throw new UsageError(`no profile '${name}' (turno profile list shows them; turno profile add ${name} creates it)`);
89
+ return launchSafe(profileAgent(name, io.env), name, args, io);
90
+ }
62
91
  const file = launcherPath(name, io.env);
63
92
  if (!file) {
64
93
  if (!isValidProfileName(name))
@@ -1,10 +1,11 @@
1
- import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
1
+ import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync, } from "node:fs";
2
2
  import { delimiter, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { DEFAULT_AGENT, adapter, agentHub, agentProfileDir } from "../agents/index.js";
5
5
  import { loadConfig } from "../core/config.js";
6
6
  import { paths, tildify } from "../core/paths.js";
7
7
  import { agentOf } from "../core/profiles.js";
8
+ import { oneOffRunner } from "../core/version.js";
8
9
  import { profileTokenFile } from "../mcpd/tokens.js";
9
10
  import { CliError, UsageError } from "./io.js";
10
11
  /** Every launcher turno writes carries this line; only marked files are ever overwritten. */
@@ -41,8 +42,8 @@ export function findOnPath(cmd, env = process.env) {
41
42
  }
42
43
  return undefined;
43
44
  }
44
- export const NPX_MESSAGE = "turno is running from npx's cache. Install it first: npm install --global turno-cli";
45
- /** True when this turno runs from npm's npx cache, which npm may delete at any time. */
45
+ export const NPX_MESSAGE = "turno is running from a temporary copy (npx, pnpm dlx or bunx). Install it first, for example: npm install --global turno-cli";
46
+ /** True when this turno runs from the cache of a one-off runner (npx, pnpm dlx, bunx), which may delete it at any time. */
46
47
  export function runningFromNpx(argv1 = process.argv[1]) {
47
48
  if (!argv1)
48
49
  return false;
@@ -53,7 +54,7 @@ export function runningFromNpx(argv1 = process.argv[1]) {
53
54
  catch {
54
55
  /* keep the given path */
55
56
  }
56
- return file.includes("/_npx/");
57
+ return oneOffRunner(file) !== undefined;
57
58
  }
58
59
  /** Refuse a write that would keep a path into npx's cache (launchers, status line). */
59
60
  export function refuseNpx(argv1 = process.argv[1]) {
@@ -81,12 +82,16 @@ function requireAgent(agent) {
81
82
  * `xdg-open` (Linux). Elsewhere the agent keeps its own browser handling.
82
83
  */
83
84
  function browserLines(env, platform, comment) {
84
- const works = platform === "darwin" || (platform === "linux" && Boolean(findOnPath("xdg-open", env)));
85
- if (!works)
85
+ if (!launcherBrowser(env, platform))
86
86
  return [];
87
87
  const line = `export BROWSER=${shPath(join(paths(env).bin, "turno-open"), env)}`;
88
88
  return comment ? ["# claude.ai links (artifacts, login) open with this account: turno open.", line] : [line];
89
89
  }
90
+ /** The BROWSER a launcher exports on this platform (turno-open), or undefined where it cannot work. */
91
+ export function launcherBrowser(env, platform = process.platform) {
92
+ const works = platform === "darwin" || (platform === "linux" && Boolean(findOnPath("xdg-open", env)));
93
+ return works ? join(paths(env).bin, "turno-open") : undefined;
94
+ }
90
95
  /** Double-quoted POSIX shell word; a path under HOME is written as "$HOME/...". */
91
96
  export function shPath(p, env = process.env) {
92
97
  const home = paths(env).home;
@@ -112,8 +117,8 @@ export function launcherName(name, agent = DEFAULT_AGENT) {
112
117
  /** A shell word for an environment value: as it is when nothing in it needs quoting. */
113
118
  const shWord = (v) => (/^[A-Za-z0-9_.,:/@%+=-]+$/.test(v) ? v : `"${esc(v)}"`);
114
119
  /**
115
- * Text of a profile's launcher (claude-<name>, codex-<name>, ...), from the agent's adapter
116
- * (ADR 0032). Classic launchers (Claude Code) keep the format they had before other agents.
120
+ * Text of a profile's launcher (claude-<name>, codex-<name>, ...), from the agent's adapter.
121
+ * Classic launchers (Claude Code) keep the format they had before other agents.
117
122
  */
118
123
  export function launcherText(name, env = process.env, agent = DEFAULT_AGENT, platform = process.platform) {
119
124
  const a = adapter(agent);
@@ -140,7 +145,12 @@ export function launcherText(name, env = process.env, agent = DEFAULT_AGENT, pla
140
145
  "export TURNO_MCPD_TOKEN",
141
146
  ]
142
147
  : []),
143
- ...(hubDirs.length ? ["# If a cleanup removed an empty hub folder, the profile symlink would dangle.", `mkdir -p ${hubDirs.join(" ")}`] : []),
148
+ ...(hubDirs.length
149
+ ? [
150
+ "# If a cleanup removed an empty hub folder, the profile symlink would dangle.",
151
+ `mkdir -p ${hubDirs.join(" ")}`,
152
+ ]
153
+ : []),
144
154
  ...browserLines(env, platform, a.classicLauncher),
145
155
  "# exec keeps the PID, so turno sessions knows which account each session uses.",
146
156
  `mkdir -p ${run} && echo ${name} >${runFile} 2>/dev/null`,
@@ -199,7 +209,12 @@ export function resolveTurnoCommand(env = process.env, argv1 = process.argv[1])
199
209
  const onPath = findOnPath("turno", env);
200
210
  if (onPath && !onPath.includes("/_npx/") && !legacyScript(onPath)) {
201
211
  const shown = tildify(onPath, env);
202
- return { words: quote(onPath), ...(VERSIONED.test(onPath) ? { warning: `wrote an absolute path (${shown}); it breaks if you switch Node versions` } : {}) };
212
+ return {
213
+ words: quote(onPath),
214
+ ...(VERSIONED.test(onPath)
215
+ ? { warning: `wrote an absolute path (${shown}); it breaks if you switch Node versions` }
216
+ : {}),
217
+ };
203
218
  }
204
219
  const main = fileURLToPath(new URL("./main.js", import.meta.url));
205
220
  if (!argv1 || !sameFile(argv1, main))
package/dist/cli/main.js CHANGED
@@ -2,8 +2,9 @@
2
2
  import { realpathSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { enableCompileCache } from "./compile-cache.js";
5
- import { CliError, UsageError, closest, defaultIo, fail, isColorMode, noInputReason, paint, withoutAsk } from "./io.js";
6
- import { COMMANDS, HELP_SUMMARY, QUIET, SECTIONS, expand, visibleCommands } from "./registry.js";
5
+ import { Exit, exitName } from "./exit.js";
6
+ import { CliError, UsageError, closest, defaultIo, fail, isColorMode, noInputReason, paint, withoutAsk, } from "./io.js";
7
+ import { COMMANDS, HELP_SUMMARY, HELP_TOPICS, QUIET, SECTIONS, expand, visibleCommands } from "./registry.js";
7
8
  async function help(io) {
8
9
  const sections = await Promise.all(SECTIONS.map(async (s) => ({
9
10
  title: s.title,
@@ -15,7 +16,7 @@ async function help(io) {
15
16
  return 0;
16
17
  }
17
18
  /** Error classes whose message is the whole story: printed without a stack trace. */
18
- const ONE_LINE_ERRORS = new Set(["ConfigError", "SecretError"]);
19
+ const ONE_LINE_ERRORS = new Set(["ConfigError", "SecretError", "StateError"]);
19
20
  /** Commands whose arguments belong to the agent they start: only a first --help is theirs. */
20
21
  const PASSTHROUGH = new Set(["run", "auto", "hook", "statusline", "__complete"]);
21
22
  function asksHelp(name, rest) {
@@ -28,8 +29,14 @@ function unknownCommand(word) {
28
29
  const near = closest(word, visibleCommands());
29
30
  return fail(near ? `unknown command '${word}'. Did you mean 'turno ${near}'?` : `unknown command '${word}' (turno --help)`);
30
31
  }
31
- /** `turno help <command> [sub]`: the same text as `turno <command> [sub] --help`. */
32
+ /** `turno help <command> [sub]`: the same text as `turno <command> [sub] --help`; or a topic. */
32
33
  async function helpFor(words, io) {
34
+ if (HELP_TOPICS.includes(words[0])) {
35
+ const { TOPICS } = await import("./topics.js");
36
+ for (const line of TOPICS[words[0]].text())
37
+ io.out(line);
38
+ return 0;
39
+ }
33
40
  const [name, rest] = expand(words[0], words.slice(1));
34
41
  const load = COMMANDS[name];
35
42
  if (!load)
@@ -84,7 +91,9 @@ export function takeNoInput(argv) {
84
91
  function colorValue(v) {
85
92
  if (isColorMode(v))
86
93
  return v;
87
- return fail(v === undefined || v.startsWith("-") ? "--color needs a value: auto, always or never" : `--color ${v}: use auto, always or never`);
94
+ return fail(v === undefined || v.startsWith("-")
95
+ ? "--color needs a value: auto, always or never"
96
+ : `--color ${v}: use auto, always or never`);
88
97
  }
89
98
  /**
90
99
  * Take the global `--color auto|always|never` (or `--color=<mode>`) out of argv, like --no-input:
@@ -129,6 +138,35 @@ export function takeColor(argv) {
129
138
  }
130
139
  return at({ argv: [...lead, head, ...kept, ...(end < 0 ? [] : tail.slice(end))] });
131
140
  }
141
+ /** Whether this run asked for --json: then an error is a JSON line on stderr. */
142
+ function wantsJson(argv) {
143
+ const [head, ...tail] = argv;
144
+ if (!head || head.startsWith("-") || head === "help")
145
+ return false;
146
+ const [name, rest] = expand(head, tail);
147
+ if (!COMMANDS[name] || PASSTHROUGH.has(name))
148
+ return false;
149
+ const end = rest.indexOf("--");
150
+ return (end < 0 ? rest : rest.slice(0, end)).some((a) => a === "--json" || a.startsWith("--json="));
151
+ }
152
+ /** Print an error the way the run asked (a `turno:` line, or JSON under --json) and return its exit code. */
153
+ async function report(err, io, json) {
154
+ const e = err;
155
+ const code = err instanceof UsageError ? Exit.usage : err instanceof CliError ? err.code : Exit.failure;
156
+ // Errors that explain themselves in one line; anything else is a bug and keeps its stack.
157
+ const known = err instanceof UsageError || err instanceof CliError || ONE_LINE_ERRORS.has(e?.name);
158
+ if (json) {
159
+ const { jsonError } = await import("./output.js");
160
+ const fields = err.fields;
161
+ io.err(jsonError(e?.message ?? String(err), code, exitName(code), {
162
+ ...(Array.isArray(fields) ? { fields } : {}),
163
+ ...(known ? {} : { stack: e?.stack }),
164
+ }));
165
+ }
166
+ else
167
+ io.err(`turno: ${known ? e.message : (e?.stack ?? e?.message ?? String(err))}`);
168
+ return code;
169
+ }
132
170
  export async function main(args, io = defaultIo()) {
133
171
  let picked;
134
172
  try {
@@ -136,7 +174,7 @@ export async function main(args, io = defaultIo()) {
136
174
  }
137
175
  catch (err) {
138
176
  io.err(`turno: ${err.message}`);
139
- return 2;
177
+ return Exit.usage;
140
178
  }
141
179
  if (picked.color)
142
180
  io = { ...io, color: picked.color };
@@ -147,7 +185,9 @@ export async function main(args, io = defaultIo()) {
147
185
  else if (io.ask && noInputReason(io.env))
148
186
  io = withoutAsk(io);
149
187
  const [head, ...tail] = argv;
188
+ let json = false;
150
189
  try {
190
+ json = wantsJson(argv);
151
191
  if (!head) {
152
192
  // Once turno is set up, bare `turno` is the status screen; before that, the help.
153
193
  const { homeScreen } = await import("./commands/status.js");
@@ -177,6 +217,11 @@ export async function main(args, io = defaultIo()) {
177
217
  io.out(command.usage);
178
218
  return 0;
179
219
  }
220
+ if (command.json && !PASSTHROUGH.has(first)) {
221
+ const { answerFields } = await import("./output.js");
222
+ if (answerFields(rest, command.json, io))
223
+ return 0;
224
+ }
180
225
  const code = await command.run(rest, io);
181
226
  await notice(first, io);
182
227
  return code;
@@ -188,18 +233,7 @@ export async function main(args, io = defaultIo()) {
188
233
  return await launchProfile(first, rest, io);
189
234
  }
190
235
  catch (err) {
191
- if (err instanceof UsageError) {
192
- io.err(`turno: ${err.message}`);
193
- return 2;
194
- }
195
- if (err instanceof CliError) {
196
- io.err(`turno: ${err.message}`);
197
- return err.code;
198
- }
199
- const e = err;
200
- // Errors that explain themselves in one line; anything else is a bug and keeps its stack.
201
- io.err(`turno: ${ONE_LINE_ERRORS.has(e.name) ? e.message : (e.stack ?? e.message)}`);
202
- return 1;
236
+ return report(err, io, json);
203
237
  }
204
238
  }
205
239
  function isEntry() {
@@ -0,0 +1,144 @@
1
+ /**
2
+ * Optional packages: installed apart from turno-cli and loaded only by the commands that need
3
+ * them. turno-browser today; a turno-tui later goes in OPTIONAL the same way.
4
+ */
5
+ import { execFileSync } from "node:child_process";
6
+ import { existsSync, readdirSync, realpathSync } from "node:fs";
7
+ import { createRequire } from "node:module";
8
+ import { join, sep } from "node:path";
9
+ import { fileURLToPath, pathToFileURL } from "node:url";
10
+ import { CliError } from "./io.js";
11
+ export const OPTIONAL = {
12
+ browser: { name: "turno-browser", install: "npm install --global turno-browser" },
13
+ tui: { name: "turno-tui", install: "npm install --global turno-tui" },
14
+ };
15
+ function isApiVersion(v) {
16
+ const o = v;
17
+ return (typeof o === "object" && o !== null && [o.major, o.minor].every((n) => Number.isInteger(n) && n >= 0));
18
+ }
19
+ /**
20
+ * Why an installed package's `API_VERSION` does not fit the one this turno was built against,
21
+ * or undefined when it does: the same major and at least the minor. One line that names the
22
+ * command to run: update the package when it is older, update turno when it is newer.
23
+ */
24
+ export function apiMismatch(pkg, found, wanted) {
25
+ const needs = `this turno needs ${wanted.major}.${wanted.minor} or a later ${wanted.major}.x`;
26
+ const update = `update it: ${pkg.install}@latest`;
27
+ if (!isApiVersion(found))
28
+ return `${pkg.name} is too old for this turno (it has no API_VERSION, ${needs}); ${update}`;
29
+ if (found.major > wanted.major)
30
+ return `${pkg.name} is too new for this turno (its API is ${found.major}.${found.minor}, this turno speaks ${wanted.major}.x); update turno: turno upgrade`;
31
+ if (found.major < wanted.major || found.minor < wanted.minor)
32
+ return `${pkg.name} is too old for this turno (its API is ${found.major}.${found.minor}, ${needs}); ${update}`;
33
+ return undefined;
34
+ }
35
+ /** "turno-browser is not installed: npm install --global turno-browser". */
36
+ export function notInstalled(pkg) {
37
+ return `${pkg.name} is not installed: ${pkg.install}`;
38
+ }
39
+ /** Whether an import failed because the package (or its entry) is not there. */
40
+ export function isMissingModule(err) {
41
+ const code = err?.code;
42
+ return code === "ERR_MODULE_NOT_FOUND" || code === "MODULE_NOT_FOUND" || code === "ERR_PACKAGE_PATH_NOT_EXPORTED";
43
+ }
44
+ /** The global npm folder, where `npm install --global <pkg>` puts packages. */
45
+ function npmGlobalRoot(env) {
46
+ try {
47
+ return (execFileSync("npm", ["root", "--global"], {
48
+ env,
49
+ encoding: "utf8",
50
+ stdio: ["ignore", "pipe", "ignore"],
51
+ timeout: 5000,
52
+ }).trim() || undefined);
53
+ }
54
+ catch {
55
+ return undefined;
56
+ }
57
+ }
58
+ /**
59
+ * The node_modules folders of every pnpm global group, when `self` (this turno's package
60
+ * folder) is in one. pnpm 11 and later install each global package in its own group
61
+ * (`$PNPM_HOME/global/v11/<group>/node_modules`), so a package added with its own
62
+ * `pnpm add --global` is not next to turno, and npm's global folder does not have it either.
63
+ */
64
+ export function pnpmGlobalRoots(self) {
65
+ let real = self;
66
+ try {
67
+ real = realpathSync(self);
68
+ }
69
+ catch {
70
+ /* keep it */
71
+ }
72
+ const parts = real.split(sep);
73
+ const at = parts.findIndex((p, i) => p === "global" && /^v\d+$/.test(parts[i + 1] ?? "") && parts[i + 3] === "node_modules");
74
+ if (at < 0)
75
+ return [];
76
+ const groups = parts.slice(0, at + 2).join(sep);
77
+ let names;
78
+ try {
79
+ names = readdirSync(groups).sort();
80
+ }
81
+ catch {
82
+ return [];
83
+ }
84
+ return names.map((g) => join(groups, g, "node_modules")).filter((d) => existsSync(d));
85
+ }
86
+ /**
87
+ * Load an optional package: next to this install first, then (with `global`) from the global
88
+ * npm folder. Undefined when it is not installed; any other import error is thrown, as is a
89
+ * module whose API_VERSION does not fit or that the guard rejects (a CliError naming the
90
+ * update command).
91
+ */
92
+ export async function loadOptional(pkg, options = {}) {
93
+ const load = options.importer ?? ((s) => import(s));
94
+ const checked = (mod) => {
95
+ if (options.api) {
96
+ const problem = apiMismatch(pkg, mod?.API_VERSION, options.api);
97
+ if (problem)
98
+ throw new CliError(problem);
99
+ }
100
+ if (options.guard && !options.guard(mod))
101
+ throw new CliError(`this ${pkg.name} is too old or not a ${pkg.name} for this turno; update it: ${pkg.install}@latest`);
102
+ return mod;
103
+ };
104
+ try {
105
+ return checked(await load(pkg.name));
106
+ }
107
+ catch (err) {
108
+ if (!isMissingModule(err))
109
+ throw err;
110
+ }
111
+ if (!options.global)
112
+ return undefined;
113
+ const self = options.self ?? fileURLToPath(new URL("../../", import.meta.url));
114
+ for (const root of pnpmGlobalRoots(self)) {
115
+ const found = await loadFrom(root, pkg, load, checked);
116
+ if (found !== undefined)
117
+ return found;
118
+ }
119
+ const root = (options.globalRoot ?? npmGlobalRoot)(options.env ?? process.env);
120
+ if (!root)
121
+ return undefined;
122
+ return await loadFrom(root, pkg, load, checked);
123
+ }
124
+ /** The package as installed in the node_modules folder `root`, undefined when it is not there. */
125
+ async function loadFrom(root, pkg, load, checked) {
126
+ let entry;
127
+ try {
128
+ entry = createRequire(join(root, "noop.js")).resolve(pkg.name);
129
+ }
130
+ catch (err) {
131
+ if (isMissingModule(err))
132
+ return undefined;
133
+ throw err;
134
+ }
135
+ try {
136
+ return checked(await load(pathToFileURL(entry).href));
137
+ }
138
+ catch (err) {
139
+ if (isMissingModule(err))
140
+ return undefined;
141
+ throw err;
142
+ }
143
+ }
144
+ //# sourceMappingURL=optional.js.map