turno-cli 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/CHANGELOG.md +432 -0
  2. package/README.md +228 -73
  3. package/dist/accounts/audit.js +154 -12
  4. package/dist/accounts/builtin.js +100 -25
  5. package/dist/accounts/delegate.js +199 -35
  6. package/dist/accounts/policy.js +79 -0
  7. package/dist/accounts/registry.js +39 -21
  8. package/dist/agents/adapter.js +29 -0
  9. package/dist/agents/claude.js +246 -0
  10. package/dist/agents/codex.js +186 -0
  11. package/dist/agents/copilot.js +56 -0
  12. package/dist/agents/cursor.js +58 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +43 -13
  15. package/dist/cli/args.js +38 -6
  16. package/dist/cli/commands/accounts.js +119 -52
  17. package/dist/cli/commands/auto.js +121 -33
  18. package/dist/cli/commands/browser-identity.js +514 -0
  19. package/dist/cli/commands/browser-session.js +102 -0
  20. package/dist/cli/commands/browser-vault.js +193 -0
  21. package/dist/cli/commands/browser.js +319 -138
  22. package/dist/cli/commands/complete.js +14 -3
  23. package/dist/cli/commands/completion.js +8 -2
  24. package/dist/cli/commands/config.js +186 -24
  25. package/dist/cli/commands/demo.js +321 -0
  26. package/dist/cli/commands/doctor.js +525 -123
  27. package/dist/cli/commands/handoff.js +33 -22
  28. package/dist/cli/commands/identity.js +192 -54
  29. package/dist/cli/commands/init.js +648 -0
  30. package/dist/cli/commands/limit.js +84 -16
  31. package/dist/cli/commands/mcp-call.js +240 -0
  32. package/dist/cli/commands/mcp-oauth.js +221 -0
  33. package/dist/cli/commands/mcp-observe.js +539 -0
  34. package/dist/cli/commands/mcp-share.js +201 -0
  35. package/dist/cli/commands/mcp.js +816 -187
  36. package/dist/cli/commands/mcpd.js +388 -76
  37. package/dist/cli/commands/migrate.js +6 -4
  38. package/dist/cli/commands/open.js +115 -27
  39. package/dist/cli/commands/profile.js +396 -78
  40. package/dist/cli/commands/resolve.js +14 -3
  41. package/dist/cli/commands/run.js +36 -6
  42. package/dist/cli/commands/secret.js +80 -76
  43. package/dist/cli/commands/session.js +17 -6
  44. package/dist/cli/commands/sessions.js +48 -12
  45. package/dist/cli/commands/setup.js +214 -164
  46. package/dist/cli/commands/status.js +227 -44
  47. package/dist/cli/commands/statusline.js +311 -114
  48. package/dist/cli/commands/ui.js +78 -68
  49. package/dist/cli/commands/undo.js +193 -18
  50. package/dist/cli/commands/uninstall.js +481 -0
  51. package/dist/cli/commands/upgrade.js +172 -79
  52. package/dist/cli/commands/usage.js +125 -51
  53. package/dist/cli/commands/version.js +21 -7
  54. package/dist/cli/commands/which.js +9 -24
  55. package/dist/cli/compile-cache.js +32 -0
  56. package/dist/cli/diagnostics.js +184 -0
  57. package/dist/cli/exit.js +65 -0
  58. package/dist/cli/group.js +24 -12
  59. package/dist/cli/help.js +62 -0
  60. package/dist/cli/highlight.js +236 -0
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +186 -1
  63. package/dist/cli/launch.js +52 -39
  64. package/dist/cli/launchers.js +161 -95
  65. package/dist/cli/main.js +201 -31
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +459 -0
  69. package/dist/cli/registry.js +61 -6
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +561 -0
  73. package/dist/cli/style.js +311 -0
  74. package/dist/cli/topics.js +142 -0
  75. package/dist/core/config.js +181 -23
  76. package/dist/core/exhausted.js +6 -8
  77. package/dist/core/fsutil.js +39 -0
  78. package/dist/core/journal.js +294 -16
  79. package/dist/core/manifest.js +153 -6
  80. package/dist/core/paths.js +14 -13
  81. package/dist/core/profiles.js +160 -10
  82. package/dist/core/resolve.js +139 -23
  83. package/dist/core/secrets.js +68 -23
  84. package/dist/core/sessions.js +13 -20
  85. package/dist/core/state-file.js +107 -0
  86. package/dist/core/update.js +31 -18
  87. package/dist/core/version.js +57 -10
  88. package/dist/demo/server.js +42 -0
  89. package/dist/mcpd/cache.js +23 -10
  90. package/dist/mcpd/calllog.js +254 -0
  91. package/dist/mcpd/client-names.js +46 -0
  92. package/dist/mcpd/connectors.js +188 -18
  93. package/dist/mcpd/daemon.js +472 -115
  94. package/dist/mcpd/folder-sets.js +42 -0
  95. package/dist/mcpd/gateway.js +473 -51
  96. package/dist/mcpd/health.js +313 -0
  97. package/dist/mcpd/importer.js +453 -36
  98. package/dist/mcpd/instances.js +453 -65
  99. package/dist/mcpd/jsonrpc.js +11 -1
  100. package/dist/mcpd/launchd.js +65 -48
  101. package/dist/mcpd/middleware.js +144 -0
  102. package/dist/mcpd/modern.js +686 -0
  103. package/dist/mcpd/oauth.js +845 -0
  104. package/dist/mcpd/peerpid.js +134 -6
  105. package/dist/mcpd/pressure.js +88 -0
  106. package/dist/mcpd/rss.js +166 -0
  107. package/dist/mcpd/service.js +191 -0
  108. package/dist/mcpd/share.js +217 -0
  109. package/dist/mcpd/state.js +183 -0
  110. package/dist/mcpd/sync.js +72 -87
  111. package/dist/mcpd/systemd.js +83 -0
  112. package/dist/mcpd/tokens.js +85 -0
  113. package/dist/mcpd/upstream.js +163 -46
  114. package/dist/statusline/cost.js +167 -44
  115. package/dist/statusline/input.js +78 -0
  116. package/dist/statusline/render.js +9 -3
  117. package/dist/ui/fonts.js +8 -3
  118. package/dist/ui/settings.js +33 -16
  119. package/npm-shrinkwrap.json +1102 -0
  120. package/package.json +10 -9
  121. package/dist/cli/commands/available.js +0 -18
