turno-cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/LICENSE +202 -0
- package/NOTICE +18 -0
- package/README.md +335 -2
- package/dist/accounts/audit.js +54 -0
- package/dist/accounts/builtin.js +214 -0
- package/dist/accounts/delegate.js +185 -0
- package/dist/accounts/registry.js +190 -0
- package/dist/agents/index.js +101 -0
- package/dist/agents/snippets.js +64 -0
- package/dist/cli/args.js +47 -0
- package/dist/cli/commands/accounts.js +216 -0
- package/dist/cli/commands/auto.js +44 -0
- package/dist/cli/commands/available.js +18 -0
- package/dist/cli/commands/browser.js +175 -0
- package/dist/cli/commands/complete.js +112 -0
- package/dist/cli/commands/completion.js +57 -0
- package/dist/cli/commands/config.js +168 -0
- package/dist/cli/commands/doctor.js +324 -0
- package/dist/cli/commands/exhausted.js +40 -0
- package/dist/cli/commands/handoff.js +118 -0
- package/dist/cli/commands/hook.js +63 -0
- package/dist/cli/commands/identity.js +114 -0
- package/dist/cli/commands/limit.js +102 -0
- package/dist/cli/commands/mcp.js +350 -0
- package/dist/cli/commands/mcpd.js +161 -0
- package/dist/cli/commands/migrate.js +176 -0
- package/dist/cli/commands/open.js +60 -0
- package/dist/cli/commands/profile.js +259 -0
- package/dist/cli/commands/resolve.js +23 -0
- package/dist/cli/commands/run.js +15 -0
- package/dist/cli/commands/secret.js +123 -0
- package/dist/cli/commands/session.js +36 -0
- package/dist/cli/commands/sessions.js +27 -0
- package/dist/cli/commands/setup.js +224 -0
- package/dist/cli/commands/status.js +101 -0
- package/dist/cli/commands/statusline.js +275 -0
- package/dist/cli/commands/ui.js +276 -0
- package/dist/cli/commands/undo.js +67 -0
- package/dist/cli/commands/update-check.js +22 -0
- package/dist/cli/commands/upgrade.js +162 -0
- package/dist/cli/commands/usage.js +167 -0
- package/dist/cli/commands/version.js +27 -0
- package/dist/cli/commands/which.js +28 -0
- package/dist/cli/group.js +50 -0
- package/dist/cli/io.js +22 -0
- package/dist/cli/launch.js +98 -0
- package/dist/cli/launchers.js +200 -0
- package/dist/cli/main.js +94 -0
- package/dist/cli/registry.js +77 -0
- package/dist/core/config-edit.js +42 -0
- package/dist/core/config.js +137 -0
- package/dist/core/exhausted.js +30 -0
- package/dist/core/journal.js +185 -0
- package/dist/core/manifest.js +177 -0
- package/dist/core/paths.js +54 -0
- package/dist/core/profiles.js +61 -0
- package/dist/core/ratelimit.js +39 -0
- package/dist/core/resolve.js +78 -0
- package/dist/core/secrets.js +44 -0
- package/dist/core/sessions.js +173 -0
- package/dist/core/toml-edit.js +152 -0
- package/dist/core/update.js +102 -0
- package/dist/core/version.js +109 -0
- package/dist/mcpd/cache.js +41 -0
- package/dist/mcpd/connectors.js +63 -0
- package/dist/mcpd/daemon.js +163 -0
- package/dist/mcpd/gateway.js +308 -0
- package/dist/mcpd/importer.js +160 -0
- package/dist/mcpd/instances.js +303 -0
- package/dist/mcpd/jsonrpc.js +19 -0
- package/dist/mcpd/launchd.js +86 -0
- package/dist/mcpd/peerpid.js +25 -0
- package/dist/mcpd/sync.js +208 -0
- package/dist/mcpd/upstream.js +232 -0
- package/dist/statusline/cost.js +135 -0
- package/dist/statusline/render.js +246 -0
- package/dist/ui/cmap.js +57 -0
- package/dist/ui/fonts.js +107 -0
- package/dist/ui/settings.js +69 -0
- package/dist/ui/terminal-id.js +30 -0
- package/dist/ui/terminals.js +163 -0
- package/package.json +69 -3
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import { existsSync, realpathSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { effectiveLaunch, variantKey } from "../core/manifest.js";
|
|
5
|
+
import { resolveRecord } from "../core/secrets.js";
|
|
6
|
+
import { fingerprint } from "./cache.js";
|
|
7
|
+
import { ErrorCode, rpcError } from "./jsonrpc.js";
|
|
8
|
+
import { Upstream } from "./upstream.js";
|
|
9
|
+
export function processAlive(pid) {
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, 0);
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
catch (err) {
|
|
15
|
+
return err.code === "EPERM";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
/** Git top level of a folder (worktree-specific), else the folder itself. */
|
|
19
|
+
export function projectRoot(cwd) {
|
|
20
|
+
try {
|
|
21
|
+
return execFileSync("git", ["-C", cwd, "rev-parse", "--show-toplevel"], {
|
|
22
|
+
encoding: "utf8",
|
|
23
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
24
|
+
timeout: 3000,
|
|
25
|
+
}).trim();
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
try {
|
|
29
|
+
return realpathSync(cwd);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return cwd;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function variantOf(server, profile) {
|
|
37
|
+
return server.kind === "stdio" ? variantKey(server, profile) : "default";
|
|
38
|
+
}
|
|
39
|
+
export function scopeOf(server) {
|
|
40
|
+
if (server.kind === "remote")
|
|
41
|
+
return "shared";
|
|
42
|
+
if (server.builtin)
|
|
43
|
+
return "session";
|
|
44
|
+
return server.scope;
|
|
45
|
+
}
|
|
46
|
+
export function descriptionFingerprint(server, variant) {
|
|
47
|
+
if (server.kind === "remote")
|
|
48
|
+
return fingerprint({ url: server.url, headers: Object.keys(server.headers) });
|
|
49
|
+
const launch = effectiveLaunch(server, variant);
|
|
50
|
+
return fingerprint({ c: launch.command, a: launch.args, e: launch.env, v: variant, p: server.package ?? null, b: server.builtin ?? null });
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Owns every running upstream. Starts them lazily, shares or isolates them by scope,
|
|
54
|
+
* hands out exclusive leases, and stops them when their owner dies or they go idle.
|
|
55
|
+
*/
|
|
56
|
+
export class InstanceManager {
|
|
57
|
+
opts;
|
|
58
|
+
instances = new Map();
|
|
59
|
+
starting = new Map();
|
|
60
|
+
describing = new Map();
|
|
61
|
+
clients = new Set();
|
|
62
|
+
isAlive;
|
|
63
|
+
now;
|
|
64
|
+
constructor(opts) {
|
|
65
|
+
this.opts = opts;
|
|
66
|
+
this.isAlive = opts.isAlive ?? processAlive;
|
|
67
|
+
this.now = opts.now ?? Date.now;
|
|
68
|
+
}
|
|
69
|
+
register(client) {
|
|
70
|
+
this.clients.add(client);
|
|
71
|
+
}
|
|
72
|
+
/** A client session ended: drop it from every instance and release its leases. */
|
|
73
|
+
detach(client) {
|
|
74
|
+
this.clients.delete(client);
|
|
75
|
+
for (const inst of this.instances.values()) {
|
|
76
|
+
if (inst.clients.delete(client))
|
|
77
|
+
inst.upstream.forgetClient(client);
|
|
78
|
+
if (inst.holder === client) {
|
|
79
|
+
delete inst.holder;
|
|
80
|
+
delete inst.holderSince;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
keyOf(ctx) {
|
|
85
|
+
const s = ctx.server;
|
|
86
|
+
const variant = variantOf(s, ctx.profile);
|
|
87
|
+
const descKey = `${s.name}@${variant}`;
|
|
88
|
+
const scope = scopeOf(s);
|
|
89
|
+
if (scope === "shared")
|
|
90
|
+
return { key: `${s.name}|${variant}`, descKey, variant, workdir: this.opts.home };
|
|
91
|
+
if (scope === "project") {
|
|
92
|
+
const root = ctx.cwd ? projectRoot(ctx.cwd) : this.opts.home;
|
|
93
|
+
return { key: `${s.name}|${variant}|root:${root}`, descKey, variant, workdir: root };
|
|
94
|
+
}
|
|
95
|
+
const workdir = ctx.cwd && existsSync(ctx.cwd) ? ctx.cwd : this.opts.home;
|
|
96
|
+
if (ctx.pid)
|
|
97
|
+
return { key: `${s.name}|${variant}|pid:${ctx.pid}`, descKey, variant, workdir, pid: ctx.pid };
|
|
98
|
+
return { key: `${s.name}|${variant}|sid:${ctx.sessionId}`, descKey, variant, workdir };
|
|
99
|
+
}
|
|
100
|
+
/** Description for initialize and the list methods: cached, else from a (kept) running instance. */
|
|
101
|
+
async describe(client) {
|
|
102
|
+
const { descKey, variant } = this.keyOf(client.ctx);
|
|
103
|
+
const fp = descriptionFingerprint(client.ctx.server, variant);
|
|
104
|
+
const cached = this.opts.cache.get(descKey, fp);
|
|
105
|
+
if (cached)
|
|
106
|
+
return cached;
|
|
107
|
+
let p = this.describing.get(descKey);
|
|
108
|
+
if (!p) {
|
|
109
|
+
p = (async () => {
|
|
110
|
+
const inst = await this.instanceFor(client, false);
|
|
111
|
+
return this.refreshDescription(inst);
|
|
112
|
+
})();
|
|
113
|
+
this.describing.set(descKey, p);
|
|
114
|
+
p.finally(() => this.describing.delete(descKey)).catch(() => { });
|
|
115
|
+
}
|
|
116
|
+
return p;
|
|
117
|
+
}
|
|
118
|
+
/** The instance that serves a real request from this client (starts it, checks leases). */
|
|
119
|
+
async acquire(client) {
|
|
120
|
+
let inst;
|
|
121
|
+
try {
|
|
122
|
+
inst = await this.instanceFor(client, true);
|
|
123
|
+
}
|
|
124
|
+
catch (err) {
|
|
125
|
+
return rpcError(ErrorCode.Unavailable, `could not start ${client.ctx.server.name}: ${err.message}`);
|
|
126
|
+
}
|
|
127
|
+
const s = client.ctx.server;
|
|
128
|
+
if (s.kind === "stdio" && s.exclusive) {
|
|
129
|
+
this.expireLease(inst);
|
|
130
|
+
if (inst.holder && inst.holder !== client) {
|
|
131
|
+
const h = inst.holder.ctx;
|
|
132
|
+
return rpcError(ErrorCode.Busy, `${s.name} is in use by another session (profile ${h.profile ?? "?"}, pid ${h.pid ?? "?"}) since ${new Date(inst.holderSince ?? 0).toLocaleTimeString("en-US", { hour12: false })}. Try again later or close that session.`);
|
|
133
|
+
}
|
|
134
|
+
if (inst.holder !== client) {
|
|
135
|
+
inst.holder = client;
|
|
136
|
+
inst.holderSince = this.now();
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
inst.clients.add(client);
|
|
140
|
+
return inst;
|
|
141
|
+
}
|
|
142
|
+
/** Instance already serving this client, if any (no start). */
|
|
143
|
+
existing(client) {
|
|
144
|
+
const inst = this.instances.get(this.keyOf(client.ctx).key);
|
|
145
|
+
return inst && !inst.upstream.isClosed ? inst : undefined;
|
|
146
|
+
}
|
|
147
|
+
async refreshDescription(inst) {
|
|
148
|
+
const init = inst.upstream.init;
|
|
149
|
+
if (!init)
|
|
150
|
+
throw new Error(`${inst.server.name} is not initialized`);
|
|
151
|
+
const caps = init.capabilities;
|
|
152
|
+
const d = {
|
|
153
|
+
fingerprint: descriptionFingerprint(inst.server, inst.variant),
|
|
154
|
+
serverInfo: init.serverInfo,
|
|
155
|
+
capabilities: caps,
|
|
156
|
+
...(init.instructions ? { instructions: init.instructions } : {}),
|
|
157
|
+
updatedAt: this.now(),
|
|
158
|
+
};
|
|
159
|
+
if (caps.tools)
|
|
160
|
+
d.tools = await inst.upstream.listAll("tools/list", "tools");
|
|
161
|
+
if (caps.prompts)
|
|
162
|
+
d.prompts = await inst.upstream.listAll("prompts/list", "prompts");
|
|
163
|
+
if (caps.resources) {
|
|
164
|
+
d.resources = await inst.upstream.listAll("resources/list", "resources");
|
|
165
|
+
d.resourceTemplates = await inst.upstream.listAll("resources/templates/list", "resourceTemplates").catch(() => []);
|
|
166
|
+
}
|
|
167
|
+
this.opts.cache.set(inst.descKey, d);
|
|
168
|
+
return d;
|
|
169
|
+
}
|
|
170
|
+
async instanceFor(client, join) {
|
|
171
|
+
const k = this.keyOf(client.ctx);
|
|
172
|
+
const existing = this.instances.get(k.key);
|
|
173
|
+
if (existing && !existing.upstream.isClosed) {
|
|
174
|
+
if (join)
|
|
175
|
+
existing.clients.add(client);
|
|
176
|
+
return existing;
|
|
177
|
+
}
|
|
178
|
+
let p = this.starting.get(k.key);
|
|
179
|
+
if (!p) {
|
|
180
|
+
p = this.start(client.ctx, k);
|
|
181
|
+
this.starting.set(k.key, p);
|
|
182
|
+
p.finally(() => this.starting.delete(k.key)).catch(() => { });
|
|
183
|
+
}
|
|
184
|
+
const inst = await p;
|
|
185
|
+
if (join)
|
|
186
|
+
inst.clients.add(client);
|
|
187
|
+
return inst;
|
|
188
|
+
}
|
|
189
|
+
async start(ctx, k) {
|
|
190
|
+
const server = ctx.server;
|
|
191
|
+
const { transport, pid } = await this.opts.connector.connect(server, k.variant, ctx, k.workdir);
|
|
192
|
+
let inst;
|
|
193
|
+
const upstream = new Upstream({
|
|
194
|
+
label: `${server.name}${k.variant === "default" ? "" : `@${k.variant}`}`,
|
|
195
|
+
connect: async () => transport,
|
|
196
|
+
pid,
|
|
197
|
+
onBroadcast: (method, params) => this.onBroadcast(inst, method, params),
|
|
198
|
+
onClose: (reason) => {
|
|
199
|
+
if (this.instances.get(k.key) === inst)
|
|
200
|
+
this.instances.delete(k.key);
|
|
201
|
+
this.opts.log?.(`stopped ${inst.upstream.label} (${reason})`);
|
|
202
|
+
},
|
|
203
|
+
});
|
|
204
|
+
inst = {
|
|
205
|
+
key: k.key,
|
|
206
|
+
descKey: k.descKey,
|
|
207
|
+
server,
|
|
208
|
+
variant: k.variant,
|
|
209
|
+
upstream,
|
|
210
|
+
clients: new Set(),
|
|
211
|
+
workdir: k.workdir,
|
|
212
|
+
...(k.pid ? { pid: k.pid } : {}),
|
|
213
|
+
};
|
|
214
|
+
await upstream.start();
|
|
215
|
+
this.instances.set(k.key, inst);
|
|
216
|
+
this.opts.log?.(`started ${upstream.label} pid=${upstream.pid ?? "-"} key=${k.key}`);
|
|
217
|
+
return inst;
|
|
218
|
+
}
|
|
219
|
+
onBroadcast(inst, method, params) {
|
|
220
|
+
if (method.endsWith("/list_changed")) {
|
|
221
|
+
this.refreshDescription(inst)
|
|
222
|
+
.then(() => {
|
|
223
|
+
for (const c of this.clients) {
|
|
224
|
+
if (this.keyOf(c.ctx).descKey === inst.descKey)
|
|
225
|
+
c.notify(method, params);
|
|
226
|
+
}
|
|
227
|
+
})
|
|
228
|
+
.catch((err) => this.opts.log?.(`refresh ${inst.upstream.label} failed: ${err.message}`));
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
for (const c of inst.clients)
|
|
232
|
+
c.notify(method, params);
|
|
233
|
+
}
|
|
234
|
+
expireLease(inst) {
|
|
235
|
+
const s = inst.server;
|
|
236
|
+
if (!inst.holder || s.kind !== "stdio")
|
|
237
|
+
return;
|
|
238
|
+
const h = inst.holder;
|
|
239
|
+
const dead = h.ctx.pid ? !this.isAlive(h.ctx.pid) : false;
|
|
240
|
+
const idle = this.now() - h.lastSeen > s.lease * 1000;
|
|
241
|
+
if (dead || idle || !this.clients.has(h)) {
|
|
242
|
+
delete inst.holder;
|
|
243
|
+
delete inst.holderSince;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/** Stop instances whose owner died or that sat idle too long; forget dead clients. */
|
|
247
|
+
async reap() {
|
|
248
|
+
const stopped = [];
|
|
249
|
+
for (const c of [...this.clients]) {
|
|
250
|
+
if (c.ctx.pid && !this.isAlive(c.ctx.pid))
|
|
251
|
+
this.detach(c);
|
|
252
|
+
}
|
|
253
|
+
for (const inst of [...this.instances.values()]) {
|
|
254
|
+
this.expireLease(inst);
|
|
255
|
+
const s = inst.server;
|
|
256
|
+
const idleLimit = (s.kind === "stdio" ? s.idle : s.idle) * 1000;
|
|
257
|
+
const ownerDead = inst.pid !== undefined && !this.isAlive(inst.pid);
|
|
258
|
+
const idle = inst.upstream.inflight === 0 && this.now() - inst.upstream.lastActivity > idleLimit;
|
|
259
|
+
if (ownerDead || idle) {
|
|
260
|
+
this.instances.delete(inst.key);
|
|
261
|
+
await inst.upstream.close();
|
|
262
|
+
stopped.push(`${inst.upstream.label}: ${ownerDead ? "owner exited" : "idle"}`);
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
return stopped;
|
|
266
|
+
}
|
|
267
|
+
list() {
|
|
268
|
+
return [...this.instances.values()];
|
|
269
|
+
}
|
|
270
|
+
clientCount() {
|
|
271
|
+
return this.clients.size;
|
|
272
|
+
}
|
|
273
|
+
async stopAll() {
|
|
274
|
+
const all = [...this.instances.values()];
|
|
275
|
+
this.instances.clear();
|
|
276
|
+
await Promise.all(all.map((i) => i.upstream.close()));
|
|
277
|
+
}
|
|
278
|
+
async stop(key) {
|
|
279
|
+
const inst = this.instances.get(key);
|
|
280
|
+
if (!inst)
|
|
281
|
+
return false;
|
|
282
|
+
this.instances.delete(key);
|
|
283
|
+
await inst.upstream.close();
|
|
284
|
+
return true;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Resolve a command against an installed package (turno mcp install). A declared package
|
|
289
|
+
* that is not installed yet runs through `npx -y -p <package> <command>` so it still works.
|
|
290
|
+
*/
|
|
291
|
+
export function resolveCommand(server, command, args, serversDir) {
|
|
292
|
+
if (server.package) {
|
|
293
|
+
const local = join(serversDir, server.name, "node_modules", ".bin", command);
|
|
294
|
+
if (existsSync(local))
|
|
295
|
+
return { command: local, args };
|
|
296
|
+
return { command: "npx", args: ["-y", "-p", server.package, command, ...args] };
|
|
297
|
+
}
|
|
298
|
+
return { command, args };
|
|
299
|
+
}
|
|
300
|
+
export async function resolvedEnv(server, variant, resolve) {
|
|
301
|
+
return resolveRecord(effectiveLaunch(server, variant).env, resolve);
|
|
302
|
+
}
|
|
303
|
+
//# sourceMappingURL=instances.js.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export const isRequest = (m) => typeof m.method === "string" && m.id !== undefined && m.id !== null;
|
|
2
|
+
export const isNotification = (m) => typeof m.method === "string" && (m.id === undefined || m.id === null);
|
|
3
|
+
export const isResponse = (m) => m.method === undefined && m.id !== undefined && ("result" in m || "error" in m);
|
|
4
|
+
export const ErrorCode = {
|
|
5
|
+
MethodNotFound: -32601,
|
|
6
|
+
InvalidParams: -32602,
|
|
7
|
+
Internal: -32603,
|
|
8
|
+
/** Server-defined: the upstream could not be started or is unavailable. */
|
|
9
|
+
Unavailable: -32002,
|
|
10
|
+
/** Server-defined: an exclusive server is held by another session. */
|
|
11
|
+
Busy: -32003,
|
|
12
|
+
};
|
|
13
|
+
export function toResponse(id, outcome) {
|
|
14
|
+
return "error" in outcome ? { jsonrpc: "2.0", id, error: outcome.error } : { jsonrpc: "2.0", id, result: outcome.result };
|
|
15
|
+
}
|
|
16
|
+
export function rpcError(code, message, data) {
|
|
17
|
+
return { error: data === undefined ? { code, message } : { code, message, data } };
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=jsonrpc.js.map
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { paths } from "../core/paths.js";
|
|
6
|
+
const run = promisify(execFile);
|
|
7
|
+
export const LABEL = "dev.turno.mcpd";
|
|
8
|
+
export function plistPath(env = process.env) {
|
|
9
|
+
return join(paths(env).home, "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
10
|
+
}
|
|
11
|
+
function xml(s) {
|
|
12
|
+
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
13
|
+
}
|
|
14
|
+
/** LaunchAgent that keeps `turno mcpd run` alive, with the caller's PATH (launchd's is minimal). */
|
|
15
|
+
export function plist(opts) {
|
|
16
|
+
const p = paths(opts.env);
|
|
17
|
+
const vars = {
|
|
18
|
+
PATH: opts.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
|
|
19
|
+
HOME: p.home,
|
|
20
|
+
};
|
|
21
|
+
for (const k of ["XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_DATA_HOME", "LANG"])
|
|
22
|
+
if (opts.env[k])
|
|
23
|
+
vars[k] = opts.env[k];
|
|
24
|
+
const envXml = Object.entries(vars)
|
|
25
|
+
.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
|
|
26
|
+
.join("\n");
|
|
27
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
28
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
29
|
+
<plist version="1.0">
|
|
30
|
+
<dict>
|
|
31
|
+
<key>Label</key>
|
|
32
|
+
<string>${LABEL}</string>
|
|
33
|
+
<key>ProgramArguments</key>
|
|
34
|
+
<array>
|
|
35
|
+
<string>${xml(opts.node)}</string>
|
|
36
|
+
<string>${xml(opts.script)}</string>
|
|
37
|
+
<string>mcpd</string>
|
|
38
|
+
<string>run</string>
|
|
39
|
+
</array>
|
|
40
|
+
<key>EnvironmentVariables</key>
|
|
41
|
+
<dict>
|
|
42
|
+
${envXml}
|
|
43
|
+
</dict>
|
|
44
|
+
<key>RunAtLoad</key>
|
|
45
|
+
<true/>
|
|
46
|
+
<key>KeepAlive</key>
|
|
47
|
+
<true/>
|
|
48
|
+
<key>ProcessType</key>
|
|
49
|
+
<string>Background</string>
|
|
50
|
+
<key>StandardOutPath</key>
|
|
51
|
+
<string>${xml(join(p.logsDir, "mcpd.stdout.log"))}</string>
|
|
52
|
+
<key>StandardErrorPath</key>
|
|
53
|
+
<string>${xml(join(p.logsDir, "mcpd.stderr.log"))}</string>
|
|
54
|
+
</dict>
|
|
55
|
+
</plist>
|
|
56
|
+
`;
|
|
57
|
+
}
|
|
58
|
+
function domain() {
|
|
59
|
+
return `gui/${process.getuid?.() ?? 501}`;
|
|
60
|
+
}
|
|
61
|
+
export async function isLoaded() {
|
|
62
|
+
try {
|
|
63
|
+
await run("launchctl", ["print", `${domain()}/${LABEL}`], { timeout: 5000 });
|
|
64
|
+
return true;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return false;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export async function install(opts) {
|
|
71
|
+
const file = plistPath(opts.env);
|
|
72
|
+
mkdirSync(join(paths(opts.env).home, "Library", "LaunchAgents"), { recursive: true });
|
|
73
|
+
mkdirSync(paths(opts.env).logsDir, { recursive: true });
|
|
74
|
+
writeFileSync(file, plist(opts));
|
|
75
|
+
if (await isLoaded())
|
|
76
|
+
await run("launchctl", ["bootout", `${domain()}/${LABEL}`], { timeout: 10_000 }).catch(() => { });
|
|
77
|
+
await run("launchctl", ["bootstrap", domain(), file], { timeout: 10_000 });
|
|
78
|
+
return file;
|
|
79
|
+
}
|
|
80
|
+
export async function uninstall() {
|
|
81
|
+
await run("launchctl", ["bootout", `${domain()}/${LABEL}`], { timeout: 10_000 });
|
|
82
|
+
}
|
|
83
|
+
export async function restart() {
|
|
84
|
+
await run("launchctl", ["kickstart", "-k", `${domain()}/${LABEL}`], { timeout: 10_000 });
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=launchd.js.map
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
const run = promisify(execFile);
|
|
4
|
+
/**
|
|
5
|
+
* PID of the local process that owns the client side of a TCP connection to mcpd, found
|
|
6
|
+
* with lsof. Used when a session did not send X-Turno-Pid (not started by a launcher).
|
|
7
|
+
*/
|
|
8
|
+
export async function peerPid(remotePort, self = process.pid) {
|
|
9
|
+
try {
|
|
10
|
+
const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], { timeout: 3000 });
|
|
11
|
+
let pid;
|
|
12
|
+
for (const line of stdout.split("\n")) {
|
|
13
|
+
if (line.startsWith("p"))
|
|
14
|
+
pid = Number(line.slice(1));
|
|
15
|
+
// The client side is the socket whose local port is remotePort: "n127.0.0.1:<remotePort>->..."
|
|
16
|
+
if (line.startsWith("n") && pid && pid !== self && line.slice(1).split("->")[0]?.endsWith(`:${remotePort}`))
|
|
17
|
+
return pid;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
// lsof missing or nothing found
|
|
22
|
+
}
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
//# sourceMappingURL=peerpid.js.map
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname } from "node:path";
|
|
3
|
+
import { parse } from "smol-toml";
|
|
4
|
+
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)}`;
|
|
19
|
+
/**
|
|
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.
|
|
23
|
+
*/
|
|
24
|
+
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
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* 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).
|
|
62
|
+
*/
|
|
63
|
+
export function profileServers(manifest, profile, port, token, agent = "claude") {
|
|
64
|
+
const out = {};
|
|
65
|
+
for (const [name, def] of Object.entries(manifest.servers)) {
|
|
66
|
+
if (!servesProfile(def, profile))
|
|
67
|
+
continue;
|
|
68
|
+
if (def.kind === "remote" && !def.proxy) {
|
|
69
|
+
if (agent === "claude")
|
|
70
|
+
out[name] = { ...def.entry };
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
out[name] = gatewayEntryFor(agent, name, port, token, profile);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
export function readManaged(file) {
|
|
78
|
+
try {
|
|
79
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
80
|
+
}
|
|
81
|
+
catch {
|
|
82
|
+
return {};
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
export function writeManaged(file, state) {
|
|
86
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
87
|
+
writeFileSync(file, `${JSON.stringify(state, null, 2)}\n`);
|
|
88
|
+
}
|
|
89
|
+
/** Decide what changes in a server map; mutates `servers`. */
|
|
90
|
+
function plan(servers, wanted, previouslyManaged, opts) {
|
|
91
|
+
const res = { added: [], updated: [], removed: [], foreign: [], replaced: [], changed: false };
|
|
92
|
+
const managed = new Set(previouslyManaged);
|
|
93
|
+
for (const name of Object.keys(servers)) {
|
|
94
|
+
if (!(name in wanted) && managed.has(name)) {
|
|
95
|
+
delete servers[name];
|
|
96
|
+
res.removed.push(name);
|
|
97
|
+
}
|
|
98
|
+
else if (!(name in wanted)) {
|
|
99
|
+
res.foreign.push(name);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
for (const [name, entry] of Object.entries(wanted)) {
|
|
103
|
+
const before = servers[name];
|
|
104
|
+
if (before === undefined)
|
|
105
|
+
res.added.push(name);
|
|
106
|
+
else if (JSON.stringify(before) !== JSON.stringify(entry)) {
|
|
107
|
+
if (!managed.has(name)) {
|
|
108
|
+
res.replaced.push(name);
|
|
109
|
+
opts.backup?.(name, before);
|
|
110
|
+
}
|
|
111
|
+
res.updated.push(name);
|
|
112
|
+
}
|
|
113
|
+
else
|
|
114
|
+
continue;
|
|
115
|
+
servers[name] = entry;
|
|
116
|
+
}
|
|
117
|
+
res.changed = res.added.length + res.updated.length + res.removed.length > 0;
|
|
118
|
+
return res;
|
|
119
|
+
}
|
|
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
|
+
/**
|
|
128
|
+
* Rewrite the server map under `key` of a JSON config file (Claude Code `.claude.json`,
|
|
129
|
+
* Copilot `mcp-config.json`, Cursor `mcp.json`): add or update manifest entries, remove
|
|
130
|
+
* entries turno wrote earlier that left the manifest, keep everything else.
|
|
131
|
+
*/
|
|
132
|
+
export function syncJsonServers(configFile, key, wanted, previouslyManaged, opts = {}) {
|
|
133
|
+
const cfg = existsSync(configFile) ? JSON.parse(readFileSync(configFile, "utf8")) : {};
|
|
134
|
+
const servers = { ...(cfg[key] ?? {}) };
|
|
135
|
+
const res = plan(servers, wanted, previouslyManaged, opts);
|
|
136
|
+
if (res.changed && !opts.dryRun)
|
|
137
|
+
writeAtomic(configFile, `${JSON.stringify({ ...cfg, [key]: servers }, null, 2)}\n`);
|
|
138
|
+
return res;
|
|
139
|
+
}
|
|
140
|
+
/** The mcpServers of a Claude Code config file. */
|
|
141
|
+
export function syncConfigFile(configFile, wanted, previouslyManaged, opts = {}) {
|
|
142
|
+
return syncJsonServers(configFile, "mcpServers", wanted, previouslyManaged, opts);
|
|
143
|
+
}
|
|
144
|
+
const BARE_KEY = /^[A-Za-z0-9_-]+$/;
|
|
145
|
+
const tomlKey = (k) => (BARE_KEY.test(k) ? k : JSON.stringify(k));
|
|
146
|
+
function tomlValue(v) {
|
|
147
|
+
if (typeof v === "string")
|
|
148
|
+
return JSON.stringify(v);
|
|
149
|
+
if (typeof v === "number" || typeof v === "boolean")
|
|
150
|
+
return String(v);
|
|
151
|
+
if (Array.isArray(v))
|
|
152
|
+
return `[${v.map(tomlValue).join(", ")}]`;
|
|
153
|
+
if (v && typeof v === "object") {
|
|
154
|
+
return `{ ${Object.entries(v).map(([k, x]) => `${tomlKey(k)} = ${tomlValue(x)}`).join(", ")} }`;
|
|
155
|
+
}
|
|
156
|
+
throw new Error(`cannot write ${String(v)} as TOML`);
|
|
157
|
+
}
|
|
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*(#.*)?$/;
|
|
161
|
+
const anyHeader = /^\s*\[/;
|
|
162
|
+
const out = new Map();
|
|
163
|
+
for (let i = 0; i < lines.length; i++) {
|
|
164
|
+
const m = header.exec(lines[i]);
|
|
165
|
+
if (!m)
|
|
166
|
+
continue;
|
|
167
|
+
const name = m[1].startsWith('"') ? JSON.parse(m[1]) : m[1];
|
|
168
|
+
let end = i + 1;
|
|
169
|
+
while (end < lines.length && !anyHeader.test(lines[end]))
|
|
170
|
+
end++;
|
|
171
|
+
const prev = out.get(name);
|
|
172
|
+
out.set(name, prev ? [prev[0], end] : [i, end]);
|
|
173
|
+
}
|
|
174
|
+
return out;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
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.
|
|
179
|
+
*/
|
|
180
|
+
export function syncCodexToml(configFile, wanted, previouslyManaged, opts = {}) {
|
|
181
|
+
const text = existsSync(configFile) ? readFileSync(configFile, "utf8") : "";
|
|
182
|
+
const current = (parse(text).mcp_servers ?? {});
|
|
183
|
+
const servers = { ...current };
|
|
184
|
+
const res = plan(servers, wanted, previouslyManaged, opts);
|
|
185
|
+
if (!res.changed || opts.dryRun)
|
|
186
|
+
return res;
|
|
187
|
+
let lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
|
|
188
|
+
// Drop the tables that go or change, from the bottom up so ranges stay valid.
|
|
189
|
+
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]);
|
|
191
|
+
for (const [start, end] of ranges)
|
|
192
|
+
lines.splice(start, end - start);
|
|
193
|
+
for (const name of [...res.updated, ...res.added]) {
|
|
194
|
+
while (lines.length && lines[lines.length - 1].trim() === "")
|
|
195
|
+
lines.pop();
|
|
196
|
+
if (lines.length)
|
|
197
|
+
lines.push("");
|
|
198
|
+
lines.push(`[mcp_servers.${tomlKey(name)}]`);
|
|
199
|
+
for (const [k, v] of Object.entries(wanted[name]))
|
|
200
|
+
lines.push(`${tomlKey(k)} = ${tomlValue(v)}`);
|
|
201
|
+
}
|
|
202
|
+
lines = lines.length ? lines : [];
|
|
203
|
+
const next = `${lines.join("\n")}\n`;
|
|
204
|
+
parse(next); // never write a file Codex cannot read
|
|
205
|
+
writeAtomic(configFile, next);
|
|
206
|
+
return res;
|
|
207
|
+
}
|
|
208
|
+
//# sourceMappingURL=sync.js.map
|