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,32 +1,55 @@
1
1
  import { execFile, execFileSync, spawn } from "node:child_process";
2
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
3
- import { dirname, join } from "node:path";
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, existsSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from "node:fs";
4
+ import { dirname, join, resolve } from "node:path";
4
5
  import { fileURLToPath } from "node:url";
5
6
  import { loadConfig } from "../../core/config.js";
6
7
  import { exhaustedUntil } from "../../core/exhausted.js";
7
- import { paths } from "../../core/paths.js";
8
+ import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE, paths } from "../../core/paths.js";
8
9
  import { profileFromConfigDir } from "../../core/profiles.js";
9
10
  import { resolveProfile } from "../../core/resolve.js";
10
11
  import { nerdHere } from "../../ui/terminal-id.js";
11
- import { NAMED_COLORS, PILL_DEFAULTS, render, turnsLeft } from "../../statusline/render.js";
12
+ import { isObj, limits as checkLimits, num, sanitize, sessionId, turns } from "../../statusline/input.js";
13
+ import { PILL_DEFAULTS, render, turnsLeft } from "../../statusline/render.js";
14
+ import { profileColor } from "../style.js";
15
+ import { readJsonFile } from "../../core/fsutil.js";
12
16
  const USAGE = `Usage:
13
17
  turno statusline render the status line from the JSON Claude Code sends on stdin
14
18
 
15
19
  Set it in settings.json:
16
20
  "statusLine": { "type": "command", "command": "turno statusline" }`;
