@mostra/cli 0.9.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 (57) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/bootstrap-BStzS_41.js +1 -0
  3. package/dist/{bootstrap-Dc-SQHRF.js → bootstrap-_iCl_HaO.js} +3 -2
  4. package/dist/bootstrap-_iCl_HaO.js.map +1 -0
  5. package/dist/{flush-C16w3JL8.js → flush-D648gCYs.js} +12 -3
  6. package/dist/flush-D648gCYs.js.map +1 -0
  7. package/dist/index.d.ts +1 -1
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/reference/cli.md +210 -4
  11. package/dist/reference/diagnostics.json +171 -0
  12. package/dist/reference/errors/MOSTRA_ACTION_PAUSED.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  15. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  16. package/dist/reference/errors/MOSTRA_REMOTE_HOME_MOVING.md +23 -0
  17. package/dist/reference/errors/MOSTRA_REMOTE_HOME_SUSPENDED.md +23 -0
  18. package/dist/reference/errors/MOSTRA_REMOTE_LIMIT_REACHED.md +23 -0
  19. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  20. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  21. package/dist/reference/errors/MOSTRA_REMOTE_NO_INSTANCE.md +23 -0
  22. package/dist/reference/errors/MOSTRA_REMOTE_OPERATOR_UNAVAILABLE.md +23 -0
  23. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  24. package/dist/reference/errors/MOSTRA_REMOTE_PAUSED_BY_OPERATOR.md +23 -0
  25. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  26. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  27. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  28. package/dist/reference/errors/MOSTRA_REMOTE_UNDER_REVIEW.md +23 -0
  29. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  30. package/dist/reference/errors/MOSTRA_SUBMIT_PAUSED.md +23 -0
  31. package/dist/reference/self-hosting.md +130 -0
  32. package/dist/run-Bpg_ZRY8.js +1 -0
  33. package/dist/{run-DdYT3iHQ.js → run-BxYL-DaX.js} +333 -225
  34. package/dist/run-BxYL-DaX.js.map +1 -0
  35. package/dist/skill/SKILL.md +5 -3
  36. package/dist/skill/references/answers.md +36 -0
  37. package/dist/skill/references/mcp.md +9 -4
  38. package/dist/skill/references/sharing.md +55 -4
  39. package/dist/telemetry/flush-main.js +1 -1
  40. package/package.json +5 -5
  41. package/src/client.ts +1 -1
  42. package/src/commands/admin.ts +13 -3
  43. package/src/commands/authoring.ts +85 -3
  44. package/src/commands/index.ts +18 -3
  45. package/src/commands/remote.ts +209 -0
  46. package/src/commands/sharing.ts +33 -6
  47. package/src/commands/viewing.ts +20 -2
  48. package/src/detached.ts +3 -0
  49. package/src/docs.ts +12 -217
  50. package/src/exit.ts +2 -0
  51. package/src/mcp.ts +3 -21
  52. package/src/telemetry/store.ts +15 -4
  53. package/dist/bootstrap-Dc-SQHRF.js.map +0 -1
  54. package/dist/bootstrap-aaE5wFo9.js +0 -1
  55. package/dist/flush-C16w3JL8.js.map +0 -1
  56. package/dist/run-Bw4_6kcW.js +0 -1
  57. package/dist/run-DdYT3iHQ.js.map +0 -1
