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.
Files changed (104) hide show
  1. package/CHANGELOG.md +284 -0
  2. package/README.md +120 -53
  3. package/dist/accounts/audit.js +137 -7
  4. package/dist/accounts/builtin.js +68 -21
  5. package/dist/accounts/delegate.js +176 -35
  6. package/dist/accounts/policy.js +77 -0
  7. package/dist/accounts/registry.js +37 -21
  8. package/dist/agents/adapter.js +7 -0
  9. package/dist/agents/claude.js +195 -0
  10. package/dist/agents/codex.js +98 -0
  11. package/dist/agents/copilot.js +39 -0
  12. package/dist/agents/cursor.js +41 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +7 -4
  15. package/dist/cli/args.js +19 -4
  16. package/dist/cli/commands/accounts.js +96 -51
  17. package/dist/cli/commands/auto.js +82 -32
  18. package/dist/cli/commands/browser.js +216 -135
  19. package/dist/cli/commands/complete.js +2 -1
  20. package/dist/cli/commands/completion.js +4 -2
  21. package/dist/cli/commands/config.js +103 -18
  22. package/dist/cli/commands/demo.js +292 -0
  23. package/dist/cli/commands/doctor.js +387 -119
  24. package/dist/cli/commands/handoff.js +33 -22
  25. package/dist/cli/commands/identity.js +101 -50
  26. package/dist/cli/commands/init.js +616 -0
  27. package/dist/cli/commands/limit.js +25 -13
  28. package/dist/cli/commands/mcp-oauth.js +194 -0
  29. package/dist/cli/commands/mcp-observe.js +434 -0
  30. package/dist/cli/commands/mcp.js +653 -185
  31. package/dist/cli/commands/mcpd.js +323 -75
  32. package/dist/cli/commands/migrate.js +6 -4
  33. package/dist/cli/commands/open.js +92 -27
  34. package/dist/cli/commands/profile.js +205 -69
  35. package/dist/cli/commands/resolve.js +6 -2
  36. package/dist/cli/commands/run.js +15 -5
  37. package/dist/cli/commands/secret.js +61 -42
  38. package/dist/cli/commands/session.js +2 -2
  39. package/dist/cli/commands/sessions.js +42 -12
  40. package/dist/cli/commands/setup.js +136 -158
  41. package/dist/cli/commands/status.js +172 -41
  42. package/dist/cli/commands/statusline.js +305 -113
  43. package/dist/cli/commands/ui.js +64 -66
  44. package/dist/cli/commands/undo.js +161 -18
  45. package/dist/cli/commands/uninstall.js +462 -0
  46. package/dist/cli/commands/upgrade.js +75 -19
  47. package/dist/cli/commands/usage.js +117 -44
  48. package/dist/cli/commands/version.js +7 -5
  49. package/dist/cli/commands/which.js +7 -24
  50. package/dist/cli/compile-cache.js +32 -0
  51. package/dist/cli/group.js +10 -10
  52. package/dist/cli/help.js +57 -0
  53. package/dist/cli/highlight.js +236 -0
  54. package/dist/cli/io.js +170 -1
  55. package/dist/cli/launch.js +21 -37
  56. package/dist/cli/launchers.js +145 -94
  57. package/dist/cli/main.js +163 -27
  58. package/dist/cli/picker.js +447 -0
  59. package/dist/cli/registry.js +42 -5
  60. package/dist/cli/security.js +539 -0
  61. package/dist/cli/style.js +281 -0
  62. package/dist/core/config.js +145 -23
  63. package/dist/core/exhausted.js +6 -8
  64. package/dist/core/fsutil.js +47 -0
  65. package/dist/core/journal.js +281 -11
  66. package/dist/core/manifest.js +126 -6
  67. package/dist/core/paths.js +114 -7
  68. package/dist/core/profiles.js +139 -9
  69. package/dist/core/resolve.js +129 -23
  70. package/dist/core/secrets.js +215 -20
  71. package/dist/core/sessions.js +13 -20
  72. package/dist/core/update.js +18 -8
  73. package/dist/demo/server.js +34 -0
  74. package/dist/mcpd/cache.js +18 -4
  75. package/dist/mcpd/calllog.js +253 -0
  76. package/dist/mcpd/client-names.js +51 -0
  77. package/dist/mcpd/connectors.js +148 -17
  78. package/dist/mcpd/daemon.js +452 -116
  79. package/dist/mcpd/folder-sets.js +39 -0
  80. package/dist/mcpd/gateway.js +441 -47
  81. package/dist/mcpd/health.js +269 -0
  82. package/dist/mcpd/importer.js +356 -36
  83. package/dist/mcpd/instances.js +425 -65
  84. package/dist/mcpd/jsonrpc.js +8 -0
  85. package/dist/mcpd/launchd.js +65 -48
  86. package/dist/mcpd/modern.js +648 -0
  87. package/dist/mcpd/oauth.js +791 -0
  88. package/dist/mcpd/peerpid.js +122 -6
  89. package/dist/mcpd/pressure.js +85 -0
  90. package/dist/mcpd/rss.js +151 -0
  91. package/dist/mcpd/service.js +167 -0
  92. package/dist/mcpd/state.js +183 -0
  93. package/dist/mcpd/sync.js +55 -80
  94. package/dist/mcpd/systemd.js +80 -0
  95. package/dist/mcpd/tokens.js +89 -0
  96. package/dist/mcpd/upstream.js +154 -44
  97. package/dist/statusline/cost.js +154 -44
  98. package/dist/statusline/input.js +66 -0
  99. package/dist/statusline/render.js +9 -3
  100. package/dist/ui/fonts.js +8 -3
  101. package/dist/ui/settings.js +27 -15
  102. package/npm-shrinkwrap.json +1093 -0
  103. package/package.json +6 -6
  104. package/dist/cli/commands/available.js +0 -18
