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