@mostra/cli 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/bootstrap-BStzS_41.js +1 -0
  3. package/dist/bootstrap-_iCl_HaO.js +423 -0
  4. package/dist/bootstrap-_iCl_HaO.js.map +1 -0
  5. package/dist/{flush-CBN3AU9X.js → flush-znWmNZA1.js} +34 -5
  6. package/dist/flush-znWmNZA1.js.map +1 -0
  7. package/dist/index.d.ts +14 -4
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +2 -2
  10. package/dist/reference/cli.md +177 -4
  11. package/dist/reference/diagnostics.json +129 -3
  12. package/dist/reference/errors/MOSTRA_ARTIFACT_BUNDLE_INVALID.md +23 -0
  13. package/dist/reference/errors/MOSTRA_ARTIFACT_ID_DROPPED.md +23 -0
  14. package/dist/reference/errors/MOSTRA_ARTIFACT_PATCH_REJECTED.md +23 -0
  15. package/dist/reference/errors/MOSTRA_ARTIFACT_PATH_INVALID.md +23 -0
  16. package/dist/reference/errors/MOSTRA_ENV_RUNTIME_INSTALLING.md +23 -0
  17. package/dist/reference/errors/MOSTRA_HOME_NETWORK_FILESYSTEM.md +23 -0
  18. package/dist/reference/errors/MOSTRA_REMOTE_CONFIG_INVALID.md +23 -0
  19. package/dist/reference/errors/MOSTRA_REMOTE_LOGIN_FAILED.md +23 -0
  20. package/dist/reference/errors/MOSTRA_REMOTE_NOT_OWNER_INSTANCE.md +23 -0
  21. package/dist/reference/errors/MOSTRA_REMOTE_OWNER_OFFLINE.md +23 -0
  22. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +23 -0
  23. package/dist/reference/errors/MOSTRA_REMOTE_RATE_LIMITED.md +23 -0
  24. package/dist/reference/errors/MOSTRA_REMOTE_SIGN_IN_REQUIRED.md +23 -0
  25. package/dist/reference/errors/MOSTRA_REMOTE_UNREACHABLE.md +23 -0
  26. package/dist/reference/errors/MOSTRA_SUBMIT_NOT_FOUND.md +3 -3
  27. package/dist/reference/telemetry.md +5 -3
  28. package/dist/{run-CuMkFuH7.js → run-Aq4HVIY0.js} +1244 -767
  29. package/dist/run-Aq4HVIY0.js.map +1 -0
  30. package/dist/run-D1U_RFEP.js +1 -0
  31. package/dist/skill/SKILL.md +6 -3
  32. package/dist/skill/references/answers.md +37 -1
  33. package/dist/skill/references/long-lived.md +2 -2
  34. package/dist/skill/references/mcp.md +63 -0
  35. package/dist/skill/references/sharing.md +54 -4
  36. package/dist/telemetry/flush-main.js +1 -1
  37. package/package.json +10 -4
  38. package/src/bootstrap.ts +16 -3
  39. package/src/client.ts +1 -1
  40. package/src/command.ts +13 -3
  41. package/src/commands/admin.ts +11 -1
  42. package/src/commands/authoring.ts +85 -3
  43. package/src/commands/dev.ts +60 -44
  44. package/src/commands/index.ts +18 -3
  45. package/src/commands/interaction.ts +19 -1
  46. package/src/commands/mcp.ts +128 -0
  47. package/src/commands/remote.ts +113 -0
  48. package/src/commands/sharing.ts +33 -6
  49. package/src/commands/viewing.ts +20 -2
  50. package/src/detached.ts +3 -0
  51. package/src/docs.ts +14 -6
  52. package/src/exit.ts +2 -0
  53. package/src/help.ts +1 -1
  54. package/src/home.ts +5 -3
  55. package/src/mcp.ts +448 -0
  56. package/src/parse.ts +20 -6
  57. package/src/run.ts +24 -13
  58. package/src/telemetry/harness.ts +24 -0
  59. package/src/telemetry/index.ts +75 -48
  60. package/src/telemetry/store.ts +15 -4
  61. package/dist/bootstrap-DfEe_yPr.js +0 -113
  62. package/dist/bootstrap-DfEe_yPr.js.map +0 -1
  63. package/dist/exit-CBIf8nAU.js +0 -79
  64. package/dist/exit-CBIf8nAU.js.map +0 -1
  65. package/dist/flush-CBN3AU9X.js.map +0 -1
  66. package/dist/run-3WlZ2Jos.js +0 -1
  67. package/dist/run-CuMkFuH7.js.map +0 -1
