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