turno-cli 0.1.1 → 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 (121) hide show
  1. package/CHANGELOG.md +432 -0
  2. package/README.md +228 -73
  3. package/dist/accounts/audit.js +154 -12
  4. package/dist/accounts/builtin.js +100 -25
  5. package/dist/accounts/delegate.js +199 -35
  6. package/dist/accounts/policy.js +79 -0
  7. package/dist/accounts/registry.js +39 -21
  8. package/dist/agents/adapter.js +29 -0
  9. package/dist/agents/claude.js +246 -0
  10. package/dist/agents/codex.js +186 -0
  11. package/dist/agents/copilot.js +56 -0
  12. package/dist/agents/cursor.js +58 -0
  13. package/dist/agents/index.js +26 -86
  14. package/dist/agents/snippets.js +43 -13
  15. package/dist/cli/args.js +38 -6
  16. package/dist/cli/commands/accounts.js +119 -52
  17. package/dist/cli/commands/auto.js +121 -33
  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 +319 -138
  22. package/dist/cli/commands/complete.js +14 -3
  23. package/dist/cli/commands/completion.js +8 -2
  24. package/dist/cli/commands/config.js +186 -24
  25. package/dist/cli/commands/demo.js +321 -0
  26. package/dist/cli/commands/doctor.js +525 -123
  27. package/dist/cli/commands/handoff.js +33 -22
  28. package/dist/cli/commands/identity.js +192 -54
  29. package/dist/cli/commands/init.js +648 -0
  30. package/dist/cli/commands/limit.js +84 -16
  31. package/dist/cli/commands/mcp-call.js +240 -0
  32. package/dist/cli/commands/mcp-oauth.js +221 -0
  33. package/dist/cli/commands/mcp-observe.js +539 -0
  34. package/dist/cli/commands/mcp-share.js +201 -0
  35. package/dist/cli/commands/mcp.js +816 -187
  36. package/dist/cli/commands/mcpd.js +388 -76
  37. package/dist/cli/commands/migrate.js +6 -4
  38. package/dist/cli/commands/open.js +115 -27
  39. package/dist/cli/commands/profile.js +396 -78
  40. package/dist/cli/commands/resolve.js +14 -3
  41. package/dist/cli/commands/run.js +36 -6
  42. package/dist/cli/commands/secret.js +80 -76
  43. package/dist/cli/commands/session.js +17 -6
  44. package/dist/cli/commands/sessions.js +48 -12
  45. package/dist/cli/commands/setup.js +214 -164
  46. package/dist/cli/commands/status.js +227 -44
  47. package/dist/cli/commands/statusline.js +311 -114
  48. package/dist/cli/commands/ui.js +78 -68
  49. package/dist/cli/commands/undo.js +193 -18
  50. package/dist/cli/commands/uninstall.js +481 -0
  51. package/dist/cli/commands/upgrade.js +172 -79
  52. package/dist/cli/commands/usage.js +125 -51
  53. package/dist/cli/commands/version.js +21 -7
  54. package/dist/cli/commands/which.js +9 -24
  55. package/dist/cli/compile-cache.js +32 -0
  56. package/dist/cli/diagnostics.js +184 -0
  57. package/dist/cli/exit.js +65 -0
  58. package/dist/cli/group.js +24 -12
  59. package/dist/cli/help.js +62 -0
  60. package/dist/cli/highlight.js +236 -0
  61. package/dist/cli/hints.js +30 -0
  62. package/dist/cli/io.js +186 -1
  63. package/dist/cli/launch.js +52 -39
  64. package/dist/cli/launchers.js +161 -95
  65. package/dist/cli/main.js +201 -31
  66. package/dist/cli/optional.js +144 -0
  67. package/dist/cli/output.js +123 -0
  68. package/dist/cli/picker.js +459 -0
  69. package/dist/cli/registry.js +61 -6
  70. package/dist/cli/safe.js +87 -0
  71. package/dist/cli/secret-input.js +63 -0
  72. package/dist/cli/security.js +561 -0
  73. package/dist/cli/style.js +311 -0
  74. package/dist/cli/topics.js +142 -0
  75. package/dist/core/config.js +181 -23
  76. package/dist/core/exhausted.js +6 -8
  77. package/dist/core/fsutil.js +39 -0
  78. package/dist/core/journal.js +294 -16
  79. package/dist/core/manifest.js +153 -6
  80. package/dist/core/paths.js +14 -13
  81. package/dist/core/profiles.js +160 -10
  82. package/dist/core/resolve.js +139 -23
  83. package/dist/core/secrets.js +68 -23
  84. package/dist/core/sessions.js +13 -20
  85. package/dist/core/state-file.js +107 -0
  86. package/dist/core/update.js +31 -18
  87. package/dist/core/version.js +57 -10
  88. package/dist/demo/server.js +42 -0
  89. package/dist/mcpd/cache.js +23 -10
  90. package/dist/mcpd/calllog.js +254 -0
  91. package/dist/mcpd/client-names.js +46 -0
  92. package/dist/mcpd/connectors.js +188 -18
  93. package/dist/mcpd/daemon.js +472 -115
  94. package/dist/mcpd/folder-sets.js +42 -0
  95. package/dist/mcpd/gateway.js +473 -51
  96. package/dist/mcpd/health.js +313 -0
  97. package/dist/mcpd/importer.js +453 -36
  98. package/dist/mcpd/instances.js +453 -65
  99. package/dist/mcpd/jsonrpc.js +11 -1
  100. package/dist/mcpd/launchd.js +65 -48
  101. package/dist/mcpd/middleware.js +144 -0
  102. package/dist/mcpd/modern.js +686 -0
  103. package/dist/mcpd/oauth.js +845 -0
  104. package/dist/mcpd/peerpid.js +134 -6
  105. package/dist/mcpd/pressure.js +88 -0
  106. package/dist/mcpd/rss.js +166 -0
  107. package/dist/mcpd/service.js +191 -0
  108. package/dist/mcpd/share.js +217 -0
  109. package/dist/mcpd/state.js +183 -0
  110. package/dist/mcpd/sync.js +72 -87
  111. package/dist/mcpd/systemd.js +83 -0
  112. package/dist/mcpd/tokens.js +85 -0
  113. package/dist/mcpd/upstream.js +163 -46
  114. package/dist/statusline/cost.js +167 -44
  115. package/dist/statusline/input.js +78 -0
  116. package/dist/statusline/render.js +9 -3
  117. package/dist/ui/fonts.js +8 -3
  118. package/dist/ui/settings.js +33 -16
  119. package/npm-shrinkwrap.json +1102 -0
  120. package/package.json +10 -9
  121. package/dist/cli/commands/available.js +0 -18
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Reading turno's own state files: JSON that turno wrote earlier (locks, caches, the
3
+ * managed-entries list, journal manifests, audit and call log lines). A file another program or
4
+ * a crash left half-written, a hand edit, or a newer turno's format must never become a cast that
5
+ * crashes later: each reader passes a small guard for the shape it needs and the format version
6
+ * it understands, and gets the value, or a reason it cannot have it.
7
+ *
8
+ * Versions: an object may carry a top-level `version` number. A file without one is format 1
9
+ * (everything written before versioning). A file whose version is above the reader's is from a
10
+ * newer turno and is not read. Keep this file free of heavy imports: the status line uses it.
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ /** A state file that exists but cannot be used: main prints its message on one line. */
14
+ export class StateError extends Error {
15
+ problem;
16
+ constructor(message, problem) {
17
+ super(message);
18
+ this.problem = problem;
19
+ this.name = "StateError";
20
+ }
21
+ }
22
+ /** The format version of a parsed value: its `version` field, 1 without one. */
23
+ function formatVersion(v) {
24
+ const n = typeof v === "object" && v !== null && !Array.isArray(v) ? v.version : undefined;
25
+ return typeof n === "number" && Number.isInteger(n) && n > 0 ? n : 1;
26
+ }
27
+ /** Check parsed JSON against a guard and a version; `label` names it in the message. */
28
+ function checkState(v, guard, version, label) {
29
+ const found = formatVersion(v);
30
+ if (found > version)
31
+ return {
32
+ ok: false,
33
+ problem: "newer",
34
+ message: `${label} is format ${found}, from a newer turno (this one reads up to ${version})`,
35
+ };
36
+ if (!guard(v))
37
+ return { ok: false, problem: "shape", message: `${label} does not hold what turno expects` };
38
+ return { ok: true, value: v };
39
+ }
40
+ /** Parse JSON text (one file, or one line of a log) and check it. */
41
+ export function parseState(text, guard, version, label) {
42
+ let v;
43
+ try {
44
+ v = JSON.parse(text);
45
+ }
46
+ catch {
47
+ return { ok: false, problem: "corrupt", message: `${label} is not valid JSON` };
48
+ }
49
+ return checkState(v, guard, version, label);
50
+ }
51
+ /** Read and check a state file, saying what went wrong when it cannot be used. */
52
+ export function readStateResult(file, guard, version = 1) {
53
+ let text;
54
+ try {
55
+ text = readFileSync(file, "utf8");
56
+ }
57
+ catch (err) {
58
+ const code = err.code;
59
+ if (code === "ENOENT" || code === "ENOTDIR")
60
+ return { ok: false, problem: "missing", message: `${file} does not exist` };
61
+ return { ok: false, problem: "unreadable", message: `${file} cannot be read (${code ?? err.message})` };
62
+ }
63
+ return parseState(text, guard, version, file);
64
+ }
65
+ /**
66
+ * The value of a state file, or undefined when it is missing or cannot be used. For caches and
67
+ * hints, where the safe default is to act as if the file were not there.
68
+ */
69
+ export function readState(file, guard, version = 1) {
70
+ const r = readStateResult(file, guard, version);
71
+ return r.ok ? r.value : undefined;
72
+ }
73
+ /**
74
+ * The value of a state file, undefined when it is missing, and a StateError (one clear line that
75
+ * names the file and says to fix or remove it) when it exists but cannot be used. For state
76
+ * whose loss would make turno act wrongly, such as the list of entries it may remove.
77
+ */
78
+ export function requireState(file, guard, version = 1) {
79
+ const r = readStateResult(file, guard, version);
80
+ if (r.ok)
81
+ return r.value;
82
+ if (r.problem === "missing")
83
+ return undefined;
84
+ const fix = r.problem === "newer" ? "upgrade turno (turno upgrade)" : "fix it by hand or remove it";
85
+ throw new StateError(`${r.message}; ${fix}`, r.problem);
86
+ }
87
+ // Small guards shared by the readers ------------------------------------------------------------
88
+ export const isRecord = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
89
+ export const isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
90
+ /** An object whose every value passes `each` (a map such as `file -> names`). */
91
+ export function recordOf(each) {
92
+ return (v) => isRecord(v) && Object.values(v).every(each);
93
+ }
94
+ /** An object with these fields of these types (others are allowed, as newer files add fields). */
95
+ export function hasFields(v, fields) {
96
+ if (!isRecord(v))
97
+ return false;
98
+ return Object.entries(fields).every(([k, t]) => {
99
+ const x = v[k];
100
+ if (t === "array")
101
+ return Array.isArray(x);
102
+ if (t === "object")
103
+ return isRecord(x);
104
+ return typeof x === t;
105
+ });
106
+ }
107
+ //# sourceMappingURL=state-file.js.map
@@ -1,28 +1,31 @@
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 { join } from "node:path";
3
+ import { paths, writePrivateFile } from "./paths.js";
5
4
  import { compareVersions, packageInfo } from "./version.js";
