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,13 +1,13 @@
1
1
  import { createHash, randomBytes } from "node:crypto";
2
2
  import { createServer } from "node:http";
3
3
  import { buildDiscoveryUrls, discoverOAuthProtectedResourceMetadata, exchangeAuthorization, extractWWWAuthenticateParams, isHttpsUrl, refreshAuthorization, registerClient, startAuthorization, } from "@modelcontextprotocol/sdk/client/auth.js";
4
- import { InvalidClientError, InvalidGrantError, UnauthorizedClientError } from "@modelcontextprotocol/sdk/server/auth/errors.js";
4
+ import { InvalidClientError, InvalidGrantError, UnauthorizedClientError, } from "@modelcontextprotocol/sdk/server/auth/errors.js";
5
5
  import { OAuthMetadataSchema, OpenIdProviderDiscoveryMetadataSchema, } from "@modelcontextprotocol/sdk/shared/auth.js";
6
6
  import { checkResourceAllowed, resourceUrlFromServerUrl } from "@modelcontextprotocol/sdk/shared/auth-utils.js";
7
7
  import { LATEST_PROTOCOL_VERSION } from "@modelcontextprotocol/sdk/types.js";
8
8
  import { packageInfo } from "../core/version.js";
9
9
  /**
10
- * mcpd as the OAuth client of remote MCP servers (ADR 0029), following the MCP authorization
10
+ * mcpd as the OAuth client of remote MCP servers, following the MCP authorization
11
11
  * specification (revision 2026-07-28): protected resource metadata (RFC 9728), authorization
12
12
  * server metadata (RFC 8414, OpenID Connect Discovery) with issuer validation, pre-registration,
13
13
  * Client ID Metadata Documents or Dynamic Client Registration (RFC 7591), PKCE with S256
@@ -48,7 +48,9 @@ export function parseRecord(raw) {
48
48
  return undefined;
49
49
  try {
50
50
  const r = JSON.parse(raw);
51
- return r && r.v === 1 && typeof r.issuer === "string" && r.client && typeof r.client.client_id === "string" ? r : undefined;
51
+ return r && r.v === 1 && typeof r.issuer === "string" && r.client && typeof r.client.client_id === "string"
52
+ ? r
53
+ : undefined;
52
54
  }
53
55
  catch {
54
56
  return undefined;
@@ -127,7 +129,10 @@ async function authorizationServerMetadata(issuer, fetchFn = fetch) {
127
129
  for (const { url, type } of buildDiscoveryUrls(issuer)) {
128
130
  let res;
129
131
  try {
130
- res = await fetchFn(url, { headers: { Accept: "application/json", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION }, redirect: "error" });
132
+ res = await fetchFn(url, {
133
+ headers: { Accept: "application/json", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION },
134
+ redirect: "error",
135
+ });
131
136
  }
132
137
  catch (err) {
133
138
  throw new OAuthFlowError(`cannot reach the authorization server at ${url.origin}: ${err.message}`);
@@ -150,7 +155,12 @@ async function authorizationServerMetadata(issuer, fetchFn = fetch) {
150
155
  }
151
156
  if (!m.response_types_supported.includes("code"))
152
157
  throw new OAuthFlowError(`the authorization server ${issuer} does not support the authorization code flow`);
153
- for (const [k, v] of Object.entries({ authorization_endpoint: m.authorization_endpoint, token_endpoint: m.token_endpoint, registration_endpoint: m.registration_endpoint, revocation_endpoint: revocationEndpoint(m) })) {
158
+ for (const [k, v] of Object.entries({
159
+ authorization_endpoint: m.authorization_endpoint,
160
+ token_endpoint: m.token_endpoint,
161
+ registration_endpoint: m.registration_endpoint,
162
+ revocation_endpoint: revocationEndpoint(m),
163
+ })) {
154
164
  if (typeof v === "string")
155
165
  requireSecure(v, k);
156
166
  }
@@ -164,12 +174,20 @@ async function probe(serverUrl, fetchFn) {
164
174
  try {
165
175
  res = await fetchFn(serverUrl, {
166
176
  method: "POST",
167
- headers: { "Content-Type": "application/json", Accept: "application/json, text/event-stream", "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION },
177
+ headers: {
178
+ "Content-Type": "application/json",
179
+ Accept: "application/json, text/event-stream",
180
+ "MCP-Protocol-Version": LATEST_PROTOCOL_VERSION,
181
+ },
168
182
  body: JSON.stringify({
169
183
  jsonrpc: "2.0",
170
184
  id: 1,
171
185
  method: "initialize",
172
- params: { protocolVersion: LATEST_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "turno-mcpd", version: packageInfo().version } },
186
+ params: {
187
+ protocolVersion: LATEST_PROTOCOL_VERSION,
188
+ capabilities: {},
189
+ clientInfo: { name: "turno-mcpd", version: packageInfo().version },
190
+ },
173
191
  }),
174
192
  redirect: "error",
175
193
  });
@@ -216,7 +234,13 @@ async function discover(server, fetchFn = fetch, challenge = false) {
216
234
  if (!issuer)
217
235
  throw new OAuthFlowError(`${server.name}: authorization_server ${wanted} is not one of ${listed.join(", ")}`);
218
236
  const metadata = await authorizationServerMetadata(issuer, fetchFn);
219
- return { resourceMetadata, resource: resourceMetadata.resource, issuer, metadata, ...(challengeScope ? { challengeScope } : {}) };
237
+ return {
238
+ resourceMetadata,
239
+ resource: resourceMetadata.resource,
240
+ issuer,
241
+ metadata,
242
+ ...(challengeScope ? { challengeScope } : {}),
243
+ };
220
244
  }
221
245
  /** Space-separated union, keeping the first order. */
