@mostra/cli 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/bootstrap-Dc-SQHRF.js +422 -0
- package/dist/bootstrap-Dc-SQHRF.js.map +1 -0
- package/dist/bootstrap-aaE5wFo9.js +1 -0
- package/dist/{flush-CBN3AU9X.js → flush-C16w3JL8.js} +24 -3
- package/dist/flush-C16w3JL8.js.map +1 -0
- package/dist/index.d.ts +13 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/reference/cli.md +35 -2
- package/dist/reference/diagnostics.json +39 -3
- package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +3 -3
- package/dist/reference/telemetry.md +5 -3
- package/dist/run-Bw4_6kcW.js +1 -0
- package/dist/{run-DO9Y3Dtm.js → run-DdYT3iHQ.js} +1137 -763
- package/dist/run-DdYT3iHQ.js.map +1 -0
- package/dist/skill/SKILL.md +120 -0
- package/dist/skill/assets/examples/dashboard/index.tsx +161 -0
- package/dist/skill/assets/examples/dashboard/live.ts +25 -0
- package/dist/skill/assets/examples/dashboard/styles.css +125 -0
- package/dist/skill/assets/examples/decision/index.tsx +95 -0
- package/dist/skill/assets/examples/decision/styles.css +125 -0
- package/dist/skill/assets/examples/inbox/actions.ts +23 -0
- package/dist/skill/assets/examples/inbox/index.tsx +109 -0
- package/dist/skill/assets/examples/inbox/styles.css +125 -0
- package/dist/skill/assets/studio.css +125 -0
- package/dist/skill/references/answers.md +181 -0
- package/dist/skill/references/design.md +154 -0
- package/dist/skill/references/libraries.md +167 -0
- package/dist/skill/references/long-lived.md +148 -0
- package/dist/skill/references/mcp.md +63 -0
- package/dist/skill/references/page.md +131 -0
- package/dist/skill/references/server.md +146 -0
- package/dist/skill/references/sharing.md +72 -0
- package/dist/skill/references/verify.md +71 -0
- package/dist/telemetry/flush-main.js +1 -1
- package/package.json +12 -5
- package/src/bootstrap.ts +16 -3
- package/src/command.ts +13 -3
- package/src/commands/admin.ts +5 -4
- package/src/commands/dev.ts +60 -44
- package/src/commands/index.ts +4 -2
- package/src/commands/interaction.ts +19 -1
- package/src/commands/mcp.ts +128 -0
- package/src/detached.ts +1 -0
- package/src/docs.ts +141 -7
- package/src/help.ts +1 -1
- package/src/home.ts +5 -3
- package/src/mcp.ts +448 -0
- package/src/parse.ts +20 -6
- package/src/run.ts +24 -13
- package/src/telemetry/harness.ts +24 -0
- package/src/telemetry/index.ts +75 -48
- package/dist/bootstrap-DfEe_yPr.js +0 -113
- package/dist/bootstrap-DfEe_yPr.js.map +0 -1
- package/dist/exit-CBIf8nAU.js +0 -79
- package/dist/exit-CBIf8nAU.js.map +0 -1
- package/dist/flush-CBN3AU9X.js.map +0 -1
- package/dist/run-DKNRTR1j.js +0 -1
- package/dist/run-DO9Y3Dtm.js.map +0 -1
|
@@ -1,36 +1,35 @@
|
|
|
1
|
-
import { a as
|
|
2
|
-
import { n as
|
|
1
|
+
import { a as GLOBAL_FLAGS, c as parseCommandLine, d as EXIT, f as exitCodeFor, l as topWords, m as defineCommand, o as durationMs, p as commandName, r as progressReporter, s as globalFlags, u as usage } from "./bootstrap-Dc-SQHRF.js";
|
|
2
|
+
import { _ as packageRoot, a as detachedEnvironment, c as durationBucket, d as mcpSessionFields, f as buildEndpoint, g as fromSource, h as cliVersion, i as detachedDirectory, l as minute, m as truthy, n as startFlusher, o as TelemetryEvent, p as decide, r as TelemetryStore, s as catalogCodes, u as detectHarness } from "./flush-C16w3JL8.js";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
4
|
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
-
import { isAbsolute, join, resolve, win32 } from "node:path";
|
|
5
|
+
import { extname, isAbsolute, join, resolve, win32 } from "node:path";
|
|
6
6
|
import { ARTIFACT_PROGRESS, CLI_CLIENT_NAME, DEFAULT_DOCS_BASE, DEV_NOTIFY, FieldOp, HOST_PROTOCOL_REVISIONS, LineSplitter, MutationId, RpcError, RpcPeer, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, diagnosticCatalog, encodeLine, gcRunMethod, instanceCheckMethod, instanceStatusMethod, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, resultsGetMethod, secretDeleteMethod, secretListMethod, secretSetMethod, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
|
|
7
7
|
import { checkBrowser, checkFiles, connectControl, enclosingBundle, readBundle, readSetup, resolveRuntime } from "@mostra/sdk";
|
|
8
8
|
import { homedir, tmpdir } from "node:os";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
10
|
+
import { MCP_PATH, createHttpEndpoint, createMcpServerFactory, defaultWorkspaceRoot, localWorkspace } from "@mostra/mcp";
|
|
11
|
+
import { isIP } from "node:net";
|
|
12
|
+
import { serve } from "@hono/node-server";
|
|
13
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
11
14
|
import { createInterface } from "node:readline";
|
|
12
|
-
//#region src/command.ts
|
|
13
|
-
/** Defines a command; the identity function, for types. */
|
|
14
|
-
function defineCommand(command) {
|
|
15
|
-
return command;
|
|
16
|
-
}
|
|
17
|
-
/** The command path as one string: `daemon install`. */
|
|
18
|
-
function commandName(command) {
|
|
19
|
-
return command.path.join(" ");
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
15
|
//#region src/docs.ts
|
|
23
16
|
/**
|
|
24
17
|
* `mostra docs` (D140 item 17): the reference that ships with the CLI, by stable slug. The
|
|
25
18
|
* diagnostic pages are keyed by code (`mostra docs MOSTRA_DEP_MISSING`, as hints say), beside the
|
|
26
|
-
* CLI reference and the telemetry page.
|
|
27
|
-
*
|
|
19
|
+
* CLI reference and the telemetry page. The Agent Skill (`skills/mostra/`, WP-14) is in it too, as
|
|
20
|
+
* `guide` and `guide/<name>`, so an agent whose harness has no Skill reads the same text through
|
|
21
|
+
* the CLI. This index is the one source WP-15's `docs_search` and WP-26's site read.
|
|
28
22
|
*/
|
|
29
23
|
/** Where the reference is: bundled in the build (`dist/reference`), or the repository's. */
|
|
30
24
|
function referenceDir() {
|
|
31
25
|
const bundled = join(packageRoot(), "dist", "reference");
|
|
32
26
|
return !fromSource() && existsSync(bundled) ? bundled : join(packageRoot(), "..", "..", "docs", "reference");
|
|
33
27
|
}
|
|
28
|
+
/** Where the Agent Skill is: bundled in the build (`dist/skill`), or the repository's. */
|
|
29
|
+
function skillDir() {
|
|
30
|
+
const bundled = join(packageRoot(), "dist", "skill");
|
|
31
|
+
return !fromSource() && existsSync(bundled) ? bundled : join(packageRoot(), "..", "..", "skills", "mostra");
|
|
32
|
+
}
|
|
34
33
|
function titleOf(file) {
|
|
35
34
|
const first = readFileSync(file, "utf8").split("\n").find((line) => line.startsWith("# "));
|
|
36
35
|
return first ? first.slice(2).trim() : "";
|
|
@@ -59,11 +58,117 @@ function docsIndex(dir = referenceDir()) {
|
|
|
59
58
|
file
|
|
60
59
|
};
|
|
61
60
|
});
|
|
62
|
-
return [
|
|
61
|
+
return [
|
|
62
|
+
...pages,
|
|
63
|
+
...guideTopics(skillDir(), base),
|
|
64
|
+
...errors
|
|
65
|
+
];
|
|
66
|
+
}
|
|
67
|
+
const byName = (a, b) => a.name < b.name ? -1 : 1;
|
|
68
|
+
/** Every file below `root`'s `prefix`, relative to `root`, sorted. */
|
|
69
|
+
function filesBelow(root, prefix) {
|
|
70
|
+
return readdirSync(join(root, prefix), { withFileTypes: true }).sort(byName).flatMap((entry) => {
|
|
71
|
+
const path = `${prefix}/${entry.name}`;
|
|
72
|
+
return entry.isDirectory() ? filesBelow(root, path) : [path];
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The Skill as topics: `guide` (its SKILL.md), `guide/<name>` for each reference,
|
|
77
|
+
* `guide/<file>` for each asset (the baseline stylesheet), and `guide/examples/<name>` for each
|
|
78
|
+
* example, every file of it.
|
|
79
|
+
*/
|
|
80
|
+
function guideTopics(dir, base) {
|
|
81
|
+
const skill = join(dir, "SKILL.md");
|
|
82
|
+
if (!existsSync(skill)) return [];
|
|
83
|
+
const topics = [{
|
|
84
|
+
topic: "guide",
|
|
85
|
+
title: "Using Mostra",
|
|
86
|
+
url: `${base}/guide`,
|
|
87
|
+
file: skill
|
|
88
|
+
}];
|
|
89
|
+
const references = join(dir, "references");
|
|
90
|
+
if (existsSync(references)) for (const name of readdirSync(references).filter((entry) => entry.endsWith(".md")).sort()) {
|
|
91
|
+
const file = join(references, name);
|
|
92
|
+
const slug = name.slice(0, -3);
|
|
93
|
+
topics.push({
|
|
94
|
+
topic: `guide/${slug}`,
|
|
95
|
+
title: titleOf(file),
|
|
96
|
+
url: `${base}/guide/${slug}`,
|
|
97
|
+
file
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
const assets = join(dir, "assets");
|
|
101
|
+
if (!existsSync(assets)) return topics;
|
|
102
|
+
for (const entry of readdirSync(assets, { withFileTypes: true }).sort(byName)) {
|
|
103
|
+
if (!entry.isFile()) continue;
|
|
104
|
+
topics.push({
|
|
105
|
+
topic: `guide/${entry.name}`,
|
|
106
|
+
title: entry.name,
|
|
107
|
+
url: `${base}/guide/${entry.name}`,
|
|
108
|
+
file: join(assets, entry.name),
|
|
109
|
+
files: [entry.name]
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
const examples = join(assets, "examples");
|
|
113
|
+
if (!existsSync(examples)) return topics;
|
|
114
|
+
for (const entry of readdirSync(examples, { withFileTypes: true }).sort(byName)) {
|
|
115
|
+
if (!entry.isDirectory()) continue;
|
|
116
|
+
const files = filesBelow(assets, `examples/${entry.name}`);
|
|
117
|
+
if (files.length === 0) continue;
|
|
118
|
+
topics.push({
|
|
119
|
+
topic: `guide/examples/${entry.name}`,
|
|
120
|
+
title: `Example: ${entry.name}`,
|
|
121
|
+
url: `${base}/guide/examples/${entry.name}`,
|
|
122
|
+
file: join(assets, files[0]),
|
|
123
|
+
files
|
|
124
|
+
});
|
|
125
|
+
}
|
|
126
|
+
return topics;
|
|
127
|
+
}
|
|
128
|
+
const FENCE_LANGUAGES = {
|
|
129
|
+
".css": "css",
|
|
130
|
+
".json": "json",
|
|
131
|
+
".md": "md",
|
|
132
|
+
".mdx": "mdx",
|
|
133
|
+
".ts": "ts",
|
|
134
|
+
".tsx": "tsx"
|
|
135
|
+
};
|
|
136
|
+
/** How the guide's relative links read through the CLI, before each of its pages. */
|
|
137
|
+
const GUIDE_LINKS = "> 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>`.";
|
|
138
|
+
/** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */
|
|
139
|
+
const MCP_GUIDE_LINKS = "> 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`).";
|
|
140
|
+
/**
|
|
141
|
+
* A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the
|
|
142
|
+
* CLI by default, or `links`); a guide topic made of files shows each one as code under its path.
|
|
143
|
+
*/
|
|
144
|
+
function topicMarkdown(topic, dir = skillDir(), links = GUIDE_LINKS) {
|
|
145
|
+
if (topic.files !== void 0) {
|
|
146
|
+
const parts = topic.files.map((path) => {
|
|
147
|
+
const text = readFileSync(join(dir, "assets", path), "utf8");
|
|
148
|
+
const fence = text.includes("```") ? "````" : "```";
|
|
149
|
+
const body = text.endsWith("\n") ? text : `${text}\n`;
|
|
150
|
+
return `## \`${path}\`\n\n${fence}${FENCE_LANGUAGES[extname(path)] ?? ""}\n${body}${fence}\n`;
|
|
151
|
+
});
|
|
152
|
+
return [
|
|
153
|
+
`# ${topic.title}`,
|
|
154
|
+
"",
|
|
155
|
+
links,
|
|
156
|
+
"",
|
|
157
|
+
...parts
|
|
158
|
+
].join("\n");
|
|
159
|
+
}
|
|
160
|
+
const text = readFileSync(topic.file, "utf8");
|
|
161
|
+
if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
|
|
162
|
+
return [
|
|
163
|
+
links,
|
|
164
|
+
"",
|
|
165
|
+
text.replace(/^---\n[\s\S]*?\n---\n+/, "")
|
|
166
|
+
].join("\n");
|
|
63
167
|
}
|
|
64
168
|
/** The index as Markdown: what `mostra docs` prints without a topic. */
|
|
65
169
|
function indexMarkdown(topics) {
|
|
66
|
-
const pages = topics.filter((topic) => !topic.topic.startsWith("MOSTRA_"));
|
|
170
|
+
const pages = topics.filter((topic) => !topic.topic.startsWith("MOSTRA_") && !topic.topic.startsWith("guide"));
|
|
171
|
+
const guide = topics.filter((topic) => topic.topic === "guide" || topic.topic.startsWith("guide/"));
|
|
67
172
|
const codes = topics.filter((topic) => topic.topic.startsWith("MOSTRA_"));
|
|
68
173
|
return [
|
|
69
174
|
"# Mostra reference",
|
|
@@ -72,6 +177,12 @@ function indexMarkdown(topics) {
|
|
|
72
177
|
"",
|
|
73
178
|
...pages.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
|
|
74
179
|
"",
|
|
180
|
+
...guide.length > 0 ? [
|
|
181
|
+
"## Writing artifacts",
|
|
182
|
+
"",
|
|
183
|
+
...guide.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
|
|
184
|
+
""
|
|
185
|
+
] : [],
|
|
75
186
|
"## Diagnostic codes",
|
|
76
187
|
"",
|
|
77
188
|
...codes.map((topic) => `- \`${topic.topic}\`: ${topic.title}`),
|
|
@@ -149,9 +260,11 @@ function configDir(env, cwd, platform = process.platform) {
|
|
|
149
260
|
}
|
|
150
261
|
/**
|
|
151
262
|
* The runtime the CLI starts (D85, RT-01), found as the SDK finds it: `MOSTRA_BUNDLE`,
|
|
152
|
-
* `MOSTRA_RUNTIME_BIN`, the runtime bundle this CLI sits in,
|
|
153
|
-
* runtime beside it. The bootstrap (`bootstrap.ts`) has already moved
|
|
154
|
-
* into its pinned bundle, so this
|
|
263
|
+
* `MOSTRA_RUNTIME_BIN`, the runtime bundle this CLI sits in, its release's pinned bundle, or a
|
|
264
|
+
* development checkout's built runtime beside it. The bootstrap (`bootstrap.ts`) has already moved
|
|
265
|
+
* a CLI installed from npm into its pinned bundle, so this downloads nothing, except under
|
|
266
|
+
* `mostra mcp`, which serves before the bundle is there and installs it itself (D164 item 7), so
|
|
267
|
+
* this finds it installed. Throws the SDK's diagnostic when there is none.
|
|
155
268
|
*/
|
|
156
269
|
async function locateRuntime(env) {
|
|
157
270
|
const runtime = await resolveRuntime({ env });
|
|
@@ -192,205 +305,6 @@ function readHomeMarks(home) {
|
|
|
192
305
|
}
|
|
193
306
|
}
|
|
194
307
|
//#endregion
|
|
195
|
-
//#region src/parse.ts
|
|
196
|
-
/**
|
|
197
|
-
* The command line, read against the command definitions (D140 item 13): the global flags, the
|
|
198
|
-
* command path, its arguments and flags. Every failure is `MOSTRA_CLI_USAGE` or
|
|
199
|
-
* `MOSTRA_CLI_UNKNOWN_COMMAND`, so `--json` mode reports it like any other error.
|
|
200
|
-
*/
|
|
201
|
-
/** The flags every command takes (INTERFACES §9). */
|
|
202
|
-
const GLOBAL_FLAGS = [
|
|
203
|
-
{
|
|
204
|
-
name: "json",
|
|
205
|
-
kind: "boolean",
|
|
206
|
-
summary: "Print one JSON envelope on stdout (NDJSON for streams)."
|
|
207
|
-
},
|
|
208
|
-
{
|
|
209
|
-
name: "home",
|
|
210
|
-
kind: "string",
|
|
211
|
-
value: "<dir>",
|
|
212
|
-
summary: "Use this Mostra home instead of MOSTRA_HOME or the default."
|
|
213
|
-
},
|
|
214
|
-
{
|
|
215
|
-
name: "cwd",
|
|
216
|
-
kind: "string",
|
|
217
|
-
value: "<dir>",
|
|
218
|
-
summary: "Resolve relative paths from this directory."
|
|
219
|
-
},
|
|
220
|
-
{
|
|
221
|
-
name: "timeout",
|
|
222
|
-
kind: "duration",
|
|
223
|
-
value: "<d>",
|
|
224
|
-
summary: "Give up on the instance after this long (exit 4), such as 30s or 5m."
|
|
225
|
-
},
|
|
226
|
-
{
|
|
227
|
-
name: "help",
|
|
228
|
-
kind: "boolean",
|
|
229
|
-
summary: "Show this command's help; with --json, its definition."
|
|
230
|
-
}
|
|
231
|
-
];
|
|
232
|
-
/** A usage error. */
|
|
233
|
-
function usage(message) {
|
|
234
|
-
return new RpcError(createDiagnostic("MOSTRA_CLI_USAGE", { message }));
|
|
235
|
-
}
|
|
236
|
-
const DURATION = /^([1-9][0-9]*)(ms|s|m|h|d)$/;
|
|
237
|
-
const UNIT_MS = {
|
|
238
|
-
ms: 1,
|
|
239
|
-
s: 1e3,
|
|
240
|
-
m: 6e4,
|
|
241
|
-
h: 36e5,
|
|
242
|
-
d: 864e5
|
|
243
|
-
};
|
|
244
|
-
/** A duration flag's milliseconds: `30s`, `5m`, `2h`, `7d`, `500ms`. */
|
|
245
|
-
function durationMs(value) {
|
|
246
|
-
const match = DURATION.exec(value);
|
|
247
|
-
if (!match) throw usage(`"${value}" isn't a duration; use a number with ms, s, m, h or d, such as 30s.`);
|
|
248
|
-
return Number(match[1]) * UNIT_MS[match[2]];
|
|
249
|
-
}
|
|
250
|
-
/**
|
|
251
|
-
* Reads the global flags wherever they stand, before the command is known: `--json` anywhere
|
|
252
|
-
* before `--` makes even a usage error a JSON envelope (D140 item 16).
|
|
253
|
-
*/
|
|
254
|
-
function globalFlags(argv) {
|
|
255
|
-
const end = argv.indexOf("--");
|
|
256
|
-
const words = end === -1 ? argv : argv.slice(0, end);
|
|
257
|
-
const value = (name) => {
|
|
258
|
-
for (let index = 0; index < words.length; index += 1) {
|
|
259
|
-
const word = words[index];
|
|
260
|
-
if (word === `--${name}`) return words[index + 1];
|
|
261
|
-
if (word.startsWith(`--${name}=`)) return word.slice(name.length + 3);
|
|
262
|
-
}
|
|
263
|
-
};
|
|
264
|
-
const timeout = value("timeout");
|
|
265
|
-
let timeoutMs;
|
|
266
|
-
try {
|
|
267
|
-
timeoutMs = timeout === void 0 ? void 0 : durationMs(timeout);
|
|
268
|
-
} catch {
|
|
269
|
-
timeoutMs = void 0;
|
|
270
|
-
}
|
|
271
|
-
const home = value("home");
|
|
272
|
-
const cwd = value("cwd");
|
|
273
|
-
return {
|
|
274
|
-
json: words.includes("--json"),
|
|
275
|
-
...home !== void 0 ? { home } : {},
|
|
276
|
-
...cwd !== void 0 ? { cwd } : {},
|
|
277
|
-
...timeoutMs !== void 0 ? { timeoutMs } : {}
|
|
278
|
-
};
|
|
279
|
-
}
|
|
280
|
-
/** The command that names `words`' longest prefix. */
|
|
281
|
-
function findCommand(commands, words) {
|
|
282
|
-
let best;
|
|
283
|
-
for (const command of commands) {
|
|
284
|
-
const { path } = command;
|
|
285
|
-
if (path.length <= words.length && path.every((word, index) => words[index] === word)) {
|
|
286
|
-
if (!best || path.length > best.used) best = {
|
|
287
|
-
command,
|
|
288
|
-
used: path.length
|
|
289
|
-
};
|
|
290
|
-
}
|
|
291
|
-
}
|
|
292
|
-
return best;
|
|
293
|
-
}
|
|
294
|
-
/** The first words of every command: the groups and the single-word commands. */
|
|
295
|
-
function topWords(commands) {
|
|
296
|
-
return [...new Set(commands.map((command) => command.path[0]))].sort();
|
|
297
|
-
}
|
|
298
|
-
/** Parses the command line against the definitions. Throws a usage diagnostic. */
|
|
299
|
-
function parseCommandLine(commands, argv) {
|
|
300
|
-
const bare = argv.filter((word) => word !== "--json");
|
|
301
|
-
if (bare.length === 1 && (bare[0] === "--version" || bare[0] === "-v")) return { kind: "version" };
|
|
302
|
-
const words = [];
|
|
303
|
-
const pathAt = [];
|
|
304
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
305
|
-
const word = argv[index];
|
|
306
|
-
if (word === "--json" || word === "--help" || word === "-h") continue;
|
|
307
|
-
if (word === "--home" || word === "--cwd" || word === "--timeout") {
|
|
308
|
-
index += 1;
|
|
309
|
-
continue;
|
|
310
|
-
}
|
|
311
|
-
if (/^--(home|cwd|timeout)=/.test(word)) continue;
|
|
312
|
-
if (word.startsWith("-")) break;
|
|
313
|
-
words.push(word);
|
|
314
|
-
pathAt.push(index);
|
|
315
|
-
}
|
|
316
|
-
const helpAsked = argv.includes("--help") || argv.includes("-h");
|
|
317
|
-
if (words.length === 0) {
|
|
318
|
-
if (helpAsked || argv.every((word) => word === "--json")) return { kind: "help" };
|
|
319
|
-
throw usage(`Name a command first; ${argv[0]} isn't one.`);
|
|
320
|
-
}
|
|
321
|
-
const found = findCommand(commands, words);
|
|
322
|
-
if (!found) {
|
|
323
|
-
const group = commands.filter((command) => command.path[0] === words[0]);
|
|
324
|
-
if (group.length > 0) {
|
|
325
|
-
if (helpAsked) return {
|
|
326
|
-
kind: "help",
|
|
327
|
-
group: words[0]
|
|
328
|
-
};
|
|
329
|
-
throw usage(`"mostra ${words[0]}" needs one of: ${group.map((command) => command.path.slice(1).join(" ")).join(", ")}.`);
|
|
330
|
-
}
|
|
331
|
-
throw new RpcError(createDiagnostic("MOSTRA_CLI_UNKNOWN_COMMAND", { message: `"${words[0]}" isn't a mostra command. The commands are: ${topWords(commands).join(", ")}.` }));
|
|
332
|
-
}
|
|
333
|
-
const { command } = found;
|
|
334
|
-
if (helpAsked) return {
|
|
335
|
-
kind: "help",
|
|
336
|
-
command
|
|
337
|
-
};
|
|
338
|
-
const used = new Set(pathAt.slice(0, found.used));
|
|
339
|
-
const rest = argv.filter((_, index) => !used.has(index));
|
|
340
|
-
const flagDefs = [...GLOBAL_FLAGS, ...command.flags ?? []];
|
|
341
|
-
let parsed;
|
|
342
|
-
try {
|
|
343
|
-
parsed = parseArgs({
|
|
344
|
-
args: [...rest],
|
|
345
|
-
allowPositionals: true,
|
|
346
|
-
strict: true,
|
|
347
|
-
options: Object.fromEntries(flagDefs.map((flag) => [flag.name, { type: flag.kind === "boolean" ? "boolean" : "string" }]))
|
|
348
|
-
});
|
|
349
|
-
} catch (error) {
|
|
350
|
-
throw usage(`${error.message.split(". To specify")[0]}. Run "mostra ${commandName(command)} --help".`);
|
|
351
|
-
}
|
|
352
|
-
const flags = {};
|
|
353
|
-
for (const flag of command.flags ?? []) {
|
|
354
|
-
const raw = parsed.values[flag.name];
|
|
355
|
-
if (raw === void 0) continue;
|
|
356
|
-
if (flag.kind === "boolean") {
|
|
357
|
-
flags[flag.name] = raw === true;
|
|
358
|
-
continue;
|
|
359
|
-
}
|
|
360
|
-
const text = String(raw);
|
|
361
|
-
if (flag.choices && !flag.choices.includes(text)) throw usage(`--${flag.name} takes one of ${flag.choices.join(", ")}; "${text}" isn't one.`);
|
|
362
|
-
if (flag.kind === "number") {
|
|
363
|
-
const number = Number(text);
|
|
364
|
-
if (!Number.isInteger(number) || number < 0) throw usage(`--${flag.name} takes a whole number; "${text}" isn't one.`);
|
|
365
|
-
flags[flag.name] = number;
|
|
366
|
-
} else if (flag.kind === "duration") {
|
|
367
|
-
durationMs(text);
|
|
368
|
-
flags[flag.name] = text;
|
|
369
|
-
} else if (flag.kind === "list") flags[flag.name] = text.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
370
|
-
else flags[flag.name] = text;
|
|
371
|
-
}
|
|
372
|
-
const positionals = [...parsed.positionals];
|
|
373
|
-
const args = {};
|
|
374
|
-
for (const arg of command.args ?? []) {
|
|
375
|
-
if (arg.variadic) {
|
|
376
|
-
if (positionals.length === 0 && !arg.optional) throw usage(`"mostra ${commandName(command)}" needs <${arg.name}…>.`);
|
|
377
|
-
args[arg.name] = positionals.splice(0);
|
|
378
|
-
continue;
|
|
379
|
-
}
|
|
380
|
-
const value = positionals.shift();
|
|
381
|
-
if (value === void 0 && !arg.optional) throw usage(`"mostra ${commandName(command)}" needs <${arg.name}>.`);
|
|
382
|
-
args[arg.name] = value;
|
|
383
|
-
}
|
|
384
|
-
if (positionals.length > 0) throw usage(`"mostra ${commandName(command)}" takes no argument "${positionals[0]}". Run "mostra ${commandName(command)} --help".`);
|
|
385
|
-
if (typeof parsed.values["timeout"] === "string") durationMs(parsed.values["timeout"]);
|
|
386
|
-
return {
|
|
387
|
-
kind: "run",
|
|
388
|
-
command,
|
|
389
|
-
args,
|
|
390
|
-
flags
|
|
391
|
-
};
|
|
392
|
-
}
|
|
393
|
-
//#endregion
|
|
394
308
|
//#region src/platform.ts
|
|
395
309
|
/**
|
|
396
310
|
* The CLI's platform gate (D35, D146, RT-07), the runtime's rule (`home/platform.ts` in
|
|
@@ -1334,62 +1248,76 @@ function telemetrySession(options) {
|
|
|
1334
1248
|
fields: event.fields
|
|
1335
1249
|
});
|
|
1336
1250
|
},
|
|
1251
|
+
checkpoint(state) {
|
|
1252
|
+
if (options.quiet || pending.length === 0) return;
|
|
1253
|
+
queue(state.hostInstance, void 0);
|
|
1254
|
+
},
|
|
1337
1255
|
end(outcome) {
|
|
1338
1256
|
if (options.quiet) return;
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1257
|
+
queue(outcome.hostInstance, outcome);
|
|
1258
|
+
}
|
|
1259
|
+
};
|
|
1260
|
+
/**
|
|
1261
|
+
* Queues the pending events, and the command's own when `outcome` is given, and starts the
|
|
1262
|
+
* flusher; nothing when telemetry doesn't allow it. The pending events are taken either way, so
|
|
1263
|
+
* none is queued twice.
|
|
1264
|
+
*/
|
|
1265
|
+
function queue(hostInstance, outcome) {
|
|
1266
|
+
const taken = pending.splice(0);
|
|
1267
|
+
const current = decision(options.hostHome || hostInstance);
|
|
1268
|
+
if (!current.enabled || current.consent === void 0 || !shown()) return;
|
|
1269
|
+
const id = store.installId();
|
|
1270
|
+
if (!id) return;
|
|
1271
|
+
const common = {
|
|
1272
|
+
schema: 1,
|
|
1273
|
+
at: minute(new Date(now())),
|
|
1274
|
+
installId: id.id,
|
|
1275
|
+
version: cliVersion(),
|
|
1276
|
+
os: process.platform === "darwin" || process.platform === "win32" ? process.platform : "linux",
|
|
1277
|
+
arch: process.arch,
|
|
1278
|
+
node: Number(process.versions.node.split(".")[0]),
|
|
1279
|
+
harness,
|
|
1280
|
+
ci,
|
|
1281
|
+
consent: current.consent
|
|
1282
|
+
};
|
|
1283
|
+
const events = [];
|
|
1284
|
+
if (id.created) events.push({
|
|
1285
|
+
...common,
|
|
1286
|
+
event: "cli.first_run"
|
|
1287
|
+
});
|
|
1288
|
+
for (const item of taken) {
|
|
1289
|
+
const fields = item.event === "verify.result" ? {
|
|
1290
|
+
status: item.fields["status"],
|
|
1291
|
+
...catalogCodes(item.fields["codes"] ?? [], CATALOG)
|
|
1292
|
+
} : item.fields;
|
|
1371
1293
|
events.push({
|
|
1372
1294
|
...common,
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
exit: outcome.exit,
|
|
1376
|
-
duration: durationBucket(outcome.durationMs),
|
|
1377
|
-
json: options.json,
|
|
1378
|
-
...outcome.error !== void 0 && CATALOG.has(outcome.error) ? { error: outcome.error } : {}
|
|
1295
|
+
...fields,
|
|
1296
|
+
event: item.event
|
|
1379
1297
|
});
|
|
1380
|
-
const lines = [];
|
|
1381
|
-
for (const event of events) {
|
|
1382
|
-
const parsed = TelemetryEvent.safeParse(event);
|
|
1383
|
-
if (parsed.success) lines.push(JSON.stringify(parsed.data));
|
|
1384
|
-
}
|
|
1385
|
-
if (truthy(options.env["MOSTRA_TELEMETRY_DEBUG"])) {
|
|
1386
|
-
for (const line of lines) options.stderr(`mostra telemetry (debug, not sent): ${line}\n`);
|
|
1387
|
-
return;
|
|
1388
|
-
}
|
|
1389
|
-
store.append(lines, now());
|
|
1390
|
-
if (options.flush !== false) startFlusher(store, options.env, now());
|
|
1391
1298
|
}
|
|
1392
|
-
|
|
1299
|
+
if (outcome !== void 0) events.push({
|
|
1300
|
+
...common,
|
|
1301
|
+
event: "cli.command",
|
|
1302
|
+
command: options.command,
|
|
1303
|
+
exit: outcome.exit,
|
|
1304
|
+
duration: durationBucket(outcome.durationMs),
|
|
1305
|
+
json: options.json,
|
|
1306
|
+
...outcome.error !== void 0 && CATALOG.has(outcome.error) ? { error: outcome.error } : {}
|
|
1307
|
+
});
|
|
1308
|
+
const lines = [];
|
|
1309
|
+
for (const event of events) {
|
|
1310
|
+
const parsed = TelemetryEvent.safeParse(event);
|
|
1311
|
+
if (parsed.success) lines.push(JSON.stringify(parsed.data));
|
|
1312
|
+
}
|
|
1313
|
+
if (lines.length === 0) return;
|
|
1314
|
+
if (truthy(options.env["MOSTRA_TELEMETRY_DEBUG"])) {
|
|
1315
|
+
for (const line of lines) options.stderr(`mostra telemetry (debug, not sent): ${line}\n`);
|
|
1316
|
+
return;
|
|
1317
|
+
}
|
|
1318
|
+
store.append(lines, now());
|
|
1319
|
+
if (options.flush !== false) startFlusher(store, options.env, now());
|
|
1320
|
+
}
|
|
1393
1321
|
}
|
|
1394
1322
|
/** `mostra telemetry status`: the decision, the install ID and the queue. */
|
|
1395
1323
|
function telemetryStatus(options) {
|
|
@@ -2116,7 +2044,7 @@ async function alwaysOnCheck(context) {
|
|
|
2116
2044
|
/** `mostra docs [topic]`. */
|
|
2117
2045
|
const docsCommand = defineCommand({
|
|
2118
2046
|
path: ["docs"],
|
|
2119
|
-
summary: "Print Mostra's reference: the CLI, telemetry, and every diagnostic code's page.",
|
|
2047
|
+
summary: "Print Mostra's reference: the guide to writing artifacts, the CLI, telemetry, and every diagnostic code's page.",
|
|
2120
2048
|
args: [{
|
|
2121
2049
|
name: "topic",
|
|
2122
2050
|
summary: "A topic or a diagnostic code. Default: the index.",
|
|
@@ -2151,7 +2079,7 @@ const docsCommand = defineCommand({
|
|
|
2151
2079
|
}
|
|
2152
2080
|
const found = topics.find((topic) => topic.topic === wanted || topic.topic === wanted.toUpperCase());
|
|
2153
2081
|
if (!found) throw usage(`No topic "${wanted}". The nearest: ${nearestTopics(wanted, topics).join(", ")}. Run "mostra docs" for the index.`);
|
|
2154
|
-
const markdown =
|
|
2082
|
+
const markdown = topicMarkdown(found);
|
|
2155
2083
|
return {
|
|
2156
2084
|
result: {
|
|
2157
2085
|
topic: found.topic,
|
|
@@ -2532,53 +2460,64 @@ const devCommand = defineCommand({
|
|
|
2532
2460
|
example: "dev ./sidebar-review",
|
|
2533
2461
|
streams: true,
|
|
2534
2462
|
async run(context) {
|
|
2535
|
-
const connection = await context.connection();
|
|
2536
|
-
let sessionId;
|
|
2537
|
-
const early = [];
|
|
2538
|
-
const show = (event) => {
|
|
2539
|
-
if (event.kind === "diagnostics") for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
|
|
2540
|
-
context.emit(event, line$1(event));
|
|
2541
|
-
};
|
|
2542
|
-
connection?.onNotification(DEV_NOTIFY, (params) => {
|
|
2543
|
-
const event = params;
|
|
2544
|
-
if (sessionId === void 0) early.push(event);
|
|
2545
|
-
else if (event.sessionId === sessionId) show(event);
|
|
2546
|
-
});
|
|
2547
|
-
const portFlag = context.flags["port"];
|
|
2548
|
-
const started = await context.call(devStartMethod, {
|
|
2549
|
-
source: sourceRef(arg(context, "path"), context.cwd),
|
|
2550
|
-
...typeof portFlag === "number" ? { port: portFlag } : {}
|
|
2551
|
-
});
|
|
2552
|
-
sessionId = started.sessionId;
|
|
2553
|
-
context.emit({
|
|
2554
|
-
kind: "started",
|
|
2555
|
-
...started
|
|
2556
|
-
}, `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`);
|
|
2557
|
-
for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
|
|
2558
|
-
let stop = () => {};
|
|
2559
2463
|
const signals = [
|
|
2560
2464
|
"SIGINT",
|
|
2561
2465
|
"SIGTERM",
|
|
2562
2466
|
"SIGBREAK"
|
|
2563
2467
|
];
|
|
2564
|
-
|
|
2565
|
-
|
|
2566
|
-
|
|
2567
|
-
|
|
2568
|
-
|
|
2569
|
-
for (const signal of signals) process.
|
|
2570
|
-
|
|
2571
|
-
|
|
2572
|
-
hint: "Run mostra dev again."
|
|
2573
|
-
}));
|
|
2574
|
-
await context.call(devStopMethod, { sessionId }).catch(() => void 0);
|
|
2575
|
-
return {
|
|
2576
|
-
result: {
|
|
2577
|
-
sessionId,
|
|
2578
|
-
stopped: "signal"
|
|
2579
|
-
},
|
|
2580
|
-
human: "Stopped.\n"
|
|
2468
|
+
let interrupted = false;
|
|
2469
|
+
let stop = () => {
|
|
2470
|
+
interrupted = true;
|
|
2471
|
+
};
|
|
2472
|
+
const onSignal = () => stop();
|
|
2473
|
+
for (const signal of signals) process.once(signal, onSignal);
|
|
2474
|
+
const release = () => {
|
|
2475
|
+
for (const signal of signals) process.off(signal, onSignal);
|
|
2581
2476
|
};
|
|
2477
|
+
try {
|
|
2478
|
+
const connection = await context.connection();
|
|
2479
|
+
let sessionId;
|
|
2480
|
+
const early = [];
|
|
2481
|
+
const show = (event) => {
|
|
2482
|
+
if (event.kind === "diagnostics") for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
|
|
2483
|
+
context.emit(event, line$1(event));
|
|
2484
|
+
};
|
|
2485
|
+
connection?.onNotification(DEV_NOTIFY, (params) => {
|
|
2486
|
+
const event = params;
|
|
2487
|
+
if (sessionId === void 0) early.push(event);
|
|
2488
|
+
else if (event.sessionId === sessionId) show(event);
|
|
2489
|
+
});
|
|
2490
|
+
const portFlag = context.flags["port"];
|
|
2491
|
+
const started = await context.call(devStartMethod, {
|
|
2492
|
+
source: sourceRef(arg(context, "path"), context.cwd),
|
|
2493
|
+
...typeof portFlag === "number" ? { port: portFlag } : {}
|
|
2494
|
+
});
|
|
2495
|
+
sessionId = started.sessionId;
|
|
2496
|
+
context.emit({
|
|
2497
|
+
kind: "started",
|
|
2498
|
+
...started
|
|
2499
|
+
}, `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`);
|
|
2500
|
+
for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
|
|
2501
|
+
const ended = interrupted ? "signal" : await new Promise((done) => {
|
|
2502
|
+
stop = () => done("signal");
|
|
2503
|
+
connection?.closed.then(() => done("closed"));
|
|
2504
|
+
});
|
|
2505
|
+
release();
|
|
2506
|
+
if (ended === "closed") throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
|
|
2507
|
+
message: "The instance ended the development preview (it stopped or restarted).",
|
|
2508
|
+
hint: "Run mostra dev again."
|
|
2509
|
+
}));
|
|
2510
|
+
await context.call(devStopMethod, { sessionId }).catch(() => void 0);
|
|
2511
|
+
return {
|
|
2512
|
+
result: {
|
|
2513
|
+
sessionId,
|
|
2514
|
+
stopped: "signal"
|
|
2515
|
+
},
|
|
2516
|
+
human: "Stopped.\n"
|
|
2517
|
+
};
|
|
2518
|
+
} finally {
|
|
2519
|
+
release();
|
|
2520
|
+
}
|
|
2582
2521
|
}
|
|
2583
2522
|
});
|
|
2584
2523
|
//#endregion
|
|
@@ -2590,6 +2529,17 @@ const devCommand = defineCommand({
|
|
|
2590
2529
|
*/
|
|
2591
2530
|
/** The longest one `wait` request may ask for (INTERFACES §6: 2^31 − 1 ms). */
|
|
2592
2531
|
const MAX_WAIT_MS = 2 ** 31 - 1;
|
|
2532
|
+
/**
|
|
2533
|
+
* What `wait` prints when its condition held: the event and cursor, and for a signal its name and
|
|
2534
|
+
* the payload the page or action sent (#115), which is otherwise only in `--json`.
|
|
2535
|
+
*/
|
|
2536
|
+
function satisfiedLine(event, cursor) {
|
|
2537
|
+
const line = `${event.type} at cursor ${cursor}`;
|
|
2538
|
+
if (event.type !== "signal.raised") return `${line}\n`;
|
|
2539
|
+
const name = typeof event.payload?.["name"] === "string" ? ` ${event.payload["name"]}` : "";
|
|
2540
|
+
const payload = event.payload !== void 0 && Object.hasOwn(event.payload, "payload") ? `\npayload: ${JSON.stringify(event.payload["payload"])}` : "";
|
|
2541
|
+
return `${event.type}${name} at cursor ${cursor}${payload}\n`;
|
|
2542
|
+
}
|
|
2593
2543
|
/** `mostra wait <artifact>`. */
|
|
2594
2544
|
const waitCommand = defineCommand({
|
|
2595
2545
|
path: ["wait"],
|
|
@@ -2641,7 +2591,7 @@ const waitCommand = defineCommand({
|
|
|
2641
2591
|
});
|
|
2642
2592
|
if (result.status === "satisfied") return {
|
|
2643
2593
|
result,
|
|
2644
|
-
human:
|
|
2594
|
+
human: satisfiedLine(result.event, result.cursor)
|
|
2645
2595
|
};
|
|
2646
2596
|
if (result.status !== "still_waiting") return {
|
|
2647
2597
|
result,
|
|
@@ -2911,253 +2861,64 @@ const statePatchCommand = defineCommand({
|
|
|
2911
2861
|
}
|
|
2912
2862
|
});
|
|
2913
2863
|
//#endregion
|
|
2914
|
-
//#region src/
|
|
2915
|
-
/**
|
|
2916
|
-
* `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
|
|
2917
|
-
* runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
|
|
2918
|
-
* identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
|
|
2919
|
-
* funnel`), whose link expires (1 hour by default, 7 days at most). The share lives in the
|
|
2920
|
-
* daemon, so the command returns at once with the link; `share stop` ends it and `share list`
|
|
2921
|
-
* shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
|
|
2922
|
-
*/
|
|
2923
|
-
const SHARE_ID = /^shr_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
2924
|
-
/** How each tunnel is named in human output. */
|
|
2925
|
-
const THROUGH = {
|
|
2926
|
-
tailnet: "Tailscale Serve, inside your tailnet",
|
|
2927
|
-
funnel: "Tailscale Funnel, public",
|
|
2928
|
-
cloudflare: "a Cloudflare quick tunnel, public"
|
|
2929
|
-
};
|
|
2864
|
+
//#region src/browser.ts
|
|
2930
2865
|
/**
|
|
2931
|
-
*
|
|
2932
|
-
*
|
|
2933
|
-
*
|
|
2934
|
-
*
|
|
2866
|
+
* Opening a browser on a launch URL without putting it on a command line (D140 item 15, Opus
|
|
2867
|
+
* review finding 4). A program's arguments are readable by every local user (`ps`,
|
|
2868
|
+
* `/proc/<pid>/cmdline`), so the opener gets the path of a page that redirects to the launch URL,
|
|
2869
|
+
* written mode 0600 in a fresh directory of mode 0700, as Jupyter's server does for its token.
|
|
2870
|
+
* Windows has no modes: there the page goes under the user's own profile
|
|
2871
|
+
* (`%LOCALAPPDATA%\mostra-cli\open`), whose access list only the user, `SYSTEM` and
|
|
2872
|
+
* administrators pass, never under `%TEMP%`, which may name a folder other users can read (Opus
|
|
2873
|
+
* review of WP-W2, finding 1). The launch ticket in the page is single-use and lives a minute, so a
|
|
2874
|
+
* page left behind is harmless; each launch removes the ones older than that.
|
|
2935
2875
|
*/
|
|
2936
|
-
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
|
|
2876
|
+
/** The prefix of the directories launch pages live in. */
|
|
2877
|
+
const PREFIX = "mostra-open-";
|
|
2878
|
+
/** A launch page older than this holds a ticket that expired: it goes on the next launch. */
|
|
2879
|
+
const STALE_MS = 12e4;
|
|
2880
|
+
/** Escapes text for an HTML attribute or element. */
|
|
2881
|
+
const html = (text) => text.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
2882
|
+
/** The page that sends the browser on to `url`. */
|
|
2883
|
+
function launchPage(url) {
|
|
2884
|
+
const script = JSON.stringify(url).replaceAll("<", "\\u003c");
|
|
2885
|
+
return `<!DOCTYPE html>
|
|
2886
|
+
<html lang="en">
|
|
2887
|
+
<head>
|
|
2888
|
+
<meta charset="utf-8">
|
|
2889
|
+
<meta name="referrer" content="no-referrer">
|
|
2890
|
+
<meta http-equiv="refresh" content="0;url=${html(url)}">
|
|
2891
|
+
<title>Opening Mostra</title>
|
|
2892
|
+
<script>location.replace(${script});<\/script>
|
|
2893
|
+
</head>
|
|
2894
|
+
<body>
|
|
2895
|
+
<p>Opening the artifact. If nothing happens, <a href="${html(url)}">open it here</a>.</p>
|
|
2896
|
+
</body>
|
|
2897
|
+
</html>
|
|
2898
|
+
`;
|
|
2940
2899
|
}
|
|
2941
|
-
/**
|
|
2942
|
-
function
|
|
2943
|
-
const
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
|
|
2949
|
-
|
|
2950
|
-
|
|
2951
|
-
name
|
|
2952
|
-
|
|
2953
|
-
|
|
2954
|
-
|
|
2955
|
-
|
|
2956
|
-
|
|
2957
|
-
|
|
2958
|
-
|
|
2959
|
-
|
|
2960
|
-
|
|
2961
|
-
|
|
2962
|
-
|
|
2963
|
-
summary: "Share publicly: anyone with the link can open it until it expires."
|
|
2964
|
-
},
|
|
2965
|
-
{
|
|
2966
|
-
name: "via",
|
|
2967
|
-
kind: "string",
|
|
2968
|
-
value: "<tunnel>",
|
|
2969
|
-
choices: ["cloudflare", "funnel"],
|
|
2970
|
-
default: "cloudflare",
|
|
2971
|
-
summary: "The public tunnel: a Cloudflare quick tunnel (no account), or Tailscale Funnel (shows your device's tailnet name)."
|
|
2972
|
-
},
|
|
2973
|
-
{
|
|
2974
|
-
name: "ttl",
|
|
2975
|
-
kind: "duration",
|
|
2976
|
-
value: "<d>",
|
|
2977
|
-
summary: "How long the link works, such as 30m or 24h. Public: 1h by default, 7d at most."
|
|
2978
|
-
},
|
|
2979
|
-
{
|
|
2980
|
-
name: "scope",
|
|
2981
|
-
kind: "list",
|
|
2982
|
-
value: "<a,b>",
|
|
2983
|
-
summary: "The link's scopes: view, draft, submit, review, signal, action:*. Default: all."
|
|
2984
|
-
},
|
|
2985
|
-
{
|
|
2986
|
-
name: "viewer",
|
|
2987
|
-
kind: "string",
|
|
2988
|
-
value: "<ref>",
|
|
2989
|
-
summary: "The person the link is for, by your own stable key for them; without it, each link is a viewer of its own."
|
|
2990
|
-
},
|
|
2991
|
-
{
|
|
2992
|
-
name: "viewer-name",
|
|
2993
|
-
kind: "string",
|
|
2994
|
-
value: "<name>",
|
|
2995
|
-
summary: "The display name of --viewer."
|
|
2996
|
-
},
|
|
2997
|
-
{
|
|
2998
|
-
name: "request-id",
|
|
2999
|
-
kind: "string",
|
|
3000
|
-
value: "<id>",
|
|
3001
|
-
summary: "Make a retried share return the same share instead of opening another."
|
|
3002
|
-
}
|
|
3003
|
-
],
|
|
3004
|
-
output: {
|
|
3005
|
-
type: "ShareStartResult",
|
|
3006
|
-
topic: "cli"
|
|
3007
|
-
},
|
|
3008
|
-
exits: [EXIT.failure, EXIT.environment],
|
|
3009
|
-
example: "share ./sidebar-review --public --ttl 2h",
|
|
3010
|
-
async run(context) {
|
|
3011
|
-
const artifact = artifactRef(arg(context, "artifact"), context.cwd);
|
|
3012
|
-
const tailnet = context.flags["tailnet"] === true;
|
|
3013
|
-
const publicly = context.flags["public"] === true;
|
|
3014
|
-
if (tailnet === publicly) throw usage("Give --tailnet or --public.");
|
|
3015
|
-
const viaFlag = flag(context, "via");
|
|
3016
|
-
if (viaFlag !== void 0 && !publicly) throw usage("--via chooses a public tunnel: add --public.");
|
|
3017
|
-
const via = tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
|
|
3018
|
-
const ttl = flag(context, "ttl");
|
|
3019
|
-
const scopes = context.flags["scope"];
|
|
3020
|
-
const viewerRef = flag(context, "viewer");
|
|
3021
|
-
const viewerName = flag(context, "viewer-name");
|
|
3022
|
-
const requestId = flag(context, "request-id");
|
|
3023
|
-
if (viewerName !== void 0 && viewerRef === void 0) throw usage("--viewer-name needs --viewer.");
|
|
3024
|
-
const share = await context.call(shareStartMethod, {
|
|
3025
|
-
artifact,
|
|
3026
|
-
via,
|
|
3027
|
-
...ttl !== void 0 ? { ttl } : {},
|
|
3028
|
-
...scopes !== void 0 ? { scopes } : {},
|
|
3029
|
-
...viewerRef !== void 0 ? { viewer: {
|
|
3030
|
-
ref: viewerRef,
|
|
3031
|
-
...viewerName !== void 0 ? { name: viewerName } : {}
|
|
3032
|
-
} } : {},
|
|
3033
|
-
...requestId !== void 0 ? { requestId } : {}
|
|
3034
|
-
});
|
|
3035
|
-
context.record({
|
|
3036
|
-
event: "share.done",
|
|
3037
|
-
fields: { kind: via }
|
|
3038
|
-
});
|
|
3039
|
-
const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
|
|
3040
|
-
return {
|
|
3041
|
-
result: share,
|
|
3042
|
-
human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`
|
|
3043
|
-
};
|
|
3044
|
-
}
|
|
3045
|
-
});
|
|
3046
|
-
/** `mostra share stop <artifact|shareId>`. */
|
|
3047
|
-
const shareStopCommand = defineCommand({
|
|
3048
|
-
path: ["share", "stop"],
|
|
3049
|
-
summary: "Stop a share, or every share of an artifact: its link stops working and its tunnel closes.",
|
|
3050
|
-
args: [{
|
|
3051
|
-
name: "target",
|
|
3052
|
-
summary: "A share's ID (shr_…), or an artifact's source path or ID."
|
|
3053
|
-
}],
|
|
3054
|
-
flags: [],
|
|
3055
|
-
output: {
|
|
3056
|
-
type: "ShareStopResult",
|
|
3057
|
-
topic: "cli"
|
|
3058
|
-
},
|
|
3059
|
-
exits: [EXIT.failure, EXIT.environment],
|
|
3060
|
-
example: "share stop ./sidebar-review",
|
|
3061
|
-
async run(context) {
|
|
3062
|
-
const target = arg(context, "target");
|
|
3063
|
-
const result = await context.call(shareStopMethod, SHARE_ID.test(target) ? { shareId: target } : { artifact: artifactRef(target, context.cwd) });
|
|
3064
|
-
return {
|
|
3065
|
-
result,
|
|
3066
|
-
human: result.stopped.length === 0 ? "Nothing was shared.\n" : result.stopped.map((share) => `Stopped ${share.shareId}\n`).join("")
|
|
3067
|
-
};
|
|
3068
|
-
}
|
|
3069
|
-
});
|
|
3070
|
-
/** `mostra share list [artifact] [--all]`. */
|
|
3071
|
-
const shareListCommand = defineCommand({
|
|
3072
|
-
path: ["share", "list"],
|
|
3073
|
-
summary: "List the active shares, of every artifact or of one; --all adds the ones that ended.",
|
|
3074
|
-
args: [{
|
|
3075
|
-
name: "artifact",
|
|
3076
|
-
summary: "Only this artifact's shares: its source path or ID.",
|
|
3077
|
-
optional: true
|
|
3078
|
-
}],
|
|
3079
|
-
flags: [{
|
|
3080
|
-
name: "all",
|
|
3081
|
-
kind: "boolean",
|
|
3082
|
-
summary: "Also list shares that ended, and why."
|
|
3083
|
-
}],
|
|
3084
|
-
output: {
|
|
3085
|
-
type: "ShareListResult",
|
|
3086
|
-
topic: "cli"
|
|
3087
|
-
},
|
|
3088
|
-
exits: [EXIT.failure],
|
|
3089
|
-
example: "share list --all",
|
|
3090
|
-
async run(context) {
|
|
3091
|
-
const given = context.args["artifact"];
|
|
3092
|
-
const result = await context.call(shareListMethod, {
|
|
3093
|
-
...typeof given === "string" ? { artifact: artifactRef(given, context.cwd) } : {},
|
|
3094
|
-
...context.flags["all"] === true ? { all: true } : {}
|
|
3095
|
-
});
|
|
3096
|
-
return {
|
|
3097
|
-
result,
|
|
3098
|
-
human: result.shares.length === 0 ? "Nothing is shared.\n" : `${result.shares.map((share) => line(share)).join("\n")}\n`
|
|
3099
|
-
};
|
|
3100
|
-
}
|
|
3101
|
-
});
|
|
3102
|
-
//#endregion
|
|
3103
|
-
//#region src/browser.ts
|
|
3104
|
-
/**
|
|
3105
|
-
* Opening a browser on a launch URL without putting it on a command line (D140 item 15, Opus
|
|
3106
|
-
* review finding 4). A program's arguments are readable by every local user (`ps`,
|
|
3107
|
-
* `/proc/<pid>/cmdline`), so the opener gets the path of a page that redirects to the launch URL,
|
|
3108
|
-
* written mode 0600 in a fresh directory of mode 0700, as Jupyter's server does for its token.
|
|
3109
|
-
* Windows has no modes: there the page goes under the user's own profile
|
|
3110
|
-
* (`%LOCALAPPDATA%\mostra-cli\open`), whose access list only the user, `SYSTEM` and
|
|
3111
|
-
* administrators pass, never under `%TEMP%`, which may name a folder other users can read (Opus
|
|
3112
|
-
* review of WP-W2, finding 1). The launch ticket in the page is single-use and lives a minute, so a
|
|
3113
|
-
* page left behind is harmless; each launch removes the ones older than that.
|
|
3114
|
-
*/
|
|
3115
|
-
/** The prefix of the directories launch pages live in. */
|
|
3116
|
-
const PREFIX = "mostra-open-";
|
|
3117
|
-
/** A launch page older than this holds a ticket that expired: it goes on the next launch. */
|
|
3118
|
-
const STALE_MS = 12e4;
|
|
3119
|
-
/** Escapes text for an HTML attribute or element. */
|
|
3120
|
-
const html = (text) => text.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
3121
|
-
/** The page that sends the browser on to `url`. */
|
|
3122
|
-
function launchPage(url) {
|
|
3123
|
-
const script = JSON.stringify(url).replaceAll("<", "\\u003c");
|
|
3124
|
-
return `<!DOCTYPE html>
|
|
3125
|
-
<html lang="en">
|
|
3126
|
-
<head>
|
|
3127
|
-
<meta charset="utf-8">
|
|
3128
|
-
<meta name="referrer" content="no-referrer">
|
|
3129
|
-
<meta http-equiv="refresh" content="0;url=${html(url)}">
|
|
3130
|
-
<title>Opening Mostra</title>
|
|
3131
|
-
<script>location.replace(${script});<\/script>
|
|
3132
|
-
</head>
|
|
3133
|
-
<body>
|
|
3134
|
-
<p>Opening the artifact. If nothing happens, <a href="${html(url)}">open it here</a>.</p>
|
|
3135
|
-
</body>
|
|
3136
|
-
</html>
|
|
3137
|
-
`;
|
|
3138
|
-
}
|
|
3139
|
-
/** Removes launch pages of earlier launches that are this user's and older than a minute or two. */
|
|
3140
|
-
function sweep(base, now) {
|
|
3141
|
-
const uid = process.getuid?.();
|
|
3142
|
-
let names;
|
|
3143
|
-
try {
|
|
3144
|
-
names = readdirSync(base);
|
|
3145
|
-
} catch {
|
|
3146
|
-
return;
|
|
3147
|
-
}
|
|
3148
|
-
for (const name of names) {
|
|
3149
|
-
if (!name.startsWith(PREFIX)) continue;
|
|
3150
|
-
const dir = join(base, name);
|
|
3151
|
-
try {
|
|
3152
|
-
const stats = lstatSync(dir);
|
|
3153
|
-
if (!stats.isDirectory() || uid !== void 0 && stats.uid !== uid) continue;
|
|
3154
|
-
if (now - stats.mtimeMs < STALE_MS) continue;
|
|
3155
|
-
rmSync(dir, {
|
|
3156
|
-
recursive: true,
|
|
3157
|
-
force: true
|
|
3158
|
-
});
|
|
3159
|
-
} catch {}
|
|
3160
|
-
}
|
|
2900
|
+
/** Removes launch pages of earlier launches that are this user's and older than a minute or two. */
|
|
2901
|
+
function sweep(base, now) {
|
|
2902
|
+
const uid = process.getuid?.();
|
|
2903
|
+
let names;
|
|
2904
|
+
try {
|
|
2905
|
+
names = readdirSync(base);
|
|
2906
|
+
} catch {
|
|
2907
|
+
return;
|
|
2908
|
+
}
|
|
2909
|
+
for (const name of names) {
|
|
2910
|
+
if (!name.startsWith(PREFIX)) continue;
|
|
2911
|
+
const dir = join(base, name);
|
|
2912
|
+
try {
|
|
2913
|
+
const stats = lstatSync(dir);
|
|
2914
|
+
if (!stats.isDirectory() || uid !== void 0 && stats.uid !== uid) continue;
|
|
2915
|
+
if (now - stats.mtimeMs < STALE_MS) continue;
|
|
2916
|
+
rmSync(dir, {
|
|
2917
|
+
recursive: true,
|
|
2918
|
+
force: true
|
|
2919
|
+
});
|
|
2920
|
+
} catch {}
|
|
2921
|
+
}
|
|
3161
2922
|
}
|
|
3162
2923
|
/** Writes the launch page for `url`; its path. */
|
|
3163
2924
|
function writeLaunchPage(url, base = tmpdir(), now = Date.now()) {
|
|
@@ -3301,13 +3062,798 @@ async function openInBrowser(url, env) {
|
|
|
3301
3062
|
recursive: true,
|
|
3302
3063
|
mode: 448
|
|
3303
3064
|
});
|
|
3304
|
-
page = writeLaunchPage(url, base);
|
|
3305
|
-
} catch {
|
|
3306
|
-
return false;
|
|
3065
|
+
page = writeLaunchPage(url, base);
|
|
3066
|
+
} catch {
|
|
3067
|
+
return false;
|
|
3068
|
+
}
|
|
3069
|
+
for (const command of browserCommands(page, env)) if (await start(command)) return true;
|
|
3070
|
+
return false;
|
|
3071
|
+
}
|
|
3072
|
+
//#endregion
|
|
3073
|
+
//#region src/client.ts
|
|
3074
|
+
/**
|
|
3075
|
+
* The CLI's connection to its home's instance (D45, D81, INTERFACES §9): it attaches to the
|
|
3076
|
+
* daemon recorded in `instance.json`, or starts one (`mostra-runtime daemon`, which itself
|
|
3077
|
+
* attaches when another starter won), and opens a session as `mostra-cli`. The SDK (WP-11) does
|
|
3078
|
+
* the same few steps over the same protocol.
|
|
3079
|
+
*/
|
|
3080
|
+
/** How long one attempt to reach a recorded socket waits. */
|
|
3081
|
+
const ATTACH_TIMEOUT_MS = 5e3;
|
|
3082
|
+
/** How long a daemon this command starts may take to say where it listens. */
|
|
3083
|
+
const START_TIMEOUT_MS = 3e4;
|
|
3084
|
+
/**
|
|
3085
|
+
* Opens a session with the home's instance, starting its daemon when none runs. Returns
|
|
3086
|
+
* `undefined` when `autostart` is false and no instance runs. Throws the start's diagnostic when
|
|
3087
|
+
* the daemon can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …).
|
|
3088
|
+
*/
|
|
3089
|
+
async function connect(options) {
|
|
3090
|
+
const recorded = readSocket(options.home);
|
|
3091
|
+
if (recorded !== void 0) {
|
|
3092
|
+
const session = await open(recorded, options, false).catch(() => void 0);
|
|
3093
|
+
if (session) return session;
|
|
3094
|
+
}
|
|
3095
|
+
if (options.autostart === false) return void 0;
|
|
3096
|
+
options.onStarting?.(true);
|
|
3097
|
+
let started;
|
|
3098
|
+
try {
|
|
3099
|
+
started = await startDaemon(options);
|
|
3100
|
+
} finally {
|
|
3101
|
+
options.onStarting?.(false);
|
|
3102
|
+
}
|
|
3103
|
+
return open(started.socket, options, started.status === "started");
|
|
3104
|
+
}
|
|
3105
|
+
/**
|
|
3106
|
+
* Opens the endpoint `instance.json` or a starting daemon named: a Unix socket, or on Windows the
|
|
3107
|
+
* owner-only pipe through the runtime's helper, which refuses a pipe another user created under
|
|
3108
|
+
* the name (D150, the SDK's `connectControl`). Only Windows needs the runtime resolved first.
|
|
3109
|
+
*/
|
|
3110
|
+
async function openEndpoint(endpoint, options) {
|
|
3111
|
+
const runtime = process.platform === "win32" ? (await locateRuntime(options.env)).runtime : void 0;
|
|
3112
|
+
return connectControl(endpoint, {
|
|
3113
|
+
runtime,
|
|
3114
|
+
env: options.env,
|
|
3115
|
+
timeoutMs: ATTACH_TIMEOUT_MS
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
/** The socket `instance.json` records (D81), if the file exists and reads. */
|
|
3119
|
+
function readSocket(home) {
|
|
3120
|
+
try {
|
|
3121
|
+
const record = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
|
|
3122
|
+
return typeof record.socket === "string" ? record.socket : void 0;
|
|
3123
|
+
} catch {
|
|
3124
|
+
return;
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
/**
|
|
3128
|
+
* Starts the home's daemon, detached from this process, and reads the one line it prints: where
|
|
3129
|
+
* it listens, or why it couldn't start. A daemon another starter won prints `attached` and exits.
|
|
3130
|
+
*/
|
|
3131
|
+
async function startDaemon(options) {
|
|
3132
|
+
const deadlineAt = Date.now() + START_TIMEOUT_MS;
|
|
3133
|
+
const timedOut = () => new RpcError(createDiagnostic("MOSTRA_HOST_TIMEOUT", { message: `The home's daemon didn't start within ${formatDuration(START_TIMEOUT_MS)}.` }));
|
|
3134
|
+
const runtime = await locateRuntime(options.env);
|
|
3135
|
+
if (Date.now() >= deadlineAt) throw timedOut();
|
|
3136
|
+
const args = [
|
|
3137
|
+
resolve(runtime.entry),
|
|
3138
|
+
"daemon",
|
|
3139
|
+
"--home",
|
|
3140
|
+
options.home
|
|
3141
|
+
];
|
|
3142
|
+
return new Promise((resolve, reject) => {
|
|
3143
|
+
const child = spawn(runtime.node, args, {
|
|
3144
|
+
detached: true,
|
|
3145
|
+
cwd: detachedDirectory(options.home),
|
|
3146
|
+
windowsHide: true,
|
|
3147
|
+
stdio: [
|
|
3148
|
+
"ignore",
|
|
3149
|
+
"pipe",
|
|
3150
|
+
"ignore"
|
|
3151
|
+
],
|
|
3152
|
+
env: detachedEnvironment({
|
|
3153
|
+
...process.env,
|
|
3154
|
+
...options.env
|
|
3155
|
+
})
|
|
3156
|
+
});
|
|
3157
|
+
const splitter = new LineSplitter();
|
|
3158
|
+
let settled = false;
|
|
3159
|
+
const finish = (outcome) => {
|
|
3160
|
+
if (settled) return;
|
|
3161
|
+
settled = true;
|
|
3162
|
+
clearTimeout(timer);
|
|
3163
|
+
child.stdout?.removeAllListeners("data");
|
|
3164
|
+
child.stdout?.destroy();
|
|
3165
|
+
child.unref();
|
|
3166
|
+
outcome();
|
|
3167
|
+
};
|
|
3168
|
+
const timer = setTimeout(() => finish(() => reject(timedOut())), Math.max(0, deadlineAt - Date.now()));
|
|
3169
|
+
child.on("error", (error) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_MISSING", { message: `The runtime couldn't be started: ${error.message}` })))));
|
|
3170
|
+
child.on("close", (code) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: `The home's daemon exited (${code ?? "signal"}) before it said where it listens.` })))));
|
|
3171
|
+
child.stdout?.setEncoding("utf8");
|
|
3172
|
+
child.stdout?.on("data", (chunk) => {
|
|
3173
|
+
for (const line of splitter.push(chunk)) {
|
|
3174
|
+
let parsed;
|
|
3175
|
+
try {
|
|
3176
|
+
parsed = JSON.parse(line);
|
|
3177
|
+
} catch {
|
|
3178
|
+
continue;
|
|
3179
|
+
}
|
|
3180
|
+
finish(() => {
|
|
3181
|
+
if (parsed.status === "failed") reject(new RpcError(parsed.diagnostic ?? createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: "The home's daemon failed to start." })));
|
|
3182
|
+
else resolve(parsed);
|
|
3183
|
+
});
|
|
3184
|
+
return;
|
|
3185
|
+
}
|
|
3186
|
+
});
|
|
3187
|
+
});
|
|
3188
|
+
}
|
|
3189
|
+
async function open(socketPath, options, started) {
|
|
3190
|
+
const socket = await openEndpoint(socketPath, options);
|
|
3191
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
3192
|
+
const peer = new RpcPeer({
|
|
3193
|
+
send: (message) => {
|
|
3194
|
+
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
3195
|
+
},
|
|
3196
|
+
onNotification: (method, params) => handlers.get(method)?.(params)
|
|
3197
|
+
});
|
|
3198
|
+
let markClosed = () => {};
|
|
3199
|
+
const closedPromise = new Promise((done) => {
|
|
3200
|
+
markClosed = done;
|
|
3201
|
+
});
|
|
3202
|
+
const splitter = new LineSplitter();
|
|
3203
|
+
socket.setEncoding("utf8");
|
|
3204
|
+
socket.on("data", (chunk) => {
|
|
3205
|
+
for (const line of splitter.push(chunk)) peer.receiveLine(line);
|
|
3206
|
+
});
|
|
3207
|
+
const end = () => {
|
|
3208
|
+
peer.close();
|
|
3209
|
+
markClosed();
|
|
3210
|
+
};
|
|
3211
|
+
socket.on("close", end);
|
|
3212
|
+
socket.on("error", () => socket.destroy());
|
|
3213
|
+
let result;
|
|
3214
|
+
try {
|
|
3215
|
+
result = await peer.call(mostraInitializeMethod, {
|
|
3216
|
+
client: {
|
|
3217
|
+
name: CLI_CLIENT_NAME,
|
|
3218
|
+
version: cliVersion()
|
|
3219
|
+
},
|
|
3220
|
+
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
3221
|
+
capabilities: { notifications: [ARTIFACT_PROGRESS, DEV_NOTIFY] },
|
|
3222
|
+
ports: [],
|
|
3223
|
+
home: { path: options.home }
|
|
3224
|
+
}, { timeoutMs: ATTACH_TIMEOUT_MS });
|
|
3225
|
+
} catch (error) {
|
|
3226
|
+
socket.destroy();
|
|
3227
|
+
throw error;
|
|
3228
|
+
}
|
|
3229
|
+
return {
|
|
3230
|
+
summary: {
|
|
3231
|
+
home: result.instance.home,
|
|
3232
|
+
socket: socketPath,
|
|
3233
|
+
pid: result.instance.pid,
|
|
3234
|
+
mode: result.instance.mode,
|
|
3235
|
+
version: result.instance.version,
|
|
3236
|
+
started
|
|
3237
|
+
},
|
|
3238
|
+
warnings: result.warnings,
|
|
3239
|
+
call: (method, params, timeoutMs) => peer.call(method, params, timeoutMs !== void 0 ? { timeoutMs } : {}),
|
|
3240
|
+
onNotification: (method, handler) => {
|
|
3241
|
+
handlers.set(method, handler);
|
|
3242
|
+
},
|
|
3243
|
+
closed: closedPromise,
|
|
3244
|
+
close: () => {
|
|
3245
|
+
peer.close();
|
|
3246
|
+
socket.end();
|
|
3247
|
+
socket.destroy();
|
|
3248
|
+
}
|
|
3249
|
+
};
|
|
3250
|
+
}
|
|
3251
|
+
/** A limit as people write it: `250 ms`, `5 s`, `1.5 s`. */
|
|
3252
|
+
function formatDuration(ms) {
|
|
3253
|
+
if (ms < 1e3) return `${ms} ms`;
|
|
3254
|
+
const seconds = ms / 1e3;
|
|
3255
|
+
return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)} s`;
|
|
3256
|
+
}
|
|
3257
|
+
/** The runtime install of {@link RuntimeInstall}, reporting its progress through `log`. */
|
|
3258
|
+
function runtimeInstall(options) {
|
|
3259
|
+
const testWait = Number(options.env["MOSTRA_TEST_RUNTIME_WAIT_MS"]);
|
|
3260
|
+
const waitMs = options.waitMs ?? (Number.isFinite(testWait) && testWait > 0 ? testWait : 45e3);
|
|
3261
|
+
const report = progressReporter({
|
|
3262
|
+
stderr: (text) => {
|
|
3263
|
+
for (const line of text.split("\n")) if (line.trim() !== "") options.log(line.trim());
|
|
3264
|
+
},
|
|
3265
|
+
stderrTty: false
|
|
3266
|
+
});
|
|
3267
|
+
let ready = false;
|
|
3268
|
+
let pending;
|
|
3269
|
+
let done;
|
|
3270
|
+
const start = () => {
|
|
3271
|
+
if (pending !== void 0) return pending;
|
|
3272
|
+
const installing = resolveRuntime({
|
|
3273
|
+
env: options.env,
|
|
3274
|
+
onProgress: (progress) => {
|
|
3275
|
+
if (progress.step === "download") done = `${Math.floor(progress.received / progress.total * 100)}% downloaded`;
|
|
3276
|
+
else if (progress.step === "files") done = "downloaded, checking its files";
|
|
3277
|
+
else if (progress.step === "browser") done = "fetching the browser verify uses";
|
|
3278
|
+
report(progress);
|
|
3279
|
+
}
|
|
3280
|
+
}).then(() => {
|
|
3281
|
+
ready = true;
|
|
3282
|
+
});
|
|
3283
|
+
pending = installing;
|
|
3284
|
+
installing.catch((error) => {
|
|
3285
|
+
if (pending === installing) pending = void 0;
|
|
3286
|
+
done = void 0;
|
|
3287
|
+
const diagnostic = error instanceof RpcError ? error.diagnostic : void 0;
|
|
3288
|
+
options.log(`mostra mcp: the runtime's install failed: ${diagnostic?.code ?? ""} ${diagnostic?.message ?? String(error)}`.trim());
|
|
3289
|
+
});
|
|
3290
|
+
return installing;
|
|
3291
|
+
};
|
|
3292
|
+
return {
|
|
3293
|
+
start() {
|
|
3294
|
+
start().catch(() => {});
|
|
3295
|
+
},
|
|
3296
|
+
async wait() {
|
|
3297
|
+
if (ready) return;
|
|
3298
|
+
const installing = start();
|
|
3299
|
+
let timer;
|
|
3300
|
+
const late = new Promise((_, reject) => {
|
|
3301
|
+
timer = setTimeout(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_INSTALLING", { message: `Mostra is installing its runtime for this release (${done ?? "starting the download"}); the install goes on.` }))), waitMs);
|
|
3302
|
+
timer.unref();
|
|
3303
|
+
});
|
|
3304
|
+
try {
|
|
3305
|
+
await Promise.race([installing, late]);
|
|
3306
|
+
} finally {
|
|
3307
|
+
clearTimeout(timer);
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
};
|
|
3311
|
+
}
|
|
3312
|
+
/** The home's daemon as the MCP server's instance (D164 item 5). */
|
|
3313
|
+
function daemonInstance(options) {
|
|
3314
|
+
const idleMs = options.idleMs ?? 3e5;
|
|
3315
|
+
const runtime = options.runtime;
|
|
3316
|
+
const opener = options.connect ?? connect;
|
|
3317
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
3318
|
+
let session;
|
|
3319
|
+
let host = false;
|
|
3320
|
+
let inflight = 0;
|
|
3321
|
+
let idle;
|
|
3322
|
+
const open = () => {
|
|
3323
|
+
if (session !== void 0) return session;
|
|
3324
|
+
const opening = opener({
|
|
3325
|
+
home: options.home,
|
|
3326
|
+
env: options.env
|
|
3327
|
+
}).then((connection) => {
|
|
3328
|
+
if (connection === void 0) throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: "No instance runs for this home." }));
|
|
3329
|
+
host = connection.summary.mode === "host";
|
|
3330
|
+
for (const warning of connection.warnings) options.log(`mostra mcp: ${warning.code}: ${warning.message}`);
|
|
3331
|
+
connection.onNotification(ARTIFACT_PROGRESS, (params) => {
|
|
3332
|
+
const progress = params;
|
|
3333
|
+
listeners.get(progress.progressToken)?.(progress);
|
|
3334
|
+
});
|
|
3335
|
+
connection.closed.then(() => {
|
|
3336
|
+
if (session === opening) session = void 0;
|
|
3337
|
+
});
|
|
3338
|
+
return connection;
|
|
3339
|
+
});
|
|
3340
|
+
session = opening;
|
|
3341
|
+
opening.catch(() => {
|
|
3342
|
+
if (session === opening) session = void 0;
|
|
3343
|
+
});
|
|
3344
|
+
return opening;
|
|
3345
|
+
};
|
|
3346
|
+
const release = () => {
|
|
3347
|
+
const current = session;
|
|
3348
|
+
session = void 0;
|
|
3349
|
+
current?.then((connection) => connection.close()).catch(() => {});
|
|
3350
|
+
};
|
|
3351
|
+
const settle = () => {
|
|
3352
|
+
inflight -= 1;
|
|
3353
|
+
if (inflight > 0) return;
|
|
3354
|
+
clearTimeout(idle);
|
|
3355
|
+
idle = setTimeout(release, idleMs);
|
|
3356
|
+
idle.unref();
|
|
3357
|
+
};
|
|
3358
|
+
return {
|
|
3359
|
+
async call(method, params) {
|
|
3360
|
+
inflight += 1;
|
|
3361
|
+
clearTimeout(idle);
|
|
3362
|
+
try {
|
|
3363
|
+
await runtime?.wait();
|
|
3364
|
+
const used = open();
|
|
3365
|
+
try {
|
|
3366
|
+
return await (await used).call(method, params);
|
|
3367
|
+
} catch (error) {
|
|
3368
|
+
if (!(error instanceof RpcError && error.diagnostic.code === "MOSTRA_HOST_CONNECTION_CLOSED") || method.mutating) throw error;
|
|
3369
|
+
if (session === used) session = void 0;
|
|
3370
|
+
return await (await open()).call(method, params);
|
|
3371
|
+
}
|
|
3372
|
+
} finally {
|
|
3373
|
+
settle();
|
|
3374
|
+
}
|
|
3375
|
+
},
|
|
3376
|
+
onProgress(token, listener) {
|
|
3377
|
+
listeners.set(token, listener);
|
|
3378
|
+
return () => listeners.delete(token);
|
|
3379
|
+
},
|
|
3380
|
+
hostInstance: () => host,
|
|
3381
|
+
close() {
|
|
3382
|
+
clearTimeout(idle);
|
|
3383
|
+
release();
|
|
3384
|
+
}
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
/** The bundled reference (`mostra docs`), read as the MCP server's docs. */
|
|
3388
|
+
function bundledDocs() {
|
|
3389
|
+
let topics;
|
|
3390
|
+
const all = () => {
|
|
3391
|
+
topics ??= docsIndex();
|
|
3392
|
+
return topics;
|
|
3393
|
+
};
|
|
3394
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3395
|
+
return {
|
|
3396
|
+
topics: () => all().map((topic) => ({
|
|
3397
|
+
topic: topic.topic,
|
|
3398
|
+
title: topic.title,
|
|
3399
|
+
url: topic.url
|
|
3400
|
+
})),
|
|
3401
|
+
read(topic) {
|
|
3402
|
+
const cached = cache.get(topic);
|
|
3403
|
+
if (cached !== void 0) return cached;
|
|
3404
|
+
const found = all().find((entry) => entry.topic === topic);
|
|
3405
|
+
if (found === void 0) return void 0;
|
|
3406
|
+
const markdown = topicMarkdown(found, skillDir(), MCP_GUIDE_LINKS);
|
|
3407
|
+
cache.set(topic, markdown);
|
|
3408
|
+
return markdown;
|
|
3409
|
+
}
|
|
3410
|
+
};
|
|
3411
|
+
}
|
|
3412
|
+
/** The daemon instance, with the runtime's install started at once (D164 item 7). */
|
|
3413
|
+
function startInstance(options) {
|
|
3414
|
+
const runtime = runtimeInstall({
|
|
3415
|
+
env: options.env,
|
|
3416
|
+
log: options.log
|
|
3417
|
+
});
|
|
3418
|
+
runtime.start();
|
|
3419
|
+
return daemonInstance({
|
|
3420
|
+
...options,
|
|
3421
|
+
runtime
|
|
3422
|
+
});
|
|
3423
|
+
}
|
|
3424
|
+
function factoryFor(options, instance) {
|
|
3425
|
+
return createMcpServerFactory({
|
|
3426
|
+
instance,
|
|
3427
|
+
workspace: localWorkspace(options.workspace),
|
|
3428
|
+
docs: bundledDocs(),
|
|
3429
|
+
browser: { open: (url) => openInBrowser(url, options.env) },
|
|
3430
|
+
version: options.version,
|
|
3431
|
+
onClient: (client) => options.onClient(client, instance)
|
|
3432
|
+
});
|
|
3433
|
+
}
|
|
3434
|
+
/** Resolves when the process is asked to stop: Ctrl-C, SIGTERM, SIGHUP, or Ctrl+Break on Windows. */
|
|
3435
|
+
function stopSignal() {
|
|
3436
|
+
return new Promise((resolve) => {
|
|
3437
|
+
for (const signal of [
|
|
3438
|
+
"SIGINT",
|
|
3439
|
+
"SIGTERM",
|
|
3440
|
+
"SIGHUP",
|
|
3441
|
+
"SIGBREAK"
|
|
3442
|
+
]) process.once(signal, () => resolve(signal));
|
|
3443
|
+
});
|
|
3444
|
+
}
|
|
3445
|
+
/** Serves over stdio until the client closes stdin or the process is stopped. */
|
|
3446
|
+
async function serveOverStdio(options) {
|
|
3447
|
+
const instance = startInstance(options);
|
|
3448
|
+
const handle = serveStdio(factoryFor(options, instance), { onerror: (error) => options.log(`mostra mcp: ${error.message}`) });
|
|
3449
|
+
const ended = new Promise((resolve) => {
|
|
3450
|
+
process.stdin.once("end", () => resolve("stdin"));
|
|
3451
|
+
process.stdin.once("close", () => resolve("stdin"));
|
|
3452
|
+
});
|
|
3453
|
+
await Promise.race([ended, stopSignal()]);
|
|
3454
|
+
await handle.close().catch(() => {});
|
|
3455
|
+
instance.close();
|
|
3456
|
+
return instance;
|
|
3457
|
+
}
|
|
3458
|
+
/** The address and URL host of `--bind` and `--url-host` (D99's rules, D164 item 3). */
|
|
3459
|
+
function mcpBind(options) {
|
|
3460
|
+
const fail = (message) => new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message }));
|
|
3461
|
+
const address = (options.bind ?? "127.0.0.1").replace(/^\[(.*)\]$/, "$1");
|
|
3462
|
+
if (isIP(address) === 0) throw fail(`--bind takes an IP address, such as 127.0.0.1, not "${options.bind}".`);
|
|
3463
|
+
if (options.urlHost !== void 0 && options.bind === void 0) throw fail("--url-host needs --bind: without it the server listens on 127.0.0.1 only.");
|
|
3464
|
+
const canonical = new URL(`http://${isIP(address) === 6 ? `[${address}]` : address}/`).hostname;
|
|
3465
|
+
if ((canonical === "0.0.0.0" || canonical === "[::]" || canonical === "[::ffff:0:0]") && options.urlHost === void 0) throw fail(`--bind ${options.bind} listens on every interface; name the host clients use with --url-host.`);
|
|
3466
|
+
if (options.urlHost !== void 0 && !/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+)$/i.test(options.urlHost)) throw fail(`--url-host takes a host name or an IP address, not "${options.urlHost}".`);
|
|
3467
|
+
return {
|
|
3468
|
+
address,
|
|
3469
|
+
urlHost: (options.urlHost ?? canonical).toLowerCase()
|
|
3470
|
+
};
|
|
3471
|
+
}
|
|
3472
|
+
/** The fewest distinct characters a chosen token must have, so `aaaa…` isn't accepted. */
|
|
3473
|
+
const TOKEN_VARIETY = 8;
|
|
3474
|
+
/** The bearer token: `MOSTRA_MCP_TOKEN`, or one made for this run (160 bits). */
|
|
3475
|
+
function mcpToken(env) {
|
|
3476
|
+
const given = env["MOSTRA_MCP_TOKEN"];
|
|
3477
|
+
if (given !== void 0 && given !== "") {
|
|
3478
|
+
if (given.length < 26 || /\s/.test(given) || new Set(given).size < TOKEN_VARIETY) throw new RpcError(createDiagnostic("MOSTRA_CLI_USAGE", { message: `MOSTRA_MCP_TOKEN must be at least 26 characters, with no spaces and at least ${TOKEN_VARIETY} different characters: a random one, such as from \`openssl rand -hex 20\`.` }));
|
|
3479
|
+
return {
|
|
3480
|
+
token: given,
|
|
3481
|
+
generated: false
|
|
3482
|
+
};
|
|
3483
|
+
}
|
|
3484
|
+
return {
|
|
3485
|
+
token: randomBytes(20).toString("base64url"),
|
|
3486
|
+
generated: true
|
|
3487
|
+
};
|
|
3488
|
+
}
|
|
3489
|
+
/** A request's headers as `[name, value]` pairs in arrival order (Node's `rawHeaders`). */
|
|
3490
|
+
function pairs(incoming) {
|
|
3491
|
+
const raw = incoming.rawHeaders;
|
|
3492
|
+
const out = [];
|
|
3493
|
+
for (let index = 0; index + 1 < raw.length; index += 2) out.push([raw[index], raw[index + 1]]);
|
|
3494
|
+
return out;
|
|
3495
|
+
}
|
|
3496
|
+
/** Serves Streamable HTTP until the process is stopped; tells `onListening` where. */
|
|
3497
|
+
async function serveOverHttp(options) {
|
|
3498
|
+
const { address, urlHost } = mcpBind({
|
|
3499
|
+
...options.bind !== void 0 ? { bind: options.bind } : {},
|
|
3500
|
+
...options.urlHost !== void 0 ? { urlHost: options.urlHost } : {}
|
|
3501
|
+
});
|
|
3502
|
+
const { token, generated } = mcpToken(options.env);
|
|
3503
|
+
const instance = startInstance(options);
|
|
3504
|
+
const factory = factoryFor(options, instance);
|
|
3505
|
+
let endpoint;
|
|
3506
|
+
const server = serve({
|
|
3507
|
+
fetch: (request, env) => {
|
|
3508
|
+
if (endpoint === void 0) return new Response(null, { status: 503 });
|
|
3509
|
+
return endpoint.fetch(request, {
|
|
3510
|
+
target: env.incoming.url ?? "/",
|
|
3511
|
+
headers: pairs(env.incoming)
|
|
3512
|
+
});
|
|
3513
|
+
},
|
|
3514
|
+
port: options.port,
|
|
3515
|
+
hostname: address
|
|
3516
|
+
});
|
|
3517
|
+
const port = await new Promise((resolve, reject) => {
|
|
3518
|
+
server.once("error", (error) => reject(new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message: `The MCP server couldn't listen on ${address}:${options.port} (${error.code ?? error.message}).` }))));
|
|
3519
|
+
server.once("listening", () => {
|
|
3520
|
+
const bound = server.address();
|
|
3521
|
+
resolve(typeof bound === "object" && bound !== null ? bound.port : options.port);
|
|
3522
|
+
});
|
|
3523
|
+
});
|
|
3524
|
+
if ("keepAliveTimeout" in server) {
|
|
3525
|
+
server.keepAliveTimeout = 305e3;
|
|
3526
|
+
server.headersTimeout = 306e3;
|
|
3527
|
+
}
|
|
3528
|
+
const origin = `http://${urlHost}:${port}`;
|
|
3529
|
+
endpoint = createHttpEndpoint(factory, {
|
|
3530
|
+
origin,
|
|
3531
|
+
hosts: [`${urlHost}:${port}`],
|
|
3532
|
+
token,
|
|
3533
|
+
onRefusal: (refused) => options.log(`mostra mcp: refused a request (${refused.status} ${refused.code})`),
|
|
3534
|
+
onError: (error) => options.log(`mostra mcp: ${error.message}`)
|
|
3535
|
+
});
|
|
3536
|
+
options.onListening({
|
|
3537
|
+
url: `${origin}${MCP_PATH}`,
|
|
3538
|
+
port,
|
|
3539
|
+
token,
|
|
3540
|
+
generated
|
|
3541
|
+
});
|
|
3542
|
+
await stopSignal();
|
|
3543
|
+
await endpoint.close().catch(() => {});
|
|
3544
|
+
await new Promise((resolve) => {
|
|
3545
|
+
server.close(() => resolve());
|
|
3546
|
+
server.closeAllConnections?.();
|
|
3547
|
+
});
|
|
3548
|
+
instance.close();
|
|
3549
|
+
return instance;
|
|
3550
|
+
}
|
|
3551
|
+
//#endregion
|
|
3552
|
+
//#region src/commands/mcp.ts
|
|
3553
|
+
/**
|
|
3554
|
+
* `mostra mcp` (INTERFACES §12, D164): Mostra's MCP server, for any MCP client. Over stdio by
|
|
3555
|
+
* default (a client starts it), or Streamable HTTP with `--http`. Its tools are `@mostra/mcp`'s;
|
|
3556
|
+
* this command gives them the home's daemon, the workspace and the reference, and counts each
|
|
3557
|
+
* MCP client in telemetry unless `--embedded` says a host or harness plugin started it (D148).
|
|
3558
|
+
*/
|
|
3559
|
+
/** `mostra mcp`. */
|
|
3560
|
+
const mcpCommand = defineCommand({
|
|
3561
|
+
path: ["mcp"],
|
|
3562
|
+
summary: "Run Mostra's MCP server, so an MCP client can create, verify and publish artifacts, wait for answers and read results.",
|
|
3563
|
+
flags: [
|
|
3564
|
+
{
|
|
3565
|
+
name: "http",
|
|
3566
|
+
kind: "boolean",
|
|
3567
|
+
summary: "Serve Streamable HTTP at /mcp instead of stdio; every request needs Authorization: Bearer <token>."
|
|
3568
|
+
},
|
|
3569
|
+
{
|
|
3570
|
+
name: "port",
|
|
3571
|
+
kind: "number",
|
|
3572
|
+
value: "<port>",
|
|
3573
|
+
summary: "With --http, the port; default one the system picks."
|
|
3574
|
+
},
|
|
3575
|
+
{
|
|
3576
|
+
name: "bind",
|
|
3577
|
+
kind: "string",
|
|
3578
|
+
value: "<address>",
|
|
3579
|
+
summary: "With --http, listen on this address instead of 127.0.0.1."
|
|
3580
|
+
},
|
|
3581
|
+
{
|
|
3582
|
+
name: "url-host",
|
|
3583
|
+
kind: "string",
|
|
3584
|
+
value: "<name>",
|
|
3585
|
+
summary: "With --http, the host name clients use; a wildcard --bind needs it."
|
|
3586
|
+
},
|
|
3587
|
+
{
|
|
3588
|
+
name: "workspace",
|
|
3589
|
+
kind: "string",
|
|
3590
|
+
value: "<dir>",
|
|
3591
|
+
summary: "Where relative artifact directories and new artifacts go. Default: MOSTRA_MCP_WORKSPACE, else ~/mostra-artifacts."
|
|
3592
|
+
},
|
|
3593
|
+
{
|
|
3594
|
+
name: "embedded",
|
|
3595
|
+
kind: "boolean",
|
|
3596
|
+
summary: "This server runs on someone's behalf (a harness plugin or another host started it), so it sends no telemetry."
|
|
3597
|
+
}
|
|
3598
|
+
],
|
|
3599
|
+
output: {
|
|
3600
|
+
type: "the MCP protocol on stdin and stdout, or over HTTP",
|
|
3601
|
+
topic: "cli"
|
|
3602
|
+
},
|
|
3603
|
+
exits: [],
|
|
3604
|
+
example: "mcp",
|
|
3605
|
+
readsStdin: (flags) => flags["http"] !== true,
|
|
3606
|
+
quiet: (flags) => flags["embedded"] === true,
|
|
3607
|
+
async run(context) {
|
|
3608
|
+
const http = context.flags["http"] === true;
|
|
3609
|
+
const port = context.flags["port"];
|
|
3610
|
+
const bind = flag(context, "bind");
|
|
3611
|
+
const urlHost = flag(context, "url-host");
|
|
3612
|
+
if (!http && (port !== void 0 || bind !== void 0 || urlHost !== void 0)) throw usage("--port, --bind and --url-host go with --http.");
|
|
3613
|
+
if (typeof port === "number" && (!Number.isInteger(port) || port < 0 || port > 65535)) throw usage("--port takes a port number from 0 to 65535.");
|
|
3614
|
+
const given = flag(context, "workspace") ?? context.env["MOSTRA_MCP_WORKSPACE"];
|
|
3615
|
+
const workspace = given !== void 0 && given !== "" ? resolve(context.cwd, given) : defaultWorkspaceRoot();
|
|
3616
|
+
const counted = /* @__PURE__ */ new Set();
|
|
3617
|
+
let reached;
|
|
3618
|
+
const options = {
|
|
3619
|
+
home: context.home,
|
|
3620
|
+
env: context.env,
|
|
3621
|
+
workspace,
|
|
3622
|
+
version: cliVersion(),
|
|
3623
|
+
log: context.log,
|
|
3624
|
+
onClient(client, instance) {
|
|
3625
|
+
reached = instance;
|
|
3626
|
+
const fields = mcpSessionFields(client);
|
|
3627
|
+
const key = `${fields.client}@${fields.clientVersion ?? ""}`;
|
|
3628
|
+
if (counted.has(key)) return;
|
|
3629
|
+
counted.add(key);
|
|
3630
|
+
context.record({
|
|
3631
|
+
event: "mcp.session",
|
|
3632
|
+
fields
|
|
3633
|
+
});
|
|
3634
|
+
context.checkpoint(instance.hostInstance() || embeddedHome(readHomeMarks(context.home)));
|
|
3635
|
+
}
|
|
3636
|
+
};
|
|
3637
|
+
const done = {
|
|
3638
|
+
result: void 0,
|
|
3639
|
+
raw: true
|
|
3640
|
+
};
|
|
3641
|
+
if (!http) {
|
|
3642
|
+
await serveOverStdio(options);
|
|
3643
|
+
return {
|
|
3644
|
+
...done,
|
|
3645
|
+
hostInstance: reached?.hostInstance() === true
|
|
3646
|
+
};
|
|
3647
|
+
}
|
|
3648
|
+
await serveOverHttp({
|
|
3649
|
+
...options,
|
|
3650
|
+
port: typeof port === "number" ? port : 0,
|
|
3651
|
+
...bind !== void 0 ? { bind } : {},
|
|
3652
|
+
...urlHost !== void 0 ? { urlHost } : {},
|
|
3653
|
+
onListening({ url, token, generated }) {
|
|
3654
|
+
if (context.json) context.emit({
|
|
3655
|
+
kind: "listening",
|
|
3656
|
+
url
|
|
3657
|
+
});
|
|
3658
|
+
else context.stderr(`Mostra's MCP server is listening at ${url}\n`);
|
|
3659
|
+
context.stderr(generated ? `Send Authorization: Bearer ${token} with every request (set MOSTRA_MCP_TOKEN to choose the token).\n` : "Send Authorization: Bearer <MOSTRA_MCP_TOKEN> with every request.\n");
|
|
3660
|
+
}
|
|
3661
|
+
});
|
|
3662
|
+
return {
|
|
3663
|
+
...done,
|
|
3664
|
+
hostInstance: reached?.hostInstance() === true
|
|
3665
|
+
};
|
|
3666
|
+
}
|
|
3667
|
+
});
|
|
3668
|
+
//#endregion
|
|
3669
|
+
//#region src/commands/sharing.ts
|
|
3670
|
+
/**
|
|
3671
|
+
* `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
|
|
3672
|
+
* runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
|
|
3673
|
+
* identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
|
|
3674
|
+
* funnel`), whose link expires (1 hour by default, 7 days at most). The share lives in the
|
|
3675
|
+
* daemon, so the command returns at once with the link; `share stop` ends it and `share list`
|
|
3676
|
+
* shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
|
|
3677
|
+
*/
|
|
3678
|
+
const SHARE_ID = /^shr_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
3679
|
+
/** How each tunnel is named in human output. */
|
|
3680
|
+
const THROUGH = {
|
|
3681
|
+
tailnet: "Tailscale Serve, inside your tailnet",
|
|
3682
|
+
funnel: "Tailscale Funnel, public",
|
|
3683
|
+
cloudflare: "a Cloudflare quick tunnel, public"
|
|
3684
|
+
};
|
|
3685
|
+
/**
|
|
3686
|
+
* What a tailnet viewer's device needs, found on a real tailnet in WP-13: the tailnet's access
|
|
3687
|
+
* policy must let them reach the share's two ports of this device, and their browser's traffic
|
|
3688
|
+
* must go through Tailscale (no private or secure DNS of its own, no split tunneling that leaves
|
|
3689
|
+
* the browser out).
|
|
3690
|
+
*/
|
|
3691
|
+
function tailnetReach(share) {
|
|
3692
|
+
const port = (origin) => origin === void 0 ? void 0 : new URL(origin).port || "443";
|
|
3693
|
+
const ports = [port(share.url), port(share.artifactOrigin)].filter((value) => value !== void 0);
|
|
3694
|
+
return `Viewers need this device's port${ports.length === 1 ? "" : "s"} ${ports.join(" and ")} allowed by the tailnet's access policy, and their browser's traffic sent through Tailscale.\n`;
|
|
3695
|
+
}
|
|
3696
|
+
/** One share as a line of human output. */
|
|
3697
|
+
function line(share) {
|
|
3698
|
+
const until = share.state === "stopped" ? `stopped${share.stopReason ? ` (${share.stopReason})` : ""}` : share.expiresAt ? `until ${share.expiresAt}` : "no expiry";
|
|
3699
|
+
return `${share.shareId} ${share.via} ${share.hostname} ${until}`;
|
|
3700
|
+
}
|
|
3701
|
+
/** `mostra share <artifact> --tailnet | --public`. */
|
|
3702
|
+
const shareCommand = defineCommand({
|
|
3703
|
+
path: ["share"],
|
|
3704
|
+
summary: "Open an artifact to people beyond this machine: inside your tailnet, or publicly with a link that expires.",
|
|
3705
|
+
args: [{
|
|
3706
|
+
name: "artifact",
|
|
3707
|
+
summary: "The artifact: its source path or its ID."
|
|
3708
|
+
}],
|
|
3709
|
+
flags: [
|
|
3710
|
+
{
|
|
3711
|
+
name: "tailnet",
|
|
3712
|
+
kind: "boolean",
|
|
3713
|
+
summary: "Share inside your tailnet through Tailscale Serve; each viewer is their tailnet identity."
|
|
3714
|
+
},
|
|
3715
|
+
{
|
|
3716
|
+
name: "public",
|
|
3717
|
+
kind: "boolean",
|
|
3718
|
+
summary: "Share publicly: anyone with the link can open it until it expires."
|
|
3719
|
+
},
|
|
3720
|
+
{
|
|
3721
|
+
name: "via",
|
|
3722
|
+
kind: "string",
|
|
3723
|
+
value: "<tunnel>",
|
|
3724
|
+
choices: ["cloudflare", "funnel"],
|
|
3725
|
+
default: "cloudflare",
|
|
3726
|
+
summary: "The public tunnel: a Cloudflare quick tunnel (no account), or Tailscale Funnel (shows your device's tailnet name)."
|
|
3727
|
+
},
|
|
3728
|
+
{
|
|
3729
|
+
name: "ttl",
|
|
3730
|
+
kind: "duration",
|
|
3731
|
+
value: "<d>",
|
|
3732
|
+
summary: "How long the link works, such as 30m or 24h. Public: 1h by default, 7d at most."
|
|
3733
|
+
},
|
|
3734
|
+
{
|
|
3735
|
+
name: "scope",
|
|
3736
|
+
kind: "list",
|
|
3737
|
+
value: "<a,b>",
|
|
3738
|
+
summary: "The link's scopes: view, draft, submit, review, signal, action:*. Default: all."
|
|
3739
|
+
},
|
|
3740
|
+
{
|
|
3741
|
+
name: "viewer",
|
|
3742
|
+
kind: "string",
|
|
3743
|
+
value: "<ref>",
|
|
3744
|
+
summary: "The person the link is for, by your own stable key for them; without it, each link is a viewer of its own."
|
|
3745
|
+
},
|
|
3746
|
+
{
|
|
3747
|
+
name: "viewer-name",
|
|
3748
|
+
kind: "string",
|
|
3749
|
+
value: "<name>",
|
|
3750
|
+
summary: "The display name of --viewer."
|
|
3751
|
+
},
|
|
3752
|
+
{
|
|
3753
|
+
name: "request-id",
|
|
3754
|
+
kind: "string",
|
|
3755
|
+
value: "<id>",
|
|
3756
|
+
summary: "Make a retried share return the same share instead of opening another."
|
|
3757
|
+
}
|
|
3758
|
+
],
|
|
3759
|
+
output: {
|
|
3760
|
+
type: "ShareStartResult",
|
|
3761
|
+
topic: "cli"
|
|
3762
|
+
},
|
|
3763
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3764
|
+
example: "share ./sidebar-review --public --ttl 2h",
|
|
3765
|
+
async run(context) {
|
|
3766
|
+
const artifact = artifactRef(arg(context, "artifact"), context.cwd);
|
|
3767
|
+
const tailnet = context.flags["tailnet"] === true;
|
|
3768
|
+
const publicly = context.flags["public"] === true;
|
|
3769
|
+
if (tailnet === publicly) throw usage("Give --tailnet or --public.");
|
|
3770
|
+
const viaFlag = flag(context, "via");
|
|
3771
|
+
if (viaFlag !== void 0 && !publicly) throw usage("--via chooses a public tunnel: add --public.");
|
|
3772
|
+
const via = tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
|
|
3773
|
+
const ttl = flag(context, "ttl");
|
|
3774
|
+
const scopes = context.flags["scope"];
|
|
3775
|
+
const viewerRef = flag(context, "viewer");
|
|
3776
|
+
const viewerName = flag(context, "viewer-name");
|
|
3777
|
+
const requestId = flag(context, "request-id");
|
|
3778
|
+
if (viewerName !== void 0 && viewerRef === void 0) throw usage("--viewer-name needs --viewer.");
|
|
3779
|
+
const share = await context.call(shareStartMethod, {
|
|
3780
|
+
artifact,
|
|
3781
|
+
via,
|
|
3782
|
+
...ttl !== void 0 ? { ttl } : {},
|
|
3783
|
+
...scopes !== void 0 ? { scopes } : {},
|
|
3784
|
+
...viewerRef !== void 0 ? { viewer: {
|
|
3785
|
+
ref: viewerRef,
|
|
3786
|
+
...viewerName !== void 0 ? { name: viewerName } : {}
|
|
3787
|
+
} } : {},
|
|
3788
|
+
...requestId !== void 0 ? { requestId } : {}
|
|
3789
|
+
});
|
|
3790
|
+
context.record({
|
|
3791
|
+
event: "share.done",
|
|
3792
|
+
fields: { kind: via }
|
|
3793
|
+
});
|
|
3794
|
+
const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
|
|
3795
|
+
return {
|
|
3796
|
+
result: share,
|
|
3797
|
+
human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`
|
|
3798
|
+
};
|
|
3799
|
+
}
|
|
3800
|
+
});
|
|
3801
|
+
/** `mostra share stop <artifact|shareId>`. */
|
|
3802
|
+
const shareStopCommand = defineCommand({
|
|
3803
|
+
path: ["share", "stop"],
|
|
3804
|
+
summary: "Stop a share, or every share of an artifact: its link stops working and its tunnel closes.",
|
|
3805
|
+
args: [{
|
|
3806
|
+
name: "target",
|
|
3807
|
+
summary: "A share's ID (shr_…), or an artifact's source path or ID."
|
|
3808
|
+
}],
|
|
3809
|
+
flags: [],
|
|
3810
|
+
output: {
|
|
3811
|
+
type: "ShareStopResult",
|
|
3812
|
+
topic: "cli"
|
|
3813
|
+
},
|
|
3814
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3815
|
+
example: "share stop ./sidebar-review",
|
|
3816
|
+
async run(context) {
|
|
3817
|
+
const target = arg(context, "target");
|
|
3818
|
+
const result = await context.call(shareStopMethod, SHARE_ID.test(target) ? { shareId: target } : { artifact: artifactRef(target, context.cwd) });
|
|
3819
|
+
return {
|
|
3820
|
+
result,
|
|
3821
|
+
human: result.stopped.length === 0 ? "Nothing was shared.\n" : result.stopped.map((share) => `Stopped ${share.shareId}\n`).join("")
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
});
|
|
3825
|
+
/** `mostra share list [artifact] [--all]`. */
|
|
3826
|
+
const shareListCommand = defineCommand({
|
|
3827
|
+
path: ["share", "list"],
|
|
3828
|
+
summary: "List the active shares, of every artifact or of one; --all adds the ones that ended.",
|
|
3829
|
+
args: [{
|
|
3830
|
+
name: "artifact",
|
|
3831
|
+
summary: "Only this artifact's shares: its source path or ID.",
|
|
3832
|
+
optional: true
|
|
3833
|
+
}],
|
|
3834
|
+
flags: [{
|
|
3835
|
+
name: "all",
|
|
3836
|
+
kind: "boolean",
|
|
3837
|
+
summary: "Also list shares that ended, and why."
|
|
3838
|
+
}],
|
|
3839
|
+
output: {
|
|
3840
|
+
type: "ShareListResult",
|
|
3841
|
+
topic: "cli"
|
|
3842
|
+
},
|
|
3843
|
+
exits: [EXIT.failure],
|
|
3844
|
+
example: "share list --all",
|
|
3845
|
+
async run(context) {
|
|
3846
|
+
const given = context.args["artifact"];
|
|
3847
|
+
const result = await context.call(shareListMethod, {
|
|
3848
|
+
...typeof given === "string" ? { artifact: artifactRef(given, context.cwd) } : {},
|
|
3849
|
+
...context.flags["all"] === true ? { all: true } : {}
|
|
3850
|
+
});
|
|
3851
|
+
return {
|
|
3852
|
+
result,
|
|
3853
|
+
human: result.shares.length === 0 ? "Nothing is shared.\n" : `${result.shares.map((share) => line(share)).join("\n")}\n`
|
|
3854
|
+
};
|
|
3307
3855
|
}
|
|
3308
|
-
|
|
3309
|
-
return false;
|
|
3310
|
-
}
|
|
3856
|
+
});
|
|
3311
3857
|
//#endregion
|
|
3312
3858
|
//#region src/commands/viewing.ts
|
|
3313
3859
|
/**
|
|
@@ -3488,6 +4034,7 @@ const COMMANDS = [
|
|
|
3488
4034
|
daemonInstallCommand,
|
|
3489
4035
|
daemonUninstallCommand,
|
|
3490
4036
|
hostCommand,
|
|
4037
|
+
mcpCommand,
|
|
3491
4038
|
docsCommand,
|
|
3492
4039
|
doctorCommand,
|
|
3493
4040
|
gcCommand,
|
|
@@ -3531,7 +4078,11 @@ function flagLine(flag) {
|
|
|
3531
4078
|
return ` ${name.padEnd(28)} ${flag.summary}${choices}${fallback}`;
|
|
3532
4079
|
}
|
|
3533
4080
|
/** Commands that run until their connection or Ctrl-C ends them: `--timeout` doesn't bound them. */
|
|
3534
|
-
const UNBOUNDED = /* @__PURE__ */ new Set([
|
|
4081
|
+
const UNBOUNDED = /* @__PURE__ */ new Set([
|
|
4082
|
+
"host",
|
|
4083
|
+
"dev",
|
|
4084
|
+
"mcp"
|
|
4085
|
+
]);
|
|
3535
4086
|
/**
|
|
3536
4087
|
* The global flags a command doesn't define again (`wait --timeout` is the wait's own); a command
|
|
3537
4088
|
* `--timeout` doesn't bound has no `--timeout`.
|
|
@@ -3652,191 +4203,6 @@ function referenceMarkdown(commands) {
|
|
|
3652
4203
|
].join("\n");
|
|
3653
4204
|
}
|
|
3654
4205
|
//#endregion
|
|
3655
|
-
//#region src/client.ts
|
|
3656
|
-
/**
|
|
3657
|
-
* The CLI's connection to its home's instance (D45, D81, INTERFACES §9): it attaches to the
|
|
3658
|
-
* daemon recorded in `instance.json`, or starts one (`mostra-runtime daemon`, which itself
|
|
3659
|
-
* attaches when another starter won), and opens a session as `mostra-cli`. The SDK (WP-11) does
|
|
3660
|
-
* the same few steps over the same protocol.
|
|
3661
|
-
*/
|
|
3662
|
-
/** How long one attempt to reach a recorded socket waits. */
|
|
3663
|
-
const ATTACH_TIMEOUT_MS = 5e3;
|
|
3664
|
-
/** How long a daemon this command starts may take to say where it listens. */
|
|
3665
|
-
const START_TIMEOUT_MS = 3e4;
|
|
3666
|
-
/**
|
|
3667
|
-
* Opens a session with the home's instance, starting its daemon when none runs. Returns
|
|
3668
|
-
* `undefined` when `autostart` is false and no instance runs. Throws the start's diagnostic when
|
|
3669
|
-
* the daemon can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …).
|
|
3670
|
-
*/
|
|
3671
|
-
async function connect(options) {
|
|
3672
|
-
const recorded = readSocket(options.home);
|
|
3673
|
-
if (recorded !== void 0) {
|
|
3674
|
-
const session = await open(recorded, options, false).catch(() => void 0);
|
|
3675
|
-
if (session) return session;
|
|
3676
|
-
}
|
|
3677
|
-
if (options.autostart === false) return void 0;
|
|
3678
|
-
options.onStarting?.(true);
|
|
3679
|
-
let started;
|
|
3680
|
-
try {
|
|
3681
|
-
started = await startDaemon(options);
|
|
3682
|
-
} finally {
|
|
3683
|
-
options.onStarting?.(false);
|
|
3684
|
-
}
|
|
3685
|
-
return open(started.socket, options, started.status === "started");
|
|
3686
|
-
}
|
|
3687
|
-
/**
|
|
3688
|
-
* Opens the endpoint `instance.json` or a starting daemon named: a Unix socket, or on Windows the
|
|
3689
|
-
* owner-only pipe through the runtime's helper, which refuses a pipe another user created under
|
|
3690
|
-
* the name (D150, the SDK's `connectControl`). Only Windows needs the runtime resolved first.
|
|
3691
|
-
*/
|
|
3692
|
-
async function openEndpoint(endpoint, options) {
|
|
3693
|
-
const runtime = process.platform === "win32" ? (await locateRuntime(options.env)).runtime : void 0;
|
|
3694
|
-
return connectControl(endpoint, {
|
|
3695
|
-
runtime,
|
|
3696
|
-
env: options.env,
|
|
3697
|
-
timeoutMs: ATTACH_TIMEOUT_MS
|
|
3698
|
-
});
|
|
3699
|
-
}
|
|
3700
|
-
/** The socket `instance.json` records (D81), if the file exists and reads. */
|
|
3701
|
-
function readSocket(home) {
|
|
3702
|
-
try {
|
|
3703
|
-
const record = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
|
|
3704
|
-
return typeof record.socket === "string" ? record.socket : void 0;
|
|
3705
|
-
} catch {
|
|
3706
|
-
return;
|
|
3707
|
-
}
|
|
3708
|
-
}
|
|
3709
|
-
/**
|
|
3710
|
-
* Starts the home's daemon, detached from this process, and reads the one line it prints: where
|
|
3711
|
-
* it listens, or why it couldn't start. A daemon another starter won prints `attached` and exits.
|
|
3712
|
-
*/
|
|
3713
|
-
async function startDaemon(options) {
|
|
3714
|
-
const deadlineAt = Date.now() + START_TIMEOUT_MS;
|
|
3715
|
-
const timedOut = () => new RpcError(createDiagnostic("MOSTRA_HOST_TIMEOUT", { message: `The home's daemon didn't start within ${formatDuration(START_TIMEOUT_MS)}.` }));
|
|
3716
|
-
const runtime = await locateRuntime(options.env);
|
|
3717
|
-
if (Date.now() >= deadlineAt) throw timedOut();
|
|
3718
|
-
const args = [
|
|
3719
|
-
resolve(runtime.entry),
|
|
3720
|
-
"daemon",
|
|
3721
|
-
"--home",
|
|
3722
|
-
options.home
|
|
3723
|
-
];
|
|
3724
|
-
return new Promise((resolve, reject) => {
|
|
3725
|
-
const child = spawn(runtime.node, args, {
|
|
3726
|
-
detached: true,
|
|
3727
|
-
cwd: detachedDirectory(options.home),
|
|
3728
|
-
windowsHide: true,
|
|
3729
|
-
stdio: [
|
|
3730
|
-
"ignore",
|
|
3731
|
-
"pipe",
|
|
3732
|
-
"ignore"
|
|
3733
|
-
],
|
|
3734
|
-
env: detachedEnvironment({
|
|
3735
|
-
...process.env,
|
|
3736
|
-
...options.env
|
|
3737
|
-
})
|
|
3738
|
-
});
|
|
3739
|
-
const splitter = new LineSplitter();
|
|
3740
|
-
let settled = false;
|
|
3741
|
-
const finish = (outcome) => {
|
|
3742
|
-
if (settled) return;
|
|
3743
|
-
settled = true;
|
|
3744
|
-
clearTimeout(timer);
|
|
3745
|
-
child.stdout?.removeAllListeners("data");
|
|
3746
|
-
child.stdout?.destroy();
|
|
3747
|
-
child.unref();
|
|
3748
|
-
outcome();
|
|
3749
|
-
};
|
|
3750
|
-
const timer = setTimeout(() => finish(() => reject(timedOut())), Math.max(0, deadlineAt - Date.now()));
|
|
3751
|
-
child.on("error", (error) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_MISSING", { message: `The runtime couldn't be started: ${error.message}` })))));
|
|
3752
|
-
child.on("close", (code) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: `The home's daemon exited (${code ?? "signal"}) before it said where it listens.` })))));
|
|
3753
|
-
child.stdout?.setEncoding("utf8");
|
|
3754
|
-
child.stdout?.on("data", (chunk) => {
|
|
3755
|
-
for (const line of splitter.push(chunk)) {
|
|
3756
|
-
let parsed;
|
|
3757
|
-
try {
|
|
3758
|
-
parsed = JSON.parse(line);
|
|
3759
|
-
} catch {
|
|
3760
|
-
continue;
|
|
3761
|
-
}
|
|
3762
|
-
finish(() => {
|
|
3763
|
-
if (parsed.status === "failed") reject(new RpcError(parsed.diagnostic ?? createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: "The home's daemon failed to start." })));
|
|
3764
|
-
else resolve(parsed);
|
|
3765
|
-
});
|
|
3766
|
-
return;
|
|
3767
|
-
}
|
|
3768
|
-
});
|
|
3769
|
-
});
|
|
3770
|
-
}
|
|
3771
|
-
async function open(socketPath, options, started) {
|
|
3772
|
-
const socket = await openEndpoint(socketPath, options);
|
|
3773
|
-
const handlers = /* @__PURE__ */ new Map();
|
|
3774
|
-
const peer = new RpcPeer({
|
|
3775
|
-
send: (message) => {
|
|
3776
|
-
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
3777
|
-
},
|
|
3778
|
-
onNotification: (method, params) => handlers.get(method)?.(params)
|
|
3779
|
-
});
|
|
3780
|
-
let markClosed = () => {};
|
|
3781
|
-
const closedPromise = new Promise((done) => {
|
|
3782
|
-
markClosed = done;
|
|
3783
|
-
});
|
|
3784
|
-
const splitter = new LineSplitter();
|
|
3785
|
-
socket.setEncoding("utf8");
|
|
3786
|
-
socket.on("data", (chunk) => {
|
|
3787
|
-
for (const line of splitter.push(chunk)) peer.receiveLine(line);
|
|
3788
|
-
});
|
|
3789
|
-
const end = () => {
|
|
3790
|
-
peer.close();
|
|
3791
|
-
markClosed();
|
|
3792
|
-
};
|
|
3793
|
-
socket.on("close", end);
|
|
3794
|
-
socket.on("error", () => socket.destroy());
|
|
3795
|
-
let result;
|
|
3796
|
-
try {
|
|
3797
|
-
result = await peer.call(mostraInitializeMethod, {
|
|
3798
|
-
client: {
|
|
3799
|
-
name: CLI_CLIENT_NAME,
|
|
3800
|
-
version: cliVersion()
|
|
3801
|
-
},
|
|
3802
|
-
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
3803
|
-
capabilities: { notifications: [ARTIFACT_PROGRESS, DEV_NOTIFY] },
|
|
3804
|
-
ports: [],
|
|
3805
|
-
home: { path: options.home }
|
|
3806
|
-
}, { timeoutMs: ATTACH_TIMEOUT_MS });
|
|
3807
|
-
} catch (error) {
|
|
3808
|
-
socket.destroy();
|
|
3809
|
-
throw error;
|
|
3810
|
-
}
|
|
3811
|
-
return {
|
|
3812
|
-
summary: {
|
|
3813
|
-
home: result.instance.home,
|
|
3814
|
-
socket: socketPath,
|
|
3815
|
-
pid: result.instance.pid,
|
|
3816
|
-
mode: result.instance.mode,
|
|
3817
|
-
version: result.instance.version,
|
|
3818
|
-
started
|
|
3819
|
-
},
|
|
3820
|
-
warnings: result.warnings,
|
|
3821
|
-
call: (method, params, timeoutMs) => peer.call(method, params, timeoutMs !== void 0 ? { timeoutMs } : {}),
|
|
3822
|
-
onNotification: (method, handler) => {
|
|
3823
|
-
handlers.set(method, handler);
|
|
3824
|
-
},
|
|
3825
|
-
closed: closedPromise,
|
|
3826
|
-
close: () => {
|
|
3827
|
-
peer.close();
|
|
3828
|
-
socket.end();
|
|
3829
|
-
socket.destroy();
|
|
3830
|
-
}
|
|
3831
|
-
};
|
|
3832
|
-
}
|
|
3833
|
-
/** A limit as people write it: `250 ms`, `5 s`, `1.5 s`. */
|
|
3834
|
-
function formatDuration(ms) {
|
|
3835
|
-
if (ms < 1e3) return `${ms} ms`;
|
|
3836
|
-
const seconds = ms / 1e3;
|
|
3837
|
-
return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)} s`;
|
|
3838
|
-
}
|
|
3839
|
-
//#endregion
|
|
3840
4206
|
//#region src/run.ts
|
|
3841
4207
|
/**
|
|
3842
4208
|
* The runner (INTERFACES §9, D140 item 16): reads the command line, runs one command, and owns
|
|
@@ -3960,7 +4326,7 @@ async function run(io) {
|
|
|
3960
4326
|
json,
|
|
3961
4327
|
tty: io.tty,
|
|
3962
4328
|
readsStdin,
|
|
3963
|
-
quiet: command.quiet === true,
|
|
4329
|
+
quiet: typeof command.quiet === "function" ? command.quiet(parsed.flags) : command.quiet === true,
|
|
3964
4330
|
hostHome: embeddedHome(marks),
|
|
3965
4331
|
stderr: io.stderr,
|
|
3966
4332
|
ask: (question, timeoutMs) => ask(io, question, timeoutMs)
|
|
@@ -4026,22 +4392,30 @@ async function run(io) {
|
|
|
4026
4392
|
io.stderr(describe(diagnostic));
|
|
4027
4393
|
},
|
|
4028
4394
|
record: (event) => telemetry.record(event),
|
|
4395
|
+
checkpoint(hostInstance) {
|
|
4396
|
+
try {
|
|
4397
|
+
telemetry.checkpoint({ hostInstance });
|
|
4398
|
+
} catch {}
|
|
4399
|
+
},
|
|
4029
4400
|
runtime: (args, stdio = "pipe") => runRuntime(io, args, stdio)
|
|
4030
4401
|
};
|
|
4031
4402
|
let exit;
|
|
4032
4403
|
let error;
|
|
4404
|
+
let ownHostInstance = false;
|
|
4033
4405
|
try {
|
|
4034
4406
|
if (!await telemetry.begin().catch(() => true)) return 130;
|
|
4035
4407
|
const outcome = await withTimeout(command, context, timeoutMs, () => startingDaemon);
|
|
4036
4408
|
exit = outcome.exit ?? EXIT.ok;
|
|
4037
|
-
|
|
4038
|
-
if (
|
|
4039
|
-
|
|
4040
|
-
|
|
4041
|
-
|
|
4042
|
-
|
|
4043
|
-
|
|
4044
|
-
|
|
4409
|
+
ownHostInstance = outcome.hostInstance === true;
|
|
4410
|
+
if (outcome.raw !== true) {
|
|
4411
|
+
if (json) writeJson({
|
|
4412
|
+
ok: true,
|
|
4413
|
+
result: outcome.result ?? null,
|
|
4414
|
+
...summary && !streamed && command.local !== true ? { instance: summary } : {},
|
|
4415
|
+
warnings
|
|
4416
|
+
});
|
|
4417
|
+
else io.stdout(outcome.human ?? `${JSON.stringify(outcome.result, null, 2)}\n`);
|
|
4418
|
+
}
|
|
4045
4419
|
} catch (caught) {
|
|
4046
4420
|
const diagnostic = diagnosticOf(caught);
|
|
4047
4421
|
error = diagnostic.code;
|
|
@@ -4053,7 +4427,7 @@ async function run(io) {
|
|
|
4053
4427
|
telemetry.end({
|
|
4054
4428
|
exit,
|
|
4055
4429
|
durationMs: Date.now() - started,
|
|
4056
|
-
hostInstance: summary?.mode === "host",
|
|
4430
|
+
hostInstance: summary?.mode === "host" || ownHostInstance,
|
|
4057
4431
|
...error !== void 0 ? { error } : {}
|
|
4058
4432
|
});
|
|
4059
4433
|
} catch {}
|
|
@@ -4064,7 +4438,7 @@ async function run(io) {
|
|
|
4064
4438
|
* until their connection or Ctrl-C ends them, so `--timeout` bounds neither.
|
|
4065
4439
|
*/
|
|
4066
4440
|
async function withTimeout(command, context, timeoutMs, startingDaemon) {
|
|
4067
|
-
if (timeoutMs === void 0 ||
|
|
4441
|
+
if (timeoutMs === void 0 || UNBOUNDED.has(command.path[0] ?? "")) return command.run(context);
|
|
4068
4442
|
let timer;
|
|
4069
4443
|
try {
|
|
4070
4444
|
return await Promise.race([command.run(context), new Promise((_, reject) => {
|
|
@@ -4106,4 +4480,4 @@ async function runRuntime(io, args, stdio) {
|
|
|
4106
4480
|
//#endregion
|
|
4107
4481
|
export { COMMANDS as a, referenceMarkdown as i, commandDefinition as n, commandHelp as r, run as t };
|
|
4108
4482
|
|
|
4109
|
-
//# sourceMappingURL=run-
|
|
4483
|
+
//# sourceMappingURL=run-DdYT3iHQ.js.map
|