turno-cli 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +284 -0
- package/README.md +120 -53
- package/dist/accounts/audit.js +137 -7
- package/dist/accounts/builtin.js +68 -21
- package/dist/accounts/delegate.js +176 -35
- package/dist/accounts/policy.js +77 -0
- package/dist/accounts/registry.js +37 -21
- package/dist/agents/adapter.js +7 -0
- package/dist/agents/claude.js +195 -0
- package/dist/agents/codex.js +98 -0
- package/dist/agents/copilot.js +39 -0
- package/dist/agents/cursor.js +41 -0
- package/dist/agents/index.js +26 -86
- package/dist/agents/snippets.js +7 -4
- package/dist/cli/args.js +19 -4
- package/dist/cli/commands/accounts.js +96 -51
- package/dist/cli/commands/auto.js +82 -32
- package/dist/cli/commands/browser.js +216 -135
- package/dist/cli/commands/complete.js +2 -1
- package/dist/cli/commands/completion.js +4 -2
- package/dist/cli/commands/config.js +103 -18
- package/dist/cli/commands/demo.js +292 -0
- package/dist/cli/commands/doctor.js +387 -119
- package/dist/cli/commands/handoff.js +33 -22
- package/dist/cli/commands/identity.js +101 -50
- package/dist/cli/commands/init.js +616 -0
- package/dist/cli/commands/limit.js +25 -13
- package/dist/cli/commands/mcp-oauth.js +194 -0
- package/dist/cli/commands/mcp-observe.js +434 -0
- package/dist/cli/commands/mcp.js +653 -185
- package/dist/cli/commands/mcpd.js +323 -75
- package/dist/cli/commands/migrate.js +6 -4
- package/dist/cli/commands/open.js +92 -27
- package/dist/cli/commands/profile.js +205 -69
- package/dist/cli/commands/resolve.js +6 -2
- package/dist/cli/commands/run.js +15 -5
- package/dist/cli/commands/secret.js +61 -42
- package/dist/cli/commands/session.js +2 -2
- package/dist/cli/commands/sessions.js +42 -12
- package/dist/cli/commands/setup.js +136 -158
- package/dist/cli/commands/status.js +172 -41
- package/dist/cli/commands/statusline.js +305 -113
- package/dist/cli/commands/ui.js +64 -66
- package/dist/cli/commands/undo.js +161 -18
- package/dist/cli/commands/uninstall.js +462 -0
- package/dist/cli/commands/upgrade.js +75 -19
- package/dist/cli/commands/usage.js +117 -44
- package/dist/cli/commands/version.js +7 -5
- package/dist/cli/commands/which.js +7 -24
- package/dist/cli/compile-cache.js +32 -0
- package/dist/cli/group.js +10 -10
- package/dist/cli/help.js +57 -0
- package/dist/cli/highlight.js +236 -0
- package/dist/cli/io.js +170 -1
- package/dist/cli/launch.js +21 -37
- package/dist/cli/launchers.js +145 -94
- package/dist/cli/main.js +163 -27
- package/dist/cli/picker.js +447 -0
- package/dist/cli/registry.js +42 -5
- package/dist/cli/security.js +539 -0
- package/dist/cli/style.js +281 -0
- package/dist/core/config.js +145 -23
- package/dist/core/exhausted.js +6 -8
- package/dist/core/fsutil.js +47 -0
- package/dist/core/journal.js +281 -11
- package/dist/core/manifest.js +126 -6
- package/dist/core/paths.js +114 -7
- package/dist/core/profiles.js +139 -9
- package/dist/core/resolve.js +129 -23
- package/dist/core/secrets.js +215 -20
- package/dist/core/sessions.js +13 -20
- package/dist/core/update.js +18 -8
- package/dist/demo/server.js +34 -0
- package/dist/mcpd/cache.js +18 -4
- package/dist/mcpd/calllog.js +253 -0
- package/dist/mcpd/client-names.js +51 -0
- package/dist/mcpd/connectors.js +148 -17
- package/dist/mcpd/daemon.js +452 -116
- package/dist/mcpd/folder-sets.js +39 -0
- package/dist/mcpd/gateway.js +441 -47
- package/dist/mcpd/health.js +269 -0
- package/dist/mcpd/importer.js +356 -36
- package/dist/mcpd/instances.js +425 -65
- package/dist/mcpd/jsonrpc.js +8 -0
- package/dist/mcpd/launchd.js +65 -48
- package/dist/mcpd/modern.js +648 -0
- package/dist/mcpd/oauth.js +791 -0
- package/dist/mcpd/peerpid.js +122 -6
- package/dist/mcpd/pressure.js +85 -0
- package/dist/mcpd/rss.js +151 -0
- package/dist/mcpd/service.js +167 -0
- package/dist/mcpd/state.js +183 -0
- package/dist/mcpd/sync.js +55 -80
- package/dist/mcpd/systemd.js +80 -0
- package/dist/mcpd/tokens.js +89 -0
- package/dist/mcpd/upstream.js +154 -44
- package/dist/statusline/cost.js +154 -44
- package/dist/statusline/input.js +66 -0
- package/dist/statusline/render.js +9 -3
- package/dist/ui/fonts.js +8 -3
- package/dist/ui/settings.js +27 -15
- package/npm-shrinkwrap.json +1093 -0
- package/package.json +6 -6
- package/dist/cli/commands/available.js +0 -18
|
@@ -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
|
+
/** Files mcpd keeps in the state folder besides `mcpd.token` and `mcpd.port`. */
|
|
17
|
+
export function daemonFiles(env = process.env) {
|
|
18
|
+
const p = paths(env);
|
|
19
|
+
return {
|
|
20
|
+
lock: join(p.state, "mcpd.lock"),
|
|
21
|
+
lastGood: join(p.state, "mcp.last-good.toml"),
|
|
22
|
+
error: join(p.state, "mcpd.error.json"),
|
|
23
|
+
log: join(p.logsDir, "mcpd.log"),
|
|
24
|
+
calls: join(p.logsDir, "calls.jsonl"),
|
|
25
|
+
rss: join(p.state, "mcpd-rss.json"),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function defaultWarn(message) {
|
|
29
|
+
process.stderr.write(`turno: ${message}\n`);
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* The only place that reads or writes the gateway's master token (mode 600, in the state
|
|
33
|
+
* folder). `read` returns it or undefined; `ensure` creates it when missing; `rotate` always
|
|
34
|
+
* writes a new one. On read the file is checked with fstat: a mode wider than 600 is fixed (or
|
|
35
|
+
* reported when it cannot be), and a file owned by another user is reported. The token is
|
|
36
|
+
* never printed. Per-profile tokens derive from this one (mcpd/tokens.ts, ADR 0023).
|
|
37
|
+
*/
|
|
38
|
+
export function masterToken(env = process.env, mode = "ensure", warn = defaultWarn) {
|
|
39
|
+
const file = paths(env).mcpdToken;
|
|
40
|
+
if (mode !== "rotate") {
|
|
41
|
+
let fd;
|
|
42
|
+
try {
|
|
43
|
+
fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
44
|
+
const st = fstatSync(fd);
|
|
45
|
+
if (st.isFile()) {
|
|
46
|
+
const uid = process.getuid?.();
|
|
47
|
+
if (uid !== undefined && st.uid !== uid)
|
|
48
|
+
warn(`${file} belongs to uid ${st.uid}, not to you; rotate it with: turno mcp token rotate`);
|
|
49
|
+
else if (st.mode & 0o077) {
|
|
50
|
+
try {
|
|
51
|
+
fchmodSync(fd, 0o600);
|
|
52
|
+
warn(`${file} was readable by others (mode ${(st.mode & 0o777).toString(8)}); set it to 600`);
|
|
53
|
+
}
|
|
54
|
+
catch {
|
|
55
|
+
warn(`${file} is readable by others (mode ${(st.mode & 0o777).toString(8)}); run: chmod 600 ${file}`);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const t = readFileSync(fd, "utf8").trim();
|
|
59
|
+
if (t.length >= 32)
|
|
60
|
+
return t;
|
|
61
|
+
}
|
|
62
|
+
else
|
|
63
|
+
warn(`${file} is not a regular file`);
|
|
64
|
+
}
|
|
65
|
+
catch (err) {
|
|
66
|
+
const code = err.code;
|
|
67
|
+
if (code === "ELOOP")
|
|
68
|
+
warn(`${file} is a symbolic link; turno replaces it with a regular file`);
|
|
69
|
+
else if (code !== "ENOENT")
|
|
70
|
+
warn(`cannot read ${file}: ${err.message}`);
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
if (fd !== undefined)
|
|
74
|
+
closeSync(fd);
|
|
75
|
+
}
|
|
76
|
+
if (mode === "read")
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
const token = randomBytes(32).toString("hex");
|
|
80
|
+
atomicWrite(file, `${token}\n`, 0o600);
|
|
81
|
+
return token;
|
|
82
|
+
}
|
|
83
|
+
/** The bearer token sessions use; created once with mode 600. */
|
|
84
|
+
export function ensureToken(env = process.env, warn) {
|
|
85
|
+
return masterToken(env, "ensure", warn);
|
|
86
|
+
}
|
|
87
|
+
export function readToken(env = process.env, warn) {
|
|
88
|
+
return masterToken(env, "read", warn);
|
|
89
|
+
}
|
|
90
|
+
/** Replace the token with a new one. Profiles need `turno mcp sync` and mcpd a restart (or SIGHUP). */
|
|
91
|
+
export function rotateToken(env = process.env) {
|
|
92
|
+
return masterToken(env, "rotate");
|
|
93
|
+
}
|
|
94
|
+
export function readLock(env = process.env) {
|
|
95
|
+
try {
|
|
96
|
+
const v = JSON.parse(readFileSync(daemonFiles(env).lock, "utf8"));
|
|
97
|
+
return Number.isInteger(v.pid) && v.pid > 0 ? v : undefined;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
return undefined;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/** Whether `pid` runs mcpd: alive and, when ps can tell, its command line is `... mcp daemon run` (or `mcpd run`). */
|
|
104
|
+
export function isMcpdProcess(pid) {
|
|
105
|
+
if (pid === process.pid)
|
|
106
|
+
return true;
|
|
107
|
+
if (!pidAlive(pid))
|
|
108
|
+
return false;
|
|
109
|
+
try {
|
|
110
|
+
const cmd = execFileSync("ps", ["-o", "command=", "-p", String(pid)], { encoding: "utf8", timeout: 2000, stdio: ["ignore", "pipe", "ignore"] });
|
|
111
|
+
return /\b(mcpd|daemon) run\b/.test(cmd);
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return true; // cannot tell: assume it is
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/** The lock of a live mcpd, or undefined (no lock, or a stale one left by a crash). */
|
|
118
|
+
export function liveLock(env = process.env) {
|
|
119
|
+
const lock = readLock(env);
|
|
120
|
+
return lock && isMcpdProcess(lock.pid) ? lock : undefined;
|
|
121
|
+
}
|
|
122
|
+
/** Configuration that never throws: a broken config.toml gives the defaults, keeping its port when it can be read. */
|
|
123
|
+
export function loadConfigSafe(env = process.env) {
|
|
124
|
+
try {
|
|
125
|
+
return { config: loadConfig(env) };
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
const file = paths(env).configFile;
|
|
129
|
+
const config = parseConfig("", file, env);
|
|
130
|
+
try {
|
|
131
|
+
const port = parseToml(readFileSync(file, "utf8")).mcpd?.port;
|
|
132
|
+
if (typeof port === "number" && Number.isInteger(port) && port >= 1024 && port <= 65535)
|
|
133
|
+
config.mcpd.port = port;
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
/* not even TOML: the default port */
|
|
137
|
+
}
|
|
138
|
+
return { config, error: err.message };
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The port mcpd listens on: the one a live mcpd recorded, else the configured one. A port
|
|
143
|
+
* file without a live lock is stale (a crash) and ignored; one without any lock comes from an
|
|
144
|
+
* mcpd older than the lock and is trusted.
|
|
145
|
+
*/
|
|
146
|
+
export function mcpdPort(env = process.env) {
|
|
147
|
+
const lock = readLock(env);
|
|
148
|
+
if (!lock || pidAlive(lock.pid)) {
|
|
149
|
+
try {
|
|
150
|
+
const n = Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10);
|
|
151
|
+
if (n > 0)
|
|
152
|
+
return n;
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
/* fall through */
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return loadConfigSafe(env).config.mcpd.port;
|
|
159
|
+
}
|
|
160
|
+
export function readStartError(env = process.env) {
|
|
161
|
+
try {
|
|
162
|
+
return JSON.parse(readFileSync(daemonFiles(env).error, "utf8"));
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
return undefined;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
/** Whether our own mcpd answers /status on `port` with our token. */
|
|
169
|
+
export async function answersAsMcpd(port, token) {
|
|
170
|
+
if (!token)
|
|
171
|
+
return undefined;
|
|
172
|
+
try {
|
|
173
|
+
const res = await fetch(`http://127.0.0.1:${port}/status`, { headers: { authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(2000) });
|
|
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,76 +1,41 @@
|
|
|
1
|
-
import { chmodSync, existsSync, mkdirSync, readFileSync,
|
|
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
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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";
|
|
19
11
|
/**
|
|
20
|
-
* A gateway entry in the format of each agent (ADR 0013). Claude Code gets the
|
|
21
|
-
*
|
|
22
|
-
*
|
|
12
|
+
* A gateway entry in the format of each agent (ADR 0013, ADR 0032). Claude Code gets the
|
|
13
|
+
* profile's token (ADR 0023) in the entry; the others read it, and the session PID, from the
|
|
14
|
+
* launcher's environment.
|
|
23
15
|
*/
|
|
24
16
|
export function gatewayEntryFor(agent, name, port, token, profile) {
|
|
25
|
-
|
|
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
|
-
}
|
|
17
|
+
return adapter(agent).mcp.gatewayEntry(name, port, token, profile);
|
|
57
18
|
}
|
|
58
19
|
/**
|
|
59
20
|
* 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
|
|
61
|
-
*
|
|
21
|
+
* go through the gateway are written as they are for agents that take them (Claude Code), and
|
|
22
|
+
* skipped for the others (their formats differ; `turno mcp config` prints them). `master` is the gateway's
|
|
23
|
+
* master token: entries carry the profile's own token derived from it (ADR 0023), never the
|
|
24
|
+
* master itself.
|
|
62
25
|
*/
|
|
63
|
-
export function profileServers(manifest, profile, port,
|
|
26
|
+
export function profileServers(manifest, profile, port, master, agent = DEFAULT_AGENT) {
|
|
27
|
+
const a = adapter(agent);
|
|
64
28
|
const out = {};
|
|
29
|
+
const token = profile ? profileToken(master, profile) : "";
|
|
65
30
|
for (const [name, def] of Object.entries(manifest.servers)) {
|
|
66
31
|
if (!servesProfile(def, profile))
|
|
67
32
|
continue;
|
|
68
33
|
if (def.kind === "remote" && !def.proxy) {
|
|
69
|
-
if (
|
|
34
|
+
if (a.mcp.directRemote)
|
|
70
35
|
out[name] = { ...def.entry };
|
|
71
36
|
continue;
|
|
72
37
|
}
|
|
73
|
-
out[name] =
|
|
38
|
+
out[name] = a.mcp.gatewayEntry(name, port, token, profile);
|
|
74
39
|
}
|
|
75
40
|
return out;
|
|
76
41
|
}
|
|
@@ -83,8 +48,9 @@ export function readManaged(file) {
|
|
|
83
48
|
}
|
|
84
49
|
}
|
|
85
50
|
export function writeManaged(file, state) {
|
|
86
|
-
mkdirSync(dirname(file), { recursive: true });
|
|
87
|
-
writeFileSync(file, `${JSON.stringify(state, null, 2)}\n
|
|
51
|
+
mkdirSync(dirname(file), { recursive: true, mode: PRIVATE_DIR_MODE });
|
|
52
|
+
writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`, { mode: PRIVATE_FILE_MODE });
|
|
53
|
+
chmodSync(file, PRIVATE_FILE_MODE);
|
|
88
54
|
}
|
|
89
55
|
/** Decide what changes in a server map; mutates `servers`. */
|
|
90
56
|
function plan(servers, wanted, previouslyManaged, opts) {
|
|
@@ -117,26 +83,31 @@ function plan(servers, wanted, previouslyManaged, opts) {
|
|
|
117
83
|
res.changed = res.added.length + res.updated.length + res.removed.length > 0;
|
|
118
84
|
return res;
|
|
119
85
|
}
|
|
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
86
|
/**
|
|
128
87
|
* Rewrite the server map under `key` of a JSON config file (Claude Code `.claude.json`,
|
|
129
88
|
* Copilot `mcp-config.json`, Cursor `mcp.json`): add or update manifest entries, remove
|
|
130
89
|
* entries turno wrote earlier that left the manifest, keep everything else.
|
|
131
90
|
*/
|
|
132
91
|
export function syncJsonServers(configFile, key, wanted, previouslyManaged, opts = {}) {
|
|
133
|
-
const cfg = existsSync(configFile) ?
|
|
134
|
-
const
|
|
92
|
+
const cfg = existsSync(configFile) ? parseJsonObject(readFileSync(configFile, "utf8"), configFile) : {};
|
|
93
|
+
const current = cfg[key] ?? {};
|
|
94
|
+
if (!isObject(current))
|
|
95
|
+
throw new CliError(`${configFile}: ${key} is not a JSON object; fix it by hand`);
|
|
96
|
+
const servers = { ...current };
|
|
135
97
|
const res = plan(servers, wanted, previouslyManaged, opts);
|
|
136
98
|
if (res.changed && !opts.dryRun)
|
|
137
|
-
|
|
99
|
+
atomicWrite(configFile, `${JSON.stringify({ ...cfg, [key]: servers }, null, 2)}\n`, 0o600);
|
|
138
100
|
return res;
|
|
139
101
|
}
|
|
102
|
+
/**
|
|
103
|
+
* Rewrite the servers of an agent config file in its store's format (ADR 0032): add or update
|
|
104
|
+
* `wanted`, remove entries turno wrote earlier that left it, keep everything else.
|
|
105
|
+
*/
|
|
106
|
+
export function syncServers(configFile, store, wanted, previouslyManaged, opts = {}) {
|
|
107
|
+
return store.format === "toml"
|
|
108
|
+
? syncTomlServers(configFile, store.key, wanted, previouslyManaged, opts)
|
|
109
|
+
: syncJsonServers(configFile, store.key, wanted, previouslyManaged, opts);
|
|
110
|
+
}
|
|
140
111
|
/** The mcpServers of a Claude Code config file. */
|
|
141
112
|
export function syncConfigFile(configFile, wanted, previouslyManaged, opts = {}) {
|
|
142
113
|
return syncJsonServers(configFile, "mcpServers", wanted, previouslyManaged, opts);
|
|
@@ -155,9 +126,10 @@ function tomlValue(v) {
|
|
|
155
126
|
}
|
|
156
127
|
throw new Error(`cannot write ${String(v)} as TOML`);
|
|
157
128
|
}
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
129
|
+
const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
130
|
+
/** Line ranges of every `[<key>.<name>]` table (and its sub-tables) in a TOML text. */
|
|
131
|
+
function serverTables(lines, key) {
|
|
132
|
+
const header = new RegExp(`^\\s*\\[\\s*${escapeRegExp(key)}\\.("(?:[^"\\\\]|\\\\.)*"|[A-Za-z0-9_-]+)(\\.[^\\]]*)?\\s*\\]\\s*(#.*)?$`);
|
|
161
133
|
const anyHeader = /^\s*\[/;
|
|
162
134
|
const out = new Map();
|
|
163
135
|
for (let i = 0; i < lines.length; i++) {
|
|
@@ -174,20 +146,20 @@ function codexTables(lines) {
|
|
|
174
146
|
return out;
|
|
175
147
|
}
|
|
176
148
|
/**
|
|
177
|
-
* The `[
|
|
178
|
-
* every other setting stay as they are.
|
|
149
|
+
* The `[<key>.*]` tables of a TOML config (Codex: `[mcp_servers.*]` in config.toml), edited
|
|
150
|
+
* line by line so comments and every other setting stay as they are.
|
|
179
151
|
*/
|
|
180
|
-
|
|
152
|
+
function syncTomlServers(configFile, key, wanted, previouslyManaged, opts) {
|
|
181
153
|
const text = existsSync(configFile) ? readFileSync(configFile, "utf8") : "";
|
|
182
|
-
const current = (parse(text)
|
|
154
|
+
const current = (parse(text)[key] ?? {});
|
|
183
155
|
const servers = { ...current };
|
|
184
156
|
const res = plan(servers, wanted, previouslyManaged, opts);
|
|
185
157
|
if (!res.changed || opts.dryRun)
|
|
186
158
|
return res;
|
|
187
|
-
|
|
159
|
+
const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
|
|
188
160
|
// Drop the tables that go or change, from the bottom up so ranges stay valid.
|
|
189
161
|
const drop = [...res.removed, ...res.updated];
|
|
190
|
-
const ranges = [...
|
|
162
|
+
const ranges = [...serverTables(lines, key).entries()].filter(([n]) => drop.includes(n)).map(([, r]) => r).sort((a, b) => b[0] - a[0]);
|
|
191
163
|
for (const [start, end] of ranges)
|
|
192
164
|
lines.splice(start, end - start);
|
|
193
165
|
for (const name of [...res.updated, ...res.added]) {
|
|
@@ -195,14 +167,17 @@ export function syncCodexToml(configFile, wanted, previouslyManaged, opts = {})
|
|
|
195
167
|
lines.pop();
|
|
196
168
|
if (lines.length)
|
|
197
169
|
lines.push("");
|
|
198
|
-
lines.push(`[
|
|
170
|
+
lines.push(`[${tomlKey(key)}.${tomlKey(name)}]`);
|
|
199
171
|
for (const [k, v] of Object.entries(wanted[name]))
|
|
200
172
|
lines.push(`${tomlKey(k)} = ${tomlValue(v)}`);
|
|
201
173
|
}
|
|
202
|
-
lines = lines.length ? lines : [];
|
|
203
174
|
const next = `${lines.join("\n")}\n`;
|
|
204
|
-
parse(next); // never write a file
|
|
205
|
-
|
|
175
|
+
parse(next); // never write a file the agent cannot read
|
|
176
|
+
atomicWrite(configFile, next, 0o600);
|
|
206
177
|
return res;
|
|
207
178
|
}
|
|
179
|
+
/** The `[mcp_servers.*]` tables of a Codex config.toml. */
|
|
180
|
+
export function syncCodexToml(configFile, wanted, previouslyManaged, opts = {}) {
|
|
181
|
+
return syncTomlServers(configFile, "mcp_servers", wanted, previouslyManaged, opts);
|
|
182
|
+
}
|
|
208
183
|
//# sourceMappingURL=sync.js.map
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { paths } from "../core/paths.js";
|
|
3
|
+
import { runTool, serviceArgs, serviceEnv } from "./service.js";
|
|
4
|
+
export const UNIT = "turno-mcpd.service";
|
|
5
|
+
export function unitPath(env = process.env) {
|
|
6
|
+
const base = env.XDG_CONFIG_HOME || join(paths(env).home, ".config");
|
|
7
|
+
return join(base, "systemd", "user", UNIT);
|
|
8
|
+
}
|
|
9
|
+
/** One word of ExecStart or Environment, quoted for systemd: specifiers and variables are escaped. */
|
|
10
|
+
function quote(s) {
|
|
11
|
+
return `"${s.replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/%/g, "%%").replace(/\$/g, "$$$$")}"`;
|
|
12
|
+
}
|
|
13
|
+
function unquote(s) {
|
|
14
|
+
return s.replace(/\$\$/g, "$").replace(/%%/g, "%").replace(/\\(["\\])/g, "$1");
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* `systemd --user` unit that keeps `turno mcp daemon run` alive. Restart=on-failure: a clean
|
|
18
|
+
* exit (another mcpd already serves) is not restarted, a crash is.
|
|
19
|
+
*/
|
|
20
|
+
export function unit(spec) {
|
|
21
|
+
const env = Object.entries(serviceEnv(spec, "systemd"))
|
|
22
|
+
.map(([k, v]) => `Environment=${quote(`${k}=${v}`)}`)
|
|
23
|
+
.join("\n");
|
|
24
|
+
return `[Unit]
|
|
25
|
+
Description=turno MCP gateway (mcpd)
|
|
26
|
+
Documentation=https://github.com/wimo-dev/turno
|
|
27
|
+
|
|
28
|
+
[Service]
|
|
29
|
+
Type=simple
|
|
30
|
+
ExecStart=${serviceArgs(spec).map(quote).join(" ")}
|
|
31
|
+
${env}
|
|
32
|
+
Restart=on-failure
|
|
33
|
+
RestartSec=5
|
|
34
|
+
|
|
35
|
+
[Install]
|
|
36
|
+
WantedBy=default.target
|
|
37
|
+
`;
|
|
38
|
+
}
|
|
39
|
+
/** The ExecStart words of a unit written by `unit()`. */
|
|
40
|
+
export function unitProgram(text) {
|
|
41
|
+
const line = /^ExecStart=(.*)$/m.exec(text)?.[1];
|
|
42
|
+
if (!line)
|
|
43
|
+
return [];
|
|
44
|
+
return [...line.matchAll(/"((?:[^"\\]|\\.)*)"|(\S+)/g)].map((m) => (m[1] !== undefined ? unquote(m[1]) : m[2]));
|
|
45
|
+
}
|
|
46
|
+
const ctl = (env, ...args) => runTool("systemctl", ["--user", ...args], env);
|
|
47
|
+
export const systemd = {
|
|
48
|
+
kind: "systemd",
|
|
49
|
+
noun: "systemd user unit",
|
|
50
|
+
file: unitPath,
|
|
51
|
+
render: unit,
|
|
52
|
+
programOf: unitProgram,
|
|
53
|
+
async isLoaded(env) {
|
|
54
|
+
try {
|
|
55
|
+
await ctl(env, "is-enabled", "--quiet", UNIT);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
try {
|
|
60
|
+
await ctl(env, "is-active", "--quiet", UNIT);
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
async load(env) {
|
|
69
|
+
await ctl(env, "daemon-reload");
|
|
70
|
+
await ctl(env, "enable", UNIT);
|
|
71
|
+
await ctl(env, "restart", UNIT);
|
|
72
|
+
},
|
|
73
|
+
async unload(env) {
|
|
74
|
+
await ctl(env, "disable", "--now", UNIT);
|
|
75
|
+
},
|
|
76
|
+
async restart(env) {
|
|
77
|
+
await ctl(env, "restart", UNIT);
|
|
78
|
+
},
|
|
79
|
+
};
|
|
80
|
+
//# sourceMappingURL=systemd.js.map
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { readFileSync, rmSync } from "node:fs";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { atomicWrite } from "../core/journal.js";
|
|
5
|
+
import { ensurePrivateDir, paths } from "../core/paths.js";
|
|
6
|
+
/**
|
|
7
|
+
* Per-profile gateway tokens (ADR 0023). Each profile's agent config carries its own token,
|
|
8
|
+
* derived from the master token so mcpd needs no list of them:
|
|
9
|
+
*
|
|
10
|
+
* tp1.<profile>.<base64url(HMAC-SHA256(master, "profile:" + profile))>
|
|
11
|
+
*
|
|
12
|
+
* The profile name travels in clear (it is not a secret, the MAC is), so the gateway reads the
|
|
13
|
+
* profile from the token itself and never from a header. Rotating the master token invalidates
|
|
14
|
+
* every derived token at once.
|
|
15
|
+
*/
|
|
16
|
+
const PREFIX = "tp1";
|
|
17
|
+
const SHAPE = /^tp1\.([a-z0-9][a-z0-9_-]*)\.([A-Za-z0-9_-]{43})$/;
|
|
18
|
+
/** The token profile `profile` uses to reach mcpd. */
|
|
19
|
+
export function profileToken(master, profile) {
|
|
20
|
+
const mac = createHmac("sha256", master).update(`profile:${profile}`).digest("base64url");
|
|
21
|
+
return `${PREFIX}.${profile}.${mac}`;
|
|
22
|
+
}
|
|
23
|
+
/** The profile a token was issued for under this master token, or undefined. */
|
|
24
|
+
export function tokenProfile(master, token) {
|
|
25
|
+
const m = SHAPE.exec(token);
|
|
26
|
+
if (!m)
|
|
27
|
+
return undefined;
|
|
28
|
+
const want = Buffer.from(profileToken(master, m[1]));
|
|
29
|
+
const got = Buffer.from(token);
|
|
30
|
+
return want.length === got.length && timingSafeEqual(want, got) ? m[1] : undefined;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Where a profile's token waits for launchers of agents that read it from the environment
|
|
34
|
+
* (Codex, Copilot, Cursor, and agents set up by hand from `turno mcp config`).
|
|
35
|
+
*/
|
|
36
|
+
export function profileTokenFile(profile, env = process.env) {
|
|
37
|
+
return join(paths(env).state, "mcpd-tokens", `${profile}.token`);
|
|
38
|
+
}
|
|
39
|
+
export function readProfileTokenFile(profile, env = process.env) {
|
|
40
|
+
try {
|
|
41
|
+
return readFileSync(profileTokenFile(profile, env), "utf8").trim() || undefined;
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return undefined;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** Write the profile's token file (mode 600) when it is missing or stale. True when it changed. */
|
|
48
|
+
export function writeProfileTokenFile(profile, master, env = process.env) {
|
|
49
|
+
const token = profileToken(master, profile);
|
|
50
|
+
if (readProfileTokenFile(profile, env) === token)
|
|
51
|
+
return false;
|
|
52
|
+
const file = profileTokenFile(profile, env);
|
|
53
|
+
ensurePrivateDir(dirname(file), env);
|
|
54
|
+
atomicWrite(file, `${token}\n`, 0o600);
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Profiles whose token file `turno mcp sync` wrote, so a later sync removes only its own files
|
|
59
|
+
* once their profile is gone; files written for agents set up by hand (`turno mcp config`, any
|
|
60
|
+
* name) stay.
|
|
61
|
+
*/
|
|
62
|
+
function syncedListFile(env) {
|
|
63
|
+
return join(dirname(profileTokenFile("x", env)), "synced.json");
|
|
64
|
+
}
|
|
65
|
+
export function readSyncedTokenProfiles(env = process.env) {
|
|
66
|
+
try {
|
|
67
|
+
const v = JSON.parse(readFileSync(syncedListFile(env), "utf8"));
|
|
68
|
+
return Array.isArray(v) ? v.filter((x) => typeof x === "string") : [];
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return [];
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
export function writeSyncedTokenProfiles(names, env = process.env) {
|
|
75
|
+
const file = syncedListFile(env);
|
|
76
|
+
ensurePrivateDir(dirname(file), env);
|
|
77
|
+
atomicWrite(file, `${JSON.stringify([...new Set(names)].sort())}\n`, 0o600);
|
|
78
|
+
}
|
|
79
|
+
/** Delete a profile's token file; true when there was one. */
|
|
80
|
+
export function removeProfileTokenFile(profile, env = process.env) {
|
|
81
|
+
try {
|
|
82
|
+
rmSync(profileTokenFile(profile, env));
|
|
83
|
+
return true;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return false;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
//# sourceMappingURL=tokens.js.map
|