@mostra/cli 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +2 -2
- package/dist/bootstrap-Dc-SQHRF.js +422 -0
- package/dist/bootstrap-Dc-SQHRF.js.map +1 -0
- package/dist/bootstrap-aaE5wFo9.js +1 -0
- package/dist/{flush-CBN3AU9X.js → flush-C16w3JL8.js} +24 -3
- package/dist/flush-C16w3JL8.js.map +1 -0
- package/dist/index.d.ts +13 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/reference/cli.md +34 -1
- package/dist/reference/diagnostics.json +39 -3
- package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
- package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
- package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
- package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +3 -3
- package/dist/reference/telemetry.md +5 -3
- package/dist/run-Bw4_6kcW.js +1 -0
- package/dist/{run-CuMkFuH7.js → run-DdYT3iHQ.js} +1072 -814
- package/dist/run-DdYT3iHQ.js.map +1 -0
- package/dist/skill/SKILL.md +5 -2
- package/dist/skill/references/answers.md +1 -1
- package/dist/skill/references/long-lived.md +2 -2
- package/dist/skill/references/mcp.md +63 -0
- package/dist/telemetry/flush-main.js +1 -1
- package/package.json +10 -4
- package/src/bootstrap.ts +16 -3
- package/src/command.ts +13 -3
- package/src/commands/dev.ts +60 -44
- package/src/commands/index.ts +4 -2
- package/src/commands/interaction.ts +19 -1
- package/src/commands/mcp.ts +128 -0
- package/src/detached.ts +1 -0
- package/src/docs.ts +14 -6
- package/src/help.ts +1 -1
- package/src/home.ts +5 -3
- package/src/mcp.ts +448 -0
- package/src/parse.ts +20 -6
- package/src/run.ts +24 -13
- package/src/telemetry/harness.ts +24 -0
- package/src/telemetry/index.ts +75 -48
- package/dist/bootstrap-DfEe_yPr.js +0 -113
- package/dist/bootstrap-DfEe_yPr.js.map +0 -1
- package/dist/exit-CBIf8nAU.js +0 -79
- package/dist/exit-CBIf8nAU.js.map +0 -1
- package/dist/flush-CBN3AU9X.js.map +0 -1
- package/dist/run-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-Dc-SQHRF.js";
|
|
2
|
+
import { _ as packageRoot, a as detachedEnvironment, c as durationBucket, d as mcpSessionFields, f as buildEndpoint, g as fromSource, h as cliVersion, i as detachedDirectory, l as minute, m as truthy, n as startFlusher, o as TelemetryEvent, p as decide, r as TelemetryStore, s as catalogCodes, u as detectHarness } from "./flush-C16w3JL8.js";
|
|
3
3
|
import { spawn } from "node:child_process";
|
|
4
4
|
import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, readlinkSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { extname, isAbsolute, join, resolve, win32 } from "node:path";
|
|
6
6
|
import { ARTIFACT_PROGRESS, CLI_CLIENT_NAME, DEFAULT_DOCS_BASE, DEV_NOTIFY, FieldOp, HOST_PROTOCOL_REVISIONS, LineSplitter, MutationId, RpcError, RpcPeer, artifactCreateMethod, artifactGetMethod, artifactListMethod, artifactPublishMethod, artifactVerifyMethod, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, diagnosticCatalog, encodeLine, gcRunMethod, instanceCheckMethod, instanceStatusMethod, livePushMethod, mostraInitializeMethod, mostraShutdownMethod, resultsGetMethod, secretDeleteMethod, secretListMethod, secretSetMethod, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, waitMethod } from "@mostra/protocol";
|
|
7
7
|
import { checkBrowser, checkFiles, connectControl, enclosingBundle, readBundle, readSetup, resolveRuntime } from "@mostra/sdk";
|
|
8
8
|
import { homedir, tmpdir } from "node:os";
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
9
|
+
import { randomBytes, randomUUID } from "node:crypto";
|
|
10
|
+
import { MCP_PATH, createHttpEndpoint, createMcpServerFactory, defaultWorkspaceRoot, localWorkspace } from "@mostra/mcp";
|
|
11
|
+
import { isIP } from "node:net";
|
|
12
|
+
import { serve } from "@hono/node-server";
|
|
13
|
+
import { serveStdio } from "@modelcontextprotocol/server/stdio";
|
|
11
14
|
import { createInterface } from "node:readline";
|
|
12
|
-
//#region src/command.ts
|
|
13
|
-
/** Defines a command; the identity function, for types. */
|
|
14
|
-
function defineCommand(command) {
|
|
15
|
-
return command;
|
|
16
|
-
}
|
|
17
|
-
/** The command path as one string: `daemon install`. */
|
|
18
|
-
function commandName(command) {
|
|
19
|
-
return command.path.join(" ");
|
|
20
|
-
}
|
|
21
|
-
//#endregion
|
|
22
15
|
//#region src/docs.ts
|
|
23
16
|
/**
|
|
24
17
|
* `mostra docs` (D140 item 17): the reference that ships with the CLI, by stable slug. The
|
|
@@ -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) {
|
|
@@ -2648,53 +2460,64 @@ const devCommand = defineCommand({
|
|
|
2648
2460
|
example: "dev ./sidebar-review",
|
|
2649
2461
|
streams: true,
|
|
2650
2462
|
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
2463
|
const signals = [
|
|
2676
2464
|
"SIGINT",
|
|
2677
2465
|
"SIGTERM",
|
|
2678
2466
|
"SIGBREAK"
|
|
2679
2467
|
];
|
|
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"
|
|
2468
|
+
let interrupted = false;
|
|
2469
|
+
let stop = () => {
|
|
2470
|
+
interrupted = true;
|
|
2697
2471
|
};
|
|
2472
|
+
const onSignal = () => stop();
|
|
2473
|
+
for (const signal of signals) process.once(signal, onSignal);
|
|
2474
|
+
const release = () => {
|
|
2475
|
+
for (const signal of signals) process.off(signal, onSignal);
|
|
2476
|
+
};
|
|
2477
|
+
try {
|
|
2478
|
+
const connection = await context.connection();
|
|
2479
|
+
let sessionId;
|
|
2480
|
+
const early = [];
|
|
2481
|
+
const show = (event) => {
|
|
2482
|
+
if (event.kind === "diagnostics") for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
|
|
2483
|
+
context.emit(event, line$1(event));
|
|
2484
|
+
};
|
|
2485
|
+
connection?.onNotification(DEV_NOTIFY, (params) => {
|
|
2486
|
+
const event = params;
|
|
2487
|
+
if (sessionId === void 0) early.push(event);
|
|
2488
|
+
else if (event.sessionId === sessionId) show(event);
|
|
2489
|
+
});
|
|
2490
|
+
const portFlag = context.flags["port"];
|
|
2491
|
+
const started = await context.call(devStartMethod, {
|
|
2492
|
+
source: sourceRef(arg(context, "path"), context.cwd),
|
|
2493
|
+
...typeof portFlag === "number" ? { port: portFlag } : {}
|
|
2494
|
+
});
|
|
2495
|
+
sessionId = started.sessionId;
|
|
2496
|
+
context.emit({
|
|
2497
|
+
kind: "started",
|
|
2498
|
+
...started
|
|
2499
|
+
}, `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`);
|
|
2500
|
+
for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
|
|
2501
|
+
const ended = interrupted ? "signal" : await new Promise((done) => {
|
|
2502
|
+
stop = () => done("signal");
|
|
2503
|
+
connection?.closed.then(() => done("closed"));
|
|
2504
|
+
});
|
|
2505
|
+
release();
|
|
2506
|
+
if (ended === "closed") throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
|
|
2507
|
+
message: "The instance ended the development preview (it stopped or restarted).",
|
|
2508
|
+
hint: "Run mostra dev again."
|
|
2509
|
+
}));
|
|
2510
|
+
await context.call(devStopMethod, { sessionId }).catch(() => void 0);
|
|
2511
|
+
return {
|
|
2512
|
+
result: {
|
|
2513
|
+
sessionId,
|
|
2514
|
+
stopped: "signal"
|
|
2515
|
+
},
|
|
2516
|
+
human: "Stopped.\n"
|
|
2517
|
+
};
|
|
2518
|
+
} finally {
|
|
2519
|
+
release();
|
|
2520
|
+
}
|
|
2698
2521
|
}
|
|
2699
2522
|
});
|
|
2700
2523
|
//#endregion
|
|
@@ -2706,6 +2529,17 @@ const devCommand = defineCommand({
|
|
|
2706
2529
|
*/
|
|
2707
2530
|
/** The longest one `wait` request may ask for (INTERFACES §6: 2^31 − 1 ms). */
|
|
2708
2531
|
const MAX_WAIT_MS = 2 ** 31 - 1;
|
|
2532
|
+
/**
|
|
2533
|
+
* What `wait` prints when its condition held: the event and cursor, and for a signal its name and
|
|
2534
|
+
* the payload the page or action sent (#115), which is otherwise only in `--json`.
|
|
2535
|
+
*/
|
|
2536
|
+
function satisfiedLine(event, cursor) {
|
|
2537
|
+
const line = `${event.type} at cursor ${cursor}`;
|
|
2538
|
+
if (event.type !== "signal.raised") return `${line}\n`;
|
|
2539
|
+
const name = typeof event.payload?.["name"] === "string" ? ` ${event.payload["name"]}` : "";
|
|
2540
|
+
const payload = event.payload !== void 0 && Object.hasOwn(event.payload, "payload") ? `\npayload: ${JSON.stringify(event.payload["payload"])}` : "";
|
|
2541
|
+
return `${event.type}${name} at cursor ${cursor}${payload}\n`;
|
|
2542
|
+
}
|
|
2709
2543
|
/** `mostra wait <artifact>`. */
|
|
2710
2544
|
const waitCommand = defineCommand({
|
|
2711
2545
|
path: ["wait"],
|
|
@@ -2757,7 +2591,7 @@ const waitCommand = defineCommand({
|
|
|
2757
2591
|
});
|
|
2758
2592
|
if (result.status === "satisfied") return {
|
|
2759
2593
|
result,
|
|
2760
|
-
human:
|
|
2594
|
+
human: satisfiedLine(result.event, result.cursor)
|
|
2761
2595
|
};
|
|
2762
2596
|
if (result.status !== "still_waiting") return {
|
|
2763
2597
|
result,
|
|
@@ -3027,308 +2861,119 @@ const statePatchCommand = defineCommand({
|
|
|
3027
2861
|
}
|
|
3028
2862
|
});
|
|
3029
2863
|
//#endregion
|
|
3030
|
-
//#region src/
|
|
2864
|
+
//#region src/browser.ts
|
|
3031
2865
|
/**
|
|
3032
|
-
*
|
|
3033
|
-
*
|
|
3034
|
-
*
|
|
3035
|
-
*
|
|
3036
|
-
*
|
|
3037
|
-
*
|
|
2866
|
+
* Opening a browser on a launch URL without putting it on a command line (D140 item 15, Opus
|
|
2867
|
+
* review finding 4). A program's arguments are readable by every local user (`ps`,
|
|
2868
|
+
* `/proc/<pid>/cmdline`), so the opener gets the path of a page that redirects to the launch URL,
|
|
2869
|
+
* written mode 0600 in a fresh directory of mode 0700, as Jupyter's server does for its token.
|
|
2870
|
+
* Windows has no modes: there the page goes under the user's own profile
|
|
2871
|
+
* (`%LOCALAPPDATA%\mostra-cli\open`), whose access list only the user, `SYSTEM` and
|
|
2872
|
+
* administrators pass, never under `%TEMP%`, which may name a folder other users can read (Opus
|
|
2873
|
+
* review of WP-W2, finding 1). The launch ticket in the page is single-use and lives a minute, so a
|
|
2874
|
+
* page left behind is harmless; each launch removes the ones older than that.
|
|
3038
2875
|
*/
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3043
|
-
|
|
3044
|
-
|
|
3045
|
-
|
|
2876
|
+
/** The prefix of the directories launch pages live in. */
|
|
2877
|
+
const PREFIX = "mostra-open-";
|
|
2878
|
+
/** A launch page older than this holds a ticket that expired: it goes on the next launch. */
|
|
2879
|
+
const STALE_MS = 12e4;
|
|
2880
|
+
/** Escapes text for an HTML attribute or element. */
|
|
2881
|
+
const html = (text) => text.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
2882
|
+
/** The page that sends the browser on to `url`. */
|
|
2883
|
+
function launchPage(url) {
|
|
2884
|
+
const script = JSON.stringify(url).replaceAll("<", "\\u003c");
|
|
2885
|
+
return `<!DOCTYPE html>
|
|
2886
|
+
<html lang="en">
|
|
2887
|
+
<head>
|
|
2888
|
+
<meta charset="utf-8">
|
|
2889
|
+
<meta name="referrer" content="no-referrer">
|
|
2890
|
+
<meta http-equiv="refresh" content="0;url=${html(url)}">
|
|
2891
|
+
<title>Opening Mostra</title>
|
|
2892
|
+
<script>location.replace(${script});<\/script>
|
|
2893
|
+
</head>
|
|
2894
|
+
<body>
|
|
2895
|
+
<p>Opening the artifact. If nothing happens, <a href="${html(url)}">open it here</a>.</p>
|
|
2896
|
+
</body>
|
|
2897
|
+
</html>
|
|
2898
|
+
`;
|
|
2899
|
+
}
|
|
2900
|
+
/** Removes launch pages of earlier launches that are this user's and older than a minute or two. */
|
|
2901
|
+
function sweep(base, now) {
|
|
2902
|
+
const uid = process.getuid?.();
|
|
2903
|
+
let names;
|
|
2904
|
+
try {
|
|
2905
|
+
names = readdirSync(base);
|
|
2906
|
+
} catch {
|
|
2907
|
+
return;
|
|
2908
|
+
}
|
|
2909
|
+
for (const name of names) {
|
|
2910
|
+
if (!name.startsWith(PREFIX)) continue;
|
|
2911
|
+
const dir = join(base, name);
|
|
2912
|
+
try {
|
|
2913
|
+
const stats = lstatSync(dir);
|
|
2914
|
+
if (!stats.isDirectory() || uid !== void 0 && stats.uid !== uid) continue;
|
|
2915
|
+
if (now - stats.mtimeMs < STALE_MS) continue;
|
|
2916
|
+
rmSync(dir, {
|
|
2917
|
+
recursive: true,
|
|
2918
|
+
force: true
|
|
2919
|
+
});
|
|
2920
|
+
} catch {}
|
|
2921
|
+
}
|
|
2922
|
+
}
|
|
2923
|
+
/** Writes the launch page for `url`; its path. */
|
|
2924
|
+
function writeLaunchPage(url, base = tmpdir(), now = Date.now()) {
|
|
2925
|
+
sweep(base, now);
|
|
2926
|
+
const dir = mkdtempSync(join(base, PREFIX));
|
|
2927
|
+
const file = join(dir, "open.html");
|
|
2928
|
+
writeFileSync(file, launchPage(url), {
|
|
2929
|
+
mode: 384,
|
|
2930
|
+
flag: "wx"
|
|
2931
|
+
});
|
|
2932
|
+
return file;
|
|
2933
|
+
}
|
|
3046
2934
|
/**
|
|
3047
|
-
*
|
|
3048
|
-
*
|
|
3049
|
-
* must go through Tailscale (no private or secure DNS of its own, no split tunneling that leaves
|
|
3050
|
-
* the browser out).
|
|
2935
|
+
* Splits a command the way a shell would split plain words and quotes, without running one:
|
|
2936
|
+
* `firefox --new-window %s` or `"/Applications/My Browser" %s`.
|
|
3051
2937
|
*/
|
|
3052
|
-
function
|
|
3053
|
-
const
|
|
3054
|
-
|
|
3055
|
-
|
|
2938
|
+
function splitCommand(command) {
|
|
2939
|
+
const words = [];
|
|
2940
|
+
let word = "";
|
|
2941
|
+
let inWord = false;
|
|
2942
|
+
let quote;
|
|
2943
|
+
for (let index = 0; index < command.length; index += 1) {
|
|
2944
|
+
const char = command[index];
|
|
2945
|
+
if (quote) {
|
|
2946
|
+
if (char === quote) quote = void 0;
|
|
2947
|
+
else if (char === "\\" && quote === "\"" && index + 1 < command.length) {
|
|
2948
|
+
index += 1;
|
|
2949
|
+
word += command[index];
|
|
2950
|
+
} else word += char;
|
|
2951
|
+
continue;
|
|
2952
|
+
}
|
|
2953
|
+
if (char === "\"" || char === "'") {
|
|
2954
|
+
quote = char;
|
|
2955
|
+
inWord = true;
|
|
2956
|
+
} else if (char === "\\" && index + 1 < command.length) {
|
|
2957
|
+
index += 1;
|
|
2958
|
+
word += command[index];
|
|
2959
|
+
inWord = true;
|
|
2960
|
+
} else if (/\s/.test(char)) {
|
|
2961
|
+
if (inWord) words.push(word);
|
|
2962
|
+
word = "";
|
|
2963
|
+
inWord = false;
|
|
2964
|
+
} else {
|
|
2965
|
+
word += char;
|
|
2966
|
+
inWord = true;
|
|
2967
|
+
}
|
|
2968
|
+
}
|
|
2969
|
+
if (inWord) words.push(word);
|
|
2970
|
+
return words;
|
|
3056
2971
|
}
|
|
3057
|
-
/**
|
|
3058
|
-
function
|
|
3059
|
-
|
|
3060
|
-
return
|
|
3061
|
-
|
|
3062
|
-
/** `mostra share <artifact> --tailnet | --public`. */
|
|
3063
|
-
const shareCommand = defineCommand({
|
|
3064
|
-
path: ["share"],
|
|
3065
|
-
summary: "Open an artifact to people beyond this machine: inside your tailnet, or publicly with a link that expires.",
|
|
3066
|
-
args: [{
|
|
3067
|
-
name: "artifact",
|
|
3068
|
-
summary: "The artifact: its source path or its ID."
|
|
3069
|
-
}],
|
|
3070
|
-
flags: [
|
|
3071
|
-
{
|
|
3072
|
-
name: "tailnet",
|
|
3073
|
-
kind: "boolean",
|
|
3074
|
-
summary: "Share inside your tailnet through Tailscale Serve; each viewer is their tailnet identity."
|
|
3075
|
-
},
|
|
3076
|
-
{
|
|
3077
|
-
name: "public",
|
|
3078
|
-
kind: "boolean",
|
|
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
|
-
}
|
|
3277
|
-
}
|
|
3278
|
-
/** Writes the launch page for `url`; its path. */
|
|
3279
|
-
function writeLaunchPage(url, base = tmpdir(), now = Date.now()) {
|
|
3280
|
-
sweep(base, now);
|
|
3281
|
-
const dir = mkdtempSync(join(base, PREFIX));
|
|
3282
|
-
const file = join(dir, "open.html");
|
|
3283
|
-
writeFileSync(file, launchPage(url), {
|
|
3284
|
-
mode: 384,
|
|
3285
|
-
flag: "wx"
|
|
3286
|
-
});
|
|
3287
|
-
return file;
|
|
3288
|
-
}
|
|
3289
|
-
/**
|
|
3290
|
-
* Splits a command the way a shell would split plain words and quotes, without running one:
|
|
3291
|
-
* `firefox --new-window %s` or `"/Applications/My Browser" %s`.
|
|
3292
|
-
*/
|
|
3293
|
-
function splitCommand(command) {
|
|
3294
|
-
const words = [];
|
|
3295
|
-
let word = "";
|
|
3296
|
-
let inWord = false;
|
|
3297
|
-
let quote;
|
|
3298
|
-
for (let index = 0; index < command.length; index += 1) {
|
|
3299
|
-
const char = command[index];
|
|
3300
|
-
if (quote) {
|
|
3301
|
-
if (char === quote) quote = void 0;
|
|
3302
|
-
else if (char === "\\" && quote === "\"" && index + 1 < command.length) {
|
|
3303
|
-
index += 1;
|
|
3304
|
-
word += command[index];
|
|
3305
|
-
} else word += char;
|
|
3306
|
-
continue;
|
|
3307
|
-
}
|
|
3308
|
-
if (char === "\"" || char === "'") {
|
|
3309
|
-
quote = char;
|
|
3310
|
-
inWord = true;
|
|
3311
|
-
} else if (char === "\\" && index + 1 < command.length) {
|
|
3312
|
-
index += 1;
|
|
3313
|
-
word += command[index];
|
|
3314
|
-
inWord = true;
|
|
3315
|
-
} else if (/\s/.test(char)) {
|
|
3316
|
-
if (inWord) words.push(word);
|
|
3317
|
-
word = "";
|
|
3318
|
-
inWord = false;
|
|
3319
|
-
} else {
|
|
3320
|
-
word += char;
|
|
3321
|
-
inWord = true;
|
|
3322
|
-
}
|
|
3323
|
-
}
|
|
3324
|
-
if (inWord) words.push(word);
|
|
3325
|
-
return words;
|
|
3326
|
-
}
|
|
3327
|
-
/** The program that opens a file with its default application, by platform. */
|
|
3328
|
-
function platformOpener(platform) {
|
|
3329
|
-
if (platform === "darwin") return ["open"];
|
|
3330
|
-
if (platform === "win32") return ["explorer.exe"];
|
|
3331
|
-
return ["xdg-open"];
|
|
2972
|
+
/** The program that opens a file with its default application, by platform. */
|
|
2973
|
+
function platformOpener(platform) {
|
|
2974
|
+
if (platform === "darwin") return ["open"];
|
|
2975
|
+
if (platform === "win32") return ["explorer.exe"];
|
|
2976
|
+
return ["xdg-open"];
|
|
3332
2977
|
}
|
|
3333
2978
|
/**
|
|
3334
2979
|
* Splits a command as Windows programs read their command lines, for `$BROWSER` there: words
|
|
@@ -3417,13 +3062,798 @@ async function openInBrowser(url, env) {
|
|
|
3417
3062
|
recursive: true,
|
|
3418
3063
|
mode: 448
|
|
3419
3064
|
});
|
|
3420
|
-
page = writeLaunchPage(url, base);
|
|
3421
|
-
} catch {
|
|
3422
|
-
return false;
|
|
3065
|
+
page = writeLaunchPage(url, base);
|
|
3066
|
+
} catch {
|
|
3067
|
+
return false;
|
|
3068
|
+
}
|
|
3069
|
+
for (const command of browserCommands(page, env)) if (await start(command)) return true;
|
|
3070
|
+
return false;
|
|
3071
|
+
}
|
|
3072
|
+
//#endregion
|
|
3073
|
+
//#region src/client.ts
|
|
3074
|
+
/**
|
|
3075
|
+
* The CLI's connection to its home's instance (D45, D81, INTERFACES §9): it attaches to the
|
|
3076
|
+
* daemon recorded in `instance.json`, or starts one (`mostra-runtime daemon`, which itself
|
|
3077
|
+
* attaches when another starter won), and opens a session as `mostra-cli`. The SDK (WP-11) does
|
|
3078
|
+
* the same few steps over the same protocol.
|
|
3079
|
+
*/
|
|
3080
|
+
/** How long one attempt to reach a recorded socket waits. */
|
|
3081
|
+
const ATTACH_TIMEOUT_MS = 5e3;
|
|
3082
|
+
/** How long a daemon this command starts may take to say where it listens. */
|
|
3083
|
+
const START_TIMEOUT_MS = 3e4;
|
|
3084
|
+
/**
|
|
3085
|
+
* Opens a session with the home's instance, starting its daemon when none runs. Returns
|
|
3086
|
+
* `undefined` when `autostart` is false and no instance runs. Throws the start's diagnostic when
|
|
3087
|
+
* the daemon can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …).
|
|
3088
|
+
*/
|
|
3089
|
+
async function connect(options) {
|
|
3090
|
+
const recorded = readSocket(options.home);
|
|
3091
|
+
if (recorded !== void 0) {
|
|
3092
|
+
const session = await open(recorded, options, false).catch(() => void 0);
|
|
3093
|
+
if (session) return session;
|
|
3094
|
+
}
|
|
3095
|
+
if (options.autostart === false) return void 0;
|
|
3096
|
+
options.onStarting?.(true);
|
|
3097
|
+
let started;
|
|
3098
|
+
try {
|
|
3099
|
+
started = await startDaemon(options);
|
|
3100
|
+
} finally {
|
|
3101
|
+
options.onStarting?.(false);
|
|
3102
|
+
}
|
|
3103
|
+
return open(started.socket, options, started.status === "started");
|
|
3104
|
+
}
|
|
3105
|
+
/**
|
|
3106
|
+
* Opens the endpoint `instance.json` or a starting daemon named: a Unix socket, or on Windows the
|
|
3107
|
+
* owner-only pipe through the runtime's helper, which refuses a pipe another user created under
|
|
3108
|
+
* the name (D150, the SDK's `connectControl`). Only Windows needs the runtime resolved first.
|
|
3109
|
+
*/
|
|
3110
|
+
async function openEndpoint(endpoint, options) {
|
|
3111
|
+
const runtime = process.platform === "win32" ? (await locateRuntime(options.env)).runtime : void 0;
|
|
3112
|
+
return connectControl(endpoint, {
|
|
3113
|
+
runtime,
|
|
3114
|
+
env: options.env,
|
|
3115
|
+
timeoutMs: ATTACH_TIMEOUT_MS
|
|
3116
|
+
});
|
|
3117
|
+
}
|
|
3118
|
+
/** The socket `instance.json` records (D81), if the file exists and reads. */
|
|
3119
|
+
function readSocket(home) {
|
|
3120
|
+
try {
|
|
3121
|
+
const record = JSON.parse(readFileSync(join(home, "instance.json"), "utf8"));
|
|
3122
|
+
return typeof record.socket === "string" ? record.socket : void 0;
|
|
3123
|
+
} catch {
|
|
3124
|
+
return;
|
|
3125
|
+
}
|
|
3126
|
+
}
|
|
3127
|
+
/**
|
|
3128
|
+
* Starts the home's daemon, detached from this process, and reads the one line it prints: where
|
|
3129
|
+
* it listens, or why it couldn't start. A daemon another starter won prints `attached` and exits.
|
|
3130
|
+
*/
|
|
3131
|
+
async function startDaemon(options) {
|
|
3132
|
+
const deadlineAt = Date.now() + START_TIMEOUT_MS;
|
|
3133
|
+
const timedOut = () => new RpcError(createDiagnostic("MOSTRA_HOST_TIMEOUT", { message: `The home's daemon didn't start within ${formatDuration(START_TIMEOUT_MS)}.` }));
|
|
3134
|
+
const runtime = await locateRuntime(options.env);
|
|
3135
|
+
if (Date.now() >= deadlineAt) throw timedOut();
|
|
3136
|
+
const args = [
|
|
3137
|
+
resolve(runtime.entry),
|
|
3138
|
+
"daemon",
|
|
3139
|
+
"--home",
|
|
3140
|
+
options.home
|
|
3141
|
+
];
|
|
3142
|
+
return new Promise((resolve, reject) => {
|
|
3143
|
+
const child = spawn(runtime.node, args, {
|
|
3144
|
+
detached: true,
|
|
3145
|
+
cwd: detachedDirectory(options.home),
|
|
3146
|
+
windowsHide: true,
|
|
3147
|
+
stdio: [
|
|
3148
|
+
"ignore",
|
|
3149
|
+
"pipe",
|
|
3150
|
+
"ignore"
|
|
3151
|
+
],
|
|
3152
|
+
env: detachedEnvironment({
|
|
3153
|
+
...process.env,
|
|
3154
|
+
...options.env
|
|
3155
|
+
})
|
|
3156
|
+
});
|
|
3157
|
+
const splitter = new LineSplitter();
|
|
3158
|
+
let settled = false;
|
|
3159
|
+
const finish = (outcome) => {
|
|
3160
|
+
if (settled) return;
|
|
3161
|
+
settled = true;
|
|
3162
|
+
clearTimeout(timer);
|
|
3163
|
+
child.stdout?.removeAllListeners("data");
|
|
3164
|
+
child.stdout?.destroy();
|
|
3165
|
+
child.unref();
|
|
3166
|
+
outcome();
|
|
3167
|
+
};
|
|
3168
|
+
const timer = setTimeout(() => finish(() => reject(timedOut())), Math.max(0, deadlineAt - Date.now()));
|
|
3169
|
+
child.on("error", (error) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_MISSING", { message: `The runtime couldn't be started: ${error.message}` })))));
|
|
3170
|
+
child.on("close", (code) => finish(() => reject(new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: `The home's daemon exited (${code ?? "signal"}) before it said where it listens.` })))));
|
|
3171
|
+
child.stdout?.setEncoding("utf8");
|
|
3172
|
+
child.stdout?.on("data", (chunk) => {
|
|
3173
|
+
for (const line of splitter.push(chunk)) {
|
|
3174
|
+
let parsed;
|
|
3175
|
+
try {
|
|
3176
|
+
parsed = JSON.parse(line);
|
|
3177
|
+
} catch {
|
|
3178
|
+
continue;
|
|
3179
|
+
}
|
|
3180
|
+
finish(() => {
|
|
3181
|
+
if (parsed.status === "failed") reject(new RpcError(parsed.diagnostic ?? createDiagnostic("MOSTRA_HOST_INTERNAL_ERROR", { message: "The home's daemon failed to start." })));
|
|
3182
|
+
else resolve(parsed);
|
|
3183
|
+
});
|
|
3184
|
+
return;
|
|
3185
|
+
}
|
|
3186
|
+
});
|
|
3187
|
+
});
|
|
3188
|
+
}
|
|
3189
|
+
async function open(socketPath, options, started) {
|
|
3190
|
+
const socket = await openEndpoint(socketPath, options);
|
|
3191
|
+
const handlers = /* @__PURE__ */ new Map();
|
|
3192
|
+
const peer = new RpcPeer({
|
|
3193
|
+
send: (message) => {
|
|
3194
|
+
if (!socket.destroyed) socket.write(encodeLine(message));
|
|
3195
|
+
},
|
|
3196
|
+
onNotification: (method, params) => handlers.get(method)?.(params)
|
|
3197
|
+
});
|
|
3198
|
+
let markClosed = () => {};
|
|
3199
|
+
const closedPromise = new Promise((done) => {
|
|
3200
|
+
markClosed = done;
|
|
3201
|
+
});
|
|
3202
|
+
const splitter = new LineSplitter();
|
|
3203
|
+
socket.setEncoding("utf8");
|
|
3204
|
+
socket.on("data", (chunk) => {
|
|
3205
|
+
for (const line of splitter.push(chunk)) peer.receiveLine(line);
|
|
3206
|
+
});
|
|
3207
|
+
const end = () => {
|
|
3208
|
+
peer.close();
|
|
3209
|
+
markClosed();
|
|
3210
|
+
};
|
|
3211
|
+
socket.on("close", end);
|
|
3212
|
+
socket.on("error", () => socket.destroy());
|
|
3213
|
+
let result;
|
|
3214
|
+
try {
|
|
3215
|
+
result = await peer.call(mostraInitializeMethod, {
|
|
3216
|
+
client: {
|
|
3217
|
+
name: CLI_CLIENT_NAME,
|
|
3218
|
+
version: cliVersion()
|
|
3219
|
+
},
|
|
3220
|
+
revisions: [...HOST_PROTOCOL_REVISIONS],
|
|
3221
|
+
capabilities: { notifications: [ARTIFACT_PROGRESS, DEV_NOTIFY] },
|
|
3222
|
+
ports: [],
|
|
3223
|
+
home: { path: options.home }
|
|
3224
|
+
}, { timeoutMs: ATTACH_TIMEOUT_MS });
|
|
3225
|
+
} catch (error) {
|
|
3226
|
+
socket.destroy();
|
|
3227
|
+
throw error;
|
|
3228
|
+
}
|
|
3229
|
+
return {
|
|
3230
|
+
summary: {
|
|
3231
|
+
home: result.instance.home,
|
|
3232
|
+
socket: socketPath,
|
|
3233
|
+
pid: result.instance.pid,
|
|
3234
|
+
mode: result.instance.mode,
|
|
3235
|
+
version: result.instance.version,
|
|
3236
|
+
started
|
|
3237
|
+
},
|
|
3238
|
+
warnings: result.warnings,
|
|
3239
|
+
call: (method, params, timeoutMs) => peer.call(method, params, timeoutMs !== void 0 ? { timeoutMs } : {}),
|
|
3240
|
+
onNotification: (method, handler) => {
|
|
3241
|
+
handlers.set(method, handler);
|
|
3242
|
+
},
|
|
3243
|
+
closed: closedPromise,
|
|
3244
|
+
close: () => {
|
|
3245
|
+
peer.close();
|
|
3246
|
+
socket.end();
|
|
3247
|
+
socket.destroy();
|
|
3248
|
+
}
|
|
3249
|
+
};
|
|
3250
|
+
}
|
|
3251
|
+
/** A limit as people write it: `250 ms`, `5 s`, `1.5 s`. */
|
|
3252
|
+
function formatDuration(ms) {
|
|
3253
|
+
if (ms < 1e3) return `${ms} ms`;
|
|
3254
|
+
const seconds = ms / 1e3;
|
|
3255
|
+
return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)} s`;
|
|
3256
|
+
}
|
|
3257
|
+
/** The runtime install of {@link RuntimeInstall}, reporting its progress through `log`. */
|
|
3258
|
+
function runtimeInstall(options) {
|
|
3259
|
+
const testWait = Number(options.env["MOSTRA_TEST_RUNTIME_WAIT_MS"]);
|
|
3260
|
+
const waitMs = options.waitMs ?? (Number.isFinite(testWait) && testWait > 0 ? testWait : 45e3);
|
|
3261
|
+
const report = progressReporter({
|
|
3262
|
+
stderr: (text) => {
|
|
3263
|
+
for (const line of text.split("\n")) if (line.trim() !== "") options.log(line.trim());
|
|
3264
|
+
},
|
|
3265
|
+
stderrTty: false
|
|
3266
|
+
});
|
|
3267
|
+
let ready = false;
|
|
3268
|
+
let pending;
|
|
3269
|
+
let done;
|
|
3270
|
+
const start = () => {
|
|
3271
|
+
if (pending !== void 0) return pending;
|
|
3272
|
+
const installing = resolveRuntime({
|
|
3273
|
+
env: options.env,
|
|
3274
|
+
onProgress: (progress) => {
|
|
3275
|
+
if (progress.step === "download") done = `${Math.floor(progress.received / progress.total * 100)}% downloaded`;
|
|
3276
|
+
else if (progress.step === "files") done = "downloaded, checking its files";
|
|
3277
|
+
else if (progress.step === "browser") done = "fetching the browser verify uses";
|
|
3278
|
+
report(progress);
|
|
3279
|
+
}
|
|
3280
|
+
}).then(() => {
|
|
3281
|
+
ready = true;
|
|
3282
|
+
});
|
|
3283
|
+
pending = installing;
|
|
3284
|
+
installing.catch((error) => {
|
|
3285
|
+
if (pending === installing) pending = void 0;
|
|
3286
|
+
done = void 0;
|
|
3287
|
+
const diagnostic = error instanceof RpcError ? error.diagnostic : void 0;
|
|
3288
|
+
options.log(`mostra mcp: the runtime's install failed: ${diagnostic?.code ?? ""} ${diagnostic?.message ?? String(error)}`.trim());
|
|
3289
|
+
});
|
|
3290
|
+
return installing;
|
|
3291
|
+
};
|
|
3292
|
+
return {
|
|
3293
|
+
start() {
|
|
3294
|
+
start().catch(() => {});
|
|
3295
|
+
},
|
|
3296
|
+
async wait() {
|
|
3297
|
+
if (ready) return;
|
|
3298
|
+
const installing = start();
|
|
3299
|
+
let timer;
|
|
3300
|
+
const late = new Promise((_, reject) => {
|
|
3301
|
+
timer = setTimeout(() => reject(new RpcError(createDiagnostic("MOSTRA_ENV_RUNTIME_INSTALLING", { message: `Mostra is installing its runtime for this release (${done ?? "starting the download"}); the install goes on.` }))), waitMs);
|
|
3302
|
+
timer.unref();
|
|
3303
|
+
});
|
|
3304
|
+
try {
|
|
3305
|
+
await Promise.race([installing, late]);
|
|
3306
|
+
} finally {
|
|
3307
|
+
clearTimeout(timer);
|
|
3308
|
+
}
|
|
3309
|
+
}
|
|
3310
|
+
};
|
|
3311
|
+
}
|
|
3312
|
+
/** The home's daemon as the MCP server's instance (D164 item 5). */
|
|
3313
|
+
function daemonInstance(options) {
|
|
3314
|
+
const idleMs = options.idleMs ?? 3e5;
|
|
3315
|
+
const runtime = options.runtime;
|
|
3316
|
+
const opener = options.connect ?? connect;
|
|
3317
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
3318
|
+
let session;
|
|
3319
|
+
let host = false;
|
|
3320
|
+
let inflight = 0;
|
|
3321
|
+
let idle;
|
|
3322
|
+
const open = () => {
|
|
3323
|
+
if (session !== void 0) return session;
|
|
3324
|
+
const opening = opener({
|
|
3325
|
+
home: options.home,
|
|
3326
|
+
env: options.env
|
|
3327
|
+
}).then((connection) => {
|
|
3328
|
+
if (connection === void 0) throw new RpcError(createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", { message: "No instance runs for this home." }));
|
|
3329
|
+
host = connection.summary.mode === "host";
|
|
3330
|
+
for (const warning of connection.warnings) options.log(`mostra mcp: ${warning.code}: ${warning.message}`);
|
|
3331
|
+
connection.onNotification(ARTIFACT_PROGRESS, (params) => {
|
|
3332
|
+
const progress = params;
|
|
3333
|
+
listeners.get(progress.progressToken)?.(progress);
|
|
3334
|
+
});
|
|
3335
|
+
connection.closed.then(() => {
|
|
3336
|
+
if (session === opening) session = void 0;
|
|
3337
|
+
});
|
|
3338
|
+
return connection;
|
|
3339
|
+
});
|
|
3340
|
+
session = opening;
|
|
3341
|
+
opening.catch(() => {
|
|
3342
|
+
if (session === opening) session = void 0;
|
|
3343
|
+
});
|
|
3344
|
+
return opening;
|
|
3345
|
+
};
|
|
3346
|
+
const release = () => {
|
|
3347
|
+
const current = session;
|
|
3348
|
+
session = void 0;
|
|
3349
|
+
current?.then((connection) => connection.close()).catch(() => {});
|
|
3350
|
+
};
|
|
3351
|
+
const settle = () => {
|
|
3352
|
+
inflight -= 1;
|
|
3353
|
+
if (inflight > 0) return;
|
|
3354
|
+
clearTimeout(idle);
|
|
3355
|
+
idle = setTimeout(release, idleMs);
|
|
3356
|
+
idle.unref();
|
|
3357
|
+
};
|
|
3358
|
+
return {
|
|
3359
|
+
async call(method, params) {
|
|
3360
|
+
inflight += 1;
|
|
3361
|
+
clearTimeout(idle);
|
|
3362
|
+
try {
|
|
3363
|
+
await runtime?.wait();
|
|
3364
|
+
const used = open();
|
|
3365
|
+
try {
|
|
3366
|
+
return await (await used).call(method, params);
|
|
3367
|
+
} catch (error) {
|
|
3368
|
+
if (!(error instanceof RpcError && error.diagnostic.code === "MOSTRA_HOST_CONNECTION_CLOSED") || method.mutating) throw error;
|
|
3369
|
+
if (session === used) session = void 0;
|
|
3370
|
+
return await (await open()).call(method, params);
|
|
3371
|
+
}
|
|
3372
|
+
} finally {
|
|
3373
|
+
settle();
|
|
3374
|
+
}
|
|
3375
|
+
},
|
|
3376
|
+
onProgress(token, listener) {
|
|
3377
|
+
listeners.set(token, listener);
|
|
3378
|
+
return () => listeners.delete(token);
|
|
3379
|
+
},
|
|
3380
|
+
hostInstance: () => host,
|
|
3381
|
+
close() {
|
|
3382
|
+
clearTimeout(idle);
|
|
3383
|
+
release();
|
|
3384
|
+
}
|
|
3385
|
+
};
|
|
3386
|
+
}
|
|
3387
|
+
/** The bundled reference (`mostra docs`), read as the MCP server's docs. */
|
|
3388
|
+
function bundledDocs() {
|
|
3389
|
+
let topics;
|
|
3390
|
+
const all = () => {
|
|
3391
|
+
topics ??= docsIndex();
|
|
3392
|
+
return topics;
|
|
3393
|
+
};
|
|
3394
|
+
const cache = /* @__PURE__ */ new Map();
|
|
3395
|
+
return {
|
|
3396
|
+
topics: () => all().map((topic) => ({
|
|
3397
|
+
topic: topic.topic,
|
|
3398
|
+
title: topic.title,
|
|
3399
|
+
url: topic.url
|
|
3400
|
+
})),
|
|
3401
|
+
read(topic) {
|
|
3402
|
+
const cached = cache.get(topic);
|
|
3403
|
+
if (cached !== void 0) return cached;
|
|
3404
|
+
const found = all().find((entry) => entry.topic === topic);
|
|
3405
|
+
if (found === void 0) return void 0;
|
|
3406
|
+
const markdown = topicMarkdown(found, skillDir(), MCP_GUIDE_LINKS);
|
|
3407
|
+
cache.set(topic, markdown);
|
|
3408
|
+
return markdown;
|
|
3409
|
+
}
|
|
3410
|
+
};
|
|
3411
|
+
}
|
|
3412
|
+
/** The daemon instance, with the runtime's install started at once (D164 item 7). */
|
|
3413
|
+
function startInstance(options) {
|
|
3414
|
+
const runtime = runtimeInstall({
|
|
3415
|
+
env: options.env,
|
|
3416
|
+
log: options.log
|
|
3417
|
+
});
|
|
3418
|
+
runtime.start();
|
|
3419
|
+
return daemonInstance({
|
|
3420
|
+
...options,
|
|
3421
|
+
runtime
|
|
3422
|
+
});
|
|
3423
|
+
}
|
|
3424
|
+
function factoryFor(options, instance) {
|
|
3425
|
+
return createMcpServerFactory({
|
|
3426
|
+
instance,
|
|
3427
|
+
workspace: localWorkspace(options.workspace),
|
|
3428
|
+
docs: bundledDocs(),
|
|
3429
|
+
browser: { open: (url) => openInBrowser(url, options.env) },
|
|
3430
|
+
version: options.version,
|
|
3431
|
+
onClient: (client) => options.onClient(client, instance)
|
|
3432
|
+
});
|
|
3433
|
+
}
|
|
3434
|
+
/** Resolves when the process is asked to stop: Ctrl-C, SIGTERM, SIGHUP, or Ctrl+Break on Windows. */
|
|
3435
|
+
function stopSignal() {
|
|
3436
|
+
return new Promise((resolve) => {
|
|
3437
|
+
for (const signal of [
|
|
3438
|
+
"SIGINT",
|
|
3439
|
+
"SIGTERM",
|
|
3440
|
+
"SIGHUP",
|
|
3441
|
+
"SIGBREAK"
|
|
3442
|
+
]) process.once(signal, () => resolve(signal));
|
|
3443
|
+
});
|
|
3444
|
+
}
|
|
3445
|
+
/** Serves over stdio until the client closes stdin or the process is stopped. */
|
|
3446
|
+
async function serveOverStdio(options) {
|
|
3447
|
+
const instance = startInstance(options);
|
|
3448
|
+
const handle = serveStdio(factoryFor(options, instance), { onerror: (error) => options.log(`mostra mcp: ${error.message}`) });
|
|
3449
|
+
const ended = new Promise((resolve) => {
|
|
3450
|
+
process.stdin.once("end", () => resolve("stdin"));
|
|
3451
|
+
process.stdin.once("close", () => resolve("stdin"));
|
|
3452
|
+
});
|
|
3453
|
+
await Promise.race([ended, stopSignal()]);
|
|
3454
|
+
await handle.close().catch(() => {});
|
|
3455
|
+
instance.close();
|
|
3456
|
+
return instance;
|
|
3457
|
+
}
|
|
3458
|
+
/** The address and URL host of `--bind` and `--url-host` (D99's rules, D164 item 3). */
|
|
3459
|
+
function mcpBind(options) {
|
|
3460
|
+
const fail = (message) => new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message }));
|
|
3461
|
+
const address = (options.bind ?? "127.0.0.1").replace(/^\[(.*)\]$/, "$1");
|
|
3462
|
+
if (isIP(address) === 0) throw fail(`--bind takes an IP address, such as 127.0.0.1, not "${options.bind}".`);
|
|
3463
|
+
if (options.urlHost !== void 0 && options.bind === void 0) throw fail("--url-host needs --bind: without it the server listens on 127.0.0.1 only.");
|
|
3464
|
+
const canonical = new URL(`http://${isIP(address) === 6 ? `[${address}]` : address}/`).hostname;
|
|
3465
|
+
if ((canonical === "0.0.0.0" || canonical === "[::]" || canonical === "[::ffff:0:0]") && options.urlHost === void 0) throw fail(`--bind ${options.bind} listens on every interface; name the host clients use with --url-host.`);
|
|
3466
|
+
if (options.urlHost !== void 0 && !/^(\[[0-9a-f:.]+\]|[a-z0-9.-]+)$/i.test(options.urlHost)) throw fail(`--url-host takes a host name or an IP address, not "${options.urlHost}".`);
|
|
3467
|
+
return {
|
|
3468
|
+
address,
|
|
3469
|
+
urlHost: (options.urlHost ?? canonical).toLowerCase()
|
|
3470
|
+
};
|
|
3471
|
+
}
|
|
3472
|
+
/** The fewest distinct characters a chosen token must have, so `aaaa…` isn't accepted. */
|
|
3473
|
+
const TOKEN_VARIETY = 8;
|
|
3474
|
+
/** The bearer token: `MOSTRA_MCP_TOKEN`, or one made for this run (160 bits). */
|
|
3475
|
+
function mcpToken(env) {
|
|
3476
|
+
const given = env["MOSTRA_MCP_TOKEN"];
|
|
3477
|
+
if (given !== void 0 && given !== "") {
|
|
3478
|
+
if (given.length < 26 || /\s/.test(given) || new Set(given).size < TOKEN_VARIETY) throw new RpcError(createDiagnostic("MOSTRA_CLI_USAGE", { message: `MOSTRA_MCP_TOKEN must be at least 26 characters, with no spaces and at least ${TOKEN_VARIETY} different characters: a random one, such as from \`openssl rand -hex 20\`.` }));
|
|
3479
|
+
return {
|
|
3480
|
+
token: given,
|
|
3481
|
+
generated: false
|
|
3482
|
+
};
|
|
3483
|
+
}
|
|
3484
|
+
return {
|
|
3485
|
+
token: randomBytes(20).toString("base64url"),
|
|
3486
|
+
generated: true
|
|
3487
|
+
};
|
|
3488
|
+
}
|
|
3489
|
+
/** A request's headers as `[name, value]` pairs in arrival order (Node's `rawHeaders`). */
|
|
3490
|
+
function pairs(incoming) {
|
|
3491
|
+
const raw = incoming.rawHeaders;
|
|
3492
|
+
const out = [];
|
|
3493
|
+
for (let index = 0; index + 1 < raw.length; index += 2) out.push([raw[index], raw[index + 1]]);
|
|
3494
|
+
return out;
|
|
3495
|
+
}
|
|
3496
|
+
/** Serves Streamable HTTP until the process is stopped; tells `onListening` where. */
|
|
3497
|
+
async function serveOverHttp(options) {
|
|
3498
|
+
const { address, urlHost } = mcpBind({
|
|
3499
|
+
...options.bind !== void 0 ? { bind: options.bind } : {},
|
|
3500
|
+
...options.urlHost !== void 0 ? { urlHost: options.urlHost } : {}
|
|
3501
|
+
});
|
|
3502
|
+
const { token, generated } = mcpToken(options.env);
|
|
3503
|
+
const instance = startInstance(options);
|
|
3504
|
+
const factory = factoryFor(options, instance);
|
|
3505
|
+
let endpoint;
|
|
3506
|
+
const server = serve({
|
|
3507
|
+
fetch: (request, env) => {
|
|
3508
|
+
if (endpoint === void 0) return new Response(null, { status: 503 });
|
|
3509
|
+
return endpoint.fetch(request, {
|
|
3510
|
+
target: env.incoming.url ?? "/",
|
|
3511
|
+
headers: pairs(env.incoming)
|
|
3512
|
+
});
|
|
3513
|
+
},
|
|
3514
|
+
port: options.port,
|
|
3515
|
+
hostname: address
|
|
3516
|
+
});
|
|
3517
|
+
const port = await new Promise((resolve, reject) => {
|
|
3518
|
+
server.once("error", (error) => reject(new RpcError(createDiagnostic("MOSTRA_ENV_BIND_FAILED", { message: `The MCP server couldn't listen on ${address}:${options.port} (${error.code ?? error.message}).` }))));
|
|
3519
|
+
server.once("listening", () => {
|
|
3520
|
+
const bound = server.address();
|
|
3521
|
+
resolve(typeof bound === "object" && bound !== null ? bound.port : options.port);
|
|
3522
|
+
});
|
|
3523
|
+
});
|
|
3524
|
+
if ("keepAliveTimeout" in server) {
|
|
3525
|
+
server.keepAliveTimeout = 305e3;
|
|
3526
|
+
server.headersTimeout = 306e3;
|
|
3527
|
+
}
|
|
3528
|
+
const origin = `http://${urlHost}:${port}`;
|
|
3529
|
+
endpoint = createHttpEndpoint(factory, {
|
|
3530
|
+
origin,
|
|
3531
|
+
hosts: [`${urlHost}:${port}`],
|
|
3532
|
+
token,
|
|
3533
|
+
onRefusal: (refused) => options.log(`mostra mcp: refused a request (${refused.status} ${refused.code})`),
|
|
3534
|
+
onError: (error) => options.log(`mostra mcp: ${error.message}`)
|
|
3535
|
+
});
|
|
3536
|
+
options.onListening({
|
|
3537
|
+
url: `${origin}${MCP_PATH}`,
|
|
3538
|
+
port,
|
|
3539
|
+
token,
|
|
3540
|
+
generated
|
|
3541
|
+
});
|
|
3542
|
+
await stopSignal();
|
|
3543
|
+
await endpoint.close().catch(() => {});
|
|
3544
|
+
await new Promise((resolve) => {
|
|
3545
|
+
server.close(() => resolve());
|
|
3546
|
+
server.closeAllConnections?.();
|
|
3547
|
+
});
|
|
3548
|
+
instance.close();
|
|
3549
|
+
return instance;
|
|
3550
|
+
}
|
|
3551
|
+
//#endregion
|
|
3552
|
+
//#region src/commands/mcp.ts
|
|
3553
|
+
/**
|
|
3554
|
+
* `mostra mcp` (INTERFACES §12, D164): Mostra's MCP server, for any MCP client. Over stdio by
|
|
3555
|
+
* default (a client starts it), or Streamable HTTP with `--http`. Its tools are `@mostra/mcp`'s;
|
|
3556
|
+
* this command gives them the home's daemon, the workspace and the reference, and counts each
|
|
3557
|
+
* MCP client in telemetry unless `--embedded` says a host or harness plugin started it (D148).
|
|
3558
|
+
*/
|
|
3559
|
+
/** `mostra mcp`. */
|
|
3560
|
+
const mcpCommand = defineCommand({
|
|
3561
|
+
path: ["mcp"],
|
|
3562
|
+
summary: "Run Mostra's MCP server, so an MCP client can create, verify and publish artifacts, wait for answers and read results.",
|
|
3563
|
+
flags: [
|
|
3564
|
+
{
|
|
3565
|
+
name: "http",
|
|
3566
|
+
kind: "boolean",
|
|
3567
|
+
summary: "Serve Streamable HTTP at /mcp instead of stdio; every request needs Authorization: Bearer <token>."
|
|
3568
|
+
},
|
|
3569
|
+
{
|
|
3570
|
+
name: "port",
|
|
3571
|
+
kind: "number",
|
|
3572
|
+
value: "<port>",
|
|
3573
|
+
summary: "With --http, the port; default one the system picks."
|
|
3574
|
+
},
|
|
3575
|
+
{
|
|
3576
|
+
name: "bind",
|
|
3577
|
+
kind: "string",
|
|
3578
|
+
value: "<address>",
|
|
3579
|
+
summary: "With --http, listen on this address instead of 127.0.0.1."
|
|
3580
|
+
},
|
|
3581
|
+
{
|
|
3582
|
+
name: "url-host",
|
|
3583
|
+
kind: "string",
|
|
3584
|
+
value: "<name>",
|
|
3585
|
+
summary: "With --http, the host name clients use; a wildcard --bind needs it."
|
|
3586
|
+
},
|
|
3587
|
+
{
|
|
3588
|
+
name: "workspace",
|
|
3589
|
+
kind: "string",
|
|
3590
|
+
value: "<dir>",
|
|
3591
|
+
summary: "Where relative artifact directories and new artifacts go. Default: MOSTRA_MCP_WORKSPACE, else ~/mostra-artifacts."
|
|
3592
|
+
},
|
|
3593
|
+
{
|
|
3594
|
+
name: "embedded",
|
|
3595
|
+
kind: "boolean",
|
|
3596
|
+
summary: "This server runs on someone's behalf (a harness plugin or another host started it), so it sends no telemetry."
|
|
3597
|
+
}
|
|
3598
|
+
],
|
|
3599
|
+
output: {
|
|
3600
|
+
type: "the MCP protocol on stdin and stdout, or over HTTP",
|
|
3601
|
+
topic: "cli"
|
|
3602
|
+
},
|
|
3603
|
+
exits: [],
|
|
3604
|
+
example: "mcp",
|
|
3605
|
+
readsStdin: (flags) => flags["http"] !== true,
|
|
3606
|
+
quiet: (flags) => flags["embedded"] === true,
|
|
3607
|
+
async run(context) {
|
|
3608
|
+
const http = context.flags["http"] === true;
|
|
3609
|
+
const port = context.flags["port"];
|
|
3610
|
+
const bind = flag(context, "bind");
|
|
3611
|
+
const urlHost = flag(context, "url-host");
|
|
3612
|
+
if (!http && (port !== void 0 || bind !== void 0 || urlHost !== void 0)) throw usage("--port, --bind and --url-host go with --http.");
|
|
3613
|
+
if (typeof port === "number" && (!Number.isInteger(port) || port < 0 || port > 65535)) throw usage("--port takes a port number from 0 to 65535.");
|
|
3614
|
+
const given = flag(context, "workspace") ?? context.env["MOSTRA_MCP_WORKSPACE"];
|
|
3615
|
+
const workspace = given !== void 0 && given !== "" ? resolve(context.cwd, given) : defaultWorkspaceRoot();
|
|
3616
|
+
const counted = /* @__PURE__ */ new Set();
|
|
3617
|
+
let reached;
|
|
3618
|
+
const options = {
|
|
3619
|
+
home: context.home,
|
|
3620
|
+
env: context.env,
|
|
3621
|
+
workspace,
|
|
3622
|
+
version: cliVersion(),
|
|
3623
|
+
log: context.log,
|
|
3624
|
+
onClient(client, instance) {
|
|
3625
|
+
reached = instance;
|
|
3626
|
+
const fields = mcpSessionFields(client);
|
|
3627
|
+
const key = `${fields.client}@${fields.clientVersion ?? ""}`;
|
|
3628
|
+
if (counted.has(key)) return;
|
|
3629
|
+
counted.add(key);
|
|
3630
|
+
context.record({
|
|
3631
|
+
event: "mcp.session",
|
|
3632
|
+
fields
|
|
3633
|
+
});
|
|
3634
|
+
context.checkpoint(instance.hostInstance() || embeddedHome(readHomeMarks(context.home)));
|
|
3635
|
+
}
|
|
3636
|
+
};
|
|
3637
|
+
const done = {
|
|
3638
|
+
result: void 0,
|
|
3639
|
+
raw: true
|
|
3640
|
+
};
|
|
3641
|
+
if (!http) {
|
|
3642
|
+
await serveOverStdio(options);
|
|
3643
|
+
return {
|
|
3644
|
+
...done,
|
|
3645
|
+
hostInstance: reached?.hostInstance() === true
|
|
3646
|
+
};
|
|
3647
|
+
}
|
|
3648
|
+
await serveOverHttp({
|
|
3649
|
+
...options,
|
|
3650
|
+
port: typeof port === "number" ? port : 0,
|
|
3651
|
+
...bind !== void 0 ? { bind } : {},
|
|
3652
|
+
...urlHost !== void 0 ? { urlHost } : {},
|
|
3653
|
+
onListening({ url, token, generated }) {
|
|
3654
|
+
if (context.json) context.emit({
|
|
3655
|
+
kind: "listening",
|
|
3656
|
+
url
|
|
3657
|
+
});
|
|
3658
|
+
else context.stderr(`Mostra's MCP server is listening at ${url}\n`);
|
|
3659
|
+
context.stderr(generated ? `Send Authorization: Bearer ${token} with every request (set MOSTRA_MCP_TOKEN to choose the token).\n` : "Send Authorization: Bearer <MOSTRA_MCP_TOKEN> with every request.\n");
|
|
3660
|
+
}
|
|
3661
|
+
});
|
|
3662
|
+
return {
|
|
3663
|
+
...done,
|
|
3664
|
+
hostInstance: reached?.hostInstance() === true
|
|
3665
|
+
};
|
|
3666
|
+
}
|
|
3667
|
+
});
|
|
3668
|
+
//#endregion
|
|
3669
|
+
//#region src/commands/sharing.ts
|
|
3670
|
+
/**
|
|
3671
|
+
* `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
|
|
3672
|
+
* runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
|
|
3673
|
+
* identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
|
|
3674
|
+
* funnel`), whose link expires (1 hour by default, 7 days at most). The share lives in the
|
|
3675
|
+
* daemon, so the command returns at once with the link; `share stop` ends it and `share list`
|
|
3676
|
+
* shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
|
|
3677
|
+
*/
|
|
3678
|
+
const SHARE_ID = /^shr_[0-9A-HJKMNP-TV-Z]{26}$/;
|
|
3679
|
+
/** How each tunnel is named in human output. */
|
|
3680
|
+
const THROUGH = {
|
|
3681
|
+
tailnet: "Tailscale Serve, inside your tailnet",
|
|
3682
|
+
funnel: "Tailscale Funnel, public",
|
|
3683
|
+
cloudflare: "a Cloudflare quick tunnel, public"
|
|
3684
|
+
};
|
|
3685
|
+
/**
|
|
3686
|
+
* What a tailnet viewer's device needs, found on a real tailnet in WP-13: the tailnet's access
|
|
3687
|
+
* policy must let them reach the share's two ports of this device, and their browser's traffic
|
|
3688
|
+
* must go through Tailscale (no private or secure DNS of its own, no split tunneling that leaves
|
|
3689
|
+
* the browser out).
|
|
3690
|
+
*/
|
|
3691
|
+
function tailnetReach(share) {
|
|
3692
|
+
const port = (origin) => origin === void 0 ? void 0 : new URL(origin).port || "443";
|
|
3693
|
+
const ports = [port(share.url), port(share.artifactOrigin)].filter((value) => value !== void 0);
|
|
3694
|
+
return `Viewers need this device's port${ports.length === 1 ? "" : "s"} ${ports.join(" and ")} allowed by the tailnet's access policy, and their browser's traffic sent through Tailscale.\n`;
|
|
3695
|
+
}
|
|
3696
|
+
/** One share as a line of human output. */
|
|
3697
|
+
function line(share) {
|
|
3698
|
+
const until = share.state === "stopped" ? `stopped${share.stopReason ? ` (${share.stopReason})` : ""}` : share.expiresAt ? `until ${share.expiresAt}` : "no expiry";
|
|
3699
|
+
return `${share.shareId} ${share.via} ${share.hostname} ${until}`;
|
|
3700
|
+
}
|
|
3701
|
+
/** `mostra share <artifact> --tailnet | --public`. */
|
|
3702
|
+
const shareCommand = defineCommand({
|
|
3703
|
+
path: ["share"],
|
|
3704
|
+
summary: "Open an artifact to people beyond this machine: inside your tailnet, or publicly with a link that expires.",
|
|
3705
|
+
args: [{
|
|
3706
|
+
name: "artifact",
|
|
3707
|
+
summary: "The artifact: its source path or its ID."
|
|
3708
|
+
}],
|
|
3709
|
+
flags: [
|
|
3710
|
+
{
|
|
3711
|
+
name: "tailnet",
|
|
3712
|
+
kind: "boolean",
|
|
3713
|
+
summary: "Share inside your tailnet through Tailscale Serve; each viewer is their tailnet identity."
|
|
3714
|
+
},
|
|
3715
|
+
{
|
|
3716
|
+
name: "public",
|
|
3717
|
+
kind: "boolean",
|
|
3718
|
+
summary: "Share publicly: anyone with the link can open it until it expires."
|
|
3719
|
+
},
|
|
3720
|
+
{
|
|
3721
|
+
name: "via",
|
|
3722
|
+
kind: "string",
|
|
3723
|
+
value: "<tunnel>",
|
|
3724
|
+
choices: ["cloudflare", "funnel"],
|
|
3725
|
+
default: "cloudflare",
|
|
3726
|
+
summary: "The public tunnel: a Cloudflare quick tunnel (no account), or Tailscale Funnel (shows your device's tailnet name)."
|
|
3727
|
+
},
|
|
3728
|
+
{
|
|
3729
|
+
name: "ttl",
|
|
3730
|
+
kind: "duration",
|
|
3731
|
+
value: "<d>",
|
|
3732
|
+
summary: "How long the link works, such as 30m or 24h. Public: 1h by default, 7d at most."
|
|
3733
|
+
},
|
|
3734
|
+
{
|
|
3735
|
+
name: "scope",
|
|
3736
|
+
kind: "list",
|
|
3737
|
+
value: "<a,b>",
|
|
3738
|
+
summary: "The link's scopes: view, draft, submit, review, signal, action:*. Default: all."
|
|
3739
|
+
},
|
|
3740
|
+
{
|
|
3741
|
+
name: "viewer",
|
|
3742
|
+
kind: "string",
|
|
3743
|
+
value: "<ref>",
|
|
3744
|
+
summary: "The person the link is for, by your own stable key for them; without it, each link is a viewer of its own."
|
|
3745
|
+
},
|
|
3746
|
+
{
|
|
3747
|
+
name: "viewer-name",
|
|
3748
|
+
kind: "string",
|
|
3749
|
+
value: "<name>",
|
|
3750
|
+
summary: "The display name of --viewer."
|
|
3751
|
+
},
|
|
3752
|
+
{
|
|
3753
|
+
name: "request-id",
|
|
3754
|
+
kind: "string",
|
|
3755
|
+
value: "<id>",
|
|
3756
|
+
summary: "Make a retried share return the same share instead of opening another."
|
|
3757
|
+
}
|
|
3758
|
+
],
|
|
3759
|
+
output: {
|
|
3760
|
+
type: "ShareStartResult",
|
|
3761
|
+
topic: "cli"
|
|
3762
|
+
},
|
|
3763
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3764
|
+
example: "share ./sidebar-review --public --ttl 2h",
|
|
3765
|
+
async run(context) {
|
|
3766
|
+
const artifact = artifactRef(arg(context, "artifact"), context.cwd);
|
|
3767
|
+
const tailnet = context.flags["tailnet"] === true;
|
|
3768
|
+
const publicly = context.flags["public"] === true;
|
|
3769
|
+
if (tailnet === publicly) throw usage("Give --tailnet or --public.");
|
|
3770
|
+
const viaFlag = flag(context, "via");
|
|
3771
|
+
if (viaFlag !== void 0 && !publicly) throw usage("--via chooses a public tunnel: add --public.");
|
|
3772
|
+
const via = tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
|
|
3773
|
+
const ttl = flag(context, "ttl");
|
|
3774
|
+
const scopes = context.flags["scope"];
|
|
3775
|
+
const viewerRef = flag(context, "viewer");
|
|
3776
|
+
const viewerName = flag(context, "viewer-name");
|
|
3777
|
+
const requestId = flag(context, "request-id");
|
|
3778
|
+
if (viewerName !== void 0 && viewerRef === void 0) throw usage("--viewer-name needs --viewer.");
|
|
3779
|
+
const share = await context.call(shareStartMethod, {
|
|
3780
|
+
artifact,
|
|
3781
|
+
via,
|
|
3782
|
+
...ttl !== void 0 ? { ttl } : {},
|
|
3783
|
+
...scopes !== void 0 ? { scopes } : {},
|
|
3784
|
+
...viewerRef !== void 0 ? { viewer: {
|
|
3785
|
+
ref: viewerRef,
|
|
3786
|
+
...viewerName !== void 0 ? { name: viewerName } : {}
|
|
3787
|
+
} } : {},
|
|
3788
|
+
...requestId !== void 0 ? { requestId } : {}
|
|
3789
|
+
});
|
|
3790
|
+
context.record({
|
|
3791
|
+
event: "share.done",
|
|
3792
|
+
fields: { kind: via }
|
|
3793
|
+
});
|
|
3794
|
+
const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
|
|
3795
|
+
return {
|
|
3796
|
+
result: share,
|
|
3797
|
+
human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`
|
|
3798
|
+
};
|
|
3799
|
+
}
|
|
3800
|
+
});
|
|
3801
|
+
/** `mostra share stop <artifact|shareId>`. */
|
|
3802
|
+
const shareStopCommand = defineCommand({
|
|
3803
|
+
path: ["share", "stop"],
|
|
3804
|
+
summary: "Stop a share, or every share of an artifact: its link stops working and its tunnel closes.",
|
|
3805
|
+
args: [{
|
|
3806
|
+
name: "target",
|
|
3807
|
+
summary: "A share's ID (shr_…), or an artifact's source path or ID."
|
|
3808
|
+
}],
|
|
3809
|
+
flags: [],
|
|
3810
|
+
output: {
|
|
3811
|
+
type: "ShareStopResult",
|
|
3812
|
+
topic: "cli"
|
|
3813
|
+
},
|
|
3814
|
+
exits: [EXIT.failure, EXIT.environment],
|
|
3815
|
+
example: "share stop ./sidebar-review",
|
|
3816
|
+
async run(context) {
|
|
3817
|
+
const target = arg(context, "target");
|
|
3818
|
+
const result = await context.call(shareStopMethod, SHARE_ID.test(target) ? { shareId: target } : { artifact: artifactRef(target, context.cwd) });
|
|
3819
|
+
return {
|
|
3820
|
+
result,
|
|
3821
|
+
human: result.stopped.length === 0 ? "Nothing was shared.\n" : result.stopped.map((share) => `Stopped ${share.shareId}\n`).join("")
|
|
3822
|
+
};
|
|
3823
|
+
}
|
|
3824
|
+
});
|
|
3825
|
+
/** `mostra share list [artifact] [--all]`. */
|
|
3826
|
+
const shareListCommand = defineCommand({
|
|
3827
|
+
path: ["share", "list"],
|
|
3828
|
+
summary: "List the active shares, of every artifact or of one; --all adds the ones that ended.",
|
|
3829
|
+
args: [{
|
|
3830
|
+
name: "artifact",
|
|
3831
|
+
summary: "Only this artifact's shares: its source path or ID.",
|
|
3832
|
+
optional: true
|
|
3833
|
+
}],
|
|
3834
|
+
flags: [{
|
|
3835
|
+
name: "all",
|
|
3836
|
+
kind: "boolean",
|
|
3837
|
+
summary: "Also list shares that ended, and why."
|
|
3838
|
+
}],
|
|
3839
|
+
output: {
|
|
3840
|
+
type: "ShareListResult",
|
|
3841
|
+
topic: "cli"
|
|
3842
|
+
},
|
|
3843
|
+
exits: [EXIT.failure],
|
|
3844
|
+
example: "share list --all",
|
|
3845
|
+
async run(context) {
|
|
3846
|
+
const given = context.args["artifact"];
|
|
3847
|
+
const result = await context.call(shareListMethod, {
|
|
3848
|
+
...typeof given === "string" ? { artifact: artifactRef(given, context.cwd) } : {},
|
|
3849
|
+
...context.flags["all"] === true ? { all: true } : {}
|
|
3850
|
+
});
|
|
3851
|
+
return {
|
|
3852
|
+
result,
|
|
3853
|
+
human: result.shares.length === 0 ? "Nothing is shared.\n" : `${result.shares.map((share) => line(share)).join("\n")}\n`
|
|
3854
|
+
};
|
|
3423
3855
|
}
|
|
3424
|
-
|
|
3425
|
-
return false;
|
|
3426
|
-
}
|
|
3856
|
+
});
|
|
3427
3857
|
//#endregion
|
|
3428
3858
|
//#region src/commands/viewing.ts
|
|
3429
3859
|
/**
|
|
@@ -3604,6 +4034,7 @@ const COMMANDS = [
|
|
|
3604
4034
|
daemonInstallCommand,
|
|
3605
4035
|
daemonUninstallCommand,
|
|
3606
4036
|
hostCommand,
|
|
4037
|
+
mcpCommand,
|
|
3607
4038
|
docsCommand,
|
|
3608
4039
|
doctorCommand,
|
|
3609
4040
|
gcCommand,
|
|
@@ -3647,7 +4078,11 @@ function flagLine(flag) {
|
|
|
3647
4078
|
return ` ${name.padEnd(28)} ${flag.summary}${choices}${fallback}`;
|
|
3648
4079
|
}
|
|
3649
4080
|
/** Commands that run until their connection or Ctrl-C ends them: `--timeout` doesn't bound them. */
|
|
3650
|
-
const UNBOUNDED = /* @__PURE__ */ new Set([
|
|
4081
|
+
const UNBOUNDED = /* @__PURE__ */ new Set([
|
|
4082
|
+
"host",
|
|
4083
|
+
"dev",
|
|
4084
|
+
"mcp"
|
|
4085
|
+
]);
|
|
3651
4086
|
/**
|
|
3652
4087
|
* The global flags a command doesn't define again (`wait --timeout` is the wait's own); a command
|
|
3653
4088
|
* `--timeout` doesn't bound has no `--timeout`.
|
|
@@ -3768,191 +4203,6 @@ function referenceMarkdown(commands) {
|
|
|
3768
4203
|
].join("\n");
|
|
3769
4204
|
}
|
|
3770
4205
|
//#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
4206
|
//#region src/run.ts
|
|
3957
4207
|
/**
|
|
3958
4208
|
* The runner (INTERFACES §9, D140 item 16): reads the command line, runs one command, and owns
|
|
@@ -4076,7 +4326,7 @@ async function run(io) {
|
|
|
4076
4326
|
json,
|
|
4077
4327
|
tty: io.tty,
|
|
4078
4328
|
readsStdin,
|
|
4079
|
-
quiet: command.quiet === true,
|
|
4329
|
+
quiet: typeof command.quiet === "function" ? command.quiet(parsed.flags) : command.quiet === true,
|
|
4080
4330
|
hostHome: embeddedHome(marks),
|
|
4081
4331
|
stderr: io.stderr,
|
|
4082
4332
|
ask: (question, timeoutMs) => ask(io, question, timeoutMs)
|
|
@@ -4142,22 +4392,30 @@ async function run(io) {
|
|
|
4142
4392
|
io.stderr(describe(diagnostic));
|
|
4143
4393
|
},
|
|
4144
4394
|
record: (event) => telemetry.record(event),
|
|
4395
|
+
checkpoint(hostInstance) {
|
|
4396
|
+
try {
|
|
4397
|
+
telemetry.checkpoint({ hostInstance });
|
|
4398
|
+
} catch {}
|
|
4399
|
+
},
|
|
4145
4400
|
runtime: (args, stdio = "pipe") => runRuntime(io, args, stdio)
|
|
4146
4401
|
};
|
|
4147
4402
|
let exit;
|
|
4148
4403
|
let error;
|
|
4404
|
+
let ownHostInstance = false;
|
|
4149
4405
|
try {
|
|
4150
4406
|
if (!await telemetry.begin().catch(() => true)) return 130;
|
|
4151
4407
|
const outcome = await withTimeout(command, context, timeoutMs, () => startingDaemon);
|
|
4152
4408
|
exit = outcome.exit ?? EXIT.ok;
|
|
4153
|
-
|
|
4154
|
-
if (
|
|
4155
|
-
|
|
4156
|
-
|
|
4157
|
-
|
|
4158
|
-
|
|
4159
|
-
|
|
4160
|
-
|
|
4409
|
+
ownHostInstance = outcome.hostInstance === true;
|
|
4410
|
+
if (outcome.raw !== true) {
|
|
4411
|
+
if (json) writeJson({
|
|
4412
|
+
ok: true,
|
|
4413
|
+
result: outcome.result ?? null,
|
|
4414
|
+
...summary && !streamed && command.local !== true ? { instance: summary } : {},
|
|
4415
|
+
warnings
|
|
4416
|
+
});
|
|
4417
|
+
else io.stdout(outcome.human ?? `${JSON.stringify(outcome.result, null, 2)}\n`);
|
|
4418
|
+
}
|
|
4161
4419
|
} catch (caught) {
|
|
4162
4420
|
const diagnostic = diagnosticOf(caught);
|
|
4163
4421
|
error = diagnostic.code;
|
|
@@ -4169,7 +4427,7 @@ async function run(io) {
|
|
|
4169
4427
|
telemetry.end({
|
|
4170
4428
|
exit,
|
|
4171
4429
|
durationMs: Date.now() - started,
|
|
4172
|
-
hostInstance: summary?.mode === "host",
|
|
4430
|
+
hostInstance: summary?.mode === "host" || ownHostInstance,
|
|
4173
4431
|
...error !== void 0 ? { error } : {}
|
|
4174
4432
|
});
|
|
4175
4433
|
} catch {}
|
|
@@ -4180,7 +4438,7 @@ async function run(io) {
|
|
|
4180
4438
|
* until their connection or Ctrl-C ends them, so `--timeout` bounds neither.
|
|
4181
4439
|
*/
|
|
4182
4440
|
async function withTimeout(command, context, timeoutMs, startingDaemon) {
|
|
4183
|
-
if (timeoutMs === void 0 ||
|
|
4441
|
+
if (timeoutMs === void 0 || UNBOUNDED.has(command.path[0] ?? "")) return command.run(context);
|
|
4184
4442
|
let timer;
|
|
4185
4443
|
try {
|
|
4186
4444
|
return await Promise.race([command.run(context), new Promise((_, reject) => {
|
|
@@ -4222,4 +4480,4 @@ async function runRuntime(io, args, stdio) {
|
|
|
4222
4480
|
//#endregion
|
|
4223
4481
|
export { COMMANDS as a, referenceMarkdown as i, commandDefinition as n, commandHelp as r, run as t };
|
|
4224
4482
|
|
|
4225
|
-
//# sourceMappingURL=run-
|
|
4483
|
+
//# sourceMappingURL=run-DdYT3iHQ.js.map
|