@@ -1,20 +1,16 @@
1
- import { createReadStream, existsSync, statSync } from "node:fs";
2
- import { realpathSync } from "node:fs";
1
+ import { createReadStream, existsSync, realpathSync, statSync } from "node:fs";
3
2
  import { join } from "node:path";
4
3
  import { fileURLToPath } from "node:url";
5
- import { paths } from "../../core/paths.js";
6
- import { fail, paint } from "../io.js";
7
- const USAGE = `Usage:
8
- turno mcpd run [--port N] run the gateway in the foreground
9
- turno mcpd start install and start the LaunchAgent (keeps mcpd alive)
10
- turno mcpd stop stop and unload the LaunchAgent
11
- turno mcpd restart restart the LaunchAgent
12
- turno mcpd status [--json] running servers, their clients and memory
13
- turno mcpd logs [-n N] last lines of the mcpd log`;
4
+ import { Journal } from "../../core/journal.js";
5
+ import { paths, tildify } from "../../core/paths.js";
6
+ import { DRY_RUN, JSON_FLAG, TAIL, bool, count, parseFlags, printJson, str } from "../args.js";
7
+ import { group } from "../group.js";
8
+ import { fail, paint, plural } from "../io.js";
9
+ import { duration, spinner, style } from "../style.js";
14
10
  /** GET /status from the running daemon. */
