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,24 +1,38 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
4
  import { loadConfig } from "../../core/config.js";
5
- import { paths } from "../../core/paths.js";
5
+ import { Journal } from "../../core/journal.js";
6
+ import { paths, writePrivateFile } from "../../core/paths.js";
6
7
  import { listProfiles } from "../../core/profiles.js";
7
- import { fetchLatest, updateChecksOff } from "../../core/update.js";
8
- import { compareVersions, detectInstall, packageInfo, upgradeCommand } from "../../core/version.js";
9
- import { DRY_RUN, JSON_FLAG, bool, parseFlags, printJson, str } from "../args.js";
10
- import { fail } from "../io.js";
8
+ import { fetchLatest, isSemver, updateChecksOff } from "../../core/update.js";
9
+ import { ONE_OFF_RUNNERS, compareVersions, detectInstall, isOneOff, packageInfo, upgradeCommand, } from "../../core/version.js";
10
+ import { DRY_RUN, JSON_FLAG, bool, parseFlags, str } from "../args.js";
11
+ import { emit, jsonOutput } from "../output.js";
12
+ import { confirm, fail } from "../io.js";
11
13
  import { findOnPath, launcherPath } from "../launch.js";
12
14
  import { turnoCommand, isGenerated, writeHelperLaunchers, writeLauncher } from "../launchers.js";
