turno-cli 0.0.0-stage → 0.1.1

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 +30 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/README.md +335 -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 +109 -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,177 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parse } from "smol-toml";
3
+ import { ConfigError, isValidProfileName } from "./config.js";
4
+ import { paths } from "./paths.js";
5
+ /** A value resolved at spawn time: "keychain:<service>" or "env:<NAME>". */
6
+ export function isSecretRef(v) {
7
+ return v.startsWith("keychain:") || v.startsWith("env:");
8
+ }
9
+ const SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
10
+ /** "90s", "15m", "2h" or a number of seconds. */
11
+ export function parseDuration(v, file, key) {
12
+ if (typeof v === "number" && v >= 0)
13
+ return v;
14
+ if (typeof v === "string") {
15
+ const m = /^(\d+(?:\.\d+)?)\s*(s|m|h)?$/.exec(v.trim());
16
+ if (m)
17
+ return Number(m[1]) * (m[2] === "h" ? 3600 : m[2] === "m" ? 60 : 1);
18
+ }
19
+ throw new ConfigError(file, `${key} must be a duration like "15m"`);
20
+ }
21
+ function strArray(v, file, key) {
22
+ if (v === undefined)
23
+ return [];
24
+ if (!Array.isArray(v) || v.some((x) => typeof x !== "string"))
25
+ throw new ConfigError(file, `${key} must be an array of strings`);
26
+ return v;
27
+ }
28
+ function strRecord(v, file, key) {
29
+ if (v === undefined)
30
+ return {};
31
+ if (typeof v !== "object" || v === null || Array.isArray(v))
32
+ throw new ConfigError(file, `${key} must be a table`);
33
+ const out = {};
34
+ for (const [k, val] of Object.entries(v)) {
35
+ if (typeof val !== "string")
36
+ throw new ConfigError(file, `${key}.${k} must be a string`);
37
+ out[k] = val;
38
+ }
39
+ return out;
40
+ }
41
+ function optStr(v, file, key) {
42
+ if (v === undefined)
43
+ return undefined;
44
+ if (typeof v !== "string" || !v)
45
+ throw new ConfigError(file, `${key} must be a non-empty string`);
46
+ return v;
47
+ }
48
+ function profilesOf(v, file, key) {
49
+ const list = v === undefined ? ["*"] : strArray(v, file, key);
50
+ for (const p of list)
51
+ if (p !== "*" && !isValidProfileName(p))
52
+ throw new ConfigError(file, `${key}: invalid profile "${p}"`);
53
+ return list;
54
+ }
55
+ export function parseManifest(text, file = "mcp.toml") {
56
+ let raw;
57
+ try {
58
+ raw = parse(text);
59
+ }
60
+ catch (err) {
61
+ throw new ConfigError(file, err.message);
62
+ }
63
+ const servers = {};
64
+ const table = (raw.server ?? {});
65
+ for (const [name, value] of Object.entries(table)) {
66
+ if (!SERVER_NAME.test(name))
67
+ throw new ConfigError(file, `invalid server name "${name}"`);
68
+ const v = (value ?? {});
69
+ const key = `server.${name}`;
70
+ const profiles = profilesOf(v.profiles, file, `${key}.profiles`);
71
+ if (v.url !== undefined) {
72
+ if (typeof v.url !== "string")
73
+ throw new ConfigError(file, `${key}.url must be a string`);
74
+ const { profiles: _p, idle: _i, ...rest } = v;
75
+ const entry = { type: "http", ...rest };
76
+ const headers = strRecord(v.headers, file, `${key}.headers`);
77
+ const proxy = Object.values(headers).some(isSecretRef);
78
+ servers[name] = {
79
+ kind: "remote",
80
+ name,
81
+ entry,
82
+ profiles,
83
+ proxy,
84
+ url: v.url,
85
+ headers,
86
+ idle: v.idle === undefined ? 30 * 60 : parseDuration(v.idle, file, `${key}.idle`),
87
+ };
88
+ continue;
89
+ }
90
+ const builtin = optStr(v.builtin, file, `${key}.builtin`);
91
+ const command = optStr(v.command, file, `${key}.command`) ?? (builtin ? `builtin:${builtin}` : undefined);
92
+ if (!command)
93
+ throw new ConfigError(file, `${key} needs command, url or builtin`);
94
+ const scope = (v.scope ?? "shared");
95
+ if (scope !== "shared" && scope !== "project" && scope !== "session") {
96
+ throw new ConfigError(file, `${key}.scope must be shared, project or session`);
97
+ }
98
+ const exclusive = v.exclusive === undefined ? false : v.exclusive;
99
+ if (typeof exclusive !== "boolean")
100
+ throw new ConfigError(file, `${key}.exclusive must be true or false`);
101
+ if (exclusive && scope !== "shared")
102
+ throw new ConfigError(file, `${key}: exclusive needs scope = "shared"`);
103
+ const variants = {};
104
+ for (const [prof, vv] of Object.entries((v.variant ?? {}))) {
105
+ if (!isValidProfileName(prof))
106
+ throw new ConfigError(file, `${key}.variant: invalid profile "${prof}"`);
107
+ const o = (vv ?? {});
108
+ const variant = { env: strRecord(o.env, file, `${key}.variant.${prof}.env`) };
109
+ const vc = optStr(o.command, file, `${key}.variant.${prof}.command`);
110
+ if (vc)
111
+ variant.command = vc;
112
+ if (o.args !== undefined)
113
+ variant.args = strArray(o.args, file, `${key}.variant.${prof}.args`);
114
+ const vcwd = optStr(o.cwd, file, `${key}.variant.${prof}.cwd`);
115
+ if (vcwd)
116
+ variant.cwd = vcwd;
117
+ variants[prof] = variant;
118
+ }
119
+ const server = {
120
+ kind: "stdio",
121
+ name,
122
+ command,
123
+ args: strArray(v.args, file, `${key}.args`),
124
+ env: strRecord(v.env, file, `${key}.env`),
125
+ scope,
126
+ idle: v.idle === undefined ? (scope === "shared" ? 30 * 60 : 20 * 60) : parseDuration(v.idle, file, `${key}.idle`),
127
+ exclusive,
128
+ lease: v.lease === undefined ? 5 * 60 : parseDuration(v.lease, file, `${key}.lease`),
129
+ profiles,
130
+ variants,
131
+ };
132
+ const cwd = optStr(v.cwd, file, `${key}.cwd`);
133
+ if (cwd)
134
+ server.cwd = cwd;
135
+ const pkg = optStr(v.package, file, `${key}.package`);
136
+ if (pkg)
137
+ server.package = pkg;
138
+ if (builtin)
139
+ server.builtin = builtin;
140
+ servers[name] = server;
141
+ }
142
+ return { servers };
143
+ }
144
+ export function loadManifest(env = process.env) {
145
+ const file = paths(env).mcpFile;
146
+ let text = "";
147
+ try {
148
+ text = readFileSync(file, "utf8");
149
+ }
150
+ catch (err) {
151
+ if (err.code !== "ENOENT")
152
+ throw err;
153
+ }
154
+ return parseManifest(text, file);
155
+ }
156
+ /** Whether a profile should get this server in its config. */
157
+ export function servesProfile(server, profile) {
158
+ return server.profiles.includes("*") || server.profiles.includes(profile);
159
+ }
160
+ /** The variant key for a profile: its name when it has an override block, else "default". */
161
+ export function variantKey(server, profile) {
162
+ return profile && server.variants[profile] ? profile : "default";
163
+ }
164
+ /** Effective launch settings for a variant. */
165
+ export function effectiveLaunch(server, variant) {
166
+ const v = server.variants[variant];
167
+ const out = {
168
+ command: v?.command ?? server.command,
169
+ args: v?.args ?? server.args,
170
+ env: { ...server.env, ...(v?.env ?? {}) },
171
+ };
172
+ const cwd = v?.cwd ?? server.cwd;
173
+ if (cwd)
174
+ out.cwd = cwd;
175
+ return out;
176
+ }
177
+ //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,54 @@
1
+ import { homedir } from "node:os";
2
+ import { join } from "node:path";
3
+ export function paths(env = process.env) {
4
+ const home = env.HOME || homedir();
5
+ const config = env.TURNO_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(home, ".config"), "turno");
6
+ const state = env.TURNO_STATE_DIR || join(env.XDG_STATE_HOME || join(home, ".local", "state"), "turno");
7
+ const data = env.TURNO_DATA_DIR || join(env.XDG_DATA_HOME || join(home, ".local", "share"), "turno");
8
+ return {
9
+ home,
10
+ hub: env.TURNO_HUB || join(home, ".claude"),
11
+ hubConfig: env.TURNO_HUB_CONFIG || join(home, ".claude.json"),
12
+ bin: env.TURNO_BIN || join(home, ".local", "bin"),
13
+ config,
14
+ configFile: join(config, "config.toml"),
15
+ mcpFile: join(config, "mcp.toml"),
16
+ accountsFile: join(config, "accounts.toml"),
17
+ state,
18
+ data,
19
+ usageDir: join(state, "usage"),
20
+ exhaustedDir: join(state, "exhausted"),
21
+ planDir: join(state, "plan"),
22
+ runDir: join(state, "run"),
23
+ backupsDir: join(state, "backups"),
24
+ logsDir: join(state, "logs"),
25
+ auditLog: join(state, "audit.jsonl"),
26
+ mcpdToken: join(state, "mcpd.token"),
27
+ mcpdPort: join(state, "mcpd.port"),
28
+ mcpdManaged: join(state, "mcp-managed.json"),
29
+ mcpdCacheDir: join(data, "mcpd", "cache"),
30
+ serversDir: join(data, "servers"),
31
+ browserDir: join(data, "browser"),
32
+ chromeProfilesDir: join(data, "chrome"),
33
+ legacyConfig: join(home, ".config", "claudio"),
34
+ };
35
+ }
36
+ /** Config dir of a profile: ~/.claude-<name>. */
37
+ export function profileDir(name, env = process.env) {
38
+ return join(paths(env).home, `.claude-${name}`);
39
+ }
40
+ /** Replace the home prefix with ~ for display. */
41
+ export function tildify(p, env = process.env) {
42
+ const home = paths(env).home;
43
+ return p === home ? "~" : p.startsWith(home + "/") ? "~" + p.slice(home.length) : p;
44
+ }
45
+ /** Expand a leading ~ to the home directory. */
46
+ export function expandHome(p, env = process.env) {
47
+ const home = paths(env).home;
48
+ if (p === "~")
49
+ return home;
50
+ if (p.startsWith("~/"))
51
+ return join(home, p.slice(2));
52
+ return p;
53
+ }
54
+ //# sourceMappingURL=paths.js.map
@@ -0,0 +1,61 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isValidProfileName } from "./config.js";
4
+ import { paths, profileDir } from "./paths.js";
5
+ /** The agent a profile runs: from config.toml, else Claude Code. */
6
+ export function agentOf(name, config) {
7
+ return config.profiles[name]?.agent ?? "claude";
8
+ }
9
+ /**
10
+ * A profile is a ~/.claude-<name> directory that has its claude-<name> launcher, or a
11
+ * profile declared in config.toml (the only way for agents other than Claude Code). Other
12
+ * folders matching the pattern (for example a place to keep shared skills) are not accounts.
13
+ * With `agent`, only that agent's profiles.
14
+ */
15
+ export function listProfiles(config, env = process.env, agent) {
16
+ const p = paths(env);
17
+ const found = new Set(Object.keys(config.profiles));
18
+ let entries = [];
19
+ try {
20
+ entries = readdirSync(p.home);
21
+ }
22
+ catch {
23
+ entries = [];
24
+ }
25
+ for (const entry of entries) {
26
+ if (!entry.startsWith(".claude-"))
27
+ continue;
28
+ const name = entry.slice(".claude-".length);
29
+ if (!isValidProfileName(name))
30
+ continue;
31
+ const dir = join(p.home, entry);
32
+ try {
33
+ if (!statSync(dir).isDirectory())
34
+ continue;
35
+ }
36
+ catch {
37
+ continue;
38
+ }
39
+ if (existsSync(join(p.bin, `claude-${name}`)))
40
+ found.add(name);
41
+ }
42
+ return [...found].filter((n) => !agent || agentOf(n, config) === agent).sort();
43
+ }
44
+ export function profileExists(name, config, env = process.env) {
45
+ return listProfiles(config, env).includes(name);
46
+ }
47
+ /** The profile a CLAUDE_CONFIG_DIR value belongs to, or the system profile for the hub. */
48
+ export function profileFromConfigDir(configDir, config, env = process.env) {
49
+ const p = paths(env);
50
+ const dir = (configDir ?? "").replace(/\/+$/, "");
51
+ if (dir) {
52
+ const base = dir.slice(dir.lastIndexOf("/") + 1);
53
+ if (base.startsWith(".claude-"))
54
+ return base.slice(".claude-".length);
55
+ if (dir !== p.hub)
56
+ return undefined;
57
+ }
58
+ return config.system;
59
+ }
60
+ export { profileDir };
61
+ //# sourceMappingURL=profiles.js.map
@@ -0,0 +1,39 @@
1
+ const LIMIT = /usage limit|limit reached|limit resets|resets/i;
2
+ const MONTHS = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"];
3
+ export function isUsageLimit(payload) {
4
+ return payload.error_type === "rate_limit" && LIMIT.test(String(payload.error ?? ""));
5
+ }
6
+ /**
7
+ * Epoch seconds when the limit resets. Understands "...|1762900000" and
8
+ * "resets [on] [Nov 13,] [at] 5[:30] pm". Falls back to now + 1 h.
9
+ */
10
+ export function resetTime(error, now = new Date()) {
11
+ const nowS = now.getTime() / 1000;
12
+ const epoch = /\|(\d{10})\b/.exec(error);
13
+ if (epoch) {
14
+ const t = Number(epoch[1]);
15
+ return t > nowS ? t : nowS + 3600;
16
+ }
17
+ const m = /resets?\s+(?:on\s+)?(?:([A-Z][a-z]{2})[a-z]*\.?\s+(\d{1,2}),?\s+)?(?:at\s+)?(\d{1,2})(?::(\d{2}))?\s*([ap]m)/i.exec(error);
18
+ if (!m)
19
+ return nowS + 3600;
20
+ const [, mon, day, hourS, minuteS, ampm] = m;
21
+ const hour = (Number(hourS) % 12) + (ampm?.toLowerCase() === "pm" ? 12 : 0);
22
+ const minute = Number(minuteS ?? 0);
23
+ const dt = new Date(now);
24
+ dt.setSeconds(0, 0);
25
+ dt.setHours(hour, minute);
26
+ if (mon && day) {
27
+ const month = MONTHS.indexOf(mon.slice(0, 3).toLowerCase());
28
+ if (month >= 0)
29
+ dt.setMonth(month, Number(day));
30
+ if (dt.getTime() / 1000 < nowS - 86400)
31
+ dt.setFullYear(dt.getFullYear() + 1);
32
+ }
33
+ else if (dt.getTime() / 1000 <= nowS) {
34
+ dt.setDate(dt.getDate() + 1);
35
+ }
36
+ const t = dt.getTime() / 1000;
37
+ return t > nowS ? t : nowS + 3600;
38
+ }
39
+ //# sourceMappingURL=ratelimit.js.map
@@ -0,0 +1,78 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { sep } from "node:path";
4
+ import { exhaustedUntil } from "./exhausted.js";
5
+ import { tildify } from "./paths.js";
6
+ import { agentOf } from "./profiles.js";
7
+ function real(p) {
8
+ try {
9
+ return realpathSync(p);
10
+ }
11
+ catch {
12
+ return p;
13
+ }
14
+ }
15
+ /** The directory itself plus, for a git worktree, the main repository it belongs to. */
16
+ export function candidateRoots(cwd) {
17
+ const cands = [real(cwd)];
18
+ try {
19
+ const common = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
20
+ encoding: "utf8",
21
+ stdio: ["ignore", "pipe", "ignore"],
22
+ timeout: 3000,
23
+ }).trim();
24
+ if (common.endsWith("/.git")) {
25
+ const main = real(common.slice(0, -5));
26
+ if (!cands.includes(main))
27
+ cands.push(main);
28
+ }
29
+ }
30
+ catch {
31
+ // not a git repository
32
+ }
33
+ return cands;
34
+ }
35
+ export function formatUntil(epochSeconds) {
36
+ return new Date(epochSeconds * 1000).toLocaleString("en-US", {
37
+ weekday: "short",
38
+ day: "2-digit",
39
+ month: "short",
40
+ hour: "2-digit",
41
+ minute: "2-digit",
42
+ hour12: false,
43
+ });
44
+ }
45
+ /**
46
+ * Which profile of `agent` a folder uses: the longest matching project rule among that agent's
47
+ * profiles, else the agent's default; its fallback when the assigned profile is exhausted.
48
+ */
49
+ export function resolveProfile(cwd, config, env = process.env, roots = candidateRoots(cwd), agent = "claude") {
50
+ const roles = agent === "claude" ? { default: config.default, fallback: config.fallback } : (config.agents[agent] ?? {});
51
+ let best;
52
+ for (const rule of config.projects) {
53
+ if (agentOf(rule.profile, config) !== agent)
54
+ continue;
55
+ const root = real(rule.path);
56
+ const hit = roots.some((c) => c === root || c.startsWith(root + sep));
57
+ if (hit && (!best || root.length > best.root.length))
58
+ best = { profile: rule.profile, root };
59
+ }
60
+ const assigned = best ? best.profile : (roles.default ?? "");
61
+ const reason = best ? `project ${tildify(best.root, env)}` : "folder without a rule";
62
+ let chosen = assigned;
63
+ let note = "";
64
+ let until;
65
+ if (assigned) {
66
+ until = exhaustedUntil(assigned, env);
67
+ const fallback = roles.fallback;
68
+ if (until !== undefined && fallback && fallback !== assigned && exhaustedUntil(fallback, env) === undefined) {
69
+ chosen = fallback;
70
+ note = `exhausted until ${formatUntil(until)}`;
71
+ }
72
+ else {
73
+ until = undefined;
74
+ }
75
+ }
76
+ return { chosen, assigned, reason, note, ...(until !== undefined ? { exhaustedUntil: until } : {}) };
77
+ }
78
+ //# sourceMappingURL=resolve.js.map
@@ -0,0 +1,44 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const run = promisify(execFile);
4
+ export class SecretError extends Error {
5
+ constructor(ref, why) {
6
+ super(`cannot resolve ${ref}: ${why}`);
7
+ this.name = "SecretError";
8
+ }
9
+ }
10
+ export function keychainResolver(env = process.env) {
11
+ return async (value) => {
12
+ if (value.startsWith("env:")) {
13
+ const name = value.slice(4);
14
+ const v = env[name];
15
+ if (v === undefined)
16
+ throw new SecretError(value, `environment variable ${name} is not set`);
17
+ return v;
18
+ }
19
+ if (value.startsWith("keychain:")) {
20
+ const service = value.slice("keychain:".length);
21
+ try {
22
+ const { stdout } = await run("security", ["find-generic-password", "-s", service, "-w"], { timeout: 10_000 });
23
+ return stdout.replace(/\n$/, "");
24
+ }
25
+ catch {
26
+ throw new SecretError(value, `no Keychain item with service "${service}" (turno secret set ${service})`);
27
+ }
28
+ }
29
+ return value;
30
+ };
31
+ }
32
+ /** Store a secret in the login Keychain, readable by /usr/bin/security without a dialog. */
33
+ export async function storeKeychainSecret(service, secret, account = "turno") {
34
+ await run("security", ["add-generic-password", "-U", "-a", account, "-s", service, "-w", secret, "-T", "/usr/bin/security"], {
35
+ timeout: 10_000,
36
+ });
37
+ }
38
+ export async function resolveRecord(record, resolve) {
39
+ const out = {};
40
+ for (const [k, v] of Object.entries(record))
41
+ out[k] = await resolve(v);
42
+ return out;
43
+ }
44
+ //# sourceMappingURL=secrets.js.map
@@ -0,0 +1,173 @@
1
+ import { lstatSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { isValidProfileName, loadConfig } from "./config.js";
4
+ import { paths, profileDir } from "./paths.js";
5
+ /** Whether a process is alive. EPERM means it exists but belongs to someone else. */
6
+ export function pidAlive(pid) {
7
+ if (!Number.isInteger(pid) || pid <= 0)
8
+ return false;
9
+ try {
10
+ process.kill(pid, 0);
11
+ return true;
12
+ }
13
+ catch (err) {
14
+ return err.code === "EPERM";
15
+ }
16
+ }
17
+ const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
18
+ /**
19
+ * Parse Claude Code's `procStart` ("Wed Nov 11 00:28:56 2026"). Returns both readings in
20
+ * epoch milliseconds: as UTC (what Claude Code writes) and as local time (in case it changes).
21
+ */
22
+ export function parseProcStart(text) {
23
+ const m = /^\s*[A-Za-z]{3}\s+([A-Za-z]{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{2}):(\d{2})\s+(\d{4})\s*$/.exec(text);
24
+ if (!m)
25
+ return undefined;
26
+ const month = MONTHS.indexOf(m[1]);
27
+ if (month < 0)
28
+ return undefined;
29
+ const [day, h, mi, s, y] = [m[2], m[3], m[4], m[5], m[6]].map(Number);
30
+ return { utc: Date.UTC(y, month, day, h, mi, s), local: new Date(y, month, day, h, mi, s).getTime() };
31
+ }
32
+ /**
33
+ * The profile in a launcher's run record, when the record belongs to this process: its mtime
34
+ * must be within 120 s of the process start, so a recycled PID never inherits an old record.
35
+ */
36
+ export function recordProfile(pid, procStart, env = process.env) {
37
+ const start = parseProcStart(procStart ?? "");
38
+ if (!start)
39
+ return undefined;
40
+ const p = paths(env);
41
+ // Sessions started by the bash launchers keep their records in the legacy folder.
42
+ for (const dir of [p.runDir, join(p.legacyConfig, "run")]) {
43
+ const file = join(dir, String(pid));
44
+ try {
45
+ const mtime = statSync(file).mtimeMs;
46
+ if (Math.min(Math.abs(mtime - start.utc), Math.abs(mtime - start.local)) >= 120_000)
47
+ continue;
48
+ const name = readFileSync(file, "utf8").trim();
49
+ if (isValidProfileName(name))
50
+ return name;
51
+ }
52
+ catch {
53
+ /* not in this folder */
54
+ }
55
+ }
56
+ return undefined;
57
+ }
58
+ /** Remove run records of processes that have ended. */
59
+ export function pruneRunRecords(env = process.env) {
60
+ const dir = paths(env).runDir;
61
+ let entries;
62
+ try {
63
+ entries = readdirSync(dir);
64
+ }
65
+ catch {
66
+ return;
67
+ }
68
+ for (const entry of entries) {
69
+ if (/^\d+$/.test(entry) && pidAlive(Number(entry)))
70
+ continue;
71
+ rmSync(join(dir, entry), { force: true, recursive: true });
72
+ }
73
+ }
74
+ function text(v) {
75
+ return typeof v === "string" ? v : "";
76
+ }
77
+ function readSessionFiles(dir) {
78
+ let entries;
79
+ try {
80
+ entries = readdirSync(dir);
81
+ }
82
+ catch {
83
+ return [];
84
+ }
85
+ const out = [];
86
+ for (const entry of entries) {
87
+ if (!entry.endsWith(".json"))
88
+ continue;
89
+ try {
90
+ const raw = JSON.parse(readFileSync(join(dir, entry), "utf8"));
91
+ if (raw && typeof raw === "object")
92
+ out.push(raw);
93
+ }
94
+ catch {
95
+ // being written or not a session file
96
+ }
97
+ }
98
+ return out;
99
+ }
100
+ /** Live sessions in the hub, each attributed to a profile. Also prunes dead run records. */
101
+ export function liveSessions(env = process.env, config) {
102
+ const cfg = config ?? loadConfig(env);
103
+ const sessions = [];
104
+ for (const s of readSessionFiles(join(paths(env).hub, "sessions"))) {
105
+ const pid = typeof s.pid === "number" ? s.pid : Number.parseInt(text(s.pid), 10);
106
+ if (!pidAlive(pid))
107
+ continue;
108
+ const entrypoint = text(s.entrypoint);
109
+ const procStart = text(s.procStart) || undefined;
110
+ const base = {
111
+ pid,
112
+ sessionId: text(s.sessionId),
113
+ name: text(s.name),
114
+ status: text(s.status) || "?",
115
+ cwd: text(s.cwd),
116
+ entrypoint,
117
+ ...(procStart ? { procStart } : {}),
118
+ };
119
+ if (entrypoint !== "cli") {
120
+ sessions.push({ ...base, source: "desktop" });
121
+ continue;
122
+ }
123
+ const fromRecord = recordProfile(pid, procStart, env);
124
+ if (fromRecord)
125
+ sessions.push({ ...base, profile: fromRecord, source: "record" });
126
+ else
127
+ sessions.push({ ...base, ...(cfg.system ? { profile: cfg.system } : {}), source: "system" });
128
+ }
129
+ pruneRunRecords(env);
130
+ sessions.sort((a, b) => (a.cwd === b.cwd ? displayName(a).localeCompare(displayName(b)) : a.cwd < b.cwd ? -1 : 1));
131
+ return sessions;
132
+ }
133
+ /** Session name, or the first 8 characters of its id. */
134
+ export function displayName(s) {
135
+ return s.name || s.sessionId.slice(0, 8);
136
+ }
137
+ /** Profiles with at least one live session. */
138
+ export function busyProfiles(env = process.env, config) {
139
+ const out = new Set();
140
+ for (const s of liveSessions(env, config))
141
+ if (s.profile)
142
+ out.add(s.profile);
143
+ return out;
144
+ }
145
+ /**
146
+ * Whether a profile has a live session. Besides the hub, a profile whose `sessions` folder
147
+ * is still its own copy (not yet linked to the hub) is busy when a session in it is alive.
148
+ */
149
+ export function profileBusy(name, env = process.env, config) {
150
+ if (busyProfiles(env, config).has(name))
151
+ return true;
152
+ const own = join(profileDir(name, env), "sessions");
153
+ try {
154
+ if (!lstatSync(own).isDirectory())
155
+ return false;
156
+ }
157
+ catch {
158
+ return false;
159
+ }
160
+ for (const s of readSessionFiles(own)) {
161
+ const pid = typeof s.pid === "number" ? s.pid : Number.parseInt(text(s.pid), 10);
162
+ if (pidAlive(pid))
163
+ return true;
164
+ }
165
+ // Session files are named <pid>.json; trust the name when the content is unreadable.
166
+ try {
167
+ return readdirSync(own).some((f) => /^\d+\.json$/.test(f) && pidAlive(Number(f.slice(0, -5))));
168
+ }
169
+ catch {
170
+ return false;
171
+ }
172
+ }
173
+ //# sourceMappingURL=sessions.js.map