17
- function readJson(file) {
21
+ /** Retry `claude auth status` this often while the plan is unknown (seconds). */
22
+ const PLAN_RETRY = 600;
23
+ /** Check the gateway this often, and trust a check this long (seconds). */
24
+ const HEALTH_EVERY = 60;
25
+ const HEALTH_TRUST = 300;
26
+ /** Run `fn`; on any error the status line leaves that field empty instead of failing. */
27
+ function safe(fn, fallback) {
18
28
  try {
19
- return JSON.parse(readFileSync(file, "utf8"));
29
+ return fn();
20
30
  }
21
31
  catch {
22
- return undefined;
32
+ return fallback;
23
33
  }
24
34
  }
25
- function writeJson(file, data) {
26
- mkdirSync(dirname(file), { recursive: true });
35
+ /** Atomic write that never throws: a full disk or read-only state dir only loses the cache. */
36
+ function save(file, data) {
27
37
  const tmp = `${file}.${process.pid}.tmp`;
28
- writeFileSync(tmp, JSON.stringify(data));
29
- renameSync(tmp, file);
38
+ try {
39
+ mkdirSync(dirname(file), { recursive: true, mode: PRIVATE_DIR_MODE });
40
+ writeFileSync(tmp, JSON.stringify(data), { mode: PRIVATE_FILE_MODE });
41
+ renameSync(tmp, file);
42
+ return true;
43
+ }
44
+ catch {
45
+ try {
46
+ rmSync(tmp, { force: true });
47
+ }
48
+ catch {
49
+ /* nothing to clean */
50
+ }
51
+ return false;
52
+ }
30
53
  }
31
54
  function stableJson(v) {
32
55
  if (Array.isArray(v))
@@ -52,64 +75,97 @@ function background(args) {
52
75
  /* best effort */
53
76
  }
54
77
  }
55
- export function pillColor(config, account) {
56
- const c = config.profiles[account]?.color;
57
- if (typeof c === "number")
58
- return c;
59
- if (typeof c === "string") {
60
- if (/^\d+$/.test(c))
61
- return Number(c);
62
- if (NAMED_COLORS[c.toLowerCase()] !== undefined)
63
- return NAMED_COLORS[c.toLowerCase()];
78
+ /** Create `lock` and start the worker, unless a fresh lock says one is already running. */
79
+ function lockedJob(lock, ttl, now, args) {
80
+ try {
81
+ if (now - statSync(lock).mtimeMs / 1000 < ttl)
82
+ return undefined;
83
+ }
84
+ catch {
85
+ /* no lock */
64
86
  }
65
- const names = Object.keys(config.profiles);
66
- const idx = names.includes(account) ? names.indexOf(account) : [...account].reduce((a, ch) => a + ch.charCodeAt(0), 0);
67
- return PILL_DEFAULTS[idx % PILL_DEFAULTS.length];
87
+ return () => {
88
+ try {
89
+ mkdirSync(dirname(lock), { recursive: true, mode: PRIVATE_DIR_MODE });
90
+ closeSync(openSync(lock, "w", PRIVATE_FILE_MODE));
91
+ }
92
+ catch {
93
+ return; // without a lock every render would start a worker
94
+ }
95
+ background(args);
96
+ };
97
+ }
98
+ export function pillColor(config, account) {
99
+ return profileColor(config.profiles, account);
68
100
  }
69
101
  /**
70
102
  * The account's windows, the freshest any session has seen. Each session carries the values of
71
103
  * its own last response, so an idle one has stale data. A session only publishes when its values
72
104
  * change (a new response), so a quiet session redrawing never overwrites fresh data from another.
73
105
  */
74
- function accountLimits(usageFile, cache, sessionId, limits, now) {
106
+ function accountLimits(usageFile, cache, sid, limits, now) {
75
107
  let changedAt = 0;
76
- if (Object.keys(limits).length && sessionId) {
108
+ if (Object.keys(limits).length && sid) {
77
109
  const sig = stableJson(limits);
78
- const seenFile = join(cache, `rl-${sessionId}.json`);
79
- const seen = readJson(seenFile) ?? {};
110
+ const seenFile = join(cache, `rl-${sid}.json`);
111
+ const raw = readJsonFile(seenFile);
112
+ const seen = isObj(raw) ? raw : {};
80
113
  if (seen.sig !== sig) {
81
- changedAt = "sig" in seen ? now : 0; // the first time we cannot tell whether the data is new
82
- writeJson(seenFile, { sig, changed_at: changedAt });
114
+ changedAt = typeof seen.sig === "string" ? now : 0; // the first time we cannot tell whether the data is new
115
+ save(seenFile, { sig, changed_at: changedAt });
83
116
  if (changedAt)
84
- writeJson(usageFile, { rate_limits: limits, updated_at: Math.trunc(now) });
117
+ save(usageFile, { rate_limits: limits, updated_at: Math.trunc(now) });
85
118
  }
86
119
  else {
87
- changedAt = seen.changed_at ?? 0;
120
+ changedAt = num(seen.changed_at) ?? 0;
88
121
  }
89
122
  }
90
- const shared = readJson(usageFile);
91
- if (shared?.rate_limits && (shared.updated_at ?? 0) > changedAt)
92
- return shared.rate_limits;
123
+ const shared = readJsonFile(usageFile);
124
+ if (isObj(shared) && isObj(shared.rate_limits) && (num(shared.updated_at) ?? 0) > changedAt) {
125
+ const theirs = checkLimits(shared.rate_limits);
126
+ if (Object.keys(theirs).length)
127
+ return theirs;
128
+ }
93
129
  return limits;
94
130
  }
95
131
  const PLAN_NAMES = { max: "Max", pro: "Pro", team: "Team", enterprise: "Enterprise" };
96
- function planOf(file) {
97
- let p;
132
+ /**
133
+ * The plan recorded for the account. While it is unknown, an empty file marks the last attempt
134
+ * to ask `claude auth status`, and a new attempt starts once it is older than PLAN_RETRY.
135
+ */
136
+ function planOf(file, now, jobs) {
137
+ let plan = "";
138
+ let age = Number.POSITIVE_INFINITY;
98
139
  try {
99
- p = readFileSync(file, "utf8").trim();
140
+ plan = readFileSync(file, "utf8").trim();
141
+ age = now - statSync(file).mtimeMs / 1000;
100
142
  }
101
143
  catch {
102
- mkdirSync(dirname(file), { recursive: true });
103
- writeFileSync(file, ""); // only one render asks for it
104
- background(["--plan", file]);
105
- return "";
144
+ /* never asked */
145
+ }
146
+ if (plan)
147
+ return PLAN_NAMES[plan] ?? plan;
148
+ if (age > PLAN_RETRY) {
149
+ try {
150
+ mkdirSync(dirname(file), { recursive: true, mode: PRIVATE_DIR_MODE });
151
+ writeFileSync(file, "", { mode: PRIVATE_FILE_MODE }); // stamps the attempt, so only one render asks
152
+ }
153
+ catch {
154
+ return ""; // cannot stamp: do not start a worker on every render
155
+ }
156
+ jobs.push(() => background(["--plan", file]));
106
157
  }
107
- return PLAN_NAMES[p] ?? p;
158
+ return "";
159
+ }
160
+ /** Cache key of a folder: its path and the config it was resolved with. */
161
+ function resolveKey(cwd, configFile) {
162
+ const mtime = safe(() => statSync(configFile).mtimeMs, 0);
163
+ return createHash("sha1").update(`${cwd}\0${mtime}`).digest("hex").slice(0, 20);
108
164
  }
109
- function resolveCached(cwd, config, env, cache, now) {
165
+ function resolveCached(cwd, config, env, p, cache, now) {
110
166
  if (!cwd)
111
167
  return { chosen: "", assigned: "" };
112
- const file = join(cache, `resolve-${cwd.replace(/[^A-Za-z0-9]/g, "-").slice(-120)}`);
168
+ const file = join(cache, `resolve-${resolveKey(cwd, p.configFile)}`);
113
169
  try {
114
170
  if (now - statSync(file).mtimeMs / 1000 < 120) {
115
171
  const [chosen = "", assigned = ""] = readFileSync(file, "utf8").split("\x1f");
@@ -120,58 +176,128 @@ function resolveCached(cwd, config, env, cache, now) {
120
176
  /* compute */
121
177
  }
122
178
  const r = resolveProfile(cwd, config, env);
123
- mkdirSync(cache, { recursive: true });
124
- writeFileSync(file, `${r.chosen}\x1f${r.assigned}`);
179
+ try {
180
+ mkdirSync(cache, { recursive: true, mode: PRIVATE_DIR_MODE });
181
+ writeFileSync(file, `${r.chosen}\x1f${r.assigned}`, { mode: PRIVATE_FILE_MODE });
182
+ }
183
+ catch {
184
+ /* read-only: resolve again next time */
185
+ }
125
186
  return { chosen: r.chosen, assigned: r.assigned };
126
187
  }
127
- function turnHistory(cache, sessionId, promptId, five) {
128
- if (!sessionId || !five || five.used_percentage === undefined)
188
+ function turnHistory(cache, sid, promptId, five) {
189
+ if (!sid || !five || five.used_percentage === undefined)
129
190
  return undefined;
130
- const file = join(cache, `turns-${sessionId}.json`);
131
- const hist = readJson(file) ?? [];
191
+ const file = join(cache, `turns-${sid}.json`);
192
+ const hist = turns(readJsonFile(file));
132
193
  if (promptId) {
133
194
  const entry = [promptId, five.used_percentage, five.resets_at ?? null];
134
- if (hist.length && hist[hist.length - 1][0] === promptId)
135
- hist[hist.length - 1] = entry;
136
- else
137
- hist.push(entry);
138
- writeJson(file, hist.slice(-12));
195
+ const last = hist[hist.length - 1];
196
+ if (!last || last[0] !== promptId || last[1] !== entry[1] || last[2] !== entry[2]) {
197
+ if (last && last[0] === promptId)
198
+ hist[hist.length - 1] = entry;
199
+ else
200
+ hist.push(entry);
201
+ save(file, hist.slice(-12));
202
+ }
139
203
  }
140
- return turnsLeft(hist);
204
+ return turnsLeft(hist.slice(-12));
141
205
  }
142
- function gitBranch(cwd) {
143
- if (!cwd || !existsSync(cwd))
144
- return "";
206
+ function gitSpawn(cwd) {
145
207
  const git = (args) => {
146
208
  try {
147
- return execFileSync("git", ["--no-optional-locks", "-C", cwd, ...args], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
209
+ return execFileSync("git", ["--no-optional-locks", "-C", cwd, ...args], {
210
+ encoding: "utf8",
211
+ timeout: 3000,
212
+ stdio: ["ignore", "pipe", "ignore"],
213
+ }).trim();
148
214
  }
149
215
  catch {
150
216
  return "";
151
217
  }
152
218
  };
153
- return git(["branch", "--show-current"]) || git(["rev-parse", "--short", "HEAD"]); // detached HEAD: short commit
219
+ return git(["branch", "--show-current"]) || git(["rev-parse", "--short", "HEAD"]);
154
220
  }
155
- function sessionCost(cache, sessionId, transcript, now) {
156
- if (!sessionId || !transcript)
157
- return undefined;
158
- const out = join(cache, `cost-${sessionId}.json`);
159
- const data = readJson(out);
160
- const stale = !data || now - (data.updated_at ?? 0) > 60;
161
- const lock = `${out}.lock`;
162
- let locked = false;
163
- try {
164
- locked = now - statSync(lock).mtimeMs / 1000 < 600;
221
+ /**
222
+ * The branch of the repository holding `cwd`, read from its HEAD file (worktrees and submodules
223
+ * through `gitdir:`), or a short commit on a detached HEAD. Only an unusual HEAD runs git.
224
+ */
225
+ export function gitBranch(cwd) {
226
+ if (!cwd || !existsSync(cwd))
227
+ return "";
228
+ let dir = resolve(cwd);
229
+ for (;;) {
230
+ const dotgit = join(dir, ".git");
231
+ let isFile;
232
+ try {
233
+ isFile = statSync(dotgit).isFile();
234
+ }
235
+ catch {
236
+ /* not here */
237
+ }
238
+ if (isFile !== undefined) {
239
+ let gitdir = dotgit;
240
+ try {
241
+ if (isFile) {
242
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, "utf8"));
243
+ if (!m)
244
+ return gitSpawn(cwd);
245
+ gitdir = resolve(dir, m[1]);
246
+ }
247
+ const head = readFileSync(join(gitdir, "HEAD"), "utf8").trim();
248
+ const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head);
249
+ if (ref)
250
+ return ref[1];
251
+ if (/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head))
252
+ return head.slice(0, 7);
253
+ }
254
+ catch {
255
+ /* fall back to git */
256
+ }
257
+ return gitSpawn(cwd);
258
+ }
259
+ const parent = dirname(dir);
260
+ if (parent === dir)
261
+ return "";
262
+ dir = parent;
165
263
  }
166
- catch {
167
- /* no lock */
264
+ }
265
+ function sessionCost(cache, sid, transcript, now, jobs) {
266
+ if (!sid || !transcript)
267
+ return undefined;
268
+ const out = join(cache, `cost-${sid}.json`);
269
+ const raw = readJsonFile(out);
270
+ const data = isObj(raw) && num(raw.total) !== undefined
271
+ ? {
272
+ total: num(raw.total),
273
+ sub: num(raw.sub) ?? 0,
274
+ unknown: Array.isArray(raw.unknown) ? raw.unknown.filter((m) => typeof m === "string") : [],
275
+ v: raw.v,
276
+ updated_at: num(raw.updated_at) ?? 0,
277
+ }
278
+ : undefined;
279
+ const stale = !data || data.v !== 2 || now - data.updated_at > 60;
280
+ if (stale) {
281
+ const job = lockedJob(`${out}.lock`, 600, now, ["--cost", transcript, out]);
282
+ if (job)
283
+ jobs.push(job);
168
284
  }
169
- if (stale && !locked) {
170
- mkdirSync(cache, { recursive: true });
171
- closeSync(openSync(lock, "w"));
172
- background(["--cost", transcript, out]);
285
+ return data && data.v === 2 ? { total: data.total, sub: data.sub, unknown: data.unknown } : undefined;
286
+ }
287
+ /** True when the agents were synced to the gateway (`mcp sync`) and its last check failed. */
288
+ function gatewayDown(p, cache, now, jobs) {
289
+ const managed = readJsonFile(p.mcpdManaged);
290
+ if (!isObj(managed) || !Object.values(managed).some((v) => Array.isArray(v) && v.length))
291
+ return false;
292
+ const file = join(cache, "mcpd-health.json");
293
+ const raw = readJsonFile(file);
294
+ const at = isObj(raw) ? (num(raw.checked_at) ?? 0) : 0;
295
+ if (now - at > HEALTH_EVERY) {
296
+ const job = lockedJob(`${file}.lock`, 30, now, ["--health", file]);
297
+ if (job)
298
+ jobs.push(job);
173
299
  }
174
- return data ? { total: data.total, sub: data.sub } : undefined;
300
+ return isObj(raw) && raw.ok === false && now - at < HEALTH_TRUST;
175
301
  }
176
302
  export function useNerd(config, env) {
177
303
  if (config.icons === "nerd")
@@ -180,47 +306,72 @@ export function useNerd(config, env) {
180
306
  return false;
181
307
  return nerdHere(env, config.nerdTerminals);
182
308
  }
183
- export function collect(data, env, now = Date.now() / 1000) {
184
- let config;
185
- try {
186
- config = loadConfig(env);
187
- }
188
- catch {
189
- config = { icons: "auto", nerdTerminals: [], updateCheck: true, profiles: {}, agents: {}, projects: [], open: { chromeDir: "" }, mcpd: { port: 47821 } };
190
- }
309
+ const FALLBACK_CONFIG = {
310
+ icons: "auto",
311
+ nerdTerminals: [],
312
+ updateCheck: true,
313
+ hints: true,
314
+ profiles: {},
315
+ agents: {},
316
+ projects: [],
317
+ open: { chromeDir: "" },
318
+ mcpd: { port: 47821, callLog: true, idleUnderPressure: 300 },
319
+ };
320
+ /**
321
+ * Everything the line shows, from the stdin payload and the state dir. Each piece is computed on
322
+ * its own: a bad cache file, a full disk or a broken repository leaves that piece empty and the
323
+ * rest of the line intact. Background workers are queued on `jobs`, not started.
324
+ */
325
+ export function collect(payload, env, now = Date.now() / 1000, jobs = []) {
326
+ const data = sanitize(payload);
327
+ const config = safe(() => loadConfig(env), FALLBACK_CONFIG);
191
328
  const p = paths(env);
192
329
  const cache = join(p.state, "cache");
193
- const account = profileFromConfigDir(env.CLAUDE_CONFIG_DIR, config, env) ?? "";
330
+ const account = safe(() => profileFromConfigDir(env.CLAUDE_CONFIG_DIR, config, env) ?? "", "");
194
331
  const cwd = data.workspace?.current_dir ?? data.cwd ?? "";
195
- const limits = account ? accountLimits(join(p.usageDir, `${account}.json`), cache, data.session_id, data.rate_limits ?? {}, now) : {};
196
- const { chosen, assigned } = account ? resolveCached(cwd, config, env, cache, now) : { chosen: "", assigned: "" };
332
+ const sid = sessionId(data.session_id);
333
+ const own = data.rate_limits ?? {};
197
334
  const input = {
198
335
  data,
199
336
  now,
200
- nerd: useNerd(config, env),
337
+ nerd: safe(() => useNerd(config, env), false),
201
338
  compact: Number(env.COLUMNS || 120) < 100,
202
339
  account,
203
- pill: pillColor(config, account),
204
- plan: account ? planOf(join(p.planDir, account)) : "",
205
- limits,
206
- chosen,
207
- assigned,
208
- branch: gitBranch(cwd),
340
+ pill: safe(() => pillColor(config, account), PILL_DEFAULTS[0]),
341
+ plan: "",
342
+ limits: account ? own : {},
343
+ chosen: "",
344
+ assigned: "",
345
+ branch: safe(() => gitBranch(cwd), ""),
209
346
  };
210
347
  if (account) {
211
- const t = turnHistory(cache, data.session_id, data.prompt_id, limits.five_hour);
348
+ input.limits = safe(() => accountLimits(join(p.usageDir, `${account}.json`), cache, sid, own, now), own);
349
+ input.plan = safe(() => planOf(join(p.planDir, account), now, jobs), "");
350
+ Object.assign(input, safe(() => resolveCached(cwd, config, env, p, cache, now), { chosen: "", assigned: "" }));
351
+ const t = safe(() => turnHistory(cache, sid, data.prompt_id, input.limits.five_hour), undefined);
212
352
  if (t !== undefined)
213
353
  input.turnsLeft = t;
214
- const mine = exhaustedUntil(account, env, now);
354
+ const mine = safe(() => exhaustedUntil(account, env, now), undefined);
215
355
  if (mine)
216
356
  input.exhaustedMine = mine;
217
- const theirs = assigned ? exhaustedUntil(assigned, env, now) : undefined;
357
+ const theirs = input.assigned ? safe(() => exhaustedUntil(input.assigned, env, now), undefined) : undefined;
218
358
  if (theirs)
219
359
  input.exhaustedAssigned = theirs;
220
360
  }
221
- const cost = sessionCost(cache, data.session_id, data.transcript_path, now);
222
- if (cost)
223
- input.cost = cost;
361
+ const cost = safe(() => sessionCost(cache, sid, data.transcript_path, now, jobs), undefined);
362
+ if (cost && cost.unknown.length) {
363
+ // Part of the conversation has no price: Claude Code's own figure, or "$?", never a low total.
364
+ const cc = data.cost?.total_cost_usd;
365
+ if (cc !== undefined)
366
+ input.cost = { total: cc, sub: 0 };
367
+ else
368
+ input.costUnknown = true;
369
+ }
370
+ else if (cost) {
371
+ input.cost = { total: cost.total, sub: cost.sub };
372
+ }
373
+ if (safe(() => gatewayDown(p, cache, now, jobs), false))
374
+ input.gatewayDown = true;
224
375
  return input;
225
376
  }
226
377
  async function readStdin() {
@@ -229,15 +380,41 @@ async function readStdin() {
229
380
  chunks.push(c);
230
381
  return Buffer.concat(chunks).toString("utf8");
231
382
  }
232
- async function planWorker(file) {
233
- const out = await new Promise((resolve) => execFile("claude", ["auth", "status", "--json"], { timeout: 20_000 }, (_e, stdout) => resolve(stdout ?? "")));
383
+ async function planWorker(file, env) {
384
+ const out = await new Promise((done) => execFile("claude", ["auth", "status", "--json"], { env, timeout: 20_000 }, (_e, stdout) => done(stdout ?? "")));
385
+ let plan;
234
386
  try {
235
- const plan = JSON.parse(out).subscriptionType ?? "";
236
- writeFileSync(file, plan);
387
+ plan = JSON.parse(out)?.subscriptionType;
237
388
  }
238
389
  catch {
239
- /* leave it empty; the next missing-file render retries */
390
+ /* not logged in or no answer */
240
391
  }
392
+ // An unknown plan leaves the empty file as is: its age schedules the next attempt.
393
+ if (typeof plan === "string" && plan.trim())
394
+ writeFileSync(file, plan.trim(), { mode: PRIVATE_FILE_MODE });
395
+ }
396
+ /** Whether the gateway answers HTTP at all; it refuses this unauthenticated request, which is enough. */
397
+ async function healthWorker(file, env) {
398
+ let port = 0;
399
+ try {
400
+ port = Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10);
401
+ }
402
+ catch {
403
+ /* not recorded */
404
+ }
405
+ if (!(port > 0))
406
+ port = safe(() => loadConfig(env).mcpd.port, FALLBACK_CONFIG.mcpd.port);
407
+ let ok = false;
408
+ try {
409
+ const res = await fetch(`http://127.0.0.1:${port}/status`, { signal: AbortSignal.timeout(1500) });
410
+ await res.body?.cancel();
411
+ ok = true;
412
+ }
413
+ catch {
414
+ ok = false;
415
+ }
416
+ save(file, { ok, port, checked_at: Math.trunc(Date.now() / 1000) });
417
+ rmSync(`${file}.lock`, { force: true });
241
418
  }
242
419
  export const command = {
243
420
  summary: "two-row status line for Claude Code",
@@ -252,23 +429,43 @@ export const command = {
252
429
  catch {
253
430
  /* not allowed */
254
431
  }
255
- const { computeCost } = await import("../../statusline/cost.js");
256
- computeCost(args[1], args[2]);
432
+ const { computeCost, pruneCache } = await import("../../statusline/cost.js");
433
+ try {
434
+ computeCost(args[1], args[2]);
435
+ }
436
+ catch {
437
+ /* the next render tries again */
438
+ }
439
+ safe(() => pruneCache(dirname(args[2])), 0);
257
440
  return 0;
258
441
  }
259
442
  if (args[0] === "--plan" && args[1]) {
260
- await planWorker(args[1]);
443
+ await planWorker(args[1], io.env).catch(() => undefined);
261
444
  return 0;
262
445
  }
446
+ if (args[0] === "--health" && args[1]) {
447
+ await healthWorker(args[1], io.env).catch(() => undefined);
448
+ return 0;
449
+ }
450
+ const jobs = [];
451
+ let line;
263
452
  try {
264
- const raw = await readStdin();
265
- const data = JSON.parse(raw || "{}");
266
- process.stdout.write(render(collect(data, io.env)));
453
+ let payload = {};
454
+ try {
455
+ payload = JSON.parse((await readStdin()) || "{}");
456
+ }
457
+ catch {
458
+ /* not JSON: draw what does not depend on it */
459
+ }
460
+ line = render(collect(payload, io.env, Date.now() / 1000, jobs));
267
461
  }
268
462
  catch (err) {
269
463
  // A minimal line beats an empty one.
270
- process.stdout.write(`turno statusline: ${err.name}: ${err.message}\n`);
464
+ line = `turno statusline: ${err.name}: ${err.message}\n`;
271
465
  }
466
+ await new Promise((done) => process.stdout.write(line, () => done()));
467
+ for (const job of jobs)
468
+ safe(job, undefined);
272
469
  return 0;
273
470
  },
274
471
  };