turno-cli 0.2.0 → 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 (112) hide show
  1. package/CHANGELOG.md +148 -0
  2. package/README.md +127 -39
  3. package/dist/accounts/audit.js +27 -15
  4. package/dist/accounts/builtin.js +35 -7
  5. package/dist/accounts/delegate.js +30 -7
  6. package/dist/accounts/policy.js +4 -2
  7. package/dist/accounts/registry.js +3 -1
  8. package/dist/agents/adapter.js +22 -0
  9. package/dist/agents/claude.js +54 -3
  10. package/dist/agents/codex.js +94 -6
  11. package/dist/agents/copilot.js +19 -2
  12. package/dist/agents/cursor.js +19 -2
  13. package/dist/agents/index.js +1 -1
  14. package/dist/agents/snippets.js +37 -10
  15. package/dist/cli/args.js +32 -15
  16. package/dist/cli/commands/accounts.js +29 -7
  17. package/dist/cli/commands/auto.js +50 -12
  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 +159 -59
  22. package/dist/cli/commands/complete.js +13 -3
  23. package/dist/cli/commands/completion.js +4 -0
  24. package/dist/cli/commands/config.js +90 -13
  25. package/dist/cli/commands/demo.js +36 -7
  26. package/dist/cli/commands/doctor.js +170 -36
  27. package/dist/cli/commands/identity.js +99 -12
  28. package/dist/cli/commands/init.js +42 -10
  29. package/dist/cli/commands/limit.js +65 -9
  30. package/dist/cli/commands/mcp-call.js +240 -0
  31. package/dist/cli/commands/mcp-oauth.js +33 -6
  32. package/dist/cli/commands/mcp-observe.js +128 -23
  33. package/dist/cli/commands/mcp-share.js +201 -0
  34. package/dist/cli/commands/mcp.js +203 -42
  35. package/dist/cli/commands/mcpd.js +76 -12
  36. package/dist/cli/commands/open.js +26 -3
  37. package/dist/cli/commands/profile.js +212 -30
  38. package/dist/cli/commands/resolve.js +8 -1
  39. package/dist/cli/commands/run.js +24 -4
  40. package/dist/cli/commands/secret.js +23 -38
  41. package/dist/cli/commands/session.js +16 -5
  42. package/dist/cli/commands/sessions.js +7 -1
  43. package/dist/cli/commands/setup.js +83 -11
  44. package/dist/cli/commands/status.js +67 -15
  45. package/dist/cli/commands/statusline.js +7 -2
  46. package/dist/cli/commands/ui.js +17 -5
  47. package/dist/cli/commands/undo.js +39 -7
  48. package/dist/cli/commands/uninstall.js +24 -5
  49. package/dist/cli/commands/upgrade.js +113 -76
  50. package/dist/cli/commands/usage.js +11 -10
  51. package/dist/cli/commands/version.js +20 -8
  52. package/dist/cli/commands/which.js +5 -3
  53. package/dist/cli/diagnostics.js +184 -0
  54. package/dist/cli/exit.js +65 -0
  55. package/dist/cli/group.js +20 -8
  56. package/dist/cli/help.js +6 -1
  57. package/dist/cli/hints.js +30 -0
  58. package/dist/cli/io.js +24 -8
  59. package/dist/cli/launch.js +31 -2
  60. package/dist/cli/launchers.js +25 -10
  61. package/dist/cli/main.js +52 -18
  62. package/dist/cli/optional.js +144 -0
  63. package/dist/cli/output.js +123 -0
  64. package/dist/cli/picker.js +17 -5
  65. package/dist/cli/registry.js +20 -2
  66. package/dist/cli/safe.js +87 -0
  67. package/dist/cli/secret-input.js +63 -0
  68. package/dist/cli/security.js +31 -9
  69. package/dist/cli/style.js +35 -5
  70. package/dist/cli/topics.js +142 -0
  71. package/dist/core/config.js +39 -3
  72. package/dist/core/fsutil.js +2 -10
  73. package/dist/core/journal.js +19 -11
  74. package/dist/core/manifest.js +28 -1
  75. package/dist/core/paths.js +6 -112
  76. package/dist/core/profiles.js +28 -8
  77. package/dist/core/resolve.js +13 -3
  78. package/dist/core/secrets.js +4 -154
  79. package/dist/core/state-file.js +107 -0
  80. package/dist/core/update.js +14 -11
  81. package/dist/core/version.js +57 -10
  82. package/dist/demo/server.js +10 -2
  83. package/dist/mcpd/cache.js +6 -7
  84. package/dist/mcpd/calllog.js +10 -9
  85. package/dist/mcpd/client-names.js +8 -13
  86. package/dist/mcpd/connectors.js +42 -3
  87. package/dist/mcpd/daemon.js +29 -8
  88. package/dist/mcpd/folder-sets.js +5 -2
  89. package/dist/mcpd/gateway.js +57 -29
  90. package/dist/mcpd/health.js +69 -25
  91. package/dist/mcpd/importer.js +106 -9
  92. package/dist/mcpd/instances.js +59 -31
  93. package/dist/mcpd/jsonrpc.js +3 -1
  94. package/dist/mcpd/middleware.js +144 -0
  95. package/dist/mcpd/modern.js +57 -19
  96. package/dist/mcpd/oauth.js +71 -17
  97. package/dist/mcpd/peerpid.js +15 -3
  98. package/dist/mcpd/pressure.js +4 -1
  99. package/dist/mcpd/rss.js +34 -19
  100. package/dist/mcpd/service.js +28 -4
  101. package/dist/mcpd/share.js +217 -0
  102. package/dist/mcpd/state.js +16 -16
  103. package/dist/mcpd/sync.js +22 -12
  104. package/dist/mcpd/systemd.js +4 -1
  105. package/dist/mcpd/tokens.js +4 -8
  106. package/dist/mcpd/upstream.js +12 -5
  107. package/dist/statusline/cost.js +17 -4
  108. package/dist/statusline/input.js +15 -3
  109. package/dist/ui/fonts.js +1 -1
  110. package/dist/ui/settings.js +6 -1
  111. package/npm-shrinkwrap.json +12 -3
  112. package/package.json +7 -6