5
+ import { hasFields, readState } from "./state-file.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) {
11
- try {
12
- return JSON.parse(readFileSync(file(env), "utf8"));
13
- }
14
- catch {
15
- return undefined;
16
- }
15
+ const isUpdateState = (v) => hasFields(v, { checkedAt: "number", channel: "string" });
16
+ function readUpdateState(env) {
17
+ return readState(file(env), isUpdateState);
17
18
  }
18
19
  function writeUpdateState(env, s) {
19
- mkdirSync(dirname(file(env)), { recursive: true });
20
- writeFileSync(file(env), `${JSON.stringify(s)}\n`);
20
+ writePrivateFile(file(env), `${JSON.stringify(s)}\n`, env);
21
21
  }
22
22
  const truthy = (v) => v !== undefined && v !== "" && v !== "0" && v.toLowerCase() !== "false";
23
- /** Why the environment turns update checks off: TURNO_NO_UPDATE_CHECK, NO_UPDATE_NOTIFIER, DO_NOT_TRACK, CI. */
23
+ /**
24
+ * Why the environment turns update checks off: TURNO_NO_UPDATE_CHECK, TURNO_NO_UPDATE_NOTIFIER
25
+ * (gh's GH_NO_UPDATE_NOTIFIER), NO_UPDATE_NOTIFIER, DO_NOT_TRACK, CI.
26
+ */
24
27
  export function envOptOut(env) {
25
- if (truthy(env.TURNO_NO_UPDATE_CHECK) || truthy(env.NO_UPDATE_NOTIFIER) || truthy(env.DO_NOT_TRACK)) {
28
+ if ([env.TURNO_NO_UPDATE_CHECK, env.TURNO_NO_UPDATE_NOTIFIER, env.NO_UPDATE_NOTIFIER, env.DO_NOT_TRACK].some(truthy)) {
26
29
  return "turned off by the environment";
27
30
  }
28
31
  if (truthy(env.CI))
@@ -31,7 +34,7 @@ export function envOptOut(env) {
31
34
  }
32
35
  /**
33
36
  * Why update checks are off, or undefined when they run. Off for unpublished (private)
34
- * copies, in CI, with TURNO_NO_UPDATE_CHECK, NO_UPDATE_NOTIFIER or DO_NOT_TRACK, and with
37
+ * copies, in CI, with TURNO_NO_UPDATE_CHECK, TURNO_NO_UPDATE_NOTIFIER, NO_UPDATE_NOTIFIER or DO_NOT_TRACK, and with
35
38
  * `update_check = false` in config.toml.
36
39
  */
37
40
  export function updateChecksOff(env, configured = true) {
@@ -51,7 +54,11 @@ export function registryUrl(env, name, channel) {
51
54
  /** Ask the registry for the version of a dist-tag. Sends nothing but the package name. */
52
55
  export async function fetchLatest(env, channel = "latest", doFetch = fetch) {
53
56
  const { name, version } = packageInfo();
54
- const state = { checkedAt: Date.now(), channel, ...(readUpdateState(env)?.notifiedAt ? { notifiedAt: readUpdateState(env).notifiedAt } : {}) };
57
+ const state = {
58
+ checkedAt: Date.now(),
59
+ channel,
60
+ ...(readUpdateState(env)?.notifiedAt ? { notifiedAt: readUpdateState(env).notifiedAt } : {}),
61
+ };
55
62
  try {
56
63
  const res = await doFetch(registryUrl(env, name, channel), {
57
64
  headers: { accept: "application/json", "user-agent": `turno/${version}` },
@@ -59,8 +66,14 @@ export async function fetchLatest(env, channel = "latest", doFetch = fetch) {
59
66
  });
60
67
  if (!res.ok)
61
68
  state.error = `registry answered HTTP ${res.status}`;
62
- else
63
- state.latest = String((await res.json()).version ?? "");
69
+ else {
70
+ // The answer becomes part of an install command: accept a plain version only.
71
+ const v = (await res.json()).version;
72
+ if (isSemver(v))
73
+ state.latest = v;
74
+ else
75
+ state.error = "the registry answered with an invalid version";
76
+ }
64
77
  }
65
78
  catch (err) {
66
79
  state.error = err.message;
@@ -11,6 +11,41 @@ export function packageInfo() {
11
11
  cached = { name: pkg.name, version: pkg.version, private: Boolean(pkg.private), root: root.replace(/\/$/, "") };
12
12
  return cached;
13
13
  }
14
+ /** The runner that executes turno from its cache for one run, and the command that runs the newest release. */
15
+ export const ONE_OFF_RUNNERS = {
16
+ npx: { runner: "npx", latest: "npx turno-cli@latest", install: "npm install --global turno-cli" },
17
+ "pnpm-dlx": { runner: "pnpm dlx", latest: "pnpm dlx turno-cli@latest", install: "pnpm add --global turno-cli" },
18
+ bunx: { runner: "bunx", latest: "bunx turno-cli@latest", install: "bun add --global turno-cli" },
19
+ };
20
+ function oneOffMethod(path) {
21
+ const parts = path.split(sep);
22
+ // npx: <npm cache>/_npx/<hash>/node_modules/<pkg>.
23
+ if (parts.includes("_npx"))
24
+ return "npx";
25
+ // pnpm dlx: <pnpm cache>/dlx/<hash>/<stamp>/node_modules/... (~/.cache/pnpm, ~/Library/Caches/pnpm).
26
+ const dlx = parts.indexOf("dlx");
27
+ if (dlx > 0 && (parts[dlx - 1] === "pnpm" || parts.includes(".pnpm") || parts.includes(".pacquet")))
28
+ return "pnpm-dlx";
29
+ // bunx: $TMPDIR/bunx-<uid>-<pkg>@<version>/node_modules/<pkg>.
30
+ if (parts.some((p) => p.startsWith("bunx-")))
31
+ return "bunx";
32
+ return undefined;
33
+ }
34
+ /** "npx", "pnpm dlx" or "bunx" when turno runs from that runner's cache, which it may delete at any time. */
35
+ export function oneOffRunner(path) {
36
+ const m = oneOffMethod(path);
37
+ return m ? ONE_OFF_RUNNERS[m].runner : undefined;
38
+ }
39
+ export function isOneOff(method) {
40
+ return method in ONE_OFF_RUNNERS;
41
+ }
42
+ /** The lockfile each package manager keeps next to its global node_modules. */
43
+ const LOCKFILES = [
44
+ ["bun.lock", "bun"],
45
+ ["bun.lockb", "bun"],
46
+ ["yarn.lock", "yarn"],
47
+ ["pnpm-lock.yaml", "pnpm"],
48
+ ];
14
49
  /** How the running turno was installed, from where its files are. */
15
50
  export function detectInstall(root = packageInfo().root) {
16
51
  let real = root;
@@ -25,15 +60,24 @@ export function detectInstall(root = packageInfo().root) {
25
60
  if (parts.includes("Cellar") && parts.includes("node_modules"))
26
61
  return { method: "brew", root: real };
27
62
  if (parts.includes("node_modules")) {
28
- const method = real.includes(`${sep}.volta${sep}`)
29
- ? "volta"
30
- : real.includes(`${sep}.bun${sep}`)
31
- ? "bun"
32
- : real.includes(`${sep}pnpm${sep}`) || real.includes(`${sep}.pnpm${sep}`)
33
- ? "pnpm"
34
- : real.includes(`${sep}yarn${sep}`) || real.includes(`${sep}.yarn${sep}`)
35
- ? "yarn"
36
- : "npm";
63
+ const once = oneOffMethod(real);
64
+ if (once)
65
+ return { method: once, root: real };
66
+ if (real.includes(`${sep}.volta${sep}`))
67
+ return { method: "volta", root: real };
68
+ // The folder that holds the outermost node_modules: yarn, bun and pnpm keep their lockfile
69
+ // there, wherever a custom prefix (--global-folder, BUN_INSTALL, PNPM_HOME) put it.
70
+ const top = parts.slice(0, parts.indexOf("node_modules")).join(sep) || sep;
71
+ const locked = LOCKFILES.find(([file]) => existsSync(join(top, file)));
72
+ if (locked)
73
+ return { method: locked[1], root: real };
74
+ const method = real.includes(`${sep}.bun${sep}`)
75
+ ? "bun"
76
+ : real.includes(`${sep}pnpm${sep}`) || parts.includes(".pnpm")
77
+ ? "pnpm"
78
+ : real.includes(`${sep}yarn${sep}`) || real.includes(`${sep}.yarn${sep}`)
79
+ ? "yarn"
80
+ : "npm";
37
81
  return { method, root: real };
38
82
  }
39
83
  for (let dir = real; dir !== dirname(dir); dir = dirname(dir)) {
@@ -58,7 +102,10 @@ export function upgradeCommand(install, name, spec) {
58
102
  return [["volta", "install", target]];
59
103
  case "brew":
60
104
  // The formula follows the newest release; brew cannot install an arbitrary version.
61
- return [["brew", "update"], ["brew", "upgrade", "turno"]];
105
+ return [
106
+ ["brew", "update"],
107
+ ["brew", "upgrade", "turno"],
108
+ ];
62
109
  case "source":
63
110
  return [
64
111
  ["git", "-C", install.repo, "pull", "--ff-only"],
@@ -0,0 +1,42 @@
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
+ {
15
+ name: "whoami",
16
+ description: `Which ${name} process answered: account, pid, start time and calls served`,
17
+ inputSchema: { type: "object", properties: {} },
18
+ },
19
+ {
20
+ name: "echo",
21
+ description: "Return the text it is given",
22
+ inputSchema: { type: "object", properties: { text: { type: "string" } } },
23
+ },
24
+ ];
25
+ const server = new Server({ name: `turno-demo-${name}`, version: "1.0.0" }, { capabilities: { tools: {} }, instructions: `A demo server of turno (${name}).` });
26
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
27
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
28
+ calls++;
29
+ const text = (t) => ({ content: [{ type: "text", text: t }] });
30
+ switch (req.params.name) {
31
+ case "whoami":
32
+ return text(JSON.stringify({ server: name, account, pid: process.pid, startedAt, calls }));
33
+ case "echo":
34
+ return text(String(req.params.arguments?.text ?? ""));
35
+ default:
36
+ return { ...text(`unknown tool ${req.params.name}`), isError: true };
37
+ }
38
+ });
39
+ await server.connect(new StdioServerTransport());
40
+ // Exit when the gateway closes the pipe, so no demo process outlives the demo.
41
+ process.stdin.on("end", () => process.exit(0));
42
+ //# sourceMappingURL=server.js.map
@@ -1,9 +1,12 @@
1
1
  import { createHash } from "node:crypto";
2
- import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { mkdirSync, 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";
5
+ import { hasFields, readState } from "../core/state-file.js";
4
6
  export function fingerprint(parts) {
5
7
  return createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 16);
6
8
  }
9
+ const isDescription = (v) => hasFields(v, { fingerprint: "string", serverInfo: "object", capabilities: "object", updatedAt: "number" });
7
10
  export class DescriptionCache {
8
11
  dir;
9
12
  memory = new Map();
@@ -14,28 +17,38 @@ export class DescriptionCache {
14
17
  return join(this.dir, `${key.replace(/[^A-Za-z0-9_.@-]/g, "_")}.json`);
15
18
  }
16
19
  get(key, fp) {
20
+ const d = this.peek(key);
21
+ return d && d.fingerprint === fp ? d : undefined;
22
+ }
23
+ /** The stored description whatever its fingerprint (to compare with a fresh one). */
24
+ peek(key) {
17
25
  let d = this.memory.get(key);
18
26
  if (!d) {
19
- try {
20
- d = JSON.parse(readFileSync(this.file(key), "utf8"));
21
- this.memory.set(key, d);
22
- }
23
- catch {
27
+ d = readState(this.file(key), isDescription);
28
+ if (!d)
24
29
  return undefined;
25
- }
30
+ this.memory.set(key, d);
26
31
  }
27
- return d.fingerprint === fp ? d : undefined;
32
+ return d;
28
33
  }
29
34
  set(key, d) {
30
35
  this.memory.set(key, d);
31
- mkdirSync(this.dir, { recursive: true });
36
+ // Under mcpd's data root, which already exists 0700: only the cache folders are created here.
37
+ mkdirSync(this.dir, { recursive: true, mode: PRIVATE_DIR_MODE });
32
38
  const file = this.file(key);
33
39
  const tmp = `${file}.${process.pid}.tmp`;
34
- writeFileSync(tmp, JSON.stringify(d, null, 2));
40
+ writeFileSync(tmp, JSON.stringify(d, null, 2), { mode: PRIVATE_FILE_MODE });
35
41
  renameSync(tmp, file);
36
42
  }
37
43
  delete(key) {
38
44
  this.memory.delete(key);
39
45
  }
46
+ /** Drop a description from memory and disk, so the next client relearns it. */
47
+ forget(key) {
48
+ const had = this.peek(key) !== undefined;
49
+ this.memory.delete(key);
50
+ rmSync(this.file(key), { force: true });
51
+ return had;
52
+ }
40
53
  }
41
54
  //# sourceMappingURL=cache.js.map
@@ -0,0 +1,254 @@
1
+ import { closeSync, existsSync, fstatSync, mkdirSync, openSync, readSync, renameSync, statSync, writeSync, } from "node:fs";
2
+ import { dirname } from "node:path";
3
+ import { ErrorCode } from "./jsonrpc.js";
4
+ import { hasFields, parseState } from "../core/state-file.js";
5
+ /** Methods that get a record. */
6
+ const LOGGED = new Set(["tools/call"]);
7
+ const MAX_ERROR = 300;
8
+ /**
9
+ * Hide what looks like a credential in an error text: bearer and basic values, key=value
10
+ * pairs named like secrets, well-known token prefixes, and long opaque strings.
11
+ */
12
+ export function redact(text) {
13
+ return text
14
+ .replace(/\b(Bearer|Basic|token)\s+[A-Za-z0-9._~+/=-]{8,}/gi, "$1 [redacted]")
15
+ .replace(/\b([A-Za-z_]*(?:token|secret|password|passwd|api[_-]?key|auth)[A-Za-z_]*)(["']?\s*[:=]\s*["']?)[^\s"'&,;]+/gi, "$1$2[redacted]")
16
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, "[redacted]")
17
+ .replace(/\b(?:ghp|gho|ghu|ghs|ghr|github_pat|xox[abpr]|glpat)[-_][A-Za-z0-9_-]{8,}/g, "[redacted]")
18
+ .replace(/[A-Za-z0-9+_-]{32,}={0,2}/g, (s) => (/\d/.test(s) && /[A-Za-z]/.test(s) ? "[redacted]" : s));
19
+ }
20
+ function outcomeOf(o) {
21
+ if ("error" in o) {
22
+ const code = o.error.code;
23
+ const outcome = code === ErrorCode.RequestCancelled ? "cancelled" : code === ErrorCode.RequestTimeout ? "timeout" : "error";
24
+ return { outcome, error: redact(String(o.error.message ?? "")).slice(0, MAX_ERROR) };
25
+ }
26
+ // A tool that failed answers with a result marked isError; its text is a result, so it stays out.
27
+ if (o.result.isError === true)
28
+ return { outcome: "error", error: "the tool reported an error" };
29
+ return { outcome: "ok" };
30
+ }
31
+ function bytes(v) {
32
+ try {
33
+ return Buffer.byteLength(JSON.stringify(v ?? {}));
34
+ }
35
+ catch {
36
+ return 0;
37
+ }
38
+ }
39
+ /** A printable client name, at most 64 characters. */
40
+ export function cleanAgentName(name) {
41
+ if (typeof name !== "string")
42
+ return undefined;
43
+ const clean = name
44
+ .replace(/[^\x20-\x7e]/g, "")
45
+ .trim()
46
+ .slice(0, 64);
47
+ return clean || undefined;
48
+ }
49
+ /** The record for one relayed request, or undefined when the method is not logged. */
50
+ export function toRecord(e) {
51
+ if (!LOGGED.has(e.method))
52
+ return undefined;
53
+ const tool = typeof e.params?.name === "string" ? e.params.name.slice(0, 200) : null;
54
+ const { outcome, error } = outcomeOf(e.outcome);
55
+ return {
56
+ time: new Date(e.startedAt).toISOString(),
57
+ agent: e.ctx.clientName ?? null,
58
+ profile: e.ctx.profile ?? null,
59
+ pid: e.ctx.pid ?? null,
60
+ server: e.ctx.serverName,
61
+ variant: e.variant ?? null,
62
+ tool,
63
+ durationMs: Math.max(0, Math.round(e.durationMs)),
64
+ outcome,
65
+ ...(error !== undefined ? { error } : {}),
66
+ requestBytes: bytes(e.params),
67
+ responseBytes: bytes("error" in e.outcome ? e.outcome.error : e.outcome.result),
68
+ };
69
+ }
70
+ /**
71
+ * Append-only writer, synchronous like mcpd.log so records keep their order across a
72
+ * rotation: `calls.jsonl` becomes `calls.jsonl.1` at `maxBytes` and `keep` old files are kept.
73
+ * Mode 600. A disk that refuses writes never takes mcpd down.
74
+ */
75
+ export function createCallLog(file, opts = {}) {
76
+ const maxBytes = opts.maxBytes ?? 5 * 1024 * 1024;
77
+ const keep = opts.keep ?? 2;
78
+ let fd;
79
+ let size = 0;
80
+ let reported = false;
81
+ const fail = (err) => {
82
+ if (reported)
83
+ return;
84
+ reported = true;
85
+ opts.onError?.(`cannot write ${file}: ${err.message}`);
86
+ };
87
+ const close = () => {
88
+ if (fd === undefined)
89
+ return;
90
+ try {
91
+ closeSync(fd);
92
+ }
93
+ catch {
94
+ /* already closed */
95
+ }
96
+ fd = undefined;
97
+ };
98
+ const open = () => {
99
+ mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
100
+ fd = openSync(file, "a", 0o600);
101
+ size = fstatSync(fd).size;
102
+ };
103
+ const rotate = () => {
104
+ close();
105
+ for (let i = keep - 1; i >= 1; i--)
106
+ if (existsSync(`${file}.${i}`))
107
+ renameSync(`${file}.${i}`, `${file}.${i + 1}`);
108
+ renameSync(file, `${file}.1`);
109
+ };
110
+ return {
111
+ record(e) {
112
+ try {
113
+ const r = toRecord(e);
114
+ if (!r)
115
+ return;
116
+ const line = Buffer.from(`${JSON.stringify(r)}\n`);
117
+ if (fd === undefined)
118
+ open();
119
+ if (size > 0 && size + line.length > maxBytes) {
120
+ rotate();
121
+ open();
122
+ }
123
+ writeSync(fd, line);
124
+ size += line.length;
125
+ reported = false;
126
+ }
127
+ catch (err) {
128
+ close();
129
+ fail(err);
130
+ }
131
+ },
132
+ close,
133
+ };
134
+ }
135
+ const isCallRecord = (v) => hasFields(v, { server: "string", time: "string" });
136
+ /** One line of the call log; a line cut short or of another shape is skipped. */
137
+ function parseLine(line) {
138
+ if (!line.trim())
139
+ return undefined;
140
+ const r = parseState(line, isCallRecord, 1, "call log line");
141
+ return r.ok ? r.value : undefined;
142
+ }
143
+ function matches(r, f) {
144
+ return (f.server === undefined || r.server === f.server) && (f.profile === undefined || r.profile === f.profile);
145
+ }
146
+ function readText(file) {
147
+ let fd;
148
+ try {
149
+ fd = openSync(file, "r");
150
+ const size = fstatSync(fd).size;
151
+ const buf = Buffer.alloc(size);
152
+ let off = 0;
153
+ while (off < size) {
154
+ const n = readSync(fd, buf, off, size - off, off);
155
+ if (n <= 0)
156
+ break;
157
+ off += n;
158
+ }
159
+ return buf.subarray(0, off).toString("utf8");
160
+ }
161
+ catch {
162
+ return "";
163
+ }
164
+ finally {
165
+ if (fd !== undefined)
166
+ closeSync(fd);
167
+ }
168
+ }
169
+ /**
170
+ * The last `tail` records that match, oldest first. Reads the current file, then the rotated
171
+ * ones only while more records are needed. Lines that do not parse are skipped.
172
+ */
173
+ export function readCalls(file, tail, filter = {}, keep = 2) {
174
+ const out = [];
175
+ for (let i = 0; i <= keep && out.length < tail; i++) {
176
+ const f = i === 0 ? file : `${file}.${i}`;
177
+ if (!existsSync(f))
178
+ continue;
179
+ const found = readText(f)
180
+ .split("\n")
181
+ .map(parseLine)
182
+ .filter((r) => r !== undefined && matches(r, filter));
183
+ out.unshift(...found.slice(-(tail - out.length)));
184
+ }
185
+ return out;
186
+ }
187
+ /**
188
+ * Follow the file like `tail -f`: report each new matching record until `signal` aborts.
189
+ * Polls (every `everyMs`), so it works on every platform and survives a rotation: a file that
190
+ * got smaller or was replaced is read again from its start.
191
+ */
192
+ export async function followCalls(file, onRecord, signal, filter = {}, everyMs = 500) {
193
+ let offset = 0;
194
+ let ino;
195
+ try {
196
+ const st = statSync(file);
197
+ offset = st.size;
198
+ ino = st.ino;
199
+ }
200
+ catch {
201
+ /* not there yet */
202
+ }
203
+ let partial = "";
204
+ const poll = () => {
205
+ let st;
206
+ try {
207
+ st = statSync(file);
208
+ }
209
+ catch {
210
+ return;
211
+ }
212
+ if (st.ino !== ino || st.size < offset) {
213
+ ino = st.ino;
214
+ offset = 0;
215
+ partial = "";
216
+ }
217
+ if (st.size === offset)
218
+ return;
219
+ let fd;
220
+ try {
221
+ fd = openSync(file, "r");
222
+ const len = Number(st.size) - offset;
223
+ const buf = Buffer.alloc(len);
224
+ const n = readSync(fd, buf, 0, len, offset);
225
+ offset += n;
226
+ const text = partial + buf.subarray(0, n).toString("utf8");
227
+ const lines = text.split("\n");
228
+ partial = lines.pop() ?? "";
229
+ for (const l of lines) {
230
+ const r = parseLine(l);
231
+ if (r && matches(r, filter))
232
+ onRecord(r);
233
+ }
234
+ }
235
+ catch {
236
+ /* try again on the next tick */
237
+ }
238
+ finally {
239
+ if (fd !== undefined)
240
+ closeSync(fd);
241
+ }
242
+ };
243
+ await new Promise((resolve) => {
244
+ if (signal.aborted)
245
+ return resolve();
246
+ const timer = setInterval(poll, everyMs);
247
+ signal.addEventListener("abort", () => {
248
+ clearInterval(timer);
249
+ poll();
250
+ resolve();
251
+ }, { once: true });
252
+ });
253
+ }
254
+ //# sourceMappingURL=calllog.js.map