@mostra/cli 0.7.0 → 0.8.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.
@@ -0,0 +1,146 @@
1
+ # Server code: actions, secrets and side effects
2
+
3
+ ## Contents
4
+
5
+ - Server functions
6
+ - Actions: `useAction`
7
+ - Side effects that happen once
8
+ - Secrets
9
+ - What server code can use: `@mostra/server`
10
+ - Verify and `dryRun()`
11
+ - Limits and crashes
12
+
13
+ ## Server functions
14
+
15
+ Any module whose first statement is `"use server"` runs on this machine, in a worker process of its own, with full Node.js: files, processes, the network, any npm package. It exports only async functions (async generators too). The page imports them like ordinary functions; Mostra sends the call to the worker.
16
+
17
+ ```ts
18
+ // actions.ts
19
+ "use server";
20
+ import { readFile } from "node:fs/promises";
21
+
22
+ export async function loadReport(name: string) {
23
+ return JSON.parse(await readFile(`data/${name}.json`, "utf8")); // relative to the artifact's directory
24
+ }
25
+ ```
26
+
27
+ ```tsx
28
+ // index.tsx
29
+ import { useState } from "react";
30
+ import { loadReport } from "./actions";
31
+
32
+ function Report() {
33
+ const [report, setReport] = useState<unknown>();
34
+ return <button onClick={async () => setReport(await loadReport("q3"))}>Load the Q3 report</button>;
35
+ }
36
+ ```
37
+
38
+ - Arguments and results are what React's Server Functions accept: JSON values, `Date`, `Map`, `Set`, `BigInt`, typed arrays, `FormData`, `File`, promises, plus async iterables as results. Functions and class instances don't cross (`MOSTRA_ACTION_UNSERIALIZABLE`).
39
+ - A thrown error reaches the page as a `MostraError` with `code: "MOSTRA_ACTION_THREW"` and the error's message; its stack goes to the run's log.
40
+ - Calling a function directly is a plain call: nothing is recorded, and a reload forgets it. Use it to read things. For anything that changes the world, use an action.
41
+
42
+ ## Actions: `useAction`
43
+
44
+ `useAction` makes every call a recorded **run** with progress, a log, a final state, and cancellation:
45
+
46
+ ```tsx
47
+ import { useAction } from "@mostra/react";
48
+ import { sendReply } from "./actions";
49
+
50
+ function Reply({ email, body }: { email: { id: string }; body: string }) {
51
+ const send = useAction(sendReply, { key: `reply-${email.id}` });
52
+ return (
53
+ <button disabled={send.isPending || send.status === "succeeded"} onClick={() => void send.run(email.id, body)}>
54
+ {send.status === "succeeded" ? "Sent" : send.isPending ? send.progress?.message ?? "Sending…" : "Send"}
55
+ </button>
56
+ );
57
+ }
58
+ ```
59
+
60
+ - **Without a `key`**, a second call while the first runs joins it, so a double click runs once.
61
+ - **With a `key`**, the run happens at most once, ever: every click, tab, reload and viewer with that key joins the same run and sees its progress and result. A run that failed stays failed; a new attempt needs a new key (`reply-${email.id}-retry-1`).
62
+ - The handle has `status` (`idle`, `queued`, `running`, `succeeded`, `failed`, `cancelled`), `isPending`, `data`, `error` (`{ code, message }`), `progress` (`{ fraction?, message? }`), `log`, `partial` (the items an async-iterable result yielded so far), `runId` and `cancel()`.
63
+ - `run()` resolves with the result or rejects with a `MostraError` whose `code` says why (`MOSTRA_ACTION_THREW`, `MOSTRA_ACTION_CANCELLED`, `MOSTRA_ACTION_INTERRUPTED`, `MOSTRA_RUNTIME_WORKER_PARKED`).
64
+ - A run keeps going when the tab closes. A page that loads later finds a keyed run again by its key.
65
+ - Results list the runs started in the submitting view, so you can see what the person did.
66
+
67
+ ## Side effects that happen once
68
+
69
+ A run cut off by a crash or a restart ends `failed` with `MOSTRA_ACTION_INTERRUPTED`, and Mostra never retries it: the email may or may not have gone. So for any external side effect, pass an idempotency key the provider understands, derived from the run's key, so the provider drops a repeat:
70
+
71
+ ```ts
72
+ "use server";
73
+ import { abortSignal, progress, secret } from "@mostra/server";
74
+
75
+ export async function sendReply(emailId: string, body: string) {
76
+ progress({ message: "Sending…" });
77
+ const response = await fetch("https://api.mail.example/v1/send", {
78
+ method: "POST",
79
+ headers: {
80
+ authorization: `Bearer ${secret("MAIL_TOKEN")}`,
81
+ "idempotency-key": `reply-${emailId}`, // the same key the page gave useAction
82
+ "content-type": "application/json",
83
+ },
84
+ body: JSON.stringify({ inReplyTo: emailId, body }),
85
+ signal: abortSignal, // cancel() aborts the request
86
+ });
87
+ if (!response.ok) throw new Error(`The mail service answered ${response.status}`);
88
+ return { sent: true };
89
+ }
90
+ ```
91
+
92
+ ## Secrets
93
+
94
+ Keep keys and tokens out of the source. Mostra stores each one in its home, read from stdin:
95
+
96
+ ```sh
97
+ mostra secret set MAIL_TOKEN --artifact ./inbox < mail-token.txt # this artifact only
98
+ mostra secret set CALENDAR_KEY < calendar-key.txt # every artifact in this home
99
+ mostra secret list --artifact ./inbox # names only, never values
100
+ mostra secret rm MAIL_TOKEN --artifact ./inbox # remove it
101
+ ```
102
+
103
+ Server code reads it with `secret("MAIL_TOKEN")`, synchronously; a missing one throws `MOSTRA_SECRET_MISSING`. Mostra redacts every value it hands out from logs, run logs, errors, events, results and live values, so returning or logging one shows `[redacted]`. A secret is the person's to store: ask them to run `mostra secret set` themselves, and never ask for the value in the conversation or in a page field.
104
+
105
+ ## What server code can use
106
+
107
+ Import these from `@mostra/server` inside a `"use server"` function or a live source:
108
+
109
+ | Function | Does |
110
+ |---|---|
111
+ | `progress({ fraction?, message? })` | Shows progress on the page's run |
112
+ | `log(line)` | Adds a line to the run's log (`console.log` goes there too) |
113
+ | `abortSignal` | Aborts when the run is cancelled; pass it to `fetch` and child processes |
114
+ | `secret(name)` | Reads a secret |
115
+ | `viewer()` | The person who called: `{ id, name? }` |
116
+ | `signal(name, payload?)` | Raises a signal you can `mostra wait <dir> --until signal:<name>` for |
117
+ | `emit("host.<name>", payload?)` | An event for the program hosting Mostra; pages never see it |
118
+ | `state.get(id)`, `state.set(id, value)`, `state.patch(ops)` | Reads and writes the artifact's shared fields ([long-lived.md](long-lived.md)) |
119
+ | `dryRun()` | True only while verify exercises the page |
120
+ | `defineLive` | Defines a live source in `live.ts` ([long-lived.md](long-lived.md)) |
121
+
122
+ Errors these throw are `MostraServerError`s with a `code`.
123
+
124
+ ## Verify and `dryRun()`
125
+
126
+ Verify clicks through the page but never runs a server function unless that function opts in by checking `dryRun()`:
127
+
128
+ ```ts
129
+ "use server";
130
+ import { dryRun } from "@mostra/server";
131
+
132
+ export async function archiveEmail(emailId: string) {
133
+ if (dryRun()) return { archived: emailId }; // verify: nothing archived, a realistic answer
134
+ // …archive it for real, then:
135
+ return { archived: emailId };
136
+ }
137
+ ```
138
+
139
+ A function that doesn't opt in is refused in verify, its click gets `MOSTRA_VERIFY_ACTION_SKIPPED` (a hint), and the verdict lists it under skipped actions. Opt in when the page's behavior after the action matters to what verify should see; keep real side effects behind the check.
140
+
141
+ ## Limits and crashes
142
+
143
+ - Arguments and results up to 16 MiB each, a run's log 1 MB, signals 64 KiB.
144
+ - A worker has a 1 GiB heap and is stopped when its event loop is blocked for 10 s; change them in the manifest's `limits` (`heapMb`, `watchdogMs`).
145
+ - A crashed worker restarts with backoff. After more than five crashes in ten minutes it stops (`MOSTRA_RUNTIME_WORKER_PARKED`, and the page says the server code keeps crashing); publish a fix to clear it.
146
+ - Workers stop after 10 idle minutes and start again on the next call. Keep nothing in module variables that must survive; use shared state or files.
@@ -0,0 +1,72 @@
1
+ # Sharing: links, people and devices
2
+
3
+ ## Contents
4
+
5
+ - The link
6
+ - One person, one link
7
+ - The three setups: local, tailnet share, public share
8
+ - Behind a public quick tunnel
9
+ - Managing links and shares
10
+ - Asking people well
11
+
12
+ ## The link
13
+
14
+ `mostra publish` prints the artifact's **default link**; `mostra open <dir>` prints it again and opens it in a browser when run at a terminal (`--no-browser` only prints it). The link is a capability URL: whoever holds it can view, answer, submit and run the page's actions. The secret is after the `#`, so it never reaches a server log, but treat the whole link like a password.
15
+
16
+ The default link doesn't expire and stays the same across versions. It opens on this machine only (`http://127.0.0.1:…`).
17
+
18
+ ## One person, one link
19
+
20
+ A link without a named person acts as one person: everyone who holds the default link shares one draft and one `once` submission. When several people should answer, mint one link per person:
21
+
22
+ ```sh
23
+ mostra open ./retro --new --viewer ada@example.com --viewer-name "Ada Lovelace" --no-browser
24
+ mostra open ./retro --new --viewer grace@example.com --viewer-name "Grace Hopper" --no-browser
25
+ ```
26
+
27
+ `--viewer` is your own stable key for the person (an email, a user ID); the same key always means the same person, and results name them. Use `{ policy: "once", scope: "per-viewer" }` so each of them submits once.
28
+
29
+ Other options of `mostra open <dir> --new`: `--ttl 24h` (the link expires), `--scope view` (look but not answer; also `draft`, `submit`, `review`, `signal`, `action:*`), `--version 3` (only that version).
30
+
31
+ ## The three setups
32
+
33
+ | Setup | Who can open it | Command |
34
+ |---|---|---|
35
+ | **Local** | Only this machine's browser | `mostra open <dir>` |
36
+ | **Tailnet share** | People and devices in your Tailscale network, such as your phone | `mostra share <dir> --tailnet` |
37
+ | **Public share** | Anyone with the link, on any device | `mostra share <dir> --public` |
38
+
39
+ - **Tailnet share** uses Tailscale Serve. Each person is their tailnet identity, so results name them without `--viewer`. The link doesn't expire unless you give `--ttl`. The output names the two ports the tailnet's access policy must allow, and the viewer's device must run Tailscale.
40
+ - **Public share** uses a Cloudflare quick tunnel by default (no account needed), or Tailscale Funnel with `--via funnel` (the URL shows your device's tailnet name). The link lasts 1 hour unless `--ttl` says otherwise, 7 days at most. Each public link is a visitor of its own: their answers never mix with yours or anyone else's, and results show them as "Shared link" unless you pass `--viewer`.
41
+ - Both drive tools installed on this machine (`tailscale`, `cloudflared`); when one is missing or signed out, the command says how to install or enable it (`MOSTRA_SHARE_TOOL_MISSING`, `MOSTRA_SHARE_TOOL_NOT_READY`, `MOSTRA_SHARE_NOT_ENABLED`).
42
+ - A share keeps Mostra running while it lasts. A quick tunnel can't keep its address across a restart, so a public Cloudflare share ends when Mostra restarts; tailnet and Funnel shares come back.
43
+
44
+ ## Behind a public quick tunnel
45
+
46
+ Over a Cloudflare quick tunnel the page runs in a slightly different mode, and nothing in your code needs to change for it:
47
+
48
+ - updates arrive by polling rather than streaming, so other people's edits and live values show up a second or two later;
49
+ - a streamed result (an async iterable) arrives in one piece at the end;
50
+ - the page can't register a service worker of its own (`MOSTRA_HYGIENE_FRAME_SESSION`).
51
+
52
+ ## Managing links and shares
53
+
54
+ ```sh
55
+ mostra share list # active shares, with their links
56
+ mostra share list --all # ended ones too, and why
57
+ mostra share stop <shareId> # or the artifact, for all of its shares; the link stops working
58
+ mostra open ./x --rotate <tokenId> # replace a link that leaked; the old one stops working
59
+ mostra open ./x --revoke <tokenId> # stop a link
60
+ ```
61
+
62
+ `--json` output carries each link's `tokenId`.
63
+
64
+ ## Asking people well
65
+
66
+ The link arrives as a message from you, so write it like one:
67
+
68
+ - Say who is asking and why ("I'm the coding agent working on the checkout redesign; I need your call between two layouts").
69
+ - Say what the page asks of them and how long it takes.
70
+ - Give a real deadline only if there is one.
71
+ - Ask for no passwords, keys or codes on a page; collect secrets through `mostra secret set` instead.
72
+ - Post a link somewhere public only if the page is meant for anyone.
@@ -0,0 +1,71 @@
1
+ # Verify: the verdict, screenshots and the dev preview
2
+
3
+ ## Contents
4
+
5
+ - What verify does
6
+ - Reading the verdict
7
+ - Errors, warnings and hints
8
+ - Screenshots and the ARIA snapshot
9
+ - Regressions between versions
10
+ - Publish and verify
11
+ - The dev preview: `mostra dev`
12
+
13
+ ## What verify does
14
+
15
+ `mostra verify <dir>` checks the artifact's current source without publishing it, in a sandbox that touches no one's answers and calls no host:
16
+
17
+ 1. **prepare** and **compile**: reads the manifest, resolves and installs packages, type-checks (TypeScript in strict mode, or with the artifact's own `tsconfig.json` settings), builds.
18
+ 2. **boot** and **render**: opens the page in a headless Chromium at 1280 × 800 and 390 × 844, with a fixed clock and reduced motion, waits until it's still (and until the calls, runs and live values it loads at mount have arrived), records page errors, console errors and failed requests, runs axe, takes an ARIA snapshot and a screenshot per size.
19
+ 3. **smoke**: clicks and types through the page's controls (up to 200 interactions or 60 s), checking that each does something and that nothing breaks. Server functions run only when they opt in through `dryRun()` ([server.md](server.md)); live sources run for real, and secrets resolve as they would.
20
+ 4. **regression**: compares with the last published version that passed ([below](#regressions-between-versions)).
21
+
22
+ It takes 10 to 30 s.
23
+
24
+ ## Reading the verdict
25
+
26
+ The human output prints `verify: pass` or `verify: fail`, each diagnostic with its hint, and the screenshots worth looking at. Exit code 0 is pass, 1 is fail. With `--json`, the result is:
27
+
28
+ ```json
29
+ {
30
+ "status": "pass",
31
+ "artifact": { "id": "art_…", "path": "…", "sourceDigest": "…", "envDigest": "…", "versionId": "ver_…" },
32
+ "diagnostics": [{ "code": "MOSTRA_…", "severity": "error", "message": "…", "hint": "…", "location": { "file": "index.tsx", "line": 12, "column": 7 }, "docs": "…" }],
33
+ "screenshots": [{ "viewport": "desktop", "path": "…/desktop.png", "width": 1280, "height": 800, "tokensEstimate": { "claude": 1334, "gpt": 1200, "gemini": 1120 }, "returned": false }],
34
+ "aria": [{ "viewport": "desktop", "path": "…/desktop.aria.yml", "summary": "3 headings, 1 button, 1 textbox, landmarks: main" }],
35
+ "smoke": { "interactions": 3, "skippedActions": [], "stateChanges": 3 },
36
+ "regressions": {},
37
+ "timingsMs": { "build": 36, "typecheck": 538, "render": 9548, "smoke": 2492, "total": 13898 }
38
+ }
39
+ ```
40
+
41
+ `status` is `fail` exactly when there is an error. Diagnostics come errors first; identical ones fold into one with a `count`. `mostra docs <CODE>` prints any code's page with an example fix.
42
+
43
+ ## Errors, warnings and hints
44
+
45
+ | Severity | Means | Examples |
46
+ |---|---|---|
47
+ | error | Something is definitely broken; publish refuses it | type and build errors, uncaught page errors, console errors, failed requests to the page's own origin, a blank page, a page that never gets ready, duplicate or unstable field IDs, a manifest that can't be read |
48
+ | warning | Worth checking; publish allows it | axe's serious findings, failed requests to other sites, a failing live source, a package without types, a secret the page needed that isn't set, every regression, a control with no visible effect |
49
+ | hint | Information | an input not bound to a field (`MOSTRA_FIELD_UNBOUND`, fine for a search box or a draft you don't want saved), an action skipped in verify, axe's minor findings, the smoke test's budget, no baseline yet |
50
+
51
+ Warnings that begin with **"Observed only"** (`MOSTRA_SMOKE_NO_EFFECT`, `MOSTRA_REGRESSION_*`) report what verify saw, such as a button whose click changed nothing visible or a page that changed since the last version. Look at the screenshot and decide; when the behavior is what you intended, change nothing.
52
+
53
+ Fix errors at their location, run verify again, and repeat until it passes. Fix the first error first: later ones are often its consequences.
54
+
55
+ ## Screenshots and the ARIA snapshot
56
+
57
+ Screenshots are always taken. `--screenshots on-failure` (the default) marks them `returned` only when verify fails; `always` marks them every time; `never` never does. The human output lists the returned ones. **Look at them before you publish**, on every round: verify can't tell you that the page looks wrong, only that it works. The design checks in [design.md](design.md#reading-your-screenshots) say what to look for.
58
+
59
+ The ARIA snapshot (`.aria.yml`) is the page as a screen reader sees it: headings, buttons, inputs and their names. Read it when you can't look at images: it shows what text and controls the page actually rendered.
60
+
61
+ ## Regressions between versions
62
+
63
+ From the second version on, verify renders the last published version that passed, in the same run, and compares: the ARIA snapshot, the pixels at each size, and the contract (fields, actions, live sources and pages that disappeared). A field you removed leaves people's answers behind, so `MOSTRA_REGRESSION_FIELD_REMOVED` is worth a second look; a layout change you made on purpose is expected.
64
+
65
+ ## Publish and verify
66
+
67
+ `mostra publish` reuses the verdict of the same source, or runs verify itself. It refuses a source whose verdict has errors (`MOSTRA_PUBLISH_VERIFY_FAILED`). `--force` publishes anyway and records the failing codes on the version; it never publishes a source that didn't build. Use it only when you know why the error doesn't matter. When the headless browser isn't available (`MOSTRA_ENV_BROWSER_MISSING`), verify still type-checks and builds, and the code's page says how to install the browser.
68
+
69
+ ## The dev preview: `mostra dev`
70
+
71
+ `mostra dev <dir>` serves the unpublished source with hot reload on this machine until Ctrl-C, and prints a link. Edits appear in the browser as you save; changed server code restarts its worker. Answers and submissions there go to a scratch store that's thrown away, and actions run for real with the real secrets. Nobody but you sees it: use it while building, then verify and publish.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/cli",
3
- "version": "0.7.0",
3
+ "version": "0.8.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",
@@ -34,17 +34,18 @@
34
34
  "provenance": true
35
35
  },
36
36
  "dependencies": {
37
- "@mostra/protocol": "0.7.0",
38
- "@mostra/sdk": "0.7.0",
37
+ "@mostra/protocol": "0.8.0",
38
+ "@mostra/sdk": "0.8.0",
39
39
  "zod": "4.6.7"
40
40
  },
41
41
  "devDependencies": {
42
- "@mostra/runtime": "0.7.0",
42
+ "@mostra/runtime": "0.8.0",
43
43
  "@mostra/tools": "0.0.0",
44
44
  "@types/node": "24.19.2",
45
45
  "tsdown": "0.23.1",
46
46
  "typescript": "7.0.2",
47
- "vitest": "5.0.5"
47
+ "vitest": "5.0.5",
48
+ "yaml": "2.9.1"
48
49
  },
49
50
  "bin": {
50
51
  "mostra": "./dist/bin.js"
@@ -4,7 +4,7 @@
4
4
  * files, except `doctor`, which reads what it needs to explain why an instance can't start.
5
5
  */
6
6
  import { spawn } from "node:child_process";
7
- import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
7
+ import { existsSync, readdirSync, statSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import {
10
10
  artifactGetMethod,
@@ -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 } from "../docs.ts";
26
+ import { docsIndex, indexMarkdown, nearestTopics, 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";
@@ -670,7 +670,8 @@ async function alwaysOnCheck(context: CommandContext): Promise<DoctorCheck> {
670
670
  /** `mostra docs [topic]`. */
671
671
  export const docsCommand: CommandDef = defineCommand({
672
672
  path: ["docs"],
673
- summary: "Print Mostra's reference: the CLI, telemetry, and every diagnostic code's page.",
673
+ summary:
674
+ "Print Mostra's reference: the guide to writing artifacts, the CLI, telemetry, and every diagnostic code's page.",
674
675
  args: [
675
676
  { name: "topic", summary: "A topic or a diagnostic code. Default: the index.", optional: true },
676
677
  ],
@@ -702,7 +703,7 @@ export const docsCommand: CommandDef = defineCommand({
702
703
  `No topic "${wanted}". The nearest: ${nearestTopics(wanted, topics).join(", ")}. Run "mostra docs" for the index.`,
703
704
  );
704
705
  }
705
- const markdown = readFileSync(found.file, "utf8");
706
+ const markdown = topicMarkdown(found);
706
707
  return { result: { topic: found.topic, markdown, url: found.url }, human: markdown };
707
708
  },
708
709
  });
package/src/docs.ts CHANGED
@@ -1,24 +1,30 @@
1
1
  /**
2
2
  * `mostra docs` (D140 item 17): the reference that ships with the CLI, by stable slug. The
3
3
  * diagnostic pages are keyed by code (`mostra docs MOSTRA_DEP_MISSING`, as hints say), beside the
4
- * CLI reference and the telemetry page. This index is the one source WP-15's `docs_search` and
5
- * WP-26's site read.
4
+ * CLI reference and the telemetry page. The Agent Skill (`skills/mostra/`, WP-14) is in it too, as
5
+ * `guide` and `guide/<name>`, so an agent whose harness has no Skill reads the same text through
6
+ * the CLI. This index is the one source WP-15's `docs_search` and WP-26's site read.
6
7
  */
7
8
  import { existsSync, readdirSync, readFileSync } from "node:fs";
8
- import { join } from "node:path";
9
+ import { extname, join } from "node:path";
9
10
  import { DEFAULT_DOCS_BASE } from "@mostra/protocol";
10
11
  import { fromSource, packageRoot } from "./version.ts";
11
12
 
12
13
  /** One topic of the reference. */
13
14
  export interface DocsTopic {
14
- /** Its stable slug: `cli`, `telemetry`, `errors`, or a diagnostic code. */
15
+ /** Its stable slug: `cli`, `telemetry`, a diagnostic code, `guide` or `guide/<name>`. */
15
16
  readonly topic: string;
16
17
  /** Its title, from the page's first heading. */
17
18
  readonly title: string;
18
19
  /** Where the docs site serves it. */
19
20
  readonly url: string;
20
- /** Its Markdown file. */
21
+ /** Its Markdown file, or a guide topic's first file. */
21
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[];
22
28
  }
23
29
 
24
30
  /** Where the reference is: bundled in the build (`dist/reference`), or the repository's. */
@@ -29,6 +35,14 @@ export function referenceDir(): string {
29
35
  : join(packageRoot(), "..", "..", "docs", "reference");
30
36
  }
31
37
 
38
+ /** Where the Agent Skill is: bundled in the build (`dist/skill`), or the repository's. */
39
+ export function skillDir(): string {
40
+ const bundled = join(packageRoot(), "dist", "skill");
41
+ return !fromSource() && existsSync(bundled)
42
+ ? bundled
43
+ : join(packageRoot(), "..", "..", "skills", "mostra");
44
+ }
45
+
32
46
  function titleOf(file: string): string {
33
47
  const first = readFileSync(file, "utf8")
34
48
  .split("\n")
@@ -56,12 +70,116 @@ export function docsIndex(dir: string = referenceDir()): DocsTopic[] {
56
70
  const file = join(errorsDir, name);
57
71
  return { topic: code, title: titleOf(file), url: `${base}/errors/${code}`, file };
58
72
  });
59
- return [...pages, ...errors];
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;
141
+ }
142
+
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
+ const GUIDE_LINKS =
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
+ /**
157
+ * A topic's Markdown. A guide page loses its frontmatter and says how its links read through the
158
+ * CLI; a guide topic made of files shows each one as code under its path.
159
+ */
160
+ export function topicMarkdown(topic: DocsTopic, dir: string = skillDir()): string {
161
+ if (topic.files !== undefined) {
162
+ const parts = topic.files.map((path) => {
163
+ const text = readFileSync(join(dir, "assets", path), "utf8");
164
+ const fence = text.includes("```") ? "````" : "```";
165
+ const body = text.endsWith("\n") ? text : `${text}\n`;
166
+ return `## \`${path}\`\n\n${fence}${FENCE_LANGUAGES[extname(path)] ?? ""}\n${body}${fence}\n`;
167
+ });
168
+ return [`# ${topic.title}`, "", GUIDE_LINKS, "", ...parts].join("\n");
169
+ }
170
+ const text = readFileSync(topic.file, "utf8");
171
+ if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
172
+ return [GUIDE_LINKS, "", text.replace(/^---\n[\s\S]*?\n---\n+/, "")].join("\n");
60
173
  }
61
174
 
62
175
  /** The index as Markdown: what `mostra docs` prints without a topic. */
63
176
  export function indexMarkdown(topics: readonly DocsTopic[]): string {
64
- const pages = topics.filter((topic) => !topic.topic.startsWith("MOSTRA_"));
177
+ const pages = topics.filter(
178
+ (topic) => !topic.topic.startsWith("MOSTRA_") && !topic.topic.startsWith("guide"),
179
+ );
180
+ const guide = topics.filter(
181
+ (topic) => topic.topic === "guide" || topic.topic.startsWith("guide/"),
182
+ );
65
183
  const codes = topics.filter((topic) => topic.topic.startsWith("MOSTRA_"));
66
184
  return [
67
185
  "# Mostra reference",
@@ -70,6 +188,14 @@ export function indexMarkdown(topics: readonly DocsTopic[]): string {
70
188
  "",
71
189
  ...pages.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
72
190
  "",
191
+ ...(guide.length > 0
192
+ ? [
193
+ "## Writing artifacts",
194
+ "",
195
+ ...guide.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
196
+ "",
197
+ ]
198
+ : []),
73
199
  "## Diagnostic codes",
74
200
  "",
75
201
  ...codes.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
@@ -1 +0,0 @@
1
- export { t as run } from "./run-DO9Y3Dtm.js";