turno-cli 0.1.0 → 0.2.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 (105) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +143 -75
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/core/version.js +6 -0
  74. package/dist/demo/server.js +34 -0
  75. package/dist/mcpd/cache.js +18 -4
  76. package/dist/mcpd/calllog.js +253 -0
  77. package/dist/mcpd/client-names.js +51 -0
  78. package/dist/mcpd/connectors.js +148 -17
  79. package/dist/mcpd/daemon.js +452 -116
  80. package/dist/mcpd/folder-sets.js +39 -0
  81. package/dist/mcpd/gateway.js +441 -47
  82. package/dist/mcpd/health.js +269 -0
  83. package/dist/mcpd/importer.js +356 -36
  84. package/dist/mcpd/instances.js +425 -65
  85. package/dist/mcpd/jsonrpc.js +8 -0
  86. package/dist/mcpd/launchd.js +65 -48
  87. package/dist/mcpd/modern.js +648 -0
  88. package/dist/mcpd/oauth.js +791 -0
  89. package/dist/mcpd/peerpid.js +122 -6
  90. package/dist/mcpd/pressure.js +85 -0
  91. package/dist/mcpd/rss.js +151 -0
  92. package/dist/mcpd/service.js +167 -0
  93. package/dist/mcpd/state.js +183 -0
  94. package/dist/mcpd/sync.js +55 -80
  95. package/dist/mcpd/systemd.js +80 -0
  96. package/dist/mcpd/tokens.js +89 -0
  97. package/dist/mcpd/upstream.js +154 -44
  98. package/dist/statusline/cost.js +154 -44
  99. package/dist/statusline/input.js +66 -0
  100. package/dist/statusline/render.js +9 -3
  101. package/dist/ui/fonts.js +8 -3
  102. package/dist/ui/settings.js +27 -15
  103. package/npm-shrinkwrap.json +1093 -0
  104. package/package.json +9 -9
  105. package/dist/cli/commands/available.js +0 -18
