@mostra/cli 0.10.0 → 0.11.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 (33) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/{flush-znWmNZA1.js → flush-D648gCYs.js} +2 -1
  3. package/dist/flush-D648gCYs.js.map +1 -0
  4. package/dist/index.js +1 -1
  5. package/dist/reference/cli.md +67 -1
  6. package/dist/reference/diagnostics.json +81 -0
  7. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  8. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  9. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  10. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  11. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  12. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  13. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  14. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  15. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  16. package/dist/reference/self-hosting.md +130 -0
  17. package/dist/run-Bpg_ZRY8.js +1 -0
  18. package/dist/{run-Aq4HVIY0.js → run-BxYL-DaX.js} +104 -215
  19. package/dist/run-BxYL-DaX.js.map +1 -0
  20. package/dist/skill/SKILL.md +4 -2
  21. package/dist/skill/references/mcp.md +8 -3
  22. package/dist/skill/references/sharing.md +1 -0
  23. package/dist/telemetry/flush-main.js +1 -1
  24. package/package.json +5 -5
  25. package/src/commands/admin.ts +2 -2
  26. package/src/commands/index.ts +3 -1
  27. package/src/commands/remote.ts +99 -3
  28. package/src/detached.ts +1 -0
  29. package/src/docs.ts +12 -217
  30. package/src/mcp.ts +3 -21
  31. package/dist/flush-znWmNZA1.js.map +0 -1
  32. package/dist/run-Aq4HVIY0.js.map +0 -1
  33. package/dist/run-D1U_RFEP.js +0 -1
@@ -4,7 +4,7 @@ description: Communicate visually with the user through Mostra. Use whenever sho
4
4
  license: Apache-2.0
5
5
  compatibility: Needs a shell that runs `mostra` (or `npx` with Node.js 22.19 or later) on macOS, Linux or Windows, x64 or arm64.
6
6
  metadata:
7
- version: "0.10.0"
7
+ version: "0.11.0"
8
8
  ---
9
9
 
10
10
  # Mostra
@@ -13,10 +13,12 @@ Mostra turns a React page you write into an **artifact**: a web page a person op
13
13
 
14
14
  ## Running Mostra
15
15
 
16
- Run `mostra <command>`. When `mostra` isn't on the `PATH`, run `npx -y @mostra/cli@0.10.0 <command>` everywhere this Skill says `mostra`; the first run downloads Mostra's own runtime (no global Node.js needed beyond `npx`). Every command takes `--json` (one JSON envelope on stdout, logs on stderr) and `--help`. `mostra docs <topic>` prints the reference, including every diagnostic code's page (`mostra docs MOSTRA_FIELD_DUPLICATE_ID`). `mostra list` lists the artifacts you've published, and `mostra status` shows the running instance.
16
+ Run `mostra <command>`. When `mostra` isn't on the `PATH`, run `npx -y @mostra/cli@0.11.0 <command>` everywhere this Skill says `mostra`; the first run downloads Mostra's own runtime (no global Node.js needed beyond `npx`). Every command takes `--json` (one JSON envelope on stdout, logs on stderr) and `--help`. `mostra docs <topic>` prints the reference, including every diagnostic code's page (`mostra docs MOSTRA_FIELD_DUPLICATE_ID`). `mostra list` lists the artifacts you've published, and `mostra status` shows the running instance.
17
17
 
18
18
  When Mostra's tools are in your tool list (`artifact_create`, `artifact_verify` and the rest), use them instead: each step below has its tool, and everything else here holds unchanged. See [references/mcp.md](references/mcp.md).
19
19
 
