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.
- package/CHANGELOG.md +293 -0
- package/README.md +143 -75
- package/dist/accounts/audit.js +137 -7
- package/dist/accounts/builtin.js +68 -21
- package/dist/accounts/delegate.js +176 -35
- package/dist/accounts/policy.js +77 -0
- package/dist/accounts/registry.js +37 -21
- package/dist/agents/adapter.js +7 -0
- package/dist/agents/claude.js +195 -0
- package/dist/agents/codex.js +98 -0
- package/dist/agents/copilot.js +39 -0
- package/dist/agents/cursor.js +41 -0
- package/dist/agents/index.js +26 -86
- package/dist/agents/snippets.js +7 -4
- package/dist/cli/args.js +19 -4
- package/dist/cli/commands/accounts.js +96 -51
- package/dist/cli/commands/auto.js +82 -32
- package/dist/cli/commands/browser.js +216 -135
- package/dist/cli/commands/complete.js +2 -1
- package/dist/cli/commands/completion.js +4 -2
- package/dist/cli/commands/config.js +103 -18
- package/dist/cli/commands/demo.js +292 -0
- package/dist/cli/commands/doctor.js +387 -119
- package/dist/cli/commands/handoff.js +33 -22
- package/dist/cli/commands/identity.js +101 -50
- package/dist/cli/commands/init.js +616 -0
- package/dist/cli/commands/limit.js +25 -13
- package/dist/cli/commands/mcp-oauth.js +194 -0
- package/dist/cli/commands/mcp-observe.js +434 -0
- package/dist/cli/commands/mcp.js +653 -185
- package/dist/cli/commands/mcpd.js +323 -75
- package/dist/cli/commands/migrate.js +6 -4
- package/dist/cli/commands/open.js +92 -27
- package/dist/cli/commands/profile.js +205 -69
- package/dist/cli/commands/resolve.js +6 -2
- package/dist/cli/commands/run.js +15 -5
- package/dist/cli/commands/secret.js +61 -42
- package/dist/cli/commands/session.js +2 -2
- package/dist/cli/commands/sessions.js +42 -12
- package/dist/cli/commands/setup.js +136 -158
- package/dist/cli/commands/status.js +172 -41
- package/dist/cli/commands/statusline.js +305 -113
- package/dist/cli/commands/ui.js +64 -66
- package/dist/cli/commands/undo.js +161 -18
- package/dist/cli/commands/uninstall.js +462 -0
- package/dist/cli/commands/upgrade.js +75 -19
- package/dist/cli/commands/usage.js +117 -44
- package/dist/cli/commands/version.js +7 -5
- package/dist/cli/commands/which.js +7 -24
- package/dist/cli/compile-cache.js +32 -0
- package/dist/cli/group.js +10 -10
- package/dist/cli/help.js +57 -0
- package/dist/cli/highlight.js +236 -0
- package/dist/cli/io.js +170 -1
- package/dist/cli/launch.js +21 -37
- package/dist/cli/launchers.js +145 -94
- package/dist/cli/main.js +163 -27
- package/dist/cli/picker.js +447 -0
- package/dist/cli/registry.js +42 -5
- package/dist/cli/security.js +539 -0
- package/dist/cli/style.js +281 -0
- package/dist/core/config.js +145 -23
- package/dist/core/exhausted.js +6 -8
- package/dist/core/fsutil.js +47 -0
- package/dist/core/journal.js +281 -11
- package/dist/core/manifest.js +126 -6
- package/dist/core/paths.js +114 -7
- package/dist/core/profiles.js +139 -9
- package/dist/core/resolve.js +129 -23
- package/dist/core/secrets.js +215 -20
- package/dist/core/sessions.js +13 -20
- package/dist/core/update.js +18 -8
- package/dist/core/version.js +6 -0
- package/dist/demo/server.js +34 -0
- package/dist/mcpd/cache.js +18 -4
- package/dist/mcpd/calllog.js +253 -0
- package/dist/mcpd/client-names.js +51 -0
- package/dist/mcpd/connectors.js +148 -17
- package/dist/mcpd/daemon.js +452 -116
- package/dist/mcpd/folder-sets.js +39 -0
- package/dist/mcpd/gateway.js +441 -47
- package/dist/mcpd/health.js +269 -0
- package/dist/mcpd/importer.js +356 -36
- package/dist/mcpd/instances.js +425 -65
- package/dist/mcpd/jsonrpc.js +8 -0
- package/dist/mcpd/launchd.js +65 -48
- package/dist/mcpd/modern.js +648 -0
- package/dist/mcpd/oauth.js +791 -0
- package/dist/mcpd/peerpid.js +122 -6
- package/dist/mcpd/pressure.js +85 -0
- package/dist/mcpd/rss.js +151 -0
- package/dist/mcpd/service.js +167 -0
- package/dist/mcpd/state.js +183 -0
- package/dist/mcpd/sync.js +55 -80
- package/dist/mcpd/systemd.js +80 -0
- package/dist/mcpd/tokens.js +89 -0
- package/dist/mcpd/upstream.js +154 -44
- package/dist/statusline/cost.js +154 -44
- package/dist/statusline/input.js +66 -0
- package/dist/statusline/render.js +9 -3
- package/dist/ui/fonts.js +8 -3
- package/dist/ui/settings.js +27 -15
- package/npm-shrinkwrap.json +1093 -0
- package/package.json +9 -9
- package/dist/cli/commands/available.js +0 -18
package/dist/mcpd/peerpid.js
CHANGED
|
@@ -1,13 +1,69 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFileSync, readdirSync, readlinkSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
2
4
|
import { promisify } from "node:util";
|
|
3
5
|
const run = promisify(execFile);
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
6
|
+
function hexPort(addr) {
|
|
7
|
+
const port = addr?.split(":").pop();
|
|
8
|
+
return port ? Number.parseInt(port, 16) : Number.NaN;
|
|
9
|
+
}
|
|
10
|
+
/** Parse the rows of /proc/net/tcp and /proc/net/tcp6 (empty when they do not exist). */
|
|
11
|
+
function procTcpRows(procRoot = "/proc") {
|
|
12
|
+
const rows = [];
|
|
13
|
+
for (const name of ["tcp", "tcp6"]) {
|
|
14
|
+
let text;
|
|
15
|
+
try {
|
|
16
|
+
text = readFileSync(join(procRoot, "net", name), "utf8");
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
for (const line of text.split("\n").slice(1)) {
|
|
22
|
+
const f = line.trim().split(/\s+/);
|
|
23
|
+
if (f.length < 10)
|
|
24
|
+
continue;
|
|
25
|
+
rows.push({ localPort: hexPort(f[1]), remotePort: hexPort(f[2]), state: f[3] ?? "", uid: Number(f[7]), inode: f[9] ?? "" });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return rows;
|
|
29
|
+
}
|
|
30
|
+
/** PID of the process holding socket `inode`, scanning the fds we are allowed to read. */
|
|
31
|
+
function pidOfInode(inode, procRoot = "/proc", skip) {
|
|
32
|
+
if (!inode || inode === "0")
|
|
33
|
+
return undefined;
|
|
34
|
+
const want = `socket:[${inode}]`;
|
|
35
|
+
let pids;
|
|
36
|
+
try {
|
|
37
|
+
pids = readdirSync(procRoot).filter((n) => /^\d+$/.test(n));
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return undefined;
|
|
41
|
+
}
|
|
42
|
+
for (const pid of pids) {
|
|
43
|
+
if (Number(pid) === skip)
|
|
44
|
+
continue;
|
|
45
|
+
let fds;
|
|
46
|
+
try {
|
|
47
|
+
fds = readdirSync(join(procRoot, pid, "fd"));
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
continue; // another user's process, or gone
|
|
51
|
+
}
|
|
52
|
+
for (const fd of fds) {
|
|
53
|
+
try {
|
|
54
|
+
if (readlinkSync(join(procRoot, pid, "fd", fd)) === want)
|
|
55
|
+
return Number(pid);
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
/* closed meanwhile */
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return undefined;
|
|
63
|
+
}
|
|
64
|
+
async function lsofPeer(remotePort, self, env) {
|
|
9
65
|
try {
|
|
10
|
-
const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], { timeout: 3000 });
|
|
66
|
+
const { stdout } = await run("lsof", ["-nP", `-iTCP:${remotePort}`, "-sTCP:ESTABLISHED", "-Fpn"], { timeout: 3000, env });
|
|
11
67
|
let pid;
|
|
12
68
|
for (const line of stdout.split("\n")) {
|
|
13
69
|
if (line.startsWith("p"))
|
|
@@ -22,4 +78,64 @@ export async function peerPid(remotePort, self = process.pid) {
|
|
|
22
78
|
}
|
|
23
79
|
return undefined;
|
|
24
80
|
}
|
|
81
|
+
/**
|
|
82
|
+
* PID of the local process that owns the client side of a TCP connection to mcpd. Used when a
|
|
83
|
+
* session did not send X-Turno-Pid (not started by a launcher). On Linux it reads
|
|
84
|
+
* /proc/net/tcp(6) and /proc/<pid>/fd; elsewhere, or when that finds nothing, it asks lsof;
|
|
85
|
+
* without either it gives up.
|
|
86
|
+
*/
|
|
87
|
+
export async function peerPid(remotePort, self = process.pid, opts = {}) {
|
|
88
|
+
const platform = opts.platform ?? process.platform;
|
|
89
|
+
if (platform === "linux") {
|
|
90
|
+
const procRoot = opts.procRoot ?? "/proc";
|
|
91
|
+
const row = procTcpRows(procRoot).find((r) => r.localPort === remotePort && r.state === "01");
|
|
92
|
+
const pid = row ? pidOfInode(row.inode, procRoot, self) : undefined;
|
|
93
|
+
if (pid)
|
|
94
|
+
return pid;
|
|
95
|
+
}
|
|
96
|
+
return lsofPeer(remotePort, self, opts.env ?? process.env);
|
|
97
|
+
}
|
|
98
|
+
/** Which process listens on 127.0.0.1:`port`, as far as this user can tell. Undefined when unknown or free. */
|
|
99
|
+
export async function portOwner(port, opts = {}) {
|
|
100
|
+
const platform = opts.platform ?? process.platform;
|
|
101
|
+
if (platform === "linux") {
|
|
102
|
+
const procRoot = opts.procRoot ?? "/proc";
|
|
103
|
+
const row = procTcpRows(procRoot).find((r) => r.localPort === port && r.state === "0A");
|
|
104
|
+
if (row) {
|
|
105
|
+
const pid = pidOfInode(row.inode, procRoot);
|
|
106
|
+
let command;
|
|
107
|
+
try {
|
|
108
|
+
if (pid)
|
|
109
|
+
command = readFileSync(join(procRoot, String(pid), "comm"), "utf8").trim();
|
|
110
|
+
}
|
|
111
|
+
catch {
|
|
112
|
+
/* gone */
|
|
113
|
+
}
|
|
114
|
+
return { uid: row.uid, ...(pid ? { pid } : {}), ...(command ? { command } : {}) };
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
const { stdout } = await run("lsof", ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fpcu"], { timeout: 3000, env: opts.env ?? process.env });
|
|
119
|
+
const owner = {};
|
|
120
|
+
for (const line of stdout.split("\n")) {
|
|
121
|
+
if (line.startsWith("p") && owner.pid === undefined)
|
|
122
|
+
owner.pid = Number(line.slice(1));
|
|
123
|
+
else if (line.startsWith("c") && owner.command === undefined)
|
|
124
|
+
owner.command = line.slice(1);
|
|
125
|
+
else if (line.startsWith("u") && owner.uid === undefined)
|
|
126
|
+
owner.uid = Number(line.slice(1));
|
|
127
|
+
}
|
|
128
|
+
return owner.pid !== undefined ? owner : undefined;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/** "node (pid 123, uid 501)" for messages. */
|
|
135
|
+
export function describeOwner(o) {
|
|
136
|
+
if (!o)
|
|
137
|
+
return "another process";
|
|
138
|
+
const bits = [o.pid !== undefined ? `pid ${o.pid}` : "", o.uid !== undefined ? `uid ${o.uid}` : ""].filter(Boolean);
|
|
139
|
+
return `${o.command ?? "a process"}${bits.length ? ` (${bits.join(", ")})` : ""}`;
|
|
140
|
+
}
|
|
25
141
|
//# sourceMappingURL=peerpid.js.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import { freemem, totalmem } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { promisify } from "node:util";
|
|
6
|
+
const run = promisify(execFile);
|
|
7
|
+
/**
|
|
8
|
+
* Linux pressure stall information (`/proc/pressure/memory`, kernel 4.20+). `some avg10` is the
|
|
9
|
+
* share of the last 10 seconds in which at least one task waited for memory, `full avg10` the
|
|
10
|
+
* share in which every task did. Thresholds: warn at some >= 10 %, critical at some >= 40 % or
|
|
11
|
+
* full >= 10 %. Undefined when the text is not PSI.
|
|
12
|
+
*/
|
|
13
|
+
export function parsePsi(text) {
|
|
14
|
+
const avg = (kind) => {
|
|
15
|
+
const m = new RegExp(`^${kind}\\s+avg10=(\\d+(?:\\.\\d+)?)`, "m").exec(text);
|
|
16
|
+
return m ? Number(m[1]) : undefined;
|
|
17
|
+
};
|
|
18
|
+
const some = avg("some");
|
|
19
|
+
if (some === undefined)
|
|
20
|
+
return undefined;
|
|
21
|
+
const full = avg("full") ?? 0;
|
|
22
|
+
if (some >= 40 || full >= 10)
|
|
23
|
+
return "critical";
|
|
24
|
+
if (some >= 10)
|
|
25
|
+
return "warn";
|
|
26
|
+
return "normal";
|
|
27
|
+
}
|
|
28
|
+
/** macOS `kern.memorystatus_vm_pressure_level` (the level `memory_pressure` reports): 1 normal, 2 warn, 4 critical. */
|
|
29
|
+
export function darwinLevel(n) {
|
|
30
|
+
return n === 1 ? "normal" : n === 2 ? "warn" : n === 4 ? "critical" : undefined;
|
|
31
|
+
}
|
|
32
|
+
/** Fallback from free memory: warn below 10 % of RAM, critical below 5 %. */
|
|
33
|
+
export function freeMemLevel(free, total) {
|
|
34
|
+
if (!(total > 0))
|
|
35
|
+
return "normal";
|
|
36
|
+
const share = free / total;
|
|
37
|
+
return share < 0.05 ? "critical" : share < 0.1 ? "warn" : "normal";
|
|
38
|
+
}
|
|
39
|
+
async function realSysctl() {
|
|
40
|
+
const { stdout } = await run("/usr/sbin/sysctl", ["-n", "kern.memorystatus_vm_pressure_level"], { encoding: "utf8", timeout: 2000 });
|
|
41
|
+
return stdout;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* The best signal the platform has: PSI on Linux, the kernel pressure level on macOS, else
|
|
45
|
+
* free memory. On macOS free memory is not a fallback: it leaves out reclaimable caches, so it
|
|
46
|
+
* reads low on a healthy machine; a failed sysctl there means "normal".
|
|
47
|
+
*/
|
|
48
|
+
export function memoryPressureProbe(opts = {}) {
|
|
49
|
+
const platform = opts.platform ?? process.platform;
|
|
50
|
+
const free = opts.freemem ?? freemem;
|
|
51
|
+
const total = opts.totalmem ?? totalmem;
|
|
52
|
+
return async () => {
|
|
53
|
+
if (platform === "darwin") {
|
|
54
|
+
try {
|
|
55
|
+
return darwinLevel(Number.parseInt((await (opts.sysctl ?? realSysctl)()).trim(), 10)) ?? "normal";
|
|
56
|
+
}
|
|
57
|
+
catch {
|
|
58
|
+
return "normal";
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (platform === "linux") {
|
|
62
|
+
try {
|
|
63
|
+
const level = parsePsi(readFileSync(join(opts.procRoot ?? "/proc", "pressure", "memory"), "utf8"));
|
|
64
|
+
if (level)
|
|
65
|
+
return level;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
/* no PSI (old kernel, some containers): use free memory */
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return freeMemLevel(free(), total());
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* The idle limit (seconds) that applies now: the server's own limit, shortened to
|
|
76
|
+
* `underPressure` when memory is tight and to a quarter of it when critical. It never grows,
|
|
77
|
+
* and `underPressure` 0 turns the feature off.
|
|
78
|
+
*/
|
|
79
|
+
export function effectiveIdle(idle, level, underPressure) {
|
|
80
|
+
if (!(underPressure > 0) || level === "normal")
|
|
81
|
+
return idle;
|
|
82
|
+
const limit = level === "critical" ? Math.max(1, Math.round(underPressure / 4)) : underPressure;
|
|
83
|
+
return Math.min(idle, limit);
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=pressure.js.map
|
package/dist/mcpd/rss.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { atomicWrite } from "../core/journal.js";
|
|
6
|
+
const run = promisify(execFile);
|
|
7
|
+
/** `ps -A -o pid=,ppid=,rss=` output (rss in KiB, as both macOS and procps print it). */
|
|
8
|
+
export function parsePs(stdout) {
|
|
9
|
+
const t = new Map();
|
|
10
|
+
for (const line of stdout.split("\n")) {
|
|
11
|
+
const [pid, ppid, rss] = line.trim().split(/\s+/).map(Number);
|
|
12
|
+
if (Number.isInteger(pid) && pid > 0 && Number.isInteger(ppid) && Number.isFinite(rss)) {
|
|
13
|
+
t.set(pid, { ppid: ppid, rss: rss * 1024 });
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return t;
|
|
17
|
+
}
|
|
18
|
+
/** The same table from /proc/<pid>/status (PPid and VmRSS lines). Undefined without procfs. */
|
|
19
|
+
export function procfsTable(root = "/proc") {
|
|
20
|
+
let entries;
|
|
21
|
+
try {
|
|
22
|
+
entries = readdirSync(root);
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
const t = new Map();
|
|
28
|
+
for (const e of entries) {
|
|
29
|
+
if (!/^\d+$/.test(e))
|
|
30
|
+
continue;
|
|
31
|
+
try {
|
|
32
|
+
const text = readFileSync(join(root, e, "status"), "utf8");
|
|
33
|
+
const ppid = Number(/^PPid:\s+(\d+)/m.exec(text)?.[1]);
|
|
34
|
+
const kb = /^VmRSS:\s+(\d+)\s*kB/m.exec(text)?.[1];
|
|
35
|
+
if (Number.isInteger(ppid))
|
|
36
|
+
t.set(Number(e), { ppid, rss: kb ? Number(kb) * 1024 : 0 });
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
/* the process exited while we looked */
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return t.size ? t : undefined;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Every process with its parent and RSS: `ps` (macOS and Linux), else procfs on Linux.
|
|
46
|
+
* Undefined when neither is available, so callers can say memory is unknown instead of 0.
|
|
47
|
+
*/
|
|
48
|
+
export async function processTable(opts = {}) {
|
|
49
|
+
try {
|
|
50
|
+
const env = opts.env ?? process.env;
|
|
51
|
+
const { stdout } = await run("ps", ["-A", "-o", "pid=,ppid=,rss="], {
|
|
52
|
+
encoding: "utf8",
|
|
53
|
+
timeout: 5000,
|
|
54
|
+
maxBuffer: 16 * 1024 * 1024,
|
|
55
|
+
env: { PATH: env.PATH ?? "", LC_ALL: "C" },
|
|
56
|
+
});
|
|
57
|
+
const t = parsePs(stdout);
|
|
58
|
+
if (t.size)
|
|
59
|
+
return t;
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
/* no ps (minimal containers): try procfs */
|
|
63
|
+
}
|
|
64
|
+
return procfsTable(opts.procRoot);
|
|
65
|
+
}
|
|
66
|
+
/** RSS of a process and all its descendants (npx and shell wrappers start the real server as a child). */
|
|
67
|
+
export function treeRss(table, pid) {
|
|
68
|
+
if (!table.has(pid))
|
|
69
|
+
return undefined;
|
|
70
|
+
const children = new Map();
|
|
71
|
+
for (const [p, { ppid }] of table) {
|
|
72
|
+
if (p === ppid)
|
|
73
|
+
continue;
|
|
74
|
+
const list = children.get(ppid);
|
|
75
|
+
if (list)
|
|
76
|
+
list.push(p);
|
|
77
|
+
else
|
|
78
|
+
children.set(ppid, [p]);
|
|
79
|
+
}
|
|
80
|
+
let total = 0;
|
|
81
|
+
const seen = new Set();
|
|
82
|
+
const stack = [pid];
|
|
83
|
+
while (stack.length) {
|
|
84
|
+
const p = stack.pop();
|
|
85
|
+
if (seen.has(p))
|
|
86
|
+
continue;
|
|
87
|
+
seen.add(p);
|
|
88
|
+
total += table.get(p)?.rss ?? 0;
|
|
89
|
+
stack.push(...(children.get(p) ?? []));
|
|
90
|
+
}
|
|
91
|
+
return total;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* What each server variant used the last time it ran, so `turno mcp savings` can estimate
|
|
95
|
+
* servers that are not running now. mcpd samples its instances every 15 seconds while any
|
|
96
|
+
* runs and keeps the result in `state/mcpd-rss.json` (mode 600) across restarts.
|
|
97
|
+
*/
|
|
98
|
+
export class RssSampler {
|
|
99
|
+
file;
|
|
100
|
+
opts;
|
|
101
|
+
known = {};
|
|
102
|
+
busy = false;
|
|
103
|
+
constructor(file, opts = {}) {
|
|
104
|
+
this.file = file;
|
|
105
|
+
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
|
+
}
|
|
115
|
+
}
|
|
116
|
+
samples() {
|
|
117
|
+
return { ...this.known };
|
|
118
|
+
}
|
|
119
|
+
/** Measure the running instances (descKey and PID) and remember each variant's RSS. */
|
|
120
|
+
async sample(instances, now = new Date()) {
|
|
121
|
+
const live = instances.filter((i) => typeof i.pid === "number" && i.pid > 0);
|
|
122
|
+
if (!live.length || this.busy)
|
|
123
|
+
return;
|
|
124
|
+
this.busy = true;
|
|
125
|
+
try {
|
|
126
|
+
const table = await processTable(this.opts);
|
|
127
|
+
if (!table)
|
|
128
|
+
return;
|
|
129
|
+
const sums = new Map();
|
|
130
|
+
for (const i of live) {
|
|
131
|
+
const rss = treeRss(table, i.pid);
|
|
132
|
+
if (rss)
|
|
133
|
+
sums.set(i.descKey, [...(sums.get(i.descKey) ?? []), rss]);
|
|
134
|
+
}
|
|
135
|
+
if (!sums.size)
|
|
136
|
+
return;
|
|
137
|
+
for (const [k, list] of sums)
|
|
138
|
+
this.known[k] = { bytes: Math.round(list.reduce((a, b) => a + b, 0) / list.length), at: now.toISOString() };
|
|
139
|
+
try {
|
|
140
|
+
atomicWrite(this.file, `${JSON.stringify(this.known)}\n`, 0o600);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
/* the memory copy still serves /status */
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
finally {
|
|
147
|
+
this.busy = false;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
//# sourceMappingURL=rss.js.map
|
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { accessSync, constants, existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { basename, delimiter, join } from "node:path";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
import { paths, tildify } from "../core/paths.js";
|
|
6
|
+
import { realOr } from "../core/fsutil.js";
|
|
7
|
+
const exec = promisify(execFile);
|
|
8
|
+
/**
|
|
9
|
+
* How mcpd is kept alive across logins (ADR 0017): a LaunchAgent on macOS, a `systemd --user`
|
|
10
|
+
* unit on Linux, nothing elsewhere. Every backend writes one file (journaled, so `turno undo`
|
|
11
|
+
* restores it) and drives the service manager through its command-line tool.
|
|
12
|
+
*/
|
|
13
|
+
/** A failure the user can act on: printed as one line, never with a stack. */
|
|
14
|
+
export class ServiceError extends Error {
|
|
15
|
+
constructor(message) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = "ServiceError";
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** Set in the service environment, so `mcp daemon run` knows a supervisor restarts it. */
|
|
21
|
+
const SERVICE_ENV = "TURNO_MCPD_SERVICE";
|
|
22
|
+
/** The command line of the service: program, then `mcp daemon run`. */
|
|
23
|
+
export function serviceArgs(spec) {
|
|
24
|
+
return [...spec.program, "mcp", "daemon", "run"];
|
|
25
|
+
}
|
|
26
|
+
/** Variables the service needs: PATH (service managers start with a minimal one), HOME and turno's own overrides. */
|
|
27
|
+
export function serviceEnv(spec, kind) {
|
|
28
|
+
const vars = {
|
|
29
|
+
PATH: spec.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
|
|
30
|
+
HOME: paths(spec.env).home,
|
|
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"]) {
|
|
33
|
+
if (spec.env[k])
|
|
34
|
+
vars[k] = spec.env[k];
|
|
35
|
+
}
|
|
36
|
+
vars[SERVICE_ENV] = kind;
|
|
37
|
+
return vars;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Run a service manager command. A missing tool becomes a one-line ServiceError instead of
|
|
41
|
+
* `spawn launchctl ENOENT` with a stack.
|
|
42
|
+
*/
|
|
43
|
+
export async function runTool(tool, args, env, timeout = 10_000) {
|
|
44
|
+
try {
|
|
45
|
+
const { stdout } = await exec(tool, args, { timeout, env });
|
|
46
|
+
return stdout;
|
|
47
|
+
}
|
|
48
|
+
catch (err) {
|
|
49
|
+
const e = err;
|
|
50
|
+
if (e.code === "ENOENT")
|
|
51
|
+
throw new ServiceError(`${tool} was not found on PATH; it is needed to manage the mcpd service`);
|
|
52
|
+
const detail = (e.stderr ?? "").trim().split("\n")[0] || e.message.split("\n")[0];
|
|
53
|
+
throw new ServiceError(`${tool} ${args.join(" ")} failed: ${detail}`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Paths that change when a version manager or Homebrew switches versions. A service that
|
|
58
|
+
* runs them breaks after `nvm uninstall`, `brew cleanup` and the like.
|
|
59
|
+
*/
|
|
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-/];
|
|
61
|
+
export function isUnstablePath(p) {
|
|
62
|
+
return UNSTABLE.some((re) => re.test(p));
|
|
63
|
+
}
|
|
64
|
+
function executable(file) {
|
|
65
|
+
try {
|
|
66
|
+
accessSync(file, constants.X_OK);
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return false;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function whichAll(cmd, env) {
|
|
74
|
+
return (env.PATH ?? "")
|
|
75
|
+
.split(delimiter)
|
|
76
|
+
.filter(Boolean)
|
|
77
|
+
.map((d) => join(d, cmd))
|
|
78
|
+
.filter(executable);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* What the service should run. In order: a `turno` on PATH at a stable location that is this
|
|
82
|
+
* same installation (or a Volta shim); the running node and script when both are stable; a
|
|
83
|
+
* stable node found on PATH or in the usual places with this script when the script is
|
|
84
|
+
* stable; otherwise the running node and script, with a warning.
|
|
85
|
+
*/
|
|
86
|
+
export function chooseProgram(opts) {
|
|
87
|
+
const script = realOr(opts.script);
|
|
88
|
+
for (const t of whichAll("turno", opts.env)) {
|
|
89
|
+
if (isUnstablePath(t))
|
|
90
|
+
continue;
|
|
91
|
+
const r = realOr(t);
|
|
92
|
+
if (r === script || basename(r) === "volta-shim")
|
|
93
|
+
return { program: [t] };
|
|
94
|
+
}
|
|
95
|
+
if (!isUnstablePath(script)) {
|
|
96
|
+
if (!isUnstablePath(opts.execPath))
|
|
97
|
+
return { program: [opts.execPath, script] };
|
|
98
|
+
const node = [...whichAll("node", opts.env), "/opt/homebrew/bin/node", "/usr/local/bin/node", "/usr/bin/node"].find((n) => !isUnstablePath(n) && executable(n));
|
|
99
|
+
if (node)
|
|
100
|
+
return { program: [node, script] };
|
|
101
|
+
}
|
|
102
|
+
return {
|
|
103
|
+
program: [opts.execPath, script],
|
|
104
|
+
warning: `the service runs node from ${tildify(opts.execPath, opts.env)}; after switching Node versions run \`turno upgrade --finish\``,
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
/** Whether `systemd --user` can be used here. */
|
|
108
|
+
async function systemdAvailable(env) {
|
|
109
|
+
try {
|
|
110
|
+
await exec("systemctl", ["--user", "show-environment"], { timeout: 5000, env });
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* The backend for this platform. Throws a one-line ServiceError where there is none (Linux
|
|
119
|
+
* without systemd, other systems): `turno mcp daemon run` still works under any supervisor.
|
|
120
|
+
*/
|
|
121
|
+
export async function serviceBackend(env, platform = process.platform) {
|
|
122
|
+
if (platform === "darwin")
|
|
123
|
+
return (await import("./launchd.js")).launchd;
|
|
124
|
+
if (platform === "linux") {
|
|
125
|
+
if (!(await systemdAvailable(env))) {
|
|
126
|
+
throw new ServiceError("no systemd user instance here (systemctl --user does not answer); run `turno mcp daemon run` under your own supervisor instead");
|
|
127
|
+
}
|
|
128
|
+
return (await import("./systemd.js")).systemd;
|
|
129
|
+
}
|
|
130
|
+
throw new ServiceError(`keeping mcpd alive is not supported on ${platform}; run \`turno mcp daemon run\` under your own supervisor instead`);
|
|
131
|
+
}
|
|
132
|
+
/** The backend whose file is installed, without asking the service manager. */
|
|
133
|
+
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;
|
|
135
|
+
return b && existsSync(b.file(env)) ? b : undefined;
|
|
136
|
+
}
|
|
137
|
+
/** Write the service file through the journal and (unless dry) load it. */
|
|
138
|
+
export async function installService(backend, spec, journal) {
|
|
139
|
+
const file = backend.file(spec.env);
|
|
140
|
+
const text = backend.render(spec);
|
|
141
|
+
let before;
|
|
142
|
+
try {
|
|
143
|
+
before = readFileSync(file, "utf8");
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
before = undefined;
|
|
147
|
+
}
|
|
148
|
+
if (journal.dryRun)
|
|
149
|
+
return { file, text, changed: before !== text };
|
|
150
|
+
if (before !== text)
|
|
151
|
+
journal.write(file, text, 0o644);
|
|
152
|
+
await backend.load(spec.env);
|
|
153
|
+
return { file, text, changed: before !== text };
|
|
154
|
+
}
|
|
155
|
+
/** Stop the service and remove its file through the journal (so it does not come back at login). */
|
|
156
|
+
export async function removeService(backend, env, journal) {
|
|
157
|
+
const file = backend.file(env);
|
|
158
|
+
const existed = existsSync(file);
|
|
159
|
+
if (journal.dryRun)
|
|
160
|
+
return { file, existed };
|
|
161
|
+
if (await backend.isLoaded(env))
|
|
162
|
+
await backend.unload(env);
|
|
163
|
+
if (existed)
|
|
164
|
+
journal.remove(file);
|
|
165
|
+
return { file, existed };
|
|
166
|
+
}
|
|
167
|
+
//# sourceMappingURL=service.js.map
|