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,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,28 +176,34 @@ 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
209
  return execFileSync("git", ["--no-optional-locks", "-C", cwd, ...args], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
@@ -150,28 +212,88 @@ function gitBranch(cwd) {
150
212
  return "";
151
213
  }
152
214
  };
153
- return git(["branch", "--show-current"]) || git(["rev-parse", "--short", "HEAD"]); // detached HEAD: short commit
215
+ return git(["branch", "--show-current"]) || git(["rev-parse", "--short", "HEAD"]);
154
216
  }
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;
217
+ /**
218
+ * The branch of the repository holding `cwd`, read from its HEAD file (worktrees and submodules
219
+ * through `gitdir:`), or a short commit on a detached HEAD. Only an unusual HEAD runs git.
220
+ */
221
+ export function gitBranch(cwd) {
222
+ if (!cwd || !existsSync(cwd))
223
+ return "";
224
+ let dir = resolve(cwd);
225
+ for (;;) {
226
+ const dotgit = join(dir, ".git");
227
+ let isFile;
228
+ try {
229
+ isFile = statSync(dotgit).isFile();
230
+ }
231
+ catch {
232
+ /* not here */
233
+ }
234
+ if (isFile !== undefined) {
235
+ let gitdir = dotgit;
236
+ try {
237
+ if (isFile) {
238
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, "utf8"));
239
+ if (!m)
240
+ return gitSpawn(cwd);
241
+ gitdir = resolve(dir, m[1]);
242
+ }
243
+ const head = readFileSync(join(gitdir, "HEAD"), "utf8").trim();
244
+ const ref = /^ref:\s*refs\/heads\/(.+)$/.exec(head);
245
+ if (ref)
246
+ return ref[1];
247
+ if (/^[0-9a-f]{40}([0-9a-f]{24})?$/.test(head))
248
+ return head.slice(0, 7);
249
+ }
250
+ catch {
251
+ /* fall back to git */
252
+ }
253
+ return gitSpawn(cwd);
254
+ }
255
+ const parent = dirname(dir);
256
+ if (parent === dir)
257
+ return "";
258
+ dir = parent;
165
259
  }