@@ -54,53 +54,69 @@ export const devCommand: CommandDef = defineCommand({
54
54
  example: "dev ./sidebar-review",
55
55
  streams: true,
56
56
  async run(context) {
57
- const connection = await context.connection();
58
- let sessionId: string | undefined;
59
- const early: DevNotifyParams[] = [];
60
- const show = (event: DevNotifyParams): void => {
61
- if (event.kind === "diagnostics") {
62
- for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
63
- }
64
- context.emit(event, line(event));
65
- };
66
- connection?.onNotification(DEV_NOTIFY, (params) => {
67
- const event = params as DevNotifyParams;
68
- if (sessionId === undefined) early.push(event);
69
- else if (event.sessionId === sessionId) show(event);
70
- });
71
- const portFlag = context.flags["port"];
72
- const started = await context.call(devStartMethod, {
73
- source: sourceRef(arg(context, "path"), context.cwd),
74
- ...(typeof portFlag === "number" ? { port: portFlag } : {}),
75
- });
76
- sessionId = started.sessionId;
77
- context.emit(
78
- { kind: "started", ...started },
79
- `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`,
80
- );
81
- for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
82
57
  // The session lasts until Ctrl-C (or SIGTERM; Ctrl+Break on Windows), or until the instance
83
- // ends it.
84
- let stop: () => void = () => {};
58
+ // ends it. The handlers are in place before anything starts or is printed: a Ctrl-C between
59
+ // "started" and a later handler met Node's default action and ended the process without
60
+ // stopping the session or printing its result (#110's CI).
85
61
  const signals = ["SIGINT", "SIGTERM", "SIGBREAK"] as const;
86
- const ended = await new Promise<"signal" | "closed">((done) => {
87
- stop = (): void => done("signal");
88
- for (const signal of signals) process.once(signal, stop);
89
- void connection?.closed.then(() => done("closed"));
90
- });
91
- for (const signal of signals) process.off(signal, stop);
92
- if (ended === "closed") {
93
- throw new RpcError(
94
- createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
95
- message: "The instance ended the development preview (it stopped or restarted).",
96
- hint: "Run mostra dev again.",
97
- }),
62
+ let interrupted = false;
63
+ let stop: () => void = () => {
64
+ interrupted = true;
65
+ };
66
+ const onSignal = (): void => stop();
67
+ for (const signal of signals) process.once(signal, onSignal);
68
+ const release = (): void => {
69
+ for (const signal of signals) process.off(signal, onSignal);
70
+ };
71
+ try {
72
+ const connection = await context.connection();
73
+ let sessionId: string | undefined;
74
+ const early: DevNotifyParams[] = [];
75
+ const show = (event: DevNotifyParams): void => {
76
+ if (event.kind === "diagnostics") {
77
+ for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);
78
+ }
79
+ context.emit(event, line(event));
80
+ };
81
+ connection?.onNotification(DEV_NOTIFY, (params) => {
82
+ const event = params as DevNotifyParams;
83
+ if (sessionId === undefined) early.push(event);
84
+ else if (event.sessionId === sessionId) show(event);
85
+ });
86
+ const portFlag = context.flags["port"];
87
+ const started = await context.call(devStartMethod, {
88
+ source: sourceRef(arg(context, "path"), context.cwd),
89
+ ...(typeof portFlag === "number" ? { port: portFlag } : {}),
90
+ });
91
+ sessionId = started.sessionId;
92
+ context.emit(
93
+ { kind: "started", ...started },
94
+ `Development preview, not published: ${started.url}\nPress Ctrl-C to stop.\n`,
98
95
  );
96
+ for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);
97
+ const ended = interrupted
98
+ ? "signal"
99
+ : await new Promise<"signal" | "closed">((done) => {
100
+ stop = (): void => done("signal");
101
+ void connection?.closed.then(() => done("closed"));
102
+ });
103
+ // A second Ctrl-C from here on ends the process, as before.
104
+ release();
105
+ if (ended === "closed") {
106
+ throw new RpcError(
107
+ createDiagnostic("MOSTRA_HOST_CONNECTION_CLOSED", {
108
+ message: "The instance ended the development preview (it stopped or restarted).",
109
+ hint: "Run mostra dev again.",
110
+ }),
111
+ );
112
+ }
113
+ await context.call(devStopMethod, { sessionId }).catch(() => undefined);
114
+ return {
115
+ result: { sessionId, stopped: "signal" },
116
+ human: "Stopped.\n",
117
+ };
118
+ } finally {
119
+ release();
99
120
  }
100
- await context.call(devStopMethod, { sessionId }).catch(() => undefined);
101
- return {
102
- result: { sessionId, stopped: "signal" },
103
- human: "Stopped.\n",
104
- };
105
121
  },
