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,6 +1,6 @@
1
1
  import { existsSync, readdirSync, statSync } from "node:fs";
2
2
  import { dirname, join, resolve as resolvePath } from "node:path";
3
- import { AGENT_IDS, DEFAULT_AGENT, adapter, agentHub, agentProfileDir, isAgentId, mcpFileFor } from "../../agents/index.js";
3
+ import { AGENT_IDS, DEFAULT_AGENT, adapter, agentHub, agentProfileDir, isAgentId, mcpFileFor, } from "../../agents/index.js";
4
4
  import { editConfig, migrationPending, MigrationPending, readConfigText } from "../../core/config-edit.js";
5
5
  import { loadConfig, parseConfig } from "../../core/config.js";
6
6
  import { Journal } from "../../core/journal.js";
@@ -169,7 +169,11 @@ function printDiff(io, before, after) {
169
169
  continue;
170
170
  }
171
171
  gap = false;
172
- io.out(op === "+" ? st.wrap(` ${paint(io, "+", "32")}`, shown) : op === "-" ? st.wrap(" ", paint(io, `-${line}`, "31")) : st.wrap(" ", shown));
172
+ io.out(op === "+"
173
+ ? st.wrap(` ${paint(io, "+", "32")}`, shown)
174
+ : op === "-"
175
+ ? st.wrap(" ", paint(io, `-${line}`, "31"))
176
+ : st.wrap(" ", shown));
173
177
  }
174
178
  }
175
179
  /** New text shown as all added lines: a green `+`, then the line highlighted as TOML. */
@@ -235,7 +239,14 @@ async function mcpPlan(io, skip, profiles) {
235
239
  return { kind: "none" };
236
240
  const report = await importServers(merged.servers);
237
241
  parseManifest(report.toml); // never write something that cannot be read back
238
- return { kind: "import", summary: foundSummary(names, merged.from), notes: [...merged.notes, ...report.notes], report, servers: names, merged: merged.servers };
242
+ return {
243
+ kind: "import",
244
+ summary: foundSummary(names, merged.from),
245
+ notes: [...merged.notes, ...report.notes],
246
+ report,
247
+ servers: names,
248
+ merged: merged.servers,
249
+ };
239
250
  }
240
251
  /** The manifest to write, with command names from npm (the only network call of init). */
