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,44 +1,106 @@
1
1
  import { execFile } from "node:child_process";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { readFileSync, statSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { loadConfig } from "../../core/config.js";
5
5
  import { exhaustedUntil } from "../../core/exhausted.js";
6
- import { paths, profileDir } from "../../core/paths.js";
6
+ import { isObject, readJsonFile } from "../../core/fsutil.js";
7
+ import { paths, profileDir, writePrivateFile } from "../../core/paths.js";
7
8
  import { listProfiles } from "../../core/profiles.js";
8
- import { paint } from "../io.js";
9
+ import { profileColor, style } from "../style.js";
10
+ /** Why `claude auth status` gave no answer, in a few words for the account column. */
11
+ function authFailure(err, stdout, stderr) {
12
+ if (err?.code === "ENOENT")
13
+ return "claude is not on PATH";
14
+ if (err?.killed || err?.signal === "SIGTERM")
15
+ return "claude auth status timed out";
16
+ const line = (stderr || stdout).trim().split("\n")[0]?.trim();
17
+ if (err && typeof err.code === "number")
18
+ return `claude auth status exited with ${err.code}${line ? `: ${line.slice(0, 120)}` : ""}`;
19
+ return "claude auth status gave no JSON";
20
+ }
21
+ /** Reuse an answer of `claude auth status` this long while the profile's login files stay the same (seconds). */
22
+ const AUTH_TTL = 300;
23
+ /**
24
+ * The files a login or logout rewrites in a profile folder (the account in .claude.json, and
25
+ * .credentials.json where there is no Keychain), as a key for the cached answer.
26
+ */
27
+ function authFingerprint(dir) {
28
+ return [".claude.json", ".credentials.json"]
29
+ .map((f) => {
30
+ try {
31
+ const st = statSync(join(dir, f));
32
+ return `${st.ino}:${st.size}:${st.mtimeMs}`;
33
+ }
34
+ catch {
35
+ return "-";
36
+ }
37
+ })
38
+ .join("|");
39
+ }
40
+ function recordPlan(profile, s, env) {
41
+ if (!s.loggedIn || !s.subscriptionType)
42
+ return;
43
+ try {
44
+ writePrivateFile(join(paths(env).planDir, profile), `${s.subscriptionType}\n`, env);
45
+ }
46
+ catch {
47
+ // the plan file is a cache for the status line
48
+ }
49
+ }
9
50
  /**
10
51
  * Run `claude auth status --json` with the profile's config dir (20 s timeout). Records the
11
- * plan in the state plan dir, where the status line reads it. Undefined when it fails.
52
+ * plan in the state plan dir, where the status line reads it. On failure `why` says what went
53
+ * wrong (claude missing, a timeout, an error line), so callers never show a bare "?".
54
+ *
55
+ * An answer is kept for AUTH_TTL seconds in the state cache, keyed by the profile's login files,
56
+ * so `turno`, `turno status` and `turno profile list` do not start one claude per profile on
57
+ * every run; logging in or out changes those files and asks again. Failures are not kept.
12
58
  */
13
- export function authStatus(profile, env = process.env) {
59
+ function authStatusResult(profile, env = process.env) {
60
+ const dir = profileDir(profile, env);
61
+ const cacheFile = join(paths(env).state, "cache", `auth-${profile}.json`);
62
+ const now = Date.now() / 1000;
63
+ const cached = readJsonFile(cacheFile);
64
+ if (isObject(cached) &&
65
+ isObject(cached.status) &&
66
+ cached.key === authFingerprint(dir) &&
67
+ typeof cached.at === "number" &&
68
+ now >= cached.at &&
69
+ now - cached.at < AUTH_TTL) {
70
+ const s = cached.status;
71
+ recordPlan(profile, s, env);
72
+ return Promise.resolve({ status: s });
73
+ }
14
74
  return new Promise((resolve) => {
15
- execFile("claude", ["auth", "status", "--json"], { env: { ...env, CLAUDE_CONFIG_DIR: profileDir(profile, env) }, timeout: 20_000, encoding: "utf8" }, (_err, stdout) => {
75
+ execFile("claude", ["auth", "status", "--json"], { env: { ...env, CLAUDE_CONFIG_DIR: dir }, timeout: 20_000, encoding: "utf8" }, (err, stdout, stderr) => {
16
76
  let s;
17
77
  try {
18
78
  s = JSON.parse(stdout);
19
79
  }
20
80
  catch {
21
- resolve(undefined);
81
+ resolve({ why: authFailure(err, stdout ?? "", stderr ?? "") });
22
82
  return;
23
83
  }
24
84
  if (!s || typeof s !== "object") {
25
- resolve(undefined);
85
+ resolve({ why: authFailure(err, stdout ?? "", stderr ?? "") });
26
86
  return;
27
87
  }
28
- if (s.loggedIn && s.subscriptionType) {
29
- try {
30
- const dir = paths(env).planDir;
31
- mkdirSync(dir, { recursive: true });
32
- writeFileSync(join(dir, profile), `${s.subscriptionType}\n`);
33
- }
34
- catch {
35
- // the plan file is a cache for the status line
36
- }
88
+ recordPlan(profile, s, env);
89
+ try {
90
+ // Keyed after the call, so a claude that touches its own files still finds the entry.
91
+ writePrivateFile(cacheFile, JSON.stringify({ key: authFingerprint(dir), at: Math.trunc(now), status: s }), env);
92
+ }
93
+ catch {
94
+ // without the cache the next run asks claude again
37
95
  }
38
- resolve(s);
96
+ resolve({ status: s });
39
97
  });
40
98
  });
41
99
  }
100
+ /** `claude auth status --json` of a profile, or undefined when it fails (authStatusResult says why). */
101
+ export async function authStatus(profile, env = process.env) {
102
+ return (await authStatusResult(profile, env)).status;
103
+ }
42
104
  function readSnapshot(file) {
43
105
  try {
44
106
  const v = JSON.parse(readFileSync(file, "utf8"));
@@ -66,11 +128,7 @@ export function shortTime(epochSeconds) {
66
128
  const d = new Date(epochSeconds * 1000);
67
129
  return `${DAYS[d.getDay()]} ${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
68
130
  }
69
- export function bar(pct, width = 30) {
70
- const filled = Math.round((Math.min(Math.max(pct, 0), 100) * width) / 100);
71
- return "█".repeat(filled) + "░".repeat(width - filled);
72
- }
73
- export function resetText(ts, now = Date.now() / 1000) {
131
+ function resetText(ts, now = Date.now() / 1000) {
74
132
  const d = Math.floor(ts - now);
75
133
  if (d <= 0)
76
134
  return "already reset";
@@ -79,7 +137,7 @@ export function resetText(ts, now = Date.now() / 1000) {
79
137
  const rel = h >= 24 ? `${Math.floor(h / 24)}d ${h % 24}h` : h ? `${h}h${pad2(m)}m` : `${m}m`;
80
138
  return `resets in ${rel} (${shortTime(ts)})`;
81
139
  }
82
- export function agoText(ts, now = Date.now() / 1000) {
140
+ function agoText(ts, now = Date.now() / 1000) {
83
141
  const d = Math.floor(now - ts);
84
142
  if (d < 60)
85
143
  return "seconds ago";
@@ -90,30 +148,36 @@ export function agoText(ts, now = Date.now() / 1000) {
90
148
  return `${Math.floor(d / 86400)} d ago`;
91
149
  }
92
150
  export async function account(profile, env) {
93
- const s = await authStatus(profile, env);
151
+ const { status: s, why } = await authStatusResult(profile, env);
94
152
  if (!s)
95
- return { email: "?", plan: "?" };
153
+ return { email: "?", plan: "", why: why ?? "claude auth status failed" };
96
154
  if (!s.loggedIn)
97
155
  return { email: "not logged in", plan: "" };
98
156
  return { email: s.email || "?", plan: s.subscriptionType || s.authMethod || "?" };
99
157
  }
100
- export function renderUsage(profiles, accounts, io) {
101
- const now = Date.now() / 1000;
158
+ /** Cells of the usage bars. */
159
+ const BAR_CELLS = 20;
160
+ /**
161
+ * The usage screen of `turno limit show`: each profile as its pill with the account, then a bar
162
+ * per window with its reset time, the exhausted mark and how old the data is. The same layout
163
+ * comes out as plain text in a pipe. `colors` holds the profiles of config.toml, for the pills.
164
+ */
165
+ export function renderUsage(profiles, accounts, io, opts = {}) {
166
+ const now = opts.now ?? Date.now() / 1000;
167
+ const s = style(io);
102
168
  const out = [];
103
169
  for (const p of profiles) {
104
- const { email, plan } = accounts[p] ?? { email: "?", plan: "?" };
105
- out.push(paint(io, `${p} ${email}${plan ? ` · ${plan}` : ""}`, "1"));
106
- const exhausted = exhaustedUntil(p, io.env);
107
- if (exhausted !== undefined && exhausted > now) {
108
- out.push(paint(io, ` marked exhausted: its projects use the fallback (if set) until ${shortTime(exhausted)}`, "2"));
109
- }
170
+ const { email, plan, why } = accounts[p] ?? { email: "?", plan: "" };
171
+ const pill = s.profile(p, opts.colors ? profileColor(opts.colors, p) : undefined);
172
+ const who = why
173
+ ? `${s.warn("account unknown")}${s.muted(` (${why})`)}`
174
+ : email === "not logged in"
175
+ ? s.warn(email)
176
+ : `${email}${plan ? s.muted(` · ${plan}`) : ""}`;
177
+ out.push(s.wrap(`${pill} `, who));
110
178
  const data = usageSnapshot(p, io.env);
111
179
  const limits = data.rate_limits ?? {};
112
180
  const hasLimits = Object.keys(limits).length > 0;
113
- if (!hasLimits) {
114
- const why = plan === "team" ? "the Team plan does not report these limits" : "shows up once a session of this account gets a response";
115
- out.push(paint(io, ` no data yet: ${why}`, "2"));
116
- }
117
181
  for (const [key, label] of [
118
182
  ["five_hour", "5 hours"],
119
183
  ["seven_day", "week"],
@@ -125,11 +189,19 @@ export function renderUsage(profiles, accounts, io) {
125
189
  const reset = typeof w.resets_at === "number" ? w.resets_at : undefined;
126
190
  if (reset && reset < now)
127
191
  pct = 0;
128
- const code = pct < 50 ? "32" : pct < 80 ? "33" : "31";
129
- out.push(` ${label.padEnd(8)}${paint(io, bar(pct), code)} ${pct.toFixed(0).padStart(3)}% ${reset ? resetText(reset, now) : ""}`);
192
+ const when = reset ? resetText(reset, now) : "";
193
+ out.push(s.wrap(` ${s.muted(label.padEnd(7))} ${s.bar(pct, BAR_CELLS)} `, pct >= 100 ? s.err(`used up, ${when}`) : s.muted(when)).trimEnd());
194
+ }
195
+ const exhausted = exhaustedUntil(p, io.env);
196
+ if (exhausted !== undefined && exhausted > now) {
197
+ out.push(s.note("err", `${s.err(`exhausted until ${shortTime(exhausted)}`)}${s.muted(": its projects open with the fallback, if one is set")}`));
198
+ }
199
+ if (!hasLimits) {
200
+ const why = plan === "team" ? "the Team plan does not report these limits" : "shows up once a session of this account gets a response";
201
+ out.push(s.muted(` no usage data yet: ${why}`));
130
202
  }
131
203
  if (hasLimits && typeof data.updated_at === "number")
132
- out.push(paint(io, ` data from ${agoText(data.updated_at, now)}`, "2"));
204
+ out.push(s.muted(` data from ${agoText(data.updated_at, now)}`));
133
205
  out.push("");
134
206
  }
135
207
  return `${out.join("\n").trimEnd()}\n`;
@@ -144,16 +216,17 @@ export const command = {
144
216
  ].join("\n"),
145
217
  async run(args, io) {
146
218
  const watch = args.includes("--watch");
147
- const profiles = listProfiles(loadConfig(io.env), io.env, "claude");
219
+ const config = loadConfig(io.env);
220
+ const profiles = listProfiles(config, io.env, "claude");
148
221
  const list = await Promise.all(profiles.map((p) => account(p, io.env)));
149
222
  const accounts = Object.fromEntries(profiles.map((p, i) => [p, list[i]]));
150
223
  if (!watch) {
151
- io.out(renderUsage(profiles, accounts, io).trimEnd());
224
+ io.out(renderUsage(profiles, accounts, io, { colors: config.profiles }).trimEnd());
152
225
  return 0;
153
226
  }
154
227
  return new Promise((resolve) => {
155
228
  const draw = () => {
156
- io.out(`\x1b[2J\x1b[H${renderUsage(profiles, accounts, io)}\n(refreshes every 30 s · Ctrl+C to quit)`);
229
+ io.out(`\x1b[2J\x1b[H${renderUsage(profiles, accounts, io, { colors: config.profiles })}\n${style(io).muted("refreshes every 30 s · Ctrl+C to quit")}`);
157
230
  };
158
231
  draw();
159
232
  const timer = setInterval(draw, 30_000);
@@ -1,23 +1,25 @@
1
1
  import { tildify } from "../../core/paths.js";
2
2
  import { availableUpdate } from "../../core/update.js";
3
3
  import { detectInstall, packageInfo } from "../../core/version.js";
4
- import { JSON_FLAG, bool, parseFlags, printJson } from "../args.js";
4
+ import { JSON_FLAG, bool, flagsOf, parseFlags, printJson } from "../args.js";
5
5
  export const command = {
6
6
  summary: "the turno version, how it was installed, and whether a newer one is known",
7
7
  usage: "Usage: turno version [--json]\n\nturno --version prints only the number.",
8
- flags: ["--json"],
8
+ flags: flagsOf(JSON_FLAG),
9
9
  async run(args, io) {
10
10
  const p = parseFlags(args, JSON_FLAG, 0);
11
11
  const pkg = packageInfo();
12
12
  const install = detectInstall();
13
13
  const latest = availableUpdate(io.env);
14
- const data = { name: pkg.name, version: pkg.version, node: process.versions.node, method: install.method, path: tildify(install.root, io.env), latest: latest ?? null };
14
+ // npx runs a temporary copy from its cache: upgrade and launchers must not rely on it.
15
+ const npx = install.root.includes("/_npx/");
16
+ const data = { name: pkg.name, version: pkg.version, node: process.versions.node, method: npx ? "npx" : install.method, path: tildify(install.root, io.env), latest: latest ?? null };
15
17
  if (bool(p, "json")) {
16
- printJson(io.out, data);
18
+ printJson(io, data);
17
19
  return 0;
18
20
  }
19
21
  io.out(`turno ${pkg.version}`);
20
- io.out(` installed with ${install.method} at ${data.path}`);
22
+ io.out(npx ? ` a temporary copy in npx's cache (${data.path}); install it with: npm install --global turno-cli` : ` installed with ${install.method} at ${data.path}`);
21
23
  io.out(` node ${data.node}`);
22
24
  if (latest)
23
25
  io.out(` ${latest} is available: turno upgrade`);
@@ -1,28 +1,11 @@
1
- import { statSync } from "node:fs";
2
- import { resolve as resolvePath } from "node:path";
3
- import { loadConfig } from "../../core/config.js";
4
- import { tildify } from "../../core/paths.js";
5
- import { resolveProfile } from "../../core/resolve.js";
6
- import { fail } from "../io.js";
1
+ import { whichCommand } from "./profile.js";
2
+ /** The 0.1 `turno which`; `which` is now an alias of `turno profile which`, which this runs. */
7
3
  export const command = {
8
4
  summary: "which account auto would use in a folder, and why",
9
- usage: "Usage: turno which [dir]\n\nExplains the profile resolution for a folder (default: the current one).",
10
- async run(args, io) {
11
- const dir = resolvePath(args[0] ?? process.cwd());
12
- let isDir = false;
13
- try {
14
- isDir = statSync(dir).isDirectory();
15
- }
16
- catch {
17
- isDir = false;
18
- }
19
- if (!isDir)
20
- fail(`no such folder: ${args[0] ?? dir}`);
21
- const r = resolveProfile(dir, loadConfig(io.env), io.env);
22
- io.out(tildify(dir, io.env));
23
- io.out(` assigned: ${r.assigned || "none"} (${r.reason})`);
24
- io.out(r.note ? ` using now: ${r.chosen} (${r.assigned} ${r.note})` : ` using now: ${r.chosen || "plain claude"}`);
25
- return 0;
26
- },
5
+ usage: "Usage: turno profile which [dir] [--json]\n\nExplains the profile resolution for a folder (default: the current one), for each agent.",
6
+ hidden: true,
7
+ args: ["dir"],
8
+ flags: ["--json"],
9
+ run: whichCommand,
27
10
  };
28
11
  //# sourceMappingURL=which.js.map
@@ -0,0 +1,32 @@
1
+ import module from "node:module";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ /**
5
+ * Where Node keeps turno's compiled code between runs: the user cache dir
6
+ * ($XDG_CACHE_HOME/turno, else ~/.cache/turno), never the shared temp dir Node uses by default.
7
+ */
8
+ export function compileCacheDir(env) {
9
+ return join(env.XDG_CACHE_HOME || join(env.HOME || homedir(), ".cache"), "turno", "node-compile-cache");
10
+ }
11
+ /**
12
+ * Turn on Node's on-disk compile cache (module.enableCompileCache, Node 22.1+), so later runs
13
+ * skip compiling the modules they import. Only the CLI entry calls it, before it imports any
14
+ * command. NODE_COMPILE_CACHE picks another folder and NODE_DISABLE_COMPILE_CACHE turns it off,
15
+ * as for any Node program. A Node without the API, or a cache that cannot be written, only
16
+ * makes turno a little slower. `turno demo` promises to leave HOME as it found it, so it runs
17
+ * without the cache (the turno commands inside the demo cache in the demo's own HOME).
18
+ */
19
+ export function enableCompileCache(argv, env = process.env) {
20
+ if (argv[0] === "demo")
21
+ return;
22
+ const enable = module.enableCompileCache;
23
+ if (typeof enable !== "function")
24
+ return;
25
+ try {
26
+ enable(env.NODE_COMPILE_CACHE ? undefined : compileCacheDir(env));
27
+ }
28
+ catch {
29
+ /* never fail a command over the cache */
30
+ }
31
+ }
32
+ //# sourceMappingURL=compile-cache.js.map
package/dist/cli/group.js CHANGED
@@ -1,16 +1,14 @@
1
- import { fail } from "./io.js";
1
+ import { closest, columns, fail } from "./io.js";
2
2
  /** Usage text of a group: one line per visible subcommand, then an optional footer. */
3
- export function groupUsage(name, subs, footer) {
3
+ function groupUsage(name, subs, footer) {
4
4
  const rows = Object.entries(subs)
5
5
  .filter(([, s]) => !s.hidden)
6
6
  .map(([n, s]) => [`turno ${name} ${n}${s.synopsis ? ` ${s.synopsis}` : ""}`, s.summary]);
7
- const w = Math.min(60, Math.max(...rows.map(([l]) => l.length)));
8
- const lines = rows.map(([l, s]) => (l.length > w ? ` ${l}\n ${" ".repeat(w)} ${s}` : ` ${l.padEnd(w)} ${s}`));
9
- return `Usage:\n${lines.join("\n")}${footer ? `\n\n${footer}` : ""}`;
7
+ return `Usage:\n${columns(rows, 2, 36)}${footer ? `\n\n${footer}` : ""}`;
10
8
  }
11
9
  /**
12
10
  * A command made of subcommands: `turno <name> <sub> [args]`. `fallback` runs when no
13
- * subcommand is given (usually `list` or `show`). `--help` after a subcommand prints the group usage.
11
+ * subcommand is given (usually `list` or `show`). `--help` after a subcommand prints its usage.
14
12
  */
15
13
  export function group(name, summary, subs, opts = {}) {
16
14
  const usage = groupUsage(name, subs, opts.footer);
@@ -37,10 +35,12 @@ export function group(name, summary, subs, opts = {}) {
37
35
  return 0;
38
36
  }
39
37
  const s = subs[sub];
40
- if (!s)
41
- return fail(`unknown ${name} command '${sub}'\n\n${usage}`);
42
- if (rest.includes("--help") || rest.includes("-h")) {
43
- io.out(groupUsage(name, { [sub]: s }));
38
+ if (!s) {
39
+ 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}`);
41
+ }
42
+ if (!s.ownHelp && (rest.includes("--help") || rest.includes("-h"))) {
43
+ io.out(groupUsage(name, { [sub]: s }, s.details));
44
44
  return 0;
45
45
  }
46
46
  return s.run(rest, io);
@@ -0,0 +1,57 @@
1
+ /** The main `turno help` screen: drawn from static rows, so it loads nothing but the style. */
2
+ import { wrap } from "./io.js";
3
+ import { padEnd, style } from "./style.js";
4
+ const EXAMPLES = [
5
+ ["turno init", "find your agents, accounts and MCP servers, and set them up"],
6
+ ["turno", "this folder, your accounts and their usage, and what to do next"],
7
+ ["turno work", "open the work profile with its agent"],
8
+ ["turno profile assign . work", "make this folder and everything under it use work"],
9
+ ["turno mcp sync", "point every profile at the gateway"],
10
+ ];
11
+ /** Rows of `left summary`, with summaries wrapped under their column within the width. */
12
+ function rows(left, right, leftWidth, width, paintLeft, paintRight) {
13
+ const out = [];
14
+ const col = 2 + leftWidth + 2;
15
+ for (const [i, l] of left.entries()) {
16
+ const body = wrap(right[i] ?? "", Math.max(24, width - col));
17
+ if (l.length > leftWidth) {
18
+ out.push(` ${paintLeft(l)}`);
19
+ for (const b of body)
20
+ out.push(`${" ".repeat(col)}${paintRight(b)}`);
21
+ continue;
22
+ }
23
+ out.push(` ${padEnd(paintLeft(l), leftWidth)} ${paintRight(body[0])}`);
24
+ for (const b of body.slice(1))
25
+ out.push(`${" ".repeat(col)}${paintRight(b)}`);
26
+ }
27
+ return out;
28
+ }
29
+ export function renderHelp(io, sections) {
30
+ const s = style(io);
31
+ // Help reads best at a modest width even on a wide terminal.
32
+ const width = Math.min(s.width, 100);
33
+ const out = [];
34
+ const tagline = "one MCP gateway and per-folder accounts for Claude Code, Codex, Copilot CLI and Cursor CLI.";
35
+ const first = wrap(`turno: ${tagline}`, width);
36
+ out.push(s.color ? `${s.bold(s.accent("turno"))}${s.bold(first[0].slice("turno".length))}` : first[0]);
37
+ for (const l of first.slice(1))
38
+ out.push(s.bold(l));
39
+ out.push("");
40
+ 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
+ const usage = ["turno <command> [flags]", "turno <profile> [args...]"];
42
+ 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
+ const w = Math.max(...sections.flatMap((x) => x.rows.map(([n]) => n.length)));
45
+ for (const sec of sections) {
46
+ out.push("", s.header(sec.title));
47
+ out.push(...rows(sec.rows.map(([n]) => n), sec.rows.map(([, sum]) => sum), w, width, (l) => s.bold(s.accent(l)), (r) => r));
48
+ }
49
+ const ew = Math.max(...EXAMPLES.map(([c]) => c.length)) + 2;
50
+ out.push("", s.header("Examples"));
51
+ out.push(...rows(EXAMPLES.map(([c]) => `$ ${c}`), EXAMPLES.map(([, why]) => why), ew, width, (l) => `${s.muted("$")}${l.slice(1)}`, (r) => s.muted(r)));
52
+ out.push("", `Run ${s.bold("turno <command> --help")}, or ${s.bold("turno help <command>")}, for details.`);
53
+ out.push(s.muted("Scripts and agents: --no-input or TURNO_NO_INPUT=1 never asks (exit 2 instead)."));
54
+ out.push(s.muted("Colors: --color auto|always|never or TURNO_COLOR, then NO_COLOR and FORCE_COLOR."));
55
+ return out;
56
+ }
57
+ //# sourceMappingURL=help.js.map