15
11
  export async function fetchStatus(env) {
16
- const { mcpdPort, readToken } = await import("../../mcpd/daemon.js");
17
- const token = readToken(env);
12
+ const { mcpdPort, readToken } = await import("../../mcpd/state.js");
13
+ const token = readToken(env, () => { });
18
14
  if (!token)
19
15
  return undefined;
20
16
  try {
@@ -50,19 +46,50 @@ async function rssOf(pids) {
50
46
  function mb(bytes) {
51
47
  return `${Math.round(bytes / 1048576)} MB`;
52
48
  }
49
+ /** Why mcpd is down, as far as the files and the port can tell (also shown by `turno status`). */
50
+ export async function downReasons(env) {
51
+ const { daemonFiles, loadConfigSafe, readLock, readStartError } = await import("../../mcpd/state.js");
52
+ const { describeOwner, portOwner } = await import("../../mcpd/peerpid.js");
53
+ const out = [];
54
+ const port = loadConfigSafe(env).config.mcpd.port;
55
+ const owner = await portOwner(port, { env });
56
+ if (owner)
57
+ out.push(`port ${port} is in use by ${describeOwner(owner)}`);
58
+ const e = readStartError(env);
59
+ if (e)
60
+ out.push(`last start failed at ${localTime(e.at)}: ${e.message}`);
61
+ const lock = readLock(env);
62
+ if (lock)
63
+ out.push(`stale lock from pid ${lock.pid} (${tildify(daemonFiles(env).lock, env)}); the next start clears it`);
64
+ return out;
65
+ }
53
66
  async function status(args, io) {
67
+ const p = parseFlags(args, JSON_FLAG, 0);
54
68
  const s = await fetchStatus(io.env);
55
69
  if (!s) {
56
- io.out("mcpd is not running (turno mcpd start)");
70
+ const reasons = await downReasons(io.env);
71
+ if (bool(p, "json"))
72
+ printJson(io, { running: false, problems: reasons });
73
+ else {
74
+ io.out("mcpd is not running (turno mcp daemon start)");
75
+ for (const r of reasons)
76
+ io.out(` ${r}`);
77
+ }
57
78
  return 1;
58
79
  }
59
- if (args.includes("--json")) {
60
- io.out(JSON.stringify(s, null, 2));
80
+ if (bool(p, "json")) {
81
+ printJson(io, s);
61
82
  return 0;
62
83
  }
63
84
  const instances = s.instances ?? [];
64
85
  const rss = await rssOf([Number(s.pid), ...instances.map((i) => Number(i.pid)).filter(Boolean)]);
65
- io.out(`${paint(io, "mcpd", "1")} pid ${s.pid} · ${mb(rss.get(Number(s.pid)) ?? 0)} · ${s.sessions} client sessions`);
86
+ io.out(`${paint(io, "mcpd", "1")} pid ${s.pid}${s.port ? ` · port ${s.port}` : ""} · ${mb(rss.get(Number(s.pid)) ?? 0)} · ${plural(Number(s.sessions) || 0, "client session")}`);
87
+ const manifest = s.manifest;
88
+ if (manifest?.error)
89
+ io.out(` ${paint(io, "warn", "33")} mcp.toml is invalid, serving the ${manifest.source}: ${manifest.error}`);
90
+ const config = s.config;
91
+ if (config?.error)
92
+ io.out(` ${paint(io, "warn", "33")} config.toml is invalid, using defaults: ${config.error}`);
66
93
  if (!instances.length) {
67
94
  io.out(" no servers running (they start on first use)");
68
95
  return 0;
@@ -72,16 +99,50 @@ async function status(args, io) {
72
99
  const mem = rss.get(Number(i.pid)) ?? 0;
73
100
  total += mem;
74
101
  const holder = i.holder;
75
- io.out(` ${String(i.server).padEnd(24)} ${String(i.variant).padEnd(10)} pid ${String(i.pid ?? "-").padEnd(7)} ${mb(mem).padStart(7)} ${i.clients} clients idle ${i.idleSeconds}s${holder ? ` held by ${holder.profile ?? "?"}/${holder.pid ?? "?"}` : ""}`);
102
+ io.out(` ${String(i.server).padEnd(24)} ${String(i.variant).padEnd(10)} pid ${String(i.pid ?? "-").padEnd(7)} ${mb(mem).padStart(7)} ${plural(Number(i.clients) || 0, "client")} idle ${i.idleSeconds}s${holder ? ` held by ${holder.profile ?? "?"}/${holder.pid ?? "?"}` : ""}`);
103
+ const busy = inflightText(i.inflightByClient);
104
+ if (busy)
105
+ io.out(` ${busy}`);
76
106
  }
77
107
  io.out(` total ${mb(total)}`);
78
108
  return 0;
79
109
  }
80
- function entryScript() {
81
- return realpathSync(join(fileURLToPath(new URL(".", import.meta.url)), "..", "main.js"));
110
+ /** "2 calls in flight: 1f2e3d4c 1, 9a8b7c6d 1" from /status `inflightByClient` (client session ids). */
111
+ export function inflightText(byClient) {
112
+ if (!byClient || typeof byClient !== "object")
113
+ return undefined;
114
+ const rows = Object.entries(byClient).filter(([, n]) => Number(n) > 0);
115
+ if (!rows.length)
116
+ return undefined;
117
+ const total = rows.reduce((t, [, n]) => t + Number(n), 0);
118
+ return `${plural(total, "call")} in flight: ${rows.map(([id, n]) => `${id.slice(0, 8)} ${n}`).join(", ")}`;
119
+ }
120
+ /** The CLI entry the service runs when no stable `turno` is on PATH. */
121
+ export function entryScript() {
122
+ const dir = fileURLToPath(new URL("..", import.meta.url));
123
+ for (const f of ["main.js", "main.ts"]) {
124
+ const file = join(dir, f);
125
+ if (existsSync(file))
126
+ return realpathSync(file);
127
+ }
128
+ return join(dir, "main.js");
129
+ }
130
+ /** "2026-11-16 15:26:45" in the local time zone, from an ISO timestamp. */
131
+ export function localTime(iso) {
132
+ const d = new Date(iso);
133
+ if (Number.isNaN(d.getTime()))
134
+ return iso;
135
+ const p = (n) => String(n).padStart(2, "0");
136
+ return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())} ${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`;
137
+ }
138
+ /** A log line with its leading UTC timestamp shown in local time. */
139
+ export function localizeLine(line) {
140
+ const m = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z) /.exec(line);
141
+ return m ? `${localTime(m[1])} ${line.slice(m[0].length)}` : line;
82
142
  }
83
143
  async function logs(args, io) {
84
- const n = Number(args[args.indexOf("-n") + 1]) || 40;
144
+ const p = parseFlags(args, { ...TAIL, utc: { type: "boolean" } }, 0);
145
+ const n = count(p, "tail", 40);
85
146
  const file = join(paths(io.env).logsDir, "mcpd.log");
86
147
  if (!existsSync(file)) {
87
148
  io.out("no log yet");
@@ -94,68 +155,255 @@ async function logs(args, io) {
94
155
  chunks.push(c);
95
156
  const lines = Buffer.concat(chunks).toString("utf8").trimEnd().split("\n");
96
157
  for (const l of lines.slice(-n))
97
- io.out(l);
158
+ io.out(bool(p, "utc") ? l : localizeLine(l));
98
159
  return 0;
99
160
  }
100
- export const command = {
101
- summary: "run or manage the MCP gateway daemon",
102
- usage: USAGE,
103
- async run(args, io) {
104
- const [sub, ...rest] = args;
105
- switch (sub) {
106
- case "run": {
107
- const { startDaemon } = await import("../../mcpd/daemon.js");
108
- const portArg = rest.indexOf("--port");
109
- const d = await startDaemon({
110
- env: io.env,
111
- logToStdout: process.stdout.isTTY,
112
- ...(portArg >= 0 ? { port: Number(rest[portArg + 1]) } : {}),
113
- });
114
- io.err(`mcpd listening on 127.0.0.1:${d.port}`);
115
- await new Promise((resolve) => {
116
- const stop = () => {
117
- void d.stop().then(resolve);
118
- };
119
- process.once("SIGINT", stop);
120
- process.once("SIGTERM", stop);
121
- });
122
- return 0;
161
+ const isService = (env) => Boolean(env.TURNO_MCPD_SERVICE);
162
+ async function runDaemon(args, io) {
163
+ const p = parseFlags(args, { port: { type: "string" } }, 0);
164
+ const raw = str(p, "port");
165
+ let port;
166
+ if (raw !== undefined) {
167
+ port = Number(raw);
168
+ if (!Number.isInteger(port) || port < 0 || port > 65535 || String(port) !== raw.trim())
169
+ fail("--port must be an integer between 0 and 65535");
170
+ }
171
+ const { AlreadyRunningError, PortBusyError, installCrashGuards, startDaemon } = await import("../../mcpd/daemon.js");
172
+ const service = isService(io.env);
173
+ let waiting = false;
174
+ for (;;) {
175
+ try {
176
+ const d = await startDaemon({ env: io.env, logToStdout: Boolean(process.stdout.isTTY) && !service, ...(port !== undefined ? { port } : {}) });
177
+ io.err(`mcpd listening on 127.0.0.1:${d.port}`);
178
+ const unguard = installCrashGuards(d.log, () => d.stop());
179
+ await new Promise((resolve) => {
180
+ const stop = () => {
181
+ void d.stop().then(resolve, resolve);
182
+ };
183
+ process.once("SIGINT", stop);
184
+ process.once("SIGTERM", stop);
185
+ });
186
+ unguard();
187
+ return 0;
188
+ }
189
+ catch (err) {
190
+ if (err instanceof AlreadyRunningError) {
191
+ io.err(`turno: ${err.message}`);
192
+ // Under a service a clean exit is not restarted: the other mcpd serves.
193
+ return service ? 0 : 1;
123
194
  }
124
- case "start": {
125
- const { install } = await import("../../mcpd/launchd.js");
126
- const { ensureToken } = await import("../../mcpd/daemon.js");
127
- ensureToken(io.env);
128
- const file = await install({ node: process.execPath, script: entryScript(), env: io.env });
129
- io.out(`LaunchAgent installed: ${file}`);
130
- for (let i = 0; i < 20; i++) {
131
- if (await fetchStatus(io.env)) {
132
- io.out("mcpd is running");
133
- return 0;
134
- }
135
- await new Promise((r) => setTimeout(r, 250));
136
- }
137
- io.err("mcpd did not answer yet; see turno mcpd logs");
195
+ if (err instanceof PortBusyError && service) {
196
+ // Exiting would make the supervisor loop; wait for the port instead (doctor shows why).
197
+ if (!waiting)
198
+ io.err(`turno: ${err.message}; retrying every 30 s`);
199
+ waiting = true;
200
+ await new Promise((r) => setTimeout(r, 30_000));
201
+ continue;
202
+ }
203
+ if (err instanceof PortBusyError) {
204
+ io.err(`turno: ${err.message}`);
138
205
  return 1;
139
206
  }
140
- case "stop": {
141
- const { uninstall } = await import("../../mcpd/launchd.js");
142
- await uninstall();
143
- io.out("mcpd stopped");
144
- return 0;
207
+ throw err;
208
+ }
209
+ }
210
+ }
211
+ async function backendOrReport(io) {
212
+ const { ServiceError, serviceBackend } = await import("../../mcpd/service.js");
213
+ try {
214
+ return await serviceBackend(io.env);
215
+ }
216
+ catch (err) {
217
+ if (err instanceof ServiceError) {
218
+ io.err(`turno: ${err.message}`);
219
+ return undefined;
220
+ }
221
+ throw err;
222
+ }
223
+ }
224
+ /** Run a service step; a ServiceError is one line on stderr and exit 1, never a stack. */
225
+ async function serviceStep(io, step) {
226
+ const { ServiceError } = await import("../../mcpd/service.js");
227
+ try {
228
+ return await step();
229
+ }
230
+ catch (err) {
231
+ if (err instanceof ServiceError) {
232
+ io.err(`turno: ${err.message}`);
233
+ return 1;
234
+ }
235
+ throw err;
236
+ }
237
+ }
238
+ async function waitFor(check, ms) {
239
+ for (let waited = 0; waited <= ms; waited += 250) {
240
+ if (await check())
241
+ return true;
242
+ await new Promise((r) => setTimeout(r, 250));
243
+ }
244
+ return false;
245
+ }
246
+ /** Write (or rewrite) the service file and (re)load it. Shared by `start` and `upgrade --finish`. */
247
+ export async function installDaemonService(io, opts = {}) {
248
+ const backend = await backendOrReport(io);
249
+ if (!backend)
250
+ return 1;
251
+ return serviceStep(io, async () => {
252
+ const { chooseProgram, installService } = await import("../../mcpd/service.js");
253
+ const choice = chooseProgram({ env: io.env, execPath: process.execPath, script: entryScript() });
254
+ const journal = opts.journal ?? new Journal(io.env, opts.command ?? "mcp daemon start", Boolean(opts.dryRun));
255
+ if (!opts.dryRun) {
256
+ const { ensureToken } = await import("../../mcpd/state.js");
257
+ ensureToken(io.env, (m) => io.err(`turno: ${m}`));
258
+ }
259
+ const r = await installService(backend, { program: choice.program, env: io.env }, journal);
260
+ if (opts.dryRun) {
261
+ io.out(`would write ${tildify(r.file, io.env)}${r.changed ? "" : " (unchanged)"} and load the ${backend.noun}:`);
262
+ io.out("");
263
+ io.out(r.text.trimEnd());
264
+ }
265
+ else
266
+ io.out(style(io).note("ok", `${backend.noun} ${r.changed ? "written" : "unchanged"}: ${tildify(r.file, io.env)}`));
267
+ if (choice.warning)
268
+ io.err(style(io).note("warn", `warning: ${choice.warning}`));
269
+ const hint = opts.journal ? undefined : journal.hint();
270
+ if (hint)
271
+ io.out(hint);
272
+ return 0;
273
+ });
274
+ }
275
+ /** Install the service and wait until mcpd answers. Non-zero when either step fails. */
276
+ export async function startDaemonService(io, opts = {}) {
277
+ const code = await installDaemonService(io, opts);
278
+ if (code)
279
+ return code;
280
+ const st = style(io);
281
+ const spin = spinner(io, "waiting for mcpd to answer");
282
+ const up = await waitFor(async () => Boolean(await fetchStatus(io.env)), 5000);
283
+ const ms = spin.stop();
284
+ if (up) {
285
+ io.out(st.note("ok", `mcpd is running ${st.muted(`(${duration(ms)})`)}`));
286
+ return 0;
287
+ }
288
+ io.err(st.note("err", "mcpd did not answer yet; see turno mcp daemon status and turno mcp daemon logs"));
289
+ return 1;
290
+ }
291
+ async function start(args, io) {
292
+ const p = parseFlags(args, DRY_RUN, 0);
293
+ const dryRun = bool(p, "dry-run");
294
+ if (dryRun)
295
+ return installDaemonService(io, { dryRun });
296
+ return startDaemonService(io);
297
+ }
298
+ /** Stop the service and remove its file, so mcpd does not come back at login. A hand-started mcpd gets SIGTERM. */
299
+ async function stop(args, io) {
300
+ const p = parseFlags(args, DRY_RUN, 0);
301
+ const dryRun = bool(p, "dry-run");
302
+ const { installedBackend, removeService } = await import("../../mcpd/service.js");
303
+ const { liveLock } = await import("../../mcpd/state.js");
304
+ return serviceStep(io, async () => {
305
+ const backend = (await installedBackend(io.env)) ?? (await backendOrReport({ ...io, err: () => { } }));
306
+ const journal = new Journal(io.env, "mcp daemon stop", dryRun);
307
+ let did = false;
308
+ if (backend) {
309
+ const r = await removeService(backend, io.env, journal);
310
+ if (r.existed) {
311
+ io.out(`${dryRun ? "would remove" : "removed"} ${tildify(r.file, io.env)} (turno mcp daemon start installs it again)`);
312
+ did = true;
145
313
  }
146
- case "restart": {
147
- const { restart } = await import("../../mcpd/launchd.js");
148
- await restart();
149
- io.out("mcpd restarted");
150
- return 0;
314
+ }
315
+ const lock = liveLock(io.env);
316
+ if (lock && lock.pid !== process.pid) {
317
+ if (dryRun)
318
+ io.out(`would stop mcpd (pid ${lock.pid})`);
319
+ else {
320
+ try {
321
+ process.kill(lock.pid, "SIGTERM");
322
+ }
323
+ catch {
324
+ /* gone already */
325
+ }
326
+ await waitFor(async () => !liveLock(io.env), 5000);
151
327
  }
152
- case "status":
153
- return status(rest, io);
154
- case "logs":
155
- return logs(rest, io);
156
- default:
157
- return fail(`unknown mcpd command "${sub ?? ""}"\n${USAGE}`);
328
+ did = true;
158
329
  }
330
+ if (!dryRun)
331
+ io.out(did ? "mcpd stopped" : "mcpd was not running");
332
+ const hint = journal.hint();
333
+ if (hint)
334
+ io.out(hint);
335
+ return 0;
336
+ });
337
+ }
338
+ async function restart(args, io) {
339
+ parseFlags(args, {}, 0);
340
+ const { installedBackend } = await import("../../mcpd/service.js");
341
+ return serviceStep(io, async () => {
342
+ const backend = await installedBackend(io.env);
343
+ if (!backend) {
344
+ io.err("turno: the mcpd service is not installed (turno mcp daemon start)");
345
+ return 1;
346
+ }
347
+ await backend.restart(io.env);
348
+ io.out("mcpd restarted; open sessions reconnect on their next call");
349
+ return 0;
350
+ });
351
+ }
352
+ /** `turno mcp token rotate`: a new master token, then mcpd picks it up and profiles need a sync. */
353
+ async function token(args, io) {
354
+ const p = parseFlags(args, DRY_RUN, 1);
355
+ const action = p.positionals[0];
356
+ if (action !== "rotate")
357
+ return fail(`usage: turno mcp token rotate [--dry-run]`);
358
+ const file = tildify(paths(io.env).mcpdToken, io.env);
359
+ if (bool(p, "dry-run")) {
360
+ io.out(`would write a new token to ${file} and restart mcpd`);
361
+ return 0;
362
+ }
363
+ const { liveLock, rotateToken } = await import("../../mcpd/state.js");
364
+ const { installedBackend } = await import("../../mcpd/service.js");
365
+ rotateToken(io.env);
366
+ io.out(`new gateway token written to ${file}`);
367
+ const code = await serviceStep(io, async () => {
368
+ const backend = await installedBackend(io.env);
369
+ if (backend && (await backend.isLoaded(io.env))) {
370
+ await backend.restart(io.env);
371
+ io.out("mcpd restarted with the new token");
372
+ return 0;
373
+ }
374
+ const lock = liveLock(io.env);
375
+ if (lock && lock.pid !== process.pid) {
376
+ process.kill(lock.pid, "SIGHUP");
377
+ io.out(`mcpd (pid ${lock.pid}) reloads the new token`);
378
+ }
379
+ else
380
+ io.out("mcpd is not running; it uses the new token when it starts");
381
+ return 0;
382
+ });
383
+ io.out("Every profile token derives from it and stopped working: run `turno mcp sync` so each profile gets its new one; open sessions need a restart.");
384
+ return code;
385
+ }
386
+ const SUBS = {
387
+ start: { synopsis: "[--dry-run]", summary: "install the service (LaunchAgent or systemd user unit) and start mcpd", flags: ["--dry-run"], run: start },
388
+ stop: { synopsis: "[--dry-run]", summary: "stop mcpd and remove the service, so it does not start at login", flags: ["--dry-run"], run: stop },
389
+ restart: { summary: "restart the service (open sessions reconnect)", run: restart },
390
+ status: { synopsis: "[--json]", summary: "running servers, their clients and memory; why mcpd is down", flags: ["--json"], run: status },
391
+ logs: { synopsis: "[-n N] [--utc]", summary: "last lines of the mcpd log, in local time", flags: ["--tail", "--utc"], run: logs },
392
+ run: { synopsis: "[--port N]", summary: "run the gateway in the foreground (what the service runs)", flags: ["--port"], run: runDaemon },
393
+ token: { synopsis: "rotate [--dry-run]", summary: "replace the gateway token (then turno mcp sync)", args: ["any"], flags: ["--dry-run"], run: token },
394
+ };
395
+ export const tokenCommand = {
396
+ summary: "replace the gateway token",
397
+ usage: "Usage: turno mcp token rotate [--dry-run]\n\nWrites a new token (mode 600), restarts mcpd, and asks you to run turno mcp sync.",
398
+ run: async (args, io) => {
399
+ if (!args.includes("--help") && !args.includes("-h"))
400
+ return token(args, io);
401
+ io.out(tokenCommand.usage);
402
+ return 0;
159
403
  },
160
404
  };
405
+ export const command = group("mcp daemon", "run or manage the MCP gateway daemon", SUBS, {
406
+ footer: "mcpd listens on 127.0.0.1 at mcpd.port (config.toml) and never moves to another port.\n" +
407
+ "start keeps it alive with a LaunchAgent on macOS or a systemd user unit on Linux; stop removes it.",
408
+ });
161
409
  //# sourceMappingURL=mcpd.js.map
@@ -2,6 +2,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { isValidProfileName, parseConfig } from "../../core/config.js";
4
4
  import { paths, tildify } from "../../core/paths.js";
5
+ import { DRY_RUN, FORCE, bool, flagsOf, parseFlags } from "../args.js";
5
6
  import { fail } from "../io.js";
6
7
  import { detectNerdTerminals } from "../../ui/terminals.js";
7
8
  import { Journal } from "../../core/journal.js";
@@ -157,8 +158,11 @@ export function migrate(io, opts = {}) {
157
158
  io.out(`undo with: turno undo ${journal.stamp}`);
158
159
  return 0;
159
160
  }
161
+ const SPEC = { ...DRY_RUN, ...FORCE };
160
162
  export const command = {
161
163
  summary: "import the bash claudio config and state into the new layout",
164
+ hidden: true,
165
+ flags: flagsOf(SPEC),
162
166
  usage: [
163
167
  "Usage: turno migrate [--dry-run] [--force]",
164
168
  "",
@@ -167,10 +171,8 @@ export const command = {
167
171
  "snapshots, exhausted marks and plans to the state folder. Never changes legacy files.",
168
172
  ].join("\n"),
169
173
  async run(args, io) {
170
- for (const a of args)
171
- if (a !== "--dry-run" && a !== "--force")
172
- fail(`unknown option: ${a}`);
173
- return migrate(io, { dryRun: args.includes("--dry-run"), force: args.includes("--force") });
174
+ const p = parseFlags(args, SPEC, 0);
175
+ return migrate(io, { dryRun: bool(p, "dry-run"), force: bool(p, "force") });
174
176
  },
175
177
  };
176
178
  //# sourceMappingURL=migrate.js.map
@@ -1,59 +1,124 @@
1
1
  import { spawn } from "node:child_process";
2
- import { existsSync, mkdirSync } from "node:fs";
2
+ import { existsSync } from "node:fs";
3
3
  import { loadConfig } from "../../core/config.js";
4
+ import { ensurePrivateDir, findOnPath } from "../../core/paths.js";
4
5
  import { profileFromConfigDir } from "../../core/profiles.js";
5
6
  import { fail } from "../io.js";
6
7
  import { checkName } from "./setup.js";
8
+ const USAGE = [
9
+ "Usage: turno open [profile] <url>",
10
+ "",
11
+ "claude.ai and claude.com links open in the profile's isolated Google Chrome profile,",
12
+ 'or in the default browser when profiles.<name>.browser = "default". Other links',
13
+ "always open in the default browser. Only http(s) and mailto links are accepted.",
14
+ "Claude Code calls this through $BROWSER. Typed in a terminal outside a profile's session,",
15
+ "a claude.ai link without a profile shows the profiles to choose from.",
16
+ ].join("\n");
7
17
  /** claude.ai and claude.com links (and their subdomains) open with the profile's account. */
8
18
  export function isClaudeUrl(url) {
9
19
  return /^https:\/\/([A-Za-z0-9-]+\.)*claude\.(ai|com)\//.test(url);
10
20
  }
21
+ /**
22
+ * Links turno hands to the system opener: http(s) and mailto only. `open` and `xdg-open` also
23
+ * run file paths, file:// URLs and custom schemes, and read a leading `-` as an option.
24
+ */
25
+ export function isOpenableUrl(url) {
26
+ return !url.startsWith("-") && /^(https?:\/\/[^\s]+|mailto:[^\s]+)$/i.test(url);
27
+ }
28
+ /** Chrome executables looked up on PATH on Linux, in order. */
29
+ export const LINUX_CHROMES = ["google-chrome", "google-chrome-stable", "chromium", "chromium-browser"];
11
30
  function chromeApp(env) {
12
31
  return env.TURNO_CHROME_APP || "/Applications/Google Chrome.app";
13
32
  }
14
- /** The `open` invocation for a link: argv for /usr/bin/open. */
15
- export function openArgs(profile, url, env = process.env) {
33
+ /** The Chrome profile a claude.ai link opens in, or undefined for the default browser. */
34
+ function chromeProfile(profile, url, env) {
16
35
  if (!isClaudeUrl(url))
17
- return [url];
36
+ return undefined;
18
37
  const config = loadConfig(env);
19
38
  const name = profile ?? profileFromConfigDir(env.CLAUDE_CONFIG_DIR, config, env) ?? config.system;
20
39
  if (!name)
21
- return [url];
40
+ return undefined;
22
41
  checkName(name);
23
42
  if (config.profiles[name]?.browser === "default")
24
- return [url];
25
- if (!existsSync(chromeApp(env)))
26
- return [url];
27
- mkdirSync(config.open.chromeDir, { recursive: true });
28
- return ["-na", "Google Chrome", "--args", `--user-data-dir=${config.open.chromeDir}`, `--profile-directory=${name}`, url];
43
+ return undefined;
44
+ return { name, dir: config.open.chromeDir };
45
+ }
46
+ /**
47
+ * The command that opens `url` on `platform`: `open` on macOS (Chrome through the app bundle),
48
+ * `xdg-open` on Linux (Chrome found on PATH). Throws a usage error for anything that is not an
49
+ * http(s) or mailto link, and on other platforms.
50
+ */
51
+ export function openInvocation(profile, url, env = process.env, platform = process.platform) {
52
+ if (!isOpenableUrl(url))
53
+ fail(`refusing to open ${JSON.stringify(url)}: only http(s) and mailto links`);
54
+ if (platform !== "darwin" && platform !== "linux")
55
+ fail(`turno open supports macOS and Linux, not ${platform}`);
56
+ const chrome = chromeProfile(profile, url, env);
57
+ if (platform === "darwin") {
58
+ if (!chrome || !existsSync(chromeApp(env)))
59
+ return { command: "open", args: [url] };
60
+ ensurePrivateDir(chrome.dir, env);
61
+ return { command: "open", args: ["-na", "Google Chrome", "--args", `--user-data-dir=${chrome.dir}`, `--profile-directory=${chrome.name}`, url] };
62
+ }
63
+ const bin = chrome && (env.TURNO_CHROME_BIN || LINUX_CHROMES.map((c) => findOnPath(c, env)).find(Boolean));
64
+ if (chrome && bin) {
65
+ ensurePrivateDir(chrome.dir, env);
66
+ return { command: bin, args: [`--user-data-dir=${chrome.dir}`, `--profile-directory=${chrome.name}`, url], detach: true };
67
+ }
68
+ if (!findOnPath("xdg-open", env))
69
+ fail("cannot open links: xdg-open is not installed (package xdg-utils)");
70
+ return { command: "xdg-open", args: [url] };
71
+ }
72
+ /** The `open` argv on macOS (kept for callers that only target macOS). */
73
+ export function openArgs(profile, url, env = process.env) {
74
+ return openInvocation(profile, url, env, "darwin").args;
75
+ }
76
+ /**
77
+ * The profile for a claude.ai link typed in a terminal without one: outside a profile's session
78
+ * a person chooses (the system profile first). Claude Code calling through $BROWSER, a script or
79
+ * an agent never sees the picker and keeps the default.
80
+ */
81
+ async function chooseProfile(url, io) {
82
+ if (!io.ask || !isOpenableUrl(url) || !isClaudeUrl(url))
83
+ return undefined;
84
+ const config = loadConfig(io.env);
85
+ // A profile's session (its launcher sets CLAUDE_CONFIG_DIR) opens links with its own account.
86
+ if (io.env.CLAUDE_CONFIG_DIR && profileFromConfigDir(io.env.CLAUDE_CONFIG_DIR, config, io.env))
87
+ return undefined;
88
+ const { pickProfile } = await import("../picker.js");
89
+ return pickProfile(io, { command: "open", title: "Open the link with", agent: "claude", ...(config.system ? { initial: config.system } : {}) });
29
90
  }
30
91
  export const command = {
31
92
  summary: "open a claude.ai link with an account (default: the session's)",
32
- usage: [
33
- "Usage: turno open [profile] <url>",
34
- "",
35
- "claude.ai and claude.com links open in the profile's isolated Google Chrome profile,",
36
- 'or in the default browser when profiles.<name>.browser = "default". Other links',
37
- "always open in the default browser. Claude Code calls this through $BROWSER.",
38
- ].join("\n"),
93
+ usage: USAGE,
39
94
  async run(args, io) {
40
- let profile;
41
- let rest = args;
42
- if (rest.length >= 2) {
43
- profile = rest[0];
44
- rest = rest.slice(1);
95
+ if (args.includes("--help") || args.includes("-h")) {
96
+ io.out(USAGE);
97
+ return 0;
45
98
  }
46
- const url = rest[0];
99
+ if (args.length > 2)
100
+ fail("usage: turno open [profile] <url>");
101
+ let [profile, url] = args.length === 2 ? [args[0], args[1]] : [undefined, args[0]];
47
102
  if (!url)
48
103
  fail("usage: turno open [profile] <url>");
49
- const argv = openArgs(profile, url, io.env);
104
+ profile ??= await chooseProfile(url, io);
105
+ const inv = openInvocation(profile, url, io.env);
50
106
  return new Promise((resolve) => {
51
- const child = spawn("open", argv, { stdio: "inherit", env: io.env });
107
+ const child = spawn(inv.command, inv.args, inv.detach ? { stdio: "ignore", env: io.env, detached: true } : { stdio: "inherit", env: io.env });
52
108
  child.on("error", (err) => {
53
- io.err(`turno: open: ${err.message}`);
109
+ io.err(`turno: open: ${err.code === "ENOENT" ? `${inv.command} not found` : err.message}`);
54
110
  resolve(1);
55
111
  });
56
- child.on("exit", (code) => resolve(code ?? 1));
112
+ if (inv.detach) {
113
+ // Chrome either hands the link to a running instance and exits, or becomes the browser.
114
+ child.on("spawn", () => {
115
+ child.unref();
116
+ resolve(0);
117
+ });
118
+ }
119
+ else {
120
+ child.on("exit", (code) => resolve(code ?? 1));
121
+ }
57
122
  });
58
123
  },
59
124
  };