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,10 +1,12 @@
1
- import { existsSync, readdirSync, statSync } from "node:fs";
1
+ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
- import { isValidProfileName } from "./config.js";
4
- import { paths, profileDir } from "./paths.js";
3
+ import { DEFAULT_AGENT, adapter } from "../agents/index.js";
4
+ import { isValidProfileName, suggestKey } from "./config.js";
5
+ import { loadManifest } from "./manifest.js";
6
+ import { paths, tildify } from "./paths.js";
5
7
  /** The agent a profile runs: from config.toml, else Claude Code. */
6
8
  export function agentOf(name, config) {
7
- return config.profiles[name]?.agent ?? "claude";
9
+ return config.profiles[name]?.agent ?? DEFAULT_AGENT;
8
10
  }
9
11
  /**
10
12
  * A profile is a ~/.claude-<name> directory that has its claude-<name> launcher, or a
@@ -12,7 +14,7 @@ export function agentOf(name, config) {
12
14
  * folders matching the pattern (for example a place to keep shared skills) are not accounts.
13
15
  * With `agent`, only that agent's profiles.
14
16
  */
15
- export function listProfiles(config, env = process.env, agent) {
17
+ export function listProfiles(config, env, agent) {
16
18
  const p = paths(env);
17
19
  const found = new Set(Object.keys(config.profiles));
18
20
  let entries = [];
@@ -41,11 +43,159 @@ export function listProfiles(config, env = process.env, agent) {
41
43
  }
42
44
  return [...found].filter((n) => !agent || agentOf(n, config) === agent).sort();
43
45
  }
44
- export function profileExists(name, config, env = process.env) {
45
- return listProfiles(config, env).includes(name);
46
+ /**
47
+ * What is wrong in a config.toml that parses: unknown keys (likely typos) and names of
48
+ * profiles that do not exist in system, default, fallback, [agents.*] and [[projects]].
49
+ * Warnings, not errors, so an older or hand-edited file keeps working. Each one says how to
50
+ * fix it: `turno profile add <name>` for a missing profile, else the line to edit.
51
+ */
52
+ export function configFindings(config, env) {
53
+ const lines = configLines(env);
54
+ const file = tildify(paths(env).configFile, env);
55
+ /** "edit ~/.config/turno/config.toml line 3: <what>", or `turno config edit` without a line. */
56
+ const edit = (key, what) => {
57
+ const line = lines ? keyLine(lines, key) : undefined;
58
+ return line ? { manual: `edit ${file} line ${line}${what ? `: ${what}` : ""}` } : { hint: "turno config edit" };
59
+ };
60
+ const out = (config.warnings ?? []).map((text) => {
61
+ const m = /^unknown key ([^\s;]+)(?: \(did you mean ([^\s?]+)\?\))?/.exec(text);
62
+ return {
63
+ text,
64
+ ...(m
65
+ ? edit(m[1], m[2] ? `rename it to ${m[2].slice(m[2].lastIndexOf(".") + 1)}` : "remove it")
66
+ : { hint: "turno config edit" }),
67
+ };
68
+ });
69
+ const known = new Set(listProfiles(config, env));
70
+ const missing = (where, name) => {
71
+ if (name && !known.has(name))
72
+ out.push({ text: `${where} = "${name}", but there is no profile ${name}`, hint: `turno profile add ${name}` });
73
+ };
74
+ missing("system", config.system);
75
+ missing("default", config.default);
76
+ missing("fallback", config.fallback);
77
+ for (const [id, roles] of Object.entries(config.agents)) {
78
+ missing(`agents.${id}.default`, roles?.default);
79
+ missing(`agents.${id}.fallback`, roles?.fallback);
80
+ for (const role of ["default", "fallback"]) {
81
+ const name = roles?.[role];
82
+ if (name && known.has(name) && agentOf(name, config) !== id) {
83
+ const label = adapter(id).label;
84
+ out.push({
85
+ text: `agents.${id}.${role} = "${name}", but ${name} is a ${adapter(agentOf(name, config)).label} profile`,
86
+ ...edit(`agents.${id}.${role}`, `name a ${label} profile`),
87
+ });
88
+ }
89
+ }
90
+ }
91
+ for (const role of ["default", "fallback"]) {
92
+ const name = config[role];
93
+ if (name && known.has(name) && agentOf(name, config) !== DEFAULT_AGENT) {
94
+ const other = agentOf(name, config);
95
+ out.push({
96
+ text: `${role} = "${name}" is for ${adapter(DEFAULT_AGENT).label}, but ${name} is a ${adapter(other).label} profile`,
97
+ ...edit(role, `move it to [agents.${other}]`),
98
+ });
99
+ }
100
+ }
101
+ for (const [i, rule] of config.projects.entries()) {
102
+ if (rule.profile && !known.has(rule.profile))
103
+ out.push({
104
+ text: `the rule for ${tildify(rule.path, env)} uses profile ${rule.profile}, which does not exist`,
105
+ hint: `turno profile add ${rule.profile}`,
106
+ });
107
+ out.push(...folderSetFindings(rule, i, env, edit));
108
+ }
109
+ return out;
110
+ }
111
+ /** The findings as `config check` prints them: the command in parentheses, or the line to edit after it. */
112
+ export function configProblems(config, env) {
113
+ return configFindings(config, env).map((f) => (f.manual ? `${f.text}; ${f.manual}` : `${f.text} (${f.hint})`));
114
+ }
115
+ /** The lines of config.toml, or undefined when it cannot be read. */
116
+ function configLines(env) {
117
+ try {
118
+ return readFileSync(paths(env).configFile, "utf8").split("\n");
119
+ }
120
+ catch {
121
+ return undefined;
122
+ }
123
+ }
124
+ /**
125
+ * The 1-based line of a dotted key in config.toml text: `default`, `profiles.work.colour`,
126
+ * `agents.codex.default`, `projects[0].profile` (the first [[projects]] table). Tables and
127
+ * array tables are followed; inline tables and dotted keys inside a table are not.
128
+ */
129
+ function keyLine(lines, key) {
130
+ let table = "";
131
+ const arrays = new Map();
132
+ const bare = (k) => k.trim().replace(/^"(.*)"$/, "$1");
133
+ for (const [i, raw] of lines.entries()) {
134
+ const line = raw.trim();
135
+ const arr = /^\[\[\s*([^\]]+?)\s*\]\]/.exec(line);
136
+ if (arr) {
137
+ const name = arr[1].split(".").map(bare).join(".");
138
+ const n = (arrays.get(name) ?? -1) + 1;
139
+ arrays.set(name, n);
140
+ table = `${name}[${n}]`;
141
+ continue;
142
+ }
143
+ const tab = /^\[\s*([^\]]+?)\s*\]/.exec(line);
144
+ if (tab) {
145
+ table = tab[1].split(".").map(bare).join(".");
146
+ continue;
147
+ }
148
+ const kv = /^("[^"]*"|[A-Za-z0-9_-]+)\s*=/.exec(line);
149
+ if (kv && (table ? `${table}.${bare(kv[1])}` : bare(kv[1])) === key)
150
+ return i + 1;
151
+ }
152
+ return undefined;
153
+ }
154
+ /**
155
+ * Folder server sets checked against mcp.toml: names it does not declare, and
156
+ * remote servers that skip mcpd, which a set cannot hide. Nothing when mcp.toml is missing or
157
+ * broken (its own check reports that).
158
+ */
159
+ function folderSetFindings(rule, index, env, edit) {
160
+ if ((!rule.mcp && !rule.mcpDeny) || !existsSync(paths(env).mcpFile))
161
+ return [];
162
+ let servers;
163
+ try {
164
+ servers = loadManifest(env).servers;
165
+ }
166
+ catch {
167
+ return [];
168
+ }
169
+ const declared = Object.keys(servers);
170
+ const out = [];
171
+ const where = `the rule for ${tildify(rule.path, env)}`;
172
+ for (const [key, list] of [
173
+ ["mcp", rule.mcp],
174
+ ["mcp_deny", rule.mcpDeny],
175
+ ]) {
176
+ for (const name of list ?? []) {
177
+ if (servers[name])
178
+ continue;
179
+ const near = suggestKey(name, declared);
180
+ out.push({
181
+ text: `${where} lists "${name}" in ${key}, which is not in mcp.toml${near ? ` (did you mean ${near}?)` : ""}`,
182
+ ...edit(`projects[${index}].${key}`, near ? `write ${near}` : `remove "${name}", or declare it in mcp.toml`),
183
+ });
184
+ }
185
+ }
186
+ for (const [name, def] of Object.entries(servers)) {
187
+ const hidden = (rule.mcp && !rule.mcp.includes(name)) || rule.mcpDeny?.includes(name);
188
+ if (hidden && def.kind === "remote" && !def.proxy) {
189
+ const fix = rule.mcpDeny?.includes(name)
190
+ ? edit(`projects[${index}].mcp_deny`, `remove ${name}`)
191
+ : edit(`projects[${index}].mcp`, `add ${name}`);
192
+ out.push({ text: `${where} cannot hide ${name}: it is a remote server that does not pass through mcpd`, ...fix });
193
+ }
194
+ }
195
+ return out;
46
196
  }
