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
@@ -0,0 +1,217 @@
1
+ /**
2
+ * `turno mcp export` and `turno mcp import <file>`: mcp.toml without secret values, and merging
3
+ * such a file (or another agent's MCP config) into mcp.toml. An exported file names each secret
4
+ * by its `keychain:` or `env:` reference; literal secrets become `keychain:turno/<server>/<key>`
5
+ * references that the importing machine fills with `turno secret set`.
6
+ */
7
+ import { parse, stringify } from "smol-toml";
8
+ import { parseManifest } from "../core/manifest.js";
9
+ import { argSecrets, isSecretValue, serviceKey, urlSecrets } from "./importer.js";
10
+ const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /**
12
+ * mcp.toml text without secret values. With `profile`, only the servers that profile gets and
13
+ * only its own variant. Comments are not kept (the file is generated).
14
+ */
15
+ export function exportManifest(text, opts = {}) {
16
+ const manifest = parseManifest(text); // refuse to export a file mcpd would refuse
17
+ const raw = parse(text);
18
+ const table = isTable(raw.server) ? raw.server : {};
19
+ const keychain = new Set();
20
+ const envVars = new Set();
21
+ const moved = [];
22
+ const redacted = [];
23
+ const out = {};
24
+ const refOf = (v) => {
25
+ if (v.startsWith("keychain:"))
26
+ keychain.add(v.slice("keychain:".length));
27
+ else if (v.startsWith("env:"))
28
+ envVars.add(v.slice(4).replace(/:-.*$/, ""));
29
+ };
30
+ /** env and headers: references stay, literal secrets become references. */
31
+ const values = (server, scope, map) => {
32
+ if (!isTable(map))
33
+ return undefined;
34
+ const next = {};
35
+ for (const [k, v] of Object.entries(map)) {
36
+ if (typeof v !== "string") {
37
+ next[k] = v;
38
+ continue;
39
+ }
40
+ if (v.startsWith("keychain:") || v.startsWith("env:")) {
41
+ refOf(v);
42
+ next[k] = v;
43
+ }
44
+ else if (!v.includes("${") && isSecretValue(k, v)) {
45
+ const service = `turno/${scope}/${serviceKey(k)}`;
46
+ keychain.add(service);
47
+ moved.push(`${server}.${k}`);
48
+ next[k] = `keychain:${service}`;
49
+ }
50
+ else
51
+ next[k] = v;
52
+ }
53
+ return next;
54
+ };
55
+ const scrub = (server, scope, t) => {
56
+ const next = { ...t };
57
+ for (const key of ["env", "headers"]) {
58
+ const v = values(server, scope, t[key]);
59
+ if (v)
60
+ next[key] = v;
61
+ }
62
+ if (Array.isArray(t.args)) {
63
+ const args = t.args.map(String);
64
+ const found = argSecrets(args);
65
+ if (found.length) {
66
+ next.args = args.map((a) => found.reduce((s, f) => s.split(f).join("<secret>"), a));
67
+ redacted.push(`${server}.args`);
68
+ }
69
+ }
70
+ if (typeof t.url === "string") {
71
+ const found = urlSecrets(t.url);
72
+ if (found.length) {
73
+ let url = t.url;
74
+ for (const f of found)
75
+ url = url.split(f).join("<secret>").split(encodeURIComponent(f)).join("<secret>");
76
+ next.url = url;
77
+ redacted.push(`${server}.url`);
78
+ }
79
+ }
80
+ if (isTable(t.oauth) && typeof t.oauth.client_secret === "string")
81
+ refOf(t.oauth.client_secret);
82
+ return next;
83
+ };
84
+ for (const [name, value] of Object.entries(table)) {
85
+ if (!isTable(value))
86
+ continue;
87
+ const def = manifest.servers[name];
88
+ if (opts.profile && !def.profiles.includes("*") && !def.profiles.includes(opts.profile))
89
+ continue;
90
+ const server = scrub(name, name, value);
91
+ if (isTable(value.variant)) {
92
+ const variants = {};
93
+ for (const [prof, v] of Object.entries(value.variant)) {
94
+ if (opts.profile && prof !== opts.profile)
95
+ continue;
96
+ if (isTable(v))
97
+ variants[prof] = scrub(`${name}.variant.${prof}`, `${name}/${prof}`, v);
98
+ }
99
+ if (Object.keys(variants).length)
100
+ server.variant = variants;
101
+ else
102
+ delete server.variant;
103
+ }
104
+ out[name] = server;
105
+ }
106
+ const names = Object.keys(out);
107
+ const head = [
108
+ `# turno MCP servers, from \`${opts.command ?? "turno mcp export"}\`. No secret values: each secret is`,
109
+ "# a keychain: or env: reference. Import it with: turno mcp import <this file> --write",
110
+ ];
111
+ if (keychain.size) {
112
+ head.push("#", "# Store these secrets on the machine that imports it (the value on stdin):");
113
+ for (const s of [...keychain].sort())
114
+ head.push(`# turno secret set ${s}`);
115
+ }
116
+ if (envVars.size)
117
+ head.push("#", `# Variables mcpd reads from its environment: ${[...envVars].sort().join(", ")}`);
118
+ if (redacted.length)
119
+ head.push("#", `# Secrets replaced by <secret> (args and URLs cannot hold a reference): ${redacted.join(", ")}`);
120
+ const body = names.length ? `${stringify({ server: out })}\n` : "";
121
+ const result = `${head.join("\n")}\n\n${body}`;
122
+ parseManifest(result, "export"); // never print something import would refuse
123
+ return {
124
+ text: result,
125
+ servers: names,
126
+ keychain: [...keychain].sort(),
127
+ envVars: [...envVars].sort(),
128
+ moved,
129
+ redacted,
130
+ };
131
+ }
132
+ /** The parts of a TOML table header: `server."a.b".env` is server, a.b, env. */
133
+ function headerPath(inner) {
134
+ const parts = [];
135
+ const re = /\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*(?:\.|$)/y;
136
+ re.lastIndex = 0;
137
+ while (re.lastIndex < inner.length) {
138
+ const m = re.exec(inner);
139
+ if (!m)
140
+ break;
141
+ parts.push(m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : (m[2] ?? m[3]));
142
+ }
143
+ return parts;
144
+ }
145
+ const HEADER = /^\s*\[\[?\s*([^[\]#]+?)\s*\]\]?\s*(#.*)?$/;
146
+ /**
147
+ * Remove `[server.<name>]` and its sub-tables (`[server.<name>.env]`, variants, ...) from
148
+ * mcp.toml text, keeping the rest and its comments. Undefined when the server is defined some
149
+ * other way (an inline table, dotted keys under `[server]`) and the text has to be edited by hand.
150
+ */
151
+ export function removeServer(text, name) {
152
+ const lines = text.split("\n");
153
+ const keep = [];
154
+ let dropping = false;
155
+ for (const line of lines) {
156
+ const h = HEADER.exec(line);
157
+ if (h) {
158
+ const path = headerPath(h[1]);
159
+ dropping = path[0] === "server" && path[1] === name;
160
+ }
161
+ if (!dropping)
162
+ keep.push(line);
163
+ }
164
+ const next = keep.join("\n").replace(/\n{3,}/g, "\n\n");
165
+ try {
166
+ return parseManifest(next).servers[name] ? undefined : next;
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
171
+ }
172
+ /**
173
+ * Merge server tables into mcp.toml text: new names are appended, names already there are kept
174
+ * unless `force`, which replaces their tables. Throws when a server cannot be replaced in place.
175
+ */
176
+ export function mergeServers(existing, incoming, force) {
177
+ const current = existing.trim() ? parseManifest(existing).servers : {};
178
+ let text = existing;
179
+ const added = [];
180
+ const replaced = [];
181
+ const kept = [];
182
+ const append = {};
183
+ for (const [name, table] of Object.entries(incoming)) {
184
+ if (current[name]) {
185
+ if (!force) {
186
+ kept.push(name);
187
+ continue;
188
+ }
189
+ const next = removeServer(text, name);
190
+ if (next === undefined)
191
+ throw new Error(`cannot replace server ${name} in mcp.toml (it is not a [server.${name}] table); edit it by hand`);
192
+ text = next;
193
+ replaced.push(name);
194
+ }
195
+ else
196
+ added.push(name);
197
+ append[name] = table;
198
+ }
199
+ if (Object.keys(append).length) {
200
+ const trimmed = text.replace(/\s+$/, "");
201
+ text = `${trimmed}${trimmed ? "\n\n" : ""}${stringify({ server: append })}\n`;
202
+ }
203
+ parseManifest(text); // never write something mcpd cannot read back
204
+ return { text, added, replaced, kept };
205
+ }
206
+ /** The server tables of a file in mcp.toml's format (what `turno mcp export` prints). */
207
+ export function manifestServers(text, file) {
208
+ parseManifest(text, file);
209
+ const raw = parse(text);
210
+ const out = {};
211
+ if (isTable(raw.server))
212
+ for (const [n, v] of Object.entries(raw.server))
213
+ if (isTable(v))
214
+ out[n] = v;
215
+ return out;
216
+ }
217
+ //# sourceMappingURL=share.js.map
@@ -0,0 +1,183 @@
1
+ /**
2
+ * The gateway's files in the state folder (token, lock, port, last start error) and the
3
+ * config it would use, without loading the gateway itself. `turno status`, `doctor` and the
4
+ * `mcp` commands read these on every run, so this module stays free of the MCP SDK; daemon.ts
5
+ * re-exports all of it.
6
+ */
7
+ import { execFileSync } from "node:child_process";
8
+ import { randomBytes } from "node:crypto";
9
+ import { closeSync, constants, fchmodSync, fstatSync, openSync, readFileSync } from "node:fs";
10
+ import { join } from "node:path";
11
+ import { parse as parseToml } from "smol-toml";
12
+ import { loadConfig, parseConfig } from "../core/config.js";
13
+ import { pidAlive } from "../core/fsutil.js";
14
+ import { atomicWrite } from "../core/journal.js";
15
+ import { paths } from "../core/paths.js";
16
+ import { hasFields, readState } from "../core/state-file.js";
17
+ /** Files mcpd keeps in the state folder besides `mcpd.token` and `mcpd.port`. */
18
+ export function daemonFiles(env = process.env) {
19
+ const p = paths(env);
20
+ return {
21
+ lock: join(p.state, "mcpd.lock"),
22
+ lastGood: join(p.state, "mcp.last-good.toml"),
23
+ error: join(p.state, "mcpd.error.json"),
24
+ log: join(p.logsDir, "mcpd.log"),
25
+ calls: join(p.logsDir, "calls.jsonl"),
26
+ rss: join(p.state, "mcpd-rss.json"),
27
+ };
28
+ }
29
+ function defaultWarn(message) {
30
+ process.stderr.write(`turno: ${message}\n`);
31
+ }
32
+ /**
33
+ * The only place that reads or writes the gateway's master token (mode 600, in the state
34
+ * folder). `read` returns it or undefined; `ensure` creates it when missing; `rotate` always
35
+ * writes a new one. On read the file is checked with fstat: a mode wider than 600 is fixed (or
36
+ * reported when it cannot be), and a file owned by another user is reported. The token is
37
+ * never printed. Per-profile tokens derive from this one (mcpd/tokens.ts).
38
+ */
39
+ export function masterToken(env = process.env, mode = "ensure", warn = defaultWarn) {
40
+ const file = paths(env).mcpdToken;
41
+ if (mode !== "rotate") {
42
+ let fd;
43
+ try {
44
+ fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
45
+ const st = fstatSync(fd);
46
+ if (st.isFile()) {
47
+ const uid = process.getuid?.();
48
+ if (uid !== undefined && st.uid !== uid)
49
+ warn(`${file} belongs to uid ${st.uid}, not to you; rotate it with: turno mcp token rotate`);
50
+ else if (st.mode & 0o077) {
51
+ try {
52
+ fchmodSync(fd, 0o600);
53
+ warn(`${file} was readable by others (mode ${(st.mode & 0o777).toString(8)}); set it to 600`);
54
+ }
55
+ catch {
56
+ warn(`${file} is readable by others (mode ${(st.mode & 0o777).toString(8)}); run: chmod 600 ${file}`);
57
+ }
58
+ }
59
+ const t = readFileSync(fd, "utf8").trim();
60
+ if (t.length >= 32)
61
+ return t;
62
+ }
63
+ else
64
+ warn(`${file} is not a regular file`);
65
+ }
66
+ catch (err) {
67
+ const code = err.code;
68
+ if (code === "ELOOP")
69
+ warn(`${file} is a symbolic link; turno replaces it with a regular file`);
70
+ else if (code !== "ENOENT")
71
+ warn(`cannot read ${file}: ${err.message}`);
72
+ }
73
+ finally {
74
+ if (fd !== undefined)
75
+ closeSync(fd);
76
+ }
77
+ if (mode === "read")
78
+ return undefined;
79
+ }
80
+ const token = randomBytes(32).toString("hex");
81
+ atomicWrite(file, `${token}\n`, 0o600);
82
+ return token;
83
+ }
84
+ /** The bearer token sessions use; created once with mode 600. */
85
+ export function ensureToken(env = process.env, warn) {
86
+ return masterToken(env, "ensure", warn);
87
+ }
88
+ export function readToken(env = process.env, warn) {
89
+ return masterToken(env, "read", warn);
90
+ }
91
+ /** Replace the token with a new one. Profiles need `turno mcp sync` and mcpd a restart (or SIGHUP). */
92
+ export function rotateToken(env = process.env) {
93
+ return masterToken(env, "rotate");
94
+ }
95
+ const isLockInfo = (v) => hasFields(v, { pid: "number" }) && Number.isInteger(v.pid) && v.pid > 0;
96
+ /** The lock file, or undefined when there is none or it is not a lock (state-file.ts). */
97
+ export function readLock(env = process.env) {
98
+ return readState(daemonFiles(env).lock, isLockInfo);
99
+ }
100
+ /** Whether `pid` runs mcpd: alive and, when ps can tell, its command line is `... mcp daemon run` (or `mcpd run`). */
101
+ export function isMcpdProcess(pid) {
102
+ if (pid === process.pid)
103
+ return true;
104
+ if (!pidAlive(pid))
105
+ return false;
106
+ try {
107
+ const cmd = execFileSync("ps", ["-o", "command=", "-p", String(pid)], {
108
+ encoding: "utf8",
109
+ timeout: 2000,
110
+ stdio: ["ignore", "pipe", "ignore"],
111
+ });
112
+ return /\b(mcpd|daemon) run\b/.test(cmd);
113
+ }
114
+ catch {
115
+ return true; // cannot tell: assume it is
116
+ }
117
+ }
118
+ /** The lock of a live mcpd, or undefined (no lock, or a stale one left by a crash). */
119
+ export function liveLock(env = process.env) {
120
+ const lock = readLock(env);
121
+ return lock && isMcpdProcess(lock.pid) ? lock : undefined;
122
+ }
123
+ /** Configuration that never throws: a broken config.toml gives the defaults, keeping its port when it can be read. */
124
+ export function loadConfigSafe(env = process.env) {
125
+ try {
126
+ return { config: loadConfig(env) };
127
+ }
128
+ catch (err) {
129
+ const file = paths(env).configFile;
130
+ const config = parseConfig("", file, env);
131
+ try {
132
+ const port = parseToml(readFileSync(file, "utf8")).mcpd?.port;
133
+ if (typeof port === "number" && Number.isInteger(port) && port >= 1024 && port <= 65535)
134
+ config.mcpd.port = port;
135
+ }
136
+ catch {
137
+ /* not even TOML: the default port */
138
+ }
139
+ return { config, error: err.message };
140
+ }
141
+ }
142
+ /**
143
+ * The port mcpd listens on: the one a live mcpd recorded, else the configured one. A port
144
+ * file without a live lock is stale (a crash) and ignored; one without any lock comes from an
145
+ * mcpd older than the lock and is trusted.
146
+ */
147
+ export function mcpdPort(env = process.env) {
148
+ const lock = readLock(env);
149
+ if (!lock || pidAlive(lock.pid)) {
150
+ try {
151
+ const n = Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10);
152
+ if (n > 0)
153
+ return n;
154
+ }
155
+ catch {
156
+ /* fall through */
157
+ }
158
+ }
159
+ return loadConfigSafe(env).config.mcpd.port;
160
+ }
161
+ const isStartError = (v) => hasFields(v, { at: "string", message: "string" });
162
+ export function readStartError(env = process.env) {
163
+ return readState(daemonFiles(env).error, isStartError);
164
+ }
165
+ /** Whether our own mcpd answers /status on `port` with our token. */
166
+ export async function answersAsMcpd(port, token) {
167
+ if (!token)
168
+ return undefined;
169
+ try {
170
+ const res = await fetch(`http://127.0.0.1:${port}/status`, {
171
+ headers: { authorization: `Bearer ${token}` },
172
+ signal: AbortSignal.timeout(2000),
173
+ });
174
+ if (!res.ok)
175
+ return undefined;
176
+ const body = (await res.json());
177
+ return { ...(typeof body.pid === "number" ? { pid: body.pid } : {}) };
178
+ }
179
+ catch {
180
+ return undefined;
181
+ }
182
+ }
183
+ //# sourceMappingURL=state.js.map
package/dist/mcpd/sync.js CHANGED
@@ -1,90 +1,61 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
2
  import { dirname } from "node:path";
3
3
  import { parse } from "smol-toml";
4
+ import { DEFAULT_AGENT, adapter } from "../agents/index.js";
5
+ import { atomicWrite } from "../core/journal.js";
6
+ import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE } from "../core/paths.js";
4
7
  import { servesProfile } from "../core/manifest.js";
5
- /** Headers every gateway entry carries. The PID and folder are expanded by Claude Code. */
6
- export function gatewayEntry(name, port, token, profile) {
7
- return {
8
- type: "http",
9
- url: `http://127.0.0.1:${port}/mcp/${encodeURIComponent(name)}`,
10
- headers: {
11
- Authorization: `Bearer ${token}`,
12
- "X-Turno-Profile": profile,
13
- "X-Turno-Pid": "${TURNO_SESSION_PID:-0}",
14
- "X-Turno-Cwd": "${PWD:-}",
15
- },
16
- };
17
- }
18
- const gatewayUrl = (name, port) => `http://127.0.0.1:${port}/mcp/${encodeURIComponent(name)}`;
8
+ import { profileToken } from "./tokens.js";
9
+ import { isObject, parseJsonObject } from "../core/fsutil.js";
10
+ import { CliError } from "../cli/io.js";
11
+ import { isStringArray, readState, recordOf, requireState } from "../core/state-file.js";
19
12
  /**
20
- * A gateway entry in the format of each agent (ADR 0013). Claude Code gets the token in the
21
- * entry, as before; the others read it, and the session PID, from the launcher's environment.
22
- * Cursor shares one file between profiles, so even the profile comes from the environment.
13
+ * A gateway entry in the format of each agent. Claude Code gets the
14
+ * profile's token in the entry; the others read it, and the session PID, from the
15
+ * launcher's environment.
23
16
  */
24
17
  export function gatewayEntryFor(agent, name, port, token, profile) {
25
- const url = gatewayUrl(name, port);
26
- switch (agent) {
27
- case "claude":
28
- return gatewayEntry(name, port, token, profile);
29
- case "codex":
30
- return {
31
- url,
32
- bearer_token_env_var: "TURNO_MCPD_TOKEN",
33
- http_headers: { "X-Turno-Profile": profile },
34
- env_http_headers: { "X-Turno-Pid": "TURNO_SESSION_PID", "X-Turno-Cwd": "PWD" },
35
- };
36
- case "copilot":
37
- return {
38
- type: "http",
39
- url,
40
- headers: {
41
- Authorization: "Bearer ${TURNO_MCPD_TOKEN}",
42
- "X-Turno-Profile": profile,
43
- "X-Turno-Pid": "${TURNO_SESSION_PID}",
44
- },
45
- tools: ["*"],
46
- };
47
- case "cursor":
48
- return {
49
- url,
50
- headers: {
51
- Authorization: "Bearer ${env:TURNO_MCPD_TOKEN}",
52
- "X-Turno-Profile": "${env:TURNO_PROFILE}",
53
- "X-Turno-Pid": "${env:TURNO_SESSION_PID}",
54
- },
55
- };
56
- }
18
+ return adapter(agent).mcp.gatewayEntry(name, port, token, profile);
57
19
  }
58
20
  /**
59
21
  * The MCP entries a profile should have, according to the manifest. Remote servers that do not
60
- * go through the gateway are written as they are for Claude Code, and skipped for the other
61
- * agents (their formats differ; `turno mcp config` prints them).
22
+ * go through the gateway are written as they are for agents that take them (Claude Code), and
23
+ * skipped for the others (their formats differ; `turno mcp config` prints them). `master` is the gateway's
24
+ * master token: entries carry the profile's own token derived from it, never the
25
+ * master itself.
62
26
  */
63
- export function profileServers(manifest, profile, port, token, agent = "claude") {
27
+ export function profileServers(manifest, profile, port, master, agent = DEFAULT_AGENT) {
28
+ const a = adapter(agent);
64
29
  const out = {};
30
+ const token = profile ? profileToken(master, profile) : "";
65
31
  for (const [name, def] of Object.entries(manifest.servers)) {
66
32
  if (!servesProfile(def, profile))
67
33
  continue;
68
34
  if (def.kind === "remote" && !def.proxy) {
69
- if (agent === "claude")
35
+ if (a.mcp.directRemote)
70
36
  out[name] = { ...def.entry };
71
37
  continue;
72
38
  }
73
- out[name] = gatewayEntryFor(agent, name, port, token, profile);
39
+ out[name] = a.mcp.gatewayEntry(name, port, token, profile);
74
40
  }
75
41
  return out;
76
42
  }
43
+ const isManaged = recordOf(isStringArray);
44
+ /**
45
+ * The entries turno wrote, before it removes any: a file that exists but cannot be read is a
46
+ * StateError (fix or remove it), never an empty list that would leave stale entries behind.
47
+ */
77
48
  export function readManaged(file) {
78
- try {
79
- return JSON.parse(readFileSync(file, "utf8"));
80
- }
81
- catch {
82
- return {};
83
- }
49
+ return requireState(file, isManaged) ?? {};
50
+ }
51
+ /** The same, empty when the file cannot be used: for checks that only read (doctor, the status line). */
52
+ export function peekManaged(file) {
53
+ return readState(file, isManaged) ?? {};
84
54
  }
85
55
  export function writeManaged(file, state) {
86
- mkdirSync(dirname(file), { recursive: true });
87
- writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`);
56
+ mkdirSync(dirname(file), { recursive: true, mode: PRIVATE_DIR_MODE });
57
+ writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
58
+ chmodSync(file, PRIVATE_FILE_MODE);
88
59
  }
89
60
  /** Decide what changes in a server map; mutates `servers`. */
90
61
  function plan(servers, wanted, previouslyManaged, opts) {
@@ -117,26 +88,31 @@ function plan(servers, wanted, previouslyManaged, opts) {
117
88
  res.changed = res.added.length + res.updated.length + res.removed.length > 0;
118
89
  return res;
119
90
  }
120
- function writeAtomic(file, text) {
121
- mkdirSync(dirname(file), { recursive: true });
122
- const tmp = `${file}.turno-${process.pid}.tmp`;
123
- writeFileSync(tmp, text, { mode: 0o600 });
124
- chmodSync(tmp, 0o600);
125
- renameSync(tmp, file);
126
- }
127
91
  /**
128
92
  * Rewrite the server map under `key` of a JSON config file (Claude Code `.claude.json`,
129
93
  * Copilot `mcp-config.json`, Cursor `mcp.json`): add or update manifest entries, remove
130
94
  * entries turno wrote earlier that left the manifest, keep everything else.
131
95
  */
132
96
  export function syncJsonServers(configFile, key, wanted, previouslyManaged, opts = {}) {
133
- const cfg = existsSync(configFile) ? JSON.parse(readFileSync(configFile, "utf8")) : {};
134
- const servers = { ...(cfg[key] ?? {}) };
97
+ const cfg = existsSync(configFile) ? parseJsonObject(readFileSync(configFile, "utf8"), configFile) : {};
98
+ const current = cfg[key] ?? {};
99
+ if (!isObject(current))
100
+ throw new CliError(`${configFile}: ${key} is not a JSON object; fix it by hand`);
101
+ const servers = { ...current };
135
102
  const res = plan(servers, wanted, previouslyManaged, opts);
136
103
  if (res.changed && !opts.dryRun)
137
- writeAtomic(configFile, `${JSON.stringify({ ...cfg, [key]: servers }, null, 2)}\n`);
104
+ atomicWrite(configFile, `${JSON.stringify({ ...cfg, [key]: servers }, null, 2)}\n`, 0o600);
138
105
  return res;
139
106
  }
107
+ /**
108
+ * Rewrite the servers of an agent config file in its store's format: add or update
109
+ * `wanted`, remove entries turno wrote earlier that left it, keep everything else.
110
+ */
111
+ export function syncServers(configFile, store, wanted, previouslyManaged, opts = {}) {
112
+ return store.format === "toml"
113
+ ? syncTomlServers(configFile, store.key, wanted, previouslyManaged, opts)
114
+ : syncJsonServers(configFile, store.key, wanted, previouslyManaged, opts);
115
+ }
140
116
  /** The mcpServers of a Claude Code config file. */
141
117
  export function syncConfigFile(configFile, wanted, previouslyManaged, opts = {}) {
142
118
  return syncJsonServers(configFile, "mcpServers", wanted, previouslyManaged, opts);
@@ -151,13 +127,16 @@ function tomlValue(v) {
151
127
  if (Array.isArray(v))
152
128
  return `[${v.map(tomlValue).join(", ")}]`;
153
129
  if (v && typeof v === "object") {
154
- return `{ ${Object.entries(v).map(([k, x]) => `${tomlKey(k)} = ${tomlValue(x)}`).join(", ")} }`;
130
+ return `{ ${Object.entries(v)
131
+ .map(([k, x]) => `${tomlKey(k)} = ${tomlValue(x)}`)
132
+ .join(", ")} }`;
155
133
  }
156
134
  throw new Error(`cannot write ${String(v)} as TOML`);
157
135
  }
158
- /** Line ranges of every `[mcp_servers.<name>]` table (and its sub-tables) in a TOML text. */
159
- function codexTables(lines) {
160
- const header = /^\s*\[\s*mcp_servers\.("(?:[^"\\]|\\.)*"|[A-Za-z0-9_-]+)(\.[^\]]*)?\s*\]\s*(#.*)?$/;
136
+ const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
137
+ /** Line ranges of every `[<key>.<name>]` table (and its sub-tables) in a TOML text. */
138
+ function serverTables(lines, key) {
139
+ const header = new RegExp(`^\\s*\\[\\s*${escapeRegExp(key)}\\.("(?:[^"\\\\]|\\\\.)*"|[A-Za-z0-9_-]+)(\\.[^\\]]*)?\\s*\\]\\s*(#.*)?$`);
161
140
  const anyHeader = /^\s*\[/;
162
141
  const out = new Map();
163
142
  for (let i = 0; i < lines.length; i++) {
@@ -174,20 +153,23 @@ function codexTables(lines) {
174
153
  return out;
175
154
  }
176
155
  /**
177
- * The `[mcp_servers.*]` tables of a Codex config.toml, edited line by line so comments and
178
- * every other setting stay as they are.
156
+ * The `[<key>.*]` tables of a TOML config (Codex: `[mcp_servers.*]` in config.toml), edited
157
+ * line by line so comments and every other setting stay as they are.
179
158
  */
180
- export function syncCodexToml(configFile, wanted, previouslyManaged, opts = {}) {
159
+ function syncTomlServers(configFile, key, wanted, previouslyManaged, opts) {
181
160
  const text = existsSync(configFile) ? readFileSync(configFile, "utf8") : "";
182
- const current = (parse(text).mcp_servers ?? {});
161
+ const current = (parse(text)[key] ?? {});
183
162
  const servers = { ...current };
184
163
  const res = plan(servers, wanted, previouslyManaged, opts);
185
164
  if (!res.changed || opts.dryRun)
186
165
  return res;
187
- let lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
166
+ const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
188
167
  // Drop the tables that go or change, from the bottom up so ranges stay valid.
189
168
  const drop = [...res.removed, ...res.updated];
190
- const ranges = [...codexTables(lines).entries()].filter(([n]) => drop.includes(n)).map(([, r]) => r).sort((a, b) => b[0] - a[0]);
169
+ const ranges = [...serverTables(lines, key).entries()]
170
+ .filter(([n]) => drop.includes(n))
171
+ .map(([, r]) => r)
172
+ .sort((a, b) => b[0] - a[0]);
191
173
  for (const [start, end] of ranges)
192
174
  lines.splice(start, end - start);
193
175
  for (const name of [...res.updated, ...res.added]) {
@@ -195,14 +177,17 @@ export function syncCodexToml(configFile, wanted, previouslyManaged, opts = {})
195
177
  lines.pop();
196
178
  if (lines.length)
197
179
  lines.push("");
198
- lines.push(`[mcp_servers.${tomlKey(name)}]`);
180
+ lines.push(`[${tomlKey(key)}.${tomlKey(name)}]`);
199
181
  for (const [k, v] of Object.entries(wanted[name]))
200
182
  lines.push(`${tomlKey(k)} = ${tomlValue(v)}`);
201
183
  }
202
- lines = lines.length ? lines : [];
203
184
  const next = `${lines.join("\n")}\n`;
204
- parse(next); // never write a file Codex cannot read
205
- writeAtomic(configFile, next);
185
+ parse(next); // never write a file the agent cannot read
186
+ atomicWrite(configFile, next, 0o600);
206
187
  return res;
207
188
  }
189
+ /** The `[mcp_servers.*]` tables of a Codex config.toml. */
190
+ export function syncCodexToml(configFile, wanted, previouslyManaged, opts = {}) {
191
+ return syncTomlServers(configFile, "mcp_servers", wanted, previouslyManaged, opts);
192
+ }
208
193
  //# sourceMappingURL=sync.js.map