106
122
  });
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Every command of `mostra` (D60, D140 item 13), in the order help lists them. Commands later
3
- * packages own (`review export`, `export`, `mcp`, `plugin`, `term`, `run`) join this list with
4
- * their packages, never as placeholders; `share` joined with WP-13.
3
+ * packages own (`review export`, `plugin`, `term`) join this list with their
4
+ * packages, never as placeholders; `share` joined with WP-13, `mcp` with WP-15, and `export` (its `bundle` class) and `run`
5
+ * with WP-29.
5
6
  */
6
7
  import type { CommandDef } from "../command.ts";
7
8
  import {
@@ -24,7 +25,14 @@ import {
24
25
  telemetryOnCommand,
25
26
  telemetryStatusCommand,
26
27
  } from "./admin.ts";
27
- import { addCommand, newCommand, publishCommand, verifyCommand } from "./authoring.ts";
28
+ import {
29
+ addCommand,
30
+ exportCommand,
31
+ newCommand,
32
+ publishCommand,
33
+ runCommand,
34
+ verifyCommand,
35
+ } from "./authoring.ts";
28
36
  import { devCommand } from "./dev.ts";
29
37
  import {
30
38
  pushCommand,
@@ -34,6 +42,8 @@ import {
34
42
  stateSetCommand,
35
43
  waitCommand,
36
44
  } from "./interaction.ts";
45
+ import { mcpCommand } from "./mcp.ts";
46
+ import { loginCommand, logoutCommand } from "./remote.ts";
37
47
  import { shareCommand, shareListCommand, shareStopCommand } from "./sharing.ts";
38
48
  import { openCommand } from "./viewing.ts";
39
49
 
@@ -47,6 +57,8 @@ export const COMMANDS: readonly CommandDef[] = [
47
57
  shareCommand,
48
58
  shareStopCommand,
49
59
  shareListCommand,
60
+ loginCommand,
61
+ logoutCommand,
50
62
  waitCommand,
51
63
  resultsCommand,
52
64
  stateGetCommand,
@@ -54,6 +66,8 @@ export const COMMANDS: readonly CommandDef[] = [
54
66
  statePatchCommand,
55
67
  pushCommand,
56
68
  addCommand,
69
+ exportCommand,
70
+ runCommand,
57
71
  secretSetCommand,
58
72
  secretListCommand,
59
73
  secretRmCommand,
@@ -66,6 +80,7 @@ export const COMMANDS: readonly CommandDef[] = [
66
80
  daemonInstallCommand,
67
81
  daemonUninstallCommand,
68
82
  hostCommand,
83
+ mcpCommand,
69
84
  docsCommand,
70
85
  doctorCommand,
71
86
  gcCommand,
@@ -22,6 +22,24 @@ import { arg, artifactRef, flag, jsonInput, parseJson, pretty } from "./shared.t
22
22
  /** The longest one `wait` request may ask for (INTERFACES §6: 2^31 − 1 ms). */
23
23
  const MAX_WAIT_MS = 2 ** 31 - 1;
24
24
 
25
+ /**
26
+ * What `wait` prints when its condition held: the event and cursor, and for a signal its name and
27
+ * the payload the page or action sent (#115), which is otherwise only in `--json`.
28
+ */
29
+ export function satisfiedLine(
30
+ event: { readonly type: string; readonly payload?: Readonly<Record<string, unknown>> },
31
+ cursor: string,
32
+ ): string {
33
+ const line = `${event.type} at cursor ${cursor}`;
34
+ if (event.type !== "signal.raised") return `${line}\n`;
35
+ const name = typeof event.payload?.["name"] === "string" ? ` ${event.payload["name"]}` : "";
36
+ const payload =
37
+ event.payload !== undefined && Object.hasOwn(event.payload, "payload")
38
+ ? `\npayload: ${JSON.stringify(event.payload["payload"])}`
39
+ : "";
40
+ return `${event.type}${name} at cursor ${cursor}${payload}\n`;
41
+ }
42
+
25
43
  /** `mostra wait <artifact>`. */
26
44
  export const waitCommand: CommandDef = defineCommand({
27
45
  path: ["wait"],
@@ -67,7 +85,7 @@ export const waitCommand: CommandDef = defineCommand({
67
85
  ...(after !== undefined ? { after } : {}),
68
86
  });
69
87
  if (result.status === "satisfied") {
70
- return { result, human: `${result.event.type} at cursor ${result.cursor}\n` };
88
+ return { result, human: satisfiedLine(result.event, result.cursor) };
71
89
  }
72
90
  // Waiting again is for still_waiting alone: an answer a newer instance gives that this CLI
73
91
  // doesn't know ends the wait as a failure, so it is neither looped on nor taken for a
@@ -0,0 +1,128 @@
1
+ /**
2
+ * `mostra mcp` (INTERFACES §12, D164): Mostra's MCP server, for any MCP client. Over stdio by
3
+ * default (a client starts it), or Streamable HTTP with `--http`. Its tools are `@mostra/mcp`'s;
4
+ * this command gives them the home's daemon, the workspace and the reference, and counts each
5
+ * MCP client in telemetry unless `--embedded` says a host or harness plugin started it (D148).
6
+ */
7
+ import { resolve } from "node:path";
8
+ import type { McpClientInfo } from "@mostra/mcp";
9
+ import { defaultWorkspaceRoot } from "@mostra/mcp";
10
+ import { type CommandDef, defineCommand } from "../command.ts";
11
+ import { embeddedHome, readHomeMarks } from "../home.ts";
12
+ import { type DaemonInstance, serveOverHttp, serveOverStdio } from "../mcp.ts";
13
+ import { usage } from "../parse.ts";
14
+ import { mcpSessionFields } from "../telemetry/harness.ts";
15
+ import { cliVersion } from "../version.ts";
16
+ import { flag } from "./shared.ts";
17
+
18
+ /** `mostra mcp`. */
19
+ export const mcpCommand: CommandDef = defineCommand({
20
+ path: ["mcp"],
21
+ summary:
22
+ "Run Mostra's MCP server, so an MCP client can create, verify and publish artifacts, wait for answers and read results.",
23
+ flags: [
24
+ {
25
+ name: "http",
26
+ kind: "boolean",
27
+ summary:
28
+ "Serve Streamable HTTP at /mcp instead of stdio; every request needs Authorization: Bearer <token>.",
29
+ },
30
+ {
31
+ name: "port",
32
+ kind: "number",
33
+ value: "<port>",
34
+ summary: "With --http, the port; default one the system picks.",
35
+ },
36
+ {
37
+ name: "bind",
38
+ kind: "string",
39
+ value: "<address>",
40
+ summary: "With --http, listen on this address instead of 127.0.0.1.",
41
+ },
42
+ {
43
+ name: "url-host",
44
+ kind: "string",
45
+ value: "<name>",
46
+ summary: "With --http, the host name clients use; a wildcard --bind needs it.",
47
+ },
48
+ {
49
+ name: "workspace",
50
+ kind: "string",
51
+ value: "<dir>",
52
+ summary:
53
+ "Where relative artifact directories and new artifacts go. Default: MOSTRA_MCP_WORKSPACE, else ~/mostra-artifacts.",
54
+ },
55
+ {
56
+ name: "embedded",
57
+ kind: "boolean",
58
+ summary:
59
+ "This server runs on someone's behalf (a harness plugin or another host started it), so it sends no telemetry.",
60
+ },
61
+ ],
62
+ output: { type: "the MCP protocol on stdin and stdout, or over HTTP", topic: "cli" },
63
+ exits: [],
64
+ example: "mcp",
65
+ readsStdin: (flags) => flags["http"] !== true,
66
+ quiet: (flags) => flags["embedded"] === true,
67
+ async run(context) {
68
+ const http = context.flags["http"] === true;
69
+ const port = context.flags["port"];
70
+ const bind = flag(context, "bind");
71
+ const urlHost = flag(context, "url-host");
72
+ if (!http && (port !== undefined || bind !== undefined || urlHost !== undefined)) {
73
+ throw usage("--port, --bind and --url-host go with --http.");
74
+ }
75
+ if (typeof port === "number" && (!Number.isInteger(port) || port < 0 || port > 65_535)) {
76
+ throw usage("--port takes a port number from 0 to 65535.");
77
+ }
78
+ const given = flag(context, "workspace") ?? context.env["MOSTRA_MCP_WORKSPACE"];
79
+ const workspace =
80
+ given !== undefined && given !== "" ? resolve(context.cwd, given) : defaultWorkspaceRoot();
81
+ const counted = new Set<string>();
82
+ let reached: DaemonInstance | undefined;
83
+ const options = {
84
+ home: context.home,
85
+ env: context.env,
86
+ workspace,
87
+ version: cliVersion(),
88
+ log: context.log,
89
+ onClient(client: McpClientInfo, instance: DaemonInstance) {
90
+ // Each client once per process (D140 item 8), and queued at once, since a harness stops
91
+ // its server within a second, before any end of the command (D164 item 4). Connecting
92
+ // starts nothing: a host-spawned instance always marks its home (D140 item 4), which
93
+ // the mark read now tells, as does a session a call already opened.
94
+ reached = instance;
95
+ const fields = mcpSessionFields(client);
96
+ const key = `${fields.client}@${fields.clientVersion ?? ""}`;
97
+ if (counted.has(key)) return;
98
+ counted.add(key);
99
+ context.record({ event: "mcp.session", fields });
100
+ context.checkpoint(instance.hostInstance() || embeddedHome(readHomeMarks(context.home)));
101
+ },
102
+ };
103
+ const done = { result: undefined, raw: true as const };
104
+ if (!http) {
105
+ await serveOverStdio(options);
106
+ return { ...done, hostInstance: reached?.hostInstance() === true };
107
+ }
108
+ await serveOverHttp({
109
+ ...options,
110
+ port: typeof port === "number" ? port : 0,
111
+ ...(bind !== undefined ? { bind } : {}),
112
+ ...(urlHost !== undefined ? { urlHost } : {}),
113
+ onListening({ url, token, generated }) {
114
+ // The token is a secret: it goes to stderr once, never to stdout, which a supervisor
115
+ // may keep in a log (D164 item 3, Opus review of WP-15, finding 8). A program that needs
116
+ // the token sets MOSTRA_MCP_TOKEN; `listening` gives it the URL.
117
+ if (context.json) context.emit({ kind: "listening", url });
118
+ else context.stderr(`Mostra's MCP server is listening at ${url}\n`);
119
+ context.stderr(
120
+ generated
121
+ ? `Send Authorization: Bearer ${token} with every request (set MOSTRA_MCP_TOKEN to choose the token).\n`
122
+ : "Send Authorization: Bearer <MOSTRA_MCP_TOKEN> with every request.\n",
123
+ );
124
+ },
125
+ });
126
+ return { ...done, hostInstance: reached?.hostInstance() === true };
127
+ },
128
+ });
@@ -0,0 +1,113 @@
1
+ /**
2
+ * `mostra login` and `mostra logout` (INTERFACES §18.7, D165 items 2, 15): this home signs in to a
3
+ * remote server by the OAuth device authorization grant, so `mostra share --cloud` can host its
4
+ * artifacts there, and signs out again. The instance keeps the refresh token in the home,
5
+ * owner-only; signing out keeps its instance link, so the artifacts it shared stay its own at the
6
+ * next sign-in, unless `--forget`. Clients of `remote/login`, `remote/login.wait` and
7
+ * `remote/logout`.
8
+ */
9
+ import { remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod } from "@mostra/protocol";
10
+ import { type CommandDef, defineCommand } from "../command.ts";
11
+ import { EXIT } from "../exit.ts";
12
+
13
+ /** How long `mostra login` waits for the person to approve, in all (the code lives 10 minutes). */
14
+ const LOGIN_WAIT_MS = 10 * 60_000;
15
+ /** Each wait asks the instance for this long, so a slow approval never meets a request timeout. */
16
+ const LOGIN_STEP_MS = 30_000;
17
+
18
+ /** `mostra login [<server>] [--default]`. */
19
+ export const loginCommand: CommandDef = defineCommand({
20
+ path: ["login"],
21
+ summary:
22
+ "Sign this machine's Mostra in to a remote server, so mostra share --cloud can host pages there.",
23
+ args: [
24
+ {
25
+ name: "server",
26
+ summary:
27
+ "The server's address, such as https://api.example.com. Default: the server signed in to last.",
28
+ optional: true,
29
+ },
30
+ ],
31
+ flags: [
32
+ {
33
+ name: "default",
34
+ kind: "boolean",
35
+ summary:
36
+ "Make this machine the account's default, the one chat apps create pages on. Default: the first machine linked.",
37
+ },
38
+ ],
39
+ output: { type: "RemoteLoginWaitResult", topic: "cli" },
40
+ exits: [EXIT.failure, EXIT.environment],
41
+ example: "login https://api.example.com",
42
+ async run(context) {
43
+ const server = context.args["server"];
44
+ const started = await context.call(remoteLoginMethod, {
45
+ ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
46
+ ...(context.flags["default"] === true ? { default: true } : {}),
47
+ });
48
+ const where = started.verificationUriComplete ?? started.verificationUri;
49
+ context.emit(
50
+ { kind: "code", ...started },
51
+ `Open ${where} and check that it shows the code ${started.userCode}, then approve.\nWaiting for you to approve…`,
52
+ );
53
+ const deadline = Date.now() + LOGIN_WAIT_MS;
54
+ for (;;) {
55
+ const waited = await context.call(remoteLoginWaitMethod, {
56
+ loginId: started.loginId,
57
+ timeoutMs: Math.max(0, Math.min(LOGIN_STEP_MS, deadline - Date.now())),
58
+ });
59
+ if (waited.status === "signed-in") {
60
+ return {
61
+ result: waited,
62
+ human: `Signed in to ${waited.server} as ${waited.account.name ?? waited.account.id}. This machine is ${waited.instanceId}.\n`,
63
+ };
64
+ }
65
+ if (Date.now() >= deadline) {
66
+ return {
67
+ result: waited,
68
+ human: "The code wasn't approved in time. Run mostra login again for a new one.\n",
69
+ exit: EXIT.timeout,
70
+ };
71
+ }
72
+ }
73
+ },
74
+ });
75
+
76
+ /** `mostra logout [<server>] [--forget]`. */
77
+ export const logoutCommand: CommandDef = defineCommand({
78
+ path: ["logout"],
79
+ summary:
80
+ "Sign this machine's Mostra out of a remote server; its hosted pages keep working, and their answers wait for the next sign-in.",
81
+ args: [
82
+ {
83
+ name: "server",
84
+ summary: "The server's address. Default: the server signed in to last.",
85
+ optional: true,
86
+ },
87
+ ],
88
+ flags: [
89
+ {
90
+ name: "forget",
91
+ kind: "boolean",
92
+ summary:
93
+ "Also forget this machine's link to the server: the pages it shared there are no longer its own.",
94
+ },
95
+ ],
96
+ output: { type: "RemoteLogoutResult", topic: "cli" },
97
+ exits: [EXIT.failure, EXIT.environment],
98
+ example: "logout",
99
+ async run(context) {
100
+ const server = context.args["server"];
101
+ const result = await context.call(remoteLogoutMethod, {
102
+ ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
103
+ ...(context.flags["forget"] === true ? { forget: true } : {}),
104
+ });
105
+ return {
106
+ result,
107
+ human:
108
+ result.servers.length === 0
109
+ ? "This machine wasn't signed in to a server.\n"
110
+ : `Signed out of ${result.servers.join(", ")}.\n`,
111
+ };
112
+ },
113
+ });
@@ -2,7 +2,8 @@
2
2
  * `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon
3
3
  * runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's
4
4
  * identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via
5
- * funnel`), whose link expires (1 hour by default, 7 days at most). The share lives in the
5
+ * funnel`), whose link expires (1 hour by default, 7 days at most); or `--cloud` (D165 item 15),
6
+ * hosted on a remote server this home signed in to, so the link works while this machine sleeps. The share lives in the
6
7
  * daemon, so the command returns at once with the link; `share stop` ends it and `share list`
7
8
  * shows what is shared. A client of `share/start`, `share/stop` and `share/list`.
8
9
  */
@@ -26,6 +27,7 @@ const THROUGH: Readonly<Record<ShareVia, string>> = {
26
27
  tailnet: "Tailscale Serve, inside your tailnet",
27
28
  funnel: "Tailscale Funnel, public",
28
29
  cloudflare: "a Cloudflare quick tunnel, public",
30
+ remote: "a remote server, hosted",
29
31
  };
30
32
 
31
33
  /**
@@ -58,9 +60,22 @@ function line(share: Share): string {
58
60
  export const shareCommand: CommandDef = defineCommand({
59
61
  path: ["share"],
60
62
  summary:
61
- "Open an artifact to people beyond this machine: inside your tailnet, or publicly with a link that expires.",
62
- args: [{ name: "artifact", summary: "The artifact: its source path or its ID." }],
63
+ "Open an artifact to people beyond this machine: inside your tailnet, publicly with a link that expires, or hosted on a server.",
64
+ args: [
65
+ { name: "artifact", summary: "The artifact: its source path or its ID." },
66
+ {
67
+ name: "server",
68
+ summary: "With --cloud: the server's address. Default: the server signed in to last.",
69
+ optional: true,
70
+ },
71
+ ],
63
72
  flags: [
73
+ {
74
+ name: "cloud",
75
+ kind: "boolean",
76
+ summary:
77
+ "Host it on a remote server you signed in to with mostra login: the link keeps working while this machine sleeps.",
78
+ },
64
79
  {
65
80
  name: "tailnet",
66
81
  kind: "boolean",
@@ -115,16 +130,26 @@ export const shareCommand: CommandDef = defineCommand({
115
130
  ],
116
131
  output: { type: "ShareStartResult", topic: "cli" },
117
132
  exits: [EXIT.failure, EXIT.environment],
118
- example: "share ./sidebar-review --public --ttl 2h",
133
+ example: "share ./sidebar-review --cloud",
119
134
  async run(context) {
120
135
  const artifact = artifactRef(arg(context, "artifact"), context.cwd);
121
136
  const tailnet = context.flags["tailnet"] === true;
122
137
  const publicly = context.flags["public"] === true;
123
- if (tailnet === publicly) throw usage("Give --tailnet or --public.");
138
+ const cloud = context.flags["cloud"] === true;
139
+ if ([tailnet, publicly, cloud].filter(Boolean).length !== 1)
140
+ throw usage("Give one of --tailnet, --public or --cloud.");
124
141
  const viaFlag = flag(context, "via");
125
142
  if (viaFlag !== undefined && !publicly)
126
143
  throw usage("--via chooses a public tunnel: add --public.");
127
- const via: ShareVia = tailnet ? "tailnet" : viaFlag === "funnel" ? "funnel" : "cloudflare";
144
+ const server = context.args["server"];
145
+ if (server !== undefined && !cloud) throw usage("A server names where --cloud hosts it.");
146
+ const via: ShareVia = cloud
147
+ ? "remote"
148
+ : tailnet
149
+ ? "tailnet"
150
+ : viaFlag === "funnel"
151
+ ? "funnel"
152
+ : "cloudflare";
128
153
  const ttl = flag(context, "ttl");
129
154
  const scopes = context.flags["scope"] as readonly string[] | undefined;
130
155
  const viewerRef = flag(context, "viewer");
@@ -135,6 +160,7 @@ export const shareCommand: CommandDef = defineCommand({
135
160
  const share = await context.call(shareStartMethod, {
136
161
  artifact,
137
162
  via,
163
+ ...(typeof server === "string" ? { server: server.replace(/\/+$/, "") } : {}),
138
164
  ...(ttl !== undefined ? { ttl: ttl as `${number}${"s" | "m" | "h" | "d"}` } : {}),
139
165
  ...(scopes !== undefined ? { scopes: scopes as CapabilityScope[] } : {}),
140
166
  ...(viewerRef !== undefined
@@ -144,6 +170,7 @@ export const shareCommand: CommandDef = defineCommand({
144
170
  });
145
171
  context.record({ event: "share.done", fields: { kind: via } });
146
172
  const until = share.expiresAt ? `until ${share.expiresAt}` : "until you stop it";
173
+ // A hosted page keeps working while this machine sleeps: its answers wait for it (D165).
147
174
  return {
148
175
  result: share,
149
176
  human: `${share.url}\nShared through ${THROUGH[via]}, ${until}.\n${via === "tailnet" ? tailnetReach(share) : ""}Stop it with: mostra share stop ${share.shareId}\n`,
@@ -37,17 +37,35 @@ function wantsBrowser(context: CommandContext): boolean {
37
37
  return context.tty.stdout && !context.json && hasDisplay(context.env);
38
38
  }
39
39
 
40
- /** The link, opened in a browser when wanted. */
40
+ /**
41
+ * Why no browser was opened, for stderr (#114): an agent's shell isn't a terminal, so without a
42
+ * word it would tell its person the page is open when it isn't.
43
+ */
44
+ function notOpenedReason(context: CommandContext, tried: boolean): string | undefined {
45
+ if (context.flags["no-browser"] === true) return undefined;
46
+ if (tried) return "No browser opened: none could be started here. Give the person the link.";
47
+ if (!hasDisplay(context.env)) {
48
+ return "No browser opened: this session has no display. Give the person the link.";
49
+ }
50
+ return "No browser opened: this isn't a terminal. Pass --browser to open it here, or give the person the link.";
51
+ }
52
+
53
+ /** The link, opened in a browser when wanted; why not on stderr when it wasn't. */
41
54
  async function show(
42
55
  context: CommandContext,
43
56
  link: CapabilityLink,
44
57
  ): Promise<{ result: CapabilityLink & { readonly opened: boolean }; human: string }> {
45
58
  let opened = false;
46
- if (wantsBrowser(context)) {
59
+ const tried = wantsBrowser(context);
60
+ if (tried) {
47
61
  const launch = await context.call(viewLaunchMethod, { tokenId: link.tokenId });
48
62
  // The launch URL reaches the browser through a 0600 page, never its arguments.
49
63
  opened = await openInBrowser(launch.url, context.env);
50
64
  }
65
+ if (!opened) {
66
+ const reason = notOpenedReason(context, tried);
67
+ if (reason !== undefined) context.log(reason);
68
+ }
51
69
  return { result: { ...link, opened }, human: `${link.url}\n` };
52
70
  }
53
71
 
package/src/detached.ts CHANGED
@@ -25,10 +25,13 @@ export const PATH_VARIABLES: readonly string[] = [
25
25
  "MOSTRA_VERIFY_ENTRY",
26
26
  "MOSTRA_WIN_HELPER",
27
27
  "MOSTRA_TEST_WORKER_HOST",
28
+ "MOSTRA_TEST_NETWORK_FILESYSTEM",
29
+ "MOSTRA_TEST_BINDING_TRACE",
28
30
  "MOSTRA_TEST_BUNDLE_PINS",
29
31
  "MOSTRA_TAILSCALE",
30
32
  "MOSTRA_CLOUDFLARED",
31
33
  "MOSTRA_TEST_TUNNELS",
34
+ "MOSTRA_MCP_WORKSPACE",
32
35
  ];
33
36
 
34
37
  /** `env` with every relative path variable resolved against `cwd`. */
package/src/docs.ts CHANGED
@@ -150,14 +150,22 @@ const FENCE_LANGUAGES: Readonly<Record<string, string>> = {
150
150
  };
151
151
 
152
152
  /** How the guide's relative links read through the CLI, before each of its pages. */
153
- const GUIDE_LINKS =
153
+ export const GUIDE_LINKS: string =
154
154
  "> Read through `mostra docs`: a link to `references/<name>.md` is `mostra docs guide/<name>`, `assets/<file>` is `mostra docs guide/<file>`, and `assets/examples/<name>/` is `mostra docs guide/examples/<name>`.";
155
155
 
156
+ /** The same for the guide read through `mostra mcp` (D164): topics of `docs_search`, or resources. */
157
+ export const MCP_GUIDE_LINKS: string =
158
+ "> Read through Mostra's MCP server: a link to `references/<name>.md` is the topic `guide/<name>`, `assets/<file>` is `guide/<file>`, and `assets/examples/<name>/` is `guide/examples/<name>`; read one with docs_search (`topic`) or the resource `mostra://docs/<topic>`. Where the guide runs a `mostra` command, use the tool of the same step (artifact_verify for `mostra verify`, artifact_wait for `mostra wait`).";
159
+
156
160
  /**
157
- * A topic's Markdown. A guide page loses its frontmatter and says how its links read through the
158
- * CLI; a guide topic made of files shows each one as code under its path.
161
+ * A topic's Markdown. A guide page loses its frontmatter and says how its links read (through the
162
+ * CLI by default, or `links`); a guide topic made of files shows each one as code under its path.
159
163
  */
160
- export function topicMarkdown(topic: DocsTopic, dir: string = skillDir()): string {
164
+ export function topicMarkdown(
165
+ topic: DocsTopic,
166
+ dir: string = skillDir(),
167
+ links: string = GUIDE_LINKS,
168
+ ): string {
161
169
  if (topic.files !== undefined) {
162
170
  const parts = topic.files.map((path) => {
163
171
  const text = readFileSync(join(dir, "assets", path), "utf8");
@@ -165,11 +173,11 @@ export function topicMarkdown(topic: DocsTopic, dir: string = skillDir()): strin
165
173
  const body = text.endsWith("\n") ? text : `${text}\n`;
166
174
  return `## \`${path}\`\n\n${fence}${FENCE_LANGUAGES[extname(path)] ?? ""}\n${body}${fence}\n`;
167
175
  });
168
- return [`# ${topic.title}`, "", GUIDE_LINKS, "", ...parts].join("\n");
176
+ return [`# ${topic.title}`, "", links, "", ...parts].join("\n");
169
177
  }
170
178
  const text = readFileSync(topic.file, "utf8");
171
179
  if (topic.topic !== "guide" && !topic.topic.startsWith("guide/")) return text;
172
- return [GUIDE_LINKS, "", text.replace(/^---\n[\s\S]*?\n---\n+/, "")].join("\n");
180
+ return [links, "", text.replace(/^---\n[\s\S]*?\n---\n+/, "")].join("\n");
173
181
  }
174
182
 
175
183
  /** The index as Markdown: what `mostra docs` prints without a topic. */
package/src/exit.ts CHANGED
@@ -59,6 +59,8 @@ const BY_AREA: Readonly<Record<DiagnosticArea, ExitCode>> = {
59
59
  PLATFORM: EXIT.environment,
60
60
  ARTIFACT: EXIT.failure,
61
61
  CLI: EXIT.usage,
62
+ // A remote server or the link to one: the environment, like a share's tunnel (D165).
63
+ REMOTE: EXIT.environment,
62
64
  };
63
65
 
64
66
  /** Codes whose exit code isn't their area's. */
package/src/help.ts CHANGED
@@ -41,7 +41,7 @@ function flagLine(flag: FlagDef): string {
41
41
  }
42
42
 
43
43
  /** Commands that run until their connection or Ctrl-C ends them: `--timeout` doesn't bound them. */
44
- export const UNBOUNDED: ReadonlySet<string> = new Set(["host", "dev"]);
44
+ export const UNBOUNDED: ReadonlySet<string> = new Set(["host", "dev", "mcp"]);
45
45
 
46
46
  /**
47
47
  * The global flags a command doesn't define again (`wait --timeout` is the wait's own); a command