turno-cli 0.1.1 → 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 (104) hide show
  1. package/CHANGELOG.md +284 -0
  2. package/README.md +120 -53
  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/demo/server.js +34 -0
  74. package/dist/mcpd/cache.js +18 -4
  75. package/dist/mcpd/calllog.js +253 -0
  76. package/dist/mcpd/client-names.js +51 -0
  77. package/dist/mcpd/connectors.js +148 -17
  78. package/dist/mcpd/daemon.js +452 -116
  79. package/dist/mcpd/folder-sets.js +39 -0
  80. package/dist/mcpd/gateway.js +441 -47
  81. package/dist/mcpd/health.js +269 -0
  82. package/dist/mcpd/importer.js +356 -36
  83. package/dist/mcpd/instances.js +425 -65
  84. package/dist/mcpd/jsonrpc.js +8 -0
  85. package/dist/mcpd/launchd.js +65 -48
  86. package/dist/mcpd/modern.js +648 -0
  87. package/dist/mcpd/oauth.js +791 -0
  88. package/dist/mcpd/peerpid.js +122 -6
  89. package/dist/mcpd/pressure.js +85 -0
  90. package/dist/mcpd/rss.js +151 -0
  91. package/dist/mcpd/service.js +167 -0
  92. package/dist/mcpd/state.js +183 -0
  93. package/dist/mcpd/sync.js +55 -80
  94. package/dist/mcpd/systemd.js +80 -0
  95. package/dist/mcpd/tokens.js +89 -0
  96. package/dist/mcpd/upstream.js +154 -44
  97. package/dist/statusline/cost.js +154 -44
  98. package/dist/statusline/input.js +66 -0
  99. package/dist/statusline/render.js +9 -3
  100. package/dist/ui/fonts.js +8 -3
  101. package/dist/ui/settings.js +27 -15
  102. package/npm-shrinkwrap.json +1093 -0
  103. package/package.json +6 -6
  104. package/dist/cli/commands/available.js +0 -18