@@ -1,52 +1,263 @@
1
- import { randomBytes } from "node:crypto";
2
- import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
1
+ import { createWriteStream, existsSync, fchmodSync, fstatSync, openSync, readFileSync, renameSync, rmSync, watch, writeFileSync, } from "node:fs";
3
2
  import { dirname, join } from "node:path";
4
3
  import { loadConfig } from "../core/config.js";
5
- import { loadManifest } from "../core/manifest.js";
6
- import { paths } from "../core/paths.js";
4
+ import { atomicWrite } from "../core/journal.js";
5
+ import { parseManifest } from "../core/manifest.js";
6
+ import { PRIVATE_FILE_MODE, ensurePrivateDir, paths } from "../core/paths.js";
7
7
  import { keychainResolver } from "../core/secrets.js";
8
+ import { packageInfo } from "../core/version.js";
8
9
  import { DescriptionCache } from "./cache.js";
10
+ import { createCallLog } from "./calllog.js";
9
11
  import { DefaultConnector } from "./connectors.js";
10
12
  import { Gateway } from "./gateway.js";
11
- import { InstanceManager, descriptionFingerprint, processAlive } from "./instances.js";
12
- import { peerPid } from "./peerpid.js";
13
- /** The bearer token sessions use; created once with mode 600. */
14
- export function ensureToken(env = process.env) {
15
- const file = paths(env).mcpdToken;
13
+ import { ClientNames } from "./client-names.js";
14
+ import { InstanceManager, descriptionFingerprint } from "./instances.js";
15
+ import { describeOwner, peerPid, portOwner } from "./peerpid.js";
16
+ import { memoryPressureProbe } from "./pressure.js";
17
+ import { RssSampler } from "./rss.js";
18
+ import { pidAlive } from "../core/fsutil.js";
19
+ import { answersAsMcpd, daemonFiles, ensureToken, isMcpdProcess, loadConfigSafe, readLock, readToken, } from "./state.js";
20
+ export { daemonFiles, loadConfigSafe, masterToken, mcpdPort, readStartError, readToken, rotateToken } from "./state.js";
21
+ /** Another mcpd already holds the lock or answers on the port. Not a failure for a supervisor. */
22
+ export class AlreadyRunningError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "AlreadyRunningError";
26
+ }
27
+ }
28
+ /** The configured port belongs to some other process. */
29
+ export class PortBusyError extends Error {
30
+ port;
31
+ constructor(message, port) {
32
+ super(message);
33
+ this.port = port;
34
+ this.name = "PortBusyError";
35
+ }
36
+ }
37
+ /** Take the single-instance lock (O_EXCL), clearing a stale one once. */
38
+ function acquireLock(env) {
39
+ const file = daemonFiles(env).lock;
40
+ ensurePrivateDir(dirname(file), env);
41
+ const body = JSON.stringify({ pid: process.pid, port: 0, startedAt: new Date().toISOString() });
42
+ for (let attempt = 0; attempt < 2; attempt++) {
43
+ try {
44
+ writeFileSync(file, `${body}\n`, { flag: "wx", mode: PRIVATE_FILE_MODE });
45
+ return;
46
+ }
47
+ catch (err) {
48
+ if (err.code !== "EEXIST")
49
+ throw err;
50
+ }
51
+ let text = "";
52
+ try {
53
+ text = readFileSync(file, "utf8");
54
+ }
55
+ catch {
56
+ continue; // removed meanwhile: try again
57
+ }
58
+ const held = readLock(env);
59
+ if (held && isMcpdProcess(held.pid)) {
60
+ throw new AlreadyRunningError(`mcpd is already running (pid ${held.pid}${held.port ? `, port ${held.port}` : ""}); stop it with: turno mcp daemon stop`);
61
+ }
62
+ // Stale: remove it only if nobody replaced it since we read it.
63
+ try {
64
+ if (readFileSync(file, "utf8") === text)
65
+ rmSync(file, { force: true });
66
+ }
67
+ catch {
68
+ /* gone already */
69
+ }
70
+ }
71
+ throw new AlreadyRunningError("another mcpd is starting right now");
72
+ }
73
+ function releaseLock(env, port) {
74
+ const f = daemonFiles(env);
75
+ if (readLock(env)?.pid !== process.pid)
76
+ return;
77
+ rmSync(f.lock, { force: true });
16
78
  try {
17
- const t = readFileSync(file, "utf8").trim();
18
- if (t.length >= 32)
19
- return t;
79
+ if (Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10) === port)
80
+ rmSync(paths(env).mcpdPort, { force: true });
20
81
  }
