@mostra/cli 0.7.0 → 0.9.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 (64) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/bootstrap-Dc-SQHRF.js +422 -0
  3. package/dist/bootstrap-Dc-SQHRF.js.map +1 -0
  4. package/dist/bootstrap-aaE5wFo9.js +1 -0
  5. package/dist/{flush-CBN3AU9X.js → flush-C16w3JL8.js} +24 -3
  6. package/dist/flush-C16w3JL8.js.map +1 -0
  7. package/dist/index.d.ts +13 -3
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/reference/cli.md +35 -2
  11. package/dist/reference/diagnostics.json +39 -3
  12. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  16. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +3 -3
  17. package/dist/reference/telemetry.md +5 -3
  18. package/dist/run-Bw4_6kcW.js +1 -0
  19. package/dist/{run-DO9Y3Dtm.js → run-DdYT3iHQ.js} +1137 -763
  20. package/dist/run-DdYT3iHQ.js.map +1 -0
  21. package/dist/skill/SKILL.md +120 -0
  22. package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
  23. package/dist/skill/assets/examples/dashboard/live.ts +25 -0
  24. package/dist/skill/assets/examples/dashboard/styles.css +125 -0
  25. package/dist/skill/assets/examples/decision/index.tsx +95 -0
  26. package/dist/skill/assets/examples/decision/styles.css +125 -0
  27. package/dist/skill/assets/examples/inbox/actions.ts +23 -0
  28. package/dist/skill/assets/examples/inbox/index.tsx +109 -0
  29. package/dist/skill/assets/examples/inbox/styles.css +125 -0
  30. package/dist/skill/assets/studio.css +125 -0
  31. package/dist/skill/references/answers.md +181 -0
  32. package/dist/skill/references/design.md +154 -0
  33. package/dist/skill/references/libraries.md +167 -0
  34. package/dist/skill/references/long-lived.md +148 -0
  35. package/dist/skill/references/mcp.md +63 -0
  36. package/dist/skill/references/page.md +131 -0
  37. package/dist/skill/references/server.md +146 -0
  38. package/dist/skill/references/sharing.md +72 -0
  39. package/dist/skill/references/verify.md +71 -0
  40. package/dist/telemetry/flush-main.js +1 -1
  41. package/package.json +12 -5
  42. package/src/bootstrap.ts +16 -3
  43. package/src/command.ts +13 -3
  44. package/src/commands/admin.ts +5 -4
  45. package/src/commands/dev.ts +60 -44
  46. package/src/commands/index.ts +4 -2
  47. package/src/commands/interaction.ts +19 -1
  48. package/src/commands/mcp.ts +128 -0
  49. package/src/detached.ts +1 -0
  50. package/src/docs.ts +141 -7
  51. package/src/help.ts +1 -1
  52. package/src/home.ts +5 -3
  53. package/src/mcp.ts +448 -0
  54. package/src/parse.ts +20 -6
  55. package/src/run.ts +24 -13
  56. package/src/telemetry/harness.ts +24 -0
  57. package/src/telemetry/index.ts +75 -48
  58. package/dist/bootstrap-DfEe_yPr.js +0 -113
  59. package/dist/bootstrap-DfEe_yPr.js.map +0 -1
  60. package/dist/exit-CBIf8nAU.js +0 -79
  61. package/dist/exit-CBIf8nAU.js.map +0 -1
  62. package/dist/flush-CBN3AU9X.js.map +0 -1
  63. package/dist/run-DKNRTR1j.js +0 -1
  64. package/dist/run-DO9Y3Dtm.js.map +0 -1