@@ -0,0 +1,209 @@
1
+ /**
2
+ * `mostra login` and `mostra logout` (INTERFACES §18.7, D165 items 2, 15): this home signs in to a
3
+ * remote server by the OAuth device authorization grant, so `mostra share --cloud` can host its
4
+ * artifacts there, and signs out again. The instance keeps the refresh token in the home,
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`. 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`.
9
+ */
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";
19
+ import { type CommandDef, defineCommand } from "../command.ts";
20
+ import { EXIT } from "../exit.ts";
21
+ import { usage } from "../parse.ts";
22
+ import { arg, artifactRef, flag } from "./shared.ts";
23
+
24
+ /** How long `mostra login` waits for the person to approve, in all (the code lives 10 minutes). */
25
+ const LOGIN_WAIT_MS = 10 * 60_000;
26
+ /** Each wait asks the instance for this long, so a slow approval never meets a request timeout. */
27
+ const LOGIN_STEP_MS = 30_000;
28
+
29
+ /** `mostra login [<server>] [--default]`. */
30
+ export const loginCommand: CommandDef = defineCommand({
31
+ path: ["login"],
32
+ summary:
33
+ "Sign this machine's Mostra in to a remote server, so mostra share --cloud can host pages there.",
34
+ args: [
35
+ {
36
+ name: "server",
37
+ summary:
38
+ "The server's address, such as https://api.example.com. Default: the server signed in to last.",
39
+ optional: true,
40
+ },
41
+ ],
42
+ flags: [
43
+ {
44
+ name: "default",
45
+ kind: "boolean",
46
+ summary:
47
+ "Make this machine the account's default, the one chat apps create pages on. Default: the first machine linked.",
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
+ },
55
+ ],
56
+ output: { type: "RemoteLoginWaitResult", topic: "cli" },
57
+ exits: [EXIT.failure, EXIT.environment],
58
+ example: "login https://api.example.com",
59
+ async run(context) {
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
+ }
84
+ const started = await context.call(remoteLoginMethod, {
85
+ ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
86
+ ...(context.flags["default"] === true ? { default: true } : {}),
87
+ });
88
+ const where = started.verificationUriComplete ?? started.verificationUri;
89
+ context.emit(
90
+ { kind: "code", ...started },
91
+ `Open ${where} and check that it shows the code ${started.userCode}, then approve.\nWaiting for you to approve…`,
92
+ );
93
+ const deadline = Date.now() + LOGIN_WAIT_MS;
94
+ for (;;) {
95
+ const waited = await context.call(remoteLoginWaitMethod, {
96
+ loginId: started.loginId,
97
+ timeoutMs: Math.max(0, Math.min(LOGIN_STEP_MS, deadline - Date.now())),
98
+ });
99
+ if (waited.status === "signed-in") {
100
+ return {
101
+ result: waited,
102
+ human: `Signed in to ${waited.server} as ${waited.account.name ?? waited.account.id}. This machine is ${waited.instanceId}.\n`,
103
+ };
104
+ }
105
+ if (Date.now() >= deadline) {
106
+ return {
107
+ result: waited,
108
+ human: "The code wasn't approved in time. Run mostra login again for a new one.\n",
109
+ exit: EXIT.timeout,
110
+ };
111
+ }
112
+ }
113
+ },
114
+ });
115
+
116
+ /** `mostra logout [<server>] [--forget]`. */
117
+ export const logoutCommand: CommandDef = defineCommand({
118
+ path: ["logout"],
119
+ summary:
120
+ "Sign this machine's Mostra out of a remote server; its hosted pages keep working, and their answers wait for the next sign-in.",
121
+ args: [
122
+ {
123
+ name: "server",
124
+ summary: "The server's address. Default: the server signed in to last.",
125
+ optional: true,
126
+ },
127
+ ],
128
+ flags: [
129
+ {
130
+ name: "forget",
131
+ kind: "boolean",
132
+ summary:
133
+ "Also forget this machine's link to the server: the pages it shared there are no longer its own.",
134
+ },
135
+ ],
136
+ output: { type: "RemoteLogoutResult", topic: "cli" },
137
+ exits: [EXIT.failure, EXIT.environment],
138
+ example: "logout",
139
+ async run(context) {
140
+ const server = context.args["server"];
141
+ const result = await context.call(remoteLogoutMethod, {
142
+ ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
143
+ ...(context.flags["forget"] === true ? { forget: true } : {}),
144
+ });
145
+ return {
146
+ result,
147
+ human:
148
+ result.servers.length === 0
149
+ ? "This machine wasn't signed in to a server.\n"
150
+ : `Signed out of ${result.servers.join(", ")}.\n`,
151
+ };
152
+ },
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
+ });
@@ -2,7 +2,8 @@
2
2
  * `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
3
3
  * runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
4
4
  * identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
5
- * funnel`), whose link expires (1 hour by default, 7 days at most). The share lives in the
5
+ * funnel`), whose link expires (1 hour by default, 7 days at most); or `--cloud` (D165 item 15),
6
+ * hosted on a remote server this home signed in to, so the link works while this machine sleeps. The share lives in the
6
7
  * daemon, so the command returns at once with the link; `share stop` ends it and `share list`
7
8
  * shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
8
9
  */
@@ -26,6 +27,7 @@ const THROUGH: Readonly<Record<ShareVia, string>> = {
26
27
  tailnet: "Tailscale Serve, inside your tailnet",
27
28
  funnel: "Tailscale Funnel, public",
28
29
  cloudflare: "a Cloudflare quick tunnel, public",
30
+ remote: "a remote server, hosted",
29
31
  };
30
32
 
31
33
  /**
@@ -58,9 +60,22 @@ function line(share: Share): string {
58
60
  export const shareCommand: CommandDef = defineCommand({
59
61
  path: ["share"],
60
62
  summary:
61
- "Open an artifact to people beyond this machine: inside your tailnet, or publicly with a link that expires.",
62
- args: [{ name: "artifact", summary: "The artifact: its source path or its ID." }],
63
+ "Open an artifact to people beyond this machine: inside your tailnet, publicly with a link that expires, or hosted on a server.",
64
+ args: [
65
+ { name: "artifact", summary: "The artifact: its source path or its ID." },
66
+ {
67
+ name: "server",
68
+ summary: "With --cloud: the server's address. Default: the server signed in to last.",
69
+ optional: true,
70
+ },
71
+ ],
63
72
  flags: [
73
+ {
74
+ name: "cloud",
75
+ kind: "boolean",
76
+ summary:
77
+ "Host it on a remote server you signed in to with mostra login: the link keeps working while this machine sleeps.",
78
+ },
64
79
  {
65
80
  name: "tailnet",
66
81
  kind: "boolean",
@@ -115,16 +130,26 @@ export const shareCommand: CommandDef = defineCommand({
115
130
  ],
116
131
  output: { type: "ShareStartResult", topic: "cli" },
117
132
  exits: [EXIT.failure, EXIT.environment],
118
- example: "share ./sidebar-review --public --ttl 2h",
133
+ example: "share ./sidebar-review --cloud",
119
134
  async run(context) {
120
135
  const artifact = artifactRef(arg(context, "artifact"), context.cwd);
121
136
  const tailnet = context.flags["tailnet"] === true;
122
137
  const publicly = context.flags["public"] === true;
123
- if (tailnet === publicly) throw usage("Give --tailnet or --public.");
138
+ const cloud = context.flags["cloud"] === true;
139
+ if ([tailnet, publicly, cloud].filter(Boolean).length !== 1)
140
+ throw usage("Give one of --tailnet, --public or --cloud.");
124
141
  const viaFlag = flag(context, "via");
125
142
  if (viaFlag !== undefined && !publicly)
126
143
  throw usage("--via chooses a public tunnel: add --public.");
127
- const via: ShareVia = tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
144
+ const server = context.args["server"];
145
+ if (server !== undefined && !cloud) throw usage("A server names where --cloud hosts it.");
146
+ const via: ShareVia = cloud
147
+ ? "remote"
148
+ : tailnet
149
+ ? "tailnet"
150
+ : viaFlag === "funnel"
151
+ ? "funnel"
152
+ : "cloudflare";
128
153
  const ttl = flag(context, "ttl");
129
154
  const scopes = context.flags["scope"] as readonly string[] | undefined;
130
155
  const viewerRef = flag(context, "viewer");
@@ -135,6 +160,7 @@ export const shareCommand: CommandDef = defineCommand({
135
160
  const share = await context.call(shareStartMethod, {
136
161
  artifact,
137
162
  via,
163
+ ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
138
164
  ...(ttl !== undefined ? { ttl: ttl as `${number}${"s" | "m" | "h" | "d"}` } : {}),
139
165
  ...(scopes !== undefined ? { scopes: scopes as CapabilityScope[] } : {}),
140
166
  ...(viewerRef !== undefined
@@ -144,6 +170,7 @@ export const shareCommand: CommandDef = defineCommand({
144
170
  });
145
171
  context.record({ event: "share.done", fields: { kind: via } });
146
172
  const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
173
+ // A hosted page keeps working while this machine sleeps: its answers wait for it (D165).
147
174
  return {
148
175
  result: share,
149
176
  human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`,
