turno-cli 0.1.0 → 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 (105) hide show
  1. package/CHANGELOG.md +293 -0
  2. package/README.md +143 -75
  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/core/version.js +6 -0
  74. package/dist/demo/server.js +34 -0
  75. package/dist/mcpd/cache.js +18 -4
  76. package/dist/mcpd/calllog.js +253 -0
  77. package/dist/mcpd/client-names.js +51 -0
  78. package/dist/mcpd/connectors.js +148 -17
  79. package/dist/mcpd/daemon.js +452 -116
  80. package/dist/mcpd/folder-sets.js +39 -0
  81. package/dist/mcpd/gateway.js +441 -47
  82. package/dist/mcpd/health.js +269 -0
  83. package/dist/mcpd/importer.js +356 -36
  84. package/dist/mcpd/instances.js +425 -65
  85. package/dist/mcpd/jsonrpc.js +8 -0
  86. package/dist/mcpd/launchd.js +65 -48
  87. package/dist/mcpd/modern.js +648 -0
  88. package/dist/mcpd/oauth.js +791 -0
  89. package/dist/mcpd/peerpid.js +122 -6
  90. package/dist/mcpd/pressure.js +85 -0
  91. package/dist/mcpd/rss.js +151 -0
  92. package/dist/mcpd/service.js +167 -0
  93. package/dist/mcpd/state.js +183 -0
  94. package/dist/mcpd/sync.js +55 -80
  95. package/dist/mcpd/systemd.js +80 -0
  96. package/dist/mcpd/tokens.js +89 -0
  97. package/dist/mcpd/upstream.js +154 -44
  98. package/dist/statusline/cost.js +154 -44
  99. package/dist/statusline/input.js +66 -0
  100. package/dist/statusline/render.js +9 -3
  101. package/dist/ui/fonts.js +8 -3
  102. package/dist/ui/settings.js +27 -15
  103. package/npm-shrinkwrap.json +1093 -0
  104. package/package.json +9 -9
  105. package/dist/cli/commands/available.js +0 -18
@@ -1,39 +1,234 @@
1
- import { execFile } from "node:child_process";
2
- import { promisify } from "node:util";
3
- const run = promisify(execFile);
1
+ import { spawn } from "node:child_process";
2
+ import { findOnPath } from "./paths.js";
4
3
  export class SecretError extends Error {
5
4
  constructor(ref, why) {
6
- super(`cannot resolve ${ref}: ${why}`);
5
+ super(ref ? `cannot resolve ${ref}: ${why}` : why);
7
6
  this.name = "SecretError";
8
7
  }
9
8
  }
