turno-cli 0.0.0-stage → 0.1.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 (83) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/README.md +334 -2
  5. package/dist/accounts/audit.js +54 -0
  6. package/dist/accounts/builtin.js +214 -0
  7. package/dist/accounts/delegate.js +185 -0
  8. package/dist/accounts/registry.js +190 -0
  9. package/dist/agents/index.js +101 -0
  10. package/dist/agents/snippets.js +64 -0
  11. package/dist/cli/args.js +47 -0
  12. package/dist/cli/commands/accounts.js +216 -0
  13. package/dist/cli/commands/auto.js +44 -0
  14. package/dist/cli/commands/available.js +18 -0
  15. package/dist/cli/commands/browser.js +175 -0
  16. package/dist/cli/commands/complete.js +112 -0
  17. package/dist/cli/commands/completion.js +57 -0
  18. package/dist/cli/commands/config.js +168 -0
  19. package/dist/cli/commands/doctor.js +324 -0
  20. package/dist/cli/commands/exhausted.js +40 -0
  21. package/dist/cli/commands/handoff.js +118 -0
  22. package/dist/cli/commands/hook.js +63 -0
  23. package/dist/cli/commands/identity.js +114 -0
  24. package/dist/cli/commands/limit.js +102 -0
  25. package/dist/cli/commands/mcp.js +350 -0
  26. package/dist/cli/commands/mcpd.js +161 -0
  27. package/dist/cli/commands/migrate.js +176 -0
  28. package/dist/cli/commands/open.js +60 -0
  29. package/dist/cli/commands/profile.js +259 -0
  30. package/dist/cli/commands/resolve.js +23 -0
  31. package/dist/cli/commands/run.js +15 -0
  32. package/dist/cli/commands/secret.js +123 -0
  33. package/dist/cli/commands/session.js +36 -0
  34. package/dist/cli/commands/sessions.js +27 -0
  35. package/dist/cli/commands/setup.js +224 -0
  36. package/dist/cli/commands/status.js +101 -0
  37. package/dist/cli/commands/statusline.js +275 -0
  38. package/dist/cli/commands/ui.js +276 -0
  39. package/dist/cli/commands/undo.js +67 -0
  40. package/dist/cli/commands/update-check.js +22 -0
  41. package/dist/cli/commands/upgrade.js +162 -0
  42. package/dist/cli/commands/usage.js +167 -0
  43. package/dist/cli/commands/version.js +27 -0
  44. package/dist/cli/commands/which.js +28 -0
  45. package/dist/cli/group.js +50 -0
  46. package/dist/cli/io.js +22 -0
  47. package/dist/cli/launch.js +98 -0
  48. package/dist/cli/launchers.js +200 -0
  49. package/dist/cli/main.js +94 -0
  50. package/dist/cli/registry.js +77 -0
  51. package/dist/core/config-edit.js +42 -0
  52. package/dist/core/config.js +137 -0
  53. package/dist/core/exhausted.js +30 -0
  54. package/dist/core/journal.js +185 -0
  55. package/dist/core/manifest.js +177 -0
  56. package/dist/core/paths.js +54 -0
  57. package/dist/core/profiles.js +61 -0
  58. package/dist/core/ratelimit.js +39 -0
  59. package/dist/core/resolve.js +78 -0
  60. package/dist/core/secrets.js +44 -0
  61. package/dist/core/sessions.js +173 -0
  62. package/dist/core/toml-edit.js +152 -0
  63. package/dist/core/update.js +102 -0
  64. package/dist/core/version.js +103 -0
  65. package/dist/mcpd/cache.js +41 -0
  66. package/dist/mcpd/connectors.js +63 -0
  67. package/dist/mcpd/daemon.js +163 -0
  68. package/dist/mcpd/gateway.js +308 -0
  69. package/dist/mcpd/importer.js +160 -0
  70. package/dist/mcpd/instances.js +303 -0
  71. package/dist/mcpd/jsonrpc.js +19 -0
  72. package/dist/mcpd/launchd.js +86 -0
  73. package/dist/mcpd/peerpid.js +25 -0
  74. package/dist/mcpd/sync.js +208 -0
  75. package/dist/mcpd/upstream.js +232 -0
  76. package/dist/statusline/cost.js +135 -0
  77. package/dist/statusline/render.js +246 -0
  78. package/dist/ui/cmap.js +57 -0
  79. package/dist/ui/fonts.js +107 -0
  80. package/dist/ui/settings.js +69 -0
  81. package/dist/ui/terminal-id.js +30 -0
  82. package/dist/ui/terminals.js +163 -0
  83. package/package.json +69 -3
