@mostra/cli 0.8.0 → 0.10.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-BStzS_41.js +1 -0
- package/dist/bootstrap-_iCl_HaO.js +423 -0
- package/dist/bootstrap-_iCl_HaO.js.map +1 -0
- package/dist/{flush-CBN3AU9X.js → flush-znWmNZA1.js} +34 -5
- package/dist/flush-znWmNZA1.js.map +1 -0
- package/dist/index.d.ts +14 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/reference/cli.md +177 -4
- package/dist/reference/diagnostics.json +129 -3
- package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
- 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_HOME_NETWORK_FILESYSTEM.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
- package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +3 -3
- package/dist/reference/telemetry.md +5 -3
- package/dist/{run-CuMkFuH7.js → run-Aq4HVIY0.js} +1244 -767
- package/dist/run-Aq4HVIY0.js.map +1 -0
- package/dist/run-D1U_RFEP.js +1 -0
- package/dist/skill/SKILL.md +6 -3
- package/dist/skill/references/answers.md +37 -1
- package/dist/skill/references/long-lived.md +2 -2
- package/dist/skill/references/mcp.md +63 -0
- package/dist/skill/references/sharing.md +54 -4
- package/dist/telemetry/flush-main.js +1 -1
- package/package.json +10 -4
- package/src/bootstrap.ts +16 -3
- package/src/client.ts +1 -1
- package/src/command.ts +13 -3
- package/src/commands/admin.ts +11 -1
- package/src/commands/authoring.ts +85 -3
- package/src/commands/dev.ts +60 -44
- package/src/commands/index.ts +18 -3
- package/src/commands/interaction.ts +19 -1
- package/src/commands/mcp.ts +128 -0
- package/src/commands/remote.ts +113 -0
- package/src/commands/sharing.ts +33 -6
- package/src/commands/viewing.ts +20 -2
- package/src/detached.ts +3 -0
- package/src/docs.ts +14 -6
- package/src/exit.ts +2 -0
- 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/src/telemetry/store.ts +15 -4
- 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-3WlZ2Jos.js +0 -1
- package/dist/run-CuMkFuH7.js.map +0 -1
|
@@ -1,24 +1,17 @@
|
|
|
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-_iCl_HaO.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-znWmNZA1.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
5
|
import { extname, isAbsolute, join, resolve, win32 } from "node:path";
|
|
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";
|
|
6
|
+
import { ARTIFACT_PROGRESS, CLI_CLIENT_NAME, DEFAULT_DOCS_BASE, DEV_NOTIFY, FieldOp, HOST_PROTOCOL_REVISIONS, LineSplitter, MutationId, RpcError, RpcPeer, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, diagnosticCatalog, encodeLine, gcRunMethod, instanceCheckMethod, instanceStatusMethod, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, 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
|
|
@@ -142,11 +135,13 @@ const FENCE_LANGUAGES = {
|
|
|
142
135
|
};
|
|
143
136
|
/** How the guide's relative links read through the CLI, before each of its pages. */
|
|
144
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`).";
|
|
145
140
|
/**
|
|
146
|
-
* A topic's Markdown. A guide page loses its frontmatter and says how its links read through the
|
|
147
|
-
* CLI; a guide topic made of files shows each one as code under its path.
|
|
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.
|
|
148
143
|
*/
|
|
149
|
-
function topicMarkdown(topic, dir = skillDir()) {
|
|
144
|
+
function topicMarkdown(topic, dir = skillDir(), links = GUIDE_LINKS) {
|
|
150
145
|
if (topic.files !== void 0) {
|
|
151
146
|
const parts = topic.files.map((path) => {
|
|
152
147
|
const text = readFileSync(join(dir, "assets", path), "utf8");
|
|
@@ -157,7 +152,7 @@ function topicMarkdown(topic, dir = skillDir()) {
|
|
|
157
152
|
return [
|
|
158
153
|
`# ${topic.title}`,
|
|
159
154
|
"",
|
|
160
|
-
|
|
155
|
+
links,
|
|
161
156
|
"",
|
|
162
157
|
...parts
|
|
163
158
|
].join("\n");
|
|
@@ -165,7 +160,7 @@ function topicMarkdown(topic, dir = skillDir()) {
|
|
|
165
160
|
const text = readFileSync(topic.file, "utf8");
|
|
166
161
|
if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
|
|
167
162
|
return [
|
|
168
|
-
|
|
163
|
+
links,
|
|
169
164
|
"",
|
|
170
165
|
text.replace(/^---\n[\s\S]*?\n---\n+/, "")
|
|
171
166
|
].join("\n");
|
|
@@ -265,9 +260,11 @@ function configDir(env, cwd, platform = process.platform) {
|
|
|
265
260
|
}
|
|
266
261
|
/**
|
|
267
262
|
* The runtime the CLI starts (D85, RT-01), found as the SDK finds it: `MOSTRA_BUNDLE`,
|
|
268
|
-
* `MOSTRA_RUNTIME_BIN`, the runtime bundle this CLI sits in,
|
|
269
|
-
* runtime beside it. The bootstrap (`bootstrap.ts`) has already moved
|
|
270
|
-
* 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.
|
|
271
268
|
*/
|
|
272
269
|
async function locateRuntime(env) {
|
|
273
270
|
const runtime = await resolveRuntime({ env });
|
|
@@ -308,205 +305,6 @@ function readHomeMarks(home) {
|
|
|
308
305
|
}
|
|
309
306
|
}
|
|
310
307
|
//#endregion
|
|
311
|
-
//#region src/parse.ts
|
|
312
|
-
/**
|
|
313
|
-
* The command line, read against the command definitions (D140 item 13): the global flags, the
|
|
314
|
-
* command path, its arguments and flags. Every failure is `MOSTRA_CLI_USAGE` or
|
|
315
|
-
* `MOSTRA_CLI_UNKNOWN_COMMAND`, so `--json` mode reports it like any other error.
|
|
316
|
-
*/
|
|
317
|
-
/** The flags every command takes (INTERFACES §9). */
|
|
318
|
-
const GLOBAL_FLAGS = [
|
|
319
|
-
{
|
|
320
|
-
name: "json",
|
|
321
|
-
kind: "boolean",
|
|
322
|
-
summary: "Print one JSON envelope on stdout (NDJSON for streams)."
|
|
323
|
-
},
|
|
324
|
-
{
|
|
325
|
-
name: "home",
|
|
326
|
-
kind: "string",
|
|
327
|
-
value: "<dir>",
|
|
328
|
-
summary: "Use this Mostra home instead of MOSTRA_HOME or the default."
|
|
329
|
-
},
|
|
330
|
-
{
|
|
331
|
-
name: "cwd",
|
|
332
|
-
kind: "string",
|
|
333
|
-
value: "<dir>",
|
|
334
|
-
summary: "Resolve relative paths from this directory."
|
|
335
|
-
},
|
|
336
|
-
{
|
|
337
|
-
name: "timeout",
|
|
338
|
-
kind: "duration",
|
|
339
|
-
value: "<d>",
|
|
340
|
-
summary: "Give up on the instance after this long (exit 4), such as 30s or 5m."
|
|
341
|
-
},
|
|
342
|
-
{
|
|
343
|
-
name: "help",
|
|
344
|
-
kind: "boolean",
|
|
345
|
-
summary: "Show this command's help; with --json, its definition."
|
|
346
|
-
}
|
|
347
|
-
];
|
|
348
|
-
/** A usage error. */
|
|
349
|
-
function usage(message) {
|
|
350
|
-
return new RpcError(createDiagnostic("MOSTRA_CLI_USAGE", { message }));
|
|
351
|
-
}
|
|
352
|
-
const DURATION = /^([1-9][0-9]*)(ms|s|m|h|d)$/;
|
|
353
|
-
const UNIT_MS = {
|
|
354
|
-
ms: 1,
|
|
355
|
-
s: 1e3,
|
|
356
|
-
m: 6e4,
|
|
357
|
-
h: 36e5,
|
|
358
|
-
d: 864e5
|
|
359
|
-
};
|
|
360
|
-
/** A duration flag's milliseconds: `30s`, `5m`, `2h`, `7d`, `500ms`. */
|
|
361
|
-
function durationMs(value) {
|
|
362
|
-
const match = DURATION.exec(value);
|
|
363
|
-
if (!match) throw usage(`"${value}" isn't a duration; use a number with ms, s, m, h or d, such as 30s.`);
|
|
364
|
-
return Number(match[1]) * UNIT_MS[match[2]];
|
|
365
|
-
}
|
|
366
|
-
/**
|
|
367
|
-
* Reads the global flags wherever they stand, before the command is known: `--json` anywhere
|
|
368
|
-
* before `--` makes even a usage error a JSON envelope (D140 item 16).
|
|
369
|
-
*/
|
|
370
|
-
function globalFlags(argv) {
|
|
371
|
-
const end = argv.indexOf("--");
|
|
372
|
-
const words = end === -1 ? argv : argv.slice(0, end);
|
|
373
|
-
const value = (name) => {
|
|
374
|
-
for (let index = 0; index < words.length; index += 1) {
|
|
375
|
-
const word = words[index];
|
|
376
|
-
if (word === `--${name}`) return words[index + 1];
|
|
377
|
-
if (word.startsWith(`--${name}=`)) return word.slice(name.length + 3);
|
|
378
|
-
}
|
|
379
|
-
};
|
|
380
|
-
const timeout = value("timeout");
|
|
381
|
-
let timeoutMs;
|
|
382
|
-
try {
|
|
383
|
-
timeoutMs = timeout === void 0 ? void 0 : durationMs(timeout);
|
|
384
|
-
} catch {
|
|
385
|
-
timeoutMs = void 0;
|
|
386
|
-
}
|
|
387
|
-
const home = value("home");
|
|
388
|
-
const cwd = value("cwd");
|
|
389
|
-
return {
|
|
390
|
-
json: words.includes("--json"),
|
|
391
|
-
...home !== void 0 ? { home } : {},
|
|
392
|
-
...cwd !== void 0 ? { cwd } : {},
|
|
393
|
-
...timeoutMs !== void 0 ? { timeoutMs } : {}
|
|
394
|
-
};
|
|
395
|
-
}
|
|
396
|
-
/** The command that names `words`' longest prefix. */
|
|
397
|
-
function findCommand(commands, words) {
|
|
398
|
-
let best;
|
|
399
|
-
for (const command of commands) {
|
|
400
|
-
const { path } = command;
|
|
401
|
-
if (path.length <= words.length && path.every((word, index) => words[index] === word)) {
|
|
402
|
-
if (!best || path.length > best.used) best = {
|
|
403
|
-
command,
|
|
404
|
-
used: path.length
|
|
405
|
-
};
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
return best;
|
|
409
|
-
}
|
|
410
|
-
/** The first words of every command: the groups and the single-word commands. */
|
|
411
|
-
function topWords(commands) {
|
|
412
|
-
return [...new Set(commands.map((command) => command.path[0]))].sort();
|
|
413
|
-
}
|
|
414
|
-
/** Parses the command line against the definitions. Throws a usage diagnostic. */
|
|
415
|
-
function parseCommandLine(commands, argv) {
|
|
416
|
-
const bare = argv.filter((word) => word !== "--json");
|
|
417
|
-
if (bare.length === 1 && (bare[0] === "--version" || bare[0] === "-v")) return { kind: "version" };
|
|
418
|
-
const words = [];
|
|
419
|
-
const pathAt = [];
|
|
420
|
-
for (let index = 0; index < argv.length; index += 1) {
|
|
421
|
-
const word = argv[index];
|
|
422
|
-
if (word === "--json" || word === "--help" || word === "-h") continue;
|
|
423
|
-
if (word === "--home" || word === "--cwd" || word === "--timeout") {
|
|
424
|
-
index += 1;
|
|
425
|
-
continue;
|
|
426
|
-
}
|
|
427
|
-
if (/^--(home|cwd|timeout)=/.test(word)) continue;
|
|
428
|
-
if (word.startsWith("-")) break;
|
|
429
|
-
words.push(word);
|
|
430
|
-
pathAt.push(index);
|
|
431
|
-
}
|
|
432
|
-
const helpAsked = argv.includes("--help") || argv.includes("-h");
|
|
433
|
-
if (words.length === 0) {
|
|
434
|
-
if (helpAsked || argv.every((word) => word === "--json")) return { kind: "help" };
|
|
435
|
-
throw usage(`Name a command first; ${argv[0]} isn't one.`);
|
|
436
|
-
}
|
|
437
|
-
const found = findCommand(commands, words);
|
|
438
|
-
if (!found) {
|
|
439
|
-
const group = commands.filter((command) => command.path[0] === words[0]);
|
|
440
|
-
if (group.length > 0) {
|
|
441
|
-
if (helpAsked) return {
|
|
442
|
-
kind: "help",
|
|
443
|
-
group: words[0]
|
|
444
|
-
};
|
|
445
|
-
throw usage(`"mostra ${words[0]}" needs one of: ${group.map((command) => command.path.slice(1).join(" ")).join(", ")}.`);
|
|
446
|
-
}
|
|
447
|
-
throw new RpcError(createDiagnostic("MOSTRA_CLI_UNKNOWN_COMMAND", { message: `"${words[0]}" isn't a mostra command. The commands are: ${topWords(commands).join(", ")}.` }));
|
|
448
|
-
}
|
|
449
|
-
const { command } = found;
|
|
450
|
-
if (helpAsked) return {
|
|
451
|
-
kind: "help",
|
|
452
|
-
command
|
|
453
|
-
};
|
|
454
|
-
const used = new Set(pathAt.slice(0, found.used));
|
|
455
|
-
const rest = argv.filter((_, index) => !used.has(index));
|
|
456
|
-
const flagDefs = [...GLOBAL_FLAGS, ...command.flags ?? []];
|
|
457
|
-
let parsed;
|
|
458
|
-
try {
|
|
459
|
-
parsed = parseArgs({
|
|
460
|
-
args: [...rest],
|
|
461
|
-
allowPositionals: true,
|
|
462
|
-
strict: true,
|
|
463
|
-
options: Object.fromEntries(flagDefs.map((flag) => [flag.name, { type: flag.kind === "boolean" ? "boolean" : "string" }]))
|
|
464
|
-
});
|
|
465
|
-
} catch (error) {
|
|
466
|
-
throw usage(`${error.message.split(". To specify")[0]}. Run "mostra ${commandName(command)} --help".`);
|
|
467
|
-
}
|
|
468
|
-
const flags = {};
|
|
469
|
-
for (const flag of command.flags ?? []) {
|
|
470
|
-
const raw = parsed.values[flag.name];
|
|
471
|
-
if (raw === void 0) continue;
|
|
472
|
-
if (flag.kind === "boolean") {
|
|
473
|
-
flags[flag.name] = raw === true;
|
|
474
|
-
continue;
|
|
475
|
-
}
|
|
476
|
-
const text = String(raw);
|
|
477
|
-
if (flag.choices && !flag.choices.includes(text)) throw usage(`--${flag.name} takes one of ${flag.choices.join(", ")}; "${text}" isn't one.`);
|
|
478
|
-
if (flag.kind === "number") {
|
|
479
|
-
const number = Number(text);
|
|
480
|
-
if (!Number.isInteger(number) || number < 0) throw usage(`--${flag.name} takes a whole number; "${text}" isn't one.`);
|
|
481
|
-
flags[flag.name] = number;
|
|
482
|
-
} else if (flag.kind === "duration") {
|
|
483
|
-
durationMs(text);
|
|
484
|
-
flags[flag.name] = text;
|
|
485
|
-
} else if (flag.kind === "list") flags[flag.name] = text.split(",").map((item) => item.trim()).filter((item) => item.length > 0);
|
|
486
|
-
else flags[flag.name] = text;
|
|
487
|
-
}
|
|
488
|
-
const positionals = [...parsed.positionals];
|
|
489
|
-
const args = {};
|
|
490
|
-
for (const arg of command.args ?? []) {
|
|
491
|
-
if (arg.variadic) {
|
|
492
|
-
if (positionals.length === 0 && !arg.optional) throw usage(`"mostra ${commandName(command)}" needs <${arg.name}…>.`);
|
|
493
|
-
args[arg.name] = positionals.splice(0);
|
|
494
|
-
continue;
|
|
495
|
-
}
|
|
496
|
-
const value = positionals.shift();
|
|
497
|
-
if (value === void 0 && !arg.optional) throw usage(`"mostra ${commandName(command)}" needs <${arg.name}>.`);
|
|
498
|
-
args[arg.name] = value;
|
|
499
|
-
}
|
|
500
|
-
if (positionals.length > 0) throw usage(`"mostra ${commandName(command)}" takes no argument "${positionals[0]}". Run "mostra ${commandName(command)} --help".`);
|
|
501
|
-
if (typeof parsed.values["timeout"] === "string") durationMs(parsed.values["timeout"]);
|
|
502
|
-
return {
|
|
503
|
-
kind: "run",
|
|
504
|
-
command,
|
|
505
|
-
args,
|
|
506
|
-
flags
|
|
507
|
-
};
|
|
508
|
-
}
|
|
509
|
-
//#endregion
|
|
510
308
|
//#region src/platform.ts
|
|
511
309
|
/**
|
|
512
310
|
* The CLI's platform gate (D35, D146, RT-07), the runtime's rule (`home/platform.ts` in
|
|
@@ -1450,62 +1248,76 @@ function telemetrySession(options) {
|
|
|
1450
1248
|
fields: event.fields
|
|
1451
1249
|
});
|
|
1452
1250
|
},
|
|
1251
|
+
checkpoint(state) {
|
|
1252
|
+
if (options.quiet || pending.length === 0) return;
|
|
1253
|
+
queue(state.hostInstance, void 0);
|
|
1254
|
+
},
|
|
1453
1255
|
end(outcome) {
|
|
1454
1256
|
if (options.quiet) return;
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
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;
|
|
1487
1293
|
events.push({
|
|
1488
1294
|
...common,
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
exit: outcome.exit,
|
|
1492
|
-
duration: durationBucket(outcome.durationMs),
|
|
1493
|
-
json: options.json,
|
|
1494
|
-
...outcome.error !== void 0 && CATALOG.has(outcome.error) ? { error: outcome.error } : {}
|
|
1295
|
+
...fields,
|
|
1296
|
+
event: item.event
|
|
1495
1297
|
});
|
|
1496
|
-
const lines = [];
|
|
1497
|
-
for (const event of events) {
|
|
1498
|
-
const parsed = TelemetryEvent.safeParse(event);
|
|
1499
|
-
if (parsed.success) lines.push(JSON.stringify(parsed.data));
|
|
1500
|
-
}
|
|
1501
|
-
if (truthy(options.env["MOSTRA_TELEMETRY_DEBUG"])) {
|
|
1502
|
-
for (const line of lines) options.stderr(`mostra telemetry (debug, not sent): ${line}\n`);
|
|
1503
|
-
return;
|
|
1504
|
-
}
|
|
1505
|
-
store.append(lines, now());
|
|
1506
|
-
if (options.flush !== false) startFlusher(store, options.env, now());
|
|
1507
1298
|
}
|
|
1508
|
-
|
|
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
|
+
}
|
|
1509
1321
|
}
|
|
1510
1322
|
/** `mostra telemetry status`: the decision, the install ID and the queue. */
|
|
1511
1323
|
function telemetryStatus(options) {
|
|
@@ -1749,9 +1561,10 @@ const statusCommand = defineCommand({
|
|
|
1749
1561
|
};
|
|
1750
1562
|
}
|
|
1751
1563
|
const status = await context.call(instanceStatusMethod, {});
|
|
1564
|
+
const links = (status.links ?? []).map((link) => `${link.server} ${link.state}${link.default ? " default" : ""}${link.pendingPushes > 0 ? ` ${link.pendingPushes} pushes waiting` : ""}${link.lastError ? ` (${link.lastError})` : ""}\n`).join("");
|
|
1752
1565
|
return {
|
|
1753
1566
|
result: status,
|
|
1754
|
-
human: pretty(status)
|
|
1567
|
+
human: `${pretty(status)}${links ? `\nRemote servers:\n${links}` : ""}`
|
|
1755
1568
|
};
|
|
1756
1569
|
}
|
|
1757
1570
|
});
|
|
@@ -2379,8 +2192,9 @@ const telemetryOffCommand = defineCommand({
|
|
|
2379
2192
|
//#endregion
|
|
2380
2193
|
//#region src/commands/authoring.ts
|
|
2381
2194
|
/**
|
|
2382
|
-
* Authoring: `new`, `verify`, `publish` and `add`, thin clients of
|
|
2383
|
-
* `artifact/verify`, `artifact/publish`
|
|
2195
|
+
* Authoring: `new`, `verify`, `publish`, `export`, `run` and `add`, thin clients of
|
|
2196
|
+
* `artifact/create`, `artifact/verify`, `artifact/publish`, `artifact/export`, `artifact/import`
|
|
2197
|
+
* and `deps/add` (INTERFACES §6, §15).
|
|
2384
2198
|
*/
|
|
2385
2199
|
/** `mostra new <dir>`. */
|
|
2386
2200
|
const newCommand = defineCommand({
|
|
@@ -2567,6 +2381,90 @@ const publishCommand = defineCommand({
|
|
|
2567
2381
|
};
|
|
2568
2382
|
}
|
|
2569
2383
|
});
|
|
2384
|
+
/** `mostra export <artifact> --as bundle --out <path>`. */
|
|
2385
|
+
const exportCommand = defineCommand({
|
|
2386
|
+
path: ["export"],
|
|
2387
|
+
summary: "Write a published version out of the home, as a portable bundle another home can run.",
|
|
2388
|
+
args: [{
|
|
2389
|
+
name: "artifact",
|
|
2390
|
+
summary: "The artifact: its source path or its ID."
|
|
2391
|
+
}],
|
|
2392
|
+
flags: [
|
|
2393
|
+
{
|
|
2394
|
+
name: "as",
|
|
2395
|
+
kind: "string",
|
|
2396
|
+
value: "<class>",
|
|
2397
|
+
choices: ["bundle"],
|
|
2398
|
+
default: "bundle",
|
|
2399
|
+
summary: "What to write: `bundle`, the version's builds, manifest, lockfile and source."
|
|
2400
|
+
},
|
|
2401
|
+
{
|
|
2402
|
+
name: "out",
|
|
2403
|
+
kind: "string",
|
|
2404
|
+
value: "<path>",
|
|
2405
|
+
summary: "Where: a new directory, or one archive when it ends in .tar.zst."
|
|
2406
|
+
},
|
|
2407
|
+
{
|
|
2408
|
+
name: "version",
|
|
2409
|
+
kind: "string",
|
|
2410
|
+
value: "<number|id>",
|
|
2411
|
+
summary: "The version. Default: the latest."
|
|
2412
|
+
}
|
|
2413
|
+
],
|
|
2414
|
+
output: {
|
|
2415
|
+
type: "ArtifactExportResult",
|
|
2416
|
+
topic: "cli"
|
|
2417
|
+
},
|
|
2418
|
+
exits: [EXIT.failure],
|
|
2419
|
+
example: "export ./sidebar-review --out ./sidebar-review.tar.zst",
|
|
2420
|
+
async run(context) {
|
|
2421
|
+
const out = flag(context, "out");
|
|
2422
|
+
if (out === void 0) throw usage("\"mostra export\" needs --out <path>.");
|
|
2423
|
+
const version = flag(context, "version");
|
|
2424
|
+
const result = await context.call(artifactExportMethod, {
|
|
2425
|
+
artifact: artifactRef(arg(context, "artifact"), context.cwd),
|
|
2426
|
+
as: "bundle",
|
|
2427
|
+
out: resolve(context.cwd, out),
|
|
2428
|
+
...version !== void 0 ? { version: /^\d+$/.test(version) ? Number(version) : version } : {}
|
|
2429
|
+
});
|
|
2430
|
+
return {
|
|
2431
|
+
result,
|
|
2432
|
+
human: `Exported ${result.versionId} to ${result.files.join(", ")}\n`
|
|
2433
|
+
};
|
|
2434
|
+
}
|
|
2435
|
+
});
|
|
2436
|
+
/** `mostra run <bundle>`. */
|
|
2437
|
+
const runCommand = defineCommand({
|
|
2438
|
+
path: ["run"],
|
|
2439
|
+
summary: "Make a bundle `mostra export` wrote a version of this home, with the same IDs, and print its link.",
|
|
2440
|
+
args: [{
|
|
2441
|
+
name: "bundle",
|
|
2442
|
+
summary: "The bundle: its directory or its .tar.zst archive."
|
|
2443
|
+
}],
|
|
2444
|
+
flags: [{
|
|
2445
|
+
name: "request-id",
|
|
2446
|
+
kind: "string",
|
|
2447
|
+
value: "<id>",
|
|
2448
|
+
summary: "Make a retry return the first attempt's receipt."
|
|
2449
|
+
}],
|
|
2450
|
+
output: {
|
|
2451
|
+
type: "PublishReceipt",
|
|
2452
|
+
topic: "cli"
|
|
2453
|
+
},
|
|
2454
|
+
exits: [EXIT.failure],
|
|
2455
|
+
example: "run ./sidebar-review.tar.zst",
|
|
2456
|
+
async run(context) {
|
|
2457
|
+
const requestId = flag(context, "request-id");
|
|
2458
|
+
const receipt = await context.call(artifactImportMethod, {
|
|
2459
|
+
bundle: resolve(context.cwd, arg(context, "bundle")),
|
|
2460
|
+
...requestId !== void 0 ? { requestId } : {}
|
|
2461
|
+
});
|
|
2462
|
+
return {
|
|
2463
|
+
result: receipt,
|
|
2464
|
+
human: `${receipt.reused ? "Already here" : "Imported"}: version ${receipt.version} (${receipt.versionId}) of ${receipt.artifactId}\n${receipt.url ?? ""}\n`
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
});
|
|
2570
2468
|
/** `mostra add <package…>`. */
|
|
2571
2469
|
const addCommand = defineCommand({
|
|
2572
2470
|
path: ["add"],
|
|
@@ -2648,53 +2546,64 @@ const devCommand = defineCommand({
|
|
|
2648
2546
|
example: "dev ./sidebar-review",
|
|
2649
2547
|
streams: true,
|
|
2650
2548
|
async run(context) {
|
|
2651
|
-
const connection = await context.connection();
|
|
2652
|
-
let sessionId;
|
|
2653
|
-
const early = [];
|
|
2654
|
-
const show = (event) => {
|
|
2655
|
-
if (event.kind === "diagnostics") for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
|
|
2656
|
-
context.emit(event, line$1(event));
|
|
2657
|
-
};
|
|
2658
|
-
connection?.onNotification(DEV_NOTIFY, (params) => {
|
|
2659
|
-
const event = params;
|
|
2660
|
-
if (sessionId === void 0) early.push(event);
|
|
2661
|
-
else if (event.sessionId === sessionId) show(event);
|
|
2662
|
-
});
|
|
2663
|
-
const portFlag = context.flags["port"];
|
|
2664
|
-
const started = await context.call(devStartMethod, {
|
|
2665
|
-
source: sourceRef(arg(context, "path"), context.cwd),
|
|
2666
|
-
...typeof portFlag === "number" ? { port: portFlag } : {}
|
|
2667
|
-
});
|
|
2668
|
-
sessionId = started.sessionId;
|
|
2669
|
-
context.emit({
|
|
2670
|
-
kind: "started",
|
|
2671
|
-
...started
|
|
2672
|
-
}, `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`);
|
|
2673
|
-
for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
|
|
2674
|
-
let stop = () => {};
|
|
2675
2549
|
const signals = [
|
|
2676
2550
|
"SIGINT",
|
|
2677
2551
|
"SIGTERM",
|
|
2678
2552
|
"SIGBREAK"
|
|
2679
2553
|
];
|
|
2680
|
-
|
|
2681
|
-
|
|
2682
|
-
|
|
2683
|
-
connection?.closed.then(() => done("closed"));
|
|
2684
|
-
});
|
|
2685
|
-
for (const signal of signals) process.off(signal, stop);
|
|
2686
|
-
if (ended === "closed") throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
|
|
2687
|
-
message: "The instance ended the development preview (it stopped or restarted).",
|
|
2688
|
-
hint: "Run mostra dev again."
|
|
2689
|
-
}));
|
|
2690
|
-
await context.call(devStopMethod, { sessionId }).catch(() => void 0);
|
|
2691
|
-
return {
|
|
2692
|
-
result: {
|
|
2693
|
-
sessionId,
|
|
2694
|
-
stopped: "signal"
|
|
2695
|
-
},
|
|
2696
|
-
human: "Stopped.\n"
|
|
2554
|
+
let interrupted = false;
|
|
2555
|
+
let stop = () => {
|
|
2556
|
+
interrupted = true;
|
|
2697
2557
|
};
|
|
2558
|
+
const onSignal = () => stop();
|
|
2559
|
+
for (const signal of signals) process.once(signal, onSignal);
|
|
2560
|
+
const release = () => {
|
|
2561
|
+
for (const signal of signals) process.off(signal, onSignal);
|
|
2562
|
+
};
|
|
2563
|
+
try {
|
|
2564
|
+
const connection = await context.connection();
|
|
2565
|
+
let sessionId;
|
|
2566
|
+
const early = [];
|
|
2567
|
+
const show = (event) => {
|
|
2568
|
+
if (event.kind === "diagnostics") for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
|
|
2569
|
+
context.emit(event, line$1(event));
|
|
2570
|
+
};
|
|
2571
|
+
connection?.onNotification(DEV_NOTIFY, (params) => {
|
|
2572
|
+
const event = params;
|
|
2573
|
+
if (sessionId === void 0) early.push(event);
|
|
2574
|
+
else if (event.sessionId === sessionId) show(event);
|
|
2575
|
+
});
|
|
2576
|
+
const portFlag = context.flags["port"];
|
|
2577
|
+
const started = await context.call(devStartMethod, {
|
|
2578
|
+
source: sourceRef(arg(context, "path"), context.cwd),
|
|
2579
|
+
...typeof portFlag === "number" ? { port: portFlag } : {}
|
|
2580
|
+
});
|
|
2581
|
+
sessionId = started.sessionId;
|
|
2582
|
+
context.emit({
|
|
2583
|
+
kind: "started",
|
|
2584
|
+
...started
|
|
2585
|
+
}, `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`);
|
|
2586
|
+
for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
|
|
2587
|
+
const ended = interrupted ? "signal" : await new Promise((done) => {
|
|
2588
|
+
stop = () => done("signal");
|
|
2589
|
+
connection?.closed.then(() => done("closed"));
|
|
2590
|
+
});
|
|
2591
|
+
release();
|
|
2592
|
+
if (ended === "closed") throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
|
|
2593
|
+
message: "The instance ended the development preview (it stopped or restarted).",
|
|
2594
|
+
hint: "Run mostra dev again."
|
|
2595
|
+
}));
|
|
2596
|
+
await context.call(devStopMethod, { sessionId }).catch(() => void 0);
|
|
2597
|
+
return {
|
|
2598
|
+
result: {
|
|
2599
|
+
sessionId,
|
|
2600
|
+
stopped: "signal"
|
|
2601
|
+
},
|
|
2602
|
+
human: "Stopped.\n"
|
|
2603
|
+
};
|
|
2604
|
+
} finally {
|
|
2605
|
+
release();
|
|
2606
|
+
}
|
|
2698
2607
|
}
|
|
2699
2608
|
});
|
|
2700
2609
|
//#endregion
|
|
@@ -2706,6 +2615,17 @@ const devCommand = defineCommand({
|
|
|
2706
2615
|
*/
|
|
2707
2616
|
/** The longest one `wait` request may ask for (INTERFACES §6: 2^31 − 1 ms). */
|
|
2708
2617
|
const MAX_WAIT_MS = 2 ** 31 - 1;
|
|
2618
|
+
/**
|
|
2619
|
+
* What `wait` prints when its condition held: the event and cursor, and for a signal its name and
|
|
2620
|
+
* the payload the page or action sent (#115), which is otherwise only in `--json`.
|
|
2621
|
+
*/
|
|
2622
|
+
function satisfiedLine(event, cursor) {
|
|
2623
|
+
const line = `${event.type} at cursor ${cursor}`;
|
|
2624
|
+
if (event.type !== "signal.raised") return `${line}\n`;
|
|
2625
|
+
const name = typeof event.payload?.["name"] === "string" ? ` ${event.payload["name"]}` : "";
|
|
2626
|
+
const payload = event.payload !== void 0 && Object.hasOwn(event.payload, "payload") ? `\npayload: ${JSON.stringify(event.payload["payload"])}` : "";
|
|
2627
|
+
return `${event.type}${name} at cursor ${cursor}${payload}\n`;
|
|
2628
|
+
}
|
|
2709
2629
|
/** `mostra wait <artifact>`. */
|
|
2710
2630
|
const waitCommand = defineCommand({
|
|
2711
2631
|
path: ["wait"],
|
|
@@ -2757,7 +2677,7 @@ const waitCommand = defineCommand({
|
|
|
2757
2677
|
});
|
|
2758
2678
|
if (result.status === "satisfied") return {
|
|
2759
2679
|
result,
|
|
2760
|
-
human:
|
|
2680
|
+
human: satisfiedLine(result.event, result.cursor)
|
|
2761
2681
|
};
|
|
2762
2682
|
if (result.status !== "still_waiting") return {
|
|
2763
2683
|
result,
|
|
@@ -3027,253 +2947,64 @@ const statePatchCommand = defineCommand({
|
|
|
3027
2947
|
}
|
|
3028
2948
|
});
|
|
3029
2949
|
//#endregion
|
|
3030
|
-
//#region src/
|
|
3031
|
-
/**
|
|
3032
|
-
* `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
|
|
3033
|
-
* runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
|
|
3034
|
-
* identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
|
|
3035
|
-
* funnel`), whose link expires (1 hour by default, 7 days at most). The share lives in the
|
|
3036
|
-
* daemon, so the command returns at once with the link; `share stop` ends it and `share list`
|
|
3037
|
-
* shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
|
|
3038
|
-
*/
|
|
3039
|
-
const SHARE_ID = /^shr_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
3040
|
-
/** How each tunnel is named in human output. */
|
|
3041
|
-
const THROUGH = {
|
|
3042
|
-
tailnet: "Tailscale Serve, inside your tailnet",
|
|
3043
|
-
funnel: "Tailscale Funnel, public",
|
|
3044
|
-
cloudflare: "a Cloudflare quick tunnel, public"
|
|
3045
|
-
};
|
|
2950
|
+
//#region src/browser.ts
|
|
3046
2951
|
/**
|
|
3047
|
-
*
|
|
3048
|
-
*
|
|
3049
|
-
*
|
|
3050
|
-
*
|
|
2952
|
+
* Opening a browser on a launch URL without putting it on a command line (D140 item 15, Opus
|
|
2953
|
+
* review finding 4). A program's arguments are readable by every local user (`ps`,
|
|
2954
|
+
* `/proc/<pid>/cmdline`), so the opener gets the path of a page that redirects to the launch URL,
|
|
2955
|
+
* written mode 0600 in a fresh directory of mode 0700, as Jupyter's server does for its token.
|
|
2956
|
+
* Windows has no modes: there the page goes under the user's own profile
|
|
2957
|
+
* (`%LOCALAPPDATA%\mostra-cli\open`), whose access list only the user, `SYSTEM` and
|
|
2958
|
+
* administrators pass, never under `%TEMP%`, which may name a folder other users can read (Opus
|
|
2959
|
+
* review of WP-W2, finding 1). The launch ticket in the page is single-use and lives a minute, so a
|
|
2960
|
+
* page left behind is harmless; each launch removes the ones older than that.
|
|
3051
2961
|
*/
|
|
3052
|
-
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
2962
|
+
/** The prefix of the directories launch pages live in. */
|
|
2963
|
+
const PREFIX = "mostra-open-";
|
|
2964
|
+
/** A launch page older than this holds a ticket that expired: it goes on the next launch. */
|
|
2965
|
+
const STALE_MS = 12e4;
|
|
2966
|
+
/** Escapes text for an HTML attribute or element. */
|
|
2967
|
+
const html = (text) => text.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
2968
|
+
/** The page that sends the browser on to `url`. */
|
|
2969
|
+
function launchPage(url) {
|
|
2970
|
+
const script = JSON.stringify(url).replaceAll("<", "\\u003c");
|
|
2971
|
+
return `<!DOCTYPE html>
|
|
2972
|
+
<html lang="en">
|
|
2973
|
+
<head>
|
|
2974
|
+
<meta charset="utf-8">
|
|
2975
|
+
<meta name="referrer" content="no-referrer">
|
|
2976
|
+
<meta http-equiv="refresh" content="0;url=${html(url)}">
|
|
2977
|
+
<title>Opening Mostra</title>
|
|
2978
|
+
<script>location.replace(${script});<\/script>
|
|
2979
|
+
</head>
|
|
2980
|
+
<body>
|
|
2981
|
+
<p>Opening the artifact. If nothing happens, <a href="${html(url)}">open it here</a>.</p>
|
|
2982
|
+
</body>
|
|
2983
|
+
</html>
|
|
2984
|
+
`;
|
|
3056
2985
|
}
|
|
3057
|
-
/**
|
|
3058
|
-
function
|
|
3059
|
-
const
|
|
3060
|
-
|
|
3061
|
-
|
|
3062
|
-
|
|
3063
|
-
|
|
3064
|
-
|
|
3065
|
-
|
|
3066
|
-
|
|
3067
|
-
name
|
|
3068
|
-
|
|
3069
|
-
|
|
3070
|
-
|
|
3071
|
-
|
|
3072
|
-
|
|
3073
|
-
|
|
3074
|
-
|
|
3075
|
-
|
|
3076
|
-
|
|
3077
|
-
|
|
3078
|
-
|
|
3079
|
-
summary: "Share publicly: anyone with the link can open it until it expires."
|
|
3080
|
-
},
|
|
3081
|
-
{
|
|
3082
|
-
name: "via",
|
|
3083
|
-
kind: "string",
|
|
3084
|
-
value: "<tunnel>",
|
|
3085
|
-
choices: ["cloudflare", "funnel"],
|
|
3086
|
-
default: "cloudflare",
|
|
3087
|
-
summary: "The public tunnel: a Cloudflare quick tunnel (no account), or Tailscale Funnel (shows your device's tailnet name)."
|
|
3088
|
-
},
|
|
3089
|
-
{
|
|
3090
|
-
name: "ttl",
|
|
3091
|
-
kind: "duration",
|
|
3092
|
-
value: "<d>",
|
|
3093
|
-
summary: "How long the link works, such as 30m or 24h. Public: 1h by default, 7d at most."
|
|
3094
|
-
},
|
|
3095
|
-
{
|
|
3096
|
-
name: "scope",
|
|
3097
|
-
kind: "list",
|
|
3098
|
-
value: "<a,b>",
|
|
3099
|
-
summary: "The link's scopes: view, draft, submit, review, signal, action:*. Default: all."
|
|
3100
|
-
},
|
|
3101
|
-
{
|
|
3102
|
-
name: "viewer",
|
|
3103
|
-
kind: "string",
|
|
3104
|
-
value: "<ref>",
|
|
3105
|
-
summary: "The person the link is for, by your own stable key for them; without it, each link is a viewer of its own."
|
|
3106
|
-
},
|
|
3107
|
-
{
|
|
3108
|
-
name: "viewer-name",
|
|
3109
|
-
kind: "string",
|
|
3110
|
-
value: "<name>",
|
|
3111
|
-
summary: "The display name of --viewer."
|
|
3112
|
-
},
|
|
3113
|
-
{
|
|
3114
|
-
name: "request-id",
|
|
3115
|
-
kind: "string",
|
|
3116
|
-
value: "<id>",
|
|
3117
|
-
summary: "Make a retried share return the same share instead of opening another."
|
|
3118
|
-
}
|
|
3119
|
-
],
|
|
3120
|
-
output: {
|
|
3121
|
-
type: "ShareStartResult",
|
|
3122
|
-
topic: "cli"
|
|
3123
|
-
},
|
|
3124
|
-
exits: [EXIT.failure, EXIT.environment],
|
|
3125
|
-
example: "share ./sidebar-review --public --ttl 2h",
|
|
3126
|
-
async run(context) {
|
|
3127
|
-
const artifact = artifactRef(arg(context, "artifact"), context.cwd);
|
|
3128
|
-
const tailnet = context.flags["tailnet"] === true;
|
|
3129
|
-
const publicly = context.flags["public"] === true;
|
|
3130
|
-
if (tailnet === publicly) throw usage("Give --tailnet or --public.");
|
|
3131
|
-
const viaFlag = flag(context, "via");
|
|
3132
|
-
if (viaFlag !== void 0 && !publicly) throw usage("--via chooses a public tunnel: add --public.");
|
|
3133
|
-
const via = tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
|
|
3134
|
-
const ttl = flag(context, "ttl");
|
|
3135
|
-
const scopes = context.flags["scope"];
|
|
3136
|
-
const viewerRef = flag(context, "viewer");
|
|
3137
|
-
const viewerName = flag(context, "viewer-name");
|
|
3138
|
-
const requestId = flag(context, "request-id");
|
|
3139
|
-
if (viewerName !== void 0 && viewerRef === void 0) throw usage("--viewer-name needs --viewer.");
|
|
3140
|
-
const share = await context.call(shareStartMethod, {
|
|
3141
|
-
artifact,
|
|
3142
|
-
via,
|
|
3143
|
-
...ttl !== void 0 ? { ttl } : {},
|
|
3144
|
-
...scopes !== void 0 ? { scopes } : {},
|
|
3145
|
-
...viewerRef !== void 0 ? { viewer: {
|
|
3146
|
-
ref: viewerRef,
|
|
3147
|
-
...viewerName !== void 0 ? { name: viewerName } : {}
|
|
3148
|
-
} } : {},
|
|
3149
|
-
...requestId !== void 0 ? { requestId } : {}
|
|
3150
|
-
});
|
|
3151
|
-
context.record({
|
|
3152
|
-
event: "share.done",
|
|
3153
|
-
fields: { kind: via }
|
|
3154
|
-
});
|
|
3155
|
-
const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
|
|
3156
|
-
return {
|
|
3157
|
-
result: share,
|
|
3158
|
-
human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`
|
|
3159
|
-
};
|
|
3160
|
-
}
|
|
3161
|
-
});
|
|
3162
|
-
/** `mostra share stop <artifact|shareId>`. */
|
|
3163
|
-
const shareStopCommand = defineCommand({
|
|
3164
|
-
path: ["share", "stop"],
|
|
3165
|
-
summary: "Stop a share, or every share of an artifact: its link stops working and its tunnel closes.",
|
|
3166
|
-
args: [{
|
|
3167
|
-
name: "target",
|
|
3168
|
-
summary: "A share's ID (shr_…), or an artifact's source path or ID."
|
|
3169
|
-
}],
|
|
3170
|
-
flags: [],
|
|
3171
|
-
output: {
|
|
3172
|
-
type: "ShareStopResult",
|
|
3173
|
-
topic: "cli"
|
|
3174
|
-
},
|
|
3175
|
-
exits: [EXIT.failure, EXIT.environment],
|
|
3176
|
-
example: "share stop ./sidebar-review",
|
|
3177
|
-
async run(context) {
|
|
3178
|
-
const target = arg(context, "target");
|
|
3179
|
-
const result = await context.call(shareStopMethod, SHARE_ID.test(target) ? { shareId: target } : { artifact: artifactRef(target, context.cwd) });
|
|
3180
|
-
return {
|
|
3181
|
-
result,
|
|
3182
|
-
human: result.stopped.length === 0 ? "Nothing was shared.\n" : result.stopped.map((share) => `Stopped ${share.shareId}\n`).join("")
|
|
3183
|
-
};
|
|
3184
|
-
}
|
|
3185
|
-
});
|
|
3186
|
-
/** `mostra share list [artifact] [--all]`. */
|
|
3187
|
-
const shareListCommand = defineCommand({
|
|
3188
|
-
path: ["share", "list"],
|
|
3189
|
-
summary: "List the active shares, of every artifact or of one; --all adds the ones that ended.",
|
|
3190
|
-
args: [{
|
|
3191
|
-
name: "artifact",
|
|
3192
|
-
summary: "Only this artifact's shares: its source path or ID.",
|
|
3193
|
-
optional: true
|
|
3194
|
-
}],
|
|
3195
|
-
flags: [{
|
|
3196
|
-
name: "all",
|
|
3197
|
-
kind: "boolean",
|
|
3198
|
-
summary: "Also list shares that ended, and why."
|
|
3199
|
-
}],
|
|
3200
|
-
output: {
|
|
3201
|
-
type: "ShareListResult",
|
|
3202
|
-
topic: "cli"
|
|
3203
|
-
},
|
|
3204
|
-
exits: [EXIT.failure],
|
|
3205
|
-
example: "share list --all",
|
|
3206
|
-
async run(context) {
|
|
3207
|
-
const given = context.args["artifact"];
|
|
3208
|
-
const result = await context.call(shareListMethod, {
|
|
3209
|
-
...typeof given === "string" ? { artifact: artifactRef(given, context.cwd) } : {},
|
|
3210
|
-
...context.flags["all"] === true ? { all: true } : {}
|
|
3211
|
-
});
|
|
3212
|
-
return {
|
|
3213
|
-
result,
|
|
3214
|
-
human: result.shares.length === 0 ? "Nothing is shared.\n" : `${result.shares.map((share) => line(share)).join("\n")}\n`
|
|
3215
|
-
};
|
|
3216
|
-
}
|
|
3217
|
-
});
|
|
3218
|
-
//#endregion
|
|
3219
|
-
//#region src/browser.ts
|
|
3220
|
-
/**
|
|
3221
|
-
* Opening a browser on a launch URL without putting it on a command line (D140 item 15, Opus
|
|
3222
|
-
* review finding 4). A program's arguments are readable by every local user (`ps`,
|
|
3223
|
-
* `/proc/<pid>/cmdline`), so the opener gets the path of a page that redirects to the launch URL,
|
|
3224
|
-
* written mode 0600 in a fresh directory of mode 0700, as Jupyter's server does for its token.
|
|
3225
|
-
* Windows has no modes: there the page goes under the user's own profile
|
|
3226
|
-
* (`%LOCALAPPDATA%\mostra-cli\open`), whose access list only the user, `SYSTEM` and
|
|
3227
|
-
* administrators pass, never under `%TEMP%`, which may name a folder other users can read (Opus
|
|
3228
|
-
* review of WP-W2, finding 1). The launch ticket in the page is single-use and lives a minute, so a
|
|
3229
|
-
* page left behind is harmless; each launch removes the ones older than that.
|
|
3230
|
-
*/
|
|
3231
|
-
/** The prefix of the directories launch pages live in. */
|
|
3232
|
-
const PREFIX = "mostra-open-";
|
|
3233
|
-
/** A launch page older than this holds a ticket that expired: it goes on the next launch. */
|
|
3234
|
-
const STALE_MS = 12e4;
|
|
3235
|
-
/** Escapes text for an HTML attribute or element. */
|
|
3236
|
-
const html = (text) => text.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
3237
|
-
/** The page that sends the browser on to `url`. */
|
|
3238
|
-
function launchPage(url) {
|
|
3239
|
-
const script = JSON.stringify(url).replaceAll("<", "\\u003c");
|
|
3240
|
-
return `<!DOCTYPE html>
|
|
3241
|
-
<html lang="en">
|
|
3242
|
-
<head>
|
|
3243
|
-
<meta charset="utf-8">
|
|
3244
|
-
<meta name="referrer" content="no-referrer">
|
|
3245
|
-
<meta http-equiv="refresh" content="0;url=${html(url)}">
|
|
3246
|
-
<title>Opening Mostra</title>
|
|
3247
|
-
<script>location.replace(${script});<\/script>
|
|
3248
|
-
</head>
|
|
3249
|
-
<body>
|
|
3250
|
-
<p>Opening the artifact. If nothing happens, <a href="${html(url)}">open it here</a>.</p>
|
|
3251
|
-
</body>
|
|
3252
|
-
</html>
|
|
3253
|
-
`;
|
|
3254
|
-
}
|
|
3255
|
-
/** Removes launch pages of earlier launches that are this user's and older than a minute or two. */
|
|
3256
|
-
function sweep(base, now) {
|
|
3257
|
-
const uid = process.getuid?.();
|
|
3258
|
-
let names;
|
|
3259
|
-
try {
|
|
3260
|
-
names = readdirSync(base);
|
|
3261
|
-
} catch {
|
|
3262
|
-
return;
|
|
3263
|
-
}
|
|
3264
|
-
for (const name of names) {
|
|
3265
|
-
if (!name.startsWith(PREFIX)) continue;
|
|
3266
|
-
const dir = join(base, name);
|
|
3267
|
-
try {
|
|
3268
|
-
const stats = lstatSync(dir);
|
|
3269
|
-
if (!stats.isDirectory() || uid !== void 0 && stats.uid !== uid) continue;
|
|
3270
|
-
if (now - stats.mtimeMs < STALE_MS) continue;
|
|
3271
|
-
rmSync(dir, {
|
|
3272
|
-
recursive: true,
|
|
3273
|
-
force: true
|
|
3274
|
-
});
|
|
3275
|
-
} catch {}
|
|
3276
|
-
}
|
|
2986
|
+
/** Removes launch pages of earlier launches that are this user's and older than a minute or two. */
|
|
2987
|
+
function sweep(base, now) {
|
|
2988
|
+
const uid = process.getuid?.();
|
|
2989
|
+
let names;
|
|
2990
|
+
try {
|
|
2991
|
+
names = readdirSync(base);
|
|
2992
|
+
} catch {
|
|
2993
|
+
return;
|
|
2994
|
+
}
|
|
2995
|
+
for (const name of names) {
|
|
2996
|
+
if (!name.startsWith(PREFIX)) continue;
|
|
2997
|
+
const dir = join(base, name);
|
|
2998
|
+
try {
|
|
2999
|
+
const stats = lstatSync(dir);
|
|
3000
|
+
if (!stats.isDirectory() || uid !== void 0 && stats.uid !== uid) continue;
|
|
3001
|
+
if (now - stats.mtimeMs < STALE_MS) continue;
|
|
3002
|
+
rmSync(dir, {
|
|
3003
|
+
recursive: true,
|
|
3004
|
+
force: true
|
|
3005
|
+
});
|
|
3006
|
+
} catch {}
|
|
3007
|
+
}
|
|
3277
3008
|
}
|
|
3278
3009
|
/** Writes the launch page for `url`; its path. */
|
|
3279
3010
|
function writeLaunchPage(url, base = tmpdir(), now = Date.now()) {
|
|
@@ -3417,13 +3148,912 @@ async function openInBrowser(url, env) {
|
|
|
3417
3148
|
recursive: true,
|
|
3418
3149
|
mode: 448
|
|
3419
3150
|
});
|
|
3420
|
-
page = writeLaunchPage(url, base);
|
|
3421
|
-
} catch {
|
|
3422
|
-
return false;
|
|
3151
|
+
page = writeLaunchPage(url, base);
|
|
3152
|
+
} catch {
|
|
3153
|
+
return false;
|
|
3154
|
+
}
|
|
3155
|
+
for (const command of browserCommands(page, env)) if (await start(command)) return true;
|
|
3156
|
+
return false;
|
|
3157
|
+
}
|
|
3158
|
+
//#endregion
|
|
3159
|
+
//#region src/client.ts
|
|
3160
|
+
/**
|
|
3161
|
+
* The CLI's connection to its home's instance (D45, D81, INTERFACES §9): it attaches to the
|
|
3162
|
+
* daemon recorded in `instance.json`, or starts one (`mostra-runtime daemon`, which itself
|
|
3163
|
+
* attaches when another starter won), and opens a session as `mostra-cli`. The SDK (WP-11) does
|
|
3164
|
+
* the same few steps over the same protocol.
|
|
3165
|
+
*/
|
|
3166
|
+
/** How long one attempt to reach a recorded socket waits. */
|
|
3167
|
+
const ATTACH_TIMEOUT_MS = 5e3;
|
|
3168
|
+
/** How long a daemon this command starts may take to say where it listens. */
|
|
3169
|
+
const START_TIMEOUT_MS = 3e4;
|
|
3170
|
+
/**
|
|
3171
|
+
* Opens a session with the home's instance, starting its daemon when none runs. Returns
|
|
3172
|
+
* `undefined` when `autostart` is false and no instance runs. Throws the start's diagnostic when
|
|
3173
|
+
* the daemon can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …).
|
|
3174
|
+
*/
|
|
3175
|
+
async function connect(options) {
|
|
3176
|
+
const recorded = readSocket(options.home);
|
|
3177
|
+
if (recorded !== void 0) {
|
|
3178
|
+
const session = await open(recorded, options, false).catch(() => void 0);
|
|
3179
|
+
if (session) return session;
|
|
3180
|
+
}
|
|
3181
|
+
if (options.autostart === false) return void 0;
|
|
3182
|
+
options.onStarting?.(true);
|
|
3183
|
+
let started;
|
|
3184
|
+
try {
|
|
3185
|
+
started = await startDaemon(options);
|
|
3186
|
+
} finally {
|
|
3187
|
+
options.onStarting?.(false);
|
|
3188
|
+
}
|
|
3189
|
+
return open(started.socket, options, started.status === "started");
|
|
3190
|
+
}
|
|
3191
|
+
/**
|
|
3192
|
+
* Opens the endpoint `instance.json` or a starting daemon named: a Unix socket, or on Windows the
|
|
3193
|
+
* owner-only pipe through the runtime's helper, which refuses a pipe another user created under
|
|
3194
|
+
* the name (D150, the SDK's `connectControl`). Only Windows needs the runtime resolved first.
|
|
3195
|
+
*/
|
|
3196
|
+
async function openEndpoint(endpoint, options) {
|
|
3197
|
+
const runtime = process.platform === "win32" ? (await locateRuntime(options.env)).runtime : void 0;
|
|
3198
|
+
return connectControl(endpoint, {
|
|
3199
|
+
runtime,
|
|
3200
|
+
env: options.env,
|
|
3201
|
+
timeoutMs: ATTACH_TIMEOUT_MS
|
|
3202
|
+
});
|
|
3203
|
+
}
|
|
3204
|
+
/** The socket `instance.json` records (D81), if the file exists and reads. */
|
|
3205
|
+
function readSocket(home) {
|
|
3206
|
+
try {
|
|
3207
|
+
const record = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
|
|
3208
|
+
return typeof record.socket === "string" ? record.socket : void 0;
|
|
3209
|
+
} catch {
|
|
3210
|
+
return;
|
|
3211
|
+
}
|
|
3212
|
+
}
|
|
3213
|
+
/**
|
|
3214
|
+
* Starts the home's daemon, detached from this process, and reads the one line it prints: where
|
|
3215
|
+
* it listens, or why it couldn't start. A daemon another starter won prints `attached` and exits.
|
|
3216
|
+
*/
|
|
3217
|
+
async function startDaemon(options) {
|
|
3218
|
+
const deadlineAt = Date.now() + START_TIMEOUT_MS;
|
|
3219
|
+
const timedOut = () => new RpcError(createDiagnostic("MOSTRA_HOST_TIMEOUT", { message: `The home's daemon didn't start within ${formatDuration(START_TIMEOUT_MS)}.` }));
|
|
3220
|
+
const runtime = await locateRuntime(options.env);
|
|
3221
|
+
if (Date.now() >= deadlineAt) throw timedOut();
|
|
3222
|
+
const args = [
|
|
3223
|
+
resolve(runtime.entry),
|
|
3224
|
+
"daemon",
|
|
3225
|
+
"--home",
|
|
3226
|
+
options.home
|
|
3227
|
+
];
|
|
3228
|
+
return new Promise((resolve, reject) => {
|
|
3229
|
+
const child = spawn(runtime.node, args, {
|
|
3230
|
+
detached: true,
|
|
3231
|
+
cwd: detachedDirectory(options.home),
|
|
3232
|
+
windowsHide: true,
|
|
3233
|
+
stdio: [
|
|
3234
|
+
"ignore",
|
|
3235
|
+
"pipe",
|
|
3236
|
+
"ignore"
|
|
3237
|
+
],
|
|
3238
|
+
env: detachedEnvironment({
|
|
3239
|
+
...process.env,
|
|
3240
|
+
...options.env
|
|
3241
|
+
})
|
|
3242
|
+
});
|
|
3243
|
+
const splitter = new LineSplitter();
|
|
3244
|
+
let settled = false;
|
|
3245
|
+
const finish = (outcome) => {
|
|
3246
|
+
if (settled) return;
|
|
3247
|
+
settled = true;
|
|
3248
|
+
clearTimeout(timer);
|
|
3249
|
+
child.stdout?.removeAllListeners("data");
|
|
3250
|
+
child.stdout?.destroy();
|
|
3251
|
+
child.unref();
|
|
3252
|
+
outcome();
|
|
3253
|
+
};
|
|
3254
|
+
const timer = setTimeout(() => finish(() => reject(timedOut())), Math.max(0, deadlineAt - Date.now()));
|
|
3255
|
+
child.on("error", (error) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_MISSING", { message: `The runtime couldn't be started: ${error.message}` })))));
|
|
3256
|
+
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.` })))));
|
|
3257
|
+
child.stdout?.setEncoding("utf8");
|
|
3258
|
+
child.stdout?.on("data", (chunk) => {
|
|
3259
|
+
for (const line of splitter.push(chunk)) {
|
|
3260
|
+
let parsed;
|
|
3261
|
+
try {
|
|
3262
|
+
parsed = JSON.parse(line);
|
|
3263
|
+
} catch {
|
|
3264
|
+
continue;
|
|
3265
|
+
}
|
|
3266
|
+
finish(() => {
|
|
3267
|
+
if (parsed.status === "failed") reject(new RpcError(parsed.diagnostic ?? createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: "The home's daemon failed to start." })));
|
|
3268
|
+
else resolve(parsed);
|
|
3269
|
+
});
|
|
3270
|
+
return;
|
|
3271
|
+
}
|
|
3272
|
+
});
|
|
3273
|
+
});
|
|
3274
|
+
}
|
|
3275
|
+
async function open(socketPath, options, started) {
|
|
3276
|
+
const socket = await openEndpoint(socketPath, options);
|
|
3277
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
3278
|
+
const peer = new RpcPeer({
|
|
3279
|
+
send: (message) => {
|
|
3280
|
+
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
3281
|
+
},
|
|
3282
|
+
onNotification: (method, params) => handlers.get(method)?.(params)
|
|
3283
|
+
});
|
|
3284
|
+
let markClosed = () => {};
|
|
3285
|
+
const closedPromise = new Promise((done) => {
|
|
3286
|
+
markClosed = done;
|
|
3287
|
+
});
|
|
3288
|
+
const splitter = new LineSplitter();
|
|
3289
|
+
socket.setEncoding("utf8");
|
|
3290
|
+
socket.on("data", (chunk) => {
|
|
3291
|
+
for (const line of splitter.push(chunk)) peer.receiveLine(line);
|
|
3292
|
+
});
|
|
3293
|
+
const end = () => {
|
|
3294
|
+
peer.close();
|
|
3295
|
+
markClosed();
|
|
3296
|
+
};
|
|
3297
|
+
socket.on("close", end);
|
|
3298
|
+
socket.on("error", () => socket.destroy());
|
|
3299
|
+
let result;
|
|
3300
|
+
try {
|
|
3301
|
+
result = await peer.call(mostraInitializeMethod, {
|
|
3302
|
+
client: {
|
|
3303
|
+
name: CLI_CLIENT_NAME,
|
|
3304
|
+
version: cliVersion()
|
|
3305
|
+
},
|
|
3306
|
+
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
3307
|
+
capabilities: { notifications: [ARTIFACT_PROGRESS, DEV_NOTIFY] },
|
|
3308
|
+
ports: [],
|
|
3309
|
+
home: { path: options.home }
|
|
3310
|
+
}, { timeoutMs: ATTACH_TIMEOUT_MS });
|
|
3311
|
+
} catch (error) {
|
|
3312
|
+
socket.destroy();
|
|
3313
|
+
throw error;
|
|
3314
|
+
}
|
|
3315
|
+
return {
|
|
3316
|
+
summary: {
|
|
3317
|
+
home: result.instance.home,
|
|
3318
|
+
socket: socketPath,
|
|
3319
|
+
pid: result.instance.pid,
|
|
3320
|
+
mode: result.instance.mode,
|
|
3321
|
+
version: result.instance.version,
|
|
3322
|
+
started
|
|
3323
|
+
},
|
|
3324
|
+
warnings: result.warnings,
|
|
3325
|
+
call: (method, params, timeoutMs) => peer.call(method, params, timeoutMs !== void 0 ? { timeoutMs } : {}),
|
|
3326
|
+
onNotification: (method, handler) => {
|
|
3327
|
+
handlers.set(method, handler);
|
|
3328
|
+
},
|
|
3329
|
+
closed: closedPromise,
|
|
3330
|
+
close: () => {
|
|
3331
|
+
peer.close();
|
|
3332
|
+
socket.end();
|
|
3333
|
+
socket.destroy();
|
|
3334
|
+
}
|
|
3335
|
+
};
|
|
3336
|
+
}
|
|
3337
|
+
/** A limit as people write it: `250 ms`, `5 s`, `1.5 s`. */
|
|
3338
|
+
function formatDuration(ms) {
|
|
3339
|
+
if (ms < 1e3) return `${ms} ms`;
|
|
3340
|
+
const seconds = ms / 1e3;
|
|
3341
|
+
return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)} s`;
|
|
3342
|
+
}
|
|
3343
|
+
/** The runtime install of {@link RuntimeInstall}, reporting its progress through `log`. */
|
|
3344
|
+
function runtimeInstall(options) {
|
|
3345
|
+
const testWait = Number(options.env["MOSTRA_TEST_RUNTIME_WAIT_MS"]);
|
|
3346
|
+
const waitMs = options.waitMs ?? (Number.isFinite(testWait) && testWait > 0 ? testWait : 45e3);
|
|
3347
|
+
const report = progressReporter({
|
|
3348
|
+
stderr: (text) => {
|
|
3349
|
+
for (const line of text.split("\n")) if (line.trim() !== "") options.log(line.trim());
|
|
3350
|
+
},
|
|
3351
|
+
stderrTty: false
|
|
3352
|
+
});
|
|
3353
|
+
let ready = false;
|
|
3354
|
+
let pending;
|
|
3355
|
+
let done;
|
|
3356
|
+
const start = () => {
|
|
3357
|
+
if (pending !== void 0) return pending;
|
|
3358
|
+
const installing = resolveRuntime({
|
|
3359
|
+
env: options.env,
|
|
3360
|
+
onProgress: (progress) => {
|
|
3361
|
+
if (progress.step === "download") done = `${Math.floor(progress.received / progress.total * 100)}% downloaded`;
|
|
3362
|
+
else if (progress.step === "files") done = "downloaded, checking its files";
|
|
3363
|
+
else if (progress.step === "browser") done = "fetching the browser verify uses";
|
|
3364
|
+
report(progress);
|
|
3365
|
+
}
|
|
3366
|
+
}).then(() => {
|
|
3367
|
+
ready = true;
|
|
3368
|
+
});
|
|
3369
|
+
pending = installing;
|
|
3370
|
+
installing.catch((error) => {
|
|
3371
|
+
if (pending === installing) pending = void 0;
|
|
3372
|
+
done = void 0;
|
|
3373
|
+
const diagnostic = error instanceof RpcError ? error.diagnostic : void 0;
|
|
3374
|
+
options.log(`mostra mcp: the runtime's install failed: ${diagnostic?.code ?? ""} ${diagnostic?.message ?? String(error)}`.trim());
|
|
3375
|
+
});
|
|
3376
|
+
return installing;
|
|
3377
|
+
};
|
|
3378
|
+
return {
|
|
3379
|
+
start() {
|
|
3380
|
+
start().catch(() => {});
|
|
3381
|
+
},
|
|
3382
|
+
async wait() {
|
|
3383
|
+
if (ready) return;
|
|
3384
|
+
const installing = start();
|
|
3385
|
+
let timer;
|
|
3386
|
+
const late = new Promise((_, reject) => {
|
|
3387
|
+
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);
|
|
3388
|
+
timer.unref();
|
|
3389
|
+
});
|
|
3390
|
+
try {
|
|
3391
|
+
await Promise.race([installing, late]);
|
|
3392
|
+
} finally {
|
|
3393
|
+
clearTimeout(timer);
|
|
3394
|
+
}
|
|
3395
|
+
}
|
|
3396
|
+
};
|
|
3397
|
+
}
|
|
3398
|
+
/** The home's daemon as the MCP server's instance (D164 item 5). */
|
|
3399
|
+
function daemonInstance(options) {
|
|
3400
|
+
const idleMs = options.idleMs ?? 3e5;
|
|
3401
|
+
const runtime = options.runtime;
|
|
3402
|
+
const opener = options.connect ?? connect;
|
|
3403
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
3404
|
+
let session;
|
|
3405
|
+
let host = false;
|
|
3406
|
+
let inflight = 0;
|
|
3407
|
+
let idle;
|
|
3408
|
+
const open = () => {
|
|
3409
|
+
if (session !== void 0) return session;
|
|
3410
|
+
const opening = opener({
|
|
3411
|
+
home: options.home,
|
|
3412
|
+
env: options.env
|
|
3413
|
+
}).then((connection) => {
|
|
3414
|
+
if (connection === void 0) throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: "No instance runs for this home." }));
|
|
3415
|
+
host = connection.summary.mode === "host";
|
|
3416
|
+
for (const warning of connection.warnings) options.log(`mostra mcp: ${warning.code}: ${warning.message}`);
|
|
3417
|
+
connection.onNotification(ARTIFACT_PROGRESS, (params) => {
|
|
3418
|
+
const progress = params;
|
|
3419
|
+
listeners.get(progress.progressToken)?.(progress);
|
|
3420
|
+
});
|
|
3421
|
+
connection.closed.then(() => {
|
|
3422
|
+
if (session === opening) session = void 0;
|
|
3423
|
+
});
|
|
3424
|
+
return connection;
|
|
3425
|
+
});
|
|
3426
|
+
session = opening;
|
|
3427
|
+
opening.catch(() => {
|
|
3428
|
+
if (session === opening) session = void 0;
|
|
3429
|
+
});
|
|
3430
|
+
return opening;
|
|
3431
|
+
};
|
|
3432
|
+
const release = () => {
|
|
3433
|
+
const current = session;
|
|
3434
|
+
session = void 0;
|
|
3435
|
+
current?.then((connection) => connection.close()).catch(() => {});
|
|
3436
|
+
};
|
|
3437
|
+
const settle = () => {
|
|
3438
|
+
inflight -= 1;
|
|
3439
|
+
if (inflight > 0) return;
|
|
3440
|
+
clearTimeout(idle);
|
|
3441
|
+
idle = setTimeout(release, idleMs);
|
|
3442
|
+
idle.unref();
|
|
3443
|
+
};
|
|
3444
|
+
return {
|
|
3445
|
+
async call(method, params) {
|
|
3446
|
+
inflight += 1;
|
|
3447
|
+
clearTimeout(idle);
|
|
3448
|
+
try {
|
|
3449
|
+
await runtime?.wait();
|
|
3450
|
+
const used = open();
|
|
3451
|
+
try {
|
|
3452
|
+
return await (await used).call(method, params);
|
|
3453
|
+
} catch (error) {
|
|
3454
|
+
if (!(error instanceof RpcError && error.diagnostic.code === "MOSTRA_HOST_CONNECTION_CLOSED") || method.mutating) throw error;
|
|
3455
|
+
if (session === used) session = void 0;
|
|
3456
|
+
return await (await open()).call(method, params);
|
|
3457
|
+
}
|
|
3458
|
+
} finally {
|
|
3459
|
+
settle();
|
|
3460
|
+
}
|
|
3461
|
+
},
|
|
3462
|
+
onProgress(token, listener) {
|
|
3463
|
+
listeners.set(token, listener);
|
|
3464
|
+
return () => listeners.delete(token);
|
|
3465
|
+
},
|
|
3466
|
+
hostInstance: () => host,
|
|
3467
|
+
close() {
|
|
3468
|
+
clearTimeout(idle);
|
|
3469
|
+
release();
|
|
3470
|
+
}
|
|
3471
|
+
};
|
|
3472
|
+
}
|
|
3473
|
+
/** The bundled reference (`mostra docs`), read as the MCP server's docs. */
|
|
3474
|
+
function bundledDocs() {
|
|
3475
|
+
let topics;
|
|
3476
|
+
const all = () => {
|
|
3477
|
+
topics ??= docsIndex();
|
|
3478
|
+
return topics;
|
|
3479
|
+
};
|
|
3480
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3481
|
+
return {
|
|
3482
|
+
topics: () => all().map((topic) => ({
|
|
3483
|
+
topic: topic.topic,
|
|
3484
|
+
title: topic.title,
|
|
3485
|
+
url: topic.url
|
|
3486
|
+
})),
|
|
3487
|
+
read(topic) {
|
|
3488
|
+
const cached = cache.get(topic);
|
|
3489
|
+
if (cached !== void 0) return cached;
|
|
3490
|
+
const found = all().find((entry) => entry.topic === topic);
|
|
3491
|
+
if (found === void 0) return void 0;
|
|
3492
|
+
const markdown = topicMarkdown(found, skillDir(), MCP_GUIDE_LINKS);
|
|
3493
|
+
cache.set(topic, markdown);
|
|
3494
|
+
return markdown;
|
|
3495
|
+
}
|
|
3496
|
+
};
|
|
3497
|
+
}
|
|
3498
|
+
/** The daemon instance, with the runtime's install started at once (D164 item 7). */
|
|
3499
|
+
function startInstance(options) {
|
|
3500
|
+
const runtime = runtimeInstall({
|
|
3501
|
+
env: options.env,
|
|
3502
|
+
log: options.log
|
|
3503
|
+
});
|
|
3504
|
+
runtime.start();
|
|
3505
|
+
return daemonInstance({
|
|
3506
|
+
...options,
|
|
3507
|
+
runtime
|
|
3508
|
+
});
|
|
3509
|
+
}
|
|
3510
|
+
function factoryFor(options, instance) {
|
|
3511
|
+
return createMcpServerFactory({
|
|
3512
|
+
instance,
|
|
3513
|
+
workspace: localWorkspace(options.workspace),
|
|
3514
|
+
docs: bundledDocs(),
|
|
3515
|
+
browser: { open: (url) => openInBrowser(url, options.env) },
|
|
3516
|
+
version: options.version,
|
|
3517
|
+
onClient: (client) => options.onClient(client, instance)
|
|
3518
|
+
});
|
|
3519
|
+
}
|
|
3520
|
+
/** Resolves when the process is asked to stop: Ctrl-C, SIGTERM, SIGHUP, or Ctrl+Break on Windows. */
|
|
3521
|
+
function stopSignal() {
|
|
3522
|
+
return new Promise((resolve) => {
|
|
3523
|
+
for (const signal of [
|
|
3524
|
+
"SIGINT",
|
|
3525
|
+
"SIGTERM",
|
|
3526
|
+
"SIGHUP",
|
|
3527
|
+
"SIGBREAK"
|
|
3528
|
+
]) process.once(signal, () => resolve(signal));
|
|
3529
|
+
});
|
|
3530
|
+
}
|
|
3531
|
+
/** Serves over stdio until the client closes stdin or the process is stopped. */
|
|
3532
|
+
async function serveOverStdio(options) {
|
|
3533
|
+
const instance = startInstance(options);
|
|
3534
|
+
const handle = serveStdio(factoryFor(options, instance), { onerror: (error) => options.log(`mostra mcp: ${error.message}`) });
|
|
3535
|
+
const ended = new Promise((resolve) => {
|
|
3536
|
+
process.stdin.once("end", () => resolve("stdin"));
|
|
3537
|
+
process.stdin.once("close", () => resolve("stdin"));
|
|
3538
|
+
});
|
|
3539
|
+
await Promise.race([ended, stopSignal()]);
|
|
3540
|
+
await handle.close().catch(() => {});
|
|
3541
|
+
instance.close();
|
|
3542
|
+
return instance;
|
|
3543
|
+
}
|
|
3544
|
+
/** The address and URL host of `--bind` and `--url-host` (D99's rules, D164 item 3). */
|
|
3545
|
+
function mcpBind(options) {
|
|
3546
|
+
const fail = (message) => new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message }));
|
|
3547
|
+
const address = (options.bind ?? "127.0.0.1").replace(/^\[(.*)\]$/, "$1");
|
|
3548
|
+
if (isIP(address) === 0) throw fail(`--bind takes an IP address, such as 127.0.0.1, not "${options.bind}".`);
|
|
3549
|
+
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.");
|
|
3550
|
+
const canonical = new URL(`http://${isIP(address) === 6 ? `[${address}]` : address}/`).hostname;
|
|
3551
|
+
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.`);
|
|
3552
|
+
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}".`);
|
|
3553
|
+
return {
|
|
3554
|
+
address,
|
|
3555
|
+
urlHost: (options.urlHost ?? canonical).toLowerCase()
|
|
3556
|
+
};
|
|
3557
|
+
}
|
|
3558
|
+
/** The fewest distinct characters a chosen token must have, so `aaaa…` isn't accepted. */
|
|
3559
|
+
const TOKEN_VARIETY = 8;
|
|
3560
|
+
/** The bearer token: `MOSTRA_MCP_TOKEN`, or one made for this run (160 bits). */
|
|
3561
|
+
function mcpToken(env) {
|
|
3562
|
+
const given = env["MOSTRA_MCP_TOKEN"];
|
|
3563
|
+
if (given !== void 0 && given !== "") {
|
|
3564
|
+
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\`.` }));
|
|
3565
|
+
return {
|
|
3566
|
+
token: given,
|
|
3567
|
+
generated: false
|
|
3568
|
+
};
|
|
3569
|
+
}
|
|
3570
|
+
return {
|
|
3571
|
+
token: randomBytes(20).toString("base64url"),
|
|
3572
|
+
generated: true
|
|
3573
|
+
};
|
|
3574
|
+
}
|
|
3575
|
+
/** A request's headers as `[name, value]` pairs in arrival order (Node's `rawHeaders`). */
|
|
3576
|
+
function pairs(incoming) {
|
|
3577
|
+
const raw = incoming.rawHeaders;
|
|
3578
|
+
const out = [];
|
|
3579
|
+
for (let index = 0; index + 1 < raw.length; index += 2) out.push([raw[index], raw[index + 1]]);
|
|
3580
|
+
return out;
|
|
3581
|
+
}
|
|
3582
|
+
/** Serves Streamable HTTP until the process is stopped; tells `onListening` where. */
|
|
3583
|
+
async function serveOverHttp(options) {
|
|
3584
|
+
const { address, urlHost } = mcpBind({
|
|
3585
|
+
...options.bind !== void 0 ? { bind: options.bind } : {},
|
|
3586
|
+
...options.urlHost !== void 0 ? { urlHost: options.urlHost } : {}
|
|
3587
|
+
});
|
|
3588
|
+
const { token, generated } = mcpToken(options.env);
|
|
3589
|
+
const instance = startInstance(options);
|
|
3590
|
+
const factory = factoryFor(options, instance);
|
|
3591
|
+
let endpoint;
|
|
3592
|
+
const server = serve({
|
|
3593
|
+
fetch: (request, env) => {
|
|
3594
|
+
if (endpoint === void 0) return new Response(null, { status: 503 });
|
|
3595
|
+
return endpoint.fetch(request, {
|
|
3596
|
+
target: env.incoming.url ?? "/",
|
|
3597
|
+
headers: pairs(env.incoming)
|
|
3598
|
+
});
|
|
3599
|
+
},
|
|
3600
|
+
port: options.port,
|
|
3601
|
+
hostname: address
|
|
3602
|
+
});
|
|
3603
|
+
const port = await new Promise((resolve, reject) => {
|
|
3604
|
+
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}).` }))));
|
|
3605
|
+
server.once("listening", () => {
|
|
3606
|
+
const bound = server.address();
|
|
3607
|
+
resolve(typeof bound === "object" && bound !== null ? bound.port : options.port);
|
|
3608
|
+
});
|
|
3609
|
+
});
|
|
3610
|
+
if ("keepAliveTimeout" in server) {
|
|
3611
|
+
server.keepAliveTimeout = 305e3;
|
|
3612
|
+
server.headersTimeout = 306e3;
|
|
3613
|
+
}
|
|
3614
|
+
const origin = `http://${urlHost}:${port}`;
|
|
3615
|
+
endpoint = createHttpEndpoint(factory, {
|
|
3616
|
+
origin,
|
|
3617
|
+
hosts: [`${urlHost}:${port}`],
|
|
3618
|
+
token,
|
|
3619
|
+
onRefusal: (refused) => options.log(`mostra mcp: refused a request (${refused.status} ${refused.code})`),
|
|
3620
|
+
onError: (error) => options.log(`mostra mcp: ${error.message}`)
|
|
3621
|
+
});
|
|
3622
|
+
options.onListening({
|
|
3623
|
+
url: `${origin}${MCP_PATH}`,
|
|
3624
|
+
port,
|
|
3625
|
+
token,
|
|
3626
|
+
generated
|
|
3627
|
+
});
|
|
3628
|
+
await stopSignal();
|
|
3629
|
+
await endpoint.close().catch(() => {});
|
|
3630
|
+
await new Promise((resolve) => {
|
|
3631
|
+
server.close(() => resolve());
|
|
3632
|
+
server.closeAllConnections?.();
|
|
3633
|
+
});
|
|
3634
|
+
instance.close();
|
|
3635
|
+
return instance;
|
|
3636
|
+
}
|
|
3637
|
+
//#endregion
|
|
3638
|
+
//#region src/commands/mcp.ts
|
|
3639
|
+
/**
|
|
3640
|
+
* `mostra mcp` (INTERFACES §12, D164): Mostra's MCP server, for any MCP client. Over stdio by
|
|
3641
|
+
* default (a client starts it), or Streamable HTTP with `--http`. Its tools are `@mostra/mcp`'s;
|
|
3642
|
+
* this command gives them the home's daemon, the workspace and the reference, and counts each
|
|
3643
|
+
* MCP client in telemetry unless `--embedded` says a host or harness plugin started it (D148).
|
|
3644
|
+
*/
|
|
3645
|
+
/** `mostra mcp`. */
|
|
3646
|
+
const mcpCommand = defineCommand({
|
|
3647
|
+
path: ["mcp"],
|
|
3648
|
+
summary: "Run Mostra's MCP server, so an MCP client can create, verify and publish artifacts, wait for answers and read results.",
|
|
3649
|
+
flags: [
|
|
3650
|
+
{
|
|
3651
|
+
name: "http",
|
|
3652
|
+
kind: "boolean",
|
|
3653
|
+
summary: "Serve Streamable HTTP at /mcp instead of stdio; every request needs Authorization: Bearer <token>."
|
|
3654
|
+
},
|
|
3655
|
+
{
|
|
3656
|
+
name: "port",
|
|
3657
|
+
kind: "number",
|
|
3658
|
+
value: "<port>",
|
|
3659
|
+
summary: "With --http, the port; default one the system picks."
|
|
3660
|
+
},
|
|
3661
|
+
{
|
|
3662
|
+
name: "bind",
|
|
3663
|
+
kind: "string",
|
|
3664
|
+
value: "<address>",
|
|
3665
|
+
summary: "With --http, listen on this address instead of 127.0.0.1."
|
|
3666
|
+
},
|
|
3667
|
+
{
|
|
3668
|
+
name: "url-host",
|
|
3669
|
+
kind: "string",
|
|
3670
|
+
value: "<name>",
|
|
3671
|
+
summary: "With --http, the host name clients use; a wildcard --bind needs it."
|
|
3672
|
+
},
|
|
3673
|
+
{
|
|
3674
|
+
name: "workspace",
|
|
3675
|
+
kind: "string",
|
|
3676
|
+
value: "<dir>",
|
|
3677
|
+
summary: "Where relative artifact directories and new artifacts go. Default: MOSTRA_MCP_WORKSPACE, else ~/mostra-artifacts."
|
|
3678
|
+
},
|
|
3679
|
+
{
|
|
3680
|
+
name: "embedded",
|
|
3681
|
+
kind: "boolean",
|
|
3682
|
+
summary: "This server runs on someone's behalf (a harness plugin or another host started it), so it sends no telemetry."
|
|
3683
|
+
}
|
|
3684
|
+
],
|
|
3685
|
+
output: {
|
|
3686
|
+
type: "the MCP protocol on stdin and stdout, or over HTTP",
|
|
3687
|
+
topic: "cli"
|
|
3688
|
+
},
|
|
3689
|
+
exits: [],
|
|
3690
|
+
example: "mcp",
|
|
3691
|
+
readsStdin: (flags) => flags["http"] !== true,
|
|
3692
|
+
quiet: (flags) => flags["embedded"] === true,
|
|
3693
|
+
async run(context) {
|
|
3694
|
+
const http = context.flags["http"] === true;
|
|
3695
|
+
const port = context.flags["port"];
|
|
3696
|
+
const bind = flag(context, "bind");
|
|
3697
|
+
const urlHost = flag(context, "url-host");
|
|
3698
|
+
if (!http && (port !== void 0 || bind !== void 0 || urlHost !== void 0)) throw usage("--port, --bind and --url-host go with --http.");
|
|
3699
|
+
if (typeof port === "number" && (!Number.isInteger(port) || port < 0 || port > 65535)) throw usage("--port takes a port number from 0 to 65535.");
|
|
3700
|
+
const given = flag(context, "workspace") ?? context.env["MOSTRA_MCP_WORKSPACE"];
|
|
3701
|
+
const workspace = given !== void 0 && given !== "" ? resolve(context.cwd, given) : defaultWorkspaceRoot();
|
|
3702
|
+
const counted = /* @__PURE__ */ new Set();
|
|
3703
|
+
let reached;
|
|
3704
|
+
const options = {
|
|
3705
|
+
home: context.home,
|
|
3706
|
+
env: context.env,
|
|
3707
|
+
workspace,
|
|
3708
|
+
version: cliVersion(),
|
|
3709
|
+
log: context.log,
|
|
3710
|
+
onClient(client, instance) {
|
|
3711
|
+
reached = instance;
|
|
3712
|
+
const fields = mcpSessionFields(client);
|
|
3713
|
+
const key = `${fields.client}@${fields.clientVersion ?? ""}`;
|
|
3714
|
+
if (counted.has(key)) return;
|
|
3715
|
+
counted.add(key);
|
|
3716
|
+
context.record({
|
|
3717
|
+
event: "mcp.session",
|
|
3718
|
+
fields
|
|
3719
|
+
});
|
|
3720
|
+
context.checkpoint(instance.hostInstance() || embeddedHome(readHomeMarks(context.home)));
|
|
3721
|
+
}
|
|
3722
|
+
};
|
|
3723
|
+
const done = {
|
|
3724
|
+
result: void 0,
|
|
3725
|
+
raw: true
|
|
3726
|
+
};
|
|
3727
|
+
if (!http) {
|
|
3728
|
+
await serveOverStdio(options);
|
|
3729
|
+
return {
|
|
3730
|
+
...done,
|
|
3731
|
+
hostInstance: reached?.hostInstance() === true
|
|
3732
|
+
};
|
|
3733
|
+
}
|
|
3734
|
+
await serveOverHttp({
|
|
3735
|
+
...options,
|
|
3736
|
+
port: typeof port === "number" ? port : 0,
|
|
3737
|
+
...bind !== void 0 ? { bind } : {},
|
|
3738
|
+
...urlHost !== void 0 ? { urlHost } : {},
|
|
3739
|
+
onListening({ url, token, generated }) {
|
|
3740
|
+
if (context.json) context.emit({
|
|
3741
|
+
kind: "listening",
|
|
3742
|
+
url
|
|
3743
|
+
});
|
|
3744
|
+
else context.stderr(`Mostra's MCP server is listening at ${url}\n`);
|
|
3745
|
+
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");
|
|
3746
|
+
}
|
|
3747
|
+
});
|
|
3748
|
+
return {
|
|
3749
|
+
...done,
|
|
3750
|
+
hostInstance: reached?.hostInstance() === true
|
|
3751
|
+
};
|
|
3752
|
+
}
|
|
3753
|
+
});
|
|
3754
|
+
//#endregion
|
|
3755
|
+
//#region src/commands/remote.ts
|
|
3756
|
+
/**
|
|
3757
|
+
* `mostra login` and `mostra logout` (INTERFACES §18.7, D165 items 2, 15): this home signs in to a
|
|
3758
|
+
* remote server by the OAuth device authorization grant, so `mostra share --cloud` can host its
|
|
3759
|
+
* artifacts there, and signs out again. The instance keeps the refresh token in the home,
|
|
3760
|
+
* owner-only; signing out keeps its instance link, so the artifacts it shared stay its own at the
|
|
3761
|
+
* next sign-in, unless `--forget`. Clients of `remote/login`, `remote/login.wait` and
|
|
3762
|
+
* `remote/logout`.
|
|
3763
|
+
*/
|
|
3764
|
+
/** How long `mostra login` waits for the person to approve, in all (the code lives 10 minutes). */
|
|
3765
|
+
const LOGIN_WAIT_MS = 6e5;
|
|
3766
|
+
/** Each wait asks the instance for this long, so a slow approval never meets a request timeout. */
|
|
3767
|
+
const LOGIN_STEP_MS = 3e4;
|
|
3768
|
+
/** `mostra login [<server>] [--default]`. */
|
|
3769
|
+
const loginCommand = defineCommand({
|
|
3770
|
+
path: ["login"],
|
|
3771
|
+
summary: "Sign this machine's Mostra in to a remote server, so mostra share --cloud can host pages there.",
|
|
3772
|
+
args: [{
|
|
3773
|
+
name: "server",
|
|
3774
|
+
summary: "The server's address, such as https://api.example.com. Default: the server signed in to last.",
|
|
3775
|
+
optional: true
|
|
3776
|
+
}],
|
|
3777
|
+
flags: [{
|
|
3778
|
+
name: "default",
|
|
3779
|
+
kind: "boolean",
|
|
3780
|
+
summary: "Make this machine the account's default, the one chat apps create pages on. Default: the first machine linked."
|
|
3781
|
+
}],
|
|
3782
|
+
output: {
|
|
3783
|
+
type: "RemoteLoginWaitResult",
|
|
3784
|
+
topic: "cli"
|
|
3785
|
+
},
|
|
3786
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3787
|
+
example: "login https://api.example.com",
|
|
3788
|
+
async run(context) {
|
|
3789
|
+
const server = context.args["server"];
|
|
3790
|
+
const started = await context.call(remoteLoginMethod, {
|
|
3791
|
+
...typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {},
|
|
3792
|
+
...context.flags["default"] === true ? { default: true } : {}
|
|
3793
|
+
});
|
|
3794
|
+
const where = started.verificationUriComplete ?? started.verificationUri;
|
|
3795
|
+
context.emit({
|
|
3796
|
+
kind: "code",
|
|
3797
|
+
...started
|
|
3798
|
+
}, `Open ${where} and check that it shows the code ${started.userCode}, then approve.\nWaiting for you to approve…`);
|
|
3799
|
+
const deadline = Date.now() + LOGIN_WAIT_MS;
|
|
3800
|
+
for (;;) {
|
|
3801
|
+
const waited = await context.call(remoteLoginWaitMethod, {
|
|
3802
|
+
loginId: started.loginId,
|
|
3803
|
+
timeoutMs: Math.max(0, Math.min(LOGIN_STEP_MS, deadline - Date.now()))
|
|
3804
|
+
});
|
|
3805
|
+
if (waited.status === "signed-in") return {
|
|
3806
|
+
result: waited,
|
|
3807
|
+
human: `Signed in to ${waited.server} as ${waited.account.name ?? waited.account.id}. This machine is ${waited.instanceId}.\n`
|
|
3808
|
+
};
|
|
3809
|
+
if (Date.now() >= deadline) return {
|
|
3810
|
+
result: waited,
|
|
3811
|
+
human: "The code wasn't approved in time. Run mostra login again for a new one.\n",
|
|
3812
|
+
exit: EXIT.timeout
|
|
3813
|
+
};
|
|
3814
|
+
}
|
|
3815
|
+
}
|
|
3816
|
+
});
|
|
3817
|
+
/** `mostra logout [<server>] [--forget]`. */
|
|
3818
|
+
const logoutCommand = defineCommand({
|
|
3819
|
+
path: ["logout"],
|
|
3820
|
+
summary: "Sign this machine's Mostra out of a remote server; its hosted pages keep working, and their answers wait for the next sign-in.",
|
|
3821
|
+
args: [{
|
|
3822
|
+
name: "server",
|
|
3823
|
+
summary: "The server's address. Default: the server signed in to last.",
|
|
3824
|
+
optional: true
|
|
3825
|
+
}],
|
|
3826
|
+
flags: [{
|
|
3827
|
+
name: "forget",
|
|
3828
|
+
kind: "boolean",
|
|
3829
|
+
summary: "Also forget this machine's link to the server: the pages it shared there are no longer its own."
|
|
3830
|
+
}],
|
|
3831
|
+
output: {
|
|
3832
|
+
type: "RemoteLogoutResult",
|
|
3833
|
+
topic: "cli"
|
|
3834
|
+
},
|
|
3835
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3836
|
+
example: "logout",
|
|
3837
|
+
async run(context) {
|
|
3838
|
+
const server = context.args["server"];
|
|
3839
|
+
const result = await context.call(remoteLogoutMethod, {
|
|
3840
|
+
...typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {},
|
|
3841
|
+
...context.flags["forget"] === true ? { forget: true } : {}
|
|
3842
|
+
});
|
|
3843
|
+
return {
|
|
3844
|
+
result,
|
|
3845
|
+
human: result.servers.length === 0 ? "This machine wasn't signed in to a server.\n" : `Signed out of ${result.servers.join(", ")}.\n`
|
|
3846
|
+
};
|
|
3847
|
+
}
|
|
3848
|
+
});
|
|
3849
|
+
//#endregion
|
|
3850
|
+
//#region src/commands/sharing.ts
|
|
3851
|
+
/**
|
|
3852
|
+
* `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
|
|
3853
|
+
* runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
|
|
3854
|
+
* identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
|
|
3855
|
+
* funnel`), whose link expires (1 hour by default, 7 days at most); or `--cloud` (D165 item 15),
|
|
3856
|
+
* hosted on a remote server this home signed in to, so the link works while this machine sleeps. The share lives in the
|
|
3857
|
+
* daemon, so the command returns at once with the link; `share stop` ends it and `share list`
|
|
3858
|
+
* shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
|
|
3859
|
+
*/
|
|
3860
|
+
const SHARE_ID = /^shr_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
3861
|
+
/** How each tunnel is named in human output. */
|
|
3862
|
+
const THROUGH = {
|
|
3863
|
+
tailnet: "Tailscale Serve, inside your tailnet",
|
|
3864
|
+
funnel: "Tailscale Funnel, public",
|
|
3865
|
+
cloudflare: "a Cloudflare quick tunnel, public",
|
|
3866
|
+
remote: "a remote server, hosted"
|
|
3867
|
+
};
|
|
3868
|
+
/**
|
|
3869
|
+
* What a tailnet viewer's device needs, found on a real tailnet in WP-13: the tailnet's access
|
|
3870
|
+
* policy must let them reach the share's two ports of this device, and their browser's traffic
|
|
3871
|
+
* must go through Tailscale (no private or secure DNS of its own, no split tunneling that leaves
|
|
3872
|
+
* the browser out).
|
|
3873
|
+
*/
|
|
3874
|
+
function tailnetReach(share) {
|
|
3875
|
+
const port = (origin) => origin === void 0 ? void 0 : new URL(origin).port || "443";
|
|
3876
|
+
const ports = [port(share.url), port(share.artifactOrigin)].filter((value) => value !== void 0);
|
|
3877
|
+
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`;
|
|
3878
|
+
}
|
|
3879
|
+
/** One share as a line of human output. */
|
|
3880
|
+
function line(share) {
|
|
3881
|
+
const until = share.state === "stopped" ? `stopped${share.stopReason ? ` (${share.stopReason})` : ""}` : share.expiresAt ? `until ${share.expiresAt}` : "no expiry";
|
|
3882
|
+
return `${share.shareId} ${share.via} ${share.hostname} ${until}`;
|
|
3883
|
+
}
|
|
3884
|
+
/** `mostra share <artifact> --tailnet | --public`. */
|
|
3885
|
+
const shareCommand = defineCommand({
|
|
3886
|
+
path: ["share"],
|
|
3887
|
+
summary: "Open an artifact to people beyond this machine: inside your tailnet, publicly with a link that expires, or hosted on a server.",
|
|
3888
|
+
args: [{
|
|
3889
|
+
name: "artifact",
|
|
3890
|
+
summary: "The artifact: its source path or its ID."
|
|
3891
|
+
}, {
|
|
3892
|
+
name: "server",
|
|
3893
|
+
summary: "With --cloud: the server's address. Default: the server signed in to last.",
|
|
3894
|
+
optional: true
|
|
3895
|
+
}],
|
|
3896
|
+
flags: [
|
|
3897
|
+
{
|
|
3898
|
+
name: "cloud",
|
|
3899
|
+
kind: "boolean",
|
|
3900
|
+
summary: "Host it on a remote server you signed in to with mostra login: the link keeps working while this machine sleeps."
|
|
3901
|
+
},
|
|
3902
|
+
{
|
|
3903
|
+
name: "tailnet",
|
|
3904
|
+
kind: "boolean",
|
|
3905
|
+
summary: "Share inside your tailnet through Tailscale Serve; each viewer is their tailnet identity."
|
|
3906
|
+
},
|
|
3907
|
+
{
|
|
3908
|
+
name: "public",
|
|
3909
|
+
kind: "boolean",
|
|
3910
|
+
summary: "Share publicly: anyone with the link can open it until it expires."
|
|
3911
|
+
},
|
|
3912
|
+
{
|
|
3913
|
+
name: "via",
|
|
3914
|
+
kind: "string",
|
|
3915
|
+
value: "<tunnel>",
|
|
3916
|
+
choices: ["cloudflare", "funnel"],
|
|
3917
|
+
default: "cloudflare",
|
|
3918
|
+
summary: "The public tunnel: a Cloudflare quick tunnel (no account), or Tailscale Funnel (shows your device's tailnet name)."
|
|
3919
|
+
},
|
|
3920
|
+
{
|
|
3921
|
+
name: "ttl",
|
|
3922
|
+
kind: "duration",
|
|
3923
|
+
value: "<d>",
|
|
3924
|
+
summary: "How long the link works, such as 30m or 24h. Public: 1h by default, 7d at most."
|
|
3925
|
+
},
|
|
3926
|
+
{
|
|
3927
|
+
name: "scope",
|
|
3928
|
+
kind: "list",
|
|
3929
|
+
value: "<a,b>",
|
|
3930
|
+
summary: "The link's scopes: view, draft, submit, review, signal, action:*. Default: all."
|
|
3931
|
+
},
|
|
3932
|
+
{
|
|
3933
|
+
name: "viewer",
|
|
3934
|
+
kind: "string",
|
|
3935
|
+
value: "<ref>",
|
|
3936
|
+
summary: "The person the link is for, by your own stable key for them; without it, each link is a viewer of its own."
|
|
3937
|
+
},
|
|
3938
|
+
{
|
|
3939
|
+
name: "viewer-name",
|
|
3940
|
+
kind: "string",
|
|
3941
|
+
value: "<name>",
|
|
3942
|
+
summary: "The display name of --viewer."
|
|
3943
|
+
},
|
|
3944
|
+
{
|
|
3945
|
+
name: "request-id",
|
|
3946
|
+
kind: "string",
|
|
3947
|
+
value: "<id>",
|
|
3948
|
+
summary: "Make a retried share return the same share instead of opening another."
|
|
3949
|
+
}
|
|
3950
|
+
],
|
|
3951
|
+
output: {
|
|
3952
|
+
type: "ShareStartResult",
|
|
3953
|
+
topic: "cli"
|
|
3954
|
+
},
|
|
3955
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3956
|
+
example: "share ./sidebar-review --cloud",
|
|
3957
|
+
async run(context) {
|
|
3958
|
+
const artifact = artifactRef(arg(context, "artifact"), context.cwd);
|
|
3959
|
+
const tailnet = context.flags["tailnet"] === true;
|
|
3960
|
+
const publicly = context.flags["public"] === true;
|
|
3961
|
+
const cloud = context.flags["cloud"] === true;
|
|
3962
|
+
if ([
|
|
3963
|
+
tailnet,
|
|
3964
|
+
publicly,
|
|
3965
|
+
cloud
|
|
3966
|
+
].filter(Boolean).length !== 1) throw usage("Give one of --tailnet, --public or --cloud.");
|
|
3967
|
+
const viaFlag = flag(context, "via");
|
|
3968
|
+
if (viaFlag !== void 0 && !publicly) throw usage("--via chooses a public tunnel: add --public.");
|
|
3969
|
+
const server = context.args["server"];
|
|
3970
|
+
if (server !== void 0 && !cloud) throw usage("A server names where --cloud hosts it.");
|
|
3971
|
+
const via = cloud ? "remote" : tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
|
|
3972
|
+
const ttl = flag(context, "ttl");
|
|
3973
|
+
const scopes = context.flags["scope"];
|
|
3974
|
+
const viewerRef = flag(context, "viewer");
|
|
3975
|
+
const viewerName = flag(context, "viewer-name");
|
|
3976
|
+
const requestId = flag(context, "request-id");
|
|
3977
|
+
if (viewerName !== void 0 && viewerRef === void 0) throw usage("--viewer-name needs --viewer.");
|
|
3978
|
+
const share = await context.call(shareStartMethod, {
|
|
3979
|
+
artifact,
|
|
3980
|
+
via,
|
|
3981
|
+
...typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {},
|
|
3982
|
+
...ttl !== void 0 ? { ttl } : {},
|
|
3983
|
+
...scopes !== void 0 ? { scopes } : {},
|
|
3984
|
+
...viewerRef !== void 0 ? { viewer: {
|
|
3985
|
+
ref: viewerRef,
|
|
3986
|
+
...viewerName !== void 0 ? { name: viewerName } : {}
|
|
3987
|
+
} } : {},
|
|
3988
|
+
...requestId !== void 0 ? { requestId } : {}
|
|
3989
|
+
});
|
|
3990
|
+
context.record({
|
|
3991
|
+
event: "share.done",
|
|
3992
|
+
fields: { kind: via }
|
|
3993
|
+
});
|
|
3994
|
+
const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
|
|
3995
|
+
return {
|
|
3996
|
+
result: share,
|
|
3997
|
+
human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`
|
|
3998
|
+
};
|
|
3999
|
+
}
|
|
4000
|
+
});
|
|
4001
|
+
/** `mostra share stop <artifact|shareId>`. */
|
|
4002
|
+
const shareStopCommand = defineCommand({
|
|
4003
|
+
path: ["share", "stop"],
|
|
4004
|
+
summary: "Stop a share, or every share of an artifact: its link stops working and its tunnel closes.",
|
|
4005
|
+
args: [{
|
|
4006
|
+
name: "target",
|
|
4007
|
+
summary: "A share's ID (shr_…), or an artifact's source path or ID."
|
|
4008
|
+
}],
|
|
4009
|
+
flags: [],
|
|
4010
|
+
output: {
|
|
4011
|
+
type: "ShareStopResult",
|
|
4012
|
+
topic: "cli"
|
|
4013
|
+
},
|
|
4014
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
4015
|
+
example: "share stop ./sidebar-review",
|
|
4016
|
+
async run(context) {
|
|
4017
|
+
const target = arg(context, "target");
|
|
4018
|
+
const result = await context.call(shareStopMethod, SHARE_ID.test(target) ? { shareId: target } : { artifact: artifactRef(target, context.cwd) });
|
|
4019
|
+
return {
|
|
4020
|
+
result,
|
|
4021
|
+
human: result.stopped.length === 0 ? "Nothing was shared.\n" : result.stopped.map((share) => `Stopped ${share.shareId}\n`).join("")
|
|
4022
|
+
};
|
|
4023
|
+
}
|
|
4024
|
+
});
|
|
4025
|
+
/** `mostra share list [artifact] [--all]`. */
|
|
4026
|
+
const shareListCommand = defineCommand({
|
|
4027
|
+
path: ["share", "list"],
|
|
4028
|
+
summary: "List the active shares, of every artifact or of one; --all adds the ones that ended.",
|
|
4029
|
+
args: [{
|
|
4030
|
+
name: "artifact",
|
|
4031
|
+
summary: "Only this artifact's shares: its source path or ID.",
|
|
4032
|
+
optional: true
|
|
4033
|
+
}],
|
|
4034
|
+
flags: [{
|
|
4035
|
+
name: "all",
|
|
4036
|
+
kind: "boolean",
|
|
4037
|
+
summary: "Also list shares that ended, and why."
|
|
4038
|
+
}],
|
|
4039
|
+
output: {
|
|
4040
|
+
type: "ShareListResult",
|
|
4041
|
+
topic: "cli"
|
|
4042
|
+
},
|
|
4043
|
+
exits: [EXIT.failure],
|
|
4044
|
+
example: "share list --all",
|
|
4045
|
+
async run(context) {
|
|
4046
|
+
const given = context.args["artifact"];
|
|
4047
|
+
const result = await context.call(shareListMethod, {
|
|
4048
|
+
...typeof given === "string" ? { artifact: artifactRef(given, context.cwd) } : {},
|
|
4049
|
+
...context.flags["all"] === true ? { all: true } : {}
|
|
4050
|
+
});
|
|
4051
|
+
return {
|
|
4052
|
+
result,
|
|
4053
|
+
human: result.shares.length === 0 ? "Nothing is shared.\n" : `${result.shares.map((share) => line(share)).join("\n")}\n`
|
|
4054
|
+
};
|
|
3423
4055
|
}
|
|
3424
|
-
|
|
3425
|
-
return false;
|
|
3426
|
-
}
|
|
4056
|
+
});
|
|
3427
4057
|
//#endregion
|
|
3428
4058
|
//#region src/commands/viewing.ts
|
|
3429
4059
|
/**
|
|
@@ -3447,10 +4077,25 @@ function wantsBrowser(context) {
|
|
|
3447
4077
|
if (context.flags["browser"] === true) return true;
|
|
3448
4078
|
return context.tty.stdout && !context.json && hasDisplay(context.env);
|
|
3449
4079
|
}
|
|
3450
|
-
/**
|
|
4080
|
+
/**
|
|
4081
|
+
* Why no browser was opened, for stderr (#114): an agent's shell isn't a terminal, so without a
|
|
4082
|
+
* word it would tell its person the page is open when it isn't.
|
|
4083
|
+
*/
|
|
4084
|
+
function notOpenedReason(context, tried) {
|
|
4085
|
+
if (context.flags["no-browser"] === true) return void 0;
|
|
4086
|
+
if (tried) return "No browser opened: none could be started here. Give the person the link.";
|
|
4087
|
+
if (!hasDisplay(context.env)) return "No browser opened: this session has no display. Give the person the link.";
|
|
4088
|
+
return "No browser opened: this isn't a terminal. Pass --browser to open it here, or give the person the link.";
|
|
4089
|
+
}
|
|
4090
|
+
/** The link, opened in a browser when wanted; why not on stderr when it wasn't. */
|
|
3451
4091
|
async function show(context, link) {
|
|
3452
4092
|
let opened = false;
|
|
3453
|
-
|
|
4093
|
+
const tried = wantsBrowser(context);
|
|
4094
|
+
if (tried) opened = await openInBrowser((await context.call(viewLaunchMethod, { tokenId: link.tokenId })).url, context.env);
|
|
4095
|
+
if (!opened) {
|
|
4096
|
+
const reason = notOpenedReason(context, tried);
|
|
4097
|
+
if (reason !== void 0) context.log(reason);
|
|
4098
|
+
}
|
|
3454
4099
|
return {
|
|
3455
4100
|
result: {
|
|
3456
4101
|
...link,
|
|
@@ -3585,6 +4230,8 @@ const COMMANDS = [
|
|
|
3585
4230
|
shareCommand,
|
|
3586
4231
|
shareStopCommand,
|
|
3587
4232
|
shareListCommand,
|
|
4233
|
+
loginCommand,
|
|
4234
|
+
logoutCommand,
|
|
3588
4235
|
waitCommand,
|
|
3589
4236
|
resultsCommand,
|
|
3590
4237
|
stateGetCommand,
|
|
@@ -3592,6 +4239,8 @@ const COMMANDS = [
|
|
|
3592
4239
|
statePatchCommand,
|
|
3593
4240
|
pushCommand,
|
|
3594
4241
|
addCommand,
|
|
4242
|
+
exportCommand,
|
|
4243
|
+
runCommand,
|
|
3595
4244
|
secretSetCommand,
|
|
3596
4245
|
secretListCommand,
|
|
3597
4246
|
secretRmCommand,
|
|
@@ -3604,6 +4253,7 @@ const COMMANDS = [
|
|
|
3604
4253
|
daemonInstallCommand,
|
|
3605
4254
|
daemonUninstallCommand,
|
|
3606
4255
|
hostCommand,
|
|
4256
|
+
mcpCommand,
|
|
3607
4257
|
docsCommand,
|
|
3608
4258
|
doctorCommand,
|
|
3609
4259
|
gcCommand,
|
|
@@ -3647,7 +4297,11 @@ function flagLine(flag) {
|
|
|
3647
4297
|
return ` ${name.padEnd(28)} ${flag.summary}${choices}${fallback}`;
|
|
3648
4298
|
}
|
|
3649
4299
|
/** Commands that run until their connection or Ctrl-C ends them: `--timeout` doesn't bound them. */
|
|
3650
|
-
const UNBOUNDED = /* @__PURE__ */ new Set([
|
|
4300
|
+
const UNBOUNDED = /* @__PURE__ */ new Set([
|
|
4301
|
+
"host",
|
|
4302
|
+
"dev",
|
|
4303
|
+
"mcp"
|
|
4304
|
+
]);
|
|
3651
4305
|
/**
|
|
3652
4306
|
* The global flags a command doesn't define again (`wait --timeout` is the wait's own); a command
|
|
3653
4307
|
* `--timeout` doesn't bound has no `--timeout`.
|
|
@@ -3768,191 +4422,6 @@ function referenceMarkdown(commands) {
|
|
|
3768
4422
|
].join("\n");
|
|
3769
4423
|
}
|
|
3770
4424
|
//#endregion
|
|
3771
|
-
//#region src/client.ts
|
|
3772
|
-
/**
|
|
3773
|
-
* The CLI's connection to its home's instance (D45, D81, INTERFACES §9): it attaches to the
|
|
3774
|
-
* daemon recorded in `instance.json`, or starts one (`mostra-runtime daemon`, which itself
|
|
3775
|
-
* attaches when another starter won), and opens a session as `mostra-cli`. The SDK (WP-11) does
|
|
3776
|
-
* the same few steps over the same protocol.
|
|
3777
|
-
*/
|
|
3778
|
-
/** How long one attempt to reach a recorded socket waits. */
|
|
3779
|
-
const ATTACH_TIMEOUT_MS = 5e3;
|
|
3780
|
-
/** How long a daemon this command starts may take to say where it listens. */
|
|
3781
|
-
const START_TIMEOUT_MS = 3e4;
|
|
3782
|
-
/**
|
|
3783
|
-
* Opens a session with the home's instance, starting its daemon when none runs. Returns
|
|
3784
|
-
* `undefined` when `autostart` is false and no instance runs. Throws the start's diagnostic when
|
|
3785
|
-
* the daemon can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …).
|
|
3786
|
-
*/
|
|
3787
|
-
async function connect(options) {
|
|
3788
|
-
const recorded = readSocket(options.home);
|
|
3789
|
-
if (recorded !== void 0) {
|
|
3790
|
-
const session = await open(recorded, options, false).catch(() => void 0);
|
|
3791
|
-
if (session) return session;
|
|
3792
|
-
}
|
|
3793
|
-
if (options.autostart === false) return void 0;
|
|
3794
|
-
options.onStarting?.(true);
|
|
3795
|
-
let started;
|
|
3796
|
-
try {
|
|
3797
|
-
started = await startDaemon(options);
|
|
3798
|
-
} finally {
|
|
3799
|
-
options.onStarting?.(false);
|
|
3800
|
-
}
|
|
3801
|
-
return open(started.socket, options, started.status === "started");
|
|
3802
|
-
}
|
|
3803
|
-
/**
|
|
3804
|
-
* Opens the endpoint `instance.json` or a starting daemon named: a Unix socket, or on Windows the
|
|
3805
|
-
* owner-only pipe through the runtime's helper, which refuses a pipe another user created under
|
|
3806
|
-
* the name (D150, the SDK's `connectControl`). Only Windows needs the runtime resolved first.
|
|
3807
|
-
*/
|
|
3808
|
-
async function openEndpoint(endpoint, options) {
|
|
3809
|
-
const runtime = process.platform === "win32" ? (await locateRuntime(options.env)).runtime : void 0;
|
|
3810
|
-
return connectControl(endpoint, {
|
|
3811
|
-
runtime,
|
|
3812
|
-
env: options.env,
|
|
3813
|
-
timeoutMs: ATTACH_TIMEOUT_MS
|
|
3814
|
-
});
|
|
3815
|
-
}
|
|
3816
|
-
/** The socket `instance.json` records (D81), if the file exists and reads. */
|
|
3817
|
-
function readSocket(home) {
|
|
3818
|
-
try {
|
|
3819
|
-
const record = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
|
|
3820
|
-
return typeof record.socket === "string" ? record.socket : void 0;
|
|
3821
|
-
} catch {
|
|
3822
|
-
return;
|
|
3823
|
-
}
|
|
3824
|
-
}
|
|
3825
|
-
/**
|
|
3826
|
-
* Starts the home's daemon, detached from this process, and reads the one line it prints: where
|
|
3827
|
-
* it listens, or why it couldn't start. A daemon another starter won prints `attached` and exits.
|
|
3828
|
-
*/
|
|
3829
|
-
async function startDaemon(options) {
|
|
3830
|
-
const deadlineAt = Date.now() + START_TIMEOUT_MS;
|
|
3831
|
-
const timedOut = () => new RpcError(createDiagnostic("MOSTRA_HOST_TIMEOUT", { message: `The home's daemon didn't start within ${formatDuration(START_TIMEOUT_MS)}.` }));
|
|
3832
|
-
const runtime = await locateRuntime(options.env);
|
|
3833
|
-
if (Date.now() >= deadlineAt) throw timedOut();
|
|
3834
|
-
const args = [
|
|
3835
|
-
resolve(runtime.entry),
|
|
3836
|
-
"daemon",
|
|
3837
|
-
"--home",
|
|
3838
|
-
options.home
|
|
3839
|
-
];
|
|
3840
|
-
return new Promise((resolve, reject) => {
|
|
3841
|
-
const child = spawn(runtime.node, args, {
|
|
3842
|
-
detached: true,
|
|
3843
|
-
cwd: detachedDirectory(options.home),
|
|
3844
|
-
windowsHide: true,
|
|
3845
|
-
stdio: [
|
|
3846
|
-
"ignore",
|
|
3847
|
-
"pipe",
|
|
3848
|
-
"ignore"
|
|
3849
|
-
],
|
|
3850
|
-
env: detachedEnvironment({
|
|
3851
|
-
...process.env,
|
|
3852
|
-
...options.env
|
|
3853
|
-
})
|
|
3854
|
-
});
|
|
3855
|
-
const splitter = new LineSplitter();
|
|
3856
|
-
let settled = false;
|
|
3857
|
-
const finish = (outcome) => {
|
|
3858
|
-
if (settled) return;
|
|
3859
|
-
settled = true;
|
|
3860
|
-
clearTimeout(timer);
|
|
3861
|
-
child.stdout?.removeAllListeners("data");
|
|
3862
|
-
child.stdout?.destroy();
|
|
3863
|
-
child.unref();
|
|
3864
|
-
outcome();
|
|
3865
|
-
};
|
|
3866
|
-
const timer = setTimeout(() => finish(() => reject(timedOut())), Math.max(0, deadlineAt - Date.now()));
|
|
3867
|
-
child.on("error", (error) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_MISSING", { message: `The runtime couldn't be started: ${error.message}` })))));
|
|
3868
|
-
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.` })))));
|
|
3869
|
-
child.stdout?.setEncoding("utf8");
|
|
3870
|
-
child.stdout?.on("data", (chunk) => {
|
|
3871
|
-
for (const line of splitter.push(chunk)) {
|
|
3872
|
-
let parsed;
|
|
3873
|
-
try {
|
|
3874
|
-
parsed = JSON.parse(line);
|
|
3875
|
-
} catch {
|
|
3876
|
-
continue;
|
|
3877
|
-
}
|
|
3878
|
-
finish(() => {
|
|
3879
|
-
if (parsed.status === "failed") reject(new RpcError(parsed.diagnostic ?? createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: "The home's daemon failed to start." })));
|
|
3880
|
-
else resolve(parsed);
|
|
3881
|
-
});
|
|
3882
|
-
return;
|
|
3883
|
-
}
|
|
3884
|
-
});
|
|
3885
|
-
});
|
|
3886
|
-
}
|
|
3887
|
-
async function open(socketPath, options, started) {
|
|
3888
|
-
const socket = await openEndpoint(socketPath, options);
|
|
3889
|
-
const handlers = /* @__PURE__ */ new Map();
|
|
3890
|
-
const peer = new RpcPeer({
|
|
3891
|
-
send: (message) => {
|
|
3892
|
-
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
3893
|
-
},
|
|
3894
|
-
onNotification: (method, params) => handlers.get(method)?.(params)
|
|
3895
|
-
});
|
|
3896
|
-
let markClosed = () => {};
|
|
3897
|
-
const closedPromise = new Promise((done) => {
|
|
3898
|
-
markClosed = done;
|
|
3899
|
-
});
|
|
3900
|
-
const splitter = new LineSplitter();
|
|
3901
|
-
socket.setEncoding("utf8");
|
|
3902
|
-
socket.on("data", (chunk) => {
|
|
3903
|
-
for (const line of splitter.push(chunk)) peer.receiveLine(line);
|
|
3904
|
-
});
|
|
3905
|
-
const end = () => {
|
|
3906
|
-
peer.close();
|
|
3907
|
-
markClosed();
|
|
3908
|
-
};
|
|
3909
|
-
socket.on("close", end);
|
|
3910
|
-
socket.on("error", () => socket.destroy());
|
|
3911
|
-
let result;
|
|
3912
|
-
try {
|
|
3913
|
-
result = await peer.call(mostraInitializeMethod, {
|
|
3914
|
-
client: {
|
|
3915
|
-
name: CLI_CLIENT_NAME,
|
|
3916
|
-
version: cliVersion()
|
|
3917
|
-
},
|
|
3918
|
-
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
3919
|
-
capabilities: { notifications: [ARTIFACT_PROGRESS, DEV_NOTIFY] },
|
|
3920
|
-
ports: [],
|
|
3921
|
-
home: { path: options.home }
|
|
3922
|
-
}, { timeoutMs: ATTACH_TIMEOUT_MS });
|
|
3923
|
-
} catch (error) {
|
|
3924
|
-
socket.destroy();
|
|
3925
|
-
throw error;
|
|
3926
|
-
}
|
|
3927
|
-
return {
|
|
3928
|
-
summary: {
|
|
3929
|
-
home: result.instance.home,
|
|
3930
|
-
socket: socketPath,
|
|
3931
|
-
pid: result.instance.pid,
|
|
3932
|
-
mode: result.instance.mode,
|
|
3933
|
-
version: result.instance.version,
|
|
3934
|
-
started
|
|
3935
|
-
},
|
|
3936
|
-
warnings: result.warnings,
|
|
3937
|
-
call: (method, params, timeoutMs) => peer.call(method, params, timeoutMs !== void 0 ? { timeoutMs } : {}),
|
|
3938
|
-
onNotification: (method, handler) => {
|
|
3939
|
-
handlers.set(method, handler);
|
|
3940
|
-
},
|
|
3941
|
-
closed: closedPromise,
|
|
3942
|
-
close: () => {
|
|
3943
|
-
peer.close();
|
|
3944
|
-
socket.end();
|
|
3945
|
-
socket.destroy();
|
|
3946
|
-
}
|
|
3947
|
-
};
|
|
3948
|
-
}
|
|
3949
|
-
/** A limit as people write it: `250 ms`, `5 s`, `1.5 s`. */
|
|
3950
|
-
function formatDuration(ms) {
|
|
3951
|
-
if (ms < 1e3) return `${ms} ms`;
|
|
3952
|
-
const seconds = ms / 1e3;
|
|
3953
|
-
return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)} s`;
|
|
3954
|
-
}
|
|
3955
|
-
//#endregion
|
|
3956
4425
|
//#region src/run.ts
|
|
3957
4426
|
/**
|
|
3958
4427
|
* The runner (INTERFACES §9, D140 item 16): reads the command line, runs one command, and owns
|
|
@@ -4076,7 +4545,7 @@ async function run(io) {
|
|
|
4076
4545
|
json,
|
|
4077
4546
|
tty: io.tty,
|
|
4078
4547
|
readsStdin,
|
|
4079
|
-
quiet: command.quiet === true,
|
|
4548
|
+
quiet: typeof command.quiet === "function" ? command.quiet(parsed.flags) : command.quiet === true,
|
|
4080
4549
|
hostHome: embeddedHome(marks),
|
|
4081
4550
|
stderr: io.stderr,
|
|
4082
4551
|
ask: (question, timeoutMs) => ask(io, question, timeoutMs)
|
|
@@ -4142,22 +4611,30 @@ async function run(io) {
|
|
|
4142
4611
|
io.stderr(describe(diagnostic));
|
|
4143
4612
|
},
|
|
4144
4613
|
record: (event) => telemetry.record(event),
|
|
4614
|
+
checkpoint(hostInstance) {
|
|
4615
|
+
try {
|
|
4616
|
+
telemetry.checkpoint({ hostInstance });
|
|
4617
|
+
} catch {}
|
|
4618
|
+
},
|
|
4145
4619
|
runtime: (args, stdio = "pipe") => runRuntime(io, args, stdio)
|
|
4146
4620
|
};
|
|
4147
4621
|
let exit;
|
|
4148
4622
|
let error;
|
|
4623
|
+
let ownHostInstance = false;
|
|
4149
4624
|
try {
|
|
4150
4625
|
if (!await telemetry.begin().catch(() => true)) return 130;
|
|
4151
4626
|
const outcome = await withTimeout(command, context, timeoutMs, () => startingDaemon);
|
|
4152
4627
|
exit = outcome.exit ?? EXIT.ok;
|
|
4153
|
-
|
|
4154
|
-
if (
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4628
|
+
ownHostInstance = outcome.hostInstance === true;
|
|
4629
|
+
if (outcome.raw !== true) {
|
|
4630
|
+
if (json) writeJson({
|
|
4631
|
+
ok: true,
|
|
4632
|
+
result: outcome.result ?? null,
|
|
4633
|
+
...summary && !streamed && command.local !== true ? { instance: summary } : {},
|
|
4634
|
+
warnings
|
|
4635
|
+
});
|
|
4636
|
+
else io.stdout(outcome.human ?? `${JSON.stringify(outcome.result, null, 2)}\n`);
|
|
4637
|
+
}
|
|
4161
4638
|
} catch (caught) {
|
|
4162
4639
|
const diagnostic = diagnosticOf(caught);
|
|
4163
4640
|
error = diagnostic.code;
|
|
@@ -4169,7 +4646,7 @@ async function run(io) {
|
|
|
4169
4646
|
telemetry.end({
|
|
4170
4647
|
exit,
|
|
4171
4648
|
durationMs: Date.now() - started,
|
|
4172
|
-
hostInstance: summary?.mode === "host",
|
|
4649
|
+
hostInstance: summary?.mode === "host" || ownHostInstance,
|
|
4173
4650
|
...error !== void 0 ? { error } : {}
|
|
4174
4651
|
});
|
|
4175
4652
|
} catch {}
|
|
@@ -4180,7 +4657,7 @@ async function run(io) {
|
|
|
4180
4657
|
* until their connection or Ctrl-C ends them, so `--timeout` bounds neither.
|
|
4181
4658
|
*/
|
|
4182
4659
|
async function withTimeout(command, context, timeoutMs, startingDaemon) {
|
|
4183
|
-
if (timeoutMs === void 0 ||
|
|
4660
|
+
if (timeoutMs === void 0 || UNBOUNDED.has(command.path[0] ?? "")) return command.run(context);
|
|
4184
4661
|
let timer;
|
|
4185
4662
|
try {
|
|
4186
4663
|
return await Promise.race([command.run(context), new Promise((_, reject) => {
|
|
@@ -4222,4 +4699,4 @@ async function runRuntime(io, args, stdio) {
|
|
|
4222
4699
|
//#endregion
|
|
4223
4700
|
export { COMMANDS as a, referenceMarkdown as i, commandDefinition as n, commandHelp as r, run as t };
|
|
4224
4701
|
|
|
4225
|
-
//# sourceMappingURL=run-
|
|
4702
|
+
//# sourceMappingURL=run-Aq4HVIY0.js.map
|