47
197
  /** 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) {
198
+ export function profileFromConfigDir(configDir, config, env) {
49
199
  const p = paths(env);
50
200
  const dir = (configDir ?? "").replace(/\/+$/, "");
51
201
  if (dir) {
@@ -55,7 +205,7 @@ export function profileFromConfigDir(configDir, config, env = process.env) {
55
205
  if (dir !== p.hub)
56
206
  return undefined;
57
207
  }
58
- return config.system;
208
+ // system = "" says the hub is no profile's account.
209
+ return config.system || undefined;
59
210
  }
60
- export { profileDir };
61
211
  //# sourceMappingURL=profiles.js.map
@@ -1,36 +1,115 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { sep } from "node:path";
2
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from "node:fs";
3
+ import { dirname, join, resolve, sep } from "node:path";
4
+ import { DEFAULT_AGENT } from "../agents/index.js";
4
5
  import { exhaustedUntil } from "./exhausted.js";
5
6
  import { tildify } from "./paths.js";
6
7
  import { agentOf } from "./profiles.js";
7
- function real(p) {
8
- try {
9
- return realpathSync(p);
10
- }
11
- catch {
12
- return p;
8
+ import { realOr } from "./fsutil.js";
9
+ /** The directory itself plus, for a git worktree, the main repository it belongs to. */
10
+ export function candidateRoots(cwd, spawnGit = gitCommonDirBySpawn) {
11
+ const cands = [realOr(cwd)];
12
+ const found = gitCommonDirOnDisk(cwd);
13
+ const common = found === UNSURE ? spawnGit(cwd) : found;
14
+ if (common?.endsWith("/.git")) {
15
+ const main = realOr(common.slice(0, -5));
16
+ if (!cands.includes(main))
17
+ cands.push(main);
13
18
  }
19
+ return cands;
14
20
  }
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)];
21
+ /** What `git rev-parse --git-common-dir` prints in `cwd`, or undefined outside a repository. */
22
+ function gitCommonDirBySpawn(cwd) {
18
23
  try {
19
- const common = execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
24
+ return execFileSync("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
20
25
  encoding: "utf8",
21
26
  stdio: ["ignore", "pipe", "ignore"],
22
27
  timeout: 3000,
23
28
  }).trim();
24
- if (common.endsWith("/.git")) {
25
- const main = real(common.slice(0, -5));
26
- if (!cands.includes(main))
27
- cands.push(main);
29
+ }
30
+ catch {
31
+ return undefined; // not a git repository
32
+ }
33
+ }
34
+ const UNSURE = Symbol("unsure");
35
+ /** Variables that change how git finds a repository: with any of them set, git itself decides. */
36
+ const GIT_DISCOVERY_VARS = [
37
+ "GIT_DIR",
38
+ "GIT_COMMON_DIR",
39
+ "GIT_WORK_TREE",
40
+ "GIT_CEILING_DIRECTORIES",
41
+ "GIT_DISCOVERY_ACROSS_FILESYSTEM",
42
+ ];
43
+ function stat(p) {
44
+ try {
45
+ return statSync(p);
46
+ }
47
+ catch {
48
+ return undefined;
49
+ }
50
+ }
51
+ /**
52
+ * The git common dir of `cwd` (real path), found the way git finds it but with the file system
53
+ * only: walk up to the first `.git`, follow a `gitdir:` file (worktrees, submodules), then the
54
+ * `commondir` file of a linked worktree. The status line and `turno auto` resolve a folder on
55
+ * every run, and a `git` process costs more than the rest of the resolve. Undefined outside a
56
+ * repository; UNSURE for anything unusual (git variables, another owner, a broken `.git`, a
57
+ * missing HEAD), which `git rev-parse` then answers as before.
58
+ */
59
+ function gitCommonDirOnDisk(cwd, env = process.env) {
60
+ if (GIT_DISCOVERY_VARS.some((k) => env[k] !== undefined))
61
+ return UNSURE;
62
+ let dir = realOr(cwd);
63
+ const start = stat(dir);
64
+ if (!start?.isDirectory())
65
+ return UNSURE;
66
+ for (;;) {
67
+ const here = stat(dir);
68
+ // git stops at a file system boundary.
69
+ if (!here || here.dev !== start.dev)
70
+ return undefined;
71
+ const dotgit = join(dir, ".git");
72
+ let st;
73
+ try {
74
+ st = lstatSync(dotgit);
75
+ }
76
+ catch {
77
+ st = undefined;
78
+ }
79
+ if (st)
80
+ return commonDirOf(dir, dotgit, st.isFile());
81
+ const parent = dirname(dir);
82
+ if (parent === dir)
83
+ return undefined;
84
+ dir = parent;
85
+ }
86
+ }
87
+ function commonDirOf(dir, dotgit, isFile) {
88
+ // git refuses a repository another user owns, unless safe.directory says otherwise.
89
+ const uid = process.getuid?.();
90
+ if (uid !== undefined && stat(dir)?.uid !== uid)
91
+ return UNSURE;
92
+ let gitdir = dotgit;
93
+ try {
94
+ if (isFile) {
95
+ const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(dotgit, "utf8"));
96
+ if (!m)
97
+ return UNSURE;
98
+ gitdir = resolve(dir, m[1]);
28
99
  }
100
+ if (!stat(join(gitdir, "HEAD"))?.isFile())
101
+ return UNSURE;
102
+ let common = gitdir;
103
+ const pointer = join(gitdir, "commondir");
104
+ if (existsSync(pointer))
105
+ common = resolve(gitdir, readFileSync(pointer, "utf8").trim());
106
+ if (!stat(join(common, "objects"))?.isDirectory())
107
+ return UNSURE;
108
+ return realpathSync(common);
29
109
  }