166
- catch {
167
- /* no lock */
260
+ }
261
+ function sessionCost(cache, sid, transcript, now, jobs) {
262
+ if (!sid || !transcript)
263
+ return undefined;
264
+ const out = join(cache, `cost-${sid}.json`);
265
+ const raw = readJsonFile(out);
266
+ const data = isObj(raw) && num(raw.total) !== undefined
267
+ ? {
268
+ total: num(raw.total),
269
+ sub: num(raw.sub) ?? 0,
270
+ unknown: Array.isArray(raw.unknown) ? raw.unknown.filter((m) => typeof m === "string") : [],
271
+ v: raw.v,
272
+ updated_at: num(raw.updated_at) ?? 0,
273
+ }
274
+ : undefined;
275
+ const stale = !data || data.v !== 2 || now - data.updated_at > 60;
276
+ if (stale) {
277
+ const job = lockedJob(`${out}.lock`, 600, now, ["--cost", transcript, out]);
278
+ if (job)
279
+ jobs.push(job);
168
280
  }
169
- if (stale && !locked) {
170
- mkdirSync(cache, { recursive: true });
171
- closeSync(openSync(lock, "w"));
172
- background(["--cost", transcript, out]);
281
+ return data && data.v === 2 ? { total: data.total, sub: data.sub, unknown: data.unknown } : undefined;
282
+ }
283
+ /** True when the agents were synced to the gateway (`mcp sync`) and its last check failed. */
284
+ function gatewayDown(p, cache, now, jobs) {
285
+ const managed = readJsonFile(p.mcpdManaged);
286
+ if (!isObj(managed) || !Object.values(managed).some((v) => Array.isArray(v) && v.length))
287
+ return false;
288
+ const file = join(cache, "mcpd-health.json");
289
+ const raw = readJsonFile(file);
290
+ const at = isObj(raw) ? (num(raw.checked_at) ?? 0) : 0;
291
+ if (now - at > HEALTH_EVERY) {
292
+ const job = lockedJob(`${file}.lock`, 30, now, ["--health", file]);
293
+ if (job)
294
+ jobs.push(job);
173
295
  }
174
- return data ? { total: data.total, sub: data.sub } : undefined;
296
+ return isObj(raw) && raw.ok === false && now - at < HEALTH_TRUST;
175
297
  }
176
298
  export function useNerd(config, env) {
177
299
  if (config.icons === "nerd")
@@ -180,47 +302,71 @@ export function useNerd(config, env) {
180
302
  return false;
181
303
  return nerdHere(env, config.nerdTerminals);
182
304
  }
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
- }
305
+ const FALLBACK_CONFIG = {
306
+ icons: "auto",
307
+ nerdTerminals: [],
308
+ updateCheck: true,
309
+ profiles: {},
310
+ agents: {},
311
+ projects: [],
312
+ open: { chromeDir: "" },
313
+ mcpd: { port: 47821, callLog: true, idleUnderPressure: 300 },
314
+ };
315
+ /**
316
+ * Everything the line shows, from the stdin payload and the state dir. Each piece is computed on
317
+ * its own: a bad cache file, a full disk or a broken repository leaves that piece empty and the
318
+ * rest of the line intact. Background workers are queued on `jobs`, not started.
319
+ */
320
+ export function collect(payload, env, now = Date.now() / 1000, jobs = []) {
321
+ const data = sanitize(payload);
322
+ const config = safe(() => loadConfig(env), FALLBACK_CONFIG);
191
323
  const p = paths(env);
192
324
  const cache = join(p.state, "cache");
193
- const account = profileFromConfigDir(env.CLAUDE_CONFIG_DIR, config, env) ?? "";
325
+ const account = safe(() => profileFromConfigDir(env.CLAUDE_CONFIG_DIR, config, env) ?? "", "");
194
326
  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: "" };
327
+ const sid = sessionId(data.session_id);
328
+ const own = data.rate_limits ?? {};
197
329
  const input = {
198
330
  data,
199
331
  now,
200
- nerd: useNerd(config, env),
332
+ nerd: safe(() => useNerd(config, env), false),
201
333
  compact: Number(env.COLUMNS || 120) < 100,
202
334
  account,
203
- pill: pillColor(config, account),
204
- plan: account ? planOf(join(p.planDir, account)) : "",
205
- limits,
206
- chosen,
207
- assigned,
208
- branch: gitBranch(cwd),
335
+ pill: safe(() => pillColor(config, account), PILL_DEFAULTS[0]),
336
+ plan: "",
337
+ limits: account ? own : {},
338
+ chosen: "",
339
+ assigned: "",
340
+ branch: safe(() => gitBranch(cwd), ""),
209
341
  };
210
342
  if (account) {
211
- const t = turnHistory(cache, data.session_id, data.prompt_id, limits.five_hour);
343
+ input.limits = safe(() => accountLimits(join(p.usageDir, `${account}.json`), cache, sid, own, now), own);
344
+ input.plan = safe(() => planOf(join(p.planDir, account), now, jobs), "");
345
+ Object.assign(input, safe(() => resolveCached(cwd, config, env, p, cache, now), { chosen: "", assigned: "" }));
346
+ const t = safe(() => turnHistory(cache, sid, data.prompt_id, input.limits.five_hour), undefined);
212
347
  if (t !== undefined)
213
348
  input.turnsLeft = t;
214
- const mine = exhaustedUntil(account, env, now);
349
+ const mine = safe(() => exhaustedUntil(account, env, now), undefined);
215
350
  if (mine)
216
351
  input.exhaustedMine = mine;
217
- const theirs = assigned ? exhaustedUntil(assigned, env, now) : undefined;
352
+ const theirs = input.assigned ? safe(() => exhaustedUntil(input.assigned, env, now), undefined) : undefined;
218
353
  if (theirs)
219
354
  input.exhaustedAssigned = theirs;
220
355
  }
221
- const cost = sessionCost(cache, data.session_id, data.transcript_path, now);
222
- if (cost)
223
- input.cost = cost;
356
+ const cost = safe(() => sessionCost(cache, sid, data.transcript_path, now, jobs), undefined);
357
+ if (cost && cost.unknown.length) {
358
+ // Part of the conversation has no price: Claude Code's own figure, or "$?", never a low total.
359
+ const cc = data.cost?.total_cost_usd;
360
+ if (cc !== undefined)
361
+ input.cost = { total: cc, sub: 0 };
362
+ else
363
+ input.costUnknown = true;
364
+ }
365
+ else if (cost) {
366
+ input.cost = { total: cost.total, sub: cost.sub };
367
+ }
368
+ if (safe(() => gatewayDown(p, cache, now, jobs), false))
369
+ input.gatewayDown = true;
224
370
  return input;
225
371
  }