@@ -37,17 +37,35 @@ function wantsBrowser(context: CommandContext): boolean {
37
37
  return context.tty.stdout && !context.json && hasDisplay(context.env);
38
38
  }
39
39
 
40
- /** The link, opened in a browser when wanted. */
40
+ /**
41
+ * Why no browser was opened, for stderr (#114): an agent's shell isn't a terminal, so without a
42
+ * word it would tell its person the page is open when it isn't.
43
+ */
44
+ function notOpenedReason(context: CommandContext, tried: boolean): string | undefined {
45
+ if (context.flags["no-browser"] === true) return undefined;
46
+ if (tried) return "No browser opened: none could be started here. Give the person the link.";
47
+ if (!hasDisplay(context.env)) {
48
+ return "No browser opened: this session has no display. Give the person the link.";
49
+ }
50
+ return "No browser opened: this isn't a terminal. Pass --browser to open it here, or give the person the link.";
51
+ }
52
+
53
+ /** The link, opened in a browser when wanted; why not on stderr when it wasn't. */
41
54
  async function show(
42
55
  context: CommandContext,
43
56
  link: CapabilityLink,
44
57
  ): Promise<{ result: CapabilityLink & { readonly opened: boolean }; human: string }> {
45
58
  let opened = false;
46
- if (wantsBrowser(context)) {
59
+ const tried = wantsBrowser(context);
60
+ if (tried) {
47
61
  const launch = await context.call(viewLaunchMethod, { tokenId: link.tokenId });
48
62
  // The launch URL reaches the browser through a 0600 page, never its arguments.
49
63
  opened = await openInBrowser(launch.url, context.env);
50
64
  }
65
+ if (!opened) {
66
+ const reason = notOpenedReason(context, tried);
67
+ if (reason !== undefined) context.log(reason);
68
+ }
51
69
  return { result: { ...link, opened }, human: `${link.url}\n` };
52
70
  }
53
71
 
package/src/detached.ts CHANGED
@@ -25,7 +25,10 @@ export const PATH_VARIABLES: readonly string[] = [
25
25
  "MOSTRA_VERIFY_ENTRY",
26
26
  "MOSTRA_WIN_HELPER",
27
27
  "MOSTRA_TEST_WORKER_HOST",
28
+ "MOSTRA_TEST_NETWORK_FILESYSTEM",
29
+ "MOSTRA_TEST_BINDING_TRACE",
28
30
  "MOSTRA_TEST_BUNDLE_PINS",
31
+ "MOSTRA_TEST_VERIFY_FAIL_ONCE",
29
32
  "MOSTRA_TAILSCALE",
30
33
  "MOSTRA_CLOUDFLARED",
31
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/exit.ts CHANGED
@@ -59,6 +59,8 @@ const BY_AREA: Readonly<Record<DiagnosticArea, ExitCode>> = {
59
59
  PLATFORM: EXIT.environment,
60
60
  ARTIFACT: EXIT.failure,
61
61
  CLI: EXIT.usage,
62
+ // A remote server or the link to one: the environment, like a share's tunnel (D165).
63
+ REMOTE: EXIT.environment,
62
64
  };
63
65
 
64
66
  /** Codes whose exit code isn't their area's. */
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. */
@@ -175,10 +175,21 @@ export class TelemetryStore {
175
175
  /** The install ID in `telemetry-id`: `undefined` when there is none, `null` when it's damaged. */
176
176
  #readId(): string | undefined | null {
177
177
  let text: string;
178
- try {
179
- text = readFileSync(this.idFile, "utf8");
180
- } catch (error) {
181
- return (error as NodeJS.ErrnoException).code === "ENOENT" ? undefined : null;
178
+ // Windows refuses to open a file another process holds for a moment (an antivirus scan of the
179
+ // new file, or the removal of the temporary name it was linked from) with `EPERM`, `EACCES` or
180
+ // `EBUSY`: the read is tried again for up to a second, as renames are (#129).
181
+ const deadline = Date.now() + 1000;
182
+ for (let pause = 5; ; pause = Math.min(pause * 2, 100)) {
183
+ try {
184
+ text = readFileSync(this.idFile, "utf8");
185
+ break;
186
+ } catch (error) {
187
+ const code = (error as NodeJS.ErrnoException).code;
188
+ if (code === "ENOENT") return undefined;
189
+ const shared = code === "EPERM" || code === "EACCES" || code === "EBUSY";
190
+ if (this.#platform !== "win32" || !shared || Date.now() > deadline) return null;
191
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, pause);
192
+ }
182
193
  }
183
194
  const id = text.trim();
184
195
  return UUID.test(id) ? id : null;