10
- export function keychainResolver(env = process.env) {
9
+ /** The one-line error when the machine has neither the Keychain nor libsecret. */
10
+ export const NO_SECRET_STORE = "no secret store found: turno uses the macOS Keychain (security) or libsecret (secret-tool, package libsecret-tools); install one, or use env:NAME references in mcp.toml";
11
+ /** Run a command with optional stdin; never rejects (a missing binary is code 127). */
12
+ function exec(cmd, args, env, input, timeout = 10_000) {
13
+ return new Promise((resolve) => {
14
+ let child;
15
+ try {
16
+ child = spawn(cmd, args, { env, stdio: ["pipe", "pipe", "pipe"], timeout });
17
+ }
18
+ catch (err) {
19
+ resolve({ code: 127, stdout: "", stderr: err.message });
20
+ return;
21
+ }
22
+ const out = [];
23
+ const err = [];
24
+ child.stdout.on("data", (c) => out.push(c));
25
+ child.stderr.on("data", (c) => err.push(c));
26
+ let done = false;
27
+ const finish = (r) => {
28
+ if (done)
29
+ return;
30
+ done = true;
31
+ resolve(r);
32
+ };
33
+ child.on("error", (e) => finish({ code: e.code === "ENOENT" ? 127 : 1, stdout: "", stderr: e.message }));
34
+ child.on("close", (code) => finish({ code: code ?? 1, stdout: Buffer.concat(out).toString("utf8"), stderr: Buffer.concat(err).toString("utf8") }));
35
+ child.stdin.on("error", () => {
36
+ /* the process exited before reading; its exit code tells */
37
+ });
38
+ child.stdin.end(input ?? "");
39
+ });
40
+ }
41
+ function firstLine(text) {
42
+ return text.trim().split("\n")[0] ?? "";
43
+ }
44
+ /** Service names travel as arguments and in `security -i` lines: keep them to one plain line. */
45
+ function checkService(service) {
46
+ if (!service || /[\0\r\n]/.test(service))
47
+ throw new SecretError("", `invalid secret name ${JSON.stringify(service)}`);
48
+ }
49
+ /** Quote one word for a `security -i` command line (double quotes, backslash escapes). */
50
+ export function securityQuote(word) {
51
+ return `"${word.replace(/[\\"]/g, (c) => `\\${c}`)}"`;
52
+ }
53
+ /** The line `security -i` reads on stdin to store an item; exported for tests. */
54
+ export function keychainAddLine(service, value, account = "turno") {
55
+ if (/[\0\r\n]/.test(value))
56
+ throw new SecretError("", "the value has a line break or NUL byte; the Keychain store reads one line");
57
+ return `add-generic-password -U -a ${securityQuote(account)} -s ${securityQuote(service)} -w ${securityQuote(value)} -T /usr/bin/security\n`;
58
+ }
59
+ /** Exit code of `security` when the item does not exist (errSecItemNotFound). */
60
+ const KEYCHAIN_NOT_FOUND = 44;
61
+ function keychainStore(bin, env) {
62
+ return {
63
+ kind: "keychain",
64
+ label: "Keychain",
65
+ async get(service) {
66
+ checkService(service);
67
+ const r = await exec(bin, ["find-generic-password", "-s", service, "-w"], env);
68
+ if (r.code === 0)
69
+ return r.stdout.replace(/\n$/, "");
70
+ if (r.code === KEYCHAIN_NOT_FOUND)
71
+ return undefined;
72
+ throw new SecretError(`keychain:${service}`, firstLine(r.stderr) || `security exited with ${r.code}`);
73
+ },
74
+ async has(service) {
75
+ checkService(service);
76
+ // Without -w this reads the item's attributes, never its value.
77
+ return (await exec(bin, ["find-generic-password", "-s", service], env)).code === 0;
78
+ },
79
+ async set(service, value) {
80
+ checkService(service);
81
+ // `security -i` reads commands from stdin, so the value never shows in `ps`. The output is
82
+ // not echoed back: an error line could quote the command.
83
+ const r = await exec(bin, ["-i"], env, keychainAddLine(service, value), 60_000);
84
+ if (r.code !== 0)
85
+ throw new SecretError("", `the Keychain did not store ${service} (security exited with ${r.code})`);
86
+ },
87
+ async remove(service) {
88
+ checkService(service);
89
+ const r = await exec(bin, ["delete-generic-password", "-s", service], env);
90
+ if (r.code === 0)
91
+ return true;
92
+ if (r.code === KEYCHAIN_NOT_FOUND)
93
+ return false;
94
+ throw new SecretError("", `the Keychain did not delete ${service}: ${firstLine(r.stderr) || `exit ${r.code}`}`);
95
+ },
96
+ };
97
+ }
98
+ /** libsecret attributes of an item: service=turno, account=<name>. */
99
+ function attrs(service) {
100
+ return ["service", "turno", "account", service];
101
+ }
102
+ function libsecretStore(bin, env) {
103
+ const lookup = (service) => exec(bin, ["lookup", ...attrs(service)], env);
104
+ return {
105
+ kind: "libsecret",
106
+ label: "Secret Service",
107
+ async get(service) {
108
+ checkService(service);
109
+ const r = await lookup(service);
110
+ if (r.code === 0)
111
+ return r.stdout.replace(/\n$/, "");
112
+ if (!r.stderr.trim())
113
+ return undefined; // not found: exit 1, nothing on stderr
114
+ throw new SecretError(`keychain:${service}`, firstLine(r.stderr));
115
+ },
116
+ async has(service) {
117
+ checkService(service);
118
+ return (await lookup(service)).code === 0;
119
+ },
120
+ async set(service, value) {
121
+ checkService(service);
122
+ // secret-tool reads the value from stdin when stdin is not a terminal.
123
+ const r = await exec(bin, ["store", `--label=turno: ${service}`, ...attrs(service)], env, value, 60_000);
124
+ if (r.code !== 0)
125
+ throw new SecretError("", `secret-tool did not store ${service}: ${firstLine(r.stderr) || `exit ${r.code}`}`);
126
+ },
127
+ async remove(service) {
128
+ checkService(service);
129
+ if (!(await this.has(service)))
130
+ return false;
131
+ const r = await exec(bin, ["clear", ...attrs(service)], env);
132
+ if (r.code !== 0)
133
+ throw new SecretError("", `secret-tool did not delete ${service}: ${firstLine(r.stderr) || `exit ${r.code}`}`);
134
+ return true;
135
+ },
136
+ };
137
+ }
138
+ /**
139
+ * The secret store of this machine: `security` on macOS, `secret-tool` elsewhere, found on the
140
+ * PATH of `env`. Undefined when there is none (the caller prints NO_SECRET_STORE).
141
+ */
142
+ export function secretStore(env, platform = process.platform) {
143
+ if (platform === "darwin") {
144
+ const bin = findOnPath("security", env);
145
+ return bin ? keychainStore(bin, env) : undefined;
146
+ }
147
+ const bin = findOnPath("secret-tool", env);
148
+ return bin ? libsecretStore(bin, env) : undefined;
149
+ }
150
+ /** The store, or a SecretError with the one-line hint. */
151
+ export function requireSecretStore(env, platform = process.platform) {
152
+ const store = secretStore(env, platform);
153
+ if (!store)
154
+ throw new SecretError("", NO_SECRET_STORE);
155
+ return store;
156
+ }
157
+ /** `${VAR}`, `${VAR:-default}` and Cursor's `${env:VAR}` anywhere inside a string. */
158
+ const VAR_REF = /\$\{(env:)?([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g;
159
+ /** Cursor's own placeholders: not environment variables, so they stay as written. */
160
+ const EDITOR_PLACEHOLDERS = new Set(["userHome", "workspaceFolder", "workspaceFolderBasename", "pathSeparator"]);
161
+ /**
162
+ * Expand `${VAR}`, `${VAR:-default}` and `${env:VAR}` inside a string from `env`, the way Claude
163
+ * Code expands them in its own MCP config. A variable that is unset and has no default is an
164
+ * error (SecretError), never an empty string. Anything else (`${workspaceFolder}`, a lone `$`)
165
+ * stays as written.
166
+ */
167
+ export function expandVars(value, env) {
168
+ if (!value.includes("${"))
169
+ return value;
170
+ return value.replace(VAR_REF, (whole, prefix, name, fallback) => {
171
+ if (!prefix && EDITOR_PLACEHOLDERS.has(name))
172
+ return whole;
173
+ const v = env[name];
174
+ if (fallback !== undefined && !v)
175
+ return fallback;
176
+ if (v === undefined)
177
+ throw new SecretError(whole, `environment variable ${name} is not set`);
178
+ return v;
179
+ });
180
+ }
181
+ /**
182
+ * The variables a value reads from `env` that are unset there and have no default: `env:NAME`
183
+ * as the whole value (with `whole`, as mcpd resolves env values and headers) and `${NAME}`
184
+ * inside it. Names only; a value is never returned.
185
+ */
186
+ export function unsetVars(value, env, whole = true) {
187
+ if (whole && value.startsWith("env:")) {
188
+ const [name, fallback] = value.slice(4).split(/:-(.*)/s, 2);
189
+ return fallback === undefined && env[name] === undefined ? [name] : [];
190
+ }
191
+ if (whole && value.startsWith("keychain:"))
192
+ return [];
193
+ const out = [];
194
+ for (const [, prefix, name, fallback] of value.matchAll(VAR_REF)) {
195
+ if (!prefix && EDITOR_PLACEHOLDERS.has(name))
196
+ continue;
197
+ if (fallback === undefined && env[name] === undefined && !out.includes(name))
198
+ out.push(name);
199
+ }
200
+ return out;
201
+ }
202
+ /**
203
+ * Resolves whole-value references (`keychain:<name>`, `env:NAME`) and expands `${VAR}` inside any
204
+ * other value. mcpd uses it for stdio env values and remote headers.
205
+ */
206
+ export function keychainResolver(env, platform = process.platform) {
11
207
  return async (value) => {
12
208
  if (value.startsWith("env:")) {
13
- const name = value.slice(4);
14
- const v = env[name];
209
+ // env:NAME, or env:NAME:-default (what `turno mcp import` writes for ${NAME:-default}).
210
+ const [name, fallback] = value.slice(4).split(/:-(.*)/s, 2);
211
+ const v = fallback !== undefined && !env[name] ? fallback : env[name];
15
212
  if (v === undefined)
16
213
  throw new SecretError(value, `environment variable ${name} is not set`);
17
214
  return v;
18
215
  }
19
216
  if (value.startsWith("keychain:")) {
20
217
  const service = value.slice("keychain:".length);
21
- try {
22
- const { stdout } = await run("security", ["find-generic-password", "-s", service, "-w"], { timeout: 10_000 });
23
- return stdout.replace(/\n$/, "");
24
- }
25
- catch {
26
- throw new SecretError(value, `no Keychain item with service "${service}" (turno secret set ${service})`);
27
- }
218
+ const store = secretStore(env, platform);
219
+ if (!store)
220
+ throw new SecretError(value, NO_SECRET_STORE);
221
+ const v = await store.get(service);
222
+ if (v === undefined)
223
+ throw new SecretError(value, `no ${store.label} item "${service}" (turno secret set ${service})`);
224
+ return v;
28
225
  }
29
- return value;
226
+ return expandVars(value, env);
30
227
  };
31
228
  }
32
- /** Store a secret in the login Keychain, readable by /usr/bin/security without a dialog. */
33
- export async function storeKeychainSecret(service, secret, account = "turno") {
34
- await run("security", ["add-generic-password", "-U", "-a", account, "-s", service, "-w", secret, "-T", "/usr/bin/security"], {
35
- timeout: 10_000,
36
- });
229
+ /** Store a secret in this machine's store (Keychain or Secret Service), keeping it out of argv. */
230
+ export async function storeKeychainSecret(service, secret, env) {
231
+ await requireSecretStore(env).set(service, secret);
37
232
  }
38
233
  export async function resolveRecord(record, resolve) {
39
234
  const out = {};
@@ -2,17 +2,10 @@ import { lstatSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs"
2
2
  import { join } from "node:path";
3
3
  import { isValidProfileName, loadConfig } from "./config.js";
4
4
  import { paths, profileDir } from "./paths.js";
5
- /** Whether a process is alive. EPERM means it exists but belongs to someone else. */
6
- export function pidAlive(pid) {
7
- if (!Number.isInteger(pid) || pid <= 0)
8
- return false;
9
- try {
10
- process.kill(pid, 0);
11
- return true;
12
- }
13
- catch (err) {
14
- return err.code === "EPERM";
15
- }
5
+ import { pidAlive } from "./fsutil.js";
6
+ /** Whether a recorded PID is a live process: process groups (0, negative) never count. */
7
+ function liveProcess(pid) {
8
+ return Number.isInteger(pid) && pid > 0 && pidAlive(pid);
16
9
  }
17
10
  const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
18
11
  /**
@@ -33,7 +26,7 @@ export function parseProcStart(text) {
33
26
  * The profile in a launcher's run record, when the record belongs to this process: its mtime
34
27
  * must be within 120 s of the process start, so a recycled PID never inherits an old record.
35
28
  */
36
- export function recordProfile(pid, procStart, env = process.env) {
29
+ function recordProfile(pid, procStart, env) {
37
30
  const start = parseProcStart(procStart ?? "");
38
31
  if (!start)
39
32
  return undefined;
@@ -56,7 +49,7 @@ export function recordProfile(pid, procStart, env = process.env) {
56
49
  return undefined;
57
50
  }
58
51
  /** Remove run records of processes that have ended. */
59
- export function pruneRunRecords(env = process.env) {
52
+ function pruneRunRecords(env) {
60
53
  const dir = paths(env).runDir;
61
54
  let entries;
62
55
  try {
@@ -66,7 +59,7 @@ export function pruneRunRecords(env = process.env) {
66
59
  return;
67
60
  }
68
61
  for (const entry of entries) {
69
- if (/^\d+$/.test(entry) && pidAlive(Number(entry)))
62
+ if (/^\d+$/.test(entry) && liveProcess(Number(entry)))
70
63
  continue;
71
64
  rmSync(join(dir, entry), { force: true, recursive: true });
72
65
  }
@@ -98,12 +91,12 @@ function readSessionFiles(dir) {
98
91
  return out;
99
92
  }
100
93
  /** Live sessions in the hub, each attributed to a profile. Also prunes dead run records. */
101
- export function liveSessions(env = process.env, config) {
94
+ export function liveSessions(env, config) {
102
95
  const cfg = config ?? loadConfig(env);
103
96
  const sessions = [];
104
97
  for (const s of readSessionFiles(join(paths(env).hub, "sessions"))) {
105
98
  const pid = typeof s.pid === "number" ? s.pid : Number.parseInt(text(s.pid), 10);
106
- if (!pidAlive(pid))
99
+ if (!liveProcess(pid))
107
100
  continue;
108
101
  const entrypoint = text(s.entrypoint);
109
102
  const procStart = text(s.procStart) || undefined;
@@ -135,7 +128,7 @@ export function displayName(s) {
135
128
  return s.name || s.sessionId.slice(0, 8);
136
129
  }
137
130
  /** Profiles with at least one live session. */
138
- export function busyProfiles(env = process.env, config) {
131
+ export function busyProfiles(env, config) {
139
132
  const out = new Set();
140
133
  for (const s of liveSessions(env, config))
141
134
  if (s.profile)
@@ -146,7 +139,7 @@ export function busyProfiles(env = process.env, config) {
146
139
  * Whether a profile has a live session. Besides the hub, a profile whose `sessions` folder
147
140
  * is still its own copy (not yet linked to the hub) is busy when a session in it is alive.
148
141
  */
149
- export function profileBusy(name, env = process.env, config) {
142
+ export function profileBusy(name, env, config) {
150
143
  if (busyProfiles(env, config).has(name))
151
144
  return true;
152
145
  const own = join(profileDir(name, env), "sessions");
@@ -159,12 +152,12 @@ export function profileBusy(name, env = process.env, config) {
159
152
  }
160
153
  for (const s of readSessionFiles(own)) {
161
154
  const pid = typeof s.pid === "number" ? s.pid : Number.parseInt(text(s.pid), 10);
162
- if (pidAlive(pid))
155
+ if (liveProcess(pid))
163
156
  return true;
164
157
  }
165
158
  // Session files are named <pid>.json; trust the name when the content is unreadable.
166
159
  try {
167
- return readdirSync(own).some((f) => /^\d+\.json$/.test(f) && pidAlive(Number(f.slice(0, -5))));
160
+ return readdirSync(own).some((f) => /^\d+\.json$/.test(f) && liveProcess(Number(f.slice(0, -5))));
168
161
  }
169
162
  catch {
170
163
  return false;
@@ -1,13 +1,18 @@
1
1
  import { spawn } from "node:child_process";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import { dirname, join } from "node:path";
4
- import { paths } from "./paths.js";
2
+ import { readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { paths, writePrivateFile } from "./paths.js";
5
5
  import { compareVersions, packageInfo } from "./version.js";
6
6
  const DAY = 24 * 3600 * 1000;
7
+ /** Strict semver 2.0.0 (no leading v, no ranges, no URLs): what may follow `turno-cli@`. */
8
+ const SEMVER = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/;
9
+ export function isSemver(v) {
10
+ return typeof v === "string" && v.length <= 256 && SEMVER.test(v);
11
+ }
7
12
  function file(env) {
8
13
  return join(paths(env).state, "update.json");
9
14
  }
10
- export function readUpdateState(env) {
15
+ function readUpdateState(env) {
11
16
  try {
12
17
  return JSON.parse(readFileSync(file(env), "utf8"));
13
18
  }
@@ -16,8 +21,7 @@ export function readUpdateState(env) {
16
21
  }
17
22
  }
18
23
  function writeUpdateState(env, s) {
19
- mkdirSync(dirname(file(env)), { recursive: true });
20
- writeFileSync(file(env), `${JSON.stringify(s)}\n`);
24
+ writePrivateFile(file(env), `${JSON.stringify(s)}\n`, env);
21
25
  }
22
26
  const truthy = (v) => v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
23
27
  /** Why the environment turns update checks off: TURNO_NO_UPDATE_CHECK, NO_UPDATE_NOTIFIER, DO_NOT_TRACK, CI. */
@@ -59,8 +63,14 @@ export async function fetchLatest(env, channel = "latest", doFetch = fetch) {
59
63
  });
60
64
  if (!res.ok)
61
65
  state.error = `registry answered HTTP ${res.status}`;
62
- else
63
- state.latest = String((await res.json()).version ?? "");
66
+ else {
67
+ // The answer becomes part of an install command: accept a plain version only.
68
+ const v = (await res.json()).version;
69
+ if (isSemver(v))
70
+ state.latest = v;
71
+ else
72
+ state.error = "the registry answered with an invalid version";
73
+ }
64
74
  }
65
75
  catch (err) {
66
76
  state.error = err.message;
@@ -21,6 +21,9 @@ export function detectInstall(root = packageInfo().root) {
21
21
  /* keep it */
22
22
  }
23
23
  const parts = real.split(sep);
24
+ // Homebrew keeps the npm package under Cellar/<formula>/<version>/libexec: brew owns it.
25
+ if (parts.includes("Cellar") && parts.includes("node_modules"))
26
+ return { method: "brew", root: real };
24
27
  if (parts.includes("node_modules")) {
25
28
  const method = real.includes(`${sep}.volta${sep}`)
26
29
  ? "volta"
@@ -53,6 +56,9 @@ export function upgradeCommand(install, name, spec) {
53
56
  return [["bun", "add", "--global", target]];
54
57
  case "volta":
55
58
  return [["volta", "install", target]];
59
+ case "brew":
60
+ // The formula follows the newest release; brew cannot install an arbitrary version.
61
+ return [["brew", "update"], ["brew", "upgrade", "turno"]];
56
62
  case "source":
57
63
  return [
58
64
  ["git", "-C", install.repo, "pull", "--ff-only"],
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The MCP server `turno demo` puts behind its gateway: a few harmless tools, no network, no
3
+ * files. `node server.js <name>` serves as <name>; DEMO_ACCOUNT (set by a profile variant in the
4
+ * demo's mcp.toml) shows which account's process answered.
5
+ */
6
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
+ const name = process.argv[2] ?? "demo";
10
+ const account = process.env.DEMO_ACCOUNT ?? "shared";
11
+ const startedAt = new Date().toISOString();
12
+ let calls = 0;
13
+ const tools = [
14
+ { name: "whoami", description: `Which ${name} process answered: account, pid, start time and calls served`, inputSchema: { type: "object", properties: {} } },
15
+ { name: "echo", description: "Return the text it is given", inputSchema: { type: "object", properties: { text: { type: "string" } } } },
16
+ ];
17
+ const server = new Server({ name: `turno-demo-${name}`, version: "1.0.0" }, { capabilities: { tools: {} }, instructions: `A demo server of turno (${name}).` });
18
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
19
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
20
+ calls++;
21
+ const text = (t) => ({ content: [{ type: "text", text: t }] });
22
+ switch (req.params.name) {
23
+ case "whoami":
24
+ return text(JSON.stringify({ server: name, account, pid: process.pid, startedAt, calls }));
25
+ case "echo":
26
+ return text(String(req.params.arguments?.text ?? ""));
27
+ default:
28
+ return { ...text(`unknown tool ${req.params.name}`), isError: true };
29
+ }
30
+ });
31
+ await server.connect(new StdioServerTransport());
32
+ // Exit when the gateway closes the pipe, so no demo process outlives the demo.
33
+ process.stdin.on("end", () => process.exit(0));
34
+ //# sourceMappingURL=server.js.map
@@ -1,5 +1,6 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
3
+ import { PRIVATE_DIR_MODE, PRIVATE_FILE_MODE } from "../core/paths.js";
3
4
  import { join } from "node:path";
4
5
  export function fingerprint(parts) {
5
6
  return createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 16);
@@ -14,6 +15,11 @@ export class DescriptionCache {
14
15
  return join(this.dir, `${key.replace(/[^A-Za-z0-9_.@-]/g, "_")}.json`);
15
16
  }
16
17
  get(key, fp) {
18
+ const d = this.peek(key);
19
+ return d && d.fingerprint === fp ? d : undefined;
20
+ }
21
+ /** The stored description whatever its fingerprint (to compare with a fresh one). */
22
+ peek(key) {
17
23
  let d = this.memory.get(key);
18
24
  if (!d) {
19
25
  try {
@@ -24,18 +30,26 @@ export class DescriptionCache {
24
30
  return undefined;
25
31
  }
26
32
  }
27
- return d.fingerprint === fp ? d : undefined;
33
+ return d;
28
34
  }
29
35
  set(key, d) {
30
36
  this.memory.set(key, d);
31
- mkdirSync(this.dir, { recursive: true });
37
+ // Under mcpd's data root, which already exists 0700: only the cache folders are created here.
38
+ mkdirSync(this.dir, { recursive: true, mode: PRIVATE_DIR_MODE });
32
39
  const file = this.file(key);
33
40
  const tmp = `${file}.${process.pid}.tmp`;
34
- writeFileSync(tmp, JSON.stringify(d, null, 2));
41
+ writeFileSync(tmp, JSON.stringify(d, null, 2), { mode: PRIVATE_FILE_MODE });
35
42
  renameSync(tmp, file);
36
43
  }
37
44
  delete(key) {
38
45
  this.memory.delete(key);
39
46
  }
47
+ /** Drop a description from memory and disk, so the next client relearns it. */
48
+ forget(key) {
49
+ const had = this.peek(key) !== undefined;
50
+ this.memory.delete(key);
51
+ rmSync(this.file(key), { force: true });
52
+ return had;
53
+ }
40
54
  }
41
55
  //# sourceMappingURL=cache.js.map