226
372
  async function readStdin() {
@@ -229,15 +375,41 @@ async function readStdin() {
229
375
  chunks.push(c);
230
376
  return Buffer.concat(chunks).toString("utf8");
231
377
  }
232
- async function planWorker(file) {
233
- const out = await new Promise((resolve) => execFile("claude", ["auth", "status", "--json"], { timeout: 20_000 }, (_e, stdout) => resolve(stdout ?? "")));
378
+ async function planWorker(file, env) {
379
+ const out = await new Promise((done) => execFile("claude", ["auth", "status", "--json"], { env, timeout: 20_000 }, (_e, stdout) => done(stdout ?? "")));
380
+ let plan;
234
381
  try {
235
- const plan = JSON.parse(out).subscriptionType ?? "";
236
- writeFileSync(file, plan);
382
+ plan = JSON.parse(out)?.subscriptionType;
237
383
  }
238
384
  catch {
239
- /* leave it empty; the next missing-file render retries */
385
+ /* not logged in or no answer */
240
386
  }
387
+ // An unknown plan leaves the empty file as is: its age schedules the next attempt.
388
+ if (typeof plan === "string" && plan.trim())
389
+ writeFileSync(file, plan.trim(), { mode: PRIVATE_FILE_MODE });
390
+ }
391
+ /** Whether the gateway answers HTTP at all; it refuses this unauthenticated request, which is enough. */
392
+ async function healthWorker(file, env) {
393
+ let port = 0;
394
+ try {
395
+ port = Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10);
396
+ }
397
+ catch {
398
+ /* not recorded */
399
+ }
400
+ if (!(port > 0))
401
+ port = safe(() => loadConfig(env).mcpd.port, FALLBACK_CONFIG.mcpd.port);
402
+ let ok = false;
403
+ try {
404
+ const res = await fetch(`http://127.0.0.1:${port}/status`, { signal: AbortSignal.timeout(1500) });
405
+ await res.body?.cancel();
406
+ ok = true;
407
+ }
408
+ catch {
409
+ ok = false;
410
+ }
411
+ save(file, { ok, port, checked_at: Math.trunc(Date.now() / 1000) });
412
+ rmSync(`${file}.lock`, { force: true });
241
413
  }
242
414
  export const command = {
243
415
  summary: "two-row status line for Claude Code",
@@ -252,23 +424,43 @@ export const command = {
252
424
  catch {
253
425
  /* not allowed */
254
426
  }
255
- const { computeCost } = await import("../../statusline/cost.js");
256
- computeCost(args[1], args[2]);
427
+ const { computeCost, pruneCache } = await import("../../statusline/cost.js");
428
+ try {
429
+ computeCost(args[1], args[2]);
430
+ }
431
+ catch {
432
+ /* the next render tries again */
433
+ }
434
+ safe(() => pruneCache(dirname(args[2])), 0);
257
435
  return 0;
258
436
  }
259
437
  if (args[0] === "--plan" && args[1]) {
260
- await planWorker(args[1]);
438
+ await planWorker(args[1], io.env).catch(() => undefined);
261
439
  return 0;
262
440
  }
441
+ if (args[0] === "--health" && args[1]) {
442
+ await healthWorker(args[1], io.env).catch(() => undefined);
443
+ return 0;
444
+ }
445
+ const jobs = [];
446
+ let line;
263
447
  try {
264
- const raw = await readStdin();
265
- const data = JSON.parse(raw || "{}");
266
- process.stdout.write(render(collect(data, io.env)));
448
+ let payload = {};
449
+ try {
450
+ payload = JSON.parse((await readStdin()) || "{}");
451
+ }
452
+ catch {
453
+ /* not JSON: draw what does not depend on it */
454
+ }
455
+ line = render(collect(payload, io.env, Date.now() / 1000, jobs));
267
456
  }
268
457
  catch (err) {
269
458
  // A minimal line beats an empty one.
270
- process.stdout.write(`turno statusline: ${err.name}: ${err.message}\n`);
459
+ line = `turno statusline: ${err.name}: ${err.message}\n`;
271
460
  }
461
+ await new Promise((done) => process.stdout.write(line, () => done()));
462
+ for (const job of jobs)
463
+ safe(job, undefined);
272
464
  return 0;
273
465
  },
274
466
  };