21
82
  catch {
22
- /* create it */
83
+ /* no port file */
23
84
  }
24
- mkdirSync(dirname(file), { recursive: true });
25
- const token = randomBytes(32).toString("hex");
26
- writeFileSync(file, `${token}\n`, { mode: 0o600 });
27
- chmodSync(file, 0o600);
28
- return token;
29
85
  }
30
- export function readToken(env = process.env) {
86
+ function writeStartError(env, e) {
87
+ const file = daemonFiles(env).error;
31
88
  try {
32
- return readFileSync(paths(env).mcpdToken, "utf8").trim() || undefined;
89
+ if (!e)
90
+ rmSync(file, { force: true });
91
+ else {
92
+ ensurePrivateDir(dirname(file), env);
93
+ atomicWrite(file, `${JSON.stringify(e)}\n`, PRIVATE_FILE_MODE);
94
+ }
33
95
  }
34
96
  catch {
35
- return undefined;
97
+ /* best effort */
36
98
  }
37
99
  }
38
- /** The port mcpd listens on: the one it recorded, else the configured one. */
39
- export function mcpdPort(env = process.env) {
100
+ /**
101
+ * The mcpd log: one append stream, rotated by size (mcpd.log.1 ... mcpd.log.<keep>), with an
102
+ * error handler so a full disk never takes the daemon down. Timestamps are UTC ISO;
103
+ * `turno mcp daemon logs` shows them in local time.
104
+ */
105
+ export function createLogger(file, opts = {}) {
106
+ const maxBytes = opts.maxBytes ?? 5 * 1024 * 1024;
107
+ const keep = opts.keep ?? 2;
108
+ let stream;
109
+ let size = 0;
110
+ let broken = false;
111
+ const onError = (err) => {
112
+ if (broken)
113
+ return;
114
+ broken = true;
115
+ try {
116
+ process.stderr.write(`mcpd: cannot write ${file}: ${err.message}\n`);
117
+ }
118
+ catch {
119
+ /* nowhere to report */
120
+ }
121
+ };
122
+ let retryAt = 0;
123
+ // Opened synchronously so the file exists before the first rotation renames it.
124
+ const open = () => {
125
+ try {
126
+ ensurePrivateDir(dirname(file), opts.env ?? process.env);
127
+ const fd = openSync(file, "a", PRIVATE_FILE_MODE);
128
+ const st = fstatSync(fd);
129
+ if (st.mode & 0o077)
130
+ fchmodSync(fd, PRIVATE_FILE_MODE);
131
+ size = st.size;
132
+ const s = createWriteStream("", { fd });
133
+ s.on("error", onError);
134
+ broken = false;
135
+ return s;
136
+ }
137
+ catch (err) {
138
+ onError(err);
139
+ retryAt = Date.now() + 30_000;
140
+ return undefined;
141
+ }
142
+ };
143
+ const rotate = () => {
144
+ stream?.end();
145
+ try {
146
+ for (let i = keep - 1; i >= 1; i--)
147
+ if (existsSync(`${file}.${i}`))
148
+ renameSync(`${file}.${i}`, `${file}.${i + 1}`);
149
+ renameSync(file, `${file}.1`);
150
+ }
151
+ catch (err) {
152
+ onError(err);
153
+ }
154
+ stream = open();
155
+ };
156
+ const log = ((line) => {
157
+ const text = `${new Date().toISOString()} ${line}\n`;
158
+ if (opts.toStdout) {
159
+ process.stdout.write(text);
160
+ return;
161
+ }
162
+ if (!stream && Date.now() >= retryAt)
163
+ stream = open();
164
+ if (!stream)
165
+ return; // the disk refused; onError said so once
166
+ const n = Buffer.byteLength(text);
167
+ if (size > 0 && size + n > maxBytes)
168
+ rotate();
169
+ stream?.write(text);
170
+ size += n;
171
+ });
172
+ log.close = () => new Promise((resolve) => (stream ? stream.end(() => resolve()) : resolve()));
173
+ return log;
174
+ }
175
+ /** Errors a socket or the disk raises that do not leave the daemon in a bad state. */
176
+ const RECOVERABLE = new Set([
177
+ "EPIPE",
178
+ "ECONNRESET",
179
+ "ECONNABORTED",
180
+ "ETIMEDOUT",
181
+ "ENOSPC",
182
+ "EIO",
183
+ "EAGAIN",
184
+ "ERR_STREAM_DESTROYED",
185
+ "ERR_STREAM_WRITE_AFTER_END",
186
+ "ERR_STREAM_PREMATURE_CLOSE",
187
+ ]);
188
+ /**
189
+ * For the daemon process only (not for tests that start mcpd in process): log unhandled
190
+ * rejections and recoverable exceptions and keep serving; on anything else log it, stop
191
+ * cleanly and exit 1 so the service manager restarts mcpd.
192
+ */
193
+ export function installCrashGuards(log, stop) {
194
+ const onRejection = (reason) => log(`unhandled rejection, still running: ${reason?.stack ?? String(reason)}`);
195
+ const onException = (err) => {
196
+ const code = err.code;
197
+ if (code && RECOVERABLE.has(code)) {
198
+ log(`uncaught ${code}, still running: ${err.stack ?? err.message}`);
199
+ return;
200
+ }
201
+ log(`fatal: ${err.stack ?? err.message}`);
202
+ let exited = false;
203
+ const exit = () => {
204
+ if (exited)
205
+ return;
206
+ exited = true;
207
+ clearTimeout(timer);
208
+ process.exit(1);
209
+ };
210
+ const timer = setTimeout(exit, 3000);
211
+ timer.unref();
212
+ stop().then(exit, exit);
213
+ };
214
+ process.on("unhandledRejection", onRejection);
215
+ process.on("uncaughtException", onException);
216
+ return () => {
217
+ process.off("unhandledRejection", onRejection);
218
+ process.off("uncaughtException", onException);
219
+ };
220
+ }
221
+ /**
222
+ * mcp.toml, never throwing: when it does not validate, the last copy that did (kept in the
223
+ * state folder on every good load), else no servers. The error is kept for /status and doctor.
224
+ */
225
+ export function loadManifestSafe(env = process.env) {
226
+ const file = paths(env).mcpFile;
227
+ const lastGood = daemonFiles(env).lastGood;
40
228
  try {
41
- const n = Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10);
42
- if (n > 0)
43
- return n;
229
+ let text = "";
230
+ try {
231
+ text = readFileSync(file, "utf8");
232
+ }
233
+ catch (err) {
234
+ if (err.code !== "ENOENT")
235
+ throw err;
236
+ }
237
+ const manifest = parseManifest(text, file);
238
+ if (text) {
239
+ try {
240
+ if (!existsSync(lastGood) || readFileSync(lastGood, "utf8") !== text)
241
+ atomicWrite(lastGood, text, 0o600);
242
+ }
243
+ catch {
244
+ /* the copy is a convenience */
245
+ }
246
+ }
247
+ return { manifest, source: "mcp.toml" };
44
248
  }
45
- catch {
46
- /* fall through */
249
+ catch (err) {
250
+ const error = err.message;
251
+ try {
252
+ return { manifest: parseManifest(readFileSync(lastGood, "utf8"), lastGood), source: "last good copy", error };
253
+ }
254
+ catch {
255
+ return { manifest: parseManifest(""), source: "empty", error };
256
+ }
47
257
  }
48
- return loadConfig(env).mcpd.port;
49
258
  }
259
+ // ---------------------------------------------------------------------------------------------
260
+ // Daemon
50
261
  async function loadBuiltins() {
51
262
  const builtins = {};
52
263
  try {
@@ -59,105 +270,251 @@ async function loadBuiltins() {
59
270
  }
60
271
  return builtins;
61
272
  }
62
- /** Start mcpd in this process. Used by `turno mcpd run` (foreground or under launchd). */
273
+ /** The gateway plus what only the daemon knows (port, manifest state), in /status. */
274
+ class DaemonGateway extends Gateway {
275
+ extra;
276
+ constructor(opts, extra) {
277
+ super(opts);
278
+ this.extra = extra;
279
+ }
280
+ status() {
281
+ return { ...super.status(), ...this.extra() };
282
+ }
283
+ }
284
+ /**
285
+ * Start mcpd in this process (`turno mcp daemon run`, in a terminal or under the service).
286
+ * Single instance: a lock file with the PID, and no port fallback. If the configured port is
287
+ * busy it fails with PortBusyError naming the owner, because every synced profile points at
288
+ * that port. A broken mcp.toml or config.toml never stops it from starting.
289
+ */
63
290
  export async function startDaemon(opts = {}) {
64
291
  const env = opts.env ?? process.env;
65
292
  const p = paths(env);
66
- mkdirSync(p.logsDir, { recursive: true });
67
- const logFile = join(p.logsDir, "mcpd.log");
68
- const log = (line) => {
69
- const text = `${new Date().toISOString()} ${line}\n`;
70
- if (opts.logToStdout)
71
- process.stdout.write(text);
72
- else
73
- appendFileSync(logFile, text);
74
- };
75
- let manifest = loadManifest(env);
76
- const config = loadConfig(env);
77
- const token = ensureToken(env);
78
- const manager = new InstanceManager({
79
- cache: new DescriptionCache(p.mcpdCacheDir),
80
- connector: new DefaultConnector({
81
- resolve: keychainResolver(env),
82
- serversDir: p.serversDir,
83
- logsDir: p.logsDir,
84
- builtins: await loadBuiltins(),
85
- baseEnv: Object.fromEntries(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR"].flatMap((k) => (env[k] ? [[k, env[k]]] : []))),
86
- }),
87
- home: p.home,
88
- log,
293
+ const files = daemonFiles(env);
294
+ const log = createLogger(files.log, {
295
+ env,
296
+ toStdout: Boolean(opts.logToStdout),
297
+ ...(opts.logMaxBytes ? { maxBytes: opts.logMaxBytes } : {}),
89
298
  });
90
- const gateway = new Gateway({ manager, manifest: () => manifest, token, peerPid, log });
299
+ const { config, error: firstConfigError } = loadConfigSafe(env);
300
+ let configError = firstConfigError;
301
+ if (configError)
302
+ log(`config.toml is invalid, using defaults: ${configError}`);
303
+ // Folder server sets: the last good [[projects]] rules, reloaded with config.toml.
304
+ let folderRules = config.projects;
91
305
  const wanted = opts.port ?? config.mcpd.port;
306
+ const fail = async (err) => {
307
+ if (!(err instanceof AlreadyRunningError))
308
+ writeStartError(env, { at: new Date().toISOString(), message: err.message, port: wanted });
309
+ log(`mcpd could not start: ${err.message}`);
310
+ await log.close();
311
+ throw err;
312
+ };
313
+ try {
314
+ acquireLock(env);
315
+ }
316
+ catch (err) {
317
+ return fail(err);
318
+ }
319
+ let state = loadManifestSafe(env);
320
+ if (state.error)
321
+ log(`mcp.toml is invalid, serving the ${state.source}: ${state.error}`);
322
+ const startedAt = new Date().toISOString();
92
323
  let port = 0;
93
- for (let attempt = 0; attempt < 20; attempt++) {
324
+ try {
325
+ const token = ensureToken(env, (m) => log(m));
326
+ // The call log follows `[mcpd] call_log`, also when config.toml changes while mcpd runs.
327
+ let calls = config.mcpd.callLog ? createCallLog(files.calls, { onError: (m) => log(m) }) : undefined;
328
+ const sampler = new RssSampler(files.rss, { env });
329
+ const manager = new InstanceManager({
330
+ cache: new DescriptionCache(p.mcpdCacheDir),
331
+ connector: new DefaultConnector({
332
+ resolve: keychainResolver(env),
333
+ serversDir: p.serversDir,
334
+ logsDir: p.logsDir,
335
+ vars: env,
336
+ builtins: await loadBuiltins(),
337
+ baseEnv: Object.fromEntries(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR"].flatMap((k) => env[k] ? [[k, env[k]]] : [])),
338
+ }),
339
+ home: p.home,
340
+ log,
341
+ pressure: memoryPressureProbe(),
342
+ idleUnderPressure: config.mcpd.idleUnderPressure,
343
+ });
344
+ const gwOpts = {
345
+ manager,
346
+ manifest: () => state.manifest,
347
+ token,
348
+ peerPid: (rp) => peerPid(rp),
349
+ log,
350
+ folderRules: () => folderRules,
351
+ home: p.home,
352
+ clientNames: new ClientNames(join(p.state, "mcpd-clients.json"), pidAlive),
353
+ callLog: () => (calls ? (e) => calls?.record(e) : undefined),
354
+ ...(config.mcpd.maxRequestBody ? { maxRequestBodyBytes: config.mcpd.maxRequestBody } : {}),
355
+ };
356
+ const gateway = new DaemonGateway(gwOpts, () => ({
357
+ version: packageInfo().version,
358
+ port,
359
+ startedAt,
360
+ manifest: {
361
+ source: state.source,
362
+ servers: Object.keys(state.manifest.servers).length,
363
+ error: state.error ?? null,
364
+ },
365
+ config: { error: configError ?? null, folderSets: folderRules.filter((r) => r.mcp || r.mcpDeny).length },
366
+ callLog: { enabled: Boolean(calls) },
367
+ serverRss: sampler.samples(),
368
+ }));
94
369
  try {
95
- port = await gateway.listen(wanted === 0 ? 0 : wanted + attempt);
96
- break;
370
+ port = await gateway.listen(wanted);
97
371
  }
98
372
  catch (err) {
99
- if (err.code !== "EADDRINUSE" || wanted === 0)
373
+ await gateway.close().catch(() => { });
374
+ if (err.code !== "EADDRINUSE")
100
375
  throw err;
376
+ const ours = await answersAsMcpd(wanted, token);
377
+ if (ours)
378
+ throw new AlreadyRunningError(`mcpd is already running on port ${wanted}${ours.pid ? ` (pid ${ours.pid})` : ""}`);
379
+ const owner = await portOwner(wanted, { env });
380
+ throw new PortBusyError(`port ${wanted} is in use by ${describeOwner(owner)}. mcpd does not move to another port, because every synced profile points at this one: free the port, or pick another with \`turno config set mcpd.port <port>\` and run \`turno mcp sync\``, wanted);
101
381
  }
102
- }
103
- if (!port)
104
- throw new Error(`no free port from ${wanted}`);
105
- mkdirSync(dirname(p.mcpdPort), { recursive: true });
106
- writeFileSync(p.mcpdPort, `${port}\n`);
107
- log(`mcpd listening on 127.0.0.1:${port} with ${Object.keys(manifest.servers).length} servers`);
108
- const reload = async (why) => {
109
- let next;
110
- try {
111
- next = loadManifest(env);
112
- }
113
- catch (err) {
114
- log(`reload skipped (${why}): ${err.message}`);
115
- return;
116
- }
117
- // Stop instances whose definition changed or disappeared; the next call starts the new one.
118
- for (const inst of manager.list()) {
119
- const def = next.servers[inst.server.name];
120
- if (!def || descriptionFingerprint(def, inst.variant) !== descriptionFingerprint(inst.server, inst.variant)) {
121
- await manager.stop(inst.key);
122
- log(`stopped ${inst.upstream.label} after manifest change`);
382
+ writeFileSync(files.lock, `${JSON.stringify({ pid: process.pid, port, startedAt })}\n`, {
383
+ mode: PRIVATE_FILE_MODE,
384
+ });
385
+ ensurePrivateDir(dirname(p.mcpdPort), env);
386
+ atomicWrite(p.mcpdPort, `${port}\n`, PRIVATE_FILE_MODE);
387
+ writeStartError(env, undefined);
388
+ log(`mcpd ${packageInfo().version} listening on 127.0.0.1:${port} with ${Object.keys(state.manifest.servers).length} servers`);
389
+ const reload = async (why) => {
390
+ const next = loadManifestSafe(env);
391
+ if (next.error) {
392
+ // Keep serving what runs now; remember why the file was refused.
393
+ state = { ...state, error: next.error, source: state.source === "mcp.toml" ? "last good copy" : state.source };
394
+ log(`reload skipped (${why}): ${next.error}`);
395
+ return;
123
396
  }
124
- }
125
- manifest = next;
126
- log(`manifest reloaded (${why}): ${Object.keys(manifest.servers).length} servers`);
127
- };
128
- let debounce;
129
- let watcher;
130
- if (existsSync(p.config)) {
131
- watcher = watch(p.config, (_event, file) => {
132
- if (file !== "mcp.toml")
397
+ const tell = gateway.beforeViewChange();
398
+ // Stop instances whose definition changed or disappeared; the next call starts the new one.
399
+ for (const inst of manager.list()) {
400
+ const def = next.manifest.servers[inst.server.name];
401
+ if (!def || descriptionFingerprint(def, inst.variant) !== descriptionFingerprint(inst.server, inst.variant)) {
402
+ await manager.stop(inst.key);
403
+ log(`stopped ${inst.upstream.label} after manifest change`);
404
+ }
405
+ }
406
+ state = next;
407
+ log(`manifest reloaded (${why}): ${Object.keys(state.manifest.servers).length} servers`);
408
+ tell();
409
+ };
410
+ /** config.toml: a broken file keeps the last good settings and is reported in /status. */
411
+ const reloadConfig = (why) => {
412
+ let next;
413
+ try {
414
+ next = loadConfig(env);
415
+ }
416
+ catch (err) {
417
+ configError = err.message;
418
+ log(`config.toml reload skipped (${why}): ${configError}`);
133
419
  return;
134
- clearTimeout(debounce);
135
- debounce = setTimeout(() => void reload("mcp.toml changed"), 300);
136
- });
420
+ }
421
+ configError = undefined;
422
+ const tell = gateway.beforeViewChange();
423
+ folderRules = next.projects;
424
+ tell();
425
+ manager.setIdleUnderPressure(next.mcpd.idleUnderPressure);
426
+ if (next.mcpd.callLog !== Boolean(calls)) {
427
+ if (calls) {
428
+ calls.close();
429
+ calls = undefined;
430
+ }
431
+ else
432
+ calls = createCallLog(files.calls, { onError: (m) => log(m) });
433
+ log(`call log ${calls ? "on" : "off"} (${why})`);
434
+ }
435
+ log(`config.toml reloaded (${why}): ${folderRules.filter((r) => r.mcp || r.mcpDeny).length} folder server sets`);
436
+ };
437
+ let debounce;
438
+ let configDebounce;
439
+ let watcher;
440
+ if (existsSync(p.config)) {
441
+ try {
442
+ watcher = watch(p.config, (_event, file) => {
443
+ if (file === "config.toml") {
444
+ clearTimeout(configDebounce);
445
+ configDebounce = setTimeout(() => reloadConfig("config.toml changed"), 300);
446
+ return;
447
+ }
448
+ if (file !== "mcp.toml")
449
+ return;
450
+ clearTimeout(debounce);
451
+ debounce = setTimeout(() => void reload("mcp.toml changed").catch((e) => log(`reload failed: ${e.message}`)), 300);
452
+ });
453
+ watcher.on("error", (e) => log(`config watch failed: ${e.message}`));
454
+ }
455
+ catch (e) {
456
+ log(`config watch failed: ${e.message}`);
457
+ }
458
+ }
459
+ // SIGHUP reloads the manifest, config.toml and the token (after `turno mcp token rotate`).
460
+ const onHup = () => {
461
+ reloadConfig("SIGHUP");
462
+ const t = readToken(env, (m) => log(m));
463
+ if (t && t !== gwOpts.token) {
464
+ gwOpts.token = t;
465
+ log("token reloaded");
466
+ }
467
+ void reload("SIGHUP").catch((e) => log(`reload failed: ${e.message}`));
468
+ };
469
+ process.on("SIGHUP", onHup);
470
+ const timer = setInterval(() => {
471
+ gateway.pruneSessions(pidAlive);
472
+ manager
473
+ .reap()
474
+ .then((stopped) => {
475
+ for (const s of stopped)
476
+ log(`reaped ${s}`);
477
+ })
478
+ .catch((err) => log(`reap failed: ${err.message}`));
479
+ void sampler.sample(manager.list().map((i) => ({ descKey: i.descKey, pid: i.upstream.pid })));
480
+ }, 15_000);
481
+ timer.unref();
482
+ // /status shows the pressure from the start instead of after the first reap.
483
+ void manager.readPressure().catch(() => { });
484
+ let stopped = false;
485
+ return {
486
+ port,
487
+ gateway,
488
+ manager,
489
+ log,
490
+ async stop() {
491
+ if (stopped)
492
+ return;
493
+ stopped = true;
494
+ clearInterval(timer);
495
+ clearTimeout(debounce);
496
+ clearTimeout(configDebounce);
497
+ watcher?.close();
498
+ process.off("SIGHUP", onHup);
499
+ // Rotated OAuth tokens the secret store refused so far: one last try before they are gone.
500
+ const lost = await Promise.race([
501
+ manager.flushLogins().catch(() => []),
502
+ new Promise((r) => setTimeout(() => r([]), 3000).unref()),
503
+ ]);
504
+ if (lost.length)
505
+ log(`OAuth tokens not saved, a new login is needed for: ${lost.join(", ")} (turno mcp login <server>)`);
506
+ await manager.stopAll();
507
+ await gateway.close();
508
+ releaseLock(env, port);
509
+ calls?.close();
510
+ log("mcpd stopped");
511
+ await log.close();
512
+ },
513
+ };
514
+ }
515
+ catch (err) {
516
+ releaseLock(env, port);
517
+ return fail(err);
137
518
  }
138
- const onHup = () => void reload("SIGHUP");
139
- process.on("SIGHUP", onHup);
140
- const timer = setInterval(() => {
141
- gateway.pruneSessions(processAlive);
142
- manager
143
- .reap()
144
- .then((stopped) => stopped.forEach((s) => log(`reaped ${s}`)))
145
- .catch((err) => log(`reap failed: ${err.message}`));
146
- }, 15_000);
147
- timer.unref();
148
- return {
149
- port,
150
- gateway,
151
- manager,
152
- async stop() {
153
- clearInterval(timer);
154
- clearTimeout(debounce);
155
- watcher?.close();
156
- process.off("SIGHUP", onHup);
157
- await manager.stopAll();
158
- await gateway.close();
159
- log("mcpd stopped");
160
- },
161
- };
162
519
  }
163
520
  //# sourceMappingURL=daemon.js.map
@@ -0,0 +1,42 @@
1
+ import { execFile } from "node:child_process";
2
+ import { realpath } from "node:fs/promises";
3
+ import { promisify } from "node:util";
4
+ const run = promisify(execFile);
5
+ /**
6
+ * The folders a session's server set is matched against: the session folder, and
7
+ * for a git worktree the main repository it belongs to, the same candidates `turno auto` uses
8
+ * for profile rules. Async (mcpd must not block on git) and cached for 10 s, because an agent
9
+ * opens one session per server at the same time.
10
+ */
11
+ const cache = new Map();
12
+ export function folderRoots(cwd, now = Date.now()) {
13
+ const hit = cache.get(cwd);
14
+ if (hit && now - hit.at < 10_000)
15
+ return hit.value;
16
+ if (cache.size > 500)
17
+ cache.clear();
18
+ const value = compute(cwd);
19
+ cache.set(cwd, { at: now, value });
20
+ return value;
21
+ }
22
+ async function compute(cwd) {
23
+ const own = await realpath(cwd).catch(() => cwd);
24
+ const out = [own];
25
+ try {
26
+ const { stdout } = await run("git", ["-C", cwd, "rev-parse", "--path-format=absolute", "--git-common-dir"], {
27
+ encoding: "utf8",
28
+ timeout: 3000,
29
+ });
30
+ const common = stdout.trim();
31
+ if (common.endsWith("/.git")) {
32
+ const main = await realpath(common.slice(0, -5)).catch(() => common.slice(0, -5));
33
+ if (!out.includes(main))
34
+ out.push(main);
35
+ }
36
+ }
37
+ catch {
38
+ // not a git repository
39
+ }
40
+ return out;
41
+ }
42
+ //# sourceMappingURL=folder-sets.js.map