20
+ A link that starts with `http://127.0.0.1` opens only on the computer Mostra runs on. When you run in a cloud sandbox (a chat app's code execution, a remote container), the person can't open it: use Mostra's tools from a connector when you have them, and otherwise say so and offer to share the page ([references/sharing.md](references/sharing.md)).
21
+
20
22
  ## Words
21
23
 
22
24
  | Word | Meaning |
@@ -7,6 +7,7 @@
7
7
  - Files and directories
8
8
  - Waiting and results
9
9
  - Links for people
10
+ - Through a Mostra server in a chat app
10
11
  - Long-lived pages
11
12
  - Adding the server to a client
12
13
 
@@ -46,7 +47,11 @@ When you also have your own file tools on the same computer, use whichever you l
46
47
 
47
48
  `artifact_open` returns the artifact's default link. A link made without `viewer` is shared by everyone who holds it: they edit one draft and have one `once` submission between them. For several people, call `artifact_open` once per person with `viewer: { ref, name }` and give each their own link (with `{ policy: "once", scope: "per-viewer" }` each submits once). `ttl`, `scopes` and `version` make a new link that expires, allows less, or opens one version, as in [sharing.md](sharing.md). `open: true` also opens the link in a browser on this computer, for the person sitting at it.
48
49
 
49
- Links open on this computer only. To reach someone elsewhere, share it as [sharing.md](sharing.md) shows (`mostra share`).
50
+ A local server's links open on this computer only: to reach someone elsewhere, share the page as [sharing.md](sharing.md) shows. Through a Mostra server (a chat app's connector), links open anywhere: `artifact_publish` and `artifact_open` return the hosted link, `https://` and a server's address ending in `/a/rte_…`.
51
+
52
+ ## Through a Mostra server in a chat app
53
+
54
+ A chat app's connector reaches the person's own computer through their Mostra server. Creating, writing, verifying and publishing run there, in its workspace, so that computer must be on with Mostra running; otherwise those tools answer `MOSTRA_REMOTE_NO_INSTANCE`, while listing, waiting and reading results keep working. Answers people send wait on the server while that computer sleeps, and reach it when it's back.
50
55
 
51
56
  ## Long-lived pages
52
57
 