package/src/mcp.ts ADDED
@@ -0,0 +1,448 @@
1
+ /**
2
+ * `mostra mcp` (INTERFACES §12, D164): serves `@mostra/mcp`'s tools over stdio, or over
3
+ * Streamable HTTP with `--http`, on the home's daemon. Everything the tools need from this
4
+ * computer is here: the session with the daemon (opened on the first call, opened again after the
5
+ * daemon restarts, released after five idle minutes so a server a harness keeps open for a week
6
+ * doesn't keep the daemon from its idle exit), the workspace of artifacts' files, the bundled
7
+ * reference and the browser opener.
8
+ */
9
+ import { randomBytes } from "node:crypto";
10
+ import type { IncomingMessage } from "node:http";
11
+ import { isIP } from "node:net";
12
+ import { serve } from "@hono/node-server";
13
+ import { serveStdio } from "@modelcontextprotocol/server/stdio";
14
+ import {
15
+ createHttpEndpoint,
16
+ createMcpServerFactory,
17
+ type DocsTopicSummary,
18
+ localWorkspace,
19
+ MCP_PATH,
20
+ type McpClientInfo,
21
+ type McpDocs,
22
+ type McpInstance,
23
+ } from "@mostra/mcp";
24
+ import {
25
+ ARTIFACT_PROGRESS,
26
+ type ArtifactProgressParams,
27
+ createDiagnostic,
28
+ type MethodDefinition,
29
+ RpcError,
30
+ } from "@mostra/protocol";
31
+ import { resolveRuntime } from "@mostra/sdk";
32
+ import { progressReporter } from "./bootstrap.ts";
33
+ import { openInBrowser } from "./browser.ts";
34
+ import { connect, type InstanceConnection } from "./client.ts";
35
+ import { docsIndex, MCP_GUIDE_LINKS, skillDir, topicMarkdown } from "./docs.ts";
36
+ import type { Environment } from "./home.ts";
37
+
38
+ /** How long the session with the daemon stays open after the last call. */
39
+ export const MCP_IDLE_MS: number = 5 * 60_000;
40
+
41
+ /** How long one call waits for the runtime's first install before it answers that it's still on. */
42
+ export const MCP_RUNTIME_WAIT_MS: number = 45_000;
43
+
44
+ /**
45
+ * The runtime `mostra mcp` starts its instance from (D164 item 7). Installed from npm, the server
46
+ * answers its client before the bundle its release pins is there, so it installs it in the
47
+ * background as it starts (`start`), and every call that needs the instance waits for it (`wait`):
48
+ * up to {@link MCP_RUNTIME_WAIT_MS}, then `MOSTRA_ENV_RUNTIME_INSTALLING` with how far it is, while
49
+ * the install goes on. One install serves every call; a failed one is tried again by the next.
50
+ * Anywhere else (inside a bundle, a checkout, `MOSTRA_RUNTIME_BIN`) it resolves at once.
51
+ */
52
+ export interface RuntimeInstall {
53
+ start(): void;
54
+ wait(): Promise<void>;
55
+ }
56
+
57
+ /** The runtime install of {@link RuntimeInstall}, reporting its progress through `log`. */
58
+ export function runtimeInstall(options: {
59
+ readonly env: Environment;
60
+ readonly log: (line: string) => void;
61
+ readonly waitMs?: number;
62
+ }): RuntimeInstall {
63
+ const testWait = Number(options.env["MOSTRA_TEST_RUNTIME_WAIT_MS"]);
64
+ const waitMs =
65
+ options.waitMs ?? (Number.isFinite(testWait) && testWait > 0 ? testWait : MCP_RUNTIME_WAIT_MS);
66
+ const report = progressReporter({
67
+ stderr: (text) => {
68
+ for (const line of text.split("\n")) if (line.trim() !== "") options.log(line.trim());
69
+ },
70
+ stderrTty: false,
71
+ });
72
+ let ready = false;
73
+ let pending: Promise<void> | undefined;
74
+ let done: string | undefined;
75
+ const start = (): Promise<void> => {
76
+ if (pending !== undefined) return pending;
77
+ const installing = resolveRuntime({
78
+ env: options.env,
79
+ onProgress: (progress) => {
80
+ if (progress.step === "download") {
81
+ done = `${Math.floor((progress.received / progress.total) * 100)}% downloaded`;
82
+ } else if (progress.step === "files") done = "downloaded, checking its files";
83
+ else if (progress.step === "browser") done = "fetching the browser verify uses";
84
+ report(progress);
85
+ },
86
+ }).then(() => {
87
+ ready = true;
88
+ });
89
+ pending = installing;
90
+ installing.catch((error: unknown) => {
91
+ // The next call tries again, and a waiting call is answered with the failure itself.
92
+ if (pending === installing) pending = undefined;
93
+ done = undefined;
94
+ const diagnostic = error instanceof RpcError ? error.diagnostic : undefined;
95
+ options.log(
96
+ `mostra mcp: the runtime's install failed: ${diagnostic?.code ?? ""} ${diagnostic?.message ?? String(error)}`.trim(),
97
+ );
98
+ });
99
+ return installing;
100
+ };
101
+ return {
102
+ start() {
103
+ void start().catch(() => {});
104
+ },
105
+ async wait() {
106
+ if (ready) return;
107
+ const installing = start();
108
+ let timer: ReturnType<typeof setTimeout> | undefined;
109
+ const late = new Promise<never>((_, reject) => {
110
+ timer = setTimeout(
111
+ () =>
112
+ reject(
113
+ new RpcError(
114
+ createDiagnostic("MOSTRA_ENV_RUNTIME_INSTALLING", {
115
+ message: `Mostra is installing its runtime for this release (${done ?? "starting the download"}); the install goes on.`,
116
+ }),
117
+ ),
118
+ ),
119
+ waitMs,
120
+ );
121
+ timer.unref();
122
+ });
123
+ try {
124
+ await Promise.race([installing, late]);
125
+ } finally {
126
+ clearTimeout(timer);
127
+ }
128
+ },
129
+ };
130
+ }
131
+
132
+ /** The instance port over the home's daemon, as the CLI reaches it. */
133
+ export interface DaemonInstance extends McpInstance {
134
+ /** Whether the instance reached is a host-spawned one (then telemetry sends nothing). */
135
+ hostInstance(): boolean;
136
+ /** Ends the session. */
137
+ close(): void;
138
+ }
139
+
140
+ /** The home's daemon as the MCP server's instance (D164 item 5). */
141
+ export function daemonInstance(options: {
142
+ readonly home: string;
143
+ readonly env: Environment;
144
+ readonly log: (line: string) => void;
145
+ readonly idleMs?: number;
146
+ readonly runtime?: RuntimeInstall;
147
+ /** How a session is opened: `connect`, or a test's stand-in. */
148
+ readonly connect?: typeof connect;
149
+ }): DaemonInstance {
150
+ const idleMs = options.idleMs ?? MCP_IDLE_MS;
151
+ const runtime = options.runtime;
152
+ const opener = options.connect ?? connect;
153
+ const listeners = new Map<string, (progress: ArtifactProgressParams) => void>();
154
+ let session: Promise<InstanceConnection> | undefined;
155
+ let host = false;
156
+ let inflight = 0;
157
+ let idle: ReturnType<typeof setTimeout> | undefined;
158
+
159
+ const open = (): Promise<InstanceConnection> => {
160
+ if (session !== undefined) return session;
161
+ const opening = opener({ home: options.home, env: options.env }).then((connection) => {
162
+ if (connection === undefined) {
163
+ throw new RpcError(
164
+ createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
165
+ message: "No instance runs for this home.",
166
+ }),
167
+ );
168
+ }
169
+ host = connection.summary.mode === "host";
170
+ for (const warning of connection.warnings)
171
+ options.log(`mostra mcp: ${warning.code}: ${warning.message}`);
172
+ connection.onNotification(ARTIFACT_PROGRESS, (params) => {
173
+ const progress = params as ArtifactProgressParams;
174
+ listeners.get(progress.progressToken)?.(progress);
175
+ });
176
+ void connection.closed.then(() => {
177
+ if (session === opening) session = undefined;
178
+ });
179
+ return connection;
180
+ });
181
+ session = opening;
182
+ opening.catch(() => {
183
+ if (session === opening) session = undefined;
184
+ });
185
+ return opening;
186
+ };
187
+
188
+ const release = (): void => {
189
+ const current = session;
190
+ session = undefined;
191
+ void current?.then((connection) => connection.close()).catch(() => {});
192
+ };
193
+
194
+ const settle = (): void => {
195
+ inflight -= 1;
196
+ if (inflight > 0) return;
197
+ clearTimeout(idle);
198
+ idle = setTimeout(release, idleMs);
199
+ idle.unref();
200
+ };
201
+
202
+ return {
203
+ async call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R> {
204
+ inflight += 1;
205
+ clearTimeout(idle);
206
+ try {
207
+ // The runtime first (D164 item 7): a call during its install waits for it, or says so.
208
+ await runtime?.wait();
209
+ const used = open();
210
+ try {
211
+ return await (await used).call(method, params);
212
+ } catch (error) {
213
+ // A daemon that restarted or went idle closed the session: a method that changes
214
+ // nothing is asked again on a new one; a change is never sent twice. Only the session
215
+ // this call used is dropped: calls that fail together then share one new session, and
216
+ // none is left open behind another (Opus review of WP-15, finding 1).
217
+ const closed =
218
+ error instanceof RpcError && error.diagnostic.code === "MOSTRA_HOST_CONNECTION_CLOSED";
219
+ if (!closed || method.mutating) throw error;
220
+ if (session === used) session = undefined;
221
+ return await (await open()).call(method, params);
222
+ }
223
+ } finally {
224
+ settle();
225
+ }
226
+ },
227
+ onProgress(token, listener) {
228
+ listeners.set(token, listener);
229
+ return () => listeners.delete(token);
230
+ },
231
+ hostInstance: () => host,
232
+ close() {
233
+ clearTimeout(idle);
234
+ release();
235
+ },
236
+ };
237
+ }
238
+
239
+ /** The bundled reference (`mostra docs`), read as the MCP server's docs. */
240
+ export function bundledDocs(): McpDocs {
241
+ let topics: ReturnType<typeof docsIndex> | undefined;
242
+ const all = (): ReturnType<typeof docsIndex> => {
243
+ topics ??= docsIndex();
244
+ return topics;
245
+ };
246
+ const cache = new Map<string, string>();
247
+ return {
248
+ topics: (): DocsTopicSummary[] =>
249
+ all().map((topic) => ({ topic: topic.topic, title: topic.title, url: topic.url })),
250
+ read(topic) {
251
+ const cached = cache.get(topic);
252
+ if (cached !== undefined) return cached;
253
+ const found = all().find((entry) => entry.topic === topic);
254
+ if (found === undefined) return undefined;
255
+ const markdown = topicMarkdown(found, skillDir(), MCP_GUIDE_LINKS);
256
+ cache.set(topic, markdown);
257
+ return markdown;
258
+ },
259
+ };
260
+ }
261
+
262
+ /** What both transports are given. */
263
+ export interface ServeOptions {
264
+ readonly home: string;
265
+ readonly env: Environment;
266
+ readonly workspace: string;
267
+ readonly version: string;
268
+ readonly log: (line: string) => void;
269
+ /**
270
+ * Told each MCP client the server serves (for telemetry, which counts each once), with the
271
+ * instance, whose session (when one is open) says whether a host spawned it.
272
+ */
273
+ readonly onClient: (client: McpClientInfo, instance: DaemonInstance) => void;
274
+ }
275
+
276
+ /** The daemon instance, with the runtime's install started at once (D164 item 7). */
277
+ function startInstance(options: ServeOptions): DaemonInstance {
278
+ const runtime = runtimeInstall({ env: options.env, log: options.log });
279
+ runtime.start();
280
+ return daemonInstance({ ...options, runtime });
281
+ }
282
+
283
+ function factoryFor(options: ServeOptions, instance: DaemonInstance) {
284
+ return createMcpServerFactory({
285
+ instance,
286
+ workspace: localWorkspace(options.workspace),
287
+ docs: bundledDocs(),
288
+ browser: { open: (url) => openInBrowser(url, options.env) },
289
+ version: options.version,
290
+ onClient: (client) => options.onClient(client, instance),
291
+ });
292
+ }
293
+
294
+ /** Resolves when the process is asked to stop: Ctrl-C, SIGTERM, SIGHUP, or Ctrl+Break on Windows. */
295
+ function stopSignal(): Promise<string> {
296
+ return new Promise((resolve) => {
297
+ for (const signal of ["SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"] as const) {
298
+ process.once(signal, () => resolve(signal));
299
+ }
300
+ });
301
+ }
302
+
303
+ /** Serves over stdio until the client closes stdin or the process is stopped. */
304
+ export async function serveOverStdio(options: ServeOptions): Promise<DaemonInstance> {
305
+ const instance = startInstance(options);
306
+ const handle = serveStdio(factoryFor(options, instance), {
307
+ onerror: (error) => options.log(`mostra mcp: ${error.message}`),
308
+ });
309
+ const ended = new Promise<string>((resolve) => {
310
+ process.stdin.once("end", () => resolve("stdin"));
311
+ process.stdin.once("close", () => resolve("stdin"));
312
+ });
313
+ await Promise.race([ended, stopSignal()]);
314
+ await handle.close().catch(() => {});
315
+ instance.close();
316
+ return instance;
317
+ }
318
+
319
+ /** The address and URL host of `--bind` and `--url-host` (D99's rules, D164 item 3). */
320
+ export function mcpBind(options: { readonly bind?: string; readonly urlHost?: string }): {
321
+ readonly address: string;
322
+ readonly urlHost: string;
323
+ } {
324
+ const fail = (message: string): RpcError =>
325
+ new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message }));
326
+ const address = (options.bind ?? "127.0.0.1").replace(/^\[(.*)\]$/, "$1");
327
+ if (isIP(address) === 0)
328
+ throw fail(`--bind takes an IP address, such as 127.0.0.1, not "${options.bind}".`);
329
+ if (options.urlHost !== undefined && options.bind === undefined) {
330
+ throw fail("--url-host needs --bind: without it the server listens on 127.0.0.1 only.");
331
+ }
332
+ const canonical = new URL(`http://${isIP(address) === 6 ? `[${address}]` : address}/`).hostname;
333
+ const wildcard = canonical === "0.0.0.0" || canonical === "[::]" || canonical === "[::ffff:0:0]";
334
+ if (wildcard && options.urlHost === undefined) {
335
+ throw fail(
336
+ `--bind ${options.bind} listens on every interface; name the host clients use with --url-host.`,
337
+ );
338
+ }
339
+ if (options.urlHost !== undefined && !/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+)$/i.test(options.urlHost)) {
340
+ throw fail(`--url-host takes a host name or an IP address, not "${options.urlHost}".`);
341
+ }
342
+ return { address, urlHost: (options.urlHost ?? canonical).toLowerCase() };
343
+ }
344
+
345
+ /** The fewest distinct characters a chosen token must have, so `aaaa…` isn't accepted. */
346
+ const TOKEN_VARIETY = 8;
347
+
348
+ /** The bearer token: `MOSTRA_MCP_TOKEN`, or one made for this run (160 bits). */
349
+ export function mcpToken(env: Environment): {
350
+ readonly token: string;
351
+ readonly generated: boolean;
352
+ } {
353
+ const given = env["MOSTRA_MCP_TOKEN"];
354
+ if (given !== undefined && given !== "") {
355
+ if (given.length < 26 || /\s/.test(given) || new Set(given).size < TOKEN_VARIETY) {
356
+ throw new RpcError(
357
+ createDiagnostic("MOSTRA_CLI_USAGE", {
358
+ message: `MOSTRA_MCP_TOKEN must be at least 26 characters, with no spaces and at least ${TOKEN_VARIETY} different characters: a random one, such as from \`openssl rand -hex 20\`.`,
359
+ }),
360
+ );
361
+ }
362
+ return { token: given, generated: false };
363
+ }
364
+ return { token: randomBytes(20).toString("base64url"), generated: true };
365
+ }
366
+
367
+ /** A request's headers as `[name, value]` pairs in arrival order (Node's `rawHeaders`). */
368
+ function pairs(incoming: Pick<IncomingMessage, "rawHeaders">): [string, string][] {
369
+ const raw = incoming.rawHeaders;
370
+ const out: [string, string][] = [];
371
+ for (let index = 0; index + 1 < raw.length; index += 2)
372
+ out.push([raw[index] as string, raw[index + 1] as string]);
373
+ return out;
374
+ }
375
+
376
+ /** Serves Streamable HTTP until the process is stopped; tells `onListening` where. */
377
+ export async function serveOverHttp(
378
+ options: ServeOptions & {
379
+ readonly port: number;
380
+ readonly bind?: string;
381
+ readonly urlHost?: string;
382
+ readonly onListening: (where: {
383
+ readonly url: string;
384
+ readonly port: number;
385
+ readonly token: string;
386
+ readonly generated: boolean;
387
+ }) => void;
388
+ },
389
+ ): Promise<DaemonInstance> {
390
+ const { address, urlHost } = mcpBind({
391
+ ...(options.bind !== undefined ? { bind: options.bind } : {}),
392
+ ...(options.urlHost !== undefined ? { urlHost: options.urlHost } : {}),
393
+ });
394
+ const { token, generated } = mcpToken(options.env);
395
+ const instance = startInstance(options);
396
+ const factory = factoryFor(options, instance);
397
+ let endpoint: ReturnType<typeof createHttpEndpoint> | undefined;
398
+ const server = serve({
399
+ fetch: (request: Request, env: { incoming: Pick<IncomingMessage, "url" | "rawHeaders"> }) => {
400
+ if (endpoint === undefined) return new Response(null, { status: 503 });
401
+ return endpoint.fetch(request, {
402
+ target: env.incoming.url ?? "/",
403
+ headers: pairs(env.incoming),
404
+ });
405
+ },
406
+ port: options.port,
407
+ hostname: address,
408
+ });
409
+ const port = await new Promise<number>((resolve, reject) => {
410
+ server.once("error", (error: NodeJS.ErrnoException) =>
411
+ reject(
412
+ new RpcError(
413
+ createDiagnostic("MOSTRA_ENV_BIND_FAILED", {
414
+ message: `The MCP server couldn't listen on ${address}:${options.port} (${error.code ?? error.message}).`,
415
+ }),
416
+ ),
417
+ ),
418
+ );
419
+ server.once("listening", () => {
420
+ const bound = server.address();
421
+ resolve(typeof bound === "object" && bound !== null ? bound.port : options.port);
422
+ });
423
+ });
424
+ // Browsers close idle connections before the server does (D157); harmless for programs.
425
+ if ("keepAliveTimeout" in server) {
426
+ (server as { keepAliveTimeout: number; headersTimeout: number }).keepAliveTimeout = 305_000;
427
+ (server as { keepAliveTimeout: number; headersTimeout: number }).headersTimeout = 306_000;
428
+ }
429
+ const origin = `http://${urlHost}:${port}`;
430
+ endpoint = createHttpEndpoint(factory, {
431
+ origin,
432
+ hosts: [`${urlHost}:${port}`],
433
+ token,
434
+ onRefusal: (refused) =>
435
+ options.log(`mostra mcp: refused a request (${refused.status} ${refused.code})`),
436
+ onError: (error) => options.log(`mostra mcp: ${error.message}`),
437
+ });
438
+ options.onListening({ url: `${origin}${MCP_PATH}`, port, token, generated });
439
+ await stopSignal();
440
+ await endpoint.close().catch(() => {});
441
+ await new Promise<void>((resolve) => {
442
+ server.close(() => resolve());
443
+ // Idle connections are kept for minutes; ending the server ends them now.
444
+ (server as { closeAllConnections?: () => void }).closeAllConnections?.();
445
+ });
446
+ instance.close();
447
+ return instance;
448
+ }
package/src/parse.ts CHANGED
@@ -132,12 +132,11 @@ export function topWords(commands: readonly CommandDef[]): string[] {
132
132
  return [...new Set(commands.map((command) => command.path[0] as string))].sort();
133
133
  }