@@ -0,0 +1,434 @@
1
+ import { JSON_FLAG, TAIL, bool, count, parseFlags, printJson, str } from "../args.js";
2
+ import { paint } from "../io.js";
3
+ import { duration as elapsed, padEnd, style } from "../style.js";
4
+ /**
5
+ * Observability subcommands of `turno mcp` (ADR 0026): `log` reads the call log mcpd keeps,
6
+ * `top` shows what each running server costs, `savings` compares mcpd's memory with what the
7
+ * same agent sessions would use without the gateway.
8
+ */
9
+ export const LOG_FLAGS = { follow: { type: "boolean", short: "f" }, ...TAIL, server: { type: "string" }, profile: { type: "string" }, ...JSON_FLAG };
10
+ export const TOP_FLAGS = { once: { type: "boolean" }, ...JSON_FLAG };
11
+ export const SAVINGS_FLAGS = { ...JSON_FLAG };
12
+ const MiB = 1024 * 1024;
13
+ const GiB = 1024 * MiB;
14
+ /** "95 MB", "1.4 GB"; "?" when unknown. */
15
+ export function memory(bytes) {
16
+ if (bytes === null || bytes === undefined || !Number.isFinite(bytes))
17
+ return "?";
18
+ return bytes >= GiB ? `${(bytes / GiB).toFixed(1)} GB` : `${Math.round(bytes / MiB)} MB`;
19
+ }
20
+ function size(bytes) {
21
+ if (bytes < 1024)
22
+ return `${bytes} B`;
23
+ if (bytes < MiB)
24
+ return `${(bytes / 1024).toFixed(1)} KB`;
25
+ return `${(bytes / MiB).toFixed(1)} MB`;
26
+ }
27
+ /** 42s, 3m 5s, 2h 4m, 3d 1h. */
28
+ export function duration(seconds) {
29
+ const s = Math.max(0, Math.round(seconds));
30
+ if (s < 60)
31
+ return `${s}s`;
32
+ if (s < 3600)
33
+ return `${Math.floor(s / 60)}m ${s % 60}s`;
34
+ if (s < 86400)
35
+ return `${Math.floor(s / 3600)}h ${Math.floor((s % 3600) / 60)}m`;
36
+ return `${Math.floor(s / 86400)}d ${Math.floor((s % 86400) / 3600)}h`;
37
+ }
38
+ /** Abort on Ctrl-C, for the commands that keep running. */
39
+ function untilInterrupted() {
40
+ const ac = new AbortController();
41
+ const stop = () => ac.abort();
42
+ process.once("SIGINT", stop);
43
+ return { signal: ac.signal, dispose: () => process.off("SIGINT", stop) };
44
+ }
45
+ // log ----------------------------------------------------------------------------------------
46
+ const OUTCOME = {
47
+ ok: { icon: "ok", paint: "ok" },
48
+ error: { icon: "err", paint: "err" },
49
+ timeout: { icon: "warn", paint: "warn" },
50
+ cancelled: { icon: "skip", paint: "muted" },
51
+ };
52
+ const sizesText = (r) => `${size(r.requestBytes)} → ${size(r.responseBytes)}`;
53
+ const serverText = (r) => (r.variant && r.variant !== "default" ? `${r.server}@${r.variant}` : r.server);
54
+ const OUTCOME_W = 11;
55
+ const DURATION_W = 5;
56
+ const GAP = 2;
57
+ /**
58
+ * Widths for these calls on this terminal: each name column as wide as its widest value within
59
+ * a cap, narrowed until the line fits, then sizes and the agent added while they fit (on a
60
+ * narrow terminal the agent goes first, then the sizes).
61
+ */
62
+ export function logLayout(io, records, now = new Date()) {
63
+ const { width } = style(io);
64
+ const day = (iso) => {
65
+ const d = new Date(iso);
66
+ return d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate();
67
+ };
68
+ const widest = (f, min, max, none) => records.length ? Math.min(max, Math.max(min, ...records.map((r) => f(r).length))) : none;
69
+ const l = {
70
+ today: records.every((r) => day(r.time)),
71
+ server: widest(serverText, 6, 18, 12),
72
+ tool: widest((r) => r.tool ?? "-", 4, 24, 16),
73
+ profile: widest((r) => r.profile ?? "-", 4, 12, 8),
74
+ agent: widest((r) => r.agent ?? "-", 5, 16, 12),
75
+ sizes: widest(sizesText, 5, 21, 17),
76
+ showAgent: false,
77
+ showSizes: false,
78
+ };
79
+ const core = () => (l.today ? 8 : 14) + OUTCOME_W + DURATION_W + l.server + l.tool + l.profile + GAP * 5;
80
+ while (core() > width && (l.tool > 10 || l.server > 8)) {
81
+ if (l.tool >= l.server && l.tool > 10)
82
+ l.tool--;
83
+ else
84
+ l.server--;
85
+ }
86
+ l.showSizes = core() + GAP + l.sizes <= width;
87
+ l.showAgent = l.showSizes && core() + GAP * 2 + l.sizes + l.agent <= width;
88
+ return l;
89
+ }
90
+ /** Cut text to `w` columns with an ellipsis. */
91
+ const clip = (text, w) => (text.length > w ? `${text.slice(0, Math.max(0, w - 1))}…` : text);
92
+ /**
93
+ * One call as a line: local time, outcome, duration, server, tool, profile, agent, sizes, error.
94
+ * Plain text keeps the fixed widths scripts read; a terminal uses `layout` (logLayout) so every
95
+ * line fits, and puts an error on its own line under the call.
96
+ */
97
+ export function formatCall(io, r, localTime, layout) {
98
+ const s = style(io);
99
+ const server = serverText(r);
100
+ if (!s.color) {
101
+ const cells = [
102
+ localTime(r.time),
103
+ r.outcome.padEnd(9),
104
+ `${r.durationMs} ms`.padStart(9),
105
+ server.padEnd(18),
106
+ (r.tool ?? "-").padEnd(22),
107
+ (r.profile ?? "-").padEnd(10),
108
+ (r.agent ?? "-").padEnd(16),
109
+ `${size(r.requestBytes)} in, ${size(r.responseBytes)} out`,
110
+ ];
111
+ return `${cells.join(" ")}${r.error ? ` ${r.error}` : ""}`;
112
+ }
113
+ const l = layout ?? logLayout(io, [r]);
114
+ const o = OUTCOME[r.outcome];
115
+ const time = localTime(r.time);
116
+ const slow = r.durationMs >= 10_000 ? s.warn : (t) => t;
117
+ const cells = [
118
+ s.muted(l.today ? time.slice(11) : time.slice(5)),
119
+ padEnd(o ? `${s.icon(o.icon)} ${s[o.paint](r.outcome)}` : r.outcome, OUTCOME_W),
120
+ slow(elapsed(r.durationMs).padStart(DURATION_W)),
121
+ padEnd(s.bold(clip(server, l.server)), l.server),
122
+ padEnd(clip(r.tool ?? "-", l.tool), l.tool),
123
+ padEnd(clip(r.profile ?? "-", l.profile), l.profile),
124
+ ...(l.showAgent ? [padEnd(s.muted(clip(r.agent ?? "-", l.agent)), l.agent)] : []),
125
+ ...(l.showSizes ? [s.muted(sizesText(r))] : []),
126
+ ];
127
+ const line = cells.join(" ".repeat(GAP)).trimEnd();
128
+ if (!r.error)
129
+ return line;
130
+ return `${line}\n${s.wrap(" ".repeat((l.today ? 8 : 14) + GAP), s.err(r.error))}`;
131
+ }
132
+ /** `turno mcp log`; `signal` stops `--follow` (Ctrl-C when not given). */
133
+ export async function log(args, io, signal) {
134
+ const p = parseFlags(args, LOG_FLAGS, 0);
135
+ const n = count(p, "tail", 20);
136
+ const filter = { ...(str(p, "server") ? { server: str(p, "server") } : {}), ...(str(p, "profile") ? { profile: str(p, "profile") } : {}) };
137
+ const json = bool(p, "json");
138
+ const { daemonFiles, loadConfigSafe } = await import("../../mcpd/state.js");
139
+ const { followCalls, readCalls } = await import("../../mcpd/calllog.js");
140
+ const { localTime } = await import("./mcpd.js");
141
+ const file = daemonFiles(io.env).calls;
142
+ if (!loadConfigSafe(io.env).config.mcpd.callLog) {
143
+ io.err(`${paint(io, "note", "33")}: the call log is off (call_log = false under [mcpd] in config.toml); mcpd records no new calls`);
144
+ }
145
+ const records = readCalls(file, n, filter);
146
+ const layout = logLayout(io, records);
147
+ const print = (r) => io.out(json ? JSON.stringify(r) : formatCall(io, r, localTime, layout));
148
+ if (!records.length && !json && !bool(p, "follow")) {
149
+ io.out("no tool calls logged yet (mcpd adds one line per tool call it relays)");
150
+ return 0;
151
+ }
152
+ for (const r of records)
153
+ print(r);
154
+ if (!bool(p, "follow"))
155
+ return 0;
156
+ const stop = signal ? { signal, dispose() { } } : untilInterrupted();
157
+ try {
158
+ await followCalls(file, print, stop.signal, filter);
159
+ }
160
+ finally {
161
+ stop.dispose();
162
+ }
163
+ return 0;
164
+ }
165
+ /** /status of the running mcpd, or undefined when it does not answer. */
166
+ async function fetchStatus(env) {
167
+ const { mcpdRequest } = await import("./mcp.js");
168
+ const r = await mcpdRequest(env, "GET", "/status");
169
+ if (r === "down" || r.status !== 200 || typeof r.body !== "object" || r.body === null)
170
+ return undefined;
171
+ const s = r.body;
172
+ return { ...s, instances: Array.isArray(s.instances) ? s.instances : [] };
173
+ }
174
+ async function measure(env) {
175
+ const { processTable } = await import("../../mcpd/rss.js");
176
+ return processTable({ env });
177
+ }
178
+ function notRunning(io, json) {
179
+ if (json)
180
+ printJson(io, { running: false });
181
+ else
182
+ io.out("mcpd is not running (turno mcp daemon start)");
183
+ return 1;
184
+ }
185
+ const MEMORY_UNKNOWN = "memory is unknown: ps is not available and there is no /proc";
186
+ export async function topSnapshot(status, procs, now = Date.now()) {
187
+ const { treeRss } = await import("../../mcpd/rss.js");
188
+ const started = status.startedAt ? Date.parse(status.startedAt) : Number.NaN;
189
+ return {
190
+ running: true,
191
+ mcpd: {
192
+ pid: status.pid,
193
+ version: status.version ?? null,
194
+ uptimeSeconds: Number.isFinite(started) ? Math.round((now - started) / 1000) : null,
195
+ sessions: status.sessions,
196
+ agents: status.agents?.length ?? 0,
197
+ rssBytes: procs?.get(status.pid)?.rss ?? null,
198
+ totalRssBytes: procs ? (treeRss(procs, status.pid) ?? null) : null,
199
+ },
200
+ instances: status.instances
201
+ .map((i) => ({
202
+ server: i.server,
203
+ variant: i.variant,
204
+ scope: i.scope,
205
+ pid: i.pid,
206
+ rssBytes: procs && i.pid ? (treeRss(procs, i.pid) ?? null) : null,
207
+ sessions: i.clients,
208
+ inflight: i.inflight,
209
+ idleSeconds: i.idleSeconds,
210
+ restarts: i.restarts ?? 0,
211
+ uptimeSeconds: Math.round((now - i.startedAt) / 1000),
212
+ heldBy: i.holder,
213
+ }))
214
+ .sort((a, b) => (b.rssBytes ?? 0) - (a.rssBytes ?? 0) || a.server.localeCompare(b.server)),
215
+ memoryKnown: procs !== undefined,
216
+ memoryPressure: status.memoryPressure
217
+ ? { level: status.memoryPressure.level, idleUnderPressureSeconds: status.memoryPressure.idleUnderPressure, idleCapSeconds: status.memoryPressure.idleCap }
218
+ : null,
219
+ };
220
+ }
221
+ /** The memory pressure line under the top header; nothing while mcpd does not watch it. */
222
+ function pressureLine(s, p) {
223
+ if (!p?.level)
224
+ return undefined;
225
+ if (p.level === "normal" || p.idleCapSeconds === null)
226
+ return s.note("ok", s.muted(`memory pressure ${p.level}: servers keep their own idle limits`));
227
+ const text = `memory pressure ${p.level}: idle servers stop after ${duration(p.idleCapSeconds)} (mcpd.idle_under_pressure)`;
228
+ return p.level === "critical" ? s.note("err", s.err(text)) : s.note("warn", s.warn(text));
229
+ }
230
+ export function renderTop(io, t) {
231
+ const s = style(io);
232
+ const m = t.mcpd;
233
+ const head = [
234
+ s.bold(s.accent(`mcpd pid ${m.pid}`)),
235
+ m.version ? s.muted(`v${m.version}`) : "",
236
+ m.uptimeSeconds !== null ? `up ${duration(m.uptimeSeconds)}` : "",
237
+ `${s.bold(memory(m.rssBytes))} own, ${s.bold(memory(m.totalRssBytes))} with servers`,
238
+ `${m.sessions} session${m.sessions === 1 ? "" : "s"} from ${m.agents} agent${m.agents === 1 ? "" : "s"}`,
239
+ ].filter(Boolean);
240
+ const out = [s.wrap("", head.join(s.muted(" · ")))];
241
+ if (!t.memoryKnown)
242
+ out.push(s.note("warn", `note: ${MEMORY_UNKNOWN}`));
243
+ const pressure = pressureLine(s, t.memoryPressure);
244
+ if (pressure)
245
+ out.push(pressure);
246
+ if (!t.instances.length) {
247
+ out.push(s.muted(" no servers running (they start on first use)"));
248
+ return out;
249
+ }
250
+ // Column titles: muted lowercase on a terminal, as in turno status; uppercase in plain text.
251
+ const rows = [["SERVER", "VARIANT", "SCOPE", "PID", "RSS", "SESSIONS", "IN FLIGHT", "IDLE", "RESTARTS", "UP", "HELD BY"].map((h) => s.muted(s.color ? h.toLowerCase() : h))];
252
+ for (const i of t.instances) {
253
+ rows.push([
254
+ `${s.icon("on")}${s.color ? " " : ""}${s.bold(i.server)}`,
255
+ i.variant === "default" ? s.muted(i.variant) : i.variant,
256
+ i.scope,
257
+ i.pid ? String(i.pid) : s.muted("-"),
258
+ i.pid ? memory(i.rssBytes) : s.muted("in mcpd"),
259
+ String(i.sessions),
260
+ i.inflight ? s.accent(String(i.inflight)) : s.muted("0"),
261
+ duration(i.idleSeconds),
262
+ i.restarts ? s.warn(String(i.restarts)) : s.muted("0"),
263
+ duration(i.uptimeSeconds),
264
+ i.heldBy ? `${i.heldBy.profile ?? "?"}/${i.heldBy.pid ?? "?"}` : "",
265
+ ]);
266
+ }
267
+ const right = { align: "right" };
268
+ // Narrow terminals drop the holder, uptime, restarts and variant first.
269
+ out.push(...s.table(rows, {
270
+ indent: 0,
271
+ columns: [{}, { drop: 1 }, {}, right, right, right, right, { ...right, drop: 3 }, { ...right, drop: 2 }, { ...right, drop: 4 }, { drop: 5 }],
272
+ }));
273
+ return out;
274
+ }
275
+ /** `turno mcp top`: refreshes every 2 s in a terminal until Ctrl-C; one snapshot otherwise. */
276
+ export async function top(args, io, signal, everyMs = 2000) {
277
+ const p = parseFlags(args, TOP_FLAGS, 0);
278
+ const json = bool(p, "json");
279
+ const once = json || bool(p, "once") || !io.isTty;
280
+ const snap = async () => {
281
+ const s = await fetchStatus(io.env);
282
+ return s ? topSnapshot(s, await measure(io.env)) : undefined;
283
+ };
284
+ if (once) {
285
+ const t = await snap();
286
+ if (!t)
287
+ return notRunning(io, json);
288
+ if (json)
289
+ printJson(io, t);
290
+ else
291
+ for (const l of renderTop(io, t))
292
+ io.out(l);
293
+ return 0;
294
+ }
295
+ const stop = signal ? { signal, dispose() { } } : untilInterrupted();
296
+ try {
297
+ while (!stop.signal.aborted) {
298
+ const t = await snap();
299
+ const lines = t ? renderTop(io, t) : ["mcpd is not running (turno mcp daemon start); trying again"];
300
+ io.out(`\x1b[H\x1b[2J${lines.join("\n")}\n${style(io).muted(`every ${everyMs / 1000}s · Ctrl-C to quit`)}`);
301
+ await new Promise((r) => {
302
+ const timer = setTimeout(r, everyMs);
303
+ stop.signal.addEventListener("abort", () => {
304
+ clearTimeout(timer);
305
+ r();
306
+ }, { once: true });
307
+ });
308
+ }
309
+ }
310
+ finally {
311
+ stop.dispose();
312
+ }
313
+ return 0;
314
+ }
315
+ const avg = (xs) => xs.reduce((a, b) => a + b, 0) / xs.length;
316
+ /**
317
+ * The comparison: mcpd plus its children now, against an estimate of the same agent sessions
318
+ * without the gateway, where each starts its own copy of every stdio server its profile gets.
319
+ */
320
+ export async function computeSavings(status, procs, manifest, now = new Date()) {
321
+ const { treeRss } = await import("../../mcpd/rss.js");
322
+ const { servesProfile, variantKey } = await import("../../core/manifest.js");
323
+ const live = new Map();
324
+ for (const i of status.instances) {
325
+ const rss = i.pid ? treeRss(procs, i.pid) : undefined;
326
+ if (rss)
327
+ live.set(`${i.server}@${i.variant}`, [...(live.get(`${i.server}@${i.variant}`) ?? []), rss]);
328
+ }
329
+ const samples = status.serverRss ?? {};
330
+ const rssOf = (name, variant) => {
331
+ for (const key of [`${name}@${variant}`, `${name}@default`]) {
332
+ const l = live.get(key);
333
+ if (l)
334
+ return { bytes: Math.round(avg(l)), source: "live", at: now.toISOString() };
335
+ const s = samples[key];
336
+ if (s)
337
+ return { bytes: s.bytes, source: "sample", at: s.at };
338
+ }
339
+ // Any variant of the server: same program, other credentials.
340
+ const anyLive = [...live].find(([k]) => k.startsWith(`${name}@`));
341
+ if (anyLive)
342
+ return { bytes: Math.round(avg(anyLive[1])), source: "live", at: now.toISOString() };
343
+ const anySample = Object.entries(samples).find(([k]) => k.startsWith(`${name}@`));
344
+ return anySample ? { bytes: anySample[1].bytes, source: "sample", at: anySample[1].at } : undefined;
345
+ };
346
+ const agents = status.agents ?? [];
347
+ const identified = agents.filter((a) => a.pid !== null);
348
+ const per = new Map();
349
+ const unmeasured = new Set();
350
+ let without = 0;
351
+ for (const a of identified) {
352
+ for (const def of Object.values(manifest.servers)) {
353
+ if (def.kind !== "stdio" || def.builtin)
354
+ continue;
355
+ if (!servesProfile(def, a.profile ?? ""))
356
+ continue;
357
+ const variant = variantKey(def, a.profile ?? undefined);
358
+ const m = rssOf(def.name, variant);
359
+ if (!m) {
360
+ unmeasured.add(def.name);
361
+ continue;
362
+ }
363
+ without += m.bytes;
364
+ const key = `${def.name}@${variant}`;
365
+ const row = per.get(key) ?? { server: def.name, variant, rssBytes: m.bytes, source: m.source, measuredAt: m.at, sessions: 0 };
366
+ row.sessions++;
367
+ per.set(key, row);
368
+ }
369
+ }
370
+ const mcpdBytes = procs.get(status.pid)?.rss ?? 0;
371
+ const total = treeRss(procs, status.pid) ?? mcpdBytes;
372
+ const saved = without - total;
373
+ const n = identified.length;
374
+ return {
375
+ running: true,
376
+ agentSessions: n,
377
+ unidentifiedSessions: agents.length - n,
378
+ withTurno: { totalBytes: total, mcpdBytes, serversBytes: total - mcpdBytes, runningServers: status.instances.filter((i) => i.pid).length },
379
+ withoutTurnoBytes: without,
380
+ savedBytes: saved,
381
+ savedPercent: without > 0 ? Math.round((saved / without) * 100) : null,
382
+ servers: [...per.values()].sort((a, b) => b.rssBytes * b.sessions - a.rssBytes * a.sessions),
383
+ unmeasured: [...unmeasured].sort(),
384
+ estimate: `Estimate: without the gateway, every live agent session (${n} now) starts its own copy of each stdio server its profile uses, ` +
385
+ "so it is sessions x per-server RSS (measured now, or the last time the server ran under mcpd).",
386
+ };
387
+ }
388
+ export async function savings(args, io) {
389
+ const p = parseFlags(args, SAVINGS_FLAGS, 0);
390
+ const json = bool(p, "json");
391
+ const status = await fetchStatus(io.env);
392
+ if (!status)
393
+ return notRunning(io, json);
394
+ const procs = await measure(io.env);
395
+ if (!procs) {
396
+ if (json)
397
+ printJson(io, { running: true, error: MEMORY_UNKNOWN });
398
+ else
399
+ io.err(`turno: ${MEMORY_UNKNOWN}`);
400
+ return 1;
401
+ }
402
+ const { loadManifestSafe } = await import("../../mcpd/daemon.js");
403
+ const state = loadManifestSafe(io.env);
404
+ if (state.error && !json)
405
+ io.err(`${paint(io, "warning", "33")}: mcp.toml is invalid, so the estimate uses the ${state.source}: ${state.error}`);
406
+ const s = await computeSavings(status, procs, state.manifest);
407
+ if (json) {
408
+ printJson(io, s);
409
+ return 0;
410
+ }
411
+ const w = s.withTurno;
412
+ io.out(`${paint(io, "With turno:", "1")} ${memory(w.totalBytes).padStart(7)} (mcpd ${memory(w.mcpdBytes)} + ${w.runningServers} running server${w.runningServers === 1 ? "" : "s"} ${memory(w.serversBytes)})`);
413
+ if (!s.agentSessions) {
414
+ io.out("No agent session is connected to mcpd right now, so there is nothing to compare. Open one and run this again.");
415
+ if (s.unidentifiedSessions)
416
+ io.out(`(${s.unidentifiedSessions} session${s.unidentifiedSessions === 1 ? "" : "s"} sent no client PID and cannot be counted.)`);
417
+ return 0;
418
+ }
419
+ io.out(`${paint(io, "Without turno:", "1")} ${memory(s.withoutTurnoBytes).padStart(7)} (estimate for ${s.agentSessions} agent session${s.agentSessions === 1 ? "" : "s"})`);
420
+ const label = s.savedBytes >= 0 ? "Saved:" : "Extra:";
421
+ io.out(`${paint(io, label, "1")}${" ".repeat(15 - label.length)} ${memory(Math.abs(s.savedBytes)).padStart(7)}${s.savedPercent !== null && s.savedBytes >= 0 ? ` (${s.savedPercent}%)` : ""}`);
422
+ io.out(s.estimate);
423
+ if (s.savedBytes < 0)
424
+ io.out("With this few sessions mcpd costs more than it saves; the saving grows with each session that shares a server.");
425
+ for (const r of s.servers) {
426
+ io.out(` ${`${r.server}@${r.variant}`.padEnd(24)} ${memory(r.rssBytes).padStart(7)} x ${r.sessions} = ${memory(r.rssBytes * r.sessions)}${r.source === "sample" ? ` (measured ${r.measuredAt.slice(0, 10)})` : ""}`);
427
+ }
428
+ if (s.unmeasured.length)
429
+ io.out(`Not counted (never measured while running): ${s.unmeasured.join(", ")}. Use them once and run this again.`);
430
+ if (s.unidentifiedSessions)
431
+ io.out(`Not counted: ${s.unidentifiedSessions} session${s.unidentifiedSessions === 1 ? "" : "s"} without a client PID.`);
432
+ return 0;
433
+ }
434
+ //# sourceMappingURL=mcp-observe.js.map