@@ -54,10 +59,10 @@ Links open on this computer only. To reach someone elsewhere, share it as [shari
54
59
 
55
60
  ## Adding the server to a client
56
61
 
57
- A client starts the server as `mostra mcp` over stdio, or `npx -y @mostra/cli@0.10.0 mcp` where `mostra` isn't installed. Its configuration names that command, for example:
62
+ A client starts the server as `mostra mcp` over stdio, or `npx -y @mostra/cli@0.11.0 mcp` where `mostra` isn't installed. Its configuration names that command, for example:
58
63
 
59
64
  ```json
60
- { "mcpServers": { "mostra": { "command": "npx", "args": ["-y", "@mostra/cli@0.10.0", "mcp"] } } }
65
+ { "mcpServers": { "mostra": { "command": "npx", "args": ["-y", "@mostra/cli@0.11.0", "mcp"] } } }
61
66
  ```
62
67
 
63
68
  For a client that speaks only HTTP, `mostra mcp --http` serves Streamable HTTP on `127.0.0.1` and prints its URL and a token on stderr; every request sends `Authorization: Bearer <token>` (set `MOSTRA_MCP_TOKEN` to choose it). `--workspace <dir>` chooses where new artifacts go.
@@ -59,6 +59,7 @@ mostra logout # sign out; hosted pages keep working,
59
59
  - Only the source, its versions and its secrets stay on this machine; the server holds the built page and what people enter.
60
60
  - Several machines can sign in to one account. The one that shared a page receives its answers. `mostra login <server> --default` makes this machine the one pages created from a chat app go to.
61
61
  - `mostra share stop` and `mostra share list` include hosted shares.
62
+ - `mostra pause ./x --reason "Closed until Monday"` stops a page taking answers and running actions, here and on every server it's hosted on; it stays viewable, its links keep working, and the draft people typed is kept. `mostra resume ./x` opens it again. A pause the server's operator made can only be lifted by the operator.
62
63
 
63
64
  ### Actions on a hosted page
64
65
 
@@ -1,4 +1,4 @@
1
- import { r as TelemetryStore, t as flush } from "../flush-znWmNZA1.js";
1
+ import { r as TelemetryStore, t as flush } from "../flush-D648gCYs.js";
2
2
  //#region src/telemetry/flush-main.ts
3
3
  /**
4
4
  * The flusher process (D140 item 6): `node flush-main.js <config dir>`, started detached by the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/cli",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "The mostra command: author, verify, publish, share and wait on agent artifacts, as a thin client of the Mostra host protocol.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -36,16 +36,16 @@
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.1.5",
38
38
  "@modelcontextprotocol/server": "2.4.0",
39
- "@mostra/mcp": "0.10.0",
40
- "@mostra/protocol": "0.10.0",
41
- "@mostra/sdk": "0.10.0",
39
+ "@mostra/mcp": "0.11.0",
40
+ "@mostra/protocol": "0.11.0",
41
+ "@mostra/sdk": "0.11.0",
42
42
  "zod": "4.6.7"
43
43
  },
44
44
  "devDependencies": {
45
45
  "@modelcontextprotocol/client": "2.4.0",
46
46
  "@modelcontextprotocol/conformance": "0.1.16",
47
47
  "@modelcontextprotocol/conformance-next": "npm:@modelcontextprotocol/conformance@0.2.0-alpha.12",
48
- "@mostra/runtime": "0.10.0",
48
+ "@mostra/runtime": "0.11.0",
49
49
  "@mostra/tools": "0.0.0",
50
50
  "@types/node": "24.19.2",
51
51
  "tsdown": "0.23.1",
@@ -23,7 +23,7 @@ import {
23
23
  } from "@mostra/protocol";
24
24
  import { checkBrowser, checkFiles, enclosingBundle, readBundle, readSetup } from "@mostra/sdk";
25
25
  import { type CommandContext, type CommandDef, defineCommand } from "../command.ts";
26
- import { docsIndex, indexMarkdown, nearestTopics, topicMarkdown } from "../docs.ts";
26
+ import { docsIndex, indexMarkdown, nearestTopics, skillDir, topicMarkdown } from "../docs.ts";
27
27
  import { EXIT, exitCodeFor } from "../exit.ts";
28
28
  import { embeddedHome, locateRuntime, readHomeMarks } from "../home.ts";
29
29
  import { usage } from "../parse.ts";
@@ -713,7 +713,7 @@ export const docsCommand: CommandDef = defineCommand({
713
713
  `No topic "${wanted}". The nearest: ${nearestTopics(wanted, topics).join(", ")}. Run "mostra docs" for the index.`,
714
714
  );
715
715
  }
716
- const markdown = topicMarkdown(found);
716
+ const markdown = topicMarkdown(found, skillDir());
717
717
  return { result: { topic: found.topic, markdown, url: found.url }, human: markdown };
718
718
  },
719
719
  });
@@ -43,7 +43,7 @@ import {
43
43
  waitCommand,
44
44
  } from "./interaction.ts";
45
45
  import { mcpCommand } from "./mcp.ts";
46
- import { loginCommand, logoutCommand } from "./remote.ts";
46
+ import { loginCommand, logoutCommand, pauseCommand, resumeCommand } from "./remote.ts";
47
47
  import { shareCommand, shareListCommand, shareStopCommand } from "./sharing.ts";
48
48
  import { openCommand } from "./viewing.ts";
49
49
 
@@ -59,6 +59,8 @@ export const COMMANDS: readonly CommandDef[] = [
59
59
  shareListCommand,
60
60
  loginCommand,
61
61
  logoutCommand,
62
+ pauseCommand,
63
+ resumeCommand,
62
64
  waitCommand,
63
65
  resultsCommand,
64
66
  stateGetCommand,
@@ -3,12 +3,23 @@
3
3
  * remote server by the OAuth device authorization grant, so `mostra share --cloud` can host its
4
4
  * artifacts there, and signs out again. The instance keeps the refresh token in the home,
5
5
  * owner-only; signing out keeps its instance link, so the artifacts it shared stay its own at the
6
- * next sign-in, unless `--forget`. Clients of `remote/login`, `remote/login.wait` and
7
- * `remote/logout`.
6
+ * next sign-in, unless `--forget`. With `--key-file`, a machine links with a key the server's
7
+ * operator issued instead (`remote/link`, D167). Clients of `remote/login`, `remote/login.wait`,
8
+ * `remote/link` and `remote/logout`.
8
9
  */
9
- import { remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod } from "@mostra/protocol";
10
+ import { readFileSync } from "node:fs";
11
+ import { resolve } from "node:path";
12
+ import {
13
+ artifactPauseMethod,
14
+ remoteLinkMethod,
15
+ remoteLoginMethod,
16
+ remoteLoginWaitMethod,
17
+ remoteLogoutMethod,
18
+ } from "@mostra/protocol";
10
19
  import { type CommandDef, defineCommand } from "../command.ts";
11
20
  import { EXIT } from "../exit.ts";
21
+ import { usage } from "../parse.ts";
22
+ import { arg, artifactRef, flag } from "./shared.ts";
12
23
 
13
24
  /** How long `mostra login` waits for the person to approve, in all (the code lives 10 minutes). */
14
25
  const LOGIN_WAIT_MS = 10 * 60_000;
@@ -35,12 +46,41 @@ export const loginCommand: CommandDef = defineCommand({
35
46
  summary:
36
47
  "Make this machine the account's default, the one chat apps create pages on. Default: the first machine linked.",
37
48
  },
49
+ {
50
+ name: "key-file",
51
+ kind: "string",
52
+ summary:
53
+ "Link with a key the server's operator issued for an account, read from this file, instead of a person's sign-in (for an always-on machine).",
54
+ },
38
55
  ],
39
56
  output: { type: "RemoteLoginWaitResult", topic: "cli" },
40
57
  exits: [EXIT.failure, EXIT.environment],
41
58
  example: "login https://api.example.com",
42
59
  async run(context) {
43
60
  const server = context.args["server"];
61
+ // An operator-issued key, from a file: never on the command line, which every local user sees.
62
+ const keyFile = flag(context, "key-file");
63
+ if (keyFile !== undefined) {
64
+ if (typeof server !== "string")
65
+ throw usage("Name the server the key is for: mostra login <server> --key-file <file>.");
66
+ let key: string;
67
+ try {
68
+ key = readFileSync(resolve(context.cwd, keyFile), "utf8").trim();
69
+ } catch (error) {
70
+ throw usage(
71
+ `--key-file ${keyFile} can't be read (${(error as NodeJS.ErrnoException).code ?? "error"}).`,
72
+ );
73
+ }
74
+ const linked = await context.call(remoteLinkMethod, {
75
+ server: server.replace(/\/+$/, ""),
76
+ key,
77
+ ...(context.flags["default"] === true ? { default: true } : {}),
78
+ });
79
+ return {
80
+ result: { status: "signed-in", ...linked },
81
+ human: `Linked to ${linked.server} for ${linked.account.name ?? linked.account.id} with the operator's key. This machine is ${linked.instanceId}.\n`,
82
+ };
83
+ }
44
84
  const started = await context.call(remoteLoginMethod, {
45
85
  ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
46
86
  ...(context.flags["default"] === true ? { default: true } : {}),
@@ -111,3 +151,59 @@ export const logoutCommand: CommandDef = defineCommand({
111
151
  };
112
152
  },
113
153
  });
154
+
155
+ /** `mostra pause <artifact> [--reason <text>]` (D165 item 14). */
156
+ export const pauseCommand: CommandDef = defineCommand({
157
+ path: ["pause"],
158
+ summary:
159
+ "Pause an artifact: its pages stay viewable and its links valid, but it takes no answers and runs no actions until resumed.",
160
+ args: [{ name: "artifact", summary: "The artifact: its source path or its ID." }],
161
+ flags: [
162
+ {
163
+ name: "reason",
164
+ kind: "string",
165
+ summary: "Why, shown to the page's viewers beside the paused notice.",
166
+ },
167
+ ],
168
+ output: { type: "ArtifactPauseResult", topic: "cli" },
169
+ exits: [EXIT.failure, EXIT.environment],
170
+ example: 'pause ./survey --reason "Closed for review until Monday"',
171
+ async run(context) {
172
+ const reason = flag(context, "reason");
173
+ const result = await context.call(artifactPauseMethod, {
174
+ artifact: artifactRef(arg(context, "artifact"), context.cwd),
175
+ paused: true,
176
+ ...(reason !== undefined ? { reason } : {}),
177
+ });
178
+ return {
179
+ result,
180
+ human:
181
+ result.by === "operator"
182
+ ? "Paused. The server's operator paused it too, and only the operator resumes that.\n"
183
+ : "Paused. Pages stay viewable; answers and actions wait until mostra resume.\n",
184
+ };
185
+ },
186
+ });
187
+
188
+ /** `mostra resume <artifact>` (D165 item 14). */
189
+ export const resumeCommand: CommandDef = defineCommand({
190
+ path: ["resume"],
191
+ summary: "Resume a paused artifact: it takes answers and runs actions again.",
192
+ args: [{ name: "artifact", summary: "The artifact: its source path or its ID." }],
193
+ output: { type: "ArtifactPauseResult", topic: "cli" },
194
+ exits: [EXIT.failure, EXIT.environment],
195
+ example: "resume ./survey",
196
+ async run(context) {
197
+ const result = await context.call(artifactPauseMethod, {
198
+ artifact: artifactRef(arg(context, "artifact"), context.cwd),
199
+ paused: false,
200
+ });
201
+ return {
202
+ result,
203
+ human: result.paused
204
+ ? "Still paused: the server's operator paused it, and only the operator resumes that.\n"
205
+ : "Resumed. The artifact takes answers and runs actions again.\n",
206
+ ...(result.paused ? { exit: EXIT.failure } : {}),
207
+ };
208
+ },
209
+ });
package/src/detached.ts CHANGED
@@ -28,6 +28,7 @@ export const PATH_VARIABLES: readonly string[] = [
28
28
  "MOSTRA_TEST_NETWORK_FILESYSTEM",
29
29
  "MOSTRA_TEST_BINDING_TRACE",
30
30
  "MOSTRA_TEST_BUNDLE_PINS",
31
+ "MOSTRA_TEST_VERIFY_FAIL_ONCE",
31
32
  "MOSTRA_TAILSCALE",
32
33
  "MOSTRA_CLOUDFLARED",
33
34
  "MOSTRA_TEST_TUNNELS",
package/src/docs.ts CHANGED
@@ -5,28 +5,11 @@
5
5
  * `guide` and `guide/<name>`, so an agent whose harness has no Skill reads the same text through
6
6
  * the CLI. This index is the one source WP-15's `docs_search` and WP-26's site read.
7
7
  */
8
- import { existsSync, readdirSync, readFileSync } from "node:fs";
9
- import { extname, join } from "node:path";
10
- import { DEFAULT_DOCS_BASE } from "@mostra/protocol";
8
+ import { existsSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { type DocsTopic, docsIndex as indexOf } from "@mostra/mcp";
11
11
  import { fromSource, packageRoot } from "./version.ts";
12
12
 
13
- /** One topic of the reference. */
14
- export interface DocsTopic {
15
- /** Its stable slug: `cli`, `telemetry`, a diagnostic code, `guide` or `guide/<name>`. */
16
- readonly topic: string;
17
- /** Its title, from the page's first heading. */
18
- readonly title: string;
19
- /** Where the docs site serves it. */
20
- readonly url: string;
21
- /** Its Markdown file, or a guide topic's first file. */
22
- readonly file: string;
23
- /**
24
- * A guide topic that isn't one Markdown page (a stylesheet, an example): its files, relative to
25
- * the Skill's `assets/`, each shown as code.
26
- */
27
- readonly files?: readonly string[];
28
- }
29
-
30
13
  /** Where the reference is: bundled in the build (`dist/reference`), or the repository's. */
31
14
  export function referenceDir(): string {
32
15
  const bundled = join(packageRoot(), "dist", "reference");
@@ -43,203 +26,15 @@ export function skillDir(): string {
43
26
  : join(packageRoot(), "..", "..", "skills", "mostra");
44
27
  }
45
28
 
46
- function titleOf(file: string): string {
47
- const first = readFileSync(file, "utf8")
48
- .split("\n")
49
- .find((line) => line.startsWith("# "));
50
- return first ? first.slice(2).trim() : "";
51
- }
52
-
53
- /** Every topic, the pages first and then the codes, sorted. */
29
+ /** Every topic of the reference this CLI ships, the pages first and then the codes, sorted. */
54
30
  export function docsIndex(dir: string = referenceDir()): DocsTopic[] {
55
- const base = DEFAULT_DOCS_BASE.replace(/\/+$/, "");
56
- const pages: DocsTopic[] = [];
57
- for (const topic of ["cli", "telemetry"]) {
58
- const file = join(dir, `${topic}.md`);
59
- if (existsSync(file))
60
- pages.push({ topic, title: titleOf(file), url: `${base}/${topic}`, file });
61
- }
62
- const errorsDir = join(dir, "errors");
63
- const codes = existsSync(errorsDir)
64
- ? readdirSync(errorsDir)
65
- .filter((name) => /^MOSTRA_[A-Z0-9_]+\.md$/.test(name))
66
- .sort()
67
- : [];
68
- const errors: DocsTopic[] = codes.map((name) => {
69
- const code = name.slice(0, -3);
70
- const file = join(errorsDir, name);
71
- return { topic: code, title: titleOf(file), url: `${base}/errors/${code}`, file };
72
- });
73
- return [...pages, ...guideTopics(skillDir(), base), ...errors];
74
- }
75
-
76
- const byName = (a: { name: string }, b: { name: string }): number => (a.name < b.name ? -1 : 1);
77
-
78
- /** Every file below `root`'s `prefix`, relative to `root`, sorted. */
79
- function filesBelow(root: string, prefix: string): string[] {
80
- return readdirSync(join(root, prefix), { withFileTypes: true })
81
- .sort(byName)
82
- .flatMap((entry) => {
83
- const path = `${prefix}/${entry.name}`;
84
- return entry.isDirectory() ? filesBelow(root, path) : [path];
85
- });
86
- }
87
-
88
- /**
89
- * The Skill as topics: `guide` (its SKILL.md), `guide/<name>` for each reference,
90
- * `guide/<file>` for each asset (the baseline stylesheet), and `guide/examples/<name>` for each
91
- * example, every file of it.
92
- */
93
- export function guideTopics(dir: string, base: string): DocsTopic[] {
94
- const skill = join(dir, "SKILL.md");
95
- if (!existsSync(skill)) return [];
96
- const topics: DocsTopic[] = [
97
- { topic: "guide", title: "Using Mostra", url: `${base}/guide`, file: skill },
98
- ];
99
- const references = join(dir, "references");
100
- if (existsSync(references)) {
101
- for (const name of readdirSync(references)
102
- .filter((entry) => entry.endsWith(".md"))
103
- .sort()) {
104
- const file = join(references, name);
105
- const slug = name.slice(0, -3);
106
- topics.push({
107
- topic: `guide/${slug}`,
108
- title: titleOf(file),
109
- url: `${base}/guide/${slug}`,
110
- file,
111
- });
112
- }
113
- }
114
- const assets = join(dir, "assets");
115
- if (!existsSync(assets)) return topics;
116
- for (const entry of readdirSync(assets, { withFileTypes: true }).sort(byName)) {
117
- if (!entry.isFile()) continue;
118
- topics.push({
119
- topic: `guide/${entry.name}`,
120
- title: entry.name,
121
- url: `${base}/guide/${entry.name}`,
122
- file: join(assets, entry.name),
123
- files: [entry.name],
124
- });
125
- }
126
- const examples = join(assets, "examples");
127
- if (!existsSync(examples)) return topics;
128
- for (const entry of readdirSync(examples, { withFileTypes: true }).sort(byName)) {
129
- if (!entry.isDirectory()) continue;
130
- const files = filesBelow(assets, `examples/${entry.name}`);
131
- if (files.length === 0) continue;
132
- topics.push({
133
- topic: `guide/examples/${entry.name}`,
134
- title: `Example: ${entry.name}`,
135
- url: `${base}/guide/examples/${entry.name}`,
136
- file: join(assets, files[0] as string),
137
- files,
138
- });
139
- }
140
- return topics;
31
+ return indexOf(dir, skillDir());
141
32
  }
142
33
 
143
- const FENCE_LANGUAGES: Readonly<Record<string, string>> = {
144
- ".css": "css",
145
- ".json": "json",
146
- ".md": "md",
147
- ".mdx": "mdx",
148
- ".ts": "ts",
149
- ".tsx": "tsx",
150
- };
151
-
152
- /** How the guide's relative links read through the CLI, before each of its pages. */
153
- export const GUIDE_LINKS: string =
154
- "> Read through `mostra docs`: a link to `references/<name>.md` is `mostra docs guide/<name>`, `assets/<file>` is `mostra docs guide/<file>`, and `assets/examples/<name>/` is `mostra docs guide/examples/<name>`.";
155
-
156
- /** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */
157
- export const MCP_GUIDE_LINKS: string =
158
- "> Read through Mostra's MCP server: a link to `references/<name>.md` is the topic `guide/<name>`, `assets/<file>` is `guide/<file>`, and `assets/examples/<name>/` is `guide/examples/<name>`; read one with docs_search (`topic`) or the resource `mostra://docs/<topic>`. Where the guide runs a `mostra` command, use the tool of the same step (artifact_verify for `mostra verify`, artifact_wait for `mostra wait`).";
159
-
160
- /**
161
- * A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the
162
- * CLI by default, or `links`); a guide topic made of files shows each one as code under its path.
163
- */
164
- export function topicMarkdown(
165
- topic: DocsTopic,
166
- dir: string = skillDir(),
167
- links: string = GUIDE_LINKS,
168
- ): string {
169
- if (topic.files !== undefined) {
170
- const parts = topic.files.map((path) => {
171
- const text = readFileSync(join(dir, "assets", path), "utf8");
172
- const fence = text.includes("```") ? "````" : "```";
173
- const body = text.endsWith("\n") ? text : `${text}\n`;
174
- return `## \`${path}\`\n\n${fence}${FENCE_LANGUAGES[extname(path)] ?? ""}\n${body}${fence}\n`;
175
- });
176
- return [`# ${topic.title}`, "", links, "", ...parts].join("\n");
177
- }
178
- const text = readFileSync(topic.file, "utf8");
179
- if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
180
- return [links, "", text.replace(/^---\n[\s\S]*?\n---\n+/, "")].join("\n");
181
- }
182
-
183
- /** The index as Markdown: what `mostra docs` prints without a topic. */
184
- export function indexMarkdown(topics: readonly DocsTopic[]): string {
185
- const pages = topics.filter(
186
- (topic) => !topic.topic.startsWith("MOSTRA_") && !topic.topic.startsWith("guide"),
187
- );
188
- const guide = topics.filter(
189
- (topic) => topic.topic === "guide" || topic.topic.startsWith("guide/"),
190
- );
191
- const codes = topics.filter((topic) => topic.topic.startsWith("MOSTRA_"));
192
- return [
193
- "# Mostra reference",
194
- "",
195
- "Run `mostra docs <topic>` to read one. Diagnostic codes are topics too.",
196
- "",
197
- ...pages.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
198
- "",
199
- ...(guide.length > 0
200
- ? [
201
- "## Writing artifacts",
202
- "",
203
- ...guide.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
204
- "",
205
- ]
206
- : []),
207
- "## Diagnostic codes",
208
- "",
209
- ...codes.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
210
- "",
211
- ].join("\n");
212
- }
213
-
214
- /** The topics nearest an unknown one, for its usage error. */
215
- export function nearestTopics(wanted: string, topics: readonly DocsTopic[], count = 3): string[] {
216
- const target = wanted.toUpperCase();
217
- const scored = topics.map((topic) => {
218
- const name = topic.topic.toUpperCase();
219
- const contains = name.includes(target) || target.includes(name) ? 0 : 1;
220
- return { topic: topic.topic, score: contains * 100 + distance(name, target) };
221
- });
222
- return scored
223
- .sort((a, b) => a.score - b.score || (a.topic < b.topic ? -1 : 1))
224
- .slice(0, count)
225
- .map((item) => item.topic);
226
- }
227
-
228
- /** Levenshtein distance. */
229
- function distance(a: string, b: string): number {
230
- const row = Array.from({ length: b.length + 1 }, (_, index) => index);
231
- for (let i = 1; i <= a.length; i += 1) {
232
- let previous = row[0] as number;
233
- row[0] = i;
234
- for (let j = 1; j <= b.length; j += 1) {
235
- const current = row[j] as number;
236
- row[j] = Math.min(
237
- (row[j] as number) + 1,
238
- (row[j - 1] as number) + 1,
239
- previous + (a[i - 1] === b[j - 1] ? 0 : 1),
240
- );
241
- previous = current;
242
- }
243
- }
244
- return row[b.length] as number;
245
- }
34
+ export {
35
+ type DocsTopic,
36
+ indexMarkdown,
37
+ MCP_GUIDE_LINKS,
38
+ nearestTopics,
39
+ topicMarkdown,
40
+ } from "@mostra/mcp";
package/src/mcp.ts CHANGED
@@ -14,7 +14,7 @@ import { serveStdio } from "@modelcontextprotocol/server/stdio";
14
14
  import {
15
15
  createHttpEndpoint,
16
16
  createMcpServerFactory,
17
- type DocsTopicSummary,
17
+ fileDocs,
18
18
  localWorkspace,
19
19
  MCP_PATH,
20
20
  type McpClientInfo,
@@ -32,7 +32,7 @@ import { resolveRuntime } from "@mostra/sdk";
32
32
  import { progressReporter } from "./bootstrap.ts";
33
33
  import { openInBrowser } from "./browser.ts";
34
34
  import { connect, type InstanceConnection } from "./client.ts";
35
- import { docsIndex, MCP_GUIDE_LINKS, skillDir, topicMarkdown } from "./docs.ts";
35
+ import { MCP_GUIDE_LINKS, referenceDir, skillDir } from "./docs.ts";
36
36
  import type { Environment } from "./home.ts";
37
37
 
38
38
  /** How long the session with the daemon stays open after the last call. */
@@ -238,25 +238,7 @@ export function daemonInstance(options: {
238
238
 
239
239
  /** The bundled reference (`mostra docs`), read as the MCP server's docs. */
240
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
- };
241
+ return fileDocs({ referenceDir: referenceDir(), skillDir: skillDir(), links: MCP_GUIDE_LINKS });
260
242
  }
261
243
 
262
244
  /** What both transports are given. */