222
246
  function unionScopes(...lists) {
@@ -242,14 +266,19 @@ function toStored(t, now) {
242
266
  token_type: t.token_type,
243
267
  ...(t.refresh_token ? { refresh_token: t.refresh_token } : {}),
244
268
  ...(t.scope ? { scope: t.scope } : {}),
245
- ...(typeof t.expires_in === "number" && Number.isFinite(t.expires_in) ? { expires_at: now + t.expires_in * 1000 } : {}),
269
+ ...(typeof t.expires_in === "number" && Number.isFinite(t.expires_in)
270
+ ? { expires_at: now + t.expires_in * 1000 }
271
+ : {}),
246
272
  };
247
273
  }
248
274
  /** The client information to present: pre-registered ones get their secret from mcp.toml at use time. */
249
275
  async function clientFor(rec, settings, resolve) {
250
276
  if (rec.registration !== "pre-registered")
251
277
  return rec.client;
252
- return { client_id: rec.client.client_id, ...(settings?.clientSecret ? { client_secret: await resolve(settings.clientSecret) } : {}) };
278
+ return {
279
+ client_id: rec.client.client_id,
280
+ ...(settings?.clientSecret ? { client_secret: await resolve(settings.clientSecret) } : {}),
281
+ };
253
282
  }
254
283
  /** A one-shot HTTP listener on 127.0.0.1 (RFC 8252 section 7.3, loopback IP literal). */