@@ -1,49 +1,65 @@
1
- import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
- import { join } from "node:path";
1
+ import { accessSync, chmodSync, constants, existsSync, mkdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs";
2
+ import { delimiter, join } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import { adapter, agentHub, agentProfileDir } from "../agents/index.js";
4
+ import { DEFAULT_AGENT, adapter, agentHub, agentProfileDir } from "../agents/index.js";
5
5
  import { loadConfig } from "../core/config.js";
6
- import { paths } from "../core/paths.js";
6
+ import { paths, tildify } from "../core/paths.js";
7
7
  import { agentOf } from "../core/profiles.js";
8
- import { UsageError } from "./io.js";
8
+ import { profileTokenFile } from "../mcpd/tokens.js";
9
+ import { CliError, UsageError } from "./io.js";
9
10
  /** Every launcher turno writes carries this line; only marked files are ever overwritten. */
10
11
  export const MARKER = "Generated by turno";
11
12
  /** Markers of the bash claudio, of its predecessor, and of turno while it was called claudio. */
12
- export const LEGACY_MARKERS = ["Generado por claudio", "Generado por claude-profile", "Generated by claudio"];
13
- /** Helper launchers of the bash claudio, kept working (Orca runs claudio-auto) by pointing them at turno. */
13
+ const LEGACY_MARKERS = ["Generado por claudio", "Generado por claude-profile", "Generated by claudio"];
14
+ /** Helper launchers of the bash tool, kept working (editors may run claudio-auto) by pointing them at turno. */
14
15
  const LEGACY_HELPERS = [
15
16
  ["claudio-auto", "auto"],
16
17
  ["claudio-open", "open"],
17
18
  ["claudio-navegador", "open"],
18
19
  ];
19
- /**
20
- * Hub folders shared by every profile. Launchers recreate them, so a cleanup that removed
21
- * an empty hub folder never leaves a profile with a dangling symlink.
22
- */
23
- export const SHARED_DIRS = [
24
- "projects",
25
- "file-history",
26
- "plans",
27
- "tasks",
28
- "paste-cache",
29
- "session-env",
30
- "uploads",
31
- "dev-mods",
32
- "sessions",
33
- "skills",
34
- "commands",
35
- "agents",
36
- "hooks",
37
- "plugins",
38
- "output-styles",
39
- "workflows",
40
- "agent-memory",
41
- "rules",
42
- "themes",
43
- "state",
44
- "usage-data",
45
- "cache",
46
- ];
20
+ export function executable(file) {
21
+ try {
22
+ if (!statSync(file).isFile())
23
+ return false;
24
+ accessSync(file, constants.X_OK);
25
+ return true;
26
+ }
27
+ catch {
28
+ return false;
29
+ }
30
+ }
31
+ /** Absolute path of a command found on PATH (or the command itself when it has a slash). */
32
+ export function findOnPath(cmd, env = process.env) {
33
+ if (cmd.includes("/"))
34
+ return executable(cmd) ? cmd : undefined;
35
+ for (const dir of (env.PATH ?? "").split(delimiter)) {
36
+ if (!dir)
37
+ continue;
38
+ const file = join(dir, cmd);
39
+ if (executable(file))
40
+ return file;
41
+ }
42
+ return undefined;
43
+ }
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. */
46
+ export function runningFromNpx(argv1 = process.argv[1]) {
47
+ if (!argv1)
48
+ return false;
49
+ let file = argv1;
50
+ try {
51
+ file = realpathSync(argv1);
52
+ }
53
+ catch {
54
+ /* keep the given path */
55
+ }
56
+ return file.includes("/_npx/");
57
+ }
58
+ /** Refuse a write that would keep a path into npx's cache (launchers, status line). */
59
+ export function refuseNpx(argv1 = process.argv[1]) {
60
+ if (runningFromNpx(argv1))
61
+ throw new CliError(NPX_MESSAGE);
62
+ }
47
63
  export function isGenerated(file) {
48
64
  try {
49
65
  const text = readFileSync(file, "utf8");
@@ -53,92 +69,106 @@ export function isGenerated(file) {
53
69
  return false;
54
70
  }
55
71
  }
72
+ /** Escape text for a double-quoted shell word. */
73
+ const esc = (s) => s.replace(/(["\\$`])/g, "\\$1");
74
+ /** A launcher line that stops with a clear message when the agent is not installed. */
75
+ function requireAgent(agent) {
76
+ const a = adapter(agent);
77
+ return `command -v ${a.command} >/dev/null 2>&1 || { echo "turno: ${esc(a.command)} is not installed (${esc(a.install)})" >&2; exit 127; }`;
78
+ }
79
+ /**
80
+ * The BROWSER export: claude.ai links open through turno-open, which needs `open` (macOS) or
81
+ * `xdg-open` (Linux). Elsewhere the agent keeps its own browser handling.
82
+ */
83
+ function browserLines(env, platform, comment) {
84
+ const works = platform === "darwin" || (platform === "linux" && Boolean(findOnPath("xdg-open", env)));
85
+ if (!works)
86
+ return [];
87
+ const line = `export BROWSER=${shPath(join(paths(env).bin, "turno-open"), env)}`;
88
+ return comment ? ["# claude.ai links (artifacts, login) open with this account: turno open.", line] : [line];
89
+ }
56
90
  /** Double-quoted POSIX shell word; a path under HOME is written as "$HOME/...". */
57
91
  export function shPath(p, env = process.env) {
58
92
  const home = paths(env).home;
59
- const esc = (s) => s.replace(/(["\\$`])/g, "\\$1");
60
93
  if (p === home)
61
94
  return '"$HOME"';
62
- if (p.startsWith(home + "/"))
95
+ if (p.startsWith(`${home}/`))
63
96
  return `"$HOME/${esc(p.slice(home.length + 1))}"`;
64
97
  return `"${esc(p)}"`;
65
98
  }
66
- /** The agent of a profile according to config.toml (Claude Code when the config is missing or broken). */
99
+ /** The agent of a profile according to config.toml (the default agent when the config is missing or broken). */
67
100
  export function profileAgent(name, env = process.env) {
68
101
  try {
69
102
  return agentOf(name, loadConfig(env));
70
103
  }
71
104
  catch {
72
- return "claude";
105
+ return DEFAULT_AGENT;
73
106
  }
74
107
  }
75
108
  /** File name of a profile's launcher in ~/.local/bin: claude-<name>, codex-<name>, ... */
76
- export function launcherName(name, agent = "claude") {
109
+ export function launcherName(name, agent = DEFAULT_AGENT) {
77
110
  return `${adapter(agent).launcherPrefix}${name}`;
78
111
  }
79
- /** Text of the launcher of an agent other than Claude Code. */
80
- function agentLauncherText(name, agent, env) {
112
+ /** A shell word for an environment value: as it is when nothing in it needs quoting. */
113
+ const shWord = (v) => (/^[A-Za-z0-9_.,:/@%+=-]+$/.test(v) ? v : `"${esc(v)}"`);
114
+ /**
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.
117
+ */
118
+ export function launcherText(name, env = process.env, agent = DEFAULT_AGENT, platform = process.platform) {
81
119
  const a = adapter(agent);
82
120
  const p = paths(env);
83
- const dir = shPath(agentProfileDir(name, agent, env), env);
84
- const hubDirs = a.sharedDirs.map((d) => shPath(join(agentHub(agent, env), d), env));
121
+ const hub = agentHub(agent, env);
122
+ const hubDirs = a.sharedDirs.map((d) => shPath(join(hub, d), env));
85
123
  const run = shPath(p.runDir, env);
86
- const runFile = run.slice(0, -1) + '/$$"';
124
+ const runFile = `${run.slice(0, -1)}/$$"`;
87
125
  return [
88
126
  "#!/bin/sh",
89
- `# ${MARKER}: ${a.label} with the "${name}" account.`,
90
- `export ${a.homeEnv}=${dir}`,
127
+ `# ${MARKER}: ${a.label} with the "${name}" account${a.classicLauncher ? `, sharing ${shPath(hub, env).slice(1, -1)}` : ""}.`,
128
+ `export ${a.homeEnv}=${shPath(agentProfileDir(name, agent, env), env)}`,
91
129
  `export TURNO_PROFILE="${name}"`,
92
- `export TURNO_AGENT="${agent}"`,
130
+ ...(a.classicLauncher ? [] : [`export TURNO_AGENT="${agent}"`]),
93
131
  "export TURNO_SESSION_PID=$$",
94
- ...a.launcherEnv,
132
+ "# The session folder for the MCP gateway, base64url so any path fits in an HTTP header.",
133
+ `TURNO_SESSION_CWD_B64="$(printf %s "$PWD" | base64 | tr -d '\\n=' | tr '+/' '-_')"`,
134
+ "export TURNO_SESSION_CWD_B64",
135
+ ...Object.entries(a.launcherEnv).map(([k, v]) => `export ${k}=${shWord(v)}`),
95
136
  ...(a.tokenFromEnv
96
- ? ["# The MCP gateway token, read by the agent from the environment (never written to its config).", `TURNO_MCPD_TOKEN="$(cat ${shPath(p.mcpdToken, env)} 2>/dev/null)"`, "export TURNO_MCPD_TOKEN"]
137
+ ? [
138
+ "# This profile's MCP gateway token (turno mcp sync writes it), read by the agent from the environment.",
139
+ `TURNO_MCPD_TOKEN="$(cat ${shPath(profileTokenFile(name, env), env)} 2>/dev/null)"`,
140
+ "export TURNO_MCPD_TOKEN",
141
+ ]
97
142
  : []),
98
143
  ...(hubDirs.length ? ["# If a cleanup removed an empty hub folder, the profile symlink would dangle.", `mkdir -p ${hubDirs.join(" ")}`] : []),
99
- `export BROWSER=${shPath(join(p.bin, "turno-open"), env)}`,
144
+ ...browserLines(env, platform, a.classicLauncher),
100
145
  "# exec keeps the PID, so turno sessions knows which account each session uses.",
101
146
  `mkdir -p ${run} && echo ${name} >${runFile} 2>/dev/null`,
147
+ requireAgent(agent),
102
148
  `exec ${a.command} "$@"`,
103
149
  "",
104
150
  ].join("\n");
105
151
  }
106
- /** Text of a profile's launcher: claude-<name> by default, or the launcher of `agent`. */
107
- export function launcherText(name, env = process.env, agent = "claude") {
108
- if (agent !== "claude")
109
- return agentLauncherText(name, agent, env);
110
- const p = paths(env);
111
- const dirs = SHARED_DIRS.map((d) => shPath(join(p.hub, d), env)).join(" ");
112
- const run = shPath(p.runDir, env);
113
- const runFile = run.slice(0, -1) + '/$$"';
114
- return [
115
- "#!/bin/sh",
116
- `# ${MARKER}: Claude Code with the "${name}" account, sharing ${shPath(p.hub, env).slice(1, -1)}.`,
117
- `export CLAUDE_CONFIG_DIR="$HOME/.claude-${name}"`,
118
- `export TURNO_PROFILE="${name}"`,
119
- "export TURNO_SESSION_PID=$$",
120
- "# If a cleanup removed an empty hub folder, the profile symlink would dangle.",
121
- `mkdir -p ${dirs}`,
122
- "# claude.ai links (artifacts, login) open with this account: turno open.",
123
- `export BROWSER=${shPath(join(p.bin, "turno-open"), env)}`,
124
- "# exec keeps the PID, so turno sessions knows which account each session uses.",
125
- `mkdir -p ${run} && echo ${name} >${runFile} 2>/dev/null`,
126
- 'exec claude "$@"',
127
- "",
128
- ].join("\n");
129
- }
130
- function writeScript(file, text) {
131
- if (existsSync(file) && !isGenerated(file)) {
152
+ /** Write a launcher; with a journal, a new or changed one is recorded so `turno undo` reverts it. */
153
+ function writeScript(file, text, journal) {
154
+ const exists = existsSync(file);
155
+ if (exists && !isGenerated(file)) {
132
156
  throw new UsageError(`${file} already exists and was not generated by turno; leaving it alone`);
133
157
  }
158
+ if (exists && readFileSync(file, "utf8") === text) {
159
+ chmodSync(file, 0o755);
160
+ return;
161
+ }
134
162
  mkdirSync(join(file, ".."), { recursive: true });
163
+ journal?.save(file);
135
164
  writeFileSync(file, text);
136
165
  chmodSync(file, 0o755);
166
+ journal?.settle(file);
137
167
  }
138
168
  /** Write the profile's launcher (claude-<name>, codex-<name>, ...). Refuses to overwrite a file turno did not generate. */
139
- export function writeLauncher(name, env = process.env, agent = profileAgent(name, env)) {
169
+ export function writeLauncher(name, env = process.env, agent = profileAgent(name, env), journal) {
140
170
  const file = join(paths(env).bin, launcherName(name, agent));
141
- writeScript(file, launcherText(name, env, agent));
171
+ writeScript(file, launcherText(name, env, agent), journal);
142
172
  return file;
143
173
  }
144
174
  function sameFile(a, b) {
@@ -149,50 +179,71 @@ function sameFile(a, b) {
149
179
  return false;
150
180
  }
151
181
  }
182
+ /** Node version managers: a path inside one stops working when the active Node version changes. */
183
+ const VERSIONED = /\/(\.nvm|\.fnm|fnm\/node-versions|\.asdf\/installs|mise\/installs|\.nodenv\/versions|n\/versions)\//;
184
+ const quote = (s) => `"${esc(s)}"`;
185
+ function legacyScript(file) {
186
+ try {
187
+ return readFileSync(file, "utf8").slice(0, 400).startsWith("#!/bin/bash");
188
+ }
189
+ catch {
190
+ return false;
191
+ }
192
+ }
152
193
  /**
153
- * Shell words that run this turno: the real path of the running CLI entry when it is
154
- * this package's main module, else `turno` from PATH.
194
+ * Shell words that run this turno, for launchers: the `turno` on PATH when there is one (as
195
+ * found there, so a Homebrew or npm upgrade keeps working), else the path of the running CLI
196
+ * entry with a warning, else plain `turno`.
155
197
  */
156
- export function turnoCommand(argv1 = process.argv[1]) {
198
+ export function resolveTurnoCommand(env = process.env, argv1 = process.argv[1]) {
199
+ const onPath = findOnPath("turno", env);
200
+ if (onPath && !onPath.includes("/_npx/") && !legacyScript(onPath)) {
201
+ 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` } : {}) };
203
+ }
157
204
  const main = fileURLToPath(new URL("./main.js", import.meta.url));
158
205
  if (!argv1 || !sameFile(argv1, main))
159
- return "turno";
206
+ return { words: "turno" };
160
207
  const real = realpathSync(argv1);
161
- const q = (s) => `"${s.replace(/(["\\$`])/g, "\\$1")}"`;
208
+ const warning = `wrote an absolute path (${tildify(real, env)}) because turno is not on your PATH; it breaks if you switch Node versions or move this copy`;
162
209
  try {
163
210
  accessSync(real, constants.X_OK);
164
- return q(real);
211
+ return { words: quote(real), warning };
165
212
  }
166
213
  catch {
167
- return `${q(process.execPath)} ${q(real)}`;
214
+ return { words: `${quote(process.execPath)} ${quote(real)}`, warning };
168
215
  }
169
216
  }
217
+ /** Shell words that run this turno (see resolveTurnoCommand). */
218
+ export function turnoCommand(argv1 = process.argv[1], env = process.env) {
219
+ return resolveTurnoCommand(env, argv1).words;
220
+ }
170
221
  function helperText(sub, why, turno) {
171
222
  return ["#!/bin/sh", `# ${MARKER}: ${why}`, `exec ${turno} ${sub} "$@"`, ""].join("\n");
172
223
  }
173
- export function autoLauncherText(turno = turnoCommand()) {
174
- return helperText("auto", "Claude Code with the account assigned to the project (Orca uses it as its Claude command).", turno);
224
+ function autoLauncherText(turno = turnoCommand()) {
225
+ return helperText("auto", "the agent with the account assigned to the folder (editors can use it as their Claude command).", turno);
175
226
  }
176
- export function openLauncherText(turno = turnoCommand()) {
227
+ function openLauncherText(turno = turnoCommand()) {
177
228
  return helperText("open", "Claude Code uses it as $BROWSER (turno open).", turno);
178
229
  }
179
230
  /**
180
231
  * Write turno-auto and turno-open. The claudio-auto and claudio-navegador left by the bash
181
- * tool are rewritten to run turno, so Orca and sessions started before the switch keep working.
232
+ * tool are rewritten to run turno, so editors and sessions started before the switch keep working.
182
233
  * Returns the names written.
183
234
  */
184
- export function writeHelperLaunchers(env = process.env, turno = turnoCommand()) {
235
+ export function writeHelperLaunchers(env = process.env, turno = turnoCommand(), journal) {
185
236
  const bin = paths(env).bin;
186
237
  const written = [];
187
- writeScript(join(bin, "turno-auto"), autoLauncherText(turno));
238
+ writeScript(join(bin, "turno-auto"), autoLauncherText(turno), journal);
188
239
  written.push("turno-auto");
189
- writeScript(join(bin, "turno-open"), openLauncherText(turno));
240
+ writeScript(join(bin, "turno-open"), openLauncherText(turno), journal);
190
241
  written.push("turno-open");
191
242
  for (const [name, sub] of LEGACY_HELPERS) {
192
243
  const legacy = join(bin, name);
193
244
  if (!existsSync(legacy) || !isGenerated(legacy))
194
245
  continue;
195
- writeScript(legacy, sub === "auto" ? autoLauncherText(turno) : openLauncherText(turno));
246
+ writeScript(legacy, sub === "auto" ? autoLauncherText(turno) : openLauncherText(turno), journal);
196
247
  written.push(name);
197
248
  }
198
249
  return written;
package/dist/cli/main.js CHANGED
@@ -1,20 +1,43 @@
1
1
  #!/usr/bin/env node
2
2
  import { realpathSync } from "node:fs";
3
3
  import { fileURLToPath } from "node:url";
4
- import { UsageError, defaultIo } from "./io.js";
5
- import { COMMANDS, QUIET, SECTIONS, expand } from "./registry.js";
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";
6
7
  async function help(io) {
7
- io.out("turno: several Claude Code accounts on one machine, sharing context, with a lazy MCP gateway.\n");
8
- io.out("Usage:");
9
- io.out(` turno ${"<profile> [claude args]".padEnd(24)} open Claude Code with that account (turno run <profile>)`);
10
- for (const section of SECTIONS) {
11
- io.out(`\n${section.title}:`);
12
- const loaded = await Promise.all(section.commands.map(async (n) => [n, (await COMMANDS[n]()).command]));
13
- for (const [name, cmd] of loaded)
14
- io.out(` turno ${name.padEnd(24)} ${cmd.summary}`);
15
- }
16
- io.out("\nRun `turno <command> --help` for details. Older names (setup, usage, exhausted, accounts, mcpd,");
17
- io.out("and the Spanish ones) still work.");
8
+ const sections = await Promise.all(SECTIONS.map(async (s) => ({
9
+ title: s.title,
10
+ rows: await Promise.all(s.commands.map(async (n) => [n, HELP_SUMMARY[n] ?? (await COMMANDS[n]()).command.summary])),
11
+ })));
12
+ const { renderHelp } = await import("./help.js");
13
+ for (const line of renderHelp(io, sections))
14
+ io.out(line);
15
+ return 0;
16
+ }
17
+ /** Error classes whose message is the whole story: printed without a stack trace. */
18
+ const ONE_LINE_ERRORS = new Set(["ConfigError", "SecretError"]);
19
+ /** Commands whose arguments belong to the agent they start: only a first --help is theirs. */
20
+ const PASSTHROUGH = new Set(["run", "auto", "hook", "statusline", "__complete"]);
21
+ function asksHelp(name, rest) {
22
+ if (PASSTHROUGH.has(name))
23
+ return rest[0] === "--help" || rest[0] === "-h";
24
+ const end = rest.indexOf("--");
25
+ return (end < 0 ? rest : rest.slice(0, end)).some((a) => a === "--help" || a === "-h");
26
+ }
27
+ function unknownCommand(word) {
28
+ const near = closest(word, visibleCommands());
29
+ return fail(near ? `unknown command '${word}'. Did you mean 'turno ${near}'?` : `unknown command '${word}' (turno --help)`);
30
+ }
31
+ /** `turno help <command> [sub]`: the same text as `turno <command> [sub] --help`. */
32
+ async function helpFor(words, io) {
33
+ const [name, rest] = expand(words[0], words.slice(1));
34
+ const load = COMMANDS[name];
35
+ if (!load)
36
+ return unknownCommand(words[0]);
37
+ const { command } = await load();
38
+ if (rest.length && command.subcommands)
39
+ return command.run([...rest, "--help"], io);
40
+ io.out(command.usage);
18
41
  return 0;
19
42
  }
20
43
  /** Print the update notice on stderr after an interactive command, at most once a day. */
@@ -39,21 +62,118 @@ async function notice(name, io) {
39
62
  /* never fail a command over the notice */
40
63
  }
41
64
  }
42
- export async function main(argv, io = defaultIo()) {
43
- const [head, ...tail] = argv;
44
- if (!head || head === "help" || head === "-h" || head === "--help")
45
- return help(io);
46
- if (head === "--version" || head === "-v") {
47
- const { packageInfo } = await import("../core/version.js");
48
- io.out(`turno ${packageInfo().version}`);
49
- return 0;
65
+ /**
66
+ * Take the global --no-input flag out of argv: before the command, or among a command's own
67
+ * flags (not after --, and not for commands whose arguments belong to an agent).
68
+ */
69
+ export function takeNoInput(argv) {
70
+ let i = 0;
71
+ while (argv[i] === "--no-input")
72
+ i++;
73
+ const [head, ...tail] = argv.slice(i);
74
+ if (head === undefined)
75
+ return { argv: [], noInput: i > 0 };
76
+ const name = expand(head, [])[0];
77
+ if (!COMMANDS[name] || PASSTHROUGH.has(name))
78
+ return { argv: [head, ...tail], noInput: i > 0 };
79
+ const end = tail.indexOf("--");
80
+ const own = end < 0 ? tail : tail.slice(0, end);
81
+ const kept = own.filter((a) => a !== "--no-input");
82
+ return { argv: [head, ...kept, ...(end < 0 ? [] : tail.slice(end))], noInput: i > 0 || kept.length < own.length };
83
+ }
84
+ function colorValue(v) {
85
+ if (isColorMode(v))
86
+ return v;
87
+ return fail(v === undefined || v.startsWith("-") ? "--color needs a value: auto, always or never" : `--color ${v}: use auto, always or never`);
88
+ }
89
+ /**
90
+ * Take the global `--color auto|always|never` (or `--color=<mode>`) out of argv, like --no-input:
91
+ * before the command, or among a command's own flags (not after --, and not for commands whose
92
+ * arguments belong to an agent). Among a command's flags only those three values count, so
93
+ * `turno profile add work --color green` keeps its own --color. The last one given wins.
94
+ */
95
+ export function takeColor(argv) {
96
+ const lead = [];
97
+ let color;
98
+ let i = 0;
99
+ for (; i < argv.length; i++) {
100
+ const a = argv[i];
101
+ if (a === "--no-input")
102
+ lead.push(a);
103
+ else if (a === "--color")
104
+ color = colorValue(argv[++i]);
105
+ else if (a.startsWith("--color="))
106
+ color = colorValue(a.slice("--color=".length));
107
+ else
108
+ break;
109
+ }
110
+ const at = (o) => (color ? { ...o, color } : o);
111
+ const [head, ...tail] = argv.slice(i);
112
+ if (head === undefined)
113
+ return at({ argv: lead });
114
+ const name = expand(head, [])[0];
115
+ if (!COMMANDS[name] || PASSTHROUGH.has(name))
116
+ return at({ argv: [...lead, head, ...tail] });
117
+ const end = tail.indexOf("--");
118
+ const own = end < 0 ? tail : tail.slice(0, end);
119
+ const kept = [];
120
+ for (let j = 0; j < own.length; j++) {
121
+ const a = own[j];
122
+ const inline = a.startsWith("--color=") ? a.slice("--color=".length) : undefined;
123
+ if (a === "--color" && isColorMode(own[j + 1]))
124
+ color = own[++j];
125
+ else if (isColorMode(inline))
126
+ color = inline;
127
+ else
128
+ kept.push(a);
129
+ }
130
+ return at({ argv: [...lead, head, ...kept, ...(end < 0 ? [] : tail.slice(end))] });
131
+ }
132
+ export async function main(args, io = defaultIo()) {
133
+ let picked;
134
+ try {
135
+ picked = takeColor(args);
50
136
  }
51
- const [first, rest] = expand(head, tail);
52
- const load = COMMANDS[first];
137
+ catch (err) {
138
+ io.err(`turno: ${err.message}`);
139
+ return 2;
140
+ }
141
+ if (picked.color)
142
+ io = { ...io, color: picked.color };
143
+ const { argv, noInput } = takeNoInput(picked.argv);
144
+ // --no-input is TURNO_NO_INPUT=1, also for the turno processes this one starts.
145
+ if (noInput)
146
+ io = { ...withoutAsk(io), env: { ...io.env, TURNO_NO_INPUT: "1" } };
147
+ else if (io.ask && noInputReason(io.env))
148
+ io = withoutAsk(io);
149
+ const [head, ...tail] = argv;
53
150
  try {
151
+ if (!head) {
152
+ // Once turno is set up, bare `turno` is the status screen; before that, the help.
153
+ const { homeScreen } = await import("./commands/status.js");
154
+ const code = await homeScreen(io);
155
+ if (code !== undefined) {
156
+ io.out(paint(io, "turno help lists every command.", "2"));
157
+ return code;
158
+ }
159
+ return await help(io);
160
+ }
161
+ if (head === "-h" || head === "--help")
162
+ return await help(io);
163
+ if (head === "help")
164
+ return tail.length ? await helpFor(tail, io) : await help(io);
165
+ if (head === "--version" || head === "-v") {
166
+ const { packageInfo } = await import("../core/version.js");
167
+ io.out(`turno ${packageInfo().version}`);
168
+ return 0;
169
+ }
170
+ if (head.startsWith("-"))
171
+ return fail(`unknown option ${head} (turno --help)`);
172
+ const [first, rest] = expand(head, tail);
173
+ const load = COMMANDS[first];
54
174
  if (load) {
55
175
  const { command } = await load();
56
- if (!command.subcommands && (rest[0] === "--help" || rest[0] === "-h")) {
176
+ if (!command.subcommands && asksHelp(first, rest)) {
57
177
  io.out(command.usage);
58
178
  return 0;
59
179
  }
@@ -61,8 +181,10 @@ export async function main(argv, io = defaultIo()) {
61
181
  await notice(first, io);
62
182
  return code;
63
183
  }
64
- // Anything else is a profile name: exec its launcher.
65
- const { launchProfile } = await import("./launch.js");
184
+ // Anything else is a profile name: exec its launcher. A typo of a command is not one.
185
+ const { launchProfile, launcherPath } = await import("./launch.js");
186
+ if (!launcherPath(first, io.env) && closest(first, visibleCommands()))
187
+ unknownCommand(first);
66
188
  return await launchProfile(first, rest, io);
67
189
  }
68
190
  catch (err) {
@@ -70,8 +192,13 @@ export async function main(argv, io = defaultIo()) {
70
192
  io.err(`turno: ${err.message}`);
71
193
  return 2;
72
194
  }
195
+ if (err instanceof CliError) {
196
+ io.err(`turno: ${err.message}`);
197
+ return err.code;
198
+ }
73
199
  const e = err;
74
- io.err(`turno: ${e.name === "ConfigError" ? e.message : (e.stack ?? e.message)}`);
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)}`);
75
202
  return 1;
76
203
  }
77
204
  }
@@ -84,6 +211,15 @@ function isEntry() {
84
211
  }
85
212
  }
86
213
  if (isEntry()) {
214
+ // Before the first command module loads, so it and everything it imports come from the cache.
215
+ let argv = process.argv.slice(2);
216
+ try {
217
+ argv = takeNoInput(takeColor(argv).argv).argv;
218
+ }
219
+ catch {
220
+ /* main reports the bad --color */
221
+ }
222
+ enableCompileCache(argv);
87
223
  main(process.argv.slice(2)).then((code) => {
88
224
  process.exitCode = code;
89
225
  }, (err) => {