30
110
  catch {
31
- // not a git repository
111
+ return UNSURE;
32
112
  }
33
- return cands;
34
113
  }
35
114
  export function formatUntil(epochSeconds) {
36
115
  return new Date(epochSeconds * 1000).toLocaleString("en-US", {
@@ -42,18 +121,55 @@ export function formatUntil(epochSeconds) {
42
121
  hour12: false,
43
122
  });
44
123
  }
124
+ /** True when `folder` is `root` or inside it (both real paths). */
125
+ function covers(root, folder) {
126
+ return folder === root || folder.startsWith(root + sep);
127
+ }
128
+ /**
129
+ * The MCP server set of a folder: among the rules that have `mcp` or `mcp_deny` and
130
+ * cover one of `roots` (the folder, and the main repository of a worktree), the one with the
131
+ * longest path. On a tie, the rule of `profile`, else the first one in the file. A rule without
132
+ * a set says nothing about servers, so a nested profile rule does not clear a parent's set.
133
+ */
134
+ export function folderMcpSet(roots, rules, profile) {
135
+ let best;
136
+ for (const rule of rules) {
137
+ if (!rule.mcp && !rule.mcpDeny)
138
+ continue;
139
+ const root = realOr(rule.path);
140
+ if (!roots.some((c) => covers(root, c)))
141
+ continue;
142
+ const longer = !best || root.length > best.root.length;
143
+ const preferred = best &&
144
+ root.length === best.root.length &&
145
+ profile !== undefined &&
146
+ rule.profile === profile &&
147
+ best.rule.profile !== profile;
148
+ if (longer || preferred)
149
+ best = { rule, root };
150
+ }
151
+ return best?.rule;
152
+ }
153
+ /** Whether a folder's set lets a session see `server` (no set: every server). */
154
+ export function mcpSetAllows(set, server) {
155
+ if (!set)
156
+ return true;
157
+ if (set.mcp && !set.mcp.includes(server))
158
+ return false;
159
+ return !set.mcpDeny?.includes(server);
160
+ }
45
161
  /**
46
162
  * Which profile of `agent` a folder uses: the longest matching project rule among that agent's
47
163
  * profiles, else the agent's default; its fallback when the assigned profile is exhausted.
48
164
  */
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] ?? {});
165
+ export function resolveProfile(cwd, config, env, roots = candidateRoots(cwd), agent = DEFAULT_AGENT) {
166
+ const roles = agent === DEFAULT_AGENT ? { default: config.default, fallback: config.fallback } : (config.agents[agent] ?? {});
51
167
  let best;
52
168
  for (const rule of config.projects) {
53
- if (agentOf(rule.profile, config) !== agent)
169
+ if (!rule.profile || agentOf(rule.profile, config) !== agent)
54
170
  continue;
55
- const root = real(rule.path);
56
- const hit = roots.some((c) => c === root || c.startsWith(root + sep));
171
+ const root = realOr(rule.path);
172
+ const hit = roots.some((c) => covers(root, c));
57
173
  if (hit && (!best || root.length > best.root.length))
58
174
  best = { profile: rule.profile, root };
59
175
  }
@@ -1,39 +1,84 @@
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";
1
+ import { NO_SECRET_STORE, SecretError, requireSecretStore, secretStore } from "turno-core/secrets";
2
+ /**
3
+ * The store itself (macOS Keychain, Linux Secret Service) lives in turno-core, shared with
4
+ * turno-browser; this module keeps what mcp.toml references need on top of it.
5
+ */
6
+ export { NO_SECRET_STORE, SecretError, keychainAddLine, requireSecretStore, secretStore, securityQuote, } from "turno-core/secrets";
7
+ /** `${VAR}`, `${VAR:-default}` and Cursor's `${env:VAR}` anywhere inside a string. */
8
+ const VAR_REF = /\$\{(env:)?([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
9
+ /** Cursor's own placeholders: not environment variables, so they stay as written. */
10
+ const EDITOR_PLACEHOLDERS = new Set(["userHome", "workspaceFolder", "workspaceFolderBasename", "pathSeparator"]);
11
+ /**
12
+ * Expand `${VAR}`, `${VAR:-default}` and `${env:VAR}` inside a string from `env`, the way Claude
13
+ * Code expands them in its own MCP config. A variable that is unset and has no default is an
14
+ * error (SecretError), never an empty string. Anything else (`${workspaceFolder}`, a lone `$`)
15
+ * stays as written.
16
+ */
17
+ export function expandVars(value, env) {
18
+ if (!value.includes("${"))
19
+ return value;
20
+ return value.replace(VAR_REF, (whole, prefix, name, fallback) => {
21
+ if (!prefix && EDITOR_PLACEHOLDERS.has(name))
22
+ return whole;
23
+ const v = env[name];
24
+ if (fallback !== undefined && !v)
25
+ return fallback;
26
+ if (v === undefined)
27
+ throw new SecretError(whole, `environment variable ${name} is not set`);
28
+ return v;
29
+ });
30
+ }
31
+ /**
32
+ * The variables a value reads from `env` that are unset there and have no default: `env:NAME`
33
+ * as the whole value (with `whole`, as mcpd resolves env values and headers) and `${NAME}`
34
+ * inside it. Names only; a value is never returned.
35
+ */
36
+ export function unsetVars(value, env, whole = true) {
37
+ if (whole && value.startsWith("env:")) {
38
+ const [name, fallback] = value.slice(4).split(/:-(.*)/s, 2);
39
+ return fallback === undefined && env[name] === undefined ? [name] : [];
8
40
  }
41
+ if (whole && value.startsWith("keychain:"))
42
+ return [];
43
+ const out = [];
44
+ for (const [, prefix, name, fallback] of value.matchAll(VAR_REF)) {
45
+ if (!prefix && EDITOR_PLACEHOLDERS.has(name))
46
+ continue;
47
+ if (fallback === undefined && env[name] === undefined && !out.includes(name))
48
+ out.push(name);
49
+ }
50
+ return out;
9
51
  }
10
- export function keychainResolver(env = process.env) {
52
+ /**
53
+ * Resolves whole-value references (`keychain:<name>`, `env:NAME`) and expands `${VAR}` inside any
54
+ * other value. mcpd uses it for stdio env values and remote headers.
55
+ */
56
+ export function keychainResolver(env, platform = process.platform) {
11
57
  return async (value) => {
12
58
  if (value.startsWith("env:")) {
13
- const name = value.slice(4);
14
- const v = env[name];
59
+ // env:NAME, or env:NAME:-default (what `turno mcp import` writes for ${NAME:-default}).
60
+ const [name, fallback] = value.slice(4).split(/:-(.*)/s, 2);
61
+ const v = fallback !== undefined && !env[name] ? fallback : env[name];
15
62
  if (v === undefined)
16
63
  throw new SecretError(value, `environment variable ${name} is not set`);
17
64
  return v;
18
65
  }
19
66
  if (value.startsWith("keychain:")) {
20
67
  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
- }
68
+ const store = secretStore(env, platform);
69
+ if (!store)
70
+ throw new SecretError(value, NO_SECRET_STORE);
71
+ const v = await store.get(service);
72
+ if (v === undefined)
73
+ throw new SecretError(value, `no ${store.label} item "${service}" (turno secret set ${service})`);
74
+ return v;
28
75
  }
29
- return value;
76
+ return expandVars(value, env);
30
77
  };
31
78
  }
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
- });
79
+ /** Store a secret in this machine's store (Keychain or Secret Service), keeping it out of argv. */
80
+ export async function storeKeychainSecret(service, secret, env) {
81
+ await requireSecretStore(env).set(service, secret);
37
82
  }
38
83
  export async function resolveRecord(record, resolve) {
39
84
  const out = {};
@@ -2,17 +2,10 @@ import { lstatSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"
2
2
  import { join } from "node:path";
3
3
  import { isValidProfileName, loadConfig } from "./config.js";
4
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
- }
5
+ import { pidAlive } from "./fsutil.js";
6
+ /** Whether a recorded PID is a live process: process groups (0, negative) never count. */
7
+ function liveProcess(pid) {
8
+ return Number.isInteger(pid) && pid > 0 && pidAlive(pid);
16
9
  }
17
10
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
18
11
  /**
@@ -33,7 +26,7 @@ export function parseProcStart(text) {
33
26
  * The profile in a launcher's run record, when the record belongs to this process: its mtime
34
27
  * must be within 120 s of the process start, so a recycled PID never inherits an old record.
35
28
  */
36
- export function recordProfile(pid, procStart, env = process.env) {
29
+ function recordProfile(pid, procStart, env) {
37
30
  const start = parseProcStart(procStart ?? "");
38
31
  if (!start)
39
32
  return undefined;
@@ -56,7 +49,7 @@ export function recordProfile(pid, procStart, env = process.env) {
56
49
  return undefined;
57
50
  }
58
51
  /** Remove run records of processes that have ended. */
59
- export function pruneRunRecords(env = process.env) {
52
+ function pruneRunRecords(env) {
60
53
  const dir = paths(env).runDir;
61
54
  let entries;
62
55
  try {
@@ -66,7 +59,7 @@ export function pruneRunRecords(env = process.env) {
66
59
  return;
67
60
  }
68
61
  for (const entry of entries) {
69
- if (/^\d+$/.test(entry) && pidAlive(Number(entry)))
62
+ if (/^\d+$/.test(entry) && liveProcess(Number(entry)))
70
63
  continue;
71
64
  rmSync(join(dir, entry), { force: true, recursive: true });
72
65
  }
@@ -98,12 +91,12 @@ function readSessionFiles(dir) {
98
91
  return out;
99
92
  }
100
93
  /** Live sessions in the hub, each attributed to a profile. Also prunes dead run records. */
101
- export function liveSessions(env = process.env, config) {
94
+ export function liveSessions(env, config) {
102
95
  const cfg = config ?? loadConfig(env);
103
96
  const sessions = [];
104
97
  for (const s of readSessionFiles(join(paths(env).hub, "sessions"))) {
105
98
  const pid = typeof s.pid === "number" ? s.pid : Number.parseInt(text(s.pid), 10);
106
- if (!pidAlive(pid))
99
+ if (!liveProcess(pid))
107
100
  continue;
108
101
  const entrypoint = text(s.entrypoint);
109
102
  const procStart = text(s.procStart) || undefined;
@@ -135,7 +128,7 @@ export function displayName(s) {
135
128
  return s.name || s.sessionId.slice(0, 8);
136
129
  }
137
130
  /** Profiles with at least one live session. */
138
- export function busyProfiles(env = process.env, config) {
131
+ export function busyProfiles(env, config) {
139
132
  const out = new Set();
140
133
  for (const s of liveSessions(env, config))
141
134
  if (s.profile)
@@ -146,7 +139,7 @@ export function busyProfiles(env = process.env, config) {
146
139
  * Whether a profile has a live session. Besides the hub, a profile whose `sessions` folder
147
140
  * is still its own copy (not yet linked to the hub) is busy when a session in it is alive.
148
141
  */
149
- export function profileBusy(name, env = process.env, config) {
142
+ export function profileBusy(name, env, config) {
150
143
  if (busyProfiles(env, config).has(name))
151
144
  return true;
152
145
  const own = join(profileDir(name, env), "sessions");
@@ -159,12 +152,12 @@ export function profileBusy(name, env = process.env, config) {
159
152
  }
160
153
  for (const s of readSessionFiles(own)) {
161
154
  const pid = typeof s.pid === "number" ? s.pid : Number.parseInt(text(s.pid), 10);
162
- if (pidAlive(pid))
155
+ if (liveProcess(pid))
163
156
  return true;
164
157
  }
165
158
  // Session files are named <pid>.json; trust the name when the content is unreadable.
166
159
  try {
167
- return readdirSync(own).some((f) => /^\d+\.json$/.test(f) && pidAlive(Number(f.slice(0, -5))));
160
+ return readdirSync(own).some((f) => /^\d+\.json$/.test(f) && liveProcess(Number(f.slice(0, -5))));
168
161
  }
169
162
  catch {
170
163
  return false;