134
134
 
135
- /** Parses the command line against the definitions. Throws a usage diagnostic. */
136
- export function parseCommandLine(commands: readonly CommandDef[], argv: readonly string[]): Parsed {
137
- const bare = argv.filter((word) => word !== "--json");
138
- if (bare.length === 1 && (bare[0] === "--version" || bare[0] === "-v"))
139
- return { kind: "version" };
140
- // The command path is the leading words that aren't flags; global flags may stand before it.
135
+ /**
136
+ * The command path's candidates: the leading words that aren't flags, with the global flags (and
137
+ * their values) that may stand before them skipped, and where each stands in `argv`.
138
+ */
139
+ function leadingWords(argv: readonly string[]): { words: string[]; pathAt: number[] } {
141
140
  const words: string[] = [];
142
141
  const pathAt: number[] = [];
143
142
  for (let index = 0; index < argv.length; index += 1) {
@@ -152,6 +151,21 @@ export function parseCommandLine(commands: readonly CommandDef[], argv: readonly
152
151
  words.push(word);
153
152
  pathAt.push(index);
154
153
  }
154
+ return { words, pathAt };
155
+ }
156
+
157
+ /** The words a command line starts its command with (`["mcp"]`, `["share", "stop", …]`). */
158
+ export function commandWords(argv: readonly string[]): string[] {
159
+ return leadingWords(argv).words;
160
+ }
161
+
162
+ /** Parses the command line against the definitions. Throws a usage diagnostic. */
163
+ export function parseCommandLine(commands: readonly CommandDef[], argv: readonly string[]): Parsed {
164
+ const bare = argv.filter((word) => word !== "--json");
165
+ if (bare.length === 1 && (bare[0] === "--version" || bare[0] === "-v"))
166
+ return { kind: "version" };
167
+ // The command path is the leading words that aren't flags; global flags may stand before it.
168
+ const { words, pathAt } = leadingWords(argv);
155
169
  const helpAsked = argv.includes("--help") || argv.includes("-h");
156
170
  if (words.length === 0) {
157
171
  if (helpAsked || argv.every((word) => word === "--json")) return { kind: "help" };
package/src/run.ts CHANGED
@@ -204,7 +204,8 @@ export async function run(io: RunnerIo): Promise<number> {
204
204
  json,
205
205
  tty: io.tty,
206
206
  readsStdin,
207
- quiet: command.quiet === true,
207
+ quiet:
208
+ typeof command.quiet === "function" ? command.quiet(parsed.flags) : command.quiet === true,
208
209
  hostHome: embeddedHome(marks),
209
210
  stderr: io.stderr,
210
211
  ask: (question, timeoutMs) => ask(io, question, timeoutMs),
@@ -276,11 +277,19 @@ export async function run(io: RunnerIo): Promise<number> {
276
277
  io.stderr(describe(diagnostic));
277
278
  },
278
279
  record: (event) => telemetry.record(event),
280
+ checkpoint(hostInstance) {
281
+ try {
282
+ telemetry.checkpoint({ hostInstance });
283
+ } catch {
284
+ // Telemetry never changes a command's outcome.
285
+ }
286
+ },
279
287
  runtime: (args, stdio = "pipe") => runRuntime(io, args, stdio),
280
288
  };
281
289
 
282
290
  let exit: number;
283
291
  let error: string | undefined;
292
+ let ownHostInstance = false;
284
293
  try {
285
294
  // Telemetry never stops a command: a failure in it is a run without telemetry.
286
295
  if (!(await telemetry.begin().catch(() => true))) return 130;
@@ -291,15 +300,18 @@ export async function run(io: RunnerIo): Promise<number> {
291
300
  () => startingDaemon,
292
301
  );
293
302
  exit = outcome.exit ?? EXIT.ok;
294
- if (outcome.raw) return exit;
295
- if (json) {
296
- writeJson({
297
- ok: true,
298
- result: outcome.result ?? null,
299
- ...(summary && !streamed && command.local !== true ? { instance: summary } : {}),
300
- warnings,
301
- });
302
- } else io.stdout(outcome.human ?? `${JSON.stringify(outcome.result, null, 2)}\n`);
303
+ ownHostInstance = outcome.hostInstance === true;
304
+ // A command that wrote its own stdout (`host`, `mcp`) gets no envelope and no text.
305
+ if (outcome.raw !== true) {
306
+ if (json) {
307
+ writeJson({
308
+ ok: true,
309
+ result: outcome.result ?? null,
310
+ ...(summary && !streamed && command.local !== true ? { instance: summary } : {}),
311
+ warnings,
312
+ });
313
+ } else io.stdout(outcome.human ?? `${JSON.stringify(outcome.result, null, 2)}\n`);
314
+ }
303
315
  } catch (caught) {
304
316
  const diagnostic = diagnosticOf(caught);
305
317
  error = diagnostic.code;
@@ -311,7 +323,7 @@ export async function run(io: RunnerIo): Promise<number> {
311
323
  telemetry.end({
312
324
  exit,
313
325
  durationMs: Date.now() - started,
314
- hostInstance: summary?.mode === "host",
326
+ hostInstance: summary?.mode === "host" || ownHostInstance,
315
327
  ...(error !== undefined ? { error } : {}),
316
328
  });
317
329
  } catch {
@@ -330,8 +342,7 @@ async function withTimeout(
330
342
  timeoutMs: number | undefined,
331
343
  startingDaemon: () => boolean,
332
344
  ): Promise<CommandOutcome> {
333
- if (timeoutMs === undefined || command.path[0] === "host" || command.path[0] === "dev")
334
- return command.run(context);
345
+ if (timeoutMs === undefined || UNBOUNDED.has(command.path[0] ?? "")) return command.run(context);
335
346
  let timer: ReturnType<typeof setTimeout> | undefined;
336
347
  try {
337
348
  return await Promise.race([
@@ -37,3 +37,27 @@ export function detectHarness(env: Environment): Harness {
37
37
  if (set(declared) || set(env["AGENT"])) return "other";
38
38
  return "none";
39
39
  }
40
+
41
+ /**
42
+ * The known agent an MCP client is, by the `clientInfo.name` it sends (D140 item 8, D164 item 4),
43
+ * as each was observed (VERIFIED_FACTS, WP-15): Claude Code sends `claude-code`, Codex
44
+ * `codex-mcp-client`. Any other name is `other`; the name itself is never sent, since it can name
45
+ * a private tool.
46
+ */
47
+ const MCP_CLIENTS: Readonly<Record<string, (typeof HARNESSES)[number]>> = {
48
+ "claude-code": "claude-code",
49
+ "codex-mcp-client": "codex",
50
+ };
51
+
52
+ /** `mcp.session`'s fields for a client: its agent's ID, and its version only for a known one. */
53
+ export function mcpSessionFields(client: { readonly name: string; readonly version?: string }): {
54
+ readonly client: (typeof HARNESSES)[number] | "other";
55
+ readonly clientVersion?: string;
56
+ } {
57
+ const known = Object.hasOwn(MCP_CLIENTS, client.name) ? MCP_CLIENTS[client.name] : undefined;
58
+ if (known === undefined) return { client: "other" };
59
+ const version = client.version;
60
+ return version !== undefined && /^[0-9A-Za-z.+-]{1,32}$/.test(version)
61
+ ? { client: known, clientVersion: version }
62
+ : { client: known };
63
+ }