@@ -0,0 +1,224 @@
1
+ import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, renameSync, rmSync, rmdirSync, symlinkSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { adapter, agentHub, agentProfileDir } from "../../agents/index.js";
4
+ import { isValidProfileName, loadConfig } from "../../core/config.js";
5
+ import { setValue } from "../../core/toml-edit.js";
6
+ import { paths, profileDir, tildify } from "../../core/paths.js";
7
+ import { agentOf } from "../../core/profiles.js";
8
+ import { profileBusy } from "../../core/sessions.js";
9
+ import { fail } from "../io.js";
10
+ import { SHARED_DIRS, launcherName, turnoCommand, writeHelperLaunchers, writeLauncher } from "../launchers.js";
11
+ export { SHARED_DIRS };
12
+ /** Hub files shared by every profile (linked only when they exist in the hub). */
13
+ export const SHARED_FILES = ["CLAUDE.md", "settings.json", "keybindings.json", "statusline-command.sh", ".mcp.json"];
14
+ /**
15
+ * Owned by each account and never linked. history.jsonl cannot be a symlink: Claude Code
16
+ * ignores it unless it is a regular file with a single link.
17
+ */
18
+ export const PER_ACCOUNT = [
19
+ ".claude.json",
20
+ ".credentials.json",
21
+ "history.jsonl",
22
+ "backups",
23
+ "daemon",
24
+ "daemon.log",
25
+ "daemon-auth-cooldown",
26
+ "daemon-auth-status.json",
27
+ "daemon.lock",
28
+ "daemon.status.json",
29
+ "feedback",
30
+ "jobs",
31
+ "policy-limits.json",
32
+ "policy-limits.json.stamp.json",
33
+ "policy-limits.json.signature.json",
34
+ "remote-settings.json",
35
+ "remote-settings.json.signature.json",
36
+ "remote-settings.json.synced-at",
37
+ "mcp-needs-auth-cache.json",
38
+ "stats-cache.json",
39
+ "telemetry",
40
+ "shell-snapshots",
41
+ "debug",
42
+ ".last-cleanup",
43
+ ".last-update-result.json",
44
+ "computer-use.lock",
45
+ ];
46
+ /** Names a profile cannot take: every command, alias and legacy word. */
47
+ export const RESERVED = new Set([
48
+ "auto", "which", "resolve", "sessions", "usage", "exhausted", "available", "hook", "setup", "status",
49
+ "open", "migrate", "doctor", "statusline", "handoff", "mcp", "mcpd", "secret", "accounts", "browser", "ui", "help", "version",
50
+ "cuenta", "resolver", "sesiones", "uso", "agotada", "disponible", "limite", "abrir", "sync-mcp",
51
+ "profile", "navegador",
52
+ "run", "limit", "session", "identity", "config", "undo", "upgrade", "completion", "__complete", "__update-check",
53
+ ]);
54
+ export function checkName(name) {
55
+ if (!isValidProfileName(name))
56
+ fail(`invalid name: '${name}' (use lowercase letters, digits, - or _)`);
57
+ if (RESERVED.has(name))
58
+ fail(`'${name}' is reserved`);
59
+ }
60
+ export { stamp } from "../../core/journal.js";
61
+ import { stamp } from "../../core/journal.js";
62
+ function lstat(path) {
63
+ try {
64
+ return lstatSync(path);
65
+ }
66
+ catch {
67
+ return undefined;
68
+ }
69
+ }
70
+ /** Make <dir>/<item> a symlink to the hub, moving a local copy aside. */
71
+ function linkItem(dir, item, aside, io, hub = paths(io.env).hub) {
72
+ const target = join(hub, item);
73
+ const path = join(dir, item);
74
+ const st = lstat(path);
75
+ if (st?.isSymbolicLink()) {
76
+ if (readlinkSync(path) === target)
77
+ return;
78
+ rmSync(path);
79
+ }
80
+ else if (st?.isDirectory() && readdirSync(path).length === 0) {
81
+ rmdirSync(path);
82
+ }
83
+ else if (st) {
84
+ mkdirSync(aside, { recursive: true });
85
+ renameSync(path, join(aside, item));
86
+ io.out(` ! ${item} was a local copy: moved to ${tildify(aside, io.env)}/ (merge it by hand if useful)`);
87
+ }
88
+ symlinkSync(target, path);
89
+ io.out(` ↔ ${item}`);
90
+ }
91
+ const SEED_KEYS = ["mcpServers", "projects", "hasCompletedOnboarding", "lastOnboardingVersion", "theme"];
92
+ /** First .claude.json of a profile: user MCP servers and per-project state, never the account. */
93
+ function seedGlobalConfig(dir, io) {
94
+ const dst = join(dir, ".claude.json");
95
+ if (existsSync(dst)) {
96
+ io.out(" = .claude.json already exists (turno mcp sync brings in new MCP servers)");
97
+ return;
98
+ }
99
+ const src = paths(io.env).hubConfig;
100
+ let hub;
101
+ try {
102
+ hub = JSON.parse(readFileSync(src, "utf8"));
103
+ }
104
+ catch {
105
+ return;
106
+ }
107
+ const seed = {};
108
+ for (const k of SEED_KEYS)
109
+ if (k in hub)
110
+ seed[k] = hub[k];
111
+ writeFileSync(dst, `${JSON.stringify(seed, null, 2)}\n`, { mode: 0o600 });
112
+ chmodSync(dst, 0o600);
113
+ const count = (v) => (v && typeof v === "object" ? Object.keys(v).length : 0);
114
+ io.out(` + .claude.json with ${count(seed.mcpServers)} MCP servers and ${count(seed.projects)} projects from the hub`);
115
+ }
116
+ /**
117
+ * Codex profiles: seed config.toml from the hub once, and always store the login in the
118
+ * profile (`cli_auth_credentials_store = "file"`), so each CODEX_HOME has its own account.
119
+ */
120
+ function prepareCodex(dir, io) {
121
+ const file = join(dir, "config.toml");
122
+ let text = "";
123
+ if (existsSync(file))
124
+ text = readFileSync(file, "utf8");
125
+ else {
126
+ const hubFile = join(agentHub("codex", io.env), "config.toml");
127
+ if (existsSync(hubFile)) {
128
+ text = readFileSync(hubFile, "utf8");
129
+ io.out(" + config.toml from ~/.codex (the login is not copied)");
130
+ }
131
+ }
132
+ const next = setValue(text, undefined, "cli_auth_credentials_store", "file");
133
+ if (next !== text || !existsSync(file)) {
134
+ writeFileSync(file, next, { mode: 0o600 });
135
+ io.out(' + cli_auth_credentials_store = "file" (the login stays in this profile)');
136
+ }
137
+ chmodSync(file, 0o600);
138
+ }
139
+ /** Profile of an agent other than Claude Code: its directory, hub links, config, launcher. */
140
+ function setupAgentProfile(name, agent, io) {
141
+ const a = adapter(agent);
142
+ const hub = agentHub(agent, io.env);
143
+ const dir = agentProfileDir(name, agent, io.env);
144
+ const aside = join(dir, `.aside-${stamp()}`);
145
+ io.out(`▸ ${name} (${a.label}) → ${tildify(dir, io.env)}`);
146
+ mkdirSync(dir, { recursive: true });
147
+ chmodSync(dir, 0o700);
148
+ for (const item of a.sharedDirs) {
149
+ mkdirSync(join(hub, item), { recursive: true });
150
+ linkItem(dir, item, aside, io, hub);
151
+ }
152
+ for (const item of a.sharedFiles) {
153
+ if (existsSync(join(hub, item)))
154
+ linkItem(dir, item, aside, io, hub);
155
+ }
156
+ if (agent === "codex")
157
+ prepareCodex(dir, io);
158
+ writeLauncher(name, io.env, agent);
159
+ io.out(` + command ${launcherName(name, agent)}`);
160
+ }
161
+ export function setupProfiles(names, io, opts = {}) {
162
+ if (names.length === 0)
163
+ fail("usage: turno setup <profile>...");
164
+ for (const name of names)
165
+ checkName(name);
166
+ const p = paths(io.env);
167
+ const config = loadConfig(io.env);
168
+ for (const name of names) {
169
+ const agent = agentOf(name, config);
170
+ if (agent !== "claude") {
171
+ setupAgentProfile(name, agent, io);
172
+ continue;
173
+ }
174
+ if (!existsSync(p.hub)) {
175
+ // Claude Code creates it on first run; profiles need it now to link the shared folders.
176
+ mkdirSync(p.hub, { recursive: true, mode: 0o700 });
177
+ io.out(` + created ${tildify(p.hub, io.env)} (the folder every Claude Code profile shares)`);
178
+ }
179
+ const dir = profileDir(name, io.env);
180
+ const aside = join(dir, `.aside-${stamp()}`);
181
+ io.out(`▸ ${name} → ${tildify(dir, io.env)}`);
182
+ mkdirSync(dir, { recursive: true });
183
+ chmodSync(dir, 0o700);
184
+ for (const item of SHARED_DIRS) {
185
+ if (item === "sessions" && !lstat(join(dir, item))?.isSymbolicLink() && profileBusy(name, io.env, config)) {
186
+ io.out(" ! sessions: this profile has open sessions; close them and run setup again");
187
+ continue;
188
+ }
189
+ mkdirSync(join(p.hub, item), { recursive: true });
190
+ linkItem(dir, item, aside, io);
191
+ }
192
+ for (const item of SHARED_FILES) {
193
+ if (existsSync(join(p.hub, item)))
194
+ linkItem(dir, item, aside, io);
195
+ }
196
+ seedGlobalConfig(dir, io);
197
+ const history = join(dir, "history.jsonl");
198
+ const hubHistory = join(p.hub, "history.jsonl");
199
+ if (!existsSync(history) && lstat(hubHistory)?.isFile()) {
200
+ copyFileSync(hubHistory, history);
201
+ chmodSync(history, 0o600);
202
+ io.out(" + history.jsonl (initial copy; the ↑ history cannot be shared)");
203
+ }
204
+ writeLauncher(name, io.env, "claude");
205
+ io.out(` + command claude-${name}`);
206
+ }
207
+ for (const written of writeHelperLaunchers(io.env, opts.turno ?? turnoCommand()))
208
+ io.out(`+ command ${written}`);
209
+ }
210
+ export const command = {
211
+ summary: "create or repair ~/.claude-<profile> and its claude-<profile> command",
212
+ usage: [
213
+ "Usage: turno setup <profile>...",
214
+ "",
215
+ "Links the shared hub folders and files into the profile (local copies are moved",
216
+ "to .aside-<timestamp>/), seeds .claude.json and history.jsonl, and writes the",
217
+ "claude-<profile>, turno-auto and turno-open launchers.",
218
+ ].join("\n"),
219
+ async run(args, io) {
220
+ setupProfiles(args, io);
221
+ return 0;
222
+ },
223
+ };
224
+ //# sourceMappingURL=setup.js.map
@@ -0,0 +1,101 @@
1
+ import { join } from "node:path";
2
+ import { migrationPending } from "../../core/config-edit.js";
3
+ import { loadConfig } from "../../core/config.js";
4
+ import { paths, tildify } from "../../core/paths.js";
5
+ import { resolveProfile } from "../../core/resolve.js";
6
+ import { availableUpdate } from "../../core/update.js";
7
+ import { packageInfo } from "../../core/version.js";
8
+ import { FALLBACK, checkFonts, userFontDir } from "../../ui/fonts.js";
9
+ import { currentStatusLine, isTurnoStatusLine } from "../../ui/settings.js";
10
+ import { currentTerminal, nerdHere } from "../../ui/terminal-id.js";
11
+ import { JSON_FLAG, bool, parseFlags, printJson } from "../args.js";
12
+ import { paint } from "../io.js";
13
+ import { mcpdStatus } from "./doctor.js";
14
+ import { adapter } from "../../agents/index.js";
15
+ import { limitsData } from "./limit.js";
16
+ import { profilesData } from "./profile.js";
17
+ import { sessionsData } from "./session.js";
18
+ import { bar, shortTime } from "./usage.js";
19
+ export function accountLine(s) {
20
+ if (!s?.loggedIn)
21
+ return undefined;
22
+ const parts = [s.email, s.orgName, s.subscriptionType].filter((v) => Boolean(v)).map(String);
23
+ return parts.length ? parts.join(" · ") : (s.authMethod ?? "logged in");
24
+ }
25
+ /** Everything `turno status` shows, as data. */
26
+ export async function statusData(env, cwd = process.cwd()) {
27
+ const config = loadConfig(env);
28
+ const [profiles, limits, mcpd] = await Promise.all([profilesData(env, config), limitsData(env, false), mcpdStatus(env, config)]);
29
+ const here = resolveProfile(cwd, config, env);
30
+ const sessions = sessionsData(env);
31
+ const line = currentStatusLine(join(paths(env).hub, "settings.json"));
32
+ const fontDir = userFontDir(env);
33
+ const fonts = fontDir ? checkFonts(FALLBACK, fontDir) : [];
34
+ const terminal = currentTerminal(env);
35
+ return {
36
+ version: packageInfo().version,
37
+ update: availableUpdate(env) ?? null,
38
+ migrationPending: migrationPending(env),
39
+ here: { dir: tildify(cwd, env), assigned: here.assigned || null, chosen: here.chosen || null, reason: here.reason, note: here.note || null },
40
+ profiles: profiles.map((p) => {
41
+ const l = limits.find((x) => x.profile === p.name);
42
+ return { ...p, fiveHour: l?.fiveHour ?? null, week: l?.week ?? null };
43
+ }),
44
+ sessions: {
45
+ total: sessions.length,
46
+ byProfile: sessions.reduce((acc, s) => {
47
+ const key = s.profile ?? (s.source === "desktop" ? "desktop" : "unknown");
48
+ return { ...acc, [key]: (acc[key] ?? 0) + 1 };
49
+ }, {}),
50
+ },
51
+ mcpd: { running: mcpd.running, port: mcpd.port },
52
+ look: {
53
+ statusLine: isTurnoStatusLine(line) ? "turno" : (line?.command ?? null),
54
+ font: fonts.length > 0 && fonts.every((f) => f.state === "installed"),
55
+ terminal: terminal ?? null,
56
+ icons: config.icons === "auto" ? (nerdHere(env, config.nerdTerminals) ? "nerd" : "unicode") : config.icons,
57
+ },
58
+ };
59
+ }
60
+ function pct(w, now) {
61
+ if (!w)
62
+ return `${"-".padStart(7)}${" ".repeat(6)}`;
63
+ const used = w.resetsAt && w.resetsAt < now ? 0 : w.used;
64
+ return `${bar(used, 8)} ${used.toFixed(0).padStart(3)}%`;
65
+ }
66
+ export const command = {
67
+ summary: "one screen with everything: this folder, profiles and usage, sessions, mcpd and the look",
68
+ usage: "Usage: turno status [--json]\n\nturno doctor checks each part in depth and can fix problems.",
69
+ flags: ["--json"],
70
+ async run(args, io) {
71
+ const p = parseFlags(args, JSON_FLAG, 0);
72
+ const d = await statusData(io.env);
73
+ if (bool(p, "json")) {
74
+ printJson(io.out, d);
75
+ return 0;
76
+ }
77
+ const now = Date.now() / 1000;
78
+ const dim = (s) => paint(io, s, "2");
79
+ io.out(`${paint(io, `turno ${d.version}`, "1")}${d.update ? paint(io, ` (${d.update} available: turno upgrade)`, "33") : ""}`);
80
+ if (d.migrationPending)
81
+ io.out(paint(io, "the bash claudio config is not migrated yet: turno migrate", "33"));
82
+ const using = d.here.chosen ?? "plain claude";
83
+ io.out(`here ${d.here.dir} -> ${using}${d.here.note ? ` (${d.here.assigned} ${d.here.note})` : dim(` (${d.here.reason})`)}`);
84
+ if (!d.profiles.length)
85
+ io.out("profiles none yet (turno profile add <name>)");
86
+ const w = Math.max(0, ...d.profiles.map((x) => x.name.length));
87
+ for (const [i, x] of d.profiles.entries()) {
88
+ const who = !x.setUp ? "not set up" : x.agent !== "claude" ? adapter(x.agent).label : (x.email ?? "not logged in");
89
+ const flags = [...x.roles, x.exhaustedUntil ? `exhausted until ${shortTime(x.exhaustedUntil)}` : ""].filter(Boolean).join(", ");
90
+ io.out(`${i === 0 ? "profiles " : " "}${x.name.padEnd(w)} 5h ${pct(x.fiveHour, now)} week ${pct(x.week, now)} ${who}${x.plan ? ` · ${x.plan}` : ""}${flags ? dim(` ${flags}`) : ""}`);
91
+ }
92
+ const by = Object.entries(d.sessions.byProfile).map(([k, v]) => `${k} ${v}`).join(", ");
93
+ io.out(`sessions ${d.sessions.total} live${by ? ` (${by})` : ""}`);
94
+ io.out(`mcpd ${d.mcpd.running ? `running on port ${d.mcpd.port}` : "not running (turno mcp daemon start)"}`);
95
+ const lineText = d.look.statusLine === "turno" ? "turno status line" : d.look.statusLine ? `status line \`${d.look.statusLine}\`` : "no status line";
96
+ io.out(`look ${lineText}, ${d.look.font ? "font installed" : "font missing (turno ui install)"}, ${d.look.icons} icons here`);
97
+ io.out(dim("\nturno doctor checks each part; turno limit, session and profile show more."));
98
+ return 0;
99
+ },
100
+ };
101
+ //# sourceMappingURL=status.js.map
@@ -0,0 +1,275 @@
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";
4
+ import { fileURLToPath } from "node:url";
5
+ import { loadConfig } from "../../core/config.js";
6
+ import { exhaustedUntil } from "../../core/exhausted.js";
7
+ import { paths } from "../../core/paths.js";
8
+ import { profileFromConfigDir } from "../../core/profiles.js";
9
+ import { resolveProfile } from "../../core/resolve.js";
10
+ import { nerdHere } from "../../ui/terminal-id.js";
11
+ import { NAMED_COLORS, PILL_DEFAULTS, render, turnsLeft } from "../../statusline/render.js";
12
+ const USAGE = `Usage:
13
+ turno statusline render the status line from the JSON Claude Code sends on stdin
14
+
15
+ Set it in settings.json:
16
+ "statusLine": { "type": "command", "command": "turno statusline" }`;
17
+ function readJson(file) {
18
+ try {
19
+ return JSON.parse(readFileSync(file, "utf8"));
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ }
25
+ function writeJson(file, data) {
26
+ mkdirSync(dirname(file), { recursive: true });
27
+ const tmp = `${file}.${process.pid}.tmp`;
28
+ writeFileSync(tmp, JSON.stringify(data));
29
+ renameSync(tmp, file);
30
+ }
31
+ function stableJson(v) {
32
+ if (Array.isArray(v))
33
+ return `[${v.map(stableJson).join(",")}]`;
34
+ if (v && typeof v === "object") {
35
+ const o = v;
36
+ return `{${Object.keys(o)
37
+ .sort()
38
+ .map((k) => `${JSON.stringify(k)}:${stableJson(o[k])}`)
39
+ .join(",")}}`;
40
+ }
41
+ return JSON.stringify(v) ?? "null";
42
+ }
43
+ function selfScript() {
44
+ return realpathSync(join(dirname(fileURLToPath(import.meta.url)), "..", "main.js"));
45
+ }
46
+ /** Run `turno statusline --<worker> ...` detached, so rendering never waits for it. */
47
+ function background(args) {
48
+ try {
49
+ spawn(process.execPath, [selfScript(), "statusline", ...args], { detached: true, stdio: "ignore" }).unref();
50
+ }
51
+ catch {
52
+ /* best effort */
53
+ }
54
+ }
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()];
64
+ }
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];
68
+ }
69
+ /**
70
+ * The account's windows, the freshest any session has seen. Each session carries the values of
71
+ * its own last response, so an idle one has stale data. A session only publishes when its values
72
+ * change (a new response), so a quiet session redrawing never overwrites fresh data from another.
73
+ */
74
+ function accountLimits(usageFile, cache, sessionId, limits, now) {
75
+ let changedAt = 0;
76
+ if (Object.keys(limits).length && sessionId) {
77
+ const sig = stableJson(limits);
78
+ const seenFile = join(cache, `rl-${sessionId}.json`);
79
+ const seen = readJson(seenFile) ?? {};
80
+ 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 });
83
+ if (changedAt)
84
+ writeJson(usageFile, { rate_limits: limits, updated_at: Math.trunc(now) });
85
+ }
86
+ else {
87
+ changedAt = seen.changed_at ?? 0;
88
+ }
89
+ }
90
+ const shared = readJson(usageFile);
91
+ if (shared?.rate_limits && (shared.updated_at ?? 0) > changedAt)
92
+ return shared.rate_limits;
93
+ return limits;
94
+ }
95
+ const PLAN_NAMES = { max: "Max", pro: "Pro", team: "Team", enterprise: "Enterprise" };
96
+ function planOf(file) {
97
+ let p;
98
+ try {
99
+ p = readFileSync(file, "utf8").trim();
100
+ }
101
+ catch {
102
+ mkdirSync(dirname(file), { recursive: true });
103
+ writeFileSync(file, ""); // only one render asks for it
104
+ background(["--plan", file]);
105
+ return "";
106
+ }
107
+ return PLAN_NAMES[p] ?? p;
108
+ }
109
+ function resolveCached(cwd, config, env, cache, now) {
110
+ if (!cwd)
111
+ return { chosen: "", assigned: "" };
112
+ const file = join(cache, `resolve-${cwd.replace(/[^A-Za-z0-9]/g, "-").slice(-120)}`);
113
+ try {
114
+ if (now - statSync(file).mtimeMs / 1000 < 120) {
115
+ const [chosen = "", assigned = ""] = readFileSync(file, "utf8").split("\x1f");
116
+ return { chosen, assigned };
117
+ }
118
+ }
119
+ catch {
120
+ /* compute */
121
+ }
122
+ const r = resolveProfile(cwd, config, env);
123
+ mkdirSync(cache, { recursive: true });
124
+ writeFileSync(file, `${r.chosen}\x1f${r.assigned}`);
125
+ return { chosen: r.chosen, assigned: r.assigned };
126
+ }
127
+ function turnHistory(cache, sessionId, promptId, five) {
128
+ if (!sessionId || !five || five.used_percentage === undefined)
129
+ return undefined;
130
+ const file = join(cache, `turns-${sessionId}.json`);
131
+ const hist = readJson(file) ?? [];
132
+ if (promptId) {
133
+ 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));
139
+ }
140
+ return turnsLeft(hist);
141
+ }
142
+ function gitBranch(cwd) {
143
+ if (!cwd || !existsSync(cwd))
144
+ return "";
145
+ const git = (args) => {
146
+ try {
147
+ return execFileSync("git", ["--no-optional-locks", "-C", cwd, ...args], { encoding: "utf8", timeout: 3000, stdio: ["ignore", "pipe", "ignore"] }).trim();
148
+ }
149
+ catch {
150
+ return "";
151
+ }
152
+ };
153
+ return git(["branch", "--show-current"]) || git(["rev-parse", "--short", "HEAD"]); // detached HEAD: short commit
154
+ }
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;
165
+ }
166
+ catch {
167
+ /* no lock */
168
+ }
169
+ if (stale && !locked) {
170
+ mkdirSync(cache, { recursive: true });
171
+ closeSync(openSync(lock, "w"));
172
+ background(["--cost", transcript, out]);
173
+ }
174
+ return data ? { total: data.total, sub: data.sub } : undefined;
175
+ }
176
+ export function useNerd(config, env) {
177
+ if (config.icons === "nerd")
178
+ return true;
179
+ if (config.icons === "unicode")
180
+ return false;
181
+ return nerdHere(env, config.nerdTerminals);
182
+ }
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
+ }
191
+ const p = paths(env);
192
+ const cache = join(p.state, "cache");
193
+ const account = profileFromConfigDir(env.CLAUDE_CONFIG_DIR, config, env) ?? "";
194
+ 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: "" };
197
+ const input = {
198
+ data,
199
+ now,
200
+ nerd: useNerd(config, env),
201
+ compact: Number(env.COLUMNS || 120) < 100,
202
+ account,
203
+ pill: pillColor(config, account),
204
+ plan: account ? planOf(join(p.planDir, account)) : "",
205
+ limits,
206
+ chosen,
207
+ assigned,
208
+ branch: gitBranch(cwd),
209
+ };
210
+ if (account) {
211
+ const t = turnHistory(cache, data.session_id, data.prompt_id, limits.five_hour);
212
+ if (t !== undefined)
213
+ input.turnsLeft = t;
214
+ const mine = exhaustedUntil(account, env, now);
215
+ if (mine)
216
+ input.exhaustedMine = mine;
217
+ const theirs = assigned ? exhaustedUntil(assigned, env, now) : undefined;
218
+ if (theirs)
219
+ input.exhaustedAssigned = theirs;
220
+ }
221
+ const cost = sessionCost(cache, data.session_id, data.transcript_path, now);
222
+ if (cost)
223
+ input.cost = cost;
224
+ return input;
225
+ }
226
+ async function readStdin() {
227
+ const chunks = [];
228
+ for await (const c of process.stdin)
229
+ chunks.push(c);
230
+ return Buffer.concat(chunks).toString("utf8");
231
+ }
232
+ async function planWorker(file) {
233
+ const out = await new Promise((resolve) => execFile("claude", ["auth", "status", "--json"], { timeout: 20_000 }, (_e, stdout) => resolve(stdout ?? "")));
234
+ try {
235
+ const plan = JSON.parse(out).subscriptionType ?? "";
236
+ writeFileSync(file, plan);
237
+ }
238
+ catch {
239
+ /* leave it empty; the next missing-file render retries */
240
+ }
241
+ }
242
+ export const command = {
243
+ summary: "two-row status line for Claude Code",
244
+ usage: USAGE,
245
+ hidden: false,
246
+ async run(args, io) {
247
+ if (args[0] === "--cost" && args[1] && args[2]) {
248
+ try {
249
+ const { setPriority } = await import("node:os");
250
+ setPriority(10);
251
+ }
252
+ catch {
253
+ /* not allowed */
254
+ }
255
+ const { computeCost } = await import("../../statusline/cost.js");
256
+ computeCost(args[1], args[2]);
257
+ return 0;
258
+ }
259
+ if (args[0] === "--plan" && args[1]) {
260
+ await planWorker(args[1]);
261
+ return 0;
262
+ }
263
+ try {
264
+ const raw = await readStdin();
265
+ const data = JSON.parse(raw || "{}");
266
+ process.stdout.write(render(collect(data, io.env)));
267
+ }
268
+ catch (err) {
269
+ // A minimal line beats an empty one.
270
+ process.stdout.write(`turno statusline: ${err.name}: ${err.message}\n`);
271
+ }
272
+ return 0;
273
+ },
274
+ };
275
+ //# sourceMappingURL=statusline.js.map