turno-cli 0.0.0-stage → 0.1.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 (83) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +18 -0
  4. package/README.md +334 -2
  5. package/dist/accounts/audit.js +54 -0
  6. package/dist/accounts/builtin.js +214 -0
  7. package/dist/accounts/delegate.js +185 -0
  8. package/dist/accounts/registry.js +190 -0
  9. package/dist/agents/index.js +101 -0
  10. package/dist/agents/snippets.js +64 -0
  11. package/dist/cli/args.js +47 -0
  12. package/dist/cli/commands/accounts.js +216 -0
  13. package/dist/cli/commands/auto.js +44 -0
  14. package/dist/cli/commands/available.js +18 -0
  15. package/dist/cli/commands/browser.js +175 -0
  16. package/dist/cli/commands/complete.js +112 -0
  17. package/dist/cli/commands/completion.js +57 -0
  18. package/dist/cli/commands/config.js +168 -0
  19. package/dist/cli/commands/doctor.js +324 -0
  20. package/dist/cli/commands/exhausted.js +40 -0
  21. package/dist/cli/commands/handoff.js +118 -0
  22. package/dist/cli/commands/hook.js +63 -0
  23. package/dist/cli/commands/identity.js +114 -0
  24. package/dist/cli/commands/limit.js +102 -0
  25. package/dist/cli/commands/mcp.js +350 -0
  26. package/dist/cli/commands/mcpd.js +161 -0
  27. package/dist/cli/commands/migrate.js +176 -0
  28. package/dist/cli/commands/open.js +60 -0
  29. package/dist/cli/commands/profile.js +259 -0
  30. package/dist/cli/commands/resolve.js +23 -0
  31. package/dist/cli/commands/run.js +15 -0
  32. package/dist/cli/commands/secret.js +123 -0
  33. package/dist/cli/commands/session.js +36 -0
  34. package/dist/cli/commands/sessions.js +27 -0
  35. package/dist/cli/commands/setup.js +224 -0
  36. package/dist/cli/commands/status.js +101 -0
  37. package/dist/cli/commands/statusline.js +275 -0
  38. package/dist/cli/commands/ui.js +276 -0
  39. package/dist/cli/commands/undo.js +67 -0
  40. package/dist/cli/commands/update-check.js +22 -0
  41. package/dist/cli/commands/upgrade.js +162 -0
  42. package/dist/cli/commands/usage.js +167 -0
  43. package/dist/cli/commands/version.js +27 -0
  44. package/dist/cli/commands/which.js +28 -0
  45. package/dist/cli/group.js +50 -0
  46. package/dist/cli/io.js +22 -0
  47. package/dist/cli/launch.js +98 -0
  48. package/dist/cli/launchers.js +200 -0
  49. package/dist/cli/main.js +94 -0
  50. package/dist/cli/registry.js +77 -0
  51. package/dist/core/config-edit.js +42 -0
  52. package/dist/core/config.js +137 -0
  53. package/dist/core/exhausted.js +30 -0
  54. package/dist/core/journal.js +185 -0
  55. package/dist/core/manifest.js +177 -0
  56. package/dist/core/paths.js +54 -0
  57. package/dist/core/profiles.js +61 -0
  58. package/dist/core/ratelimit.js +39 -0
  59. package/dist/core/resolve.js +78 -0
  60. package/dist/core/secrets.js +44 -0
  61. package/dist/core/sessions.js +173 -0
  62. package/dist/core/toml-edit.js +152 -0
  63. package/dist/core/update.js +102 -0
  64. package/dist/core/version.js +103 -0
  65. package/dist/mcpd/cache.js +41 -0
  66. package/dist/mcpd/connectors.js +63 -0
  67. package/dist/mcpd/daemon.js +163 -0
  68. package/dist/mcpd/gateway.js +308 -0
  69. package/dist/mcpd/importer.js +160 -0
  70. package/dist/mcpd/instances.js +303 -0
  71. package/dist/mcpd/jsonrpc.js +19 -0
  72. package/dist/mcpd/launchd.js +86 -0
  73. package/dist/mcpd/peerpid.js +25 -0
  74. package/dist/mcpd/sync.js +208 -0
  75. package/dist/mcpd/upstream.js +232 -0
  76. package/dist/statusline/cost.js +135 -0
  77. package/dist/statusline/render.js +246 -0
  78. package/dist/ui/cmap.js +57 -0
  79. package/dist/ui/fonts.js +107 -0
  80. package/dist/ui/settings.js +69 -0
  81. package/dist/ui/terminal-id.js +30 -0
  82. package/dist/ui/terminals.js +163 -0
  83. package/package.json +69 -3
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Line-level edits of a TOML file that keep comments, blank lines and the order of everything
3
+ * the edit does not touch. Callers validate the result by parsing it before writing.
4
+ */
5
+ /** TOML literal of a value (JSON string escapes are valid TOML basic strings). */
6
+ export function literal(v) {
7
+ if (Array.isArray(v))
8
+ return `[${v.map((s) => JSON.stringify(s)).join(", ")}]`;
9
+ if (typeof v === "string")
10
+ return JSON.stringify(v);
11
+ return String(v);
12
+ }
13
+ const TABLE = /^\s*\[\s*([^[\]#]+?)\s*\]\s*(#.*)?$/;
14
+ const ARRAY_TABLE = /^\s*\[\[\s*([^[\]#]+?)\s*\]\]\s*(#.*)?$/;
15
+ const isHeader = (l) => TABLE.test(l) || ARRAY_TABLE.test(l);
16
+ const keyLine = (key) => new RegExp(`^\\s*${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*=`);
17
+ /** [start, end) line range of `[table]` (start is the header), or the top level for undefined. */
18
+ function tableRange(lines, table) {
19
+ if (table === undefined) {
20
+ const first = lines.findIndex(isHeader);
21
+ return [-1, first < 0 ? lines.length : first];
22
+ }
23
+ const start = lines.findIndex((l) => TABLE.exec(l)?.[1] === table);
24
+ if (start < 0)
25
+ return undefined;
26
+ let end = start + 1;
27
+ while (end < lines.length && !isHeader(lines[end]))
28
+ end++;
29
+ return [start, end];
30
+ }
31
+ /** Last non-blank line of a range, so new keys go right after the existing ones. */
32
+ function insertionPoint(lines, [start, end]) {
33
+ let at = end;
34
+ while (at > start + 1 && lines[at - 1].trim() === "")
35
+ at--;
36
+ return at;
37
+ }
38
+ function join(lines) {
39
+ const text = lines.join("\n");
40
+ return text.endsWith("\n") || text === "" ? text : `${text}\n`;
41
+ }
42
+ /** Set `key` in `[table]` (top level when undefined), adding the table at the end if needed. */
43
+ export function setValue(text, table, key, value) {
44
+ const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
45
+ const entry = `${key} = ${literal(value)}`;
46
+ const range = tableRange(lines, table);
47
+ if (!range) {
48
+ while (lines.length && lines[lines.length - 1].trim() === "")
49
+ lines.pop();
50
+ if (lines.length)
51
+ lines.push("");
52
+ lines.push(`[${table}]`, entry);
53
+ return join(lines);
54
+ }
55
+ const re = keyLine(key);
56
+ for (let i = range[0] + 1; i < range[1]; i++) {
57
+ if (re.test(lines[i])) {
58
+ lines[i] = entry;
59
+ return join(lines);
60
+ }
61
+ }
62
+ lines.splice(insertionPoint(lines, range), 0, entry);
63
+ return join(lines);
64
+ }
65
+ /** Remove `key` from `[table]`; the text is unchanged when it is not there. */
66
+ export function removeValue(text, table, key) {
67
+ const lines = text.replace(/\n$/, "").split("\n");
68
+ const range = tableRange(lines, table);
69
+ if (!range)
70
+ return text;
71
+ const re = keyLine(key);
72
+ for (let i = range[0] + 1; i < range[1]; i++) {
73
+ if (re.test(lines[i])) {
74
+ lines.splice(i, 1);
75
+ return join(lines);
76
+ }
77
+ }
78
+ return text;
79
+ }
80
+ /** Add an empty `[table]` when it is missing. */
81
+ export function ensureTable(text, table) {
82
+ const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
83
+ if (tableRange(lines, table))
84
+ return text;
85
+ while (lines.length && lines[lines.length - 1].trim() === "")
86
+ lines.pop();
87
+ if (lines.length)
88
+ lines.push("");
89
+ lines.push(`[${table}]`);
90
+ return join(lines);
91
+ }
92
+ /** Remove `[table]` and its keys (comments directly above the header go too). */
93
+ export function removeTable(text, table) {
94
+ const lines = text.replace(/\n$/, "").split("\n");
95
+ const range = tableRange(lines, table);
96
+ if (!range)
97
+ return text;
98
+ let [start, end] = range;
99
+ while (start > 0 && lines[start - 1].trim().startsWith("#"))
100
+ start--;
101
+ while (end < lines.length && lines[end].trim() === "" && end + 1 < lines.length && lines[end + 1].trim() === "")
102
+ end++;
103
+ lines.splice(start, end - start);
104
+ return join(lines);
105
+ }
106
+ /** Simple `key = "string"` pairs of one block, for matching array-of-table entries. */
107
+ function blockStrings(lines, start, end) {
108
+ const out = {};
109
+ for (let i = start + 1; i < end; i++) {
110
+ const m = /^\s*([A-Za-z0-9_-]+)\s*=\s*"((?:[^"\\]|\\.)*)"/.exec(lines[i]);
111
+ if (m)
112
+ out[m[1]] = JSON.parse(`"${m[2]}"`);
113
+ }
114
+ return out;
115
+ }
116
+ /** Append a `[[name]]` entry with string keys at the end of the file. */
117
+ export function addArrayTable(text, name, entry) {
118
+ const lines = text === "" ? [] : text.replace(/\n$/, "").split("\n");
119
+ while (lines.length && lines[lines.length - 1].trim() === "")
120
+ lines.pop();
121
+ if (lines.length)
122
+ lines.push("");
123
+ lines.push(`[[${name}]]`, ...Object.entries(entry).map(([k, v]) => `${k} = ${literal(v)}`));
124
+ return join(lines);
125
+ }
126
+ /** Remove every `[[name]]` entry whose string keys match `pred`. Returns the text and how many went. */
127
+ export function removeArrayTables(text, name, pred) {
128
+ const lines = text.replace(/\n$/, "").split("\n");
129
+ let removed = 0;
130
+ for (let i = lines.length - 1; i >= 0; i--) {
131
+ if (ARRAY_TABLE.exec(lines[i])?.[1] !== name)
132
+ continue;
133
+ let end = i + 1;
134
+ while (end < lines.length && !isHeader(lines[end]))
135
+ end++;
136
+ if (!pred(blockStrings(lines, i, end)))
137
+ continue;
138
+ let start = i;
139
+ while (start > 0 && lines[start - 1].trim().startsWith("#"))
140
+ start--;
141
+ let stop = end;
142
+ while (stop > i + 1 && lines[stop - 1].trim() === "")
143
+ stop--;
144
+ // Drop one blank separator so removals do not leave growing gaps.
145
+ if (start > 0 && lines[start - 1].trim() === "")
146
+ start--;
147
+ lines.splice(start, stop - start);
148
+ removed++;
149
+ }
150
+ return { text: removed ? join(lines) : text, removed };
151
+ }
152
+ //# sourceMappingURL=toml-edit.js.map
@@ -0,0 +1,102 @@
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";
5
+ import { compareVersions, packageInfo } from "./version.js";
6
+ const DAY = 24 * 3600 * 1000;
7
+ function file(env) {
8
+ return join(paths(env).state, "update.json");
9
+ }
10
+ export function readUpdateState(env) {
11
+ try {
12
+ return JSON.parse(readFileSync(file(env), "utf8"));
13
+ }
14
+ catch {
15
+ return undefined;
16
+ }
17
+ }
18
+ function writeUpdateState(env, s) {
19
+ mkdirSync(dirname(file(env)), { recursive: true });
20
+ writeFileSync(file(env), `${JSON.stringify(s)}\n`);
21
+ }
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. */
24
+ export function envOptOut(env) {
25
+ if (truthy(env.TURNO_NO_UPDATE_CHECK) || truthy(env.NO_UPDATE_NOTIFIER) || truthy(env.DO_NOT_TRACK)) {
26
+ return "turned off by the environment";
27
+ }
28
+ if (truthy(env.CI))
29
+ return "running in CI";
30
+ return undefined;
31
+ }
32
+ /**
33
+ * 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
35
+ * `update_check = false` in config.toml.
36
+ */
37
+ export function updateChecksOff(env, configured = true) {
38
+ if (packageInfo().private)
39
+ return "this copy is not published to a registry";
40
+ const off = envOptOut(env);
41
+ if (off)
42
+ return off;
43
+ if (!configured)
44
+ return "update_check = false in config.toml";
45
+ return undefined;
46
+ }
47
+ export function registryUrl(env, name, channel) {
48
+ const base = (env.TURNO_REGISTRY || env.npm_config_registry || "https://registry.npmjs.org").replace(/\/+$/, "");
49
+ return `${base}/${name.replace("/", "%2F")}/${encodeURIComponent(channel)}`;
50
+ }
51
+ /** Ask the registry for the version of a dist-tag. Sends nothing but the package name. */
52
+ export async function fetchLatest(env, channel = "latest", doFetch = fetch) {
53
+ const { name, version } = packageInfo();
54
+ const state = { checkedAt: Date.now(), channel, ...(readUpdateState(env)?.notifiedAt ? { notifiedAt: readUpdateState(env).notifiedAt } : {}) };
55
+ try {
56
+ const res = await doFetch(registryUrl(env, name, channel), {
57
+ headers: { accept: "application/json", "user-agent": `turno/${version}` },
58
+ signal: AbortSignal.timeout(5000),
59
+ });
60
+ if (!res.ok)
61
+ state.error = `registry answered HTTP ${res.status}`;
62
+ else
63
+ state.latest = String((await res.json()).version ?? "");
64
+ }
65
+ catch (err) {
66
+ state.error = err.message;
67
+ }
68
+ writeUpdateState(env, state);
69
+ return state;
70
+ }
71
+ /** A newer version from the last check, if any. */
72
+ export function availableUpdate(env) {
73
+ const s = readUpdateState(env);
74
+ if (!s?.latest)
75
+ return undefined;
76
+ return compareVersions(s.latest, packageInfo().version) > 0 ? s.latest : undefined;
77
+ }
78
+ /**
79
+ * For interactive commands: start a background check when the last one is a day old, and
80
+ * return a one-line notice (at most once a day) when a newer version is known.
81
+ */
82
+ export function updateNotice(env, configured, entry = process.argv[1]) {
83
+ if (updateChecksOff(env, configured))
84
+ return undefined;
85
+ const s = readUpdateState(env);
86
+ const now = Date.now();
87
+ if ((!s || now - s.checkedAt > DAY) && entry) {
88
+ try {
89
+ const child = spawn(process.execPath, [entry, "__update-check"], { detached: true, stdio: "ignore", env });
90
+ child.unref();
91
+ }
92
+ catch {
93
+ /* best effort */
94
+ }
95
+ }
96
+ const latest = availableUpdate(env);
97
+ if (!latest || (s?.notifiedAt && now - s.notifiedAt < DAY))
98
+ return undefined;
99
+ writeUpdateState(env, { ...s, notifiedAt: now });
100
+ return `turno ${latest} is available (you have ${packageInfo().version}): turno upgrade`;
101
+ }
102
+ //# sourceMappingURL=update.js.map
@@ -0,0 +1,103 @@
1
+ import { existsSync, readFileSync, realpathSync } from "node:fs";
2
+ import { dirname, join, sep } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ let cached;
5
+ /** turno's own package.json (dist/core and src/core both sit two levels below it). */
6
+ export function packageInfo() {
7
+ if (cached)
8
+ return cached;
9
+ const root = fileURLToPath(new URL("../../", import.meta.url));
10
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
11
+ cached = { name: pkg.name, version: pkg.version, private: Boolean(pkg.private), root: root.replace(/\/$/, "") };
12
+ return cached;
13
+ }
14
+ /** How the running turno was installed, from where its files are. */
15
+ export function detectInstall(root = packageInfo().root) {
16
+ let real = root;
17
+ try {
18
+ real = realpathSync(root);
19
+ }
20
+ catch {
21
+ /* keep it */
22
+ }
23
+ const parts = real.split(sep);
24
+ if (parts.includes("node_modules")) {
25
+ const method = real.includes(`${sep}.volta${sep}`)
26
+ ? "volta"
27
+ : real.includes(`${sep}.bun${sep}`)
28
+ ? "bun"
29
+ : real.includes(`${sep}pnpm${sep}`) || real.includes(`${sep}.pnpm${sep}`)
30
+ ? "pnpm"
31
+ : real.includes(`${sep}yarn${sep}`) || real.includes(`${sep}.yarn${sep}`)
32
+ ? "yarn"
33
+ : "npm";
34
+ return { method, root: real };
35
+ }
36
+ for (let dir = real; dir !== dirname(dir); dir = dirname(dir)) {
37
+ if (existsSync(join(dir, ".git")) && existsSync(join(dir, "pnpm-workspace.yaml")))
38
+ return { method: "source", root: real, repo: dir };
39
+ }
40
+ return { method: "unknown", root: real };
41
+ }
42
+ /** The shell command that moves an install to `spec` (a version or a dist-tag). */
43
+ export function upgradeCommand(install, name, spec) {
44
+ const target = `${name}@${spec}`;
45
+ switch (install.method) {
46
+ case "npm":
47
+ return [["npm", "install", "--global", target]];
48
+ case "pnpm":
49
+ return [["pnpm", "add", "--global", target]];
50
+ case "yarn":
51
+ return [["yarn", "global", "add", target]];
52
+ case "bun":
53
+ return [["bun", "add", "--global", target]];
54
+ case "volta":
55
+ return [["volta", "install", target]];
56
+ case "source":
57
+ return [
58
+ ["git", "-C", install.repo, "pull", "--ff-only"],
59
+ ["pnpm", "-C", install.repo, "install", "--frozen-lockfile"],
60
+ ["pnpm", "-C", install.repo, "build"],
61
+ ];
62
+ default:
63
+ return undefined;
64
+ }
65
+ }
66
+ /** -1, 0 or 1. Plain semver: a prerelease sorts before its release. */
67
+ export function compareVersions(a, b) {
68
+ const parse = (v) => {
69
+ const [main, pre] = v.replace(/^v/, "").split("-", 2);
70
+ return { nums: main.split(".").map((n) => Number.parseInt(n, 10) || 0), pre };
71
+ };
72
+ const x = parse(a);
73
+ const y = parse(b);
74
+ for (let i = 0; i < 3; i++) {
75
+ const d = (x.nums[i] ?? 0) - (y.nums[i] ?? 0);
76
+ if (d)
77
+ return d < 0 ? -1 : 1;
78
+ }
79
+ if (x.pre === y.pre)
80
+ return 0;
81
+ if (x.pre === undefined)
82
+ return 1;
83
+ if (y.pre === undefined)
84
+ return -1;
85
+ const xs = x.pre.split(".");
86
+ const ys = y.pre.split(".");
87
+ for (let i = 0; i < Math.max(xs.length, ys.length); i++) {
88
+ const p = xs[i];
89
+ const q = ys[i];
90
+ if (p === undefined)
91
+ return -1;
92
+ if (q === undefined)
93
+ return 1;
94
+ const pn = /^\d+$/.test(p) ? Number(p) : undefined;
95
+ const qn = /^\d+$/.test(q) ? Number(q) : undefined;
96
+ if (pn !== undefined && qn !== undefined && pn !== qn)
97
+ return pn < qn ? -1 : 1;
98
+ if (p !== q)
99
+ return p < q ? -1 : 1;
100
+ }
101
+ return 0;
102
+ }
103
+ //# sourceMappingURL=version.js.map
@@ -0,0 +1,41 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ export function fingerprint(parts) {
5
+ return createHash("sha256").update(JSON.stringify(parts)).digest("hex").slice(0, 16);
6
+ }
7
+ export class DescriptionCache {
8
+ dir;
9
+ memory = new Map();
10
+ constructor(dir) {
11
+ this.dir = dir;
12
+ }
13
+ file(key) {
14
+ return join(this.dir, `${key.replace(/[^A-Za-z0-9_.@-]/g, "_")}.json`);
15
+ }
16
+ get(key, fp) {
17
+ let d = this.memory.get(key);
18
+ if (!d) {
19
+ try {
20
+ d = JSON.parse(readFileSync(this.file(key), "utf8"));
21
+ this.memory.set(key, d);
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ return d.fingerprint === fp ? d : undefined;
28
+ }
29
+ set(key, d) {
30
+ this.memory.set(key, d);
31
+ mkdirSync(this.dir, { recursive: true });
32
+ const file = this.file(key);
33
+ const tmp = `${file}.${process.pid}.tmp`;
34
+ writeFileSync(tmp, JSON.stringify(d, null, 2));
35
+ renameSync(tmp, file);
36
+ }
37
+ delete(key) {
38
+ this.memory.delete(key);
39
+ }
40
+ }
41
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1,63 @@
1
+ import { createWriteStream, mkdirSync, statSync, renameSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
4
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
5
+ import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js";
6
+ import { effectiveLaunch } from "../core/manifest.js";
7
+ import { resolveRecord } from "../core/secrets.js";
8
+ import { resolveCommand } from "./instances.js";
9
+ const MAX_LOG = 5 * 1024 * 1024;
10
+ function openLog(logsDir, name) {
11
+ mkdirSync(logsDir, { recursive: true });
12
+ const file = join(logsDir, `${name.replace(/[^A-Za-z0-9_.-]/g, "_")}.log`);
13
+ try {
14
+ if (statSync(file).size > MAX_LOG)
15
+ renameSync(file, `${file}.1`);
16
+ }
17
+ catch {
18
+ /* new file */
19
+ }
20
+ return createWriteStream(file, { flags: "a" });
21
+ }
22
+ export class DefaultConnector {
23
+ opts;
24
+ constructor(opts) {
25
+ this.opts = opts;
26
+ }
27
+ async connect(server, variant, ctx, workdir) {
28
+ if (server.kind === "remote") {
29
+ const headers = await resolveRecord(server.headers, this.opts.resolve);
30
+ const transport = new StreamableHTTPClientTransport(new URL(server.url), { requestInit: { headers } });
31
+ return { transport };
32
+ }
33
+ if (server.builtin) {
34
+ const factory = this.opts.builtins?.[server.builtin];
35
+ if (!factory)
36
+ throw new Error(`unknown builtin server "${server.builtin}"`);
37
+ const [clientSide, serverSide] = InMemoryTransport.createLinkedPair();
38
+ const srv = await factory(ctx);
39
+ await srv.connect(serverSide);
40
+ return { transport: clientSide };
41
+ }
42
+ const launch = effectiveLaunch(server, variant);
43
+ const env = { ...(this.opts.baseEnv ?? {}), ...(await resolveRecord(launch.env, this.opts.resolve)) };
44
+ const resolved = resolveCommand(server, launch.command, launch.args, this.opts.serversDir);
45
+ const transport = new StdioClientTransport({
46
+ command: resolved.command,
47
+ args: resolved.args,
48
+ env,
49
+ cwd: launch.cwd ?? workdir,
50
+ stderr: "pipe",
51
+ });
52
+ const log = openLog(this.opts.logsDir, `${server.name}${variant === "default" ? "" : `@${variant}`}`);
53
+ const origStart = transport.start.bind(transport);
54
+ transport.start = async () => {
55
+ await origStart();
56
+ const err = transport.stderr;
57
+ if (err)
58
+ err.pipe(log);
59
+ };
60
+ return { transport, pid: () => transport.pid };
61
+ }
62
+ }
63
+ //# sourceMappingURL=connectors.js.map
@@ -0,0 +1,163 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { appendFileSync, chmodSync, existsSync, mkdirSync, readFileSync, watch, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { loadConfig } from "../core/config.js";
5
+ import { loadManifest } from "../core/manifest.js";
6
+ import { paths } from "../core/paths.js";
7
+ import { keychainResolver } from "../core/secrets.js";
8
+ import { DescriptionCache } from "./cache.js";
9
+ import { DefaultConnector } from "./connectors.js";
10
+ import { Gateway } from "./gateway.js";
11
+ import { InstanceManager, descriptionFingerprint, processAlive } from "./instances.js";
12
+ import { peerPid } from "./peerpid.js";
13
+ /** The bearer token sessions use; created once with mode 600. */
14
+ export function ensureToken(env = process.env) {
15
+ const file = paths(env).mcpdToken;
16
+ try {
17
+ const t = readFileSync(file, "utf8").trim();
18
+ if (t.length >= 32)
19
+ return t;
20
+ }
21
+ catch {
22
+ /* create it */
23
+ }
24
+ mkdirSync(dirname(file), { recursive: true });
25
+ const token = randomBytes(32).toString("hex");
26
+ writeFileSync(file, `${token}\n`, { mode: 0o600 });
27
+ chmodSync(file, 0o600);
28
+ return token;
29
+ }
30
+ export function readToken(env = process.env) {
31
+ try {
32
+ return readFileSync(paths(env).mcpdToken, "utf8").trim() || undefined;
33
+ }
34
+ catch {
35
+ return undefined;
36
+ }
37
+ }
38
+ /** The port mcpd listens on: the one it recorded, else the configured one. */
39
+ export function mcpdPort(env = process.env) {
40
+ try {
41
+ const n = Number.parseInt(readFileSync(paths(env).mcpdPort, "utf8"), 10);
42
+ if (n > 0)
43
+ return n;
44
+ }
45
+ catch {
46
+ /* fall through */
47
+ }
48
+ return loadConfig(env).mcpd.port;
49
+ }
50
+ async function loadBuiltins() {
51
+ const builtins = {};
52
+ try {
53
+ const mod = (await import("../accounts/builtin.js"));
54
+ if (mod.accountsBuiltin)
55
+ builtins.accounts = mod.accountsBuiltin();
56
+ }
57
+ catch {
58
+ // accounts bridge not available in this build
59
+ }
60
+ return builtins;
61
+ }
62
+ /** Start mcpd in this process. Used by `turno mcpd run` (foreground or under launchd). */
63
+ export async function startDaemon(opts = {}) {
64
+ const env = opts.env ?? process.env;
65
+ const p = paths(env);
66
+ mkdirSync(p.logsDir, { recursive: true });
67
+ const logFile = join(p.logsDir, "mcpd.log");
68
+ const log = (line) => {
69
+ const text = `${new Date().toISOString()} ${line}\n`;
70
+ if (opts.logToStdout)
71
+ process.stdout.write(text);
72
+ else
73
+ appendFileSync(logFile, text);
74
+ };
75
+ let manifest = loadManifest(env);
76
+ const config = loadConfig(env);
77
+ const token = ensureToken(env);
78
+ const manager = new InstanceManager({
79
+ cache: new DescriptionCache(p.mcpdCacheDir),
80
+ connector: new DefaultConnector({
81
+ resolve: keychainResolver(env),
82
+ serversDir: p.serversDir,
83
+ logsDir: p.logsDir,
84
+ builtins: await loadBuiltins(),
85
+ baseEnv: Object.fromEntries(["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "TMPDIR"].flatMap((k) => (env[k] ? [[k, env[k]]] : []))),
86
+ }),
87
+ home: p.home,
88
+ log,
89
+ });
90
+ const gateway = new Gateway({ manager, manifest: () => manifest, token, peerPid, log });
91
+ const wanted = opts.port ?? config.mcpd.port;
92
+ let port = 0;
93
+ for (let attempt = 0; attempt < 20; attempt++) {
94
+ try {
95
+ port = await gateway.listen(wanted === 0 ? 0 : wanted + attempt);
96
+ break;
97
+ }
98
+ catch (err) {
99
+ if (err.code !== "EADDRINUSE" || wanted === 0)
100
+ throw err;
101
+ }
102
+ }
103
+ if (!port)
104
+ throw new Error(`no free port from ${wanted}`);
105
+ mkdirSync(dirname(p.mcpdPort), { recursive: true });
106
+ writeFileSync(p.mcpdPort, `${port}\n`);
107
+ log(`mcpd listening on 127.0.0.1:${port} with ${Object.keys(manifest.servers).length} servers`);
108
+ const reload = async (why) => {
109
+ let next;
110
+ try {
111
+ next = loadManifest(env);
112
+ }
113
+ catch (err) {
114
+ log(`reload skipped (${why}): ${err.message}`);
115
+ return;
116
+ }
117
+ // Stop instances whose definition changed or disappeared; the next call starts the new one.
118
+ for (const inst of manager.list()) {
119
+ const def = next.servers[inst.server.name];
120
+ if (!def || descriptionFingerprint(def, inst.variant) !== descriptionFingerprint(inst.server, inst.variant)) {
121
+ await manager.stop(inst.key);
122
+ log(`stopped ${inst.upstream.label} after manifest change`);
123
+ }
124
+ }
125
+ manifest = next;
126
+ log(`manifest reloaded (${why}): ${Object.keys(manifest.servers).length} servers`);
127
+ };
128
+ let debounce;
129
+ let watcher;
130
+ if (existsSync(p.config)) {
131
+ watcher = watch(p.config, (_event, file) => {
132
+ if (file !== "mcp.toml")
133
+ return;
134
+ clearTimeout(debounce);
135
+ debounce = setTimeout(() => void reload("mcp.toml changed"), 300);
136
+ });
137
+ }
138
+ const onHup = () => void reload("SIGHUP");
139
+ process.on("SIGHUP", onHup);
140
+ const timer = setInterval(() => {
141
+ gateway.pruneSessions(processAlive);
142
+ manager
143
+ .reap()
144
+ .then((stopped) => stopped.forEach((s) => log(`reaped ${s}`)))
145
+ .catch((err) => log(`reap failed: ${err.message}`));
146
+ }, 15_000);
147
+ timer.unref();
148
+ return {
149
+ port,
150
+ gateway,
151
+ manager,
152
+ async stop() {
153
+ clearInterval(timer);
154
+ clearTimeout(debounce);
155
+ watcher?.close();
156
+ process.off("SIGHUP", onHup);
157
+ await manager.stopAll();
158
+ await gateway.close();
159
+ log("mcpd stopped");
160
+ },
161
+ };
162
+ }
163
+ //# sourceMappingURL=daemon.js.map