15
+ /** `turno upgrade --check --json`. */
16
+ const CHECK_JSON = jsonOutput(["current", "latest", "channel", "method", "updateAvailable", "error", "note"]);
13
17
  const USAGE = `Usage:
14
- turno upgrade [--channel latest|next] [--to <version>] [--dry-run]
18
+ turno upgrade [--channel latest|next] [--to <version>] [--dry-run] [--yes]
15
19
  install the newest release with the tool that installed turno
16
20
  turno upgrade --check [--json] only ask the registry what the newest release is
17
- turno upgrade --finish after an upgrade: rewrite launchers, check config, show what changed
21
+ turno upgrade --finish [--yes] after an upgrade: rewrite launchers, check config, show what changed
18
22
 
19
- turno knows how it was installed (npm, pnpm, yarn, bun, volta, or a git checkout) and runs the
20
- matching command. Once a day interactive commands look for a new release in the background and
21
- mention it once; set update_check = false in config.toml or TURNO_NO_UPDATE_CHECK=1 to stop that.`;
23
+ When agent configs need a new gateway token, --finish offers to run turno mcp sync (in a
24
+ terminal it asks; --yes runs it without asking).
25
+
26
+ turno knows how it was installed (npm, pnpm, yarn, bun, volta, Homebrew, or a git checkout) and
27
+ runs the matching command. A copy that npx, pnpm dlx or bunx runs once has nothing to upgrade:
28
+ the next run of that runner with @latest gets the newest release. Once a day interactive commands look for a new release in the background and
29
+ mention it once; set update_check = false in config.toml or TURNO_NO_UPDATE_CHECK=1 to stop that.
30
+
31
+ Examples:
32
+ $ turno upgrade --check
33
+ $ turno upgrade
34
+ $ turno upgrade --dry-run --to 1.2.3
35
+ $ turno upgrade --finish`;
22
36
  function versionFile(env) {
23
37
  return join(paths(env).state, "version");
24
38
  }
@@ -32,8 +46,7 @@ export function recordedVersion(env) {
32
46
  }
33
47
  }
34
48
  export function recordVersion(env) {
35
- mkdirSync(dirname(versionFile(env)), { recursive: true });
36
- writeFileSync(versionFile(env), `${packageInfo().version}\n`);
49
+ writePrivateFile(versionFile(env), `${packageInfo().version}\n`, env);
37
50
  }
38
51
  /** CHANGELOG sections newer than `from`, up to the running version. */
39
52
  export function changesSince(from, changelog, to = packageInfo().version) {
@@ -48,8 +61,12 @@ export function changesSince(from, changelog, to = packageInfo().version) {
48
61
  }
49
62
  return out.join("\n").trim();
50
63
  }
51
- /** Steps after the files changed: idempotent, safe to run any time. */
52
- export function finishUpgrade(io) {
64
+ /**
65
+ * Steps after the files changed: idempotent, safe to run any time. `sync` says what to do when
66
+ * agent configs need `turno mcp sync`: ask (in a terminal; elsewhere only say so), run it, or
67
+ * only say so (doctor, which offers the sync as a fix of its own).
68
+ */
69
+ export async function finishUpgrade(io, opts = {}) {
53
70
  const env = io.env;
54
71
  const before = recordedVersion(env);
55
72
  const now = packageInfo().version;
@@ -61,20 +78,44 @@ export function finishUpgrade(io) {
61
78
  io.out(`config: ${err.message} (turno config edit)`);
62
79
  }
63
80
  // Launchers bake the path of the running turno, which changes with some package managers.
81
+ // The journal records the ones that change, so `turno undo` can put the old ones back.
82
+ const journal = new Journal(env, "upgrade --finish");
64
83
  let rewritten = 0;
65
84
  for (const name of config ? listProfiles(config, env) : []) {
66
85
  const file = launcherPath(name, env);
67
86
  if (file && isGenerated(file)) {
68
- writeLauncher(name, env);
87
+ writeLauncher(name, env, undefined, journal);
69
88
  rewritten++;
70
89
  }
71
90
  }
72
91
  const bin = paths(env).bin;
73
92
  if (["turno-auto", "turno-open"].some((f) => existsSync(join(bin, f)) && isGenerated(join(bin, f)))) {
74
- rewritten += writeHelperLaunchers(env, turnoCommand()).length;
93
+ rewritten += writeHelperLaunchers(env, turnoCommand(), journal).length;
75
94
  }
76
95
  if (rewritten)
77
96
  io.out(`launchers: ${rewritten} rewritten for turno ${now}`);
97
+ const hint = journal.hint();
98
+ if (hint)
99
+ io.out(hint);
100
+ // Configs synced before per-profile gateway tokens send the master token, which
101
+ // mcpd refuses for MCP sessions: say so here instead of leaving it to the first failed call.
102
+ const tokens = (await import("../../mcpd/health.js")).tokenSyncCheck(env);
103
+ if (tokens) {
104
+ const mode = opts.sync ?? "ask";
105
+ let run = mode === "yes";
106
+ if (mode === "ask" && io.ask) {
107
+ io.out(tokens.text);
108
+ run = await confirm(io, "run turno mcp sync now?");
109
+ }
110
+ if (run) {
111
+ const { command } = await import("./mcp.js");
112
+ if ((await command.run(["sync"], io)) !== 0)
113
+ io.err("turno: turno mcp sync did not finish every profile; run it again once their sessions are closed");
114
+ }
115
+ else
116
+ io.out(`${tokens.text}; run: turno mcp sync`);
117
+ }
118
+ await refreshDaemonService(io);
78
119
  recordVersion(env);
79
120
  if (before && before !== now) {
80
121
  io.out(`turno ${before} -> ${now}`);
@@ -89,74 +130,126 @@ export function finishUpgrade(io) {
89
130
  io.out(`turno ${now} is set up`);
90
131
  return 0;
91
132
  }
133
+ /**
134
+ * The mcpd service runs the turno that installed it, and the old code keeps running until a
135
+ * restart: rewrite the service file for this version and restart it, when one is installed.
136
+ */
137
+ async function refreshDaemonService(io) {
138
+ const { installedBackend } = await import("../../mcpd/service.js");
139
+ const backend = await installedBackend(io.env);
140
+ if (!backend)
141
+ return;
142
+ io.out(`mcpd: rewriting the ${backend.noun} for turno ${packageInfo().version} and restarting it; open sessions reconnect on their next call`);
143
+ const { installDaemonService } = await import("./mcpd.js");
144
+ const code = await installDaemonService(io, { command: "upgrade --finish" });
145
+ if (code)
146
+ io.err("turno: mcpd was not restarted; run turno mcp daemon start");
147
+ }
92
148
  export const command = {
93
149
  summary: "update turno to the newest release (or check for one)",
94
150
  usage: USAGE,
95
- flags: ["--check", "--channel", "--to", "--dry-run", "--json", "--finish"],
96
- async run(args, io) {
97
- const p = parseFlags(args, { check: { type: "boolean" }, finish: { type: "boolean" }, channel: { type: "string" }, to: { type: "string" }, ...DRY_RUN, ...JSON_FLAG }, 0);
98
- if (bool(p, "finish"))
99
- return finishUpgrade(io);
100
- const pkg = packageInfo();
101
- const install = detectInstall();
102
- const channel = str(p, "channel") ?? "latest";
103
- const off = updateChecksOff(io.env);
104
- const fromRegistry = install.method !== "source" && install.method !== "unknown";
105
- if (bool(p, "check")) {
106
- if (pkg.private || !fromRegistry) {
107
- const why = pkg.private ? "this copy is not published to a registry" : `installed from ${install.method}`;
108
- if (bool(p, "json"))
109
- printJson(io.out, { current: pkg.version, latest: null, method: install.method, note: why });
110
- else
111
- io.out(`turno ${pkg.version} (${why}; turno upgrade pulls the source)`);
112
- return 0;
113
- }
114
- const s = await fetchLatest(io.env, channel);
115
- const newer = s.latest && compareVersions(s.latest, pkg.version) > 0;
151
+ flags: ["--check", "--channel", "--to", "--dry-run", "--json", "--finish", "--yes"],
152
+ json: CHECK_JSON,
153
+ run: (args, io) => runUpgrade(args, io),
154
+ };
155
+ /** `turno upgrade`; `deps.install` stands for how this turno was installed, for tests. */
156
+ export async function runUpgrade(args, io, deps = {}) {
157
+ const p = parseFlags(args, {
158
+ check: { type: "boolean" },
159
+ finish: { type: "boolean" },
160
+ yes: { type: "boolean", short: "y" },
161
+ channel: { type: "string" },
162
+ to: { type: "string" },
163
+ ...DRY_RUN,
164
+ ...JSON_FLAG,
165
+ }, 0);
166
+ const yes = bool(p, "yes");
167
+ if (bool(p, "finish"))
168
+ return finishUpgrade(io, { sync: yes ? "yes" : "ask" });
169
+ const to = str(p, "to");
170
+ if (to !== undefined && !isSemver(to))
171
+ fail(`--to needs a version like 1.2.3 (got "${to}")`);
172
+ if (!/^[a-z][a-z0-9-]{0,63}$/.test(str(p, "channel") ?? "latest"))
173
+ fail("--channel needs a dist-tag such as latest or next");
174
+ const pkg = packageInfo();
175
+ const install = deps.install ?? detectInstall();
176
+ const channel = str(p, "channel") ?? "latest";
177
+ const off = updateChecksOff(io.env);
178
+ const fromRegistry = install.method !== "source" && install.method !== "unknown";
179
+ if (bool(p, "check")) {
180
+ if (pkg.private || !fromRegistry) {
181
+ const why = pkg.private ? "this copy is not published to a registry" : `installed from ${install.method}`;
116
182
  if (bool(p, "json"))
117
- printJson(io.out, { current: pkg.version, latest: s.latest ?? null, channel, method: install.method, updateAvailable: Boolean(newer), error: s.error ?? null });
118
- else if (s.error)
119
- io.out(`could not reach the registry: ${s.error}`);
183
+ emit(io, p, CHECK_JSON, { current: pkg.version, latest: null, method: install.method, note: why });
120
184
  else
121
- io.out(newer ? `turno ${s.latest} is available (you have ${pkg.version}): turno upgrade` : `turno ${pkg.version} is the newest on ${channel}`);
122
- return s.error ? 1 : 0;
123
- }
124
- if (fromRegistry && off === "this copy is not published to a registry")
125
- fail("this copy is not published to a registry");
126
- let spec = str(p, "to") ?? channel;
127
- if (fromRegistry && !str(p, "to")) {
128
- const s = await fetchLatest(io.env, channel);
129
- if (s.error)
130
- fail(`could not reach the registry: ${s.error}`);
131
- if (s.latest && compareVersions(s.latest, pkg.version) <= 0) {
132
- io.out(`turno ${pkg.version} is already the newest on ${channel}`);
133
- return 0;
134
- }
135
- spec = s.latest ?? channel;
185
+ io.out(`turno ${pkg.version} (${why}; turno upgrade pulls the source)`);
186
+ return 0;
136
187
  }
137
- const steps = upgradeCommand(install, pkg.name, spec);
138
- if (!steps)
139
- return fail(`cannot tell how turno was installed (${install.root}); reinstall it with your package manager`);
140
- for (const step of steps) {
141
- io.out(`$ ${step.join(" ")}`);
142
- if (bool(p, "dry-run"))
143
- continue;
144
- const r = spawnSync(step[0], step.slice(1), { stdio: "inherit", env: io.env });
145
- if (r.status !== 0) {
146
- io.err(`turno: ${step[0]} failed (exit ${r.status ?? r.signal}); nothing else was changed`);
147
- return 1;
148
- }
188
+ const s = await fetchLatest(io.env, channel);
189
+ const newer = s.latest && compareVersions(s.latest, pkg.version) > 0;
190
+ if (bool(p, "json"))
191
+ emit(io, p, CHECK_JSON, {
192
+ current: pkg.version,
193
+ latest: s.latest ?? null,
194
+ channel,
195
+ method: install.method,
196
+ updateAvailable: Boolean(newer),
197
+ error: s.error ?? null,
198
+ });
199
+ else if (s.error)
200
+ io.out(`could not reach the registry: ${s.error}`);
201
+ else
202
+ io.out(newer
203
+ ? `turno ${s.latest} is available (you have ${pkg.version}): turno upgrade`
204
+ : `turno ${pkg.version} is the newest on ${channel}`);
205
+ return s.error ? 1 : 0;
206
+ }
207
+ if (isOneOff(install.method)) {
208
+ // A copy in npx's (pnpm dlx's, bunx's) cache: nothing to replace, the runner fetches releases.
209
+ const once = ONE_OFF_RUNNERS[install.method];
210
+ io.out(`turno runs from ${once.runner}'s cache for this run: \`${once.latest}\` runs the newest release.`);
211
+ io.out(`To keep turno, install it: ${once.install}`);
212
+ return 0;
213
+ }
214
+ if (fromRegistry && off === "this copy is not published to a registry")
215
+ fail("this copy is not published to a registry");
216
+ let spec = str(p, "to") ?? channel;
217
+ if (fromRegistry && !str(p, "to")) {
218
+ const s = await fetchLatest(io.env, channel);
219
+ if (s.error)
220
+ fail(`could not reach the registry: ${s.error}`);
221
+ if (s.latest && compareVersions(s.latest, pkg.version) <= 0) {
222
+ io.out(`turno ${pkg.version} is already the newest on ${channel}`);
223
+ return 0;
149
224
  }
225
+ spec = s.latest ?? channel;
226
+ }
227
+ // Whatever reaches the package manager is a plain version or a dist-tag, never a URL or range.
228
+ if (!isSemver(spec) && !/^[a-z][a-z0-9-]{0,63}$/.test(spec))
229
+ fail(`refusing to install "${spec}": not a version`);
230
+ const steps = upgradeCommand(install, pkg.name, spec);
231
+ if (!steps)
232
+ return fail(`cannot tell how turno was installed (${install.root}); reinstall it with your package manager`);
233
+ for (const step of steps) {
234
+ io.out(`$ ${step.join(" ")}`);
150
235
  if (bool(p, "dry-run"))
151
- return 0;
152
- // The new files are in place: let the new version finish its own upgrade.
153
- const self = install.method === "source" ? process.argv[1] : findOnPath("turno", io.env);
154
- if (!self) {
155
- io.out("upgraded; run `turno upgrade --finish` to rewrite the launchers");
156
- return 0;
236
+ continue;
237
+ const r = spawnSync(step[0], step.slice(1), { stdio: "inherit", env: io.env });
238
+ if (r.status !== 0) {
239
+ io.err(`turno: ${step[0]} failed (exit ${r.status ?? r.signal}); nothing else was changed`);
240
+ return 1;
157
241
  }
158
- const r = spawnSync(install.method === "source" ? process.execPath : self, install.method === "source" ? [self, "upgrade", "--finish"] : ["upgrade", "--finish"], { stdio: "inherit", env: io.env });
159
- return r.status ?? 1;
160
- },
161
- };
242
+ }
243
+ if (bool(p, "dry-run"))
244
+ return 0;
245
+ // The new files are in place: let the new version finish its own upgrade.
246
+ const self = install.method === "source" ? process.argv[1] : findOnPath("turno", io.env);
247
+ if (!self) {
248
+ io.out("upgraded; run `turno upgrade --finish` to rewrite the launchers");
249
+ return 0;
250
+ }
251
+ const finish = ["upgrade", "--finish", ...(yes ? ["--yes"] : [])];
252
+ const r = spawnSync(install.method === "source" ? process.execPath : self, install.method === "source" ? [self, ...finish] : finish, { stdio: "inherit", env: io.env });
253
+ return r.status ?? 1;
254
+ }
162
255
  //# sourceMappingURL=upgrade.js.map