241
252
  async function resolveMcp(io, plan) {
@@ -278,7 +289,8 @@ async function makePlan(args, io, ask) {
278
289
  const claudeHere = agents[0].installed || existsSync(paths(env).hub);
279
290
  const fallbackAgent = claudeHere ? undefined : agents.find((a) => a.installed)?.id;
280
291
  const suggestion = fallbackAgent ? `work:${fallbackAgent} personal:${fallbackAgent}` : "work personal";
281
- const answer = (await io.ask(`Profiles to create (names; name:codex for another agent) [${suggestion}]: `)).trim() || suggestion;
292
+ const answer = (await io.ask(`Profiles to create (names; name:codex for another agent) [${suggestion}]: `)).trim() ||
293
+ suggestion;
282
294
  if (!/^none$/i.test(answer)) {
283
295
  for (const word of answer.split(/[\s,]+/).filter(Boolean)) {
284
296
  const np = parseProfileArg(word);
@@ -289,7 +301,10 @@ async function makePlan(args, io, ask) {
289
301
  }
290
302
  }
291
303
  // Folder rules for profiles of the default agent, from the projects each account was used in.
292
- const claude = [...existing.filter((n) => agentOf(n, config) === DEFAULT_AGENT), ...profiles.filter((n) => n.agent === DEFAULT_AGENT).map((n) => n.name)];
304
+ const claude = [
305
+ ...existing.filter((n) => agentOf(n, config) === DEFAULT_AGENT),
306
+ ...profiles.filter((n) => n.agent === DEFAULT_AGENT).map((n) => n.name),
307
+ ];
293
308
  const ruled = config.projects.map((r) => resolvePath(expandHome(r.path, env)));
294
309
  const rules = inferRules(folderOwners(env, claude), paths(env).home, ruled);
295
310
  let def = str(p, "default");
@@ -297,14 +312,18 @@ async function makePlan(args, io, ask) {
297
312
  fail(`--default ${def}: name a Claude Code profile (${claude.join(", ") || "none yet"})`);
298
313
  if (def === undefined && !config.default && ask && claude.length) {
299
314
  const suggestion = claude.includes("personal") ? "personal" : "none";
300
- const answer = (await io.ask(`Default profile for folders without a rule (none: plain claude) [${suggestion}]: `)).trim() || suggestion;
315
+ const answer = (await io.ask(`Default profile for folders without a rule (none: plain claude) [${suggestion}]: `)).trim() ||
316
+ suggestion;
301
317
  if (answer !== "none") {
302
318
  if (!claude.includes(answer))
303
319
  fail(`${answer} is not a Claude Code profile here (${claude.join(", ")})`);
304
320
  def = answer;
305
321
  }
306
322
  }
307
- const folders = [...existing.map((name) => ({ name, agent: agentOf(name, config) })), ...profiles.filter((np) => np.adopted)];
323
+ const folders = [
324
+ ...existing.map((name) => ({ name, agent: agentOf(name, config) })),
325
+ ...profiles.filter((np) => np.adopted),
326
+ ];
308
327
  const mcp = await mcpPlan(io, bool(p, "no-mcp"), folders);
309
328
  const plan = { agents, existing, profiles, rules, ...(def ? { default: def } : {}), mcp, notes };
310
329
  const before = readConfigText(env);
@@ -473,7 +492,10 @@ function tryLauncher(io, plan) {
473
492
  function printNext(io, plan, started, st) {
474
493
  const steps = [];
475
494
  if (plan.profiles.length)
476
- steps.push([`sign in once per profile where needed: ${plan.profiles.map((np) => loginHint(np.agent, launcherName(np.name, np.agent))).join(", ")}`, ""]);
495
+ steps.push([
496
+ `sign in once per profile where needed: ${plan.profiles.map((np) => loginHint(np.agent, launcherName(np.name, np.agent))).join(", ")}`,
497
+ "",
498
+ ]);
477
499
  if (hasServers(plan) && !started) {
478
500
  steps.push(["turno mcp daemon start", "the gateway, as a login service"]);
479
501
  steps.push(["turno mcp sync", "point every profile at it"]);
@@ -558,7 +580,11 @@ async function run(args, io) {
558
580
  }
559
581
  // Setup lines sit under the Write header.
560
582
  // Two columns narrower, so what setup wraps still fits after the indent.
561
- const indented = { ...io, env: { ...io.env, COLUMNS: String(st.width - 2) }, out: (line = "") => io.out(line ? line.replace(/^/gm, " ") : line) };
583
+ const indented = {
584
+ ...io,
585
+ env: { ...io.env, COLUMNS: String(st.width - 2) },
586
+ out: (line = "") => io.out(line ? line.replace(/^/gm, " ") : line),
587
+ };
562
588
  if (plan.profiles.length)
563
589
  setupProfiles(plan.profiles.map((np) => np.name), indented, { journal, brief: true });
564
590
  let gatewayUp = false;
@@ -606,7 +632,13 @@ and the default; without one, --yes is required and flags give the answers.
606
632
 
607
633
  When there are MCP servers, init in a terminal also offers to start the gateway as a login
608
634
  service and point every profile at it (turno mcp daemon start, turno mcp sync), in the same
609
- journal. With --yes it does that only with --start.`;
635
+ journal. With --yes it does that only with --start.
636
+
637
+ Examples:
638
+ $ turno init
639
+ $ turno init --dry-run
640
+ $ turno init --yes --profile work --profile school:codex
641
+ $ turno init --yes --no-mcp`;
610
642
  export const command = {
611
643
  summary: "set turno up in one step: find agents, profiles, folders and MCP servers, show the diff, write it (one undo)",
612
644
  usage: USAGE,
@@ -3,9 +3,10 @@ import { loadConfig } from "../../core/config.js";
3
3
  import { clearExhausted, exhaustedUntil, markExhausted } from "../../core/exhausted.js";
4
4
  import { agentOf, listProfiles } from "../../core/profiles.js";
5
5
  import { formatUntil } from "../../core/resolve.js";
6
- import { DRY_RUN, JSON_FLAG, WATCH, bool, flagsOf, parseFlags, printJson, str } from "../args.js";
6
+ import { DRY_RUN, JSON_FLAG, WATCH, bool, flagsOf, parseFlags, str } from "../args.js";
7
7
  import { group } from "../group.js";
8
8
  import { fail } from "../io.js";
9
+ import { emit, emitLines, jsonOutput } from "../output.js";
9
10
  import { launcherPath } from "../launch.js";
10
11
  import { parseLocalDateTime } from "./exhausted.js";
11
12
  import { command as usage, account, usageSnapshot } from "./usage.js";
@@ -21,11 +22,15 @@ export async function limitsData(env, withAccounts = true) {
21
22
  const config = loadConfig(env);
22
23
  const profiles = listProfiles(config, env);
23
24
  // Usage windows and accounts come from Claude Code; other agents show only exhausted marks.
24
- const accounts = withAccounts ? await Promise.all(profiles.map((p) => (adapter(agentOf(p, config)).accountDetails ? account(p, env) : undefined))) : [];
25
+ const accounts = withAccounts
26
+ ? await Promise.all(profiles.map((p) => (adapter(agentOf(p, config)).accountDetails ? account(p, env) : undefined)))
27
+ : [];
25
28
  return profiles.map((p, i) => {
26
29
  const snap = usageSnapshot(p, env);
27
30
  const limits = snap.rate_limits ?? {};
28
- const win = (w) => w ? { used: Number(w.used_percentage) || 0, resetsAt: typeof w.resets_at === "number" ? w.resets_at : null } : null;
31
+ const win = (w) => w
32
+ ? { used: Number(w.used_percentage) || 0, resetsAt: typeof w.resets_at === "number" ? w.resets_at : null }
33
+ : null;
29
34
  return {
30
35
  profile: p,
31
36
  agent: agentOf(p, config),
@@ -38,12 +43,16 @@ export async function limitsData(env, withAccounts = true) {
38
43
  });
39
44
  }
40
45
  const SHOW_SPEC = { ...JSON_FLAG, ...WATCH };
46
+ /** `turno limit show --json`: one element per profile. */
47
+ const SHOW_JSON = jsonOutput(["profile", "agent", "email", "plan", "exhaustedUntil", "fiveHour", "week", "updatedAt"]);
48
+ /** How often `limit show --watch --json` prints the profiles again. */
49
+ const WATCH_EVERY_MS = 30_000;
41
50
  async function show(args, io) {
42
51
  const p = parseFlags(args, SHOW_SPEC, 0);
43
52
  if (bool(p, "json")) {
44
53
  if (bool(p, "watch"))
45
- fail("--json and --watch do not go together");
46
- printJson(io, await limitsData(io.env));
54
+ return watchJson(io, p);
55
+ emit(io, p, SHOW_JSON, await limitsData(io.env));
47
56
  return 0;
48
57
  }
49
58
  const config = loadConfig(io.env);
@@ -57,9 +66,36 @@ async function show(args, io) {
57
66
  }
58
67
  return usage.run(bool(p, "watch") ? ["--watch"] : [], io);
59
68
  }
69
+ /**
70
+ * `--watch --json`: every profile as one JSON line (NDJSON) now and every 30 s, until Ctrl-C or
71
+ * `signal`. A reader tells the rounds apart by `updatedAt` or by the profile coming back.
72
+ */
73
+ export async function watchJson(io, p, signal, everyMs = WATCH_EVERY_MS) {
74
+ const stop = signal ?? interrupted();
75
+ while (!stop.aborted) {
76
+ emitLines(io, p, SHOW_JSON, await limitsData(io.env));
77
+ await new Promise((r) => {
78
+ const timer = setTimeout(r, everyMs);
79
+ stop.addEventListener("abort", () => {
80
+ clearTimeout(timer);
81
+ r();
82
+ }, { once: true });
83
+ });
84
+ }
85
+ return 0;
86
+ }
87
+ /** An abort signal for Ctrl-C. */
88
+ function interrupted() {
89
+ const c = new AbortController();
90
+ process.once("SIGINT", () => c.abort());
91
+ return c.signal;
92
+ }
60
93
  async function profileArg(given, io, verb) {
61
94
  const name = given ??
62
- (await (await import("../picker.js")).pickProfile(io, { command: `limit ${verb}`, title: verb === "set" ? "Profile to mark exhausted" : "Profile to clear" }));
95
+ (await (await import("../picker.js")).pickProfile(io, {
96
+ command: `limit ${verb}`,
97
+ title: verb === "set" ? "Profile to mark exhausted" : "Profile to clear",
98
+ }));
63
99
  if (!launcherPath(name, io.env))
64
100
  fail(`no profile '${name}' (turno profile list shows them)`);
65
101
  return name;
@@ -101,7 +137,13 @@ async function clear(args, io) {
101
137
  return 0;
102
138
  }
103
139
  export const command = group("limit", "usage limits of each account, and the exhausted marks that move projects to the fallback", {
104
- show: { summary: "5 h and weekly usage of each account, as bars", synopsis: "[--watch] [--json]", flags: flagsOf(SHOW_SPEC), run: show },
140
+ show: {
141
+ summary: "5 h and weekly usage of each account, as bars",
142
+ synopsis: "[--watch] [--json]",
143
+ flags: flagsOf(SHOW_SPEC),
144
+ json: SHOW_JSON,
145
+ run: show,
146
+ },
105
147
  set: {
106
148
  summary: "mark a profile exhausted (default for 5 h); its projects open with the fallback, if one is set",
107
149
  synopsis: '<profile> [--until "YYYY-MM-DD HH:MM" | --for 2h] [--dry-run]',
@@ -109,6 +151,20 @@ export const command = group("limit", "usage limits of each account, and the exh
109
151
  flags: flagsOf(SET_SPEC),
110
152
  run: set,
111
153
  },
112
- clear: { summary: "clear a profile's exhausted mark", synopsis: "<profile> [--dry-run]", args: ["profile"], flags: flagsOf(DRY_RUN), run: clear },
113
- }, { fallback: "show" });
154
+ clear: {
155
+ summary: "clear a profile's exhausted mark",
156
+ synopsis: "<profile> [--dry-run]",
157
+ args: ["profile"],
158
+ flags: flagsOf(DRY_RUN),
159
+ run: clear,
160
+ },
161
+ }, {
162
+ fallback: "show",
163
+ examples: [
164
+ "turno limit show",
165
+ "turno limit show --watch --json # one JSON line per profile, every 30 s",
166
+ "turno limit set work --for 2h",
167
+ "turno limit clear work",
168
+ ],
169
+ });
114
170
  //# sourceMappingURL=limit.js.map
@@ -0,0 +1,240 @@
1
+ /**
2
+ * `turno mcp call <server> [tool]`: call one tool through mcpd from the terminal, the way an
3
+ * agent session of a profile would (its token, this folder), to debug a server without opening
4
+ * an agent. Loaded only when the subcommand runs: it brings in the MCP SDK client.
5
+ */
6
+ import { gatewayUrl } from "../../agents/adapter.js";
7
+ import { loadConfig } from "../../core/config.js";
8
+ import { loadManifest, servesProfile } from "../../core/manifest.js";
9
+ import { resolveProfile } from "../../core/resolve.js";
10
+ import { packageInfo } from "../../core/version.js";
11
+ import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
12
+ import { Exit } from "../exit.js";
13
+ import { CliError, UsageError, fail } from "../io.js";
14
+ import { emit, jsonOutput } from "../output.js";
15
+ import { duration, style } from "../style.js";
16
+ export const CALL_FLAGS = {
17
+ args: { type: "string" },
18
+ arg: { type: "string", multiple: true },
19
+ profile: { type: "string" },
20
+ ...JSON_FLAG,
21
+ };
22
+ /**
23
+ * `turno mcp call --json`. A call fills `tool`, `isError`, `content` and
24
+ * `structuredContent`; without a tool, `tools` lists the server's tools and the rest is null.
25
+ */
26
+ export const CALL_JSON = jsonOutput([
27
+ "server",
28
+ "profile",
29
+ "tool",
30
+ "isError",
31
+ "content",
32
+ "structuredContent",
33
+ "tools",
34
+ "ms",
35
+ ]);
36
+ /**
37
+ * The tool arguments: `--args` (a JSON object), then each `--arg key=value` (a string) or
38
+ * `--arg key:=json` (any JSON value) on top of it, as httpie writes them.
39
+ */
40
+ export function callArguments(json, pairs) {
41
+ let out = {};
42
+ if (json !== undefined) {
43
+ let v;
44
+ try {
45
+ v = JSON.parse(json);
46
+ }
47
+ catch (err) {
48
+ throw new UsageError(`--args is not JSON: ${err.message}`);
49
+ }
50
+ if (typeof v !== "object" || v === null || Array.isArray(v))
51
+ throw new UsageError('--args must be a JSON object, like \'{"query": "x"}\'');
52
+ out = { ...v };
53
+ }
54
+ for (const pair of pairs) {
55
+ const m = /^([^=:]+)(:?=)([\s\S]*)$/.exec(pair);
56
+ if (!m)
57
+ throw new UsageError(`--arg ${pair}: use key=value (a string) or key:=json (a number, true, a list...)`);
58
+ const [, key, op, raw] = m;
59
+ if (op === "=") {
60
+ out[key] = raw;
61
+ continue;
62
+ }
63
+ try {
64
+ out[key] = JSON.parse(raw);
65
+ }
66
+ catch (err) {
67
+ throw new UsageError(`--arg ${key}:= needs JSON: ${err.message}`);
68
+ }
69
+ }
70
+ return out;
71
+ }
72
+ /** The profile a session in `cwd` would use: --profile, else the folder's Claude Code profile, else the hub's. */
73
+ function callerProfile(given, env, cwd) {
74
+ if (given)
75
+ return given;
76
+ const config = loadConfig(env);
77
+ return resolveProfile(cwd, config, env).chosen || config.system || "default";
78
+ }
79
+ /** One line from an SDK transport error: the gateway's `{ "error": ... }` text when it sent one. */
80
+ function gatewayMessage(err) {
81
+ const e = err;
82
+ const message = e?.message ?? String(err);
83
+ const status = typeof e?.code === "number" && e.code >= 400 && e.code < 600 ? e.code : undefined;
84
+ const body = /Error POSTing to endpoint: (.*)$/s.exec(message)?.[1];
85
+ if (body) {
86
+ try {
87
+ const parsed = JSON.parse(body);
88
+ if (typeof parsed.error === "string")
89
+ return { ...(status ? { status } : {}), message: parsed.error };
90
+ if (parsed.error && typeof parsed.error.message === "string") {
91
+ return { ...(status ? { status } : {}), message: parsed.error.message };
92
+ }
93
+ }
94
+ catch {
95
+ /* not JSON */
96
+ }
97
+ return { ...(status ? { status } : {}), message: body.trim().split("\n")[0] };
98
+ }
99
+ return { ...(status ? { status } : {}), message: message.split("\n")[0] };
100
+ }
101
+ /** A content item as terminal text: text as it is, anything else as one bracketed line. */
102
+ export function contentText(c) {
103
+ switch (c.type) {
104
+ case "text":
105
+ return c.text ?? "";
106
+ case "image":
107
+ case "audio":
108
+ return `[${c.type} ${c.mimeType ?? "?"}, ${Math.floor(((c.data ?? "").length * 3) / 4)} bytes]`;
109
+ case "resource":
110
+ return c.resource?.text !== undefined
111
+ ? c.resource.text
112
+ : `[resource ${c.resource?.uri ?? "?"}${c.resource?.mimeType ? `, ${c.resource.mimeType}` : ""}]`;
113
+ case "resource_link":
114
+ return `[link ${c.uri ?? "?"}${c.name ? ` (${c.name})` : ""}]`;
115
+ default:
116
+ return `[${c.type}]`;
117
+ }
118
+ }
119
+ export async function call(args, io) {
120
+ const p = parseFlags(args, CALL_FLAGS, 2);
121
+ const [server, tool] = p.positionals;
122
+ if (!server)
123
+ return fail("usage: turno mcp call <server> [tool] [--args JSON] [--arg key=value ...] [--profile p] [--json]");
124
+ const pairs = p.values.arg ?? [];
125
+ const toolArgs = callArguments(str(p, "args"), pairs);
126
+ if (!tool && (str(p, "args") !== undefined || pairs.length))
127
+ fail("--args and --arg go with a tool: turno mcp call <server> <tool> ...");
128
+ const json = bool(p, "json");
129
+ const manifest = loadManifest(io.env);
130
+ const def = manifest.servers[server];
131
+ if (!def)
132
+ return fail(`unknown server '${server}' (turno mcp list shows them)`);
133
+ if (def.kind === "remote" && !def.proxy) {
134
+ throw new CliError(`${server} is a remote server that agents reach directly (no keychain: or env: header and no auth = "oauth"), so mcpd does not relay it; call it from the agent`);
135
+ }
136
+ const cwd = process.cwd();
137
+ const profile = callerProfile(str(p, "profile"), io.env, cwd);
138
+ if (!servesProfile(def, profile)) {
139
+ throw new CliError(`${server} is not served to profile ${profile} (profiles = ${JSON.stringify(def.profiles)} in mcp.toml); pick another with --profile`);
140
+ }
141
+ const { mcpdPort, readToken } = await import("../../mcpd/state.js");
142
+ const { profileToken } = await import("../../mcpd/tokens.js");
143
+ const master = readToken(io.env);
144
+ const down = () => new CliError("mcpd is not running (turno mcp daemon start)", Exit.gatewayDown);
145
+ if (!master)
146
+ throw down();
147
+ const port = mcpdPort(io.env);
148
+ const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
149
+ const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
150
+ const transport = new StreamableHTTPClientTransport(new URL(gatewayUrl(server, port)), {
151
+ requestInit: {
152
+ headers: {
153
+ Authorization: `Bearer ${profileToken(master, profile)}`,
154
+ "X-Turno-Profile": profile,
155
+ "X-Turno-Pid": String(process.pid),
156
+ // This folder, so its [[projects]] rules apply as they would to an agent here.
157
+ "X-Turno-Cwd-B64": Buffer.from(cwd, "utf8").toString("base64url"),
158
+ },
159
+ },
160
+ });
161
+ const client = new Client({ name: "turno-mcp-call", version: packageInfo().version }, { capabilities: {} });
162
+ const started = Date.now();
163
+ try {
164
+ try {
165
+ await client.connect(transport);
166
+ }
167
+ catch (err) {
168
+ const g = gatewayMessage(err);
169
+ if (g.status === undefined && /ECONNREFUSED|fetch failed|connect/i.test(g.message))
170
+ throw down();
171
+ throw new CliError(`mcpd refused the session for ${server} as profile ${profile}: ${g.message}`);
172
+ }
173
+ // A server the folder's set leaves out answers with no capabilities and says why.
174
+ if (client.getServerVersion()?.version === "hidden")
175
+ throw new CliError(client.getInstructions() ?? `${server} is hidden in this folder`);
176
+ if (!tool) {
177
+ const { tools } = await client.listTools();
178
+ const ms = Date.now() - started;
179
+ if (json) {
180
+ emit(io, p, CALL_JSON, {
181
+ server,
182
+ profile,
183
+ tool: null,
184
+ isError: null,
185
+ content: null,
186
+ structuredContent: null,
187
+ tools: tools.map((t) => ({ name: t.name, description: t.description ?? null })),
188
+ ms,
189
+ });
190
+ return 0;
191
+ }
192
+ const st = style(io);
193
+ if (!tools.length)
194
+ io.out(st.muted(`${server} has no tools for profile ${profile}`));
195
+ for (const t of tools)
196
+ io.out(st.wrap(`${st.bold(t.name)} `, st.muted((t.description ?? "").split("\n")[0] ?? "")));
197
+ if (io.isTty)
198
+ io.err(st.muted(`${tools.length} tools of ${server} as profile ${profile} in ${duration(ms)}; call one with: turno mcp call ${server} <tool> --arg key=value`));
199
+ return 0;
200
+ }
201
+ let result;
202
+ try {
203
+ result = await client.callTool({ name: tool, arguments: toolArgs });
204
+ }
205
+ catch (err) {
206
+ throw new CliError(`${server}/${tool}: ${gatewayMessage(err).message}`);
207
+ }
208
+ const ms = Date.now() - started;
209
+ const content = (Array.isArray(result.content) ? result.content : []);
210
+ const isError = result.isError === true;
211
+ if (json) {
212
+ emit(io, p, CALL_JSON, {
213
+ server,
214
+ profile,
215
+ tool,
216
+ isError,
217
+ content,
218
+ structuredContent: result.structuredContent ?? null,
219
+ tools: null,
220
+ ms,
221
+ });
222
+ return isError ? 1 : 0;
223
+ }
224
+ for (const c of content)
225
+ io.out(contentText(c));
226
+ if (!content.length && result.structuredContent !== undefined)
227
+ io.out(JSON.stringify(result.structuredContent, null, 2));
228
+ const st = style(io);
229
+ if (isError)
230
+ io.err(`turno: ${server}/${tool} returned an error (isError)`);
231
+ else if (io.isTty)
232
+ io.err(st.muted(`${server}/${tool} as profile ${profile} in ${duration(ms)}`));
233
+ return isError ? 1 : 0;
234
+ }
235
+ finally {
236
+ await transport.terminateSession().catch(() => { });
237
+ await client.close().catch(() => { });
238
+ }
239
+ }
240
+ //# sourceMappingURL=mcp-call.js.map
@@ -2,15 +2,40 @@ import { spawn } from "node:child_process";
2
2
  import { isValidProfileName } from "../../core/config.js";
3
3
  import { loadManifest, servesProfile, variantKey } from "../../core/manifest.js";
4
4
  import { NO_SECRET_STORE, keychainResolver, secretStore } from "../../core/secrets.js";
5
- import { DRY_RUN, JSON_FLAG, bool, parseFlags, printJson, str } from "../args.js";
5
+ import { DRY_RUN, JSON_FLAG, bool, parseFlags, str } from "../args.js";
6
6
  import { fail } from "../io.js";
7
+ import { emit, jsonOutput } from "../output.js";
8
+ /** `turno mcp login --json`. */
9
+ export const LOGIN_JSON = jsonOutput([
10
+ "server",
11
+ "variant",
12
+ "issuer",
13
+ "registration",
14
+ "scope",
15
+ "redirectUri",
16
+ "expiresAt",
17
+ "refreshToken",
18
+ "service",
19
+ "planned",
20
+ ]);
7
21
  /**
8
- * `turno mcp login` and `turno mcp logout` (ADR 0029): mcpd is the OAuth client of remote
22
+ * `turno mcp login` and `turno mcp logout`: mcpd is the OAuth client of remote
9
23
  * servers declared with `auth = "oauth"`, one login per server variant. Agents reach the server
10
24
  * through mcpd and never log in themselves.
11
25
  */
12
- export const LOGIN_FLAGS = { profile: { type: "string" }, scope: { type: "string" }, "no-browser": { type: "boolean" }, ...DRY_RUN, ...JSON_FLAG };
13
- export const LOGOUT_FLAGS = { profile: { type: "string" }, all: { type: "boolean" }, "no-revoke": { type: "boolean" }, ...DRY_RUN };
26
+ export const LOGIN_FLAGS = {
27
+ profile: { type: "string" },
28
+ scope: { type: "string" },
29
+ "no-browser": { type: "boolean" },
30
+ ...DRY_RUN,
31
+ ...JSON_FLAG,
32
+ };
33
+ export const LOGOUT_FLAGS = {
34
+ profile: { type: "string" },
35
+ all: { type: "boolean" },
36
+ "no-revoke": { type: "boolean" },
37
+ ...DRY_RUN,
38
+ };
14
39
  function oauthServer(env, name, verb) {
15
40
  if (!name)
16
41
  fail(`usage: turno mcp ${verb} <server> [--profile <p>]`);
@@ -89,7 +114,7 @@ export async function login(args, io, deps = {}) {
89
114
  },
90
115
  });
91
116
  if (json) {
92
- printJson(io, { server: server.name, variant, ...result });
117
+ emit(io, flags, LOGIN_JSON, { server: server.name, variant, ...result });
93
118
  return 0;
94
119
  }
95
120
  if (result.planned) {
@@ -155,7 +180,9 @@ async function tellMcpd(env, server, variants) {
155
180
  if (r === "down")
156
181
  return "mcpd is not running; it reads the secret store when it starts.";
157
182
  // An mcpd from before 0.2 has no /logout: it notices within a minute.
158
- return r.status === 200 ? "mcpd stopped using the old token." : "mcpd stops using the old token within a minute (now: turno mcp daemon restart).";
183
+ return r.status === 200
184
+ ? "mcpd stopped using the old token."
185
+ : "mcpd stops using the old token within a minute (now: turno mcp daemon restart).";
159
186
  }
160
187
  /** Variants whose login is needed: "default" when some served profile has no variant of its own. */
161
188
  export function loginVariants(server) {