@@ -1,14 +1,53 @@
1
- import { JSON_FLAG, TAIL, bool, count, parseFlags, printJson, str } from "../args.js";
2
- import { paint } from "../io.js";
1
+ import { JSON_FLAG, TAIL, WATCH, bool, count, parseFlags, str } from "../args.js";
2
+ import { Exit } from "../exit.js";
3
+ import { fail, paint } from "../io.js";
4
+ import { emit, emitLine, jsonOutput } from "../output.js";
3
5
  import { duration as elapsed, padEnd, style } from "../style.js";
4
6
  /**
5
- * Observability subcommands of `turno mcp` (ADR 0026): `log` reads the call log mcpd keeps,
7
+ * Observability subcommands of `turno mcp`: `log` reads the call log mcpd keeps,
6
8
  * `top` shows what each running server costs, `savings` compares mcpd's memory with what the
7
9
  * same agent sessions would use without the gateway.
8
10
  */
9
- export const LOG_FLAGS = { follow: { type: "boolean", short: "f" }, ...TAIL, server: { type: "string" }, profile: { type: "string" }, ...JSON_FLAG };
10
- export const TOP_FLAGS = { once: { type: "boolean" }, ...JSON_FLAG };
11
+ export const LOG_FLAGS = {
12
+ follow: { type: "boolean", short: "f" },
13
+ ...TAIL,
14
+ server: { type: "string" },
15
+ profile: { type: "string" },
16
+ ...JSON_FLAG,
17
+ };
18
+ export const TOP_FLAGS = { once: { type: "boolean" }, ...WATCH, ...JSON_FLAG };
11
19
  export const SAVINGS_FLAGS = { ...JSON_FLAG };
20
+ /** `turno mcp log --json`: one call record per line. */
21
+ export const LOG_JSON = jsonOutput([
22
+ "time",
23
+ "agent",
24
+ "profile",
25
+ "pid",
26
+ "server",
27
+ "variant",
28
+ "tool",
29
+ "durationMs",
30
+ "outcome",
31
+ "error",
32
+ "requestBytes",
33
+ "responseBytes",
34
+ ]);
35
+ /** `turno mcp top --json`; `{ running: false }` when mcpd is down. */
36
+ export const TOP_JSON = jsonOutput(["running", "mcpd", "instances", "memoryKnown", "memoryPressure"]);
37
+ /** `turno mcp savings --json`; `{ running: false }` or `{ running: true, error }` when it cannot tell. */
38
+ export const SAVINGS_JSON = jsonOutput([
39
+ "running",
40
+ "agentSessions",
41
+ "unidentifiedSessions",
42
+ "withTurno",
43
+ "withoutTurnoBytes",
44
+ "savedBytes",
45
+ "savedPercent",
46
+ "servers",
47
+ "unmeasured",
48
+ "estimate",
49
+ "error",
50
+ ]);
12
51
  const MiB = 1024 * 1024;