@@ -1,52 +1,111 @@
1
1
  import { execFile } from "node:child_process";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { 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
+ import { isRecord, readState } from "../../core/state-file.js";
11
+ /** Why `claude auth status` gave no answer, in a few words for the account column. */
12
+ function authFailure(err, stdout, stderr) {
13
+ if (err?.code === "ENOENT")
14
+ return "claude is not on PATH";
15
+ if (err?.killed || err?.signal === "SIGTERM")
16
+ return "claude auth status timed out";
17
+ const line = (stderr || stdout).trim().split("\n")[0]?.trim();
18
+ if (err && typeof err.code === "number")
19
+ return `claude auth status exited with ${err.code}${line ? `: ${line.slice(0, 120)}` : ""}`;
20
+ return "claude auth status gave no JSON";
21
+ }
22
+ /** Reuse an answer of `claude auth status` this long while the profile's login files stay the same (seconds). */
23
+ const AUTH_TTL = 300;
24
+ /**
25
+ * The files a login or logout rewrites in a profile folder (the account in .claude.json, and
26
+ * .credentials.json where there is no Keychain), as a key for the cached answer.
27
+ */
28
+ function authFingerprint(dir) {
29
+ return [".claude.json", ".credentials.json"]
30
+ .map((f) => {
31
+ try {
32
+ const st = statSync(join(dir, f));
33
+ return `${st.ino}:${st.size}:${st.mtimeMs}`;
34
+ }
35
+ catch {
36
+ return "-";
37
+ }
38
+ })
39
+ .join("|");
40
+ }
41
+ function recordPlan(profile, s, env) {
42
+ if (!s.loggedIn || !s.subscriptionType)
43
+ return;
44
+ try {
45
+ writePrivateFile(join(paths(env).planDir, profile), `${s.subscriptionType}\n`, env);
46
+ }
47
+ catch {
48
+ // the plan file is a cache for the status line
49
+ }
50
+ }
9
51
  /**
10
52
  * 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.
53
+ * plan in the state plan dir, where the status line reads it. On failure `why` says what went
54
+ * wrong (claude missing, a timeout, an error line), so callers never show a bare "?".
55
+ *
56
+ * An answer is kept for AUTH_TTL seconds in the state cache, keyed by the profile's login files,
57
+ * so `turno`, `turno status` and `turno profile list` do not start one claude per profile on
58
+ * every run; logging in or out changes those files and asks again. Failures are not kept.
12
59
  */
13
- export function authStatus(profile, env = process.env) {
60
+ function authStatusResult(profile, env = process.env) {
61
+ const dir = profileDir(profile, env);
62
+ const cacheFile = join(paths(env).state, "cache", `auth-${profile}.json`);
63
+ const now = Date.now() / 1000;
64
+ const cached = readJsonFile(cacheFile);
65
+ if (isObject(cached) &&
66
+ isObject(cached.status) &&
67
+ cached.key === authFingerprint(dir) &&
68
+ typeof cached.at === "number" &&
69
+ now >= cached.at &&
70
+ now - cached.at < AUTH_TTL) {
71
+ const s = cached.status;
72
+ recordPlan(profile, s, env);
73
+ return Promise.resolve({ status: s });
74
+ }
14
75
  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) => {
76
+ execFile("claude", ["auth", "status", "--json"], { env: { ...env, CLAUDE_CONFIG_DIR: dir }, timeout: 20_000, encoding: "utf8" }, (err, stdout, stderr) => {
16
77
  let s;
17
78
  try {
18
79
  s = JSON.parse(stdout);
19
80
  }
20
81
  catch {
21
- resolve(undefined);
82
+ resolve({ why: authFailure(err, stdout ?? "", stderr ?? "") });
22
83
  return;
23
84
  }
24
85
  if (!s || typeof s !== "object") {
25
- resolve(undefined);
86
+ resolve({ why: authFailure(err, stdout ?? "", stderr ?? "") });
26
87
  return;
27
88
  }
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
- }
89
+ recordPlan(profile, s, env);
90
+ try {
91
+ // Keyed after the call, so a claude that touches its own files still finds the entry.
92
+ writePrivateFile(cacheFile, JSON.stringify({ key: authFingerprint(dir), at: Math.trunc(now), status: s }), env);
37
93
  }
38
- resolve(s);
94
+ catch {
95
+ // without the cache the next run asks claude again
96
+ }
97
+ resolve({ status: s });
39
98
  });
40
99
  });