255
284
  async function callbackServer(port) {
@@ -309,7 +338,8 @@ function portOf(uris) {
309
338
  */
310
339
  export function checkIssuerParam(q, issuer, metadata) {
311
340
  const iss = q.get("iss");
312
- const advertised = metadata.authorization_response_iss_parameter_supported === true;
341
+ const advertised = metadata
342
+ .authorization_response_iss_parameter_supported === true;
313
343
  if (iss !== null) {
314
344
  if (iss !== issuer)
315
345
  throw new OAuthFlowError(`the authorization response came from issuer ${iss}, not ${issuer}; refusing it (RFC 9207)`);
@@ -375,7 +405,12 @@ export async function login(o) {
375
405
  }
376
406
  else {
377
407
  try {
378
- client = await registerClient(d.issuer, { metadata: d.metadata, clientMetadata: clientMetadata(cb.redirectUri, scope), ...(scope ? { scope } : {}), fetchFn });
408
+ client = await registerClient(d.issuer, {
409
+ metadata: d.metadata,
410
+ clientMetadata: clientMetadata(cb.redirectUri, scope),
411
+ ...(scope ? { scope } : {}),
412
+ fetchFn,
413
+ });
379
414
  }
380
415
  catch (err) {
381
416
  throw new OAuthFlowError(`dynamic client registration at ${d.issuer} failed: ${scrub(err.message, [])}`);
@@ -458,11 +493,21 @@ export async function revoke(server, rec, resolve, fetchFn = fetch) {
458
493
  if (!endpoint)
459
494
  return "the authorization server has no revocation endpoint";
460
495
  const client = await clientFor(rec, server.oauth, resolve);
461
- const body = new URLSearchParams({ token, token_type_hint: rec.tokens?.refresh_token ? "refresh_token" : "access_token", client_id: client.client_id });
496
+ const body = new URLSearchParams({
497
+ token,
498
+ token_type_hint: rec.tokens?.refresh_token ? "refresh_token" : "access_token",
499
+ client_id: client.client_id,
500
+ });
462
501
  const headers = { "Content-Type": "application/x-www-form-urlencoded" };
463
502
  if (client.client_secret)
464
503
  headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(client.client_id)}:${encodeURIComponent(client.client_secret)}`).toString("base64")}`;
465
- const res = await fetchFn(endpoint, { method: "POST", headers, body, redirect: "error", signal: AbortSignal.timeout(10_000) });
504
+ const res = await fetchFn(endpoint, {
505
+ method: "POST",
506
+ headers,
507
+ body,
508
+ redirect: "error",
509
+ signal: AbortSignal.timeout(10_000),
510
+ });
466
511
  await res.body?.cancel().catch(() => { });
467
512
  return res.ok ? undefined : `the revocation endpoint answered HTTP ${res.status}`;
468
513
  }
@@ -604,7 +649,10 @@ export class OAuthSession {
604
649
  return t !== undefined && (t.expires_at === undefined || t.expires_at - EXPIRY_SKEW_MS > this.now());
605
650
  }
606
651
  checkBinding(server, rec) {
607
- if (!checkResourceAllowed({ requestedResource: resourceUrlFromServerUrl(server.url), configuredResource: rec.resource })) {
652
+ if (!checkResourceAllowed({
653
+ requestedResource: resourceUrlFromServerUrl(server.url),
654
+ configuredResource: rec.resource,
655
+ })) {
608
656
  throw new LoginRequiredError(this.name, this.variant, `the login is for ${rec.resource}, and mcp.toml now says ${server.url}`);
609
657
  }
610
658
  const id = server.oauth?.clientId;
@@ -671,7 +719,9 @@ export class OAuthSession {
671
719
  });
672
720
  }
673
721
  catch (err) {
674
- if (err instanceof InvalidGrantError || err instanceof InvalidClientError || err instanceof UnauthorizedClientError) {
722
+ if (err instanceof InvalidGrantError ||
723
+ err instanceof InvalidClientError ||
724
+ err instanceof UnauthorizedClientError) {
675
725
  // A login in another process may have replaced the token we hold: read the store again once.
676
726
  const latest = retried ? undefined : await this.load(true);
677
727
  if (latest?.tokens?.refresh_token && latest.tokens.refresh_token !== refreshToken) {
@@ -786,6 +836,10 @@ export async function loginState(store, name, variant, now = Date.now()) {
786
836
  const expired = t.expires_at !== undefined && t.expires_at <= now;
787
837
  if (expired && !t.refresh_token)
788
838
  return { state: "login required" };
789
- return { state: expired ? "expired" : "logged in", ...(t.expires_at ? { expiresAt: t.expires_at } : {}), refresh: Boolean(t.refresh_token) };
839
+ return {
840
+ state: expired ? "expired" : "logged in",
841
+ ...(t.expires_at ? { expiresAt: t.expires_at } : {}),
842
+ refresh: Boolean(t.refresh_token),
843
+ };
790
844
  }
791
845
  //# sourceMappingURL=oauth.js.map
@@ -22,7 +22,13 @@ function procTcpRows(procRoot = "/proc") {
22
22
  const f = line.trim().split(/\s+/);
23
23
  if (f.length < 10)
24
24
  continue;
25
- rows.push({ localPort: hexPort(f[1]), remotePort: hexPort(f[2]), state: f[3] ?? "", uid: Number(f[7]), inode: f[9] ?? "" });
25
+ rows.push({
26
+ localPort: hexPort(f[1]),
27
+ remotePort: hexPort(f[2]),
28
+ state: f[3] ?? "",
29
+ uid: Number(f[7]),
30
+ inode: f[9] ?? "",
31
+ });
26
32
  }
27
33
  }
28
34
  return rows;
@@ -63,7 +69,10 @@ function pidOfInode(inode, procRoot = "/proc", skip) {
63
69
  }
64
70
  async function lsofPeer(remotePort, self, env) {
65
71
  try {
66
- const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], { timeout: 3000, env });
72
+ const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], {
73
+ timeout: 3000,
74
+ env,
75
+ });
67
76
  let pid;
68
77
  for (const line of stdout.split("\n")) {
69
78
  if (line.startsWith("p"))
@@ -115,7 +124,10 @@ export async function portOwner(port, opts = {}) {
115
124
  }
116
125
  }
117
126
  try {
118
- const { stdout } = await run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], { timeout: 3000, env: opts.env ?? process.env });
127
+ const { stdout } = await run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], {
128
+ timeout: 3000,
129
+ env: opts.env ?? process.env,
130
+ });
119
131
  const owner = {};
120
132
  for (const line of stdout.split("\n")) {
121
133
  if (line.startsWith("p") && owner.pid === undefined)
@@ -37,7 +37,10 @@ export function freeMemLevel(free, total) {
37
37
  return share < 0.05 ? "critical" : share < 0.1 ? "warn" : "normal";
38
38
  }
39
39
  async function realSysctl() {
40
- const { stdout } = await run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"], { encoding: "utf8", timeout: 2000 });
40
+ const { stdout } = await run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"], {
41
+ encoding: "utf8",
42
+ timeout: 2000,
43
+ });
41
44
  return stdout;
42
45
  }
43
46
  /**
package/dist/mcpd/rss.js CHANGED
@@ -3,14 +3,24 @@ import { readFileSync, readdirSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { atomicWrite } from "../core/journal.js";
6
+ import { hasFields, isRecord, readState } from "../core/state-file.js";
6
7
  const run = promisify(execFile);
7
- /** `ps -A -o pid=,ppid=,rss=` output (rss in KiB, as both macOS and procps print it). */
8
+ /**
9
+ * `ps -A -o pid=,ppid=,pgid=,rss=` output (rss in KiB, as both macOS and procps print it). The
10
+ * three column form without pgid is read too.
11
+ */
8
12
  export function parsePs(stdout) {
9
13
  const t = new Map();
10
14
  for (const line of stdout.split("\n")) {
11
- const [pid, ppid, rss] = line.trim().split(/\s+/).map(Number);
15
+ const cols = line.trim().split(/\s+/).map(Number);
16
+ const [pid, ppid] = cols;
17
+ const pgid = cols.length >= 4 ? cols[2] : undefined;
18
+ const rss = cols.length >= 4 ? cols[3] : cols[2];
12
19
  if (Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) && Number.isFinite(rss)) {
13
- t.set(pid, { ppid: ppid, rss: rss * 1024 });
20
+ const bytes = rss * 1024;
21
+ t.set(pid, Number.isInteger(pgid)
22
+ ? { ppid: ppid, pgid: pgid, rss: bytes }
23
+ : { ppid: ppid, rss: bytes });
14
24
  }
15
25
  }
16
26
  return t;
@@ -48,7 +58,7 @@ export function procfsTable(root = "/proc") {
48
58
  export async function processTable(opts = {}) {
49
59
  try {
50
60
  const env = opts.env ?? process.env;
51
- const { stdout } = await run("ps", ["-A", "-o", "pid=,ppid=,rss="], {
61
+ const { stdout } = await run("ps", ["-A", "-o", "pid=,ppid=,pgid=,rss="], {
52
62
  encoding: "utf8",
53
63
  timeout: 5000,
54
64
  maxBuffer: 16 * 1024 * 1024,
@@ -63,19 +73,29 @@ export async function processTable(opts = {}) {
63
73
  }
64
74
  return procfsTable(opts.procRoot);
65
75
  }
66
- /** RSS of a process and all its descendants (npx and shell wrappers start the real server as a child). */
76
+ /**
77
+ * RSS of a process and all its descendants (npx and shell wrappers start the real server as a
78
+ * child). A descendant that leads its own process group brings the whole group: a browser server
79
+ * starts Chrome as a group leader, and a Chrome helper whose parent went away stays in that
80
+ * group.
81
+ */
67
82
  export function treeRss(table, pid) {
68
83
  if (!table.has(pid))
69
84
  return undefined;
70
85
  const children = new Map();
71
- for (const [p, { ppid }] of table) {
72
- if (p === ppid)
73
- continue;
74
- const list = children.get(ppid);
86
+ const add = (key, p) => {
87
+ const list = children.get(key);
75
88
  if (list)
76
89
  list.push(p);
77
90
  else
78
- children.set(ppid, [p]);
91
+ children.set(key, [p]);
92
+ };
93
+ for (const [p, { ppid, pgid }] of table) {
94
+ if (p !== ppid)
95
+ add(ppid, p);
96
+ // Members of a group count under its leader too (the leader's own PID is its pgid).
97
+ if (pgid !== undefined && pgid !== p && pgid !== ppid && table.get(pgid)?.pgid === pgid)
98
+ add(pgid, p);
79
99
  }
80
100
  let total = 0;
81
101
  const seen = new Set();
@@ -103,15 +123,10 @@ export class RssSampler {
103
123
  constructor(file, opts = {}) {
104
124
  this.file = file;
105
125
  this.opts = opts;
106
- try {
107
- const v = JSON.parse(readFileSync(file, "utf8"));
108
- for (const [k, s] of Object.entries(v ?? {}))
109
- if (typeof s?.bytes === "number" && typeof s.at === "string")
110
- this.known[k] = s;
111
- }
112
- catch {
113
- /* first run */
114
- }
126
+ // None on the first run; entries of another shape are dropped.
127
+ for (const [k, s] of Object.entries(readState(file, isRecord) ?? {}))
128
+ if (hasFields(s, { bytes: "number", at: "string" }))
129
+ this.known[k] = s;
115
130
  }
116
131
  samples() {
117
132
  return { ...this.known };
@@ -6,7 +6,7 @@ import { paths, tildify } from "../core/paths.js";
6
6
  import { realOr } from "../core/fsutil.js";
7
7
  const exec = promisify(execFile);
8
8
  /**
9
- * How mcpd is kept alive across logins (ADR 0017): a LaunchAgent on macOS, a `systemd --user`
9
+ * How mcpd is kept alive across logins: a LaunchAgent on macOS, a `systemd --user`
10
10
  * unit on Linux, nothing elsewhere. Every backend writes one file (journaled, so `turno undo`
11
11
  * restores it) and drives the service manager through its command-line tool.
12
12
  */
@@ -29,7 +29,15 @@ export function serviceEnv(spec, kind) {
29
29
  PATH: spec.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
30
30
  HOME: paths(spec.env).home,
31
31
  };
32
- for (const k of ["XDG_CONFIG_HOME", "XDG_STATE_HOME", "XDG_DATA_HOME", "LANG", "TURNO_CONFIG_DIR", "TURNO_STATE_DIR", "TURNO_DATA_DIR"]) {
32
+ for (const k of [
33
+ "XDG_CONFIG_HOME",
34
+ "XDG_STATE_HOME",
35
+ "XDG_DATA_HOME",
36
+ "LANG",
37
+ "TURNO_CONFIG_DIR",
38
+ "TURNO_STATE_DIR",
39
+ "TURNO_DATA_DIR",
40
+ ]) {
33
41
  if (spec.env[k])
34
42
  vars[k] = spec.env[k];
35
43
  }
@@ -57,7 +65,19 @@ export async function runTool(tool, args, env, timeout = 10_000) {
57
65
  * Paths that change when a version manager or Homebrew switches versions. A service that
58
66
  * runs them breaks after `nvm uninstall`, `brew cleanup` and the like.
59
67
  */
60
- const UNSTABLE = [/\/\.nvm\/versions\//, /\/Cellar\//, /\/\.volta\/tools\/image\//, /\/fnm\/node-versions\//, /\/\.asdf\/installs\//, /\/mise\/installs\//, /\/_npx\//, /\/\.npm\/_npx\//, /\/n\/versions\//, /\/\.local\/share\/pnpm\/\.tools\//, /\/\.local\/share\/pnpm\/dlx-/];
68
+ const UNSTABLE = [
69
+ /\/\.nvm\/versions\//,
70
+ /\/Cellar\//,
71
+ /\/\.volta\/tools\/image\//,
72
+ /\/fnm\/node-versions\//,
73
+ /\/\.asdf\/installs\//,
74
+ /\/mise\/installs\//,
75
+ /\/_npx\//,
76
+ /\/\.npm\/_npx\//,
77
+ /\/n\/versions\//,
78
+ /\/\.local\/share\/pnpm\/\.tools\//,
79
+ /\/\.local\/share\/pnpm\/dlx-/,
80
+ ];
61
81
  export function isUnstablePath(p) {
62
82
  return UNSTABLE.some((re) => re.test(p));
63
83
  }
@@ -131,7 +151,11 @@ export async function serviceBackend(env, platform = process.platform) {
131
151
  }
132
152
  /** The backend whose file is installed, without asking the service manager. */
133
153
  export async function installedBackend(env, platform = process.platform) {
134
- const b = platform === "darwin" ? (await import("./launchd.js")).launchd : platform === "linux" ? (await import("./systemd.js")).systemd : undefined;
154
+ const b = platform === "darwin"
155
+ ? (await import("./launchd.js")).launchd
156
+ : platform === "linux"
157
+ ? (await import("./systemd.js")).systemd
158
+ : undefined;
135
159
  return b && existsSync(b.file(env)) ? b : undefined;
136
160
  }
137
161
  /** Write the service file through the journal and (unless dry) load it. */
@@ -0,0 +1,217 @@
1
+ /**
2
+ * `turno mcp export` and `turno mcp import <file>`: mcp.toml without secret values, and merging
3
+ * such a file (or another agent's MCP config) into mcp.toml. An exported file names each secret
4
+ * by its `keychain:` or `env:` reference; literal secrets become `keychain:turno/<server>/<key>`
5
+ * references that the importing machine fills with `turno secret set`.
6
+ */
7
+ import { parse, stringify } from "smol-toml";
8
+ import { parseManifest } from "../core/manifest.js";
9
+ import { argSecrets, isSecretValue, serviceKey, urlSecrets } from "./importer.js";
10
+ const isTable = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /**
12
+ * mcp.toml text without secret values. With `profile`, only the servers that profile gets and
13
+ * only its own variant. Comments are not kept (the file is generated).
14
+ */
15
+ export function exportManifest(text, opts = {}) {
16
+ const manifest = parseManifest(text); // refuse to export a file mcpd would refuse
17
+ const raw = parse(text);
18
+ const table = isTable(raw.server) ? raw.server : {};
19
+ const keychain = new Set();
20
+ const envVars = new Set();
21
+ const moved = [];
22
+ const redacted = [];
23
+ const out = {};
24
+ const refOf = (v) => {
25
+ if (v.startsWith("keychain:"))
26
+ keychain.add(v.slice("keychain:".length));
27
+ else if (v.startsWith("env:"))
28
+ envVars.add(v.slice(4).replace(/:-.*$/, ""));
29
+ };
30
+ /** env and headers: references stay, literal secrets become references. */
31
+ const values = (server, scope, map) => {
32
+ if (!isTable(map))
33
+ return undefined;
34
+ const next = {};
35
+ for (const [k, v] of Object.entries(map)) {
36
+ if (typeof v !== "string") {
37
+ next[k] = v;
38
+ continue;
39
+ }
40
+ if (v.startsWith("keychain:") || v.startsWith("env:")) {
41
+ refOf(v);
42
+ next[k] = v;
43
+ }
44
+ else if (!v.includes("${") && isSecretValue(k, v)) {
45
+ const service = `turno/${scope}/${serviceKey(k)}`;
46
+ keychain.add(service);
47
+ moved.push(`${server}.${k}`);
48
+ next[k] = `keychain:${service}`;
49
+ }
50
+ else
51
+ next[k] = v;
52
+ }
53
+ return next;
54
+ };
55
+ const scrub = (server, scope, t) => {
56
+ const next = { ...t };
57
+ for (const key of ["env", "headers"]) {
58
+ const v = values(server, scope, t[key]);
59
+ if (v)
60
+ next[key] = v;
61
+ }
62
+ if (Array.isArray(t.args)) {
63
+ const args = t.args.map(String);
64
+ const found = argSecrets(args);
65
+ if (found.length) {
66
+ next.args = args.map((a) => found.reduce((s, f) => s.split(f).join("<secret>"), a));
67
+ redacted.push(`${server}.args`);
68
+ }
69
+ }
70
+ if (typeof t.url === "string") {
71
+ const found = urlSecrets(t.url);
72
+ if (found.length) {
73
+ let url = t.url;
74
+ for (const f of found)
75
+ url = url.split(f).join("<secret>").split(encodeURIComponent(f)).join("<secret>");
76
+ next.url = url;
77
+ redacted.push(`${server}.url`);
78
+ }
79
+ }
80
+ if (isTable(t.oauth) && typeof t.oauth.client_secret === "string")
81
+ refOf(t.oauth.client_secret);
82
+ return next;
83
+ };
84
+ for (const [name, value] of Object.entries(table)) {
85
+ if (!isTable(value))
86
+ continue;
87
+ const def = manifest.servers[name];
88
+ if (opts.profile && !def.profiles.includes("*") && !def.profiles.includes(opts.profile))
89
+ continue;
90
+ const server = scrub(name, name, value);
91
+ if (isTable(value.variant)) {
92
+ const variants = {};
93
+ for (const [prof, v] of Object.entries(value.variant)) {
94
+ if (opts.profile && prof !== opts.profile)
95
+ continue;
96
+ if (isTable(v))
97
+ variants[prof] = scrub(`${name}.variant.${prof}`, `${name}/${prof}`, v);
98
+ }
99
+ if (Object.keys(variants).length)
100
+ server.variant = variants;
101
+ else
102
+ delete server.variant;
103
+ }
104
+ out[name] = server;
105
+ }
106
+ const names = Object.keys(out);
107
+ const head = [
108
+ `# turno MCP servers, from \`${opts.command ?? "turno mcp export"}\`. No secret values: each secret is`,
109
+ "# a keychain: or env: reference. Import it with: turno mcp import <this file> --write",
110
+ ];
111
+ if (keychain.size) {
112
+ head.push("#", "# Store these secrets on the machine that imports it (the value on stdin):");
113
+ for (const s of [...keychain].sort())
114
+ head.push(`# turno secret set ${s}`);
115
+ }
116
+ if (envVars.size)
117
+ head.push("#", `# Variables mcpd reads from its environment: ${[...envVars].sort().join(", ")}`);
118
+ if (redacted.length)
119
+ head.push("#", `# Secrets replaced by <secret> (args and URLs cannot hold a reference): ${redacted.join(", ")}`);
120
+ const body = names.length ? `${stringify({ server: out })}\n` : "";
121
+ const result = `${head.join("\n")}\n\n${body}`;
122
+ parseManifest(result, "export"); // never print something import would refuse
123
+ return {
124
+ text: result,
125
+ servers: names,
126
+ keychain: [...keychain].sort(),
127
+ envVars: [...envVars].sort(),
128
+ moved,
129
+ redacted,
130
+ };
131
+ }
132
+ /** The parts of a TOML table header: `server."a.b".env` is server, a.b, env. */
133
+ function headerPath(inner) {
134
+ const parts = [];
135
+ const re = /\s*(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([A-Za-z0-9_-]+))\s*(?:\.|$)/y;
136
+ re.lastIndex = 0;
137
+ while (re.lastIndex < inner.length) {
138
+ const m = re.exec(inner);
139
+ if (!m)
140
+ break;
141
+ parts.push(m[1] !== undefined ? JSON.parse(`"${m[1]}"`) : (m[2] ?? m[3]));
142
+ }
143
+ return parts;
144
+ }
145
+ const HEADER = /^\s*\[\[?\s*([^[\]#]+?)\s*\]\]?\s*(#.*)?$/;
146
+ /**
147
+ * Remove `[server.<name>]` and its sub-tables (`[server.<name>.env]`, variants, ...) from
148
+ * mcp.toml text, keeping the rest and its comments. Undefined when the server is defined some
149
+ * other way (an inline table, dotted keys under `[server]`) and the text has to be edited by hand.
150
+ */
151
+ export function removeServer(text, name) {
152
+ const lines = text.split("\n");
153
+ const keep = [];
154
+ let dropping = false;
155
+ for (const line of lines) {
156
+ const h = HEADER.exec(line);
157
+ if (h) {
158
+ const path = headerPath(h[1]);
159
+ dropping = path[0] === "server" && path[1] === name;
160
+ }
161
+ if (!dropping)
162
+ keep.push(line);
163
+ }
164
+ const next = keep.join("\n").replace(/\n{3,}/g, "\n\n");
165
+ try {
166
+ return parseManifest(next).servers[name] ? undefined : next;
167
+ }
168
+ catch {
169
+ return undefined;
170
+ }
171
+ }
172
+ /**
173
+ * Merge server tables into mcp.toml text: new names are appended, names already there are kept
174
+ * unless `force`, which replaces their tables. Throws when a server cannot be replaced in place.
175
+ */
176
+ export function mergeServers(existing, incoming, force) {
177
+ const current = existing.trim() ? parseManifest(existing).servers : {};
178
+ let text = existing;
179
+ const added = [];
180
+ const replaced = [];
181
+ const kept = [];
182
+ const append = {};
183
+ for (const [name, table] of Object.entries(incoming)) {
184
+ if (current[name]) {
185
+ if (!force) {
186
+ kept.push(name);
187
+ continue;
188
+ }
189
+ const next = removeServer(text, name);
190
+ if (next === undefined)
191
+ throw new Error(`cannot replace server ${name} in mcp.toml (it is not a [server.${name}] table); edit it by hand`);
192
+ text = next;
193
+ replaced.push(name);
194
+ }
195
+ else
196
+ added.push(name);
197
+ append[name] = table;
198
+ }
199
+ if (Object.keys(append).length) {
200
+ const trimmed = text.replace(/\s+$/, "");
201
+ text = `${trimmed}${trimmed ? "\n\n" : ""}${stringify({ server: append })}\n`;
202
+ }
203
+ parseManifest(text); // never write something mcpd cannot read back
204
+ return { text, added, replaced, kept };
205
+ }
206
+ /** The server tables of a file in mcp.toml's format (what `turno mcp export` prints). */
207
+ export function manifestServers(text, file) {
208
+ parseManifest(text, file);
209
+ const raw = parse(text);
210
+ const out = {};
211
+ if (isTable(raw.server))
212
+ for (const [n, v] of Object.entries(raw.server))
213
+ if (isTable(v))
214
+ out[n] = v;
215
+ return out;
216
+ }
217
+ //# sourceMappingURL=share.js.map