13
52
  const GiB = 1024 * MiB;
14
53
  /** "95 MB", "1.4 GB"; "?" when unknown. */
@@ -133,7 +172,10 @@ export function formatCall(io, r, localTime, layout) {
133
172
  export async function log(args, io, signal) {
134
173
  const p = parseFlags(args, LOG_FLAGS, 0);
135
174
  const n = count(p, "tail", 20);
136
- const filter = { ...(str(p, "server") ? { server: str(p, "server") } : {}), ...(str(p, "profile") ? { profile: str(p, "profile") } : {}) };
175
+ const filter = {
176
+ ...(str(p, "server") ? { server: str(p, "server") } : {}),
177
+ ...(str(p, "profile") ? { profile: str(p, "profile") } : {}),
178
+ };
137
179
  const json = bool(p, "json");
138
180
  const { daemonFiles, loadConfigSafe } = await import("../../mcpd/state.js");
139
181
  const { followCalls, readCalls } = await import("../../mcpd/calllog.js");
@@ -144,7 +186,7 @@ export async function log(args, io, signal) {
144
186
  }
145
187
  const records = readCalls(file, n, filter);
146
188
  const layout = logLayout(io, records);
147
- const print = (r) => io.out(json ? JSON.stringify(r) : formatCall(io, r, localTime, layout));
189
+ const print = (r) => (json ? emitLine(io, p, LOG_JSON, r) : io.out(formatCall(io, r, localTime, layout)));
148
190
  if (!records.length && !json && !bool(p, "follow")) {
149
191
  io.out("no tool calls logged yet (mcpd adds one line per tool call it relays)");
150
192
  return 0;
@@ -175,12 +217,13 @@ async function measure(env) {
175
217
  const { processTable } = await import("../../mcpd/rss.js");
176
218
  return processTable({ env });
177
219
  }
178
- function notRunning(io, json) {
179
- if (json)
180
- printJson(io, { running: false });
220
+ /** mcpd does not answer: exit 5. */
221
+ function notRunning(io, json, out = TOP_JSON) {
222
+ if (json !== false)
223
+ emit(io, json, out, { running: false });
181
224
  else
182
225
  io.out("mcpd is not running (turno mcp daemon start)");
183
- return 1;
226
+ return Exit.gatewayDown;
184
227
  }
185
228
  const MEMORY_UNKNOWN = "memory is unknown: ps is not available and there is no /proc";
186
229
  export async function topSnapshot(status, procs, now = Date.now()) {
@@ -214,7 +257,11 @@ export async function topSnapshot(status, procs, now = Date.now()) {
214
257
  .sort((a, b) => (b.rssBytes ?? 0) - (a.rssBytes ?? 0) || a.server.localeCompare(b.server)),
215
258
  memoryKnown: procs !== undefined,
216
259
  memoryPressure: status.memoryPressure
217
- ? { level: status.memoryPressure.level, idleUnderPressureSeconds: status.memoryPressure.idleUnderPressure, idleCapSeconds: status.memoryPressure.idleCap }
260
+ ? {
261
+ level: status.memoryPressure.level,
262
+ idleUnderPressureSeconds: status.memoryPressure.idleUnderPressure,
263
+ idleCapSeconds: status.memoryPressure.idleCap,
264
+ }
218
265
  : null,
219
266
  };
220
267
  }
@@ -248,7 +295,9 @@ export function renderTop(io, t) {
248
295
  return out;
249
296
  }
250
297
  // Column titles: muted lowercase on a terminal, as in turno status; uppercase in plain text.
251
- const rows = [["SERVER", "VARIANT", "SCOPE", "PID", "RSS", "SESSIONS", "IN FLIGHT", "IDLE", "RESTARTS", "UP", "HELD BY"].map((h) => s.muted(s.color ? h.toLowerCase() : h))];
298
+ const rows = [
299
+ ["SERVER", "VARIANT", "SCOPE", "PID", "RSS", "SESSIONS", "IN FLIGHT", "IDLE", "RESTARTS", "UP", "HELD BY"].map((h) => s.muted(s.color ? h.toLowerCase() : h)),
300
+ ];
252
301
  for (const i of t.instances) {
253
302
  rows.push([
254
303
  `${s.icon("on")}${s.color ? " " : ""}${s.bold(i.server)}`,
@@ -268,15 +317,33 @@ export function renderTop(io, t) {
268
317
  // Narrow terminals drop the holder, uptime, restarts and variant first.
269
318
  out.push(...s.table(rows, {
270
319
  indent: 0,
271
- columns: [{}, { drop: 1 }, {}, right, right, right, right, { ...right, drop: 3 }, { ...right, drop: 2 }, { ...right, drop: 4 }, { drop: 5 }],
320
+ columns: [
321
+ {},
322
+ { drop: 1 },
323
+ {},
324
+ right,
325
+ right,
326
+ right,
327
+ right,
328
+ { ...right, drop: 3 },
329
+ { ...right, drop: 2 },
330
+ { ...right, drop: 4 },
331
+ { drop: 5 },
332
+ ],
272
333
  }));
273
334
  return out;
274
335
  }
275
- /** `turno mcp top`: refreshes every 2 s in a terminal until Ctrl-C; one snapshot otherwise. */
336
+ /**
337
+ * `turno mcp top`: refreshes every 2 s in a terminal until Ctrl-C; one snapshot otherwise.
338
+ * `--watch --json` prints one snapshot per line (NDJSON) every 2 s until Ctrl-C.
339
+ */
276
340
  export async function top(args, io, signal, everyMs = 2000) {
277
341
  const p = parseFlags(args, TOP_FLAGS, 0);
278
342
  const json = bool(p, "json");
279
- const once = json || bool(p, "once") || !io.isTty;
343
+ const watch = bool(p, "watch");
344
+ if (watch && bool(p, "once"))
345
+ return fail("--watch and --once do not go together");
346
+ const once = (json && !watch) || bool(p, "once") || (!io.isTty && !watch);
280
347
  const snap = async () => {
281
348
  const s = await fetchStatus(io.env);
282
349
  return s ? topSnapshot(s, await measure(io.env)) : undefined;
@@ -284,14 +351,16 @@ export async function top(args, io, signal, everyMs = 2000) {
284
351
  if (once) {
285
352
  const t = await snap();
286
353
  if (!t)
287
- return notRunning(io, json);
354
+ return notRunning(io, json ? p : false);
288
355
  if (json)
289
- printJson(io, t);
356
+ emit(io, p, TOP_JSON, t);
290
357
  else
291
358
  for (const l of renderTop(io, t))
292
359
  io.out(l);
293
360
  return 0;
294
361
  }
362
+ if (json)
363
+ return watchTop(io, p, snap, signal, everyMs);
295
364
  const stop = signal ? { signal, dispose() { } } : untilInterrupted();
296
365
  try {
297
366
  while (!stop.signal.aborted) {
@@ -312,6 +381,30 @@ export async function top(args, io, signal, everyMs = 2000) {
312
381
  }
313
382
  return 0;
314
383
  }
384
+ /** `top --watch --json`: a snapshot per line, or `{ running: false }` while mcpd is down. */
385
+ async function watchTop(io, p, snap, signal, everyMs) {
386
+ const stop = signal ? { signal, dispose() { } } : untilInterrupted();
387
+ try {
388
+ while (!stop.signal.aborted) {
389
+ emitLine(io, p, TOP_JSON, (await snap()) ?? { running: false });
390
+ await sleep(everyMs, stop.signal);
391
+ }
392
+ }
393
+ finally {
394
+ stop.dispose();
395
+ }
396
+ return 0;
397
+ }
398
+ /** Wait `ms`, or less when `signal` aborts. */
399
+ function sleep(ms, signal) {
400
+ return new Promise((r) => {
401
+ const timer = setTimeout(r, ms);
402
+ signal.addEventListener("abort", () => {
403
+ clearTimeout(timer);
404
+ r();
405
+ }, { once: true });
406
+ });
407
+ }
315
408
  const avg = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
316
409
  /**
317
410
  * The comparison: mcpd plus its children now, against an estimate of the same agent sessions
@@ -362,7 +455,14 @@ export async function computeSavings(status, procs, manifest, now = new Date())
362
455
  }
363
456
  without += m.bytes;
364
457
  const key = `${def.name}@${variant}`;
365
- const row = per.get(key) ?? { server: def.name, variant, rssBytes: m.bytes, source: m.source, measuredAt: m.at, sessions: 0 };
458
+ const row = per.get(key) ?? {
459
+ server: def.name,
460
+ variant,
461
+ rssBytes: m.bytes,
462
+ source: m.source,
463
+ measuredAt: m.at,
464
+ sessions: 0,
465
+ };
366
466
  row.sessions++;
367
467
  per.set(key, row);
368
468
  }
@@ -375,7 +475,12 @@ export async function computeSavings(status, procs, manifest, now = new Date())
375
475
  running: true,
376
476
  agentSessions: n,
377
477
  unidentifiedSessions: agents.length - n,
378
- withTurno: { totalBytes: total, mcpdBytes, serversBytes: total - mcpdBytes, runningServers: status.instances.filter((i) => i.pid).length },
478
+ withTurno: {
479
+ totalBytes: total,
480
+ mcpdBytes,
481
+ serversBytes: total - mcpdBytes,
482
+ runningServers: status.instances.filter((i) => i.pid).length,
483
+ },
379
484
  withoutTurnoBytes: without,
380
485
  savedBytes: saved,
381
486
  savedPercent: without > 0 ? Math.round((saved / without) * 100) : null,
@@ -390,11 +495,11 @@ export async function savings(args, io) {
390
495
  const json = bool(p, "json");
391
496
  const status = await fetchStatus(io.env);
392
497
  if (!status)
393
- return notRunning(io, json);
498
+ return notRunning(io, json ? p : false, SAVINGS_JSON);
394
499
  const procs = await measure(io.env);
395
500
  if (!procs) {
396
501
  if (json)
397
- printJson(io, { running: true, error: MEMORY_UNKNOWN });
502
+ emit(io, p, SAVINGS_JSON, { running: true, error: MEMORY_UNKNOWN });
398
503
  else
399
504
  io.err(`turno: ${MEMORY_UNKNOWN}`);
400
505
  return 1;
@@ -405,7 +510,7 @@ export async function savings(args, io) {
405
510
  io.err(`${paint(io, "warning", "33")}: mcp.toml is invalid, so the estimate uses the ${state.source}: ${state.error}`);
406
511
  const s = await computeSavings(status, procs, state.manifest);
407
512
  if (json) {
408
- printJson(io, s);
513
+ emit(io, p, SAVINGS_JSON, s);
409
514
  return 0;
410
515
  }
411
516
  const w = s.withTurno;
@@ -0,0 +1,201 @@
1
+ /**
2
+ * `turno mcp export` and `turno mcp import <file>`: move MCP servers between machines
3
+ * without their secret values. The export is mcp.toml's own format; import also takes another
4
+ * agent's MCP config file.
5
+ */
6
+ import { existsSync, readFileSync } from "node:fs";
7
+ import { parse } from "smol-toml";
8
+ import { isValidProfileName } from "../../core/config.js";
9
+ import { Journal } from "../../core/journal.js";
10
+ import { paths, tildify } from "../../core/paths.js";
11
+ import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
12
+ import { nextStep } from "../hints.js";
13
+ import { CliError, fail, paint, plural } from "../io.js";
14
+ import { emit, jsonOutput } from "../output.js";
15
+ export const EXPORT_FLAGS = { profile: { type: "string" }, ...JSON_FLAG };
16
+ export const EXPORT_JSON = jsonOutput(["profile", "servers", "keychain", "envVars", "moved", "redacted", "text"]);
17
+ /** `turno mcp export [--profile p]`: mcp.toml on stdout, each secret by name only. */
18
+ export async function exportCmd(args, io) {
19
+ const p = parseFlags(args, EXPORT_FLAGS, 0);
20
+ const profile = str(p, "profile");
21
+ if (profile !== undefined && !isValidProfileName(profile))
22
+ fail(`invalid profile name: ${profile}`);
23
+ const file = paths(io.env).mcpFile;
24
+ if (!existsSync(file))
25
+ throw new CliError(`${tildify(file, io.env)} does not exist; nothing to export (turno mcp import drafts it)`);
26
+ const { exportManifest } = await import("../../mcpd/share.js");
27
+ const command = `turno mcp export${profile ? ` --profile ${profile}` : ""}`;
28
+ const r = exportManifest(readFileSync(file, "utf8"), { ...(profile ? { profile } : {}), command });
29
+ if (bool(p, "json")) {
30
+ emit(io, p, EXPORT_JSON, {
31
+ profile: profile ?? null,
32
+ servers: r.servers,
33
+ keychain: r.keychain,
34
+ envVars: r.envVars,
35
+ moved: r.moved,
36
+ redacted: r.redacted,
37
+ text: r.text,
38
+ });
39
+ return 0;
40
+ }
41
+ io.out(r.text.replace(/\n$/, ""));
42
+ // stderr: stdout is the file.
43
+ io.err(`turno: exported ${plural(r.servers.length, "server")}${profile ? ` for ${profile}` : ""}, no secret values`);
44
+ if (r.moved.length)
45
+ io.err(` literal secrets named as keychain references: ${r.moved.join(", ")}`);
46
+ if (r.redacted.length)
47
+ io.err(` ${paint(io, "warning", "33")}: secrets in ${r.redacted.join(", ")} replaced by <secret>; fill them in by hand`);
48
+ nextStep(io, "on the other machine, turno mcp import <file> --write, then the turno secret set lines at the top of the file", { stream: "err" });
49
+ return 0;
50
+ }
51
+ export const IMPORT_FLAGS = {
52
+ write: { type: "boolean" },
53
+ "move-secrets": { type: "boolean" },
54
+ force: { type: "boolean" },
55
+ "dry-run": { type: "boolean" },
56
+ };
57
+ /** The servers of `file`: mcp.toml's format, or an agent config converted like `turno mcp import` does. */
58
+ async function serversOf(file, io, write, moveSecrets) {
59
+ const { agentConfigServers, importServers, markOAuth, probeOAuth } = await import("../../mcpd/importer.js");
60
+ const { manifestServers } = await import("../../mcpd/share.js");
61
+ const shown = tildify(file, io.env);
62
+ if (!existsSync(file))
63
+ throw new CliError(`no such file: ${shown}`);
64
+ const text = readFileSync(file, "utf8");
65
+ const probe = write ? { probeAuth: (url) => probeOAuth(url) } : {};
66
+ let manifest = false;
67
+ try {
68
+ manifest = "server" in parse(text);
69
+ }
70
+ catch {
71
+ /* not TOML */
72
+ }
73
+ if (manifest) {
74
+ const servers = manifestServers(text, shown);
75
+ const notes = [];
76
+ if (probe.probeAuth)
77
+ await markOAuth(servers, probe.probeAuth, notes);
78
+ return { servers, notes, secrets: [], literalSecrets: [], from: "mcp.toml format" };
79
+ }
80
+ const found = agentConfigServers(text);
81
+ if (!found)
82
+ throw new CliError(`${shown} is not an mcp.toml (turno mcp export), a JSON file with mcpServers or a Codex config.toml with [mcp_servers]`);
83
+ const { binOf } = await import("./mcp.js");
84
+ const report = await importServers(found.servers, {
85
+ moveSecrets,
86
+ ...probe,
87
+ ...(write ? { binOf: (pkg) => binOf(io, pkg) } : {}),
88
+ });
89
+ return {
90
+ servers: manifestServers(report.toml, shown),
91
+ notes: report.notes,
92
+ secrets: report.secrets,
93
+ literalSecrets: report.literalSecrets,
94
+ from: `${found.agent} config`,
95
+ };
96
+ }
97
+ /** `turno mcp import <file>`: merge its servers into mcp.toml (a preview until --write). */
98
+ export async function importFile(file, args, io) {
99
+ const p = parseFlags(args, IMPORT_FLAGS, 1);
100
+ const write = bool(p, "write");
101
+ const force = bool(p, "force");
102
+ const moveSecrets = bool(p, "move-secrets");
103
+ if (write && bool(p, "dry-run"))
104
+ fail("--dry-run and --write do not go together (without --write it is a preview)");
105
+ const target = paths(io.env).mcpFile;
106
+ const r = await serversOf(file, io, write, moveSecrets);
107
+ const names = Object.keys(r.servers);
108
+ if (!names.length) {
109
+ io.out(`no MCP servers in ${tildify(file, io.env)}; nothing to import`);
110
+ return write ? 1 : 0;
111
+ }
112
+ const { mergeServers } = await import("../../mcpd/share.js");
113
+ const existing = existsSync(target) ? readFileSync(target, "utf8") : "";
114
+ let merged;
115
+ try {
116
+ merged = mergeServers(existing, r.servers, force);
117
+ }
118
+ catch (err) {
119
+ throw new CliError(err.message);
120
+ }
121
+ io.err(`found ${plural(names.length, "server")} in ${tildify(file, io.env)} (${r.from})`);
122
+ for (const n of r.notes)
123
+ io.err(` ${n}`);
124
+ if (r.literalSecrets.length)
125
+ io.err(` ${paint(io, "warning", "33")}: literal secrets kept (${r.literalSecrets.join(", ")}); add --move-secrets to store them in the Keychain`);
126
+ const verb = write ? ["added", "replaced", "kept"] : ["would add", "would replace", "would keep"];
127
+ const lines = [
128
+ merged.added.length ? `${verb[0]} ${merged.added.join(", ")}` : "",
129
+ merged.replaced.length ? `${verb[1]} ${merged.replaced.join(", ")}` : "",
130
+ merged.kept.length ? `${verb[2]} ${merged.kept.join(", ")} (already in mcp.toml; --force replaces them)` : "",
131
+ ].filter(Boolean);
132
+ if (!write) {
133
+ for (const l of lines)
134
+ io.out(l);
135
+ for (const s of r.secrets)
136
+ io.err(` would move ${s.where} to keychain:${s.service}`);
137
+ io.err(`Nothing written. Write it with: turno mcp import ${file} --write${moveSecrets ? " --move-secrets" : ""}${merged.kept.length ? " [--force]" : ""}`);
138
+ return 0;
139
+ }
140
+ if (!merged.added.length && !merged.replaced.length) {
141
+ for (const l of lines)
142
+ io.out(l);
143
+ return 0;
144
+ }
145
+ const { storeKeychainSecret } = await import("../../core/secrets.js");
146
+ for (const s of r.secrets) {
147
+ if (s.value.includes("${"))
148
+ continue;
149
+ await storeKeychainSecret(s.service, s.value, io.env);
150
+ io.err(` moved ${s.where} to keychain:${s.service}`);
151
+ }
152
+ const journal = new Journal(io.env, `mcp import ${file} --write`);
153
+ journal.write(target, merged.text, 0o600);
154
+ for (const l of lines)
155
+ io.out(l);
156
+ io.out(`wrote ${tildify(target, io.env)}`);
157
+ io.out(journal.hint());
158
+ nextStep(io, importNextSteps(merged.text, [...merged.added, ...merged.replaced]));
159
+ return 0;
160
+ }
161
+ /** What to run after importing `names`: secrets to store, packages to pin, logins, then sync. */
162
+ export function importNextSteps(text, names) {
163
+ const steps = [];
164
+ const keychain = new Set();
165
+ let packages = false;
166
+ const logins = [];
167
+ // Read back what was written, so the steps match the file.
168
+ const raw = parseRaw(text);
169
+ for (const n of names) {
170
+ const s = raw[n] ?? {};
171
+ if (typeof s.package === "string")
172
+ packages = true;
173
+ if (s.auth === "oauth")
174
+ logins.push(n);
175
+ const variants = s.variant && typeof s.variant === "object"
176
+ ? Object.values(s.variant)
177
+ : [];
178
+ for (const t of [s, ...variants]) {
179
+ for (const key of ["env", "headers"]) {
180
+ const m = t?.[key];
181
+ if (m && typeof m === "object")
182
+ for (const v of Object.values(m))
183
+ if (typeof v === "string" && v.startsWith("keychain:"))
184
+ keychain.add(v.slice(9));
185
+ }
186
+ }
187
+ }
188
+ if (keychain.size)
189
+ steps.push(`turno secret list shows which of ${plural(keychain.size, "keychain reference")} still need turno secret set`);
190
+ if (packages)
191
+ steps.push("turno mcp install pins and installs the packages");
192
+ if (logins.length)
193
+ steps.push(`turno mcp login ${logins.join(", ")} (one login each)`);
194
+ steps.push("turno mcp sync points your profiles at them");
195
+ return steps;
196
+ }
197
+ function parseRaw(text) {
198
+ const raw = parse(text);
199
+ return (raw.server ?? {});
200
+ }
201
+ //# sourceMappingURL=mcp-share.js.map