41
100
  }
101
+ /** `claude auth status --json` of a profile, or undefined when it fails (authStatusResult says why). */
102
+ export async function authStatus(profile, env = process.env) {
103
+ return (await authStatusResult(profile, env)).status;
104
+ }
105
+ /** The status line's usage snapshot: its windows are read field by field, so the shape check is light. */
106
+ const isSnapshot = (v) => isRecord(v) && (v.rate_limits === undefined || isRecord(v.rate_limits));
42
107
  function readSnapshot(file) {
43
- try {
44
- const v = JSON.parse(readFileSync(file, "utf8"));
45
- return v && typeof v === "object" ? v : undefined;
46
- }
47
- catch {
48
- return undefined;
49
- }
108
+ return readState(file, isSnapshot);
50
109
  }
51
110
  /** The newer of the snapshot in the state dir and the one the bash tool's status line wrote. */
52
111
  export function usageSnapshot(profile, env = process.env) {
@@ -66,11 +125,7 @@ export function shortTime(epochSeconds) {
66
125
  const d = new Date(epochSeconds * 1000);
67
126
  return `${DAYS[d.getDay()]} ${pad2(d.getDate())} ${pad2(d.getHours())}:${pad2(d.getMinutes())}`;
68
127
  }
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) {
128
+ function resetText(ts, now = Date.now() / 1000) {
74
129
  const d = Math.floor(ts - now);
75
130
  if (d <= 0)
76
131
  return "already reset";
@@ -79,7 +134,7 @@ export function resetText(ts, now = Date.now() / 1000) {
79
134
  const rel = h >= 24 ? `${Math.floor(h / 24)}d ${h % 24}h` : h ? `${h}h${pad2(m)}m` : `${m}m`;
80
135
  return `resets in ${rel} (${shortTime(ts)})`;
81
136
  }
82
- export function agoText(ts, now = Date.now() / 1000) {
137
+ function agoText(ts, now = Date.now() / 1000) {
83
138
  const d = Math.floor(now - ts);
84
139
  if (d < 60)
85
140
  return "seconds ago";
@@ -90,30 +145,36 @@ export function agoText(ts, now = Date.now() / 1000) {
90
145
  return `${Math.floor(d / 86400)} d ago`;
91
146
  }
92
147
  export async function account(profile, env) {
93
- const s = await authStatus(profile, env);
148
+ const { status: s, why } = await authStatusResult(profile, env);
94
149
  if (!s)
95
- return { email: "?", plan: "?" };
150
+ return { email: "?", plan: "", why: why ?? "claude auth status failed" };
96
151
  if (!s.loggedIn)
97
152
  return { email: "not logged in", plan: "" };
98
153
  return { email: s.email || "?", plan: s.subscriptionType || s.authMethod || "?" };
99
154
  }
100
- export function renderUsage(profiles, accounts, io) {
101
- const now = Date.now() / 1000;
155
+ /** Cells of the usage bars. */
156
+ const BAR_CELLS = 20;
157
+ /**
158
+ * The usage screen of `turno limit show`: each profile as its pill with the account, then a bar
159
+ * per window with its reset time, the exhausted mark and how old the data is. The same layout
160
+ * comes out as plain text in a pipe. `colors` holds the profiles of config.toml, for the pills.
161
+ */
162
+ export function renderUsage(profiles, accounts, io, opts = {}) {
163
+ const now = opts.now ?? Date.now() / 1000;
164
+ const s = style(io);
102
165
  const out = [];
103
166
  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
- }
167
+ const { email, plan, why } = accounts[p] ?? { email: "?", plan: "" };
168
+ const pill = s.profile(p, opts.colors ? profileColor(opts.colors, p) : undefined);
169
+ const who = why
170
+ ? `${s.warn("account unknown")}${s.muted(` (${why})`)}`
171
+ : email === "not logged in"
172
+ ? s.warn(email)
173
+ : `${email}${plan ? s.muted(` · ${plan}`) : ""}`;
174
+ out.push(s.wrap(`${pill} `, who));
110
175
  const data = usageSnapshot(p, io.env);
111
176
  const limits = data.rate_limits ?? {};
112
177
  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
178
  for (const [key, label] of [
118
179
  ["five_hour", "5 hours"],
119
180
  ["seven_day", "week"],
@@ -125,11 +186,23 @@ export function renderUsage(profiles, accounts, io) {
125
186
  const reset = typeof w.resets_at === "number" ? w.resets_at : undefined;
126
187
  if (reset && reset < now)
127
188
  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) : ""}`);
189
+ const when = reset ? resetText(reset, now) : "";
190
+ out.push(s
191
+ .wrap(` ${s.muted(label.padEnd(7))} ${s.bar(pct, BAR_CELLS)} `, pct >= 100 ? s.err(`used up, ${when}`) : s.muted(when))
192
+ .trimEnd());
193
+ }
194
+ const exhausted = exhaustedUntil(p, io.env);
195
+ if (exhausted !== undefined && exhausted > now) {
196
+ out.push(s.note("err", `${s.err(`exhausted until ${shortTime(exhausted)}`)}${s.muted(": its projects open with the fallback, if one is set")}`));
197
+ }
198
+ if (!hasLimits) {
199
+ const why = plan === "team"
200
+ ? "the Team plan does not report these limits"
201
+ : "shows up once a session of this account gets a response";
202
+ out.push(s.muted(` no usage data yet: ${why}`));
130
203
  }
131
204
  if (hasLimits && typeof data.updated_at === "number")
132
- out.push(paint(io, ` data from ${agoText(data.updated_at, now)}`, "2"));
205
+ out.push(s.muted(` data from ${agoText(data.updated_at, now)}`));
133
206
  out.push("");
134
207
  }
135
208
  return `${out.join("\n").trimEnd()}\n`;
@@ -144,16 +217,17 @@ export const command = {
144
217
  ].join("\n"),
145
218
  async run(args, io) {
146
219
  const watch = args.includes("--watch");
147
- const profiles = listProfiles(loadConfig(io.env), io.env, "claude");
220
+ const config = loadConfig(io.env);
221
+ const profiles = listProfiles(config, io.env, "claude");
148
222
  const list = await Promise.all(profiles.map((p) => account(p, io.env)));
149
223
  const accounts = Object.fromEntries(profiles.map((p, i) => [p, list[i]]));
150
224
  if (!watch) {
151
- io.out(renderUsage(profiles, accounts, io).trimEnd());
225
+ io.out(renderUsage(profiles, accounts, io, { colors: config.profiles }).trimEnd());
152
226
  return 0;
153
227
  }
154
228
  return new Promise((resolve) => {
155
229
  const draw = () => {
156
- io.out(`\x1b[2J\x1b[H${renderUsage(profiles, accounts, io)}\n(refreshes every 30 s · Ctrl+C to quit)`);
230
+ 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
231
  };
158
232
  draw();
159
233
  const timer = setInterval(draw, 30_000);
@@ -1,23 +1,37 @@
1
1
  import { tildify } from "../../core/paths.js";
2
2
  import { availableUpdate } from "../../core/update.js";
3
- import { detectInstall, packageInfo } from "../../core/version.js";
4
- import { JSON_FLAG, bool, parseFlags, printJson } from "../args.js";
3
+ import { ONE_OFF_RUNNERS, detectInstall, isOneOff, packageInfo } from "../../core/version.js";
4
+ import { JSON_FLAG, bool, flagsOf, parseFlags } from "../args.js";
5
+ import { emit, jsonOutput } from "../output.js";
6
+ const JSON_OUT = jsonOutput(["name", "version", "node", "method", "path", "latest"]);
5
7
  export const command = {
6
8
  summary: "the turno version, how it was installed, and whether a newer one is known",
7
- usage: "Usage: turno version [--json]\n\nturno --version prints only the number.",
8
- flags: ["--json"],
9
+ usage: "Usage: turno version [--json]\n\nturno --version prints only the number.\n\nExamples:\n $ turno version\n $ turno version --json",
10
+ flags: flagsOf(JSON_FLAG),
11
+ json: JSON_OUT,
9
12
  async run(args, io) {
10
13
  const p = parseFlags(args, JSON_FLAG, 0);
11
14
  const pkg = packageInfo();
12
15
  const install = detectInstall();
13
16
  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 };
17
+ // npx, pnpm dlx and bunx run a temporary copy from their cache: upgrade and launchers must not rely on it.
18
+ const once = isOneOff(install.method) ? ONE_OFF_RUNNERS[install.method] : undefined;
19
+ const data = {
20
+ name: pkg.name,
21
+ version: pkg.version,
22
+ node: process.versions.node,
23
+ method: install.method,
24
+ path: tildify(install.root, io.env),
25
+ latest: latest ?? null,
26
+ };
15
27
  if (bool(p, "json")) {
16
- printJson(io.out, data);
28
+ emit(io, p, JSON_OUT, data);
17
29
  return 0;
18
30
  }
19
31
  io.out(`turno ${pkg.version}`);
20
- io.out(` installed with ${install.method} at ${data.path}`);
32
+ io.out(once
33
+ ? ` a temporary copy in ${once.runner}'s cache (${data.path}); install it with: ${once.install}`
34
+ : ` installed with ${install.method} at ${data.path}`);
21
35
  io.out(` node ${data.node}`);
22
36
  if (latest)
23
37
  io.out(` ${latest} is available: turno upgrade`);