@mostra/cli 0.11.0 → 0.13.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-_iCl_HaO.js → bootstrap-3_Tdfdg7.js} +3 -2
- package/dist/bootstrap-3_Tdfdg7.js.map +1 -0
- package/dist/bootstrap-C9a2gSWf.js +1 -0
- package/dist/{flush-D648gCYs.js → flush-TPaIdwjy.js} +2 -1
- package/dist/flush-TPaIdwjy.js.map +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/reference/cli.md +112 -2
- package/dist/reference/diagnostics.json +29 -2
- package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +2 -2
- package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
- package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
- package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
- package/dist/reference/self-hosting.md +1 -1
- package/dist/{run-BxYL-DaX.js → run-CtR0PFMj.js} +248 -19
- package/dist/run-CtR0PFMj.js.map +1 -0
- package/dist/run-NWeQcyh9.js +1 -0
- package/dist/skill/SKILL.md +5 -3
- package/dist/skill/references/answers.md +3 -1
- package/dist/skill/references/mcp.md +2 -2
- package/dist/skill/references/teams.md +78 -0
- package/dist/telemetry/flush-main.js +1 -1
- package/package.json +5 -5
- package/src/commands/index.ts +4 -0
- package/src/commands/interaction.ts +43 -2
- package/src/commands/sharing.ts +19 -1
- package/src/commands/team.ts +191 -0
- package/src/detached.ts +1 -0
- package/src/exit.ts +2 -0
- package/dist/bootstrap-BStzS_41.js +0 -1
- package/dist/bootstrap-_iCl_HaO.js.map +0 -1
- package/dist/flush-D648gCYs.js.map +0 -1
- package/dist/run-Bpg_ZRY8.js +0 -1
- package/dist/run-BxYL-DaX.js.map +0 -1
package/dist/run-BxYL-DaX.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"run-BxYL-DaX.js","names":["docsIndex","indexOf","docsIndex","line"],"sources":["../src/docs.ts","../src/home.ts","../src/platform.ts","../src/telemetry/zones.generated.ts","../src/telemetry/timezone.ts","../src/telemetry/words.ts","../src/telemetry/index.ts","../src/commands/shared.ts","../src/commands/admin.ts","../src/commands/authoring.ts","../src/commands/dev.ts","../src/commands/interaction.ts","../src/browser.ts","../src/client.ts","../src/mcp.ts","../src/commands/mcp.ts","../src/commands/remote.ts","../src/commands/sharing.ts","../src/commands/viewing.ts","../src/commands/index.ts","../src/help.ts","../src/run.ts"],"sourcesContent":["/**\n * `mostra docs` (D140 item 17): the reference that ships with the CLI, by stable slug. The\n * diagnostic pages are keyed by code (`mostra docs MOSTRA_DEP_MISSING`, as hints say), beside the\n * CLI reference and the telemetry page. The Agent Skill (`skills/mostra/`, WP-14) is in it too, as\n * `guide` and `guide/<name>`, so an agent whose harness has no Skill reads the same text through\n * the CLI. This index is the one source WP-15's `docs_search` and WP-26's site read.\n */\nimport { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { type DocsTopic, docsIndex as indexOf } from \"@mostra/mcp\";\nimport { fromSource, packageRoot } from \"./version.ts\";\n\n/** Where the reference is: bundled in the build (`dist/reference`), or the repository's. */\nexport function referenceDir(): string {\n const bundled = join(packageRoot(), \"dist\", \"reference\");\n return !fromSource() && existsSync(bundled)\n ? bundled\n : join(packageRoot(), \"..\", \"..\", \"docs\", \"reference\");\n}\n\n/** Where the Agent Skill is: bundled in the build (`dist/skill`), or the repository's. */\nexport function skillDir(): string {\n const bundled = join(packageRoot(), \"dist\", \"skill\");\n return !fromSource() && existsSync(bundled)\n ? bundled\n : join(packageRoot(), \"..\", \"..\", \"skills\", \"mostra\");\n}\n\n/** Every topic of the reference this CLI ships, the pages first and then the codes, sorted. */\nexport function docsIndex(dir: string = referenceDir()): DocsTopic[] {\n return indexOf(dir, skillDir());\n}\n\nexport {\n type DocsTopic,\n indexMarkdown,\n MCP_GUIDE_LINKS,\n nearestTopics,\n topicMarkdown,\n} from \"@mostra/mcp\";\n","/**\n * Where the CLI's things are: the home (D84's order), the runtime it starts, the home's settings\n * it reads, and the CLI's own config directory (D140 item 5). Resolving a path never touches the\n * file system; the runtime owns everything inside the home.\n */\nimport { readFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { isAbsolute, join, resolve, win32 } from \"node:path\";\nimport { type Runtime, resolveRuntime } from \"@mostra/sdk\";\n\n/** The environment the CLI reads. */\nexport type Environment = Readonly<Record<string, string | undefined>>;\n\nconst nonEmpty = (value: string | undefined): string | undefined =>\n value === undefined || value === \"\" ? undefined : value;\n\n/**\n * The home, in D84's order: `--home`, then `MOSTRA_HOME`, then the platform default (`~/.mostra`\n * on macOS, `${XDG_DATA_HOME:-~/.local/share}/mostra` on Linux, `%LOCALAPPDATA%\\mostra` on\n * Windows), the same order and defaults the runtime uses (its `platform` module).\n */\nexport function resolveHome(options: {\n readonly home?: string | undefined;\n readonly env: Environment;\n readonly cwd: string;\n readonly platform?: string;\n}): string {\n const chosen = nonEmpty(options.home) ?? nonEmpty(options.env[\"MOSTRA_HOME\"]);\n if (chosen !== undefined) return resolve(options.cwd, chosen);\n const platform = options.platform ?? process.platform;\n if (platform === \"win32\") {\n // As the runtime: the user's profile from the system, never a `HOME` a POSIX shell set.\n const local = nonEmpty(options.env[\"LOCALAPPDATA\"]);\n return win32.join(\n local !== undefined && win32.isAbsolute(local)\n ? local\n : win32.join(homedir(), \"AppData\", \"Local\"),\n \"mostra\",\n );\n }\n const user = nonEmpty(options.env[\"HOME\"]) ?? homedir();\n if (platform === \"darwin\") return join(user, \".mostra\");\n const data = nonEmpty(options.env[\"XDG_DATA_HOME\"]);\n return join(\n data !== undefined && isAbsolute(data) ? data : join(user, \".local\", \"share\"),\n \"mostra\",\n );\n}\n\n/**\n * The CLI's config directory (D140 item 5): `MOSTRA_CONFIG_DIR`, else\n * `${XDG_CONFIG_HOME:-~/.config}/mostra` on macOS and Linux, and `%APPDATA%\\mostra` on Windows,\n * where per-user settings live (D151). It holds telemetry's choice and queue, per\n * operating-system user, never per home.\n */\nexport function configDir(\n env: Environment,\n cwd: string,\n platform: string = process.platform,\n): string {\n const override = nonEmpty(env[\"MOSTRA_CONFIG_DIR\"]);\n if (override !== undefined) return resolve(cwd, override);\n if (platform === \"win32\") {\n const roaming = nonEmpty(env[\"APPDATA\"]);\n return win32.join(\n roaming !== undefined && win32.isAbsolute(roaming)\n ? roaming\n : win32.join(homedir(), \"AppData\", \"Roaming\"),\n \"mostra\",\n );\n }\n const xdg = nonEmpty(env[\"XDG_CONFIG_HOME\"]);\n const base =\n xdg !== undefined && isAbsolute(xdg)\n ? xdg\n : join(nonEmpty(env[\"HOME\"]) ?? homedir(), \".config\");\n return join(base, \"mostra\");\n}\n\n/** The runtime the CLI starts: its Node.js and its `mostra-runtime` entry. */\nexport interface RuntimeLocation {\n /** The Node.js to run it with: the runtime bundle's own, or this process's for a checkout. */\n readonly node: string;\n /** `mostra-runtime`'s entry. */\n readonly entry: string;\n /** The runtime as the SDK resolved it (its bundle, for the Windows helper beside it). */\n readonly runtime: Runtime;\n}\n\n/**\n * The runtime the CLI starts (D85, RT-01), found as the SDK finds it: `MOSTRA_BUNDLE`,\n * `MOSTRA_RUNTIME_BIN`, the runtime bundle this CLI sits in, its release's pinned bundle, or a\n * development checkout's built runtime beside it. The bootstrap (`bootstrap.ts`) has already moved\n * a CLI installed from npm into its pinned bundle, so this downloads nothing, except under\n * `mostra mcp`, which serves before the bundle is there and installs it itself (D164 item 7), so\n * this finds it installed. Throws the SDK's diagnostic when there is none.\n */\nexport async function locateRuntime(env: Environment): Promise<RuntimeLocation> {\n const runtime = await resolveRuntime({ env });\n return { node: runtime.node, entry: runtime.runtimeEntry, runtime };\n}\n\n/** What the CLI reads of a home's `config.json` (DATA_MODEL §1). */\nexport interface HomeMarks {\n /** The first host that configured the home (D140 item 4), if any. */\n readonly hostConfigured?: { readonly client: string; readonly at: string };\n /** Whether the file couldn't be read as settings: the CLI then treats the home as a host's. */\n readonly unreadable?: true;\n}\n\n/**\n * Whether the CLI treats the home as a host's, which sends no telemetry (D140 item 4): a host\n * marked it, or its `config.json` can't be read as settings (fail closed). One rule for the\n * runner and for `mostra telemetry` (Opus review finding 6).\n */\nexport function embeddedHome(marks: HomeMarks): boolean {\n return marks.hostConfigured !== undefined || marks.unreadable === true;\n}\n\n/**\n * The home's host mark, read from `config.json` without the instance, for commands that never\n * reach one. A file that can't be read as JSON counts as a host's home, so telemetry fails closed.\n */\nexport function readHomeMarks(home: string): HomeMarks {\n let text: string;\n try {\n text = readFileSync(join(home, \"config.json\"), \"utf8\");\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ENOENT\" ? {} : { unreadable: true };\n }\n try {\n const data = JSON.parse(text) as { hostConfigured?: { client?: unknown; at?: unknown } };\n const mark = data.hostConfigured;\n if (mark === undefined) return {};\n return typeof mark.client === \"string\" && typeof mark.at === \"string\"\n ? { hostConfigured: { client: mark.client, at: mark.at } }\n : { unreadable: true };\n } catch {\n return { unreadable: true };\n }\n}\n","/**\n * The CLI's platform gate (D35, D146, RT-07), the runtime's rule (`home/platform.ts` in\n * `@mostra/runtime`) repeated where the CLI must decide before it reaches any runtime: macOS,\n * Linux and Windows on x64 and arm64; everything else fails closed.\n */\nimport { createDiagnostic, type Diagnostic } from \"@mostra/protocol\";\n\n/** `MOSTRA_PLATFORM_UNSUPPORTED` for a platform Mostra doesn't run on, else `undefined`. */\nexport function checkPlatform(platform: string, arch: string): Diagnostic | undefined {\n const supported = platform === \"darwin\" || platform === \"linux\" || platform === \"win32\";\n if (supported && (arch === \"x64\" || arch === \"arm64\")) return undefined;\n const name = platform === \"win32\" ? `Windows (${platform}-${arch})` : `${platform}-${arch}`;\n return createDiagnostic(\"MOSTRA_PLATFORM_UNSUPPORTED\", {\n message: `Mostra doesn't run on ${name}; it supports macOS, Linux and Windows on x64 and arm64.`,\n });\n}\n","// Generated by scripts/ask-first-zones.ts from tzdata 2026e (data/tzdata/). Don't edit.\n\n/** The tzdata release the zones come from (VERIFIED_FACTS, WP-10). */\nexport const TZDATA_VERSION = \"2026e\";\n\n/** The time zones where Mostra asks before sending telemetry (D140 item 10), matched as given. */\nexport const ASK_FIRST_ZONES: readonly string[] = [\n \"Africa/Ceuta\",\n \"America/Cayenne\",\n \"America/Guadeloupe\",\n \"America/Marigot\",\n \"America/Martinique\",\n \"Arctic/Longyearbyen\",\n \"Asia/Famagusta\",\n \"Asia/Nicosia\",\n \"Atlantic/Azores\",\n \"Atlantic/Canary\",\n \"Atlantic/Faeroe\",\n \"Atlantic/Faroe\",\n \"Atlantic/Jan_Mayen\",\n \"Atlantic/Madeira\",\n \"Atlantic/Reykjavik\",\n \"CET\",\n \"EET\",\n \"Eire\",\n \"Etc/GMT\",\n \"Etc/GMT+0\",\n \"Etc/GMT+1\",\n \"Etc/GMT+10\",\n \"Etc/GMT+11\",\n \"Etc/GMT+12\",\n \"Etc/GMT+2\",\n \"Etc/GMT+3\",\n \"Etc/GMT+4\",\n \"Etc/GMT+5\",\n \"Etc/GMT+6\",\n \"Etc/GMT+7\",\n \"Etc/GMT+8\",\n \"Etc/GMT+9\",\n \"Etc/GMT-0\",\n \"Etc/GMT-1\",\n \"Etc/GMT-10\",\n \"Etc/GMT-11\",\n \"Etc/GMT-12\",\n \"Etc/GMT-13\",\n \"Etc/GMT-14\",\n \"Etc/GMT-2\",\n \"Etc/GMT-3\",\n \"Etc/GMT-4\",\n \"Etc/GMT-5\",\n \"Etc/GMT-6\",\n \"Etc/GMT-7\",\n \"Etc/GMT-8\",\n \"Etc/GMT-9\",\n \"Etc/GMT0\",\n \"Etc/Greenwich\",\n \"Etc/UCT\",\n \"Etc/UTC\",\n \"Etc/Universal\",\n \"Etc/Zulu\",\n \"Europe/Amsterdam\",\n \"Europe/Andorra\",\n \"Europe/Athens\",\n \"Europe/Belfast\",\n \"Europe/Berlin\",\n \"Europe/Bratislava\",\n \"Europe/Brussels\",\n \"Europe/Bucharest\",\n \"Europe/Budapest\",\n \"Europe/Busingen\",\n \"Europe/Copenhagen\",\n \"Europe/Dublin\",\n \"Europe/Gibraltar\",\n \"Europe/Guernsey\",\n \"Europe/Helsinki\",\n \"Europe/Isle_of_Man\",\n \"Europe/Jersey\",\n \"Europe/Lisbon\",\n \"Europe/Ljubljana\",\n \"Europe/London\",\n \"Europe/Luxembourg\",\n \"Europe/Madrid\",\n \"Europe/Malta\",\n \"Europe/Mariehamn\",\n \"Europe/Monaco\",\n \"Europe/Nicosia\",\n \"Europe/Oslo\",\n \"Europe/Paris\",\n \"Europe/Prague\",\n \"Europe/Riga\",\n \"Europe/Rome\",\n \"Europe/San_Marino\",\n \"Europe/Sofia\",\n \"Europe/Stockholm\",\n \"Europe/Tallinn\",\n \"Europe/Vaduz\",\n \"Europe/Vatican\",\n \"Europe/Vienna\",\n \"Europe/Vilnius\",\n \"Europe/Warsaw\",\n \"Europe/Zagreb\",\n \"Europe/Zurich\",\n \"Factory\",\n \"GB\",\n \"GB-Eire\",\n \"GMT\",\n \"GMT+0\",\n \"GMT-0\",\n \"GMT0\",\n \"Greenwich\",\n \"Iceland\",\n \"Indian/Mayotte\",\n \"Indian/Reunion\",\n \"MET\",\n \"Poland\",\n \"Portugal\",\n \"UCT\",\n \"UTC\",\n \"Universal\",\n \"WET\",\n \"Zulu\",\n];\n\n/** Every zone name tzdata 2026e knows; anything else is an unknown zone. */\nexport const KNOWN_ZONES: readonly string[] = [\n \"Africa/Abidjan\",\n \"Africa/Accra\",\n \"Africa/Addis_Ababa\",\n \"Africa/Algiers\",\n \"Africa/Asmara\",\n \"Africa/Asmera\",\n \"Africa/Bamako\",\n \"Africa/Bangui\",\n \"Africa/Banjul\",\n \"Africa/Bissau\",\n \"Africa/Blantyre\",\n \"Africa/Brazzaville\",\n \"Africa/Bujumbura\",\n \"Africa/Cairo\",\n \"Africa/Casablanca\",\n \"Africa/Ceuta\",\n \"Africa/Conakry\",\n \"Africa/Dakar\",\n \"Africa/Dar_es_Salaam\",\n \"Africa/Djibouti\",\n \"Africa/Douala\",\n \"Africa/El_Aaiun\",\n \"Africa/Freetown\",\n \"Africa/Gaborone\",\n \"Africa/Harare\",\n \"Africa/Johannesburg\",\n \"Africa/Juba\",\n \"Africa/Kampala\",\n \"Africa/Khartoum\",\n \"Africa/Kigali\",\n \"Africa/Kinshasa\",\n \"Africa/Lagos\",\n \"Africa/Libreville\",\n \"Africa/Lome\",\n \"Africa/Luanda\",\n \"Africa/Lubumbashi\",\n \"Africa/Lusaka\",\n \"Africa/Malabo\",\n \"Africa/Maputo\",\n \"Africa/Maseru\",\n \"Africa/Mbabane\",\n \"Africa/Mogadishu\",\n \"Africa/Monrovia\",\n \"Africa/Nairobi\",\n \"Africa/Ndjamena\",\n \"Africa/Niamey\",\n \"Africa/Nouakchott\",\n \"Africa/Ouagadougou\",\n \"Africa/Porto-Novo\",\n \"Africa/Sao_Tome\",\n \"Africa/Timbuktu\",\n \"Africa/Tripoli\",\n \"Africa/Tunis\",\n \"Africa/Windhoek\",\n \"America/Adak\",\n \"America/Anchorage\",\n \"America/Anguilla\",\n \"America/Antigua\",\n \"America/Araguaina\",\n \"America/Argentina/Buenos_Aires\",\n \"America/Argentina/Catamarca\",\n \"America/Argentina/ComodRivadavia\",\n \"America/Argentina/Cordoba\",\n \"America/Argentina/Jujuy\",\n \"America/Argentina/La_Rioja\",\n \"America/Argentina/Mendoza\",\n \"America/Argentina/Rio_Gallegos\",\n \"America/Argentina/Salta\",\n \"America/Argentina/San_Juan\",\n \"America/Argentina/San_Luis\",\n \"America/Argentina/Tucuman\",\n \"America/Argentina/Ushuaia\",\n \"America/Aruba\",\n \"America/Asuncion\",\n \"America/Atikokan\",\n \"America/Atka\",\n \"America/Bahia\",\n \"America/Bahia_Banderas\",\n \"America/Barbados\",\n \"America/Belem\",\n \"America/Belize\",\n \"America/Blanc-Sablon\",\n \"America/Boa_Vista\",\n \"America/Bogota\",\n \"America/Boise\",\n \"America/Buenos_Aires\",\n \"America/Cambridge_Bay\",\n \"America/Campo_Grande\",\n \"America/Cancun\",\n \"America/Caracas\",\n \"America/Catamarca\",\n \"America/Cayenne\",\n \"America/Cayman\",\n \"America/Chicago\",\n \"America/Chihuahua\",\n \"America/Ciudad_Juarez\",\n \"America/Coral_Harbour\",\n \"America/Cordoba\",\n \"America/Costa_Rica\",\n \"America/Coyhaique\",\n \"America/Creston\",\n \"America/Cuiaba\",\n \"America/Curacao\",\n \"America/Danmarkshavn\",\n \"America/Dawson\",\n \"America/Dawson_Creek\",\n \"America/Denver\",\n \"America/Detroit\",\n \"America/Dominica\",\n \"America/Edmonton\",\n \"America/Eirunepe\",\n \"America/El_Salvador\",\n \"America/Ensenada\",\n \"America/Fort_Nelson\",\n \"America/Fort_Wayne\",\n \"America/Fortaleza\",\n \"America/Glace_Bay\",\n \"America/Godthab\",\n \"America/Goose_Bay\",\n \"America/Grand_Turk\",\n \"America/Grenada\",\n \"America/Guadeloupe\",\n \"America/Guatemala\",\n \"America/Guayaquil\",\n \"America/Guyana\",\n \"America/Halifax\",\n \"America/Havana\",\n \"America/Hermosillo\",\n \"America/Indiana/Indianapolis\",\n \"America/Indiana/Knox\",\n \"America/Indiana/Marengo\",\n \"America/Indiana/Petersburg\",\n \"America/Indiana/Tell_City\",\n \"America/Indiana/Vevay\",\n \"America/Indiana/Vincennes\",\n \"America/Indiana/Winamac\",\n \"America/Indianapolis\",\n \"America/Inuvik\",\n \"America/Iqaluit\",\n \"America/Jamaica\",\n \"America/Jujuy\",\n \"America/Juneau\",\n \"America/Kentucky/Louisville\",\n \"America/Kentucky/Monticello\",\n \"America/Knox_IN\",\n \"America/Kralendijk\",\n \"America/La_Paz\",\n \"America/Lima\",\n \"America/Los_Angeles\",\n \"America/Louisville\",\n \"America/Lower_Princes\",\n \"America/Maceio\",\n \"America/Managua\",\n \"America/Manaus\",\n \"America/Marigot\",\n \"America/Martinique\",\n \"America/Matamoros\",\n \"America/Mazatlan\",\n \"America/Mendoza\",\n \"America/Menominee\",\n \"America/Merida\",\n \"America/Metlakatla\",\n \"America/Mexico_City\",\n \"America/Miquelon\",\n \"America/Moncton\",\n \"America/Monterrey\",\n \"America/Montevideo\",\n \"America/Montreal\",\n \"America/Montserrat\",\n \"America/Nassau\",\n \"America/New_York\",\n \"America/Nipigon\",\n \"America/Nome\",\n \"America/Noronha\",\n \"America/North_Dakota/Beulah\",\n \"America/North_Dakota/Center\",\n \"America/North_Dakota/New_Salem\",\n \"America/Nuuk\",\n \"America/Ojinaga\",\n \"America/Panama\",\n \"America/Pangnirtung\",\n \"America/Paramaribo\",\n \"America/Phoenix\",\n \"America/Port-au-Prince\",\n \"America/Port_of_Spain\",\n \"America/Porto_Acre\",\n \"America/Porto_Velho\",\n \"America/Puerto_Rico\",\n \"America/Punta_Arenas\",\n \"America/Rainy_River\",\n \"America/Rankin_Inlet\",\n \"America/Recife\",\n \"America/Regina\",\n \"America/Resolute\",\n \"America/Rio_Branco\",\n \"America/Rosario\",\n \"America/Santa_Isabel\",\n \"America/Santarem\",\n \"America/Santiago\",\n \"America/Santo_Domingo\",\n \"America/Sao_Paulo\",\n \"America/Scoresbysund\",\n \"America/Shiprock\",\n \"America/Sitka\",\n \"America/St_Barthelemy\",\n \"America/St_Johns\",\n \"America/St_Kitts\",\n \"America/St_Lucia\",\n \"America/St_Thomas\",\n \"America/St_Vincent\",\n \"America/Swift_Current\",\n \"America/Tegucigalpa\",\n \"America/Thule\",\n \"America/Thunder_Bay\",\n \"America/Tijuana\",\n \"America/Toronto\",\n \"America/Tortola\",\n \"America/Vancouver\",\n \"America/Virgin\",\n \"America/Whitehorse\",\n \"America/Winnipeg\",\n \"America/Yakutat\",\n \"America/Yellowknife\",\n \"Antarctica/Casey\",\n \"Antarctica/Davis\",\n \"Antarctica/DumontDUrville\",\n \"Antarctica/Macquarie\",\n \"Antarctica/Mawson\",\n \"Antarctica/McMurdo\",\n \"Antarctica/Palmer\",\n \"Antarctica/Rothera\",\n \"Antarctica/South_Pole\",\n \"Antarctica/Syowa\",\n \"Antarctica/Troll\",\n \"Antarctica/Vostok\",\n \"Arctic/Longyearbyen\",\n \"Asia/Aden\",\n \"Asia/Almaty\",\n \"Asia/Amman\",\n \"Asia/Anadyr\",\n \"Asia/Aqtau\",\n \"Asia/Aqtobe\",\n \"Asia/Ashgabat\",\n \"Asia/Ashkhabad\",\n \"Asia/Atyrau\",\n \"Asia/Baghdad\",\n \"Asia/Bahrain\",\n \"Asia/Baku\",\n \"Asia/Bangkok\",\n \"Asia/Barnaul\",\n \"Asia/Beirut\",\n \"Asia/Bishkek\",\n \"Asia/Brunei\",\n \"Asia/Calcutta\",\n \"Asia/Chita\",\n \"Asia/Choibalsan\",\n \"Asia/Chongqing\",\n \"Asia/Chungking\",\n \"Asia/Colombo\",\n \"Asia/Dacca\",\n \"Asia/Damascus\",\n \"Asia/Dhaka\",\n \"Asia/Dili\",\n \"Asia/Dubai\",\n \"Asia/Dushanbe\",\n \"Asia/Famagusta\",\n \"Asia/Gaza\",\n \"Asia/Harbin\",\n \"Asia/Hebron\",\n \"Asia/Ho_Chi_Minh\",\n \"Asia/Hong_Kong\",\n \"Asia/Hovd\",\n \"Asia/Irkutsk\",\n \"Asia/Istanbul\",\n \"Asia/Jakarta\",\n \"Asia/Jayapura\",\n \"Asia/Jerusalem\",\n \"Asia/Kabul\",\n \"Asia/Kamchatka\",\n \"Asia/Karachi\",\n \"Asia/Kashgar\",\n \"Asia/Kathmandu\",\n \"Asia/Katmandu\",\n \"Asia/Khandyga\",\n \"Asia/Kolkata\",\n \"Asia/Krasnoyarsk\",\n \"Asia/Kuala_Lumpur\",\n \"Asia/Kuching\",\n \"Asia/Kuwait\",\n \"Asia/Macao\",\n \"Asia/Macau\",\n \"Asia/Magadan\",\n \"Asia/Makassar\",\n \"Asia/Manila\",\n \"Asia/Muscat\",\n \"Asia/Nicosia\",\n \"Asia/Novokuznetsk\",\n \"Asia/Novosibirsk\",\n \"Asia/Omsk\",\n \"Asia/Oral\",\n \"Asia/Phnom_Penh\",\n \"Asia/Pontianak\",\n \"Asia/Pyongyang\",\n \"Asia/Qatar\",\n \"Asia/Qostanay\",\n \"Asia/Qyzylorda\",\n \"Asia/Rangoon\",\n \"Asia/Riyadh\",\n \"Asia/Saigon\",\n \"Asia/Sakhalin\",\n \"Asia/Samarkand\",\n \"Asia/Seoul\",\n \"Asia/Shanghai\",\n \"Asia/Singapore\",\n \"Asia/Srednekolymsk\",\n \"Asia/Taipei\",\n \"Asia/Tashkent\",\n \"Asia/Tbilisi\",\n \"Asia/Tehran\",\n \"Asia/Tel_Aviv\",\n \"Asia/Thimbu\",\n \"Asia/Thimphu\",\n \"Asia/Tokyo\",\n \"Asia/Tomsk\",\n \"Asia/Ujung_Pandang\",\n \"Asia/Ulaanbaatar\",\n \"Asia/Ulan_Bator\",\n \"Asia/Urumqi\",\n \"Asia/Ust-Nera\",\n \"Asia/Vientiane\",\n \"Asia/Vladivostok\",\n \"Asia/Yakutsk\",\n \"Asia/Yangon\",\n \"Asia/Yekaterinburg\",\n \"Asia/Yerevan\",\n \"Atlantic/Azores\",\n \"Atlantic/Bermuda\",\n \"Atlantic/Canary\",\n \"Atlantic/Cape_Verde\",\n \"Atlantic/Faeroe\",\n \"Atlantic/Faroe\",\n \"Atlantic/Jan_Mayen\",\n \"Atlantic/Madeira\",\n \"Atlantic/Reykjavik\",\n \"Atlantic/South_Georgia\",\n \"Atlantic/St_Helena\",\n \"Atlantic/Stanley\",\n \"Australia/ACT\",\n \"Australia/Adelaide\",\n \"Australia/Brisbane\",\n \"Australia/Broken_Hill\",\n \"Australia/Canberra\",\n \"Australia/Currie\",\n \"Australia/Darwin\",\n \"Australia/Eucla\",\n \"Australia/Hobart\",\n \"Australia/LHI\",\n \"Australia/Lindeman\",\n \"Australia/Lord_Howe\",\n \"Australia/Melbourne\",\n \"Australia/NSW\",\n \"Australia/North\",\n \"Australia/Perth\",\n \"Australia/Queensland\",\n \"Australia/South\",\n \"Australia/Sydney\",\n \"Australia/Tasmania\",\n \"Australia/Victoria\",\n \"Australia/West\",\n \"Australia/Yancowinna\",\n \"Brazil/Acre\",\n \"Brazil/DeNoronha\",\n \"Brazil/East\",\n \"Brazil/West\",\n \"CET\",\n \"Canada/Atlantic\",\n \"Canada/Central\",\n \"Canada/Eastern\",\n \"Canada/Mountain\",\n \"Canada/Newfoundland\",\n \"Canada/Pacific\",\n \"Canada/Saskatchewan\",\n \"Canada/Yukon\",\n \"Chile/Continental\",\n \"Chile/EasterIsland\",\n \"Cuba\",\n \"EET\",\n \"EST\",\n \"Egypt\",\n \"Eire\",\n \"Etc/GMT\",\n \"Etc/GMT+0\",\n \"Etc/GMT+1\",\n \"Etc/GMT+10\",\n \"Etc/GMT+11\",\n \"Etc/GMT+12\",\n \"Etc/GMT+2\",\n \"Etc/GMT+3\",\n \"Etc/GMT+4\",\n \"Etc/GMT+5\",\n \"Etc/GMT+6\",\n \"Etc/GMT+7\",\n \"Etc/GMT+8\",\n \"Etc/GMT+9\",\n \"Etc/GMT-0\",\n \"Etc/GMT-1\",\n \"Etc/GMT-10\",\n \"Etc/GMT-11\",\n \"Etc/GMT-12\",\n \"Etc/GMT-13\",\n \"Etc/GMT-14\",\n \"Etc/GMT-2\",\n \"Etc/GMT-3\",\n \"Etc/GMT-4\",\n \"Etc/GMT-5\",\n \"Etc/GMT-6\",\n \"Etc/GMT-7\",\n \"Etc/GMT-8\",\n \"Etc/GMT-9\",\n \"Etc/GMT0\",\n \"Etc/Greenwich\",\n \"Etc/UCT\",\n \"Etc/UTC\",\n \"Etc/Universal\",\n \"Etc/Zulu\",\n \"Europe/Amsterdam\",\n \"Europe/Andorra\",\n \"Europe/Astrakhan\",\n \"Europe/Athens\",\n \"Europe/Belfast\",\n \"Europe/Belgrade\",\n \"Europe/Berlin\",\n \"Europe/Bratislava\",\n \"Europe/Brussels\",\n \"Europe/Bucharest\",\n \"Europe/Budapest\",\n \"Europe/Busingen\",\n \"Europe/Chisinau\",\n \"Europe/Copenhagen\",\n \"Europe/Dublin\",\n \"Europe/Gibraltar\",\n \"Europe/Guernsey\",\n \"Europe/Helsinki\",\n \"Europe/Isle_of_Man\",\n \"Europe/Istanbul\",\n \"Europe/Jersey\",\n \"Europe/Kaliningrad\",\n \"Europe/Kiev\",\n \"Europe/Kirov\",\n \"Europe/Kyiv\",\n \"Europe/Lisbon\",\n \"Europe/Ljubljana\",\n \"Europe/London\",\n \"Europe/Luxembourg\",\n \"Europe/Madrid\",\n \"Europe/Malta\",\n \"Europe/Mariehamn\",\n \"Europe/Minsk\",\n \"Europe/Monaco\",\n \"Europe/Moscow\",\n \"Europe/Nicosia\",\n \"Europe/Oslo\",\n \"Europe/Paris\",\n \"Europe/Podgorica\",\n \"Europe/Prague\",\n \"Europe/Riga\",\n \"Europe/Rome\",\n \"Europe/Samara\",\n \"Europe/San_Marino\",\n \"Europe/Sarajevo\",\n \"Europe/Saratov\",\n \"Europe/Simferopol\",\n \"Europe/Skopje\",\n \"Europe/Sofia\",\n \"Europe/Stockholm\",\n \"Europe/Tallinn\",\n \"Europe/Tirane\",\n \"Europe/Tiraspol\",\n \"Europe/Ulyanovsk\",\n \"Europe/Uzhgorod\",\n \"Europe/Vaduz\",\n \"Europe/Vatican\",\n \"Europe/Vienna\",\n \"Europe/Vilnius\",\n \"Europe/Volgograd\",\n \"Europe/Warsaw\",\n \"Europe/Zagreb\",\n \"Europe/Zaporozhye\",\n \"Europe/Zurich\",\n \"Factory\",\n \"GB\",\n \"GB-Eire\",\n \"GMT\",\n \"GMT+0\",\n \"GMT-0\",\n \"GMT0\",\n \"Greenwich\",\n \"HST\",\n \"Hongkong\",\n \"Iceland\",\n \"Indian/Antananarivo\",\n \"Indian/Chagos\",\n \"Indian/Christmas\",\n \"Indian/Cocos\",\n \"Indian/Comoro\",\n \"Indian/Kerguelen\",\n \"Indian/Mahe\",\n \"Indian/Maldives\",\n \"Indian/Mauritius\",\n \"Indian/Mayotte\",\n \"Indian/Reunion\",\n \"Iran\",\n \"Israel\",\n \"Jamaica\",\n \"Japan\",\n \"Kwajalein\",\n \"Libya\",\n \"MET\",\n \"MST\",\n \"Mexico/BajaNorte\",\n \"Mexico/BajaSur\",\n \"Mexico/General\",\n \"NZ\",\n \"NZ-CHAT\",\n \"Navajo\",\n \"PRC\",\n \"Pacific/Apia\",\n \"Pacific/Auckland\",\n \"Pacific/Bougainville\",\n \"Pacific/Chatham\",\n \"Pacific/Chuuk\",\n \"Pacific/Easter\",\n \"Pacific/Efate\",\n \"Pacific/Enderbury\",\n \"Pacific/Fakaofo\",\n \"Pacific/Fiji\",\n \"Pacific/Funafuti\",\n \"Pacific/Galapagos\",\n \"Pacific/Gambier\",\n \"Pacific/Guadalcanal\",\n \"Pacific/Guam\",\n \"Pacific/Honolulu\",\n \"Pacific/Johnston\",\n \"Pacific/Kanton\",\n \"Pacific/Kiritimati\",\n \"Pacific/Kosrae\",\n \"Pacific/Kwajalein\",\n \"Pacific/Majuro\",\n \"Pacific/Marquesas\",\n \"Pacific/Midway\",\n \"Pacific/Nauru\",\n \"Pacific/Niue\",\n \"Pacific/Norfolk\",\n \"Pacific/Noumea\",\n \"Pacific/Pago_Pago\",\n \"Pacific/Palau\",\n \"Pacific/Pitcairn\",\n \"Pacific/Pohnpei\",\n \"Pacific/Ponape\",\n \"Pacific/Port_Moresby\",\n \"Pacific/Rarotonga\",\n \"Pacific/Saipan\",\n \"Pacific/Samoa\",\n \"Pacific/Tahiti\",\n \"Pacific/Tarawa\",\n \"Pacific/Tongatapu\",\n \"Pacific/Truk\",\n \"Pacific/Wake\",\n \"Pacific/Wallis\",\n \"Pacific/Yap\",\n \"Poland\",\n \"Portugal\",\n \"ROC\",\n \"ROK\",\n \"Singapore\",\n \"Turkey\",\n \"UCT\",\n \"US/Alaska\",\n \"US/Aleutian\",\n \"US/Arizona\",\n \"US/Central\",\n \"US/East-Indiana\",\n \"US/Eastern\",\n \"US/Hawaii\",\n \"US/Indiana-Starke\",\n \"US/Michigan\",\n \"US/Mountain\",\n \"US/Pacific\",\n \"US/Samoa\",\n \"UTC\",\n \"Universal\",\n \"W-SU\",\n \"WET\",\n \"Zulu\",\n];\n","/**\n * Whether this machine's time zone asks first (D140 items 2 and 10). The zone is read here, on\n * this machine, and never sent. Every candidate name counts, as given: `TZ` (a leading `:`\n * removed), the target of `/etc/localtime`, and `Intl`'s zone. A machine asks first when any of\n * them is an ask-first zone, or none is a zone tzdata knows (missing, empty, `Etc/Unknown`, a\n * POSIX rule, a typo). Names are never canonicalized: tzdata links `Europe/Zagreb` to\n * `Europe/Belgrade` and `Indian/Reunion` to `Asia/Dubai`, and ICU builds differ in what they\n * resolve.\n */\nimport { readlinkSync } from \"node:fs\";\nimport type { Environment } from \"../home.ts\";\nimport { ASK_FIRST_ZONES, KNOWN_ZONES } from \"./zones.generated.ts\";\n\nconst ASK_FIRST = new Set(ASK_FIRST_ZONES);\nconst KNOWN = new Set(KNOWN_ZONES);\n\n/** Where the zone names come from; tests replace each. */\nexport interface ZoneSources {\n readonly env: Environment;\n /** The target of `/etc/localtime`, or `undefined`. */\n readonly localtime?: () => string | undefined;\n /** `Intl.DateTimeFormat().resolvedOptions().timeZone`, which can be `undefined`. */\n readonly intl?: () => string | undefined;\n}\n\n/** The target of `/etc/localtime` after `zoneinfo/`, when it is a symbolic link. */\nfunction localtimeLink(): string | undefined {\n try {\n const target = readlinkSync(\"/etc/localtime\");\n const at = target.lastIndexOf(\"zoneinfo/\");\n return at === -1 ? undefined : target.slice(at + \"zoneinfo/\".length);\n } catch {\n return undefined;\n }\n}\n\nfunction intlZone(): string | undefined {\n try {\n const zone: unknown = Intl.DateTimeFormat().resolvedOptions().timeZone;\n return typeof zone === \"string\" ? zone : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The candidate zone names, as given (empty and missing ones dropped). */\nexport function zoneCandidates(sources: ZoneSources): string[] {\n const tz = sources.env[\"TZ\"];\n const fromTz = tz === undefined ? undefined : tz.startsWith(\":\") ? tz.slice(1) : tz;\n // Tests of the real binary name the machine's zone (`/etc/localtime`) with\n // MOSTRA_TEST_LOCALTIME, empty for none, as the runtime's MOSTRA_TEST_* hooks do; nothing else\n // reads it.\n const testLocaltime = sources.env[\"MOSTRA_TEST_LOCALTIME\"];\n const localtime =\n sources.localtime ??\n (testLocaltime !== undefined\n ? () => (testLocaltime === \"\" ? undefined : testLocaltime)\n : localtimeLink);\n const names = [fromTz, localtime(), (sources.intl ?? intlZone)()];\n return names.filter((name): name is string => typeof name === \"string\" && name.length > 0);\n}\n\n/** Whether telemetry asks first on this machine. */\nexport function asksFirst(sources: ZoneSources): boolean {\n const candidates = zoneCandidates(sources);\n if (candidates.some((name) => ASK_FIRST.has(name))) return true;\n // TZ, when set, is the zone the process runs in: an empty one (UTC under POSIX), a POSIX rule\n // or a name tzdata doesn't know is an unknown zone, so ask first.\n const tz = sources.env[\"TZ\"];\n if (tz !== undefined && !KNOWN.has(tz.startsWith(\":\") ? tz.slice(1) : tz)) return true;\n return !candidates.some((name) => KNOWN.has(name) && name !== \"Etc/Unknown\");\n}\n","/**\n * Telemetry's words to people (D140 item 11): the notice, the question, its answers and the\n * `status` lines, exactly as Mirza approved them (M28). `<docs>` is `DEFAULT_DOCS_BASE` (D37).\n */\nimport { DEFAULT_DOCS_BASE } from \"@mostra/protocol\";\n\nconst DOCS = `${DEFAULT_DOCS_BASE}/telemetry`;\n\n/** The notice where telemetry is on by default: stderr, once, before the first event. */\nexport const NOTICE_DEFAULT: string = `Mostra sends anonymous usage data to improve the CLI: the command, its\noutcome, the version, the platform, which agent ran it, and a random\ninstall ID. Never content, paths, tokens or personal data.\nDetails: ${DOCS}\nTurn it off: mostra telemetry off, or set DO_NOT_TRACK=1.\n`;\n\n/** The question in the ask-first zones, when it may be asked. */\nexport const QUESTION: string = `Mostra can send anonymous usage data to improve the CLI: the command,\nits outcome, the version, the platform, which agent ran it, and a random\ninstall ID. Never content, paths, tokens or personal data.\nDetails: ${DOCS}\nSend anonymous usage data? [y/N] `;\n\n/** The answers to the question. */\nexport const ANSWER = {\n yes: \"Telemetry is on. Turn it off any time: mostra telemetry off\\n\",\n no: \"Telemetry stays off. Turn it on any time: mostra telemetry on\\n\",\n timeout: \"No answer, so telemetry stays off. Turn it on any time: mostra telemetry on\\n\",\n} as const;\n\n/** The notice in the ask-first zones when the question can't be asked: stderr, once. */\nexport const NOTICE_ASK_FIRST: string = `Mostra can send anonymous usage data to improve the CLI: the command,\nits outcome, the version, the platform, which agent ran it, and a random\ninstall ID. Never content, paths, tokens or personal data.\nDetails: ${DOCS}\nNothing is sent unless you run: mostra telemetry on\nAn agent should ask its user before turning it on.\n`;\n\n/** `mostra telemetry on` and `off`. */\nexport const TURNED = {\n on: \"Telemetry is on. Turn it off any time: mostra telemetry off\",\n off: \"Telemetry is off. Your install ID and any unsent events were deleted.\",\n} as const;\n\n/** Why telemetry is on or off: the decision order's reasons (D140 item 3). */\nexport type TelemetryReason =\n | \"no-collector\"\n | \"embedded\"\n | \"do-not-track\"\n | \"variable\"\n | \"variable-invalid\"\n | \"setting\"\n | \"default\"\n | \"unreadable\";\n\n/** The first line of `mostra telemetry status`. */\nexport function statusLine(input: {\n readonly enabled: boolean;\n readonly reason: TelemetryReason;\n readonly askFirst: boolean;\n readonly settingsFile: string;\n}): string {\n if (input.enabled) {\n if (input.reason === \"setting\") return \"Telemetry is on: you turned it on.\";\n if (input.reason === \"variable\") return \"Telemetry is on: MOSTRA_TELEMETRY=1 is set.\";\n return \"Telemetry is on by default here. Turn it off: mostra telemetry off\";\n }\n switch (input.reason) {\n case \"setting\":\n return \"Telemetry is off: you turned it off.\";\n case \"do-not-track\":\n return \"Telemetry is off: DO_NOT_TRACK is set.\";\n case \"variable\":\n return \"Telemetry is off: MOSTRA_TELEMETRY=0 is set.\";\n case \"variable-invalid\":\n return \"Telemetry is off: MOSTRA_TELEMETRY has a value Mostra doesn't recognize, so nothing is sent.\";\n case \"embedded\":\n return \"Telemetry is off: a host configures this home, and hosts never send telemetry.\";\n case \"no-collector\":\n return \"Telemetry is off: this build has no telemetry endpoint.\";\n case \"unreadable\":\n return `Telemetry is off: ${input.settingsFile} can't be read, so nothing is sent.`;\n case \"default\":\n return \"Telemetry is off until you turn it on: mostra telemetry on\";\n }\n}\n","/**\n * The standalone CLI's telemetry (D119, D140): the only code in Mostra that can send an event, and\n * only `@mostra/cli` may import it (a dependency-cruiser rule). The runner calls {@link begin}\n * before a command's work and {@link end} after it; everything else here is the decision, the\n * words, the schema, the store and the flusher.\n */\nimport { type DiagnosticCode, diagnosticCatalog } from \"@mostra/protocol\";\nimport type { Environment } from \"../home.ts\";\nimport { cliVersion } from \"../version.ts\";\nimport { buildEndpoint, decide, type TelemetryDecision, truthy } from \"./decision.ts\";\nimport {\n type CommonFields,\n catalogCodes,\n durationBucket,\n minute,\n SCHEMA,\n TelemetryEvent,\n} from \"./events.ts\";\nimport { startFlusher } from \"./flush.ts\";\nimport { detectHarness } from \"./harness.ts\";\nimport { TelemetryStore } from \"./store.ts\";\nimport { asksFirst, type ZoneSources } from \"./timezone.ts\";\nimport { ANSWER, NOTICE_ASK_FIRST, NOTICE_DEFAULT, QUESTION, statusLine } from \"./words.ts\";\n\nexport { TelemetryStore } from \"./store.ts\";\nexport { TURNED } from \"./words.ts\";\n\n/** The catalog's codes: only these leave the machine in `error` and `codes`. */\nconst CATALOG = new Set(Object.keys(diagnosticCatalog));\n\n/** Variables CI services set; any of them means `ci: true`, and the question is never asked. */\nconst CI_MARKERS = [\n \"CI\",\n \"CONTINUOUS_INTEGRATION\",\n \"GITHUB_ACTIONS\",\n \"GITLAB_CI\",\n \"BUILDKITE\",\n \"CIRCLECI\",\n \"TRAVIS\",\n \"TF_BUILD\",\n \"JENKINS_URL\",\n \"TEAMCITY_VERSION\",\n \"BITBUCKET_BUILD_NUMBER\",\n \"CODEBUILD_BUILD_ID\",\n];\n\n/** Whether this process runs in CI. */\nexport function inCi(env: Environment): boolean {\n return CI_MARKERS.some((name) => truthy(env[name]));\n}\n\n/** What a session of one command needs. */\nexport interface TelemetryOptions {\n readonly env: Environment;\n readonly configDir: string;\n /** The command's path from the definitions (`daemon install`), or `unknown`. */\n readonly command: string;\n readonly json: boolean;\n readonly tty: { readonly stdin: boolean; readonly stderr: boolean };\n /** The command reads stdin, so the question would take its input. */\n readonly readsStdin: boolean;\n /** `telemetry`, `docs`, `--help`, `--version`: no notice, no question, no event. */\n readonly quiet: boolean;\n /** Whether the home is a host's (its `config.json` mark, or a file that can't be read). */\n readonly hostHome: boolean;\n /** Writes to stderr. */\n readonly stderr: (text: string) => void;\n /** Asks one line on stderr and reads the answer, `undefined` for none within `timeoutMs`. */\n readonly ask: (question: string, timeoutMs: number) => Promise<string | undefined | \"interrupt\">;\n /** The clock; tests move it. */\n readonly now?: () => number;\n /** The build's endpoint; tests pass their own. Default {@link buildEndpoint}. */\n readonly buildEndpoint?: string;\n /** Where the zone names come from; tests replace `/etc/localtime` and `Intl`. */\n readonly zones?: Omit<ZoneSources, \"env\">;\n /** Starts the flusher after queueing; tests of the queue turn it off. Default true. */\n readonly flush?: boolean;\n}\n\n/** How long the question waits for an answer. */\nexport const QUESTION_TIMEOUT_MS = 60_000;\n\n/** One command's telemetry. */\nexport interface TelemetrySession {\n /** Before the command's work: the notice, or the question. Resolves `false` when Ctrl-C ended it. */\n begin(): Promise<boolean>;\n /** Records an event of the command (`verify.result`, `publish.done`, `share.done`, `mcp.session`). */\n record(event: {\n readonly event: \"verify.result\" | \"publish.done\" | \"share.done\" | \"mcp.session\";\n readonly fields: Readonly<Record<string, unknown>>;\n }): void;\n /**\n * Queues the events recorded so far, when telemetry allows, without the command's own event: a\n * command that runs for days (`mostra mcp`) records as it goes, since nothing may outlive its\n * end (a harness stops a server within a second, D164 item 4).\n */\n checkpoint(state: { readonly hostInstance: boolean }): void;\n /** After the command: queues its events and starts the flusher, when telemetry allows. */\n end(outcome: {\n readonly exit: number;\n readonly durationMs: number;\n readonly error?: string;\n /** The instance was host-spawned. */\n readonly hostInstance: boolean;\n }): void;\n}\n\n/** The current decision, for `telemetry status` and the session. */\nexport function currentDecision(options: {\n readonly env: Environment;\n readonly store: TelemetryStore;\n readonly embedded: boolean;\n readonly buildEndpoint?: string;\n readonly zones?: Omit<ZoneSources, \"env\">;\n}): TelemetryDecision {\n return decide({\n env: options.env,\n buildEndpoint: options.buildEndpoint ?? buildEndpoint(),\n embedded: options.embedded,\n settings: options.store.read(),\n askFirst: asksFirst({ ...options.zones, env: options.env }),\n });\n}\n\n/** Starts one command's telemetry. */\nexport function telemetrySession(options: TelemetryOptions): TelemetrySession {\n const now = options.now ?? Date.now;\n const store = new TelemetryStore(options.configDir);\n const pending: {\n event: \"verify.result\" | \"publish.done\" | \"share.done\" | \"mcp.session\";\n fields: Readonly<Record<string, unknown>>;\n }[] = [];\n const decision = (embedded: boolean): TelemetryDecision =>\n currentDecision({\n env: options.env,\n store,\n embedded,\n ...(options.buildEndpoint !== undefined ? { buildEndpoint: options.buildEndpoint } : {}),\n ...(options.zones !== undefined ? { zones: options.zones } : {}),\n });\n const shown = (): boolean => {\n const read = store.read();\n return read.ok && read.settings.noticeShownAt !== undefined;\n };\n /** Records that the notice was shown; `false` when the store can't be written. */\n const markShown = (): boolean =>\n store.update((current) => ({ ...current, noticeShownAt: new Date(now()).toISOString() })) !==\n undefined;\n const harness = detectHarness(options.env);\n const ci = inCi(options.env);\n\n return {\n async begin() {\n if (options.quiet) return true;\n const current = decision(options.hostHome);\n // No collector, a host's home, or a person who said no: nothing to say (D140 item 7).\n if (current.reason === \"no-collector\" || current.reason === \"embedded\") return true;\n // The notice is recorded before it is printed: a store that can't record it (a directory\n // that can't be written) means no notice, and so nothing ever sent.\n if (current.enabled) {\n if (!shown() && markShown()) options.stderr(NOTICE_DEFAULT);\n return true;\n }\n if (current.reason !== \"default\" || !current.askFirst) return true;\n const canAsk =\n options.tty.stdin &&\n options.tty.stderr &&\n !options.json &&\n !ci &&\n harness === \"none\" &&\n !options.readsStdin;\n if (!canAsk) {\n // Once, and on its own record: it never stands for the default notice.\n const read = store.read();\n if (read.ok && read.settings.askFirstNoticeShownAt === undefined) {\n const marked = store.update((settings) => ({\n ...settings,\n askFirstNoticeShownAt: new Date(now()).toISOString(),\n }));\n if (marked !== undefined) options.stderr(NOTICE_ASK_FIRST);\n }\n return true;\n }\n // A person who can answer and never did is asked, whatever notices they saw before.\n const answer = await options.ask(QUESTION, QUESTION_TIMEOUT_MS);\n const yes = typeof answer === \"string\" && /^\\s*y(es)?\\s*$/i.test(answer);\n const stored = store.update((settings) => ({\n ...settings,\n choice: yes ? \"on\" : \"off\",\n noticeShownAt: new Date(now()).toISOString(),\n }));\n options.stderr(\n stored === undefined\n ? `${statusLine({ enabled: false, reason: \"unreadable\", askFirst: true, settingsFile: store.settingsFile })}\\n`\n : yes\n ? ANSWER.yes\n : answer === undefined\n ? ANSWER.timeout\n : ANSWER.no,\n );\n return answer !== \"interrupt\";\n },\n\n record(event) {\n pending.push({ event: event.event, fields: event.fields });\n },\n\n checkpoint(state) {\n if (options.quiet || pending.length === 0) return;\n queue(state.hostInstance, undefined);\n },\n\n end(outcome) {\n if (options.quiet) return;\n queue(outcome.hostInstance, outcome);\n },\n };\n\n /**\n * Queues the pending events, and the command's own when `outcome` is given, and starts the\n * flusher; nothing when telemetry doesn't allow it. The pending events are taken either way, so\n * none is queued twice.\n */\n function queue(\n hostInstance: boolean,\n outcome:\n | { readonly exit: number; readonly durationMs: number; readonly error?: string }\n | undefined,\n ): void {\n const taken = pending.splice(0);\n const current = decision(options.hostHome || hostInstance);\n if (!current.enabled || current.consent === undefined || !shown()) return;\n const id = store.installId();\n if (!id) return;\n const common: CommonFields = {\n schema: SCHEMA,\n at: minute(new Date(now())),\n installId: id.id,\n version: cliVersion(),\n os:\n process.platform === \"darwin\" || process.platform === \"win32\" ? process.platform : \"linux\",\n arch: process.arch,\n node: Number(process.versions.node.split(\".\")[0]),\n harness,\n ci,\n consent: current.consent,\n };\n const events: unknown[] = [];\n if (id.created) events.push({ ...common, event: \"cli.first_run\" });\n for (const item of taken) {\n const fields =\n item.event === \"verify.result\"\n ? {\n status: item.fields[\"status\"],\n ...catalogCodes((item.fields[\"codes\"] as string[] | undefined) ?? [], CATALOG),\n }\n : item.fields;\n events.push({ ...common, ...fields, event: item.event });\n }\n if (outcome !== undefined) {\n events.push({\n ...common,\n event: \"cli.command\",\n command: options.command,\n exit: outcome.exit,\n duration: durationBucket(outcome.durationMs),\n json: options.json,\n ...(outcome.error !== undefined && CATALOG.has(outcome.error as DiagnosticCode)\n ? { error: outcome.error }\n : {}),\n });\n }\n const lines: string[] = [];\n for (const event of events) {\n const parsed = TelemetryEvent.safeParse(event);\n if (parsed.success) lines.push(JSON.stringify(parsed.data));\n }\n if (lines.length === 0) return;\n if (truthy(options.env[\"MOSTRA_TELEMETRY_DEBUG\"])) {\n // Exactly what would be sent, and nothing sent.\n for (const line of lines) options.stderr(`mostra telemetry (debug, not sent): ${line}\\n`);\n return;\n }\n store.append(lines, now());\n if (options.flush !== false) startFlusher(store, options.env, now());\n }\n}\n\n/** `mostra telemetry status`'s result. */\nexport interface TelemetryStatus {\n readonly enabled: boolean;\n readonly reason: TelemetryDecision[\"reason\"];\n readonly askFirst: boolean;\n readonly installId?: string;\n readonly endpoint?: string;\n readonly queued: number;\n readonly noticeShownAt?: string;\n readonly settingsFile: string;\n /** With reason `unreadable`: the file that can't be read (the home's `config.json`, or this). */\n readonly unreadableFile?: string;\n}\n\n/** `mostra telemetry status`: the decision, the install ID and the queue. */\nexport function telemetryStatus(options: {\n readonly env: Environment;\n readonly configDir: string;\n readonly embedded: boolean;\n /**\n * The home's `config.json` when it can't be read: the runner sends nothing then, as for a\n * host's home, and status says so (Opus review finding 6).\n */\n readonly homeConfigUnreadable?: string;\n readonly now?: number;\n}): { readonly status: TelemetryStatus; readonly text: string } {\n const store = new TelemetryStore(options.configDir);\n const decided = currentDecision({ env: options.env, store, embedded: options.embedded });\n const homeBlocks =\n options.homeConfigUnreadable !== undefined && decided.reason !== \"no-collector\";\n const decision = homeBlocks\n ? { ...decided, enabled: false, reason: \"unreadable\" as const }\n : decided;\n const unreadableFile = homeBlocks\n ? options.homeConfigUnreadable\n : decision.reason === \"unreadable\"\n ? store.settingsFile\n : undefined;\n const read = store.read();\n const settings = read.ok ? read.settings : {};\n const queued = read.ok ? store.queued(options.now ?? Date.now()).length : 0;\n const status: TelemetryStatus = {\n enabled: decision.enabled,\n reason: decision.reason,\n askFirst: decision.askFirst,\n ...(settings.installId !== undefined ? { installId: settings.installId } : {}),\n ...(decision.endpoint !== undefined ? { endpoint: decision.endpoint } : {}),\n queued,\n ...(settings.noticeShownAt !== undefined ? { noticeShownAt: settings.noticeShownAt } : {}),\n settingsFile: store.settingsFile,\n ...(unreadableFile !== undefined ? { unreadableFile } : {}),\n };\n const lines = [\n statusLine({ ...decision, settingsFile: unreadableFile ?? store.settingsFile }),\n ...(status.installId !== undefined ? [`Install ID: ${status.installId}`] : []),\n `Queued events: ${queued}`,\n `Settings: ${store.settingsFile}`,\n ];\n return { status, text: lines.join(\"\\n\") };\n}\n","/**\n * What commands share: naming artifacts and sources on the command line, and reading JSON values.\n */\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport type { ArtifactRef, SourceRef } from \"@mostra/protocol\";\nimport type { CommandContext } from \"../command.ts\";\nimport { usage } from \"../parse.ts\";\n\nconst ARTIFACT_ID = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;\n\n/** An artifact named by its ID (`art_…`) or by a path, relative ones from `--cwd`. */\nexport function artifactRef(value: string, cwd: string): ArtifactRef {\n return ARTIFACT_ID.test(value) ? { artifactId: value } : { path: resolve(cwd, value) };\n}\n\n/** A source named the same way: a path, or the ID of an artifact (the path it was published from). */\nexport function sourceRef(value: string, cwd: string): SourceRef {\n return ARTIFACT_ID.test(value) ? { artifactId: value } : { path: resolve(cwd, value) };\n}\n\n/** A string argument the parser guaranteed. */\nexport function arg(context: CommandContext, name: string): string {\n const value = context.args[name];\n if (typeof value !== \"string\") throw usage(`<${name}> is missing.`);\n return value;\n}\n\n/** An optional string flag. */\nexport function flag(context: CommandContext, name: string): string | undefined {\n const value = context.flags[name];\n return typeof value === \"string\" ? value : undefined;\n}\n\n/** Parses a JSON value given on the command line, in a file or on stdin. */\nexport function parseJson(text: string, where: string): unknown {\n try {\n return JSON.parse(text);\n } catch (error) {\n throw usage(`${where} isn't JSON: ${(error as Error).message}`);\n }\n}\n\n/** Reads a JSON value from `--value`, `--file` or `--stdin`, exactly one of them. */\nexport async function jsonInput(context: CommandContext, valueFlag = \"value\"): Promise<unknown> {\n const given = [valueFlag, \"file\", \"stdin\"].filter(\n (name) => context.flags[name] !== undefined && context.flags[name] !== false,\n );\n if (given.length !== 1) {\n throw usage(`Give the value with exactly one of --${valueFlag}, --file or --stdin.`);\n }\n if (context.flags[\"stdin\"] === true) return parseJson(await context.readStdin(), \"stdin\");\n const file = flag(context, \"file\");\n if (file !== undefined) {\n let text: string;\n try {\n text = readFileSync(resolve(context.cwd, file), \"utf8\");\n } catch (error) {\n throw usage(\n `--file ${file} can't be read (${(error as NodeJS.ErrnoException).code ?? \"error\"}).`,\n );\n }\n return parseJson(text, file);\n }\n return parseJson(flag(context, valueFlag) ?? \"\", `--${valueFlag}`);\n}\n\n/** Indented JSON, for human output of structured results. */\nexport function pretty(value: unknown): string {\n return `${JSON.stringify(value, null, 2)}\\n`;\n}\n","/**\n * Administration: `secret`, `list`, `status`, `daemon`, `host`, `gc`, `doctor`, `docs` and\n * `telemetry`. Each is a client of the host protocol or the runtime binary, never of the home's\n * files, except `doctor`, which reads what it needs to explain why an instance can't start.\n */\nimport { spawn } from \"node:child_process\";\nimport { existsSync, readdirSync, statSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport {\n artifactGetMethod,\n artifactListMethod,\n createDiagnostic,\n type Diagnostic,\n gcRunMethod,\n type InstanceCheck,\n instanceCheckMethod,\n instanceStatusMethod,\n mostraShutdownMethod,\n RpcError,\n secretDeleteMethod,\n secretListMethod,\n secretSetMethod,\n} from \"@mostra/protocol\";\nimport { checkBrowser, checkFiles, enclosingBundle, readBundle, readSetup } from \"@mostra/sdk\";\nimport { type CommandContext, type CommandDef, defineCommand } from \"../command.ts\";\nimport { docsIndex, indexMarkdown, nearestTopics, skillDir, topicMarkdown } from \"../docs.ts\";\nimport { EXIT, exitCodeFor } from \"../exit.ts\";\nimport { embeddedHome, locateRuntime, readHomeMarks } from \"../home.ts\";\nimport { usage } from \"../parse.ts\";\nimport { checkPlatform } from \"../platform.ts\";\nimport { TelemetryStore, TURNED, telemetryStatus } from \"../telemetry/index.ts\";\nimport { NOTICE_DEFAULT } from \"../telemetry/words.ts\";\nimport { cliVersion } from \"../version.ts\";\nimport { arg, artifactRef, flag, pretty } from \"./shared.ts\";\n\nconst artifactFlag = {\n name: \"artifact\",\n kind: \"string\" as const,\n value: \"<path|id>\",\n summary: \"The artifact's own secret, instead of one the whole home shares.\",\n};\n\n/** `mostra secret set <name>`. */\nexport const secretSetCommand: CommandDef = defineCommand({\n path: [\"secret\", \"set\"],\n summary:\n \"Store a secret that server code reads with secret(name); the value comes from stdin and is never shown.\",\n args: [{ name: \"name\", summary: \"Letters, digits, _, . and -, starting with a letter or _.\" }],\n flags: [artifactFlag],\n output: { type: \"SecretEntry\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"secret set MAIL_TOKEN --artifact ./inbox < token.txt\",\n readsStdin: true,\n async run(context) {\n let value = await context.readStdin();\n // One trailing newline is the terminal's or `echo`'s, never the secret's.\n if (value.endsWith(\"\\n\")) value = value.slice(0, value.endsWith(\"\\r\\n\") ? -2 : -1);\n if (value === \"\") throw usage(\"The secret's value comes from stdin, and stdin was empty.\");\n const artifact = flag(context, \"artifact\");\n const entry = await context.call(secretSetMethod, {\n name: arg(context, \"name\"),\n value,\n ...(artifact !== undefined ? { artifact: artifactRef(artifact, context.cwd) } : {}),\n });\n return { result: entry, human: `Stored ${entry.name} (${entry.scope})\\n` };\n },\n});\n\n/** `mostra secret list`. */\nexport const secretListCommand: CommandDef = defineCommand({\n path: [\"secret\", \"list\"],\n summary: \"List the secrets' names and scopes; values are never shown.\",\n flags: [artifactFlag],\n output: { type: \"SecretListResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"secret list --artifact ./inbox\",\n async run(context) {\n const artifact = flag(context, \"artifact\");\n const result = await context.call(secretListMethod, {\n ...(artifact !== undefined ? { artifact: artifactRef(artifact, context.cwd) } : {}),\n });\n return {\n result,\n human: result.secrets\n .map((entry) => `${entry.name} ${entry.scope} ${entry.updatedAt}\\n`)\n .join(\"\"),\n };\n },\n});\n\n/** `mostra secret rm <name>`. */\nexport const secretRmCommand: CommandDef = defineCommand({\n path: [\"secret\", \"rm\"],\n summary: \"Delete a secret.\",\n args: [{ name: \"name\", summary: \"The secret's name.\" }],\n flags: [artifactFlag],\n output: { type: \"SecretDeleteResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"secret rm MAIL_TOKEN --artifact ./inbox\",\n async run(context) {\n const artifact = flag(context, \"artifact\");\n const result = await context.call(secretDeleteMethod, {\n name: arg(context, \"name\"),\n ...(artifact !== undefined ? { artifact: artifactRef(artifact, context.cwd) } : {}),\n });\n return { result, human: result.deleted ? \"Deleted\\n\" : \"No such secret\\n\" };\n },\n});\n\n/** `mostra list`. */\nexport const listCommand: CommandDef = defineCommand({\n path: [\"list\"],\n summary: \"List the home's published artifacts.\",\n flags: [\n {\n name: \"family\",\n kind: \"string\",\n value: \"<family>\",\n summary: \"Only artifacts of this family.\",\n },\n ],\n output: { type: \"ArtifactListResult\", topic: \"cli\" },\n exits: [],\n example: \"list --family dashboard\",\n async run(context) {\n const family = flag(context, \"family\");\n const result = await context.call(artifactListMethod, {\n ...(family !== undefined ? { filter: { family } } : {}),\n });\n return {\n result,\n human: result.artifacts\n .map(\n (artifact) =>\n `${artifact.id} v${artifact.latestVersion?.number ?? \"-\"} ${artifact.title}${artifact.source ? ` ${artifact.source}` : \"\"}\\n`,\n )\n .join(\"\"),\n };\n },\n});\n\n/** `mostra status [artifact]`. */\nexport const statusCommand: CommandDef = defineCommand({\n path: [\"status\"],\n summary:\n \"Show the instance (processes, workers, deliveries) or one artifact (versions, policy, links).\",\n args: [{ name: \"artifact\", summary: \"An artifact: its source path or its ID.\", optional: true }],\n output: { type: \"InstanceStatusResult or ArtifactDetail\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"status ./sidebar-review\",\n async run(context) {\n const artifact = context.args[\"artifact\"];\n if (typeof artifact === \"string\") {\n const detail = await context.call(artifactGetMethod, {\n artifact: artifactRef(artifact, context.cwd),\n });\n const versions = detail.versions\n .map(\n (version) =>\n ` v${version.number} ${version.id} ${version.publishedAt}${version.collected ? \" collected\" : \"\"}\\n`,\n )\n .join(\"\");\n return { result: detail, human: `${detail.id} ${detail.title}\\n${versions}` };\n }\n const status = await context.call(instanceStatusMethod, {});\n // Each remote server this home is linked to, by its state (INTERFACES §18.7).\n const links = (status.links ?? [])\n .map(\n (link) =>\n `${link.server} ${link.state}${link.default ? \" default\" : \"\"}${link.pendingPushes > 0 ? ` ${link.pendingPushes} pushes waiting` : \"\"}${link.lastError ? ` (${link.lastError})` : \"\"}\\n`,\n )\n .join(\"\");\n return {\n result: status,\n human: `${pretty(status)}${links ? `\\nRemote servers:\\n${links}` : \"\"}`,\n };\n },\n});\n\n/** The runtime's `service` command, as JSON. */\nasync function service(\n context: CommandContext,\n action: \"install\" | \"uninstall\" | \"status\",\n): Promise<{ manager: string; name: string; file: string; installed: boolean }> {\n const { stdout } = await context.runtime([\n \"service\",\n action,\n \"--home\",\n context.home,\n ...(context.flags[\"no-start\"] === true ? [\"--no-start\"] : []),\n ]);\n const line = stdout.split(\"\\n\").find((text) => text.trim().startsWith(\"{\"));\n let parsed: { status?: string; service?: unknown; diagnostic?: Diagnostic } = {};\n try {\n parsed = JSON.parse(line ?? \"{}\") as typeof parsed;\n } catch {\n // Reported below.\n }\n if (parsed.status === \"ok\" && parsed.service) {\n return parsed.service as { manager: string; name: string; file: string; installed: boolean };\n }\n throw new RpcError(\n parsed.diagnostic ??\n createDiagnostic(\"MOSTRA_ENV_SERVICE_FAILED\", {\n message: `mostra-runtime service ${action} gave no answer.`,\n }),\n );\n}\n\nconst noStart = {\n name: \"no-start\",\n kind: \"boolean\" as const,\n summary:\n \"Write or remove the service's definition without asking launchd, systemd or Task Scheduler to load it.\",\n};\n\n/** `mostra daemon start`. */\nexport const daemonStartCommand: CommandDef = defineCommand({\n path: [\"daemon\", \"start\"],\n summary: \"Start the home's daemon, or find the one already running.\",\n output: { type: \"DaemonStatus\", topic: \"cli\" },\n exits: [],\n example: \"daemon start\",\n async run(context) {\n const connection = await context.connection();\n const summary = connection?.summary;\n return {\n result: { running: true, ...summary },\n human: `${summary?.started ? \"Started\" : \"Running\"}: pid ${summary?.pid}, ${summary?.socket}\\n`,\n };\n },\n});\n\n/** Stops the running daemon; resolves once its socket closed. */\nasync function stopDaemon(context: CommandContext): Promise<{ stopped: boolean; pid?: number }> {\n const connection = await context.connection(false);\n if (!connection) return { stopped: false };\n const { pid } = connection.summary;\n await context.call(mostraShutdownMethod, {});\n await Promise.race([connection.closed, new Promise((done) => setTimeout(done, 15_000))]);\n // The record goes last, as the instance releases its home (D87).\n const deadline = Date.now() + 15_000;\n while (existsSync(join(context.home, \"instance.json\")) && Date.now() < deadline) {\n await new Promise((done) => setTimeout(done, 50));\n }\n return { stopped: true, pid };\n}\n\n/** `mostra daemon stop`. */\nexport const daemonStopCommand: CommandDef = defineCommand({\n path: [\"daemon\", \"stop\"],\n summary: \"Stop the home's daemon; open pages reconnect when it starts again.\",\n output: { type: \"DaemonStop\", topic: \"cli\" },\n exits: [],\n example: \"daemon stop\",\n async run(context) {\n const result = await stopDaemon(context);\n return {\n result,\n human: result.stopped ? `Stopped pid ${result.pid}\\n` : \"No daemon was running\\n\",\n };\n },\n});\n\n/** `mostra daemon restart`. */\nexport const daemonRestartCommand: CommandDef = defineCommand({\n path: [\"daemon\", \"restart\"],\n summary: \"Stop the home's daemon and start it again, for instance after an update.\",\n output: { type: \"DaemonStatus\", topic: \"cli\" },\n exits: [],\n example: \"daemon restart\",\n async run(context) {\n await stopDaemon(context);\n const connection = await context.connection();\n const summary = connection?.summary;\n return { result: { running: true, ...summary }, human: `Running: pid ${summary?.pid}\\n` };\n },\n});\n\n/** `mostra daemon status`. */\nexport const daemonStatusCommand: CommandDef = defineCommand({\n path: [\"daemon\", \"status\"],\n summary:\n \"Whether the home's daemon runs, when it would exit for lack of work, and its login service.\",\n output: { type: \"DaemonStatus\", topic: \"cli\" },\n exits: [],\n example: \"daemon status\",\n async run(context) {\n const loginService = await service(context, \"status\");\n const connection = await context.connection(false);\n if (!connection) {\n return {\n result: { running: false, service: loginService },\n human: `Not running. Login service: ${loginService.installed ? \"installed\" : \"not installed\"}\\n`,\n };\n }\n const status = await context.call(instanceStatusMethod, {});\n return {\n result: { running: true, ...connection.summary, status, service: loginService },\n human: `Running: pid ${connection.summary.pid}${status.idleExitAt ? `, exits when idle at ${status.idleExitAt}` : \"\"}. Login service: ${loginService.installed ? \"installed\" : \"not installed\"}\\n`,\n };\n },\n});\n\n/** `mostra daemon install`. */\nexport const daemonInstallCommand: CommandDef = defineCommand({\n path: [\"daemon\", \"install\"],\n summary:\n \"Run the home's daemon as a login service (launchd, systemd or Task Scheduler), so links answer at any hour.\",\n flags: [noStart],\n output: { type: \"ServiceStatus\", topic: \"cli\" },\n exits: [],\n example: \"daemon install\",\n async run(context) {\n const result = await service(context, \"install\");\n return { result, human: `Installed ${result.name} (${result.file})\\n` };\n },\n});\n\n/** `mostra daemon uninstall`. */\nexport const daemonUninstallCommand: CommandDef = defineCommand({\n path: [\"daemon\", \"uninstall\"],\n summary: \"Remove the home's login service; the daemon then exits after 30 idle minutes.\",\n flags: [noStart],\n output: { type: \"ServiceStatus\", topic: \"cli\" },\n exits: [],\n example: \"daemon uninstall\",\n async run(context) {\n const result = await service(context, \"uninstall\");\n return { result, human: `Removed ${result.name}\\n` };\n },\n});\n\n/** `mostra host`. */\nexport const hostCommand: CommandDef = defineCommand({\n path: [\"host\"],\n summary:\n \"Speak the host protocol on stdin and stdout, for a host that spawns Mostra; it sends no telemetry.\",\n flags: [\n {\n name: \"bind\",\n kind: \"string\",\n value: \"<address>\",\n summary: \"Serve viewers on this address instead of 127.0.0.1.\",\n },\n {\n name: \"url-host\",\n kind: \"string\",\n value: \"<name>\",\n summary: \"The host name links use; a wildcard --bind needs it.\",\n },\n ],\n output: { type: \"the host protocol (INTERFACES §6)\", topic: \"cli\" },\n exits: [],\n example: \"host --home ~/.my-host/mostra\",\n local: true,\n quiet: true,\n readsStdin: true,\n async run(context) {\n const runtime = await locateRuntime(context.env);\n const bind = flag(context, \"bind\");\n const urlHost = flag(context, \"url-host\");\n const code = await new Promise<number>((resolve) => {\n const child = spawn(\n runtime.node,\n [\n runtime.entry,\n \"host\",\n \"--home\",\n context.home,\n ...(bind !== undefined ? [\"--bind\", bind] : []),\n ...(urlHost !== undefined ? [\"--url-host\", urlHost] : []),\n ],\n { stdio: \"inherit\", env: context.env as NodeJS.ProcessEnv },\n );\n child.on(\"exit\", (exit) => resolve(exit ?? EXIT.environment));\n child.on(\"error\", () => resolve(EXIT.environment));\n for (const signal of [\"SIGINT\", \"SIGTERM\"] as const)\n process.on(signal, () => child.kill(signal));\n });\n return { result: undefined, exit: code, raw: true };\n },\n});\n\n/** `mostra gc`. */\nexport const gcCommand: CommandDef = defineCommand({\n path: [\"gc\"],\n summary:\n \"Remove what nothing references: unreferenced versions' files, unused packages and caches.\",\n flags: [\n {\n name: \"dry-run\",\n kind: \"boolean\",\n summary: \"List what a run would remove, and remove nothing.\",\n },\n {\n name: \"compact-events\",\n kind: \"boolean\",\n summary: \"Also replace events before --before with one summary per artifact.\",\n },\n {\n name: \"before\",\n kind: \"string\",\n value: \"<cursor>\",\n summary: \"The cursor --compact-events compacts before.\",\n },\n ],\n output: { type: \"GcRunResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"gc --dry-run\",\n async run(context) {\n const compact = context.flags[\"compact-events\"] === true;\n const before = flag(context, \"before\");\n if (compact !== (before !== undefined))\n throw usage(\"--compact-events and --before go together.\");\n if (before !== undefined && !/^[0-9]+$/.test(before))\n throw usage(`--before takes an event cursor; \"${before}\" isn't one.`);\n const result = await context.call(gcRunMethod, {\n ...(context.flags[\"dry-run\"] === true ? { dryRun: true } : {}),\n ...(before !== undefined ? { compactEvents: { before } } : {}),\n });\n // A step gc couldn't finish is a warning beside what it did (MOSTRA_HOME_GC_INCOMPLETE).\n for (const warning of result.warnings ?? []) context.warn(warning);\n const verb = result.dryRun ? \"Would remove\" : \"Removed\";\n const lines = [\n `${verb} ${result.versions.length} versions' files, ${result.snapshots.count} snapshots, ${result.lockLayouts.count} lock layouts, ${result.storePackages.count} store packages and ${result.caches.count} cache entries (${result.bytes} bytes).`,\n ...result.versions.map(\n (version) => ` ${version.artifactId} v${version.number} ${version.versionId}`,\n ),\n ...(result.compacted ? [`Compacted ${result.compacted.removed} events.`] : []),\n ];\n return { result, human: `${lines.join(\"\\n\")}\\n` };\n },\n});\n\n/** One line of `doctor`. */\ninterface DoctorCheck {\n readonly name: string;\n readonly status: \"ok\" | \"warning\" | \"error\";\n readonly detail?: string;\n readonly diagnostic?: Diagnostic;\n}\n\n/** `mostra doctor`. */\n/**\n * The check that fails `mostra doctor`: the first whose status isn't one this CLI knows is no\n * failure, so a newer instance's status it doesn't know counts as an error (Opus review of MT-01,\n * 2), never as passing.\n */\nexport function firstFailing<T extends { readonly status: string }>(\n checks: readonly T[],\n): T | undefined {\n return checks.find((check) => check.status !== \"ok\" && check.status !== \"warning\");\n}\n\nexport const doctorCommand: CommandDef = defineCommand({\n path: [\"doctor\"],\n summary:\n \"Check the platform, the runtime, the home, its daemon and ledger, and the login service.\",\n flags: [\n {\n name: \"deep\",\n kind: \"boolean\",\n summary: \"Also hash every version against its recorded output digest.\",\n },\n ],\n output: { type: \"DoctorResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"doctor\",\n async run(context) {\n const checks: DoctorCheck[] = [];\n const node = Number(process.versions.node.split(\".\")[0]);\n const unsupported = checkPlatform(process.platform, process.arch);\n checks.push(\n unsupported === undefined\n ? {\n name: \"platform\",\n status: \"ok\",\n detail: `${process.platform} ${process.arch}, Node ${process.versions.node}`,\n }\n : { name: \"platform\", status: \"error\", diagnostic: unsupported },\n );\n if (node < 24) {\n checks.push({\n name: \"node\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_ENV_RUNTIME_MISSING\", {\n message: `Mostra needs Node 24 or later; this is ${process.versions.node}.`,\n }),\n });\n }\n try {\n const runtime = await locateRuntime(context.env);\n checks.push({ name: \"runtime\", status: \"ok\", detail: runtime.entry });\n } catch (error) {\n checks.push({ name: \"runtime\", status: \"error\", diagnostic: (error as RpcError).diagnostic });\n }\n checks.push(await bundleCheck(context.env, context.flags[\"deep\"] === true));\n checks.push(homeCheck(context.home));\n let connection: Awaited<ReturnType<CommandContext[\"connection\"]>>;\n try {\n connection = await context.connection();\n checks.push({\n name: \"daemon\",\n status: \"ok\",\n detail: `pid ${connection?.summary.pid}, ${connection?.summary.socket}`,\n });\n } catch (error) {\n const diagnostic = error instanceof RpcError ? error.diagnostic : undefined;\n checks.push({\n name: \"daemon\",\n status: \"error\",\n ...(diagnostic ? { diagnostic } : { detail: String(error) }),\n ...(diagnostic?.code === \"MOSTRA_HOME_LEDGER_UNREADABLE\"\n ? { detail: backups(context.home) }\n : {}),\n });\n }\n if (connection) {\n if (connection.summary.version !== cliVersion()) {\n checks.push({\n name: \"versions\",\n status: \"warning\",\n detail: `The CLI is ${cliVersion()} and the daemon ${connection.summary.version}; run \"mostra daemon restart\" after an update.`,\n });\n }\n const instance = await context.call(\n instanceCheckMethod,\n context.flags[\"deep\"] === true ? { deep: true } : {},\n );\n checks.push(...instance.checks.map((check: InstanceCheck) => ({ ...check })));\n checks.push(await alwaysOnCheck(context));\n }\n const telemetry = telemetryStatus({\n env: context.env,\n configDir: context.configDir,\n embedded:\n readHomeMarks(context.home).hostConfigured !== undefined ||\n connection?.summary.mode === \"host\",\n });\n checks.push({\n name: \"telemetry\",\n status: \"ok\",\n detail: telemetry.text.split(\"\\n\")[0] as string,\n });\n const firstError = firstFailing(checks);\n const human = checks\n .map((check) => {\n const mark = check.status === \"ok\" ? \"ok \" : check.status === \"warning\" ? \"warn\" : \"FAIL\";\n const what = check.diagnostic\n ? `${check.diagnostic.code}: ${check.diagnostic.message}`\n : (check.detail ?? \"\");\n const hint = check.diagnostic?.hint ? `\\n ${check.diagnostic.hint}` : \"\";\n return `${mark} ${check.name}${what ? `: ${what}` : \"\"}${hint}`;\n })\n .join(\"\\n\");\n return {\n result: { checks },\n human: `${human}\\n`,\n ...(firstError\n ? {\n exit: firstError.diagnostic\n ? exitCodeFor(firstError.diagnostic.code)\n : EXIT.environment,\n }\n : {}),\n };\n },\n});\n\n/**\n * The runtime bundle this CLI runs from (RT-01): set up and matching its files. Outside a bundle\n * (a development checkout, `MOSTRA_RUNTIME_BIN`) there is nothing to check. `--deep` hashes every\n * file against the bundle's file list and the browser against its pin, as setup does.\n */\nasync function bundleCheck(env: CommandContext[\"env\"], deep: boolean): Promise<DoctorCheck> {\n const root = env[\"MOSTRA_BUNDLE\"] || enclosingBundle();\n if (!root)\n return { name: \"bundle\", status: \"ok\", detail: \"No runtime bundle: a development runtime.\" };\n try {\n const bundle = await readBundle(root);\n const label = `Mostra ${bundle.info.version} for ${bundle.info.platform} at ${root}`;\n if (!(await readSetup(bundle))) {\n return {\n name: \"bundle\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_ENV_BUNDLE_UNAVAILABLE\", {\n message: `The runtime bundle at ${root} isn't set up; run its bin/mostra-setup.`,\n }),\n };\n }\n if (!deep) return { name: \"bundle\", status: \"ok\", detail: label };\n await checkFiles(bundle);\n const browser = await checkBrowser(bundle);\n if (browser.length > 0) {\n return {\n name: \"bundle\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", {\n message: `The verify browser of the bundle at ${root} differs from its pin: ${browser.join(\"; \")}.`,\n }),\n };\n }\n return { name: \"bundle\", status: \"ok\", detail: `${label}; every file matches its SHA-256` };\n } catch (error) {\n return {\n name: \"bundle\",\n status: \"error\",\n diagnostic:\n error instanceof RpcError\n ? error.diagnostic\n : createDiagnostic(\"MOSTRA_ENV_BUNDLE_INVALID\", { message: (error as Error).message }),\n };\n }\n}\n\n/** The home: absent (it is made on first use), a directory the user owns, or not. */\nfunction homeCheck(home: string): DoctorCheck {\n let info: ReturnType<typeof statSync>;\n try {\n info = statSync(home);\n } catch {\n return { name: \"home\", status: \"ok\", detail: `${home} (not created yet)` };\n }\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid())) {\n return {\n name: \"home\",\n status: \"error\",\n diagnostic: createDiagnostic(\"MOSTRA_HOME_NOT_OWNED\", {\n message: `Mostra can't use ${home}: another user owns it or it isn't a directory.`,\n }),\n };\n }\n return { name: \"home\", status: \"ok\", detail: home };\n}\n\n/** The ledger's backups beside it, for a ledger that can't be opened (FAILURE_MODEL §3). */\nfunction backups(home: string): string {\n try {\n const found = readdirSync(join(home, \"store\")).filter((name) =>\n name.startsWith(\"ledger.sqlite.bak-\"),\n );\n return found.length > 0\n ? `Backups: ${found.map((name) => join(home, \"store\", name)).join(\", \")}`\n : \"No ledger backups.\";\n } catch {\n return \"No ledger backups.\";\n }\n}\n\n/**\n * LL-05's doctor half (D96, D63): artifacts with submission policy `none` are meant to answer at\n * any hour, which needs the home's login service.\n */\nasync function alwaysOnCheck(context: CommandContext): Promise<DoctorCheck> {\n const { artifacts } = await context.call(artifactListMethod, {});\n const longLived = artifacts.filter((artifact) => artifact.policy?.policy === \"none\");\n if (longLived.length === 0)\n return { name: \"always-on\", status: \"ok\", detail: \"No artifact needs an always-on daemon.\" };\n const loginService = await service(context, \"status\");\n if (loginService.installed) {\n return {\n name: \"always-on\",\n status: \"ok\",\n detail: `Login service ${loginService.name} keeps the daemon running.`,\n };\n }\n return {\n name: \"always-on\",\n status: \"warning\",\n diagnostic: createDiagnostic(\"MOSTRA_HOME_NOT_ALWAYS_ON\", {\n message: `${longLived.length} ${longLived.length === 1 ? \"artifact has\" : \"artifacts have\"} submission policy none (${longLived\n .map((artifact) => artifact.title)\n .slice(0, 3)\n .join(\", \")}), and no login service keeps this home's daemon running.`,\n }),\n };\n}\n\n/** `mostra docs [topic]`. */\nexport const docsCommand: CommandDef = defineCommand({\n path: [\"docs\"],\n summary:\n \"Print Mostra's reference: the guide to writing artifacts, the CLI, telemetry, and every diagnostic code's page.\",\n args: [\n { name: \"topic\", summary: \"A topic or a diagnostic code. Default: the index.\", optional: true },\n ],\n output: { type: \"DocsPage\", topic: \"cli\" },\n exits: [],\n example: \"docs MOSTRA_DEP_MISSING\",\n local: true,\n quiet: true,\n async run(context) {\n const topics = docsIndex();\n const wanted = context.args[\"topic\"];\n if (typeof wanted !== \"string\") {\n const markdown = indexMarkdown(topics);\n return {\n result: {\n topic: \"index\",\n markdown,\n url: topics[0]?.url.replace(/\\/[^/]+$/, \"\") ?? \"\",\n topics: topics.map(({ topic, title, url }) => ({ topic, title, url })),\n },\n human: markdown,\n };\n }\n const found = topics.find(\n (topic) => topic.topic === wanted || topic.topic === wanted.toUpperCase(),\n );\n if (!found) {\n throw usage(\n `No topic \"${wanted}\". The nearest: ${nearestTopics(wanted, topics).join(\", \")}. Run \"mostra docs\" for the index.`,\n );\n }\n const markdown = topicMarkdown(found, skillDir());\n return { result: { topic: found.topic, markdown, url: found.url }, human: markdown };\n },\n});\n\n/** `mostra telemetry status`. */\nexport const telemetryStatusCommand: CommandDef = defineCommand({\n path: [\"telemetry\", \"status\"],\n summary: \"Whether the CLI sends anonymous usage data, and why.\",\n output: { type: \"TelemetryStatus\", topic: \"telemetry\" },\n exits: [],\n example: \"telemetry status\",\n local: true,\n quiet: true,\n async run(context) {\n const { status, text } = telemetryStatus({\n env: context.env,\n configDir: context.configDir,\n ...homeTelemetry(context.home),\n });\n return { result: status, human: `${text}\\n` };\n },\n});\n\n/** How the home bears on telemetry: a host's home, or one whose `config.json` can't be read. */\nfunction homeTelemetry(home: string): { embedded: boolean; homeConfigUnreadable?: string } {\n const marks = readHomeMarks(home);\n return {\n embedded: embeddedHome(marks) && marks.unreadable !== true,\n ...(marks.unreadable === true ? { homeConfigUnreadable: join(home, \"config.json\") } : {}),\n };\n}\n\n/** The choice couldn't be recorded: nothing changed (Opus review finding 6). */\nfunction unwritable(store: TelemetryStore): RpcError {\n return new RpcError(\n createDiagnostic(\"MOSTRA_CLI_CONFIG_UNWRITABLE\", {\n message: `${store.settingsFile} can't be written, so the choice wasn't recorded and nothing changed.`,\n }),\n );\n}\n\n/** `mostra telemetry on`. */\nexport const telemetryOnCommand: CommandDef = defineCommand({\n path: [\"telemetry\", \"on\"],\n summary: \"Send anonymous usage data from this CLI; the notice says what it contains.\",\n output: { type: \"TelemetryStatus\", topic: \"telemetry\" },\n exits: [EXIT.environment],\n example: \"telemetry on\",\n local: true,\n quiet: true,\n async run(context) {\n const store = new TelemetryStore(context.configDir);\n const read = store.read();\n const shownBefore = read.ok && read.settings.noticeShownAt !== undefined;\n if (!shownBefore) context.stderr(NOTICE_DEFAULT);\n const now = new Date().toISOString();\n const written =\n store.update((current) => ({\n ...current,\n choice: \"on\",\n noticeShownAt: current.noticeShownAt ?? now,\n })) ?? store.locked(() => store.reset({ choice: \"on\", noticeShownAt: now }));\n if (written === undefined) throw unwritable(store);\n const { status } = telemetryStatus({\n env: context.env,\n configDir: context.configDir,\n ...homeTelemetry(context.home),\n });\n return { result: status, human: `${TURNED.on}\\n` };\n },\n});\n\n/** `mostra telemetry off`. */\nexport const telemetryOffCommand: CommandDef = defineCommand({\n path: [\"telemetry\", \"off\"],\n summary: \"Stop sending usage data, and delete the install ID and any unsent events.\",\n output: { type: \"TelemetryStatus\", topic: \"telemetry\" },\n exits: [EXIT.environment],\n example: \"telemetry off\",\n local: true,\n quiet: true,\n async run(context) {\n const store = new TelemetryStore(context.configDir);\n const done =\n store.turnOff() || store.locked(() => store.reset({ choice: \"off\" })) !== undefined;\n if (!done) throw unwritable(store);\n const { status } = telemetryStatus({\n env: context.env,\n configDir: context.configDir,\n ...homeTelemetry(context.home),\n });\n return { result: status, human: `${TURNED.off}\\n` };\n },\n});\n","/**\n * Authoring: `new`, `verify`, `publish`, `export`, `run` and `add`, thin clients of\n * `artifact/create`, `artifact/verify`, `artifact/publish`, `artifact/export`, `artifact/import`\n * and `deps/add` (INTERFACES §6, §15).\n */\nimport { randomUUID } from \"node:crypto\";\nimport { resolve } from \"node:path\";\nimport {\n ARTIFACT_PROGRESS,\n artifactCreateMethod,\n artifactExportMethod,\n artifactImportMethod,\n artifactPublishMethod,\n artifactVerifyMethod,\n depsAddMethod,\n type SubmissionPolicy,\n type VerifyVerdict,\n} from \"@mostra/protocol\";\nimport { type CommandDef, defineCommand } from \"../command.ts\";\nimport { EXIT } from \"../exit.ts\";\nimport { usage } from \"../parse.ts\";\nimport { arg, artifactRef, flag, sourceRef } from \"./shared.ts\";\n\n/** `mostra new <dir>`. */\nexport const newCommand: CommandDef = defineCommand({\n path: [\"new\"],\n summary: \"Create an artifact in an empty directory, with a generated ID.\",\n args: [{ name: \"dir\", summary: \"The directory to create it in; it must be empty or not exist.\" }],\n flags: [\n {\n name: \"title\",\n kind: \"string\",\n value: \"<text>\",\n summary: \"The artifact's title. Default: the directory's name.\",\n },\n {\n name: \"template\",\n kind: \"string\",\n value: \"<family>\",\n summary: \"Start from a template (templates arrive in a later release).\",\n },\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retry return the first attempt's result.\",\n },\n ],\n output: { type: \"ArtifactCreateResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"new ./sidebar-review --title 'Sidebar review'\",\n async run(context) {\n const title = flag(context, \"title\");\n const template = flag(context, \"template\");\n const requestId = flag(context, \"request-id\");\n const result = await context.call(artifactCreateMethod, {\n dir: resolve(context.cwd, arg(context, \"dir\")),\n ...(title !== undefined ? { title } : {}),\n ...(template !== undefined ? { template } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n });\n return {\n result,\n human: `Created ${result.artifactId} in ${result.dir}\\n${result.files.map((file) => ` ${file}\\n`).join(\"\")}`,\n };\n },\n});\n\n/** The verdict for people: the status, each diagnostic, the screenshots worth looking at. */\nfunction verdictText(verdict: VerifyVerdict): string {\n const lines = [`verify: ${verdict.status}`];\n for (const diagnostic of verdict.diagnostics) {\n const where =\n diagnostic.location && \"file\" in diagnostic.location\n ? ` ${diagnostic.location.file}:${diagnostic.location.line}:${diagnostic.location.column}`\n : \"\";\n const count =\n diagnostic.count !== undefined && diagnostic.count > 1 ? ` (×${diagnostic.count})` : \"\";\n lines.push(\n ` ${diagnostic.severity} ${diagnostic.code}${where}${count}: ${diagnostic.message}`,\n );\n if (diagnostic.hint) lines.push(` ${diagnostic.hint}`);\n }\n for (const shot of verdict.screenshots.filter((screenshot) => screenshot.returned)) {\n lines.push(` screenshot ${shot.viewport}: ${shot.path}`);\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\n/** `mostra verify <path>`. */\nexport const verifyCommand: CommandDef = defineCommand({\n path: [\"verify\"],\n summary: \"Build, render and check an artifact's source; one verdict, nothing published.\",\n args: [{ name: \"path\", summary: \"The artifact's source: a file, a directory, or its ID.\" }],\n flags: [\n {\n name: \"screenshots\",\n kind: \"string\",\n value: \"<when>\",\n choices: [\"on-failure\", \"always\", \"never\"],\n default: \"on-failure\",\n summary: \"Which screenshots the verdict marks as worth looking at.\",\n },\n ],\n output: { type: \"VerifyVerdict\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"verify ./sidebar-review\",\n async run(context) {\n const connection = await context.connection();\n const progressToken = randomUUID();\n connection?.onNotification(ARTIFACT_PROGRESS, (params) => {\n const { progressToken: token, stage } = (params ?? {}) as {\n progressToken?: string;\n stage?: string;\n };\n if (token === progressToken && typeof stage === \"string\") context.log(`verify: ${stage}`);\n });\n const screenshots = flag(context, \"screenshots\") as\n | \"on-failure\"\n | \"always\"\n | \"never\"\n | undefined;\n const verdict = await context.call(artifactVerifyMethod, {\n source: sourceRef(arg(context, \"path\"), context.cwd),\n progressToken,\n ...(screenshots !== undefined ? { screenshots } : {}),\n });\n context.record({\n event: \"verify.result\",\n fields: {\n status: verdict.status,\n codes: verdict.diagnostics.map((diagnostic) => diagnostic.code),\n },\n });\n return {\n result: verdict,\n human: verdictText(verdict),\n // Only a verdict this CLI knows means passing exits 0: a newer instance's status it doesn't\n // know (#45 lets it arrive) fails the command, never passes it (Opus review of MT-01, 2).\n ...(verdict.status === \"pass\" ? {} : { exit: EXIT.failure }),\n };\n },\n});\n\nconst POLICIES: Readonly<Record<string, SubmissionPolicy>> = {\n once: { policy: \"once\", scope: \"per-artifact\" },\n \"once-per-viewer\": { policy: \"once\", scope: \"per-viewer\" },\n epochs: { policy: \"epochs\" },\n none: { policy: \"none\" },\n};\n\n/** `mostra publish <path>`. */\nexport const publishCommand: CommandDef = defineCommand({\n path: [\"publish\"],\n summary:\n \"Publish an artifact's source as a new immutable version, gated by verify, and print its link.\",\n args: [{ name: \"path\", summary: \"The artifact's source: a file, a directory, or its ID.\" }],\n flags: [\n {\n name: \"force\",\n kind: \"boolean\",\n summary: \"Publish despite verify's errors and record their codes; never what didn't build.\",\n },\n {\n name: \"policy\",\n kind: \"string\",\n value: \"<policy>\",\n choices: Object.keys(POLICIES),\n summary: \"The submission policy to use, instead of the manifest's.\",\n },\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retry return the first attempt's receipt.\",\n },\n ],\n output: { type: \"PublishReceipt\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.conflict],\n example: \"publish ./sidebar-review\",\n async run(context) {\n const policyName = flag(context, \"policy\");\n const requestId = flag(context, \"request-id\");\n const force = context.flags[\"force\"] === true;\n const receipt = await context.call(artifactPublishMethod, {\n source: sourceRef(arg(context, \"path\"), context.cwd),\n ...(force ? { force: true } : {}),\n ...(policyName !== undefined ? { policy: POLICIES[policyName] as SubmissionPolicy } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n });\n context.record({ event: \"publish.done\", fields: { reused: receipt.reused, forced: force } });\n const forced =\n receipt.forcedDiagnostics !== undefined && receipt.forcedDiagnostics.length > 0\n ? `Forced past: ${receipt.forcedDiagnostics.join(\", \")}\\n`\n : \"\";\n return {\n result: receipt,\n human: `${receipt.reused ? \"Already published\" : \"Published\"} version ${receipt.version} (${receipt.versionId}) of ${receipt.artifactId}\\n${forced}${receipt.url ?? \"\"}\\n`,\n };\n },\n});\n\n/** `mostra export <artifact> --as bundle --out <path>`. */\nexport const exportCommand: CommandDef = defineCommand({\n path: [\"export\"],\n summary: \"Write a published version out of the home, as a portable bundle another home can run.\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n flags: [\n {\n name: \"as\",\n kind: \"string\",\n value: \"<class>\",\n choices: [\"bundle\"],\n default: \"bundle\",\n summary: \"What to write: `bundle`, the version's builds, manifest, lockfile and source.\",\n },\n {\n name: \"out\",\n kind: \"string\",\n value: \"<path>\",\n summary: \"Where: a new directory, or one archive when it ends in .tar.zst.\",\n },\n {\n name: \"version\",\n kind: \"string\",\n value: \"<number|id>\",\n summary: \"The version. Default: the latest.\",\n },\n ],\n output: { type: \"ArtifactExportResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"export ./sidebar-review --out ./sidebar-review.tar.zst\",\n async run(context) {\n const out = flag(context, \"out\");\n if (out === undefined) throw usage('\"mostra export\" needs --out <path>.');\n const version = flag(context, \"version\");\n const result = await context.call(artifactExportMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n as: \"bundle\",\n out: resolve(context.cwd, out),\n ...(version !== undefined\n ? { version: /^\\d+$/.test(version) ? Number(version) : version }\n : {}),\n });\n return {\n result,\n human: `Exported ${result.versionId} to ${result.files.join(\", \")}\\n`,\n };\n },\n});\n\n/** `mostra run <bundle>`. */\nexport const runCommand: CommandDef = defineCommand({\n path: [\"run\"],\n summary:\n \"Make a bundle `mostra export` wrote a version of this home, with the same IDs, and print its link.\",\n args: [{ name: \"bundle\", summary: \"The bundle: its directory or its .tar.zst archive.\" }],\n flags: [\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retry return the first attempt's receipt.\",\n },\n ],\n output: { type: \"PublishReceipt\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"run ./sidebar-review.tar.zst\",\n async run(context) {\n const requestId = flag(context, \"request-id\");\n const receipt = await context.call(artifactImportMethod, {\n bundle: resolve(context.cwd, arg(context, \"bundle\")),\n ...(requestId !== undefined ? { requestId } : {}),\n });\n return {\n result: receipt,\n human: `${receipt.reused ? \"Already here\" : \"Imported\"}: version ${receipt.version} (${receipt.versionId}) of ${receipt.artifactId}\\n${receipt.url ?? \"\"}\\n`,\n };\n },\n});\n\n/** `mostra add <package…>`. */\nexport const addCommand: CommandDef = defineCommand({\n path: [\"add\"],\n summary:\n \"Add npm packages to an artifact's lockfile at exact versions, installing them into the home's store.\",\n args: [\n {\n name: \"package\",\n summary: \"npm specs: name, name@version, name@range or name@tag.\",\n variadic: true,\n },\n ],\n flags: [\n {\n name: \"artifact\",\n kind: \"string\",\n value: \"<path|id>\",\n summary: \"The artifact. Default: the one in the current directory.\",\n },\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retry return the first attempt's result.\",\n },\n ],\n output: { type: \"DepsAddResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"add recharts@3 --artifact ./dashboard\",\n async run(context) {\n const packages = context.args[\"package\"];\n if (!Array.isArray(packages) || packages.length === 0)\n throw usage('\"mostra add\" needs <package…>.');\n const requestId = flag(context, \"request-id\");\n const result = await context.call(depsAddMethod, {\n artifact: sourceRef(flag(context, \"artifact\") ?? \".\", context.cwd),\n packages: packages as string[],\n ...(requestId !== undefined ? { requestId } : {}),\n });\n return {\n result,\n human: result.packages\n .map((added) => `${added.name}@${added.version}${added.warm ? \" (warm set)\" : \"\"}\\n`)\n .join(\"\"),\n };\n },\n});\n","/**\n * `mostra dev` (VR-08, D140 item 12): a development preview of unpublished source with hot\n * reload, until Ctrl-C. It prints the preview's link and then what happens in the session (built,\n * reloaded, server restarted, submissions with their Results, diagnostics) as a stream: NDJSON\n * envelopes with `--json`, lines otherwise. Viewers never reach a preview; it isn't a version.\n */\nimport {\n createDiagnostic,\n DEV_NOTIFY,\n type DevNotifyParams,\n type Diagnostic,\n devStartMethod,\n devStopMethod,\n RpcError,\n} from \"@mostra/protocol\";\nimport { type CommandDef, defineCommand } from \"../command.ts\";\nimport { EXIT } from \"../exit.ts\";\nimport { arg, sourceRef } from \"./shared.ts\";\n\n/** One event's line without `--json`. */\nfunction line(event: DevNotifyParams): string {\n const files = event.files && event.files.length > 0 ? `: ${event.files.join(\", \")}` : \"\";\n switch (event.kind) {\n case \"built\":\n return `Updated${files}\\n`;\n case \"reloaded\":\n return `Reloaded${files}\\n`;\n case \"server-restarted\":\n return `Server code restarted${files}\\n`;\n case \"submission\":\n return `Submission recorded (not delivered):\\n${JSON.stringify(event.results, null, 2)}\\n`;\n case \"diagnostics\":\n return `${(event.diagnostics ?? [])\n .map((diagnostic: Diagnostic) => `${diagnostic.code}: ${diagnostic.message}`)\n .join(\"\\n\")}\\n`;\n }\n}\n\nexport const devCommand: CommandDef = defineCommand({\n path: [\"dev\"],\n summary:\n \"Preview an artifact's unpublished source with hot reload, until Ctrl-C; viewers never see it.\",\n args: [{ name: \"path\", summary: \"The artifact's source: a file, a directory, or its ID.\" }],\n flags: [\n {\n name: \"port\",\n kind: \"number\",\n value: \"<port>\",\n summary: \"The preview's port on 127.0.0.1; default one the system picks.\",\n },\n ],\n output: { type: \"DevStartResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: \"dev ./sidebar-review\",\n streams: true,\n async run(context) {\n // The session lasts until Ctrl-C (or SIGTERM; Ctrl+Break on Windows), or until the instance\n // ends it. The handlers are in place before anything starts or is printed: a Ctrl-C between\n // \"started\" and a later handler met Node's default action and ended the process without\n // stopping the session or printing its result (#110's CI).\n const signals = [\"SIGINT\", \"SIGTERM\", \"SIGBREAK\"] as const;\n let interrupted = false;\n let stop: () => void = () => {\n interrupted = true;\n };\n const onSignal = (): void => stop();\n for (const signal of signals) process.once(signal, onSignal);\n const release = (): void => {\n for (const signal of signals) process.off(signal, onSignal);\n };\n try {\n const connection = await context.connection();\n let sessionId: string | undefined;\n const early: DevNotifyParams[] = [];\n const show = (event: DevNotifyParams): void => {\n if (event.kind === \"diagnostics\") {\n for (const diagnostic of event.diagnostics ?? []) context.warn(diagnostic);\n }\n context.emit(event, line(event));\n };\n connection?.onNotification(DEV_NOTIFY, (params) => {\n const event = params as DevNotifyParams;\n if (sessionId === undefined) early.push(event);\n else if (event.sessionId === sessionId) show(event);\n });\n const portFlag = context.flags[\"port\"];\n const started = await context.call(devStartMethod, {\n source: sourceRef(arg(context, \"path\"), context.cwd),\n ...(typeof portFlag === \"number\" ? { port: portFlag } : {}),\n });\n sessionId = started.sessionId;\n context.emit(\n { kind: \"started\", ...started },\n `Development preview, not published: ${started.url}\\nPress Ctrl-C to stop.\\n`,\n );\n for (const event of early.splice(0)) if (event.sessionId === sessionId) show(event);\n const ended = interrupted\n ? \"signal\"\n : await new Promise<\"signal\" | \"closed\">((done) => {\n stop = (): void => done(\"signal\");\n void connection?.closed.then(() => done(\"closed\"));\n });\n // A second Ctrl-C from here on ends the process, as before.\n release();\n if (ended === \"closed\") {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: \"The instance ended the development preview (it stopped or restarted).\",\n hint: \"Run mostra dev again.\",\n }),\n );\n }\n await context.call(devStopMethod, { sessionId }).catch(() => undefined);\n return {\n result: { sessionId, stopped: \"signal\" },\n human: \"Stopped.\\n\",\n };\n } finally {\n release();\n }\n },\n});\n","/**\n * Interaction: `wait`, `results`, `push` and `state get|set|patch`, thin clients of `wait`,\n * `results/get`, `live/push` and `state/*` (INTERFACES §6, D101). `wait` ends with exit 5 when it\n * times out (`still_waiting`), and a write that meets a conflict with exit 6.\n */\nimport {\n FieldOp,\n livePushMethod,\n MutationId,\n resultsGetMethod,\n stateGetMethod,\n statePatchMethod,\n type WaitCondition,\n type WaitResult,\n waitMethod,\n} from \"@mostra/protocol\";\nimport { type CommandDef, defineCommand } from \"../command.ts\";\nimport { EXIT } from \"../exit.ts\";\nimport { durationMs, usage } from \"../parse.ts\";\nimport { arg, artifactRef, flag, jsonInput, parseJson, pretty } from \"./shared.ts\";\n\n/** The longest one `wait` request may ask for (INTERFACES §6: 2^31 − 1 ms). */\nconst MAX_WAIT_MS = 2 ** 31 - 1;\n\n/**\n * What `wait` prints when its condition held: the event and cursor, and for a signal its name and\n * the payload the page or action sent (#115), which is otherwise only in `--json`.\n */\nexport function satisfiedLine(\n event: { readonly type: string; readonly payload?: Readonly<Record<string, unknown>> },\n cursor: string,\n): string {\n const line = `${event.type} at cursor ${cursor}`;\n if (event.type !== \"signal.raised\") return `${line}\\n`;\n const name = typeof event.payload?.[\"name\"] === \"string\" ? ` ${event.payload[\"name\"]}` : \"\";\n const payload =\n event.payload !== undefined && Object.hasOwn(event.payload, \"payload\")\n ? `\\npayload: ${JSON.stringify(event.payload[\"payload\"])}`\n : \"\";\n return `${event.type}${name} at cursor ${cursor}${payload}\\n`;\n}\n\n/** `mostra wait <artifact>`. */\nexport const waitCommand: CommandDef = defineCommand({\n path: [\"wait\"],\n summary:\n \"Block until an artifact's submission, signal, state change or event; still_waiting on timeout.\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n flags: [\n {\n name: \"until\",\n kind: \"string\",\n value: \"<condition>\",\n summary: \"submitted, signal:<name>, state:<fieldId> or event:<type>.\",\n },\n {\n name: \"after\",\n kind: \"string\",\n value: \"<cursor>\",\n summary: \"Wait for what comes after this cursor. Default: the latest publish.\",\n },\n {\n name: \"timeout\",\n kind: \"duration\",\n value: \"<d>\",\n summary: \"Stop waiting after this long, with still_waiting and exit 5. Default: no limit.\",\n },\n ],\n output: { type: \"WaitResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.stillWaiting],\n example: \"wait ./sidebar-review --until submitted --timeout 30m\",\n async run(context) {\n const until = flag(context, \"until\");\n if (until === undefined) throw usage('\"mostra wait\" needs --until, such as --until submitted.');\n const timeout = flag(context, \"timeout\");\n const deadline = timeout === undefined ? undefined : Date.now() + durationMs(timeout);\n const artifact = artifactRef(arg(context, \"artifact\"), context.cwd);\n let after = flag(context, \"after\");\n for (;;) {\n const remaining = deadline === undefined ? MAX_WAIT_MS : Math.max(0, deadline - Date.now());\n const result: WaitResult = await context.call(waitMethod, {\n artifact,\n until: until as WaitCondition,\n timeoutMs: Math.min(remaining, MAX_WAIT_MS),\n ...(after !== undefined ? { after } : {}),\n });\n if (result.status === \"satisfied\") {\n return { result, human: satisfiedLine(result.event, result.cursor) };\n }\n // Waiting again is for still_waiting alone: an answer a newer instance gives that this CLI\n // doesn't know ends the wait as a failure, so it is neither looped on nor taken for a\n // submission (Opus review of MT-01, 2).\n if (result.status !== \"still_waiting\") {\n return {\n result,\n // The type names only the statuses this CLI was built with; the value may be newer.\n human: `wait ended with \"${String((result as { status: unknown }).status)}\", which this CLI doesn't know\\n`,\n exit: EXIT.failure,\n };\n }\n // No limit: wait again from the newest cursor examined, so nothing is missed.\n if (deadline === undefined) {\n after = result.cursor;\n continue;\n }\n return {\n result,\n human: `still waiting; resume with --after ${result.cursor}\\n`,\n exit: EXIT.stillWaiting,\n };\n }\n },\n});\n\n/** `mostra results <artifact>`. */\nexport const resultsCommand: CommandDef = defineCommand({\n path: [\"results\"],\n summary:\n \"Print an artifact's submission in full: answers, state, choices, comments, actions and signals.\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n flags: [\n {\n name: \"submission\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"This submission instead of the latest.\",\n },\n {\n name: \"format\",\n kind: \"string\",\n value: \"<format>\",\n choices: [\"md\", \"json\"],\n summary: \"Markdown or JSON. Default: Markdown, or JSON with --json.\",\n },\n ],\n output: { type: \"Results\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"results ./sidebar-review\",\n async run(context) {\n const format = (flag(context, \"format\") ?? (context.json ? \"json\" : \"md\")) as \"md\" | \"json\";\n const submission = flag(context, \"submission\");\n const result = await context.call(resultsGetMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n format,\n ...(submission !== undefined ? { submission } : {}),\n });\n const markdown =\n typeof result === \"object\" && result !== null && \"markdown\" in result\n ? (result as { markdown: string }).markdown\n : undefined;\n return { result, human: markdown !== undefined ? `${markdown.trimEnd()}\\n` : pretty(result) };\n },\n});\n\n/** `mostra push <artifact> <key>`. */\nexport const pushCommand: CommandDef = defineCommand({\n path: [\"push\"],\n summary: \"Push a value into an artifact's live source; pages showing it update at once.\",\n args: [\n { name: \"artifact\", summary: \"The artifact: its source path or its ID.\" },\n { name: \"key\", summary: \"The live source's key: its export name in live.ts, or a new one.\" },\n ],\n flags: [\n { name: \"value\", kind: \"string\", value: \"<json>\", summary: \"The value, as JSON.\" },\n { name: \"file\", kind: \"string\", value: \"<path>\", summary: \"Read the value from a JSON file.\" },\n { name: \"stdin\", kind: \"boolean\", summary: \"Read the value from stdin.\" },\n {\n name: \"append\",\n kind: \"boolean\",\n summary: \"Add the value to the source's ring instead of replacing it.\",\n },\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retry return the first attempt's revision.\",\n },\n ],\n output: { type: \"LivePushResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: `push ./dashboard prices --value '{\"btc\": 64000}'`,\n readsStdin: (flags) => flags[\"stdin\"] === true,\n async run(context) {\n const value = await jsonInput(context);\n const requestId = flag(context, \"request-id\");\n const result = await context.call(livePushMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n key: arg(context, \"key\"),\n value,\n ...(context.flags[\"append\"] === true ? { mode: \"append\" as const } : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n });\n return { result, human: `revision ${result.revision}\\n` };\n },\n});\n\nconst writeFlags = [\n {\n name: \"base\",\n kind: \"string\" as const,\n value: \"<revision>\",\n summary:\n \"Write only if the fields are unchanged since this revision; else a conflict (exit 6).\",\n },\n {\n name: \"as\",\n kind: \"string\" as const,\n value: \"<actor>\",\n choices: [\"agent\", \"host\"],\n default: \"agent\",\n summary: \"Who the change is attributed to.\",\n },\n {\n name: \"mutation-id\",\n kind: \"string\" as const,\n value: \"<mut_…>\",\n summary: \"Make a retry return the first attempt's result.\",\n },\n];\n\n/** `mostra state get <artifact> [ids…]`. */\nexport const stateGetCommand: CommandDef = defineCommand({\n path: [\"state\", \"get\"],\n summary: \"Read an artifact's state: the fields every viewer shares, with their revisions.\",\n args: [\n { name: \"artifact\", summary: \"The artifact: its source path or its ID.\" },\n { name: \"id\", summary: \"Only these field IDs.\", optional: true, variadic: true },\n ],\n output: { type: \"StateGetResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"state get ./tasks priorities\",\n async run(context) {\n const ids = context.args[\"id\"] as readonly string[] | undefined;\n const result = await context.call(stateGetMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n ...(ids !== undefined && ids.length > 0 ? { ids: [...ids] } : {}),\n });\n return { result, human: pretty(result) };\n },\n});\n\n/** Sends one state mutation; a conflict ends with exit 6. */\nasync function patch(\n context: Parameters<(typeof stateGetCommand)[\"run\"]>[0],\n ops: readonly FieldOp[],\n): Promise<{ result: unknown; human: string; exit?: number }> {\n const base = flag(context, \"base\");\n const as = (flag(context, \"as\") ?? \"agent\") as \"agent\" | \"host\";\n const result = await context.call(statePatchMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n ops,\n mutationId: flag(context, \"mutation-id\") ?? MutationId.create(),\n as,\n ...(base !== undefined ? { baseRevision: base } : {}),\n });\n const conflicted = result.conflicts.length > 0;\n return {\n result,\n human: conflicted\n ? `conflict on ${result.conflicts.map((conflict) => conflict.id).join(\", \")}; revision ${result.revision}\\n`\n : `revision ${result.revision}\\n`,\n ...(conflicted ? { exit: EXIT.conflict } : {}),\n };\n}\n\n/** `mostra state set <artifact> <id> <json>`. */\nexport const stateSetCommand: CommandDef = defineCommand({\n path: [\"state\", \"set\"],\n summary: \"Set one field of an artifact's state; viewers see it at once.\",\n args: [\n { name: \"artifact\", summary: \"The artifact: its source path or its ID.\" },\n { name: \"id\", summary: \"The field ID.\" },\n { name: \"value\", summary: \"The value, as JSON.\" },\n ],\n flags: writeFlags,\n output: { type: \"StatePatchResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.conflict],\n example: `state set ./tasks priorities '[\"Ship the CLI\"]'`,\n async run(context) {\n return patch(context, [\n { id: arg(context, \"id\"), value: parseJson(arg(context, \"value\"), \"<value>\") },\n ]);\n },\n});\n\n/** `mostra state patch <artifact>`. */\nexport const statePatchCommand: CommandDef = defineCommand({\n path: [\"state\", \"patch\"],\n summary:\n \"Change several fields of an artifact's state in one revision: [{ id, value } | { id, delete: true }].\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n flags: [\n { name: \"ops\", kind: \"string\", value: \"<json>\", summary: \"The operations, as JSON.\" },\n {\n name: \"file\",\n kind: \"string\",\n value: \"<path>\",\n summary: \"Read the operations from a JSON file.\",\n },\n { name: \"stdin\", kind: \"boolean\", summary: \"Read the operations from stdin.\" },\n ...writeFlags,\n ],\n output: { type: \"StatePatchResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.conflict],\n example: `state patch ./tasks --file ops.json`,\n readsStdin: (flags) => flags[\"stdin\"] === true,\n async run(context) {\n const ops = await jsonInput(context, \"ops\");\n const parsed = FieldOp.array().safeParse(ops);\n if (!parsed.success || parsed.data.length === 0) {\n throw usage(\n \"The operations must be a non-empty JSON array of { id, value } or { id, delete: true }.\",\n );\n }\n return patch(context, parsed.data);\n },\n});\n","/**\n * Opening a browser on a launch URL without putting it on a command line (D140 item 15, Opus\n * review finding 4). A program's arguments are readable by every local user (`ps`,\n * `/proc/<pid>/cmdline`), so the opener gets the path of a page that redirects to the launch URL,\n * written mode 0600 in a fresh directory of mode 0700, as Jupyter's server does for its token.\n * Windows has no modes: there the page goes under the user's own profile\n * (`%LOCALAPPDATA%\\mostra-cli\\open`), whose access list only the user, `SYSTEM` and\n * administrators pass, never under `%TEMP%`, which may name a folder other users can read (Opus\n * review of WP-W2, finding 1). The launch ticket in the page is single-use and lives a minute, so a\n * page left behind is harmless; each launch removes the ones older than that.\n */\nimport { spawn } from \"node:child_process\";\nimport { lstatSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { homedir, tmpdir } from \"node:os\";\nimport { join, win32 } from \"node:path\";\nimport type { Environment } from \"./home.ts\";\n\n/** The prefix of the directories launch pages live in. */\nconst PREFIX = \"mostra-open-\";\n/** A launch page older than this holds a ticket that expired: it goes on the next launch. */\nconst STALE_MS = 2 * 60_000;\n\n/** Escapes text for an HTML attribute or element. */\nconst html = (text: string): string =>\n text\n .replaceAll(\"&\", \"&\")\n .replaceAll('\"', \""\")\n .replaceAll(\"<\", \"<\")\n .replaceAll(\">\", \">\");\n\n/** The page that sends the browser on to `url`. */\nexport function launchPage(url: string): string {\n // JSON in a script, with `<` escaped so nothing in it ends the script element.\n const script = JSON.stringify(url).replaceAll(\"<\", \"\\\\u003c\");\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"utf-8\">\n<meta name=\"referrer\" content=\"no-referrer\">\n<meta http-equiv=\"refresh\" content=\"0;url=${html(url)}\">\n<title>Opening Mostra</title>\n<script>location.replace(${script});</script>\n</head>\n<body>\n<p>Opening the artifact. If nothing happens, <a href=\"${html(url)}\">open it here</a>.</p>\n</body>\n</html>\n`;\n}\n\n/** Removes launch pages of earlier launches that are this user's and older than a minute or two. */\nfunction sweep(base: string, now: number): void {\n const uid = process.getuid?.();\n let names: string[];\n try {\n names = readdirSync(base);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.startsWith(PREFIX)) continue;\n const dir = join(base, name);\n try {\n const stats = lstatSync(dir);\n if (!stats.isDirectory() || (uid !== undefined && stats.uid !== uid)) continue;\n if (now - stats.mtimeMs < STALE_MS) continue;\n rmSync(dir, { recursive: true, force: true });\n } catch {\n // Gone already, or not ours to remove.\n }\n }\n}\n\n/** Writes the launch page for `url`; its path. */\nexport function writeLaunchPage(\n url: string,\n base: string = tmpdir(),\n now: number = Date.now(),\n): string {\n sweep(base, now);\n // mkdtemp makes the directory with a random name and mode 0700.\n const dir = mkdtempSync(join(base, PREFIX));\n const file = join(dir, \"open.html\");\n writeFileSync(file, launchPage(url), { mode: 0o600, flag: \"wx\" });\n return file;\n}\n\n/**\n * Splits a command the way a shell would split plain words and quotes, without running one:\n * `firefox --new-window %s` or `\"/Applications/My Browser\" %s`.\n */\nexport function splitCommand(command: string): string[] {\n const words: string[] = [];\n let word = \"\";\n let inWord = false;\n let quote: '\"' | \"'\" | undefined;\n for (let index = 0; index < command.length; index += 1) {\n const char = command[index] as string;\n if (quote) {\n if (char === quote) quote = undefined;\n else if (char === \"\\\\\" && quote === '\"' && index + 1 < command.length) {\n index += 1;\n word += command[index];\n } else word += char;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char;\n inWord = true;\n } else if (char === \"\\\\\" && index + 1 < command.length) {\n index += 1;\n word += command[index];\n inWord = true;\n } else if (/\\s/.test(char)) {\n if (inWord) words.push(word);\n word = \"\";\n inWord = false;\n } else {\n word += char;\n inWord = true;\n }\n }\n if (inWord) words.push(word);\n return words;\n}\n\n/** The program that opens a file with its default application, by platform. */\nfunction platformOpener(platform: string): string[] {\n if (platform === \"darwin\") return [\"open\"];\n // Explorer opens a path with the program associated with its type, `.html` with the default\n // browser, as a double click would (VERIFIED_FACTS, WP-W2); its arguments go to it directly,\n // never through `cmd`.\n if (platform === \"win32\") return [\"explorer.exe\"];\n return [\"xdg-open\"];\n}\n\n/**\n * Splits a command as Windows programs read their command lines, for `$BROWSER` there: words\n * separated by spaces, double quotes grouping words with spaces (`\"C:\\Program Files\\Firefox\\\n * firefox.exe\" %s`), and backslashes kept as they are.\n */\nexport function splitWindowsCommand(command: string): string[] {\n const words: string[] = [];\n let word = \"\";\n let inWord = false;\n let quoted = false;\n for (const char of command) {\n if (char === '\"') {\n quoted = !quoted;\n inWord = true;\n } else if (!quoted && /\\s/.test(char)) {\n if (inWord) words.push(word);\n word = \"\";\n inWord = false;\n } else {\n word += char;\n inWord = true;\n }\n }\n if (inWord) words.push(word);\n return words;\n}\n\n/**\n * The commands that may open `target`, in order: each entry of `$BROWSER` (separated by the\n * platform's path delimiter, `:` or `;` on Windows, its `%s` replaced by the target, else the\n * target appended, `%%` a literal `%`, as `xdg-open` and Python's `webbrowser` read it), else the\n * platform's opener.\n */\nexport function browserCommands(\n target: string,\n env: Environment,\n platform: string = process.platform,\n): string[][] {\n const chosen = env[\"BROWSER\"];\n if (chosen === undefined || chosen.trim() === \"\") return [[...platformOpener(platform), target]];\n const entries = chosen\n .split(platform === \"win32\" ? \";\" : \":\")\n .filter((entry) => entry.trim() !== \"\");\n const commands: string[][] = [];\n for (const entry of entries) {\n // A Windows path's backslashes are separators, never escapes.\n const words = platform === \"win32\" ? splitWindowsCommand(entry) : splitCommand(entry);\n if (words.length === 0) continue;\n let substituted = false;\n const argv = words.map((word) =>\n word.replaceAll(/%%|%s/g, (match) => {\n if (match === \"%%\") return \"%\";\n substituted = true;\n return target;\n }),\n );\n commands.push(substituted ? argv : [...argv, target]);\n }\n return commands;\n}\n\n/** Starts one command, detached; whether it started (its program was found and could run). */\nfunction start(argv: readonly string[]): Promise<boolean> {\n const [program, ...args] = argv;\n if (program === undefined) return Promise.resolve(false);\n return new Promise((resolve) => {\n try {\n const child = spawn(program, args, { detached: true, stdio: \"ignore\" });\n child.once(\"spawn\", () => {\n child.unref();\n resolve(true);\n });\n child.once(\"error\", () => resolve(false));\n } catch {\n resolve(false);\n }\n });\n}\n\n/**\n * Where launch pages go: the system's temporary directory on POSIX (the page's modes protect it),\n * the user's own profile on Windows, whatever `%TEMP%` names.\n */\nexport function launchBase(env: Environment, platform: string = process.platform): string {\n if (platform !== \"win32\") return tmpdir();\n const local = env[\"LOCALAPPDATA\"];\n const base =\n local !== undefined && local !== \"\" && win32.isAbsolute(local)\n ? local\n : win32.join(homedir(), \"AppData\", \"Local\");\n return win32.join(base, \"mostra-cli\", \"open\");\n}\n\n/** Opens `url` in a browser through a launch page; whether a browser command started. */\nexport async function openInBrowser(url: string, env: Environment): Promise<boolean> {\n let page: string;\n try {\n const base = launchBase(env);\n mkdirSync(base, { recursive: true, mode: 0o700 });\n page = writeLaunchPage(url, base);\n } catch {\n return false;\n }\n for (const command of browserCommands(page, env)) {\n if (await start(command)) return true;\n }\n return false;\n}\n","/**\n * The CLI's connection to its home's instance (D45, D81, INTERFACES §9): it attaches to the\n * daemon recorded in `instance.json`, or starts one (`mostra-runtime daemon`, which itself\n * attaches when another starter won), and opens a session as `mostra-cli`. The SDK (WP-11) does\n * the same few steps over the same protocol.\n */\nimport { spawn } from \"node:child_process\";\nimport { readFileSync } from \"node:fs\";\nimport { join, resolve } from \"node:path\";\nimport type { Duplex } from \"node:stream\";\nimport {\n ARTIFACT_PROGRESS,\n CLI_CLIENT_NAME,\n createDiagnostic,\n DEV_NOTIFY,\n type Diagnostic,\n encodeLine,\n HOST_PROTOCOL_REVISIONS,\n LineSplitter,\n type MethodDefinition,\n type MostraInitializeResult,\n mostraInitializeMethod,\n RpcError,\n RpcPeer,\n} from \"@mostra/protocol\";\nimport { connectControl, type Runtime } from \"@mostra/sdk\";\nimport { detachedDirectory, detachedEnvironment } from \"./detached.ts\";\nimport { type Environment, locateRuntime } from \"./home.ts\";\nimport { cliVersion } from \"./version.ts\";\n\n/** The instance a command reached: the `instance` of the `--json` envelope (the attach target). */\nexport interface InstanceSummary {\n /** The home it owns. */\n readonly home: string;\n /** The control socket the CLI reached. */\n readonly socket: string;\n /** Its process ID. */\n readonly pid: number;\n /** `daemon`, or `host` for an instance a host spawned (telemetry sends nothing then, D140). */\n readonly mode: \"host\" | \"daemon\" | \"hosted\";\n /** The runtime's release. */\n readonly version: string;\n /** Whether this command started the daemon. */\n readonly started: boolean;\n}\n\n/** An open session with the home's instance. */\nexport interface InstanceConnection {\n /** What the instance is. */\n readonly summary: InstanceSummary;\n /** `mostra/initialize`'s warnings. */\n readonly warnings: readonly Diagnostic[];\n /** Calls a host protocol method. */\n call<P, R>(method: MethodDefinition<P, R>, params: P, timeoutMs?: number): Promise<R>;\n /** Registers a handler for a notification (`artifact/progress`, `dev/notify`). */\n onNotification(method: string, handler: (params: unknown) => void): void;\n /** Resolves when the connection closes. */\n readonly closed: Promise<void>;\n /** Ends the session. */\n close(): void;\n}\n\n/** How to reach an instance. */\nexport interface ConnectOptions {\n readonly home: string;\n readonly env: Environment;\n /** Start the daemon when none runs. Default true. */\n readonly autostart?: boolean;\n /**\n * Told when this connection starts the home's daemon (`true`) and when the start ends\n * (`false`), so the command's own `--timeout` names the start if it runs out during it.\n */\n readonly onStarting?: (starting: boolean) => void;\n}\n\n/** How long one attempt to reach a recorded socket waits. */\nconst ATTACH_TIMEOUT_MS = 5000;\n/** How long a daemon this command starts may take to say where it listens. */\nconst START_TIMEOUT_MS = 30_000;\n\n/**\n * Opens a session with the home's instance, starting its daemon when none runs. Returns\n * `undefined` when `autostart` is false and no instance runs. Throws the start's diagnostic when\n * the daemon can't start (`MOSTRA_HOME_LOCKED`, `MOSTRA_PLATFORM_UNSUPPORTED` …).\n */\nexport async function connect(options: ConnectOptions): Promise<InstanceConnection | undefined> {\n const recorded = readSocket(options.home);\n if (recorded !== undefined) {\n const session = await open(recorded, options, false).catch(() => undefined);\n if (session) return session;\n }\n if (options.autostart === false) return undefined;\n options.onStarting?.(true);\n let started: DaemonLine;\n try {\n started = await startDaemon(options);\n } finally {\n options.onStarting?.(false);\n }\n return open(started.socket, options, started.status === \"started\");\n}\n\n/**\n * Opens the endpoint `instance.json` or a starting daemon named: a Unix socket, or on Windows the\n * owner-only pipe through the runtime's helper, which refuses a pipe another user created under\n * the name (D150, the SDK's `connectControl`). Only Windows needs the runtime resolved first.\n */\nasync function openEndpoint(endpoint: string, options: ConnectOptions): Promise<Duplex> {\n const runtime: Runtime | undefined =\n process.platform === \"win32\" ? (await locateRuntime(options.env)).runtime : undefined;\n return connectControl(endpoint, { runtime, env: options.env, timeoutMs: ATTACH_TIMEOUT_MS });\n}\n\n/** The socket `instance.json` records (D81), if the file exists and reads. */\nfunction readSocket(home: string): string | undefined {\n try {\n const record = JSON.parse(readFileSync(join(home, \"instance.json\"), \"utf8\")) as {\n socket?: unknown;\n };\n return typeof record.socket === \"string\" ? record.socket : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** What `mostra-runtime daemon` prints on its one line. */\ninterface DaemonLine {\n readonly status: \"started\" | \"attached\" | \"failed\";\n readonly socket: string;\n readonly pid?: number;\n readonly diagnostic?: Diagnostic;\n}\n\n/**\n * Starts the home's daemon, detached from this process, and reads the one line it prints: where\n * it listens, or why it couldn't start. A daemon another starter won prints `attached` and exits.\n */\nexport async function startDaemon(options: ConnectOptions): Promise<DaemonLine> {\n // The start's own limit. A shorter `--timeout` is the command's: its one timer names the\n // start when it runs out during it (run.ts), so two timers never race for one deadline.\n const deadlineAt = Date.now() + START_TIMEOUT_MS;\n const timedOut = (): RpcError =>\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_TIMEOUT\", {\n message: `The home's daemon didn't start within ${formatDuration(START_TIMEOUT_MS)}.`,\n }),\n );\n const runtime = await locateRuntime(options.env);\n if (Date.now() >= deadlineAt) throw timedOut();\n const args = [\n // Absolute: the daemon runs in the file system's root, where a relative entry (a relative\n // `MOSTRA_RUNTIME_BIN`, checked against this process's directory) would name nothing (GPT\n // review of WP-W2).\n resolve(runtime.entry),\n \"daemon\",\n // The home this CLI resolved, so the daemon owns exactly it whatever its own environment.\n \"--home\",\n options.home,\n ];\n return new Promise((resolve, reject) => {\n const child = spawn(runtime.node, args, {\n detached: true,\n // Not the command's directory but its home's file system root, which always exists: the\n // daemon outlives the command by up to 30 idle minutes, and on Windows nobody can remove or\n // rename a running process's working directory, so a project the CLI ran in would stay\n // locked (WP-W2).\n cwd: detachedDirectory(options.home),\n // No console window for the daemon on Windows.\n windowsHide: true,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n env: detachedEnvironment({ ...process.env, ...options.env }) as NodeJS.ProcessEnv,\n });\n const splitter = new LineSplitter();\n let settled = false;\n const finish = (outcome: () => void): void => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n child.stdout?.removeAllListeners(\"data\");\n child.stdout?.destroy();\n child.unref();\n outcome();\n };\n const timer = setTimeout(\n () => finish(() => reject(timedOut())),\n Math.max(0, deadlineAt - Date.now()),\n );\n child.on(\"error\", (error) =>\n finish(() =>\n reject(\n new RpcError(\n createDiagnostic(\"MOSTRA_ENV_RUNTIME_MISSING\", {\n message: `The runtime couldn't be started: ${error.message}`,\n }),\n ),\n ),\n ),\n );\n // `close`, not `exit`: a daemon that found another one prints `attached` and exits at once,\n // and its line may still be in the pipe when `exit` fires.\n child.on(\"close\", (code) =>\n finish(() =>\n reject(\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: `The home's daemon exited (${code ?? \"signal\"}) before it said where it listens.`,\n }),\n ),\n ),\n ),\n );\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n for (const line of splitter.push(chunk)) {\n let parsed: DaemonLine;\n try {\n parsed = JSON.parse(line) as DaemonLine;\n } catch {\n continue;\n }\n finish(() => {\n if (parsed.status === \"failed\") {\n reject(\n new RpcError(\n parsed.diagnostic ??\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: \"The home's daemon failed to start.\",\n }),\n ),\n );\n } else resolve(parsed);\n });\n return;\n }\n });\n });\n}\n\nasync function open(\n socketPath: string,\n options: ConnectOptions,\n started: boolean,\n): Promise<InstanceConnection> {\n const socket = await openEndpoint(socketPath, options);\n const handlers = new Map<string, (params: unknown) => void>();\n const peer = new RpcPeer({\n send: (message) => {\n if (!socket.destroyed) socket.write(encodeLine(message));\n },\n onNotification: (method, params) => handlers.get(method)?.(params),\n });\n let markClosed: () => void = () => {};\n const closedPromise = new Promise<void>((done) => {\n markClosed = done;\n });\n const splitter = new LineSplitter();\n socket.setEncoding(\"utf8\");\n socket.on(\"data\", (chunk: string) => {\n for (const line of splitter.push(chunk)) peer.receiveLine(line);\n });\n const end = (): void => {\n peer.close();\n markClosed();\n };\n socket.on(\"close\", end);\n socket.on(\"error\", () => socket.destroy());\n let result: MostraInitializeResult;\n try {\n result = await peer.call(\n mostraInitializeMethod,\n {\n client: { name: CLI_CLIENT_NAME, version: cliVersion() },\n revisions: [...HOST_PROTOCOL_REVISIONS],\n capabilities: { notifications: [ARTIFACT_PROGRESS, DEV_NOTIFY] },\n ports: [],\n // A check, never a setting (D84): the instance refuses a session for another home.\n home: { path: options.home },\n },\n { timeoutMs: ATTACH_TIMEOUT_MS },\n );\n } catch (error) {\n socket.destroy();\n throw error;\n }\n return {\n summary: {\n home: result.instance.home,\n socket: socketPath,\n pid: result.instance.pid,\n mode: result.instance.mode,\n version: result.instance.version,\n started,\n },\n warnings: result.warnings,\n call: (method, params, timeoutMs) =>\n peer.call(method, params, timeoutMs !== undefined ? { timeoutMs } : {}),\n onNotification: (method, handler) => {\n handlers.set(method, handler);\n },\n closed: closedPromise,\n close: () => {\n peer.close();\n socket.end();\n socket.destroy();\n },\n };\n}\n\n/** A limit as people write it: `250 ms`, `5 s`, `1.5 s`. */\nfunction formatDuration(ms: number): string {\n if (ms < 1000) return `${ms} ms`;\n const seconds = ms / 1000;\n return `${Number.isInteger(seconds) ? seconds : seconds.toFixed(1)} s`;\n}\n","/**\n * `mostra mcp` (INTERFACES §12, D164): serves `@mostra/mcp`'s tools over stdio, or over\n * Streamable HTTP with `--http`, on the home's daemon. Everything the tools need from this\n * computer is here: the session with the daemon (opened on the first call, opened again after the\n * daemon restarts, released after five idle minutes so a server a harness keeps open for a week\n * doesn't keep the daemon from its idle exit), the workspace of artifacts' files, the bundled\n * reference and the browser opener.\n */\nimport { randomBytes } from \"node:crypto\";\nimport type { IncomingMessage } from \"node:http\";\nimport { isIP } from \"node:net\";\nimport { serve } from \"@hono/node-server\";\nimport { serveStdio } from \"@modelcontextprotocol/server/stdio\";\nimport {\n createHttpEndpoint,\n createMcpServerFactory,\n fileDocs,\n localWorkspace,\n MCP_PATH,\n type McpClientInfo,\n type McpDocs,\n type McpInstance,\n} from \"@mostra/mcp\";\nimport {\n ARTIFACT_PROGRESS,\n type ArtifactProgressParams,\n createDiagnostic,\n type MethodDefinition,\n RpcError,\n} from \"@mostra/protocol\";\nimport { resolveRuntime } from \"@mostra/sdk\";\nimport { progressReporter } from \"./bootstrap.ts\";\nimport { openInBrowser } from \"./browser.ts\";\nimport { connect, type InstanceConnection } from \"./client.ts\";\nimport { MCP_GUIDE_LINKS, referenceDir, skillDir } from \"./docs.ts\";\nimport type { Environment } from \"./home.ts\";\n\n/** How long the session with the daemon stays open after the last call. */\nexport const MCP_IDLE_MS: number = 5 * 60_000;\n\n/** How long one call waits for the runtime's first install before it answers that it's still on. */\nexport const MCP_RUNTIME_WAIT_MS: number = 45_000;\n\n/**\n * The runtime `mostra mcp` starts its instance from (D164 item 7). Installed from npm, the server\n * answers its client before the bundle its release pins is there, so it installs it in the\n * background as it starts (`start`), and every call that needs the instance waits for it (`wait`):\n * up to {@link MCP_RUNTIME_WAIT_MS}, then `MOSTRA_ENV_RUNTIME_INSTALLING` with how far it is, while\n * the install goes on. One install serves every call; a failed one is tried again by the next.\n * Anywhere else (inside a bundle, a checkout, `MOSTRA_RUNTIME_BIN`) it resolves at once.\n */\nexport interface RuntimeInstall {\n start(): void;\n wait(): Promise<void>;\n}\n\n/** The runtime install of {@link RuntimeInstall}, reporting its progress through `log`. */\nexport function runtimeInstall(options: {\n readonly env: Environment;\n readonly log: (line: string) => void;\n readonly waitMs?: number;\n}): RuntimeInstall {\n const testWait = Number(options.env[\"MOSTRA_TEST_RUNTIME_WAIT_MS\"]);\n const waitMs =\n options.waitMs ?? (Number.isFinite(testWait) && testWait > 0 ? testWait : MCP_RUNTIME_WAIT_MS);\n const report = progressReporter({\n stderr: (text) => {\n for (const line of text.split(\"\\n\")) if (line.trim() !== \"\") options.log(line.trim());\n },\n stderrTty: false,\n });\n let ready = false;\n let pending: Promise<void> | undefined;\n let done: string | undefined;\n const start = (): Promise<void> => {\n if (pending !== undefined) return pending;\n const installing = resolveRuntime({\n env: options.env,\n onProgress: (progress) => {\n if (progress.step === \"download\") {\n done = `${Math.floor((progress.received / progress.total) * 100)}% downloaded`;\n } else if (progress.step === \"files\") done = \"downloaded, checking its files\";\n else if (progress.step === \"browser\") done = \"fetching the browser verify uses\";\n report(progress);\n },\n }).then(() => {\n ready = true;\n });\n pending = installing;\n installing.catch((error: unknown) => {\n // The next call tries again, and a waiting call is answered with the failure itself.\n if (pending === installing) pending = undefined;\n done = undefined;\n const diagnostic = error instanceof RpcError ? error.diagnostic : undefined;\n options.log(\n `mostra mcp: the runtime's install failed: ${diagnostic?.code ?? \"\"} ${diagnostic?.message ?? String(error)}`.trim(),\n );\n });\n return installing;\n };\n return {\n start() {\n void start().catch(() => {});\n },\n async wait() {\n if (ready) return;\n const installing = start();\n let timer: ReturnType<typeof setTimeout> | undefined;\n const late = new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new RpcError(\n createDiagnostic(\"MOSTRA_ENV_RUNTIME_INSTALLING\", {\n message: `Mostra is installing its runtime for this release (${done ?? \"starting the download\"}); the install goes on.`,\n }),\n ),\n ),\n waitMs,\n );\n timer.unref();\n });\n try {\n await Promise.race([installing, late]);\n } finally {\n clearTimeout(timer);\n }\n },\n };\n}\n\n/** The instance port over the home's daemon, as the CLI reaches it. */\nexport interface DaemonInstance extends McpInstance {\n /** Whether the instance reached is a host-spawned one (then telemetry sends nothing). */\n hostInstance(): boolean;\n /** Ends the session. */\n close(): void;\n}\n\n/** The home's daemon as the MCP server's instance (D164 item 5). */\nexport function daemonInstance(options: {\n readonly home: string;\n readonly env: Environment;\n readonly log: (line: string) => void;\n readonly idleMs?: number;\n readonly runtime?: RuntimeInstall;\n /** How a session is opened: `connect`, or a test's stand-in. */\n readonly connect?: typeof connect;\n}): DaemonInstance {\n const idleMs = options.idleMs ?? MCP_IDLE_MS;\n const runtime = options.runtime;\n const opener = options.connect ?? connect;\n const listeners = new Map<string, (progress: ArtifactProgressParams) => void>();\n let session: Promise<InstanceConnection> | undefined;\n let host = false;\n let inflight = 0;\n let idle: ReturnType<typeof setTimeout> | undefined;\n\n const open = (): Promise<InstanceConnection> => {\n if (session !== undefined) return session;\n const opening = opener({ home: options.home, env: options.env }).then((connection) => {\n if (connection === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: \"No instance runs for this home.\",\n }),\n );\n }\n host = connection.summary.mode === \"host\";\n for (const warning of connection.warnings)\n options.log(`mostra mcp: ${warning.code}: ${warning.message}`);\n connection.onNotification(ARTIFACT_PROGRESS, (params) => {\n const progress = params as ArtifactProgressParams;\n listeners.get(progress.progressToken)?.(progress);\n });\n void connection.closed.then(() => {\n if (session === opening) session = undefined;\n });\n return connection;\n });\n session = opening;\n opening.catch(() => {\n if (session === opening) session = undefined;\n });\n return opening;\n };\n\n const release = (): void => {\n const current = session;\n session = undefined;\n void current?.then((connection) => connection.close()).catch(() => {});\n };\n\n const settle = (): void => {\n inflight -= 1;\n if (inflight > 0) return;\n clearTimeout(idle);\n idle = setTimeout(release, idleMs);\n idle.unref();\n };\n\n return {\n async call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R> {\n inflight += 1;\n clearTimeout(idle);\n try {\n // The runtime first (D164 item 7): a call during its install waits for it, or says so.\n await runtime?.wait();\n const used = open();\n try {\n return await (await used).call(method, params);\n } catch (error) {\n // A daemon that restarted or went idle closed the session: a method that changes\n // nothing is asked again on a new one; a change is never sent twice. Only the session\n // this call used is dropped: calls that fail together then share one new session, and\n // none is left open behind another (Opus review of WP-15, finding 1).\n const closed =\n error instanceof RpcError && error.diagnostic.code === \"MOSTRA_HOST_CONNECTION_CLOSED\";\n if (!closed || method.mutating) throw error;\n if (session === used) session = undefined;\n return await (await open()).call(method, params);\n }\n } finally {\n settle();\n }\n },\n onProgress(token, listener) {\n listeners.set(token, listener);\n return () => listeners.delete(token);\n },\n hostInstance: () => host,\n close() {\n clearTimeout(idle);\n release();\n },\n };\n}\n\n/** The bundled reference (`mostra docs`), read as the MCP server's docs. */\nexport function bundledDocs(): McpDocs {\n return fileDocs({ referenceDir: referenceDir(), skillDir: skillDir(), links: MCP_GUIDE_LINKS });\n}\n\n/** What both transports are given. */\nexport interface ServeOptions {\n readonly home: string;\n readonly env: Environment;\n readonly workspace: string;\n readonly version: string;\n readonly log: (line: string) => void;\n /**\n * Told each MCP client the server serves (for telemetry, which counts each once), with the\n * instance, whose session (when one is open) says whether a host spawned it.\n */\n readonly onClient: (client: McpClientInfo, instance: DaemonInstance) => void;\n}\n\n/** The daemon instance, with the runtime's install started at once (D164 item 7). */\nfunction startInstance(options: ServeOptions): DaemonInstance {\n const runtime = runtimeInstall({ env: options.env, log: options.log });\n runtime.start();\n return daemonInstance({ ...options, runtime });\n}\n\nfunction factoryFor(options: ServeOptions, instance: DaemonInstance) {\n return createMcpServerFactory({\n instance,\n workspace: localWorkspace(options.workspace),\n docs: bundledDocs(),\n browser: { open: (url) => openInBrowser(url, options.env) },\n version: options.version,\n onClient: (client) => options.onClient(client, instance),\n });\n}\n\n/** Resolves when the process is asked to stop: Ctrl-C, SIGTERM, SIGHUP, or Ctrl+Break on Windows. */\nfunction stopSignal(): Promise<string> {\n return new Promise((resolve) => {\n for (const signal of [\"SIGINT\", \"SIGTERM\", \"SIGHUP\", \"SIGBREAK\"] as const) {\n process.once(signal, () => resolve(signal));\n }\n });\n}\n\n/** Serves over stdio until the client closes stdin or the process is stopped. */\nexport async function serveOverStdio(options: ServeOptions): Promise<DaemonInstance> {\n const instance = startInstance(options);\n const handle = serveStdio(factoryFor(options, instance), {\n onerror: (error) => options.log(`mostra mcp: ${error.message}`),\n });\n const ended = new Promise<string>((resolve) => {\n process.stdin.once(\"end\", () => resolve(\"stdin\"));\n process.stdin.once(\"close\", () => resolve(\"stdin\"));\n });\n await Promise.race([ended, stopSignal()]);\n await handle.close().catch(() => {});\n instance.close();\n return instance;\n}\n\n/** The address and URL host of `--bind` and `--url-host` (D99's rules, D164 item 3). */\nexport function mcpBind(options: { readonly bind?: string; readonly urlHost?: string }): {\n readonly address: string;\n readonly urlHost: string;\n} {\n const fail = (message: string): RpcError =>\n new RpcError(createDiagnostic(\"MOSTRA_ENV_BIND_FAILED\", { message }));\n const address = (options.bind ?? \"127.0.0.1\").replace(/^\\[(.*)\\]$/, \"$1\");\n if (isIP(address) === 0)\n throw fail(`--bind takes an IP address, such as 127.0.0.1, not \"${options.bind}\".`);\n if (options.urlHost !== undefined && options.bind === undefined) {\n throw fail(\"--url-host needs --bind: without it the server listens on 127.0.0.1 only.\");\n }\n const canonical = new URL(`http://${isIP(address) === 6 ? `[${address}]` : address}/`).hostname;\n const wildcard = canonical === \"0.0.0.0\" || canonical === \"[::]\" || canonical === \"[::ffff:0:0]\";\n if (wildcard && options.urlHost === undefined) {\n throw fail(\n `--bind ${options.bind} listens on every interface; name the host clients use with --url-host.`,\n );\n }\n if (options.urlHost !== undefined && !/^(\\[[0-9a-f:.]+\\]|[a-z0-9.-]+)$/i.test(options.urlHost)) {\n throw fail(`--url-host takes a host name or an IP address, not \"${options.urlHost}\".`);\n }\n return { address, urlHost: (options.urlHost ?? canonical).toLowerCase() };\n}\n\n/** The fewest distinct characters a chosen token must have, so `aaaa…` isn't accepted. */\nconst TOKEN_VARIETY = 8;\n\n/** The bearer token: `MOSTRA_MCP_TOKEN`, or one made for this run (160 bits). */\nexport function mcpToken(env: Environment): {\n readonly token: string;\n readonly generated: boolean;\n} {\n const given = env[\"MOSTRA_MCP_TOKEN\"];\n if (given !== undefined && given !== \"\") {\n if (given.length < 26 || /\\s/.test(given) || new Set(given).size < TOKEN_VARIETY) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_CLI_USAGE\", {\n 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\\`.`,\n }),\n );\n }\n return { token: given, generated: false };\n }\n return { token: randomBytes(20).toString(\"base64url\"), generated: true };\n}\n\n/** A request's headers as `[name, value]` pairs in arrival order (Node's `rawHeaders`). */\nfunction pairs(incoming: Pick<IncomingMessage, \"rawHeaders\">): [string, string][] {\n const raw = incoming.rawHeaders;\n const out: [string, string][] = [];\n for (let index = 0; index + 1 < raw.length; index += 2)\n out.push([raw[index] as string, raw[index + 1] as string]);\n return out;\n}\n\n/** Serves Streamable HTTP until the process is stopped; tells `onListening` where. */\nexport async function serveOverHttp(\n options: ServeOptions & {\n readonly port: number;\n readonly bind?: string;\n readonly urlHost?: string;\n readonly onListening: (where: {\n readonly url: string;\n readonly port: number;\n readonly token: string;\n readonly generated: boolean;\n }) => void;\n },\n): Promise<DaemonInstance> {\n const { address, urlHost } = mcpBind({\n ...(options.bind !== undefined ? { bind: options.bind } : {}),\n ...(options.urlHost !== undefined ? { urlHost: options.urlHost } : {}),\n });\n const { token, generated } = mcpToken(options.env);\n const instance = startInstance(options);\n const factory = factoryFor(options, instance);\n let endpoint: ReturnType<typeof createHttpEndpoint> | undefined;\n const server = serve({\n fetch: (request: Request, env: { incoming: Pick<IncomingMessage, \"url\" | \"rawHeaders\"> }) => {\n if (endpoint === undefined) return new Response(null, { status: 503 });\n return endpoint.fetch(request, {\n target: env.incoming.url ?? \"/\",\n headers: pairs(env.incoming),\n });\n },\n port: options.port,\n hostname: address,\n });\n const port = await new Promise<number>((resolve, reject) => {\n server.once(\"error\", (error: NodeJS.ErrnoException) =>\n reject(\n new RpcError(\n createDiagnostic(\"MOSTRA_ENV_BIND_FAILED\", {\n message: `The MCP server couldn't listen on ${address}:${options.port} (${error.code ?? error.message}).`,\n }),\n ),\n ),\n );\n server.once(\"listening\", () => {\n const bound = server.address();\n resolve(typeof bound === \"object\" && bound !== null ? bound.port : options.port);\n });\n });\n // Browsers close idle connections before the server does (D157); harmless for programs.\n if (\"keepAliveTimeout\" in server) {\n (server as { keepAliveTimeout: number; headersTimeout: number }).keepAliveTimeout = 305_000;\n (server as { keepAliveTimeout: number; headersTimeout: number }).headersTimeout = 306_000;\n }\n const origin = `http://${urlHost}:${port}`;\n endpoint = createHttpEndpoint(factory, {\n origin,\n hosts: [`${urlHost}:${port}`],\n token,\n onRefusal: (refused) =>\n options.log(`mostra mcp: refused a request (${refused.status} ${refused.code})`),\n onError: (error) => options.log(`mostra mcp: ${error.message}`),\n });\n options.onListening({ url: `${origin}${MCP_PATH}`, port, token, generated });\n await stopSignal();\n await endpoint.close().catch(() => {});\n await new Promise<void>((resolve) => {\n server.close(() => resolve());\n // Idle connections are kept for minutes; ending the server ends them now.\n (server as { closeAllConnections?: () => void }).closeAllConnections?.();\n });\n instance.close();\n return instance;\n}\n","/**\n * `mostra mcp` (INTERFACES §12, D164): Mostra's MCP server, for any MCP client. Over stdio by\n * default (a client starts it), or Streamable HTTP with `--http`. Its tools are `@mostra/mcp`'s;\n * this command gives them the home's daemon, the workspace and the reference, and counts each\n * MCP client in telemetry unless `--embedded` says a host or harness plugin started it (D148).\n */\nimport { resolve } from \"node:path\";\nimport type { McpClientInfo } from \"@mostra/mcp\";\nimport { defaultWorkspaceRoot } from \"@mostra/mcp\";\nimport { type CommandDef, defineCommand } from \"../command.ts\";\nimport { embeddedHome, readHomeMarks } from \"../home.ts\";\nimport { type DaemonInstance, serveOverHttp, serveOverStdio } from \"../mcp.ts\";\nimport { usage } from \"../parse.ts\";\nimport { mcpSessionFields } from \"../telemetry/harness.ts\";\nimport { cliVersion } from \"../version.ts\";\nimport { flag } from \"./shared.ts\";\n\n/** `mostra mcp`. */\nexport const mcpCommand: CommandDef = defineCommand({\n path: [\"mcp\"],\n summary:\n \"Run Mostra's MCP server, so an MCP client can create, verify and publish artifacts, wait for answers and read results.\",\n flags: [\n {\n name: \"http\",\n kind: \"boolean\",\n summary:\n \"Serve Streamable HTTP at /mcp instead of stdio; every request needs Authorization: Bearer <token>.\",\n },\n {\n name: \"port\",\n kind: \"number\",\n value: \"<port>\",\n summary: \"With --http, the port; default one the system picks.\",\n },\n {\n name: \"bind\",\n kind: \"string\",\n value: \"<address>\",\n summary: \"With --http, listen on this address instead of 127.0.0.1.\",\n },\n {\n name: \"url-host\",\n kind: \"string\",\n value: \"<name>\",\n summary: \"With --http, the host name clients use; a wildcard --bind needs it.\",\n },\n {\n name: \"workspace\",\n kind: \"string\",\n value: \"<dir>\",\n summary:\n \"Where relative artifact directories and new artifacts go. Default: MOSTRA_MCP_WORKSPACE, else ~/mostra-artifacts.\",\n },\n {\n name: \"embedded\",\n kind: \"boolean\",\n summary:\n \"This server runs on someone's behalf (a harness plugin or another host started it), so it sends no telemetry.\",\n },\n ],\n output: { type: \"the MCP protocol on stdin and stdout, or over HTTP\", topic: \"cli\" },\n exits: [],\n example: \"mcp\",\n readsStdin: (flags) => flags[\"http\"] !== true,\n quiet: (flags) => flags[\"embedded\"] === true,\n async run(context) {\n const http = context.flags[\"http\"] === true;\n const port = context.flags[\"port\"];\n const bind = flag(context, \"bind\");\n const urlHost = flag(context, \"url-host\");\n if (!http && (port !== undefined || bind !== undefined || urlHost !== undefined)) {\n throw usage(\"--port, --bind and --url-host go with --http.\");\n }\n if (typeof port === \"number\" && (!Number.isInteger(port) || port < 0 || port > 65_535)) {\n throw usage(\"--port takes a port number from 0 to 65535.\");\n }\n const given = flag(context, \"workspace\") ?? context.env[\"MOSTRA_MCP_WORKSPACE\"];\n const workspace =\n given !== undefined && given !== \"\" ? resolve(context.cwd, given) : defaultWorkspaceRoot();\n const counted = new Set<string>();\n let reached: DaemonInstance | undefined;\n const options = {\n home: context.home,\n env: context.env,\n workspace,\n version: cliVersion(),\n log: context.log,\n onClient(client: McpClientInfo, instance: DaemonInstance) {\n // Each client once per process (D140 item 8), and queued at once, since a harness stops\n // its server within a second, before any end of the command (D164 item 4). Connecting\n // starts nothing: a host-spawned instance always marks its home (D140 item 4), which\n // the mark read now tells, as does a session a call already opened.\n reached = instance;\n const fields = mcpSessionFields(client);\n const key = `${fields.client}@${fields.clientVersion ?? \"\"}`;\n if (counted.has(key)) return;\n counted.add(key);\n context.record({ event: \"mcp.session\", fields });\n context.checkpoint(instance.hostInstance() || embeddedHome(readHomeMarks(context.home)));\n },\n };\n const done = { result: undefined, raw: true as const };\n if (!http) {\n await serveOverStdio(options);\n return { ...done, hostInstance: reached?.hostInstance() === true };\n }\n await serveOverHttp({\n ...options,\n port: typeof port === \"number\" ? port : 0,\n ...(bind !== undefined ? { bind } : {}),\n ...(urlHost !== undefined ? { urlHost } : {}),\n onListening({ url, token, generated }) {\n // The token is a secret: it goes to stderr once, never to stdout, which a supervisor\n // may keep in a log (D164 item 3, Opus review of WP-15, finding 8). A program that needs\n // the token sets MOSTRA_MCP_TOKEN; `listening` gives it the URL.\n if (context.json) context.emit({ kind: \"listening\", url });\n else context.stderr(`Mostra's MCP server is listening at ${url}\\n`);\n context.stderr(\n generated\n ? `Send Authorization: Bearer ${token} with every request (set MOSTRA_MCP_TOKEN to choose the token).\\n`\n : \"Send Authorization: Bearer <MOSTRA_MCP_TOKEN> with every request.\\n\",\n );\n },\n });\n return { ...done, hostInstance: reached?.hostInstance() === true };\n },\n});\n","/**\n * `mostra login` and `mostra logout` (INTERFACES §18.7, D165 items 2, 15): this home signs in to a\n * remote server by the OAuth device authorization grant, so `mostra share --cloud` can host its\n * artifacts there, and signs out again. The instance keeps the refresh token in the home,\n * owner-only; signing out keeps its instance link, so the artifacts it shared stay its own at the\n * next sign-in, unless `--forget`. With `--key-file`, a machine links with a key the server's\n * operator issued instead (`remote/link`, D167). Clients of `remote/login`, `remote/login.wait`,\n * `remote/link` and `remote/logout`.\n */\nimport { readFileSync } from \"node:fs\";\nimport { resolve } from \"node:path\";\nimport {\n artifactPauseMethod,\n remoteLinkMethod,\n remoteLoginMethod,\n remoteLoginWaitMethod,\n remoteLogoutMethod,\n} from \"@mostra/protocol\";\nimport { type CommandDef, defineCommand } from \"../command.ts\";\nimport { EXIT } from \"../exit.ts\";\nimport { usage } from \"../parse.ts\";\nimport { arg, artifactRef, flag } from \"./shared.ts\";\n\n/** How long `mostra login` waits for the person to approve, in all (the code lives 10 minutes). */\nconst LOGIN_WAIT_MS = 10 * 60_000;\n/** Each wait asks the instance for this long, so a slow approval never meets a request timeout. */\nconst LOGIN_STEP_MS = 30_000;\n\n/** `mostra login [<server>] [--default]`. */\nexport const loginCommand: CommandDef = defineCommand({\n path: [\"login\"],\n summary:\n \"Sign this machine's Mostra in to a remote server, so mostra share --cloud can host pages there.\",\n args: [\n {\n name: \"server\",\n summary:\n \"The server's address, such as https://api.example.com. Default: the server signed in to last.\",\n optional: true,\n },\n ],\n flags: [\n {\n name: \"default\",\n kind: \"boolean\",\n summary:\n \"Make this machine the account's default, the one chat apps create pages on. Default: the first machine linked.\",\n },\n {\n name: \"key-file\",\n kind: \"string\",\n summary:\n \"Link with a key the server's operator issued for an account, read from this file, instead of a person's sign-in (for an always-on machine).\",\n },\n ],\n output: { type: \"RemoteLoginWaitResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: \"login https://api.example.com\",\n async run(context) {\n const server = context.args[\"server\"];\n // An operator-issued key, from a file: never on the command line, which every local user sees.\n const keyFile = flag(context, \"key-file\");\n if (keyFile !== undefined) {\n if (typeof server !== \"string\")\n throw usage(\"Name the server the key is for: mostra login <server> --key-file <file>.\");\n let key: string;\n try {\n key = readFileSync(resolve(context.cwd, keyFile), \"utf8\").trim();\n } catch (error) {\n throw usage(\n `--key-file ${keyFile} can't be read (${(error as NodeJS.ErrnoException).code ?? \"error\"}).`,\n );\n }\n const linked = await context.call(remoteLinkMethod, {\n server: server.replace(/\\/+$/, \"\"),\n key,\n ...(context.flags[\"default\"] === true ? { default: true } : {}),\n });\n return {\n result: { status: \"signed-in\", ...linked },\n human: `Linked to ${linked.server} for ${linked.account.name ?? linked.account.id} with the operator's key. This machine is ${linked.instanceId}.\\n`,\n };\n }\n const started = await context.call(remoteLoginMethod, {\n ...(typeof server === \"string\" ? { server: server.replace(/\\/+$/, \"\") } : {}),\n ...(context.flags[\"default\"] === true ? { default: true } : {}),\n });\n const where = started.verificationUriComplete ?? started.verificationUri;\n context.emit(\n { kind: \"code\", ...started },\n `Open ${where} and check that it shows the code ${started.userCode}, then approve.\\nWaiting for you to approve…`,\n );\n const deadline = Date.now() + LOGIN_WAIT_MS;\n for (;;) {\n const waited = await context.call(remoteLoginWaitMethod, {\n loginId: started.loginId,\n timeoutMs: Math.max(0, Math.min(LOGIN_STEP_MS, deadline - Date.now())),\n });\n if (waited.status === \"signed-in\") {\n return {\n result: waited,\n human: `Signed in to ${waited.server} as ${waited.account.name ?? waited.account.id}. This machine is ${waited.instanceId}.\\n`,\n };\n }\n if (Date.now() >= deadline) {\n return {\n result: waited,\n human: \"The code wasn't approved in time. Run mostra login again for a new one.\\n\",\n exit: EXIT.timeout,\n };\n }\n }\n },\n});\n\n/** `mostra logout [<server>] [--forget]`. */\nexport const logoutCommand: CommandDef = defineCommand({\n path: [\"logout\"],\n summary:\n \"Sign this machine's Mostra out of a remote server; its hosted pages keep working, and their answers wait for the next sign-in.\",\n args: [\n {\n name: \"server\",\n summary: \"The server's address. Default: the server signed in to last.\",\n optional: true,\n },\n ],\n flags: [\n {\n name: \"forget\",\n kind: \"boolean\",\n summary:\n \"Also forget this machine's link to the server: the pages it shared there are no longer its own.\",\n },\n ],\n output: { type: \"RemoteLogoutResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: \"logout\",\n async run(context) {\n const server = context.args[\"server\"];\n const result = await context.call(remoteLogoutMethod, {\n ...(typeof server === \"string\" ? { server: server.replace(/\\/+$/, \"\") } : {}),\n ...(context.flags[\"forget\"] === true ? { forget: true } : {}),\n });\n return {\n result,\n human:\n result.servers.length === 0\n ? \"This machine wasn't signed in to a server.\\n\"\n : `Signed out of ${result.servers.join(\", \")}.\\n`,\n };\n },\n});\n\n/** `mostra pause <artifact> [--reason <text>]` (D165 item 14). */\nexport const pauseCommand: CommandDef = defineCommand({\n path: [\"pause\"],\n summary:\n \"Pause an artifact: its pages stay viewable and its links valid, but it takes no answers and runs no actions until resumed.\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n flags: [\n {\n name: \"reason\",\n kind: \"string\",\n summary: \"Why, shown to the page's viewers beside the paused notice.\",\n },\n ],\n output: { type: \"ArtifactPauseResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: 'pause ./survey --reason \"Closed for review until Monday\"',\n async run(context) {\n const reason = flag(context, \"reason\");\n const result = await context.call(artifactPauseMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n paused: true,\n ...(reason !== undefined ? { reason } : {}),\n });\n return {\n result,\n human:\n result.by === \"operator\"\n ? \"Paused. The server's operator paused it too, and only the operator resumes that.\\n\"\n : \"Paused. Pages stay viewable; answers and actions wait until mostra resume.\\n\",\n };\n },\n});\n\n/** `mostra resume <artifact>` (D165 item 14). */\nexport const resumeCommand: CommandDef = defineCommand({\n path: [\"resume\"],\n summary: \"Resume a paused artifact: it takes answers and runs actions again.\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n output: { type: \"ArtifactPauseResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: \"resume ./survey\",\n async run(context) {\n const result = await context.call(artifactPauseMethod, {\n artifact: artifactRef(arg(context, \"artifact\"), context.cwd),\n paused: false,\n });\n return {\n result,\n human: result.paused\n ? \"Still paused: the server's operator paused it, and only the operator resumes that.\\n\"\n : \"Resumed. The artifact takes answers and runs actions again.\\n\",\n ...(result.paused ? { exit: EXIT.failure } : {}),\n };\n },\n});\n","/**\n * `mostra share`: an artifact opened to people beyond this machine through a tunnel the daemon\n * runs (D47, D158): `--tailnet` (Tailscale Serve, inside your tailnet, with each person's\n * identity) or `--public` (a Cloudflare quick tunnel by default, or Tailscale Funnel with `--via\n * funnel`), whose link expires (1 hour by default, 7 days at most); or `--cloud` (D165 item 15),\n * hosted on a remote server this home signed in to, so the link works while this machine sleeps. The share lives in the\n * daemon, so the command returns at once with the link; `share stop` ends it and `share list`\n * shows what is shared. A client of `share/start`, `share/stop` and `share/list`.\n */\nimport {\n type CapabilityScope,\n type Share,\n type ShareVia,\n shareListMethod,\n shareStartMethod,\n shareStopMethod,\n} from \"@mostra/protocol\";\nimport { type CommandDef, defineCommand } from \"../command.ts\";\nimport { EXIT } from \"../exit.ts\";\nimport { usage } from \"../parse.ts\";\nimport { arg, artifactRef, flag } from \"./shared.ts\";\n\nconst SHARE_ID = /^shr_[0-9A-HJKMNP-TV-Z]{26}$/;\n\n/** How each tunnel is named in human output. */\nconst THROUGH: Readonly<Record<ShareVia, string>> = {\n tailnet: \"Tailscale Serve, inside your tailnet\",\n funnel: \"Tailscale Funnel, public\",\n cloudflare: \"a Cloudflare quick tunnel, public\",\n remote: \"a remote server, hosted\",\n};\n\n/**\n * What a tailnet viewer's device needs, found on a real tailnet in WP-13: the tailnet's access\n * policy must let them reach the share's two ports of this device, and their browser's traffic\n * must go through Tailscale (no private or secure DNS of its own, no split tunneling that leaves\n * the browser out).\n */\nfunction tailnetReach(share: { readonly url?: string; readonly artifactOrigin?: string }): string {\n const port = (origin: string | undefined): string | undefined =>\n origin === undefined ? undefined : new URL(origin).port || \"443\";\n const ports = [port(share.url), port(share.artifactOrigin)].filter(\n (value): value is string => value !== undefined,\n );\n 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`;\n}\n\n/** One share as a line of human output. */\nfunction line(share: Share): string {\n const until =\n share.state === \"stopped\"\n ? `stopped${share.stopReason ? ` (${share.stopReason})` : \"\"}`\n : share.expiresAt\n ? `until ${share.expiresAt}`\n : \"no expiry\";\n return `${share.shareId} ${share.via} ${share.hostname} ${until}`;\n}\n\n/** `mostra share <artifact> --tailnet | --public`. */\nexport const shareCommand: CommandDef = defineCommand({\n path: [\"share\"],\n summary:\n \"Open an artifact to people beyond this machine: inside your tailnet, publicly with a link that expires, or hosted on a server.\",\n args: [\n { name: \"artifact\", summary: \"The artifact: its source path or its ID.\" },\n {\n name: \"server\",\n summary: \"With --cloud: the server's address. Default: the server signed in to last.\",\n optional: true,\n },\n ],\n flags: [\n {\n name: \"cloud\",\n kind: \"boolean\",\n summary:\n \"Host it on a remote server you signed in to with mostra login: the link keeps working while this machine sleeps.\",\n },\n {\n name: \"tailnet\",\n kind: \"boolean\",\n summary:\n \"Share inside your tailnet through Tailscale Serve; each viewer is their tailnet identity.\",\n },\n {\n name: \"public\",\n kind: \"boolean\",\n summary: \"Share publicly: anyone with the link can open it until it expires.\",\n },\n {\n name: \"via\",\n kind: \"string\",\n value: \"<tunnel>\",\n choices: [\"cloudflare\", \"funnel\"],\n default: \"cloudflare\",\n summary:\n \"The public tunnel: a Cloudflare quick tunnel (no account), or Tailscale Funnel (shows your device's tailnet name).\",\n },\n {\n name: \"ttl\",\n kind: \"duration\",\n value: \"<d>\",\n summary: \"How long the link works, such as 30m or 24h. Public: 1h by default, 7d at most.\",\n },\n {\n name: \"scope\",\n kind: \"list\",\n value: \"<a,b>\",\n summary: \"The link's scopes: view, draft, submit, review, signal, action:*. Default: all.\",\n },\n {\n name: \"viewer\",\n kind: \"string\",\n value: \"<ref>\",\n summary:\n \"The person the link is for, by your own stable key for them; without it, each link is a viewer of its own.\",\n },\n {\n name: \"viewer-name\",\n kind: \"string\",\n value: \"<name>\",\n summary: \"The display name of --viewer.\",\n },\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retried share return the same share instead of opening another.\",\n },\n ],\n output: { type: \"ShareStartResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: \"share ./sidebar-review --cloud\",\n async run(context) {\n const artifact = artifactRef(arg(context, \"artifact\"), context.cwd);\n const tailnet = context.flags[\"tailnet\"] === true;\n const publicly = context.flags[\"public\"] === true;\n const cloud = context.flags[\"cloud\"] === true;\n if ([tailnet, publicly, cloud].filter(Boolean).length !== 1)\n throw usage(\"Give one of --tailnet, --public or --cloud.\");\n const viaFlag = flag(context, \"via\");\n if (viaFlag !== undefined && !publicly)\n throw usage(\"--via chooses a public tunnel: add --public.\");\n const server = context.args[\"server\"];\n if (server !== undefined && !cloud) throw usage(\"A server names where --cloud hosts it.\");\n const via: ShareVia = cloud\n ? \"remote\"\n : tailnet\n ? \"tailnet\"\n : viaFlag === \"funnel\"\n ? \"funnel\"\n : \"cloudflare\";\n const ttl = flag(context, \"ttl\");\n const scopes = context.flags[\"scope\"] as readonly string[] | undefined;\n const viewerRef = flag(context, \"viewer\");\n const viewerName = flag(context, \"viewer-name\");\n const requestId = flag(context, \"request-id\");\n if (viewerName !== undefined && viewerRef === undefined)\n throw usage(\"--viewer-name needs --viewer.\");\n const share = await context.call(shareStartMethod, {\n artifact,\n via,\n ...(typeof server === \"string\" ? { server: server.replace(/\\/+$/, \"\") } : {}),\n ...(ttl !== undefined ? { ttl: ttl as `${number}${\"s\" | \"m\" | \"h\" | \"d\"}` } : {}),\n ...(scopes !== undefined ? { scopes: scopes as CapabilityScope[] } : {}),\n ...(viewerRef !== undefined\n ? { viewer: { ref: viewerRef, ...(viewerName !== undefined ? { name: viewerName } : {}) } }\n : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n });\n context.record({ event: \"share.done\", fields: { kind: via } });\n const until = share.expiresAt ? `until ${share.expiresAt}` : \"until you stop it\";\n // A hosted page keeps working while this machine sleeps: its answers wait for it (D165).\n return {\n result: share,\n human: `${share.url}\\nShared through ${THROUGH[via]}, ${until}.\\n${via === \"tailnet\" ? tailnetReach(share) : \"\"}Stop it with: mostra share stop ${share.shareId}\\n`,\n };\n },\n});\n\n/** `mostra share stop <artifact|shareId>`. */\nexport const shareStopCommand: CommandDef = defineCommand({\n path: [\"share\", \"stop\"],\n summary:\n \"Stop a share, or every share of an artifact: its link stops working and its tunnel closes.\",\n args: [{ name: \"target\", summary: \"A share's ID (shr_…), or an artifact's source path or ID.\" }],\n flags: [],\n output: { type: \"ShareStopResult\", topic: \"cli\" },\n exits: [EXIT.failure, EXIT.environment],\n example: \"share stop ./sidebar-review\",\n async run(context) {\n const target = arg(context, \"target\");\n const result = await context.call(\n shareStopMethod,\n SHARE_ID.test(target) ? { shareId: target } : { artifact: artifactRef(target, context.cwd) },\n );\n return {\n result,\n human:\n result.stopped.length === 0\n ? \"Nothing was shared.\\n\"\n : result.stopped.map((share) => `Stopped ${share.shareId}\\n`).join(\"\"),\n };\n },\n});\n\n/** `mostra share list [artifact] [--all]`. */\nexport const shareListCommand: CommandDef = defineCommand({\n path: [\"share\", \"list\"],\n summary: \"List the active shares, of every artifact or of one; --all adds the ones that ended.\",\n args: [\n {\n name: \"artifact\",\n summary: \"Only this artifact's shares: its source path or ID.\",\n optional: true,\n },\n ],\n flags: [{ name: \"all\", kind: \"boolean\", summary: \"Also list shares that ended, and why.\" }],\n output: { type: \"ShareListResult\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"share list --all\",\n async run(context) {\n const given = context.args[\"artifact\"];\n const result = await context.call(shareListMethod, {\n ...(typeof given === \"string\" ? { artifact: artifactRef(given, context.cwd) } : {}),\n ...(context.flags[\"all\"] === true ? { all: true } : {}),\n });\n return {\n result,\n human:\n result.shares.length === 0\n ? \"Nothing is shared.\\n\"\n : `${result.shares.map((share) => line(share)).join(\"\\n\")}\\n`,\n };\n },\n});\n","/**\n * `mostra open`: the artifact's link on stdout, and a browser opened on a one-time launch URL that\n * never carries the link's secret (D140 item 15), handed over in a page, never on a command line\n * (`browser.ts`). A client of `view/default`, `view/url`,\n * `view/rotate`, `view/revoke` and `view/launch`.\n */\nimport {\n type CapabilityLink,\n type CapabilityScope,\n viewDefaultMethod,\n viewLaunchMethod,\n viewRevokeMethod,\n viewRotateMethod,\n viewUrlMethod,\n} from \"@mostra/protocol\";\nimport { openInBrowser } from \"../browser.ts\";\nimport { type CommandContext, type CommandDef, defineCommand } from \"../command.ts\";\nimport { EXIT } from \"../exit.ts\";\nimport type { Environment } from \"../home.ts\";\nimport { usage } from \"../parse.ts\";\nimport { arg, artifactRef, flag } from \"./shared.ts\";\n\n/**\n * Whether this session can show a browser: not over SSH without a display. On macOS and Windows a\n * local session always has the user's desktop; an SSH session there has none.\n */\nexport function hasDisplay(env: Environment, platform: string = process.platform): boolean {\n const ssh = env[\"SSH_CONNECTION\"] !== undefined || env[\"SSH_TTY\"] !== undefined;\n if (platform === \"darwin\" || platform === \"win32\") return !ssh;\n return env[\"DISPLAY\"] !== undefined || env[\"WAYLAND_DISPLAY\"] !== undefined;\n}\n\n/** Whether `open` should launch a browser: a terminal without `--json`, or `--browser`. */\nfunction wantsBrowser(context: CommandContext): boolean {\n if (context.flags[\"no-browser\"] === true) return false;\n if (context.flags[\"browser\"] === true) return true;\n return context.tty.stdout && !context.json && hasDisplay(context.env);\n}\n\n/**\n * Why no browser was opened, for stderr (#114): an agent's shell isn't a terminal, so without a\n * word it would tell its person the page is open when it isn't.\n */\nfunction notOpenedReason(context: CommandContext, tried: boolean): string | undefined {\n if (context.flags[\"no-browser\"] === true) return undefined;\n if (tried) return \"No browser opened: none could be started here. Give the person the link.\";\n if (!hasDisplay(context.env)) {\n return \"No browser opened: this session has no display. Give the person the link.\";\n }\n return \"No browser opened: this isn't a terminal. Pass --browser to open it here, or give the person the link.\";\n}\n\n/** The link, opened in a browser when wanted; why not on stderr when it wasn't. */\nasync function show(\n context: CommandContext,\n link: CapabilityLink,\n): Promise<{ result: CapabilityLink & { readonly opened: boolean }; human: string }> {\n let opened = false;\n const tried = wantsBrowser(context);\n if (tried) {\n const launch = await context.call(viewLaunchMethod, { tokenId: link.tokenId });\n // The launch URL reaches the browser through a 0600 page, never its arguments.\n opened = await openInBrowser(launch.url, context.env);\n }\n if (!opened) {\n const reason = notOpenedReason(context, tried);\n if (reason !== undefined) context.log(reason);\n }\n return { result: { ...link, opened }, human: `${link.url}\\n` };\n}\n\n/** `mostra open <artifact>`. */\nexport const openCommand: CommandDef = defineCommand({\n path: [\"open\"],\n summary:\n \"Print an artifact's capability link and open it in a browser; or mint, rotate or revoke a link.\",\n args: [{ name: \"artifact\", summary: \"The artifact: its source path or its ID.\" }],\n flags: [\n {\n name: \"new\",\n kind: \"boolean\",\n summary: \"Mint a separate link instead of the artifact's default one.\",\n },\n {\n name: \"version\",\n kind: \"string\",\n value: \"<n|id>\",\n summary: \"A new link that opens only this version.\",\n },\n {\n name: \"scope\",\n kind: \"list\",\n value: \"<a,b>\",\n summary: \"A new link's scopes: view, draft, submit, review, signal, action:*. Default: all.\",\n },\n {\n name: \"ttl\",\n kind: \"duration\",\n value: \"<d>\",\n summary: \"A new link that expires after this long, such as 24h.\",\n },\n {\n name: \"viewer\",\n kind: \"string\",\n value: \"<ref>\",\n summary: \"A new link that acts for this person, by your own stable key for them.\",\n },\n {\n name: \"viewer-name\",\n kind: \"string\",\n value: \"<name>\",\n summary: \"The display name of --viewer.\",\n },\n {\n name: \"rotate\",\n kind: \"string\",\n value: \"<tokenId>\",\n summary: \"Replace this link with a new one; the old one stops working.\",\n },\n { name: \"revoke\", kind: \"string\", value: \"<tokenId>\", summary: \"Stop this link from working.\" },\n { name: \"browser\", kind: \"boolean\", summary: \"Open a browser even without a terminal.\" },\n { name: \"no-browser\", kind: \"boolean\", summary: \"Only print the link.\" },\n {\n name: \"request-id\",\n kind: \"string\",\n value: \"<id>\",\n summary: \"Make a retried --new return the same link.\",\n },\n ],\n output: { type: \"CapabilityLink\", topic: \"cli\" },\n exits: [EXIT.failure],\n example: \"open ./sidebar-review\",\n async run(context) {\n const artifact = artifactRef(arg(context, \"artifact\"), context.cwd);\n const revoke = flag(context, \"revoke\");\n const rotate = flag(context, \"rotate\");\n if (revoke !== undefined && rotate !== undefined)\n throw usage(\"Give --rotate or --revoke, not both.\");\n if (revoke !== undefined) {\n await context.call(viewRevokeMethod, { tokenId: revoke });\n return { result: { tokenId: revoke, revoked: true }, human: `Revoked ${revoke}\\n` };\n }\n if (rotate !== undefined)\n return show(context, await context.call(viewRotateMethod, { tokenId: rotate }));\n const version = flag(context, \"version\");\n const scopes = context.flags[\"scope\"] as readonly string[] | undefined;\n const ttl = flag(context, \"ttl\");\n const viewerRef = flag(context, \"viewer\");\n const viewerName = flag(context, \"viewer-name\");\n const requestId = flag(context, \"request-id\");\n if (viewerName !== undefined && viewerRef === undefined)\n throw usage(\"--viewer-name needs --viewer.\");\n const fresh =\n context.flags[\"new\"] === true ||\n version !== undefined ||\n scopes !== undefined ||\n ttl !== undefined ||\n viewerRef !== undefined;\n if (!fresh) return show(context, await context.call(viewDefaultMethod, { artifact }));\n const link = await context.call(viewUrlMethod, {\n artifact,\n ...(version !== undefined\n ? { version: /^[0-9]+$/.test(version) ? Number(version) : version }\n : {}),\n ...(scopes !== undefined ? { scopes: scopes as CapabilityScope[] } : {}),\n ...(ttl !== undefined ? { ttl: ttl as `${number}${\"s\" | \"m\" | \"h\" | \"d\"}` } : {}),\n ...(viewerRef !== undefined\n ? { viewer: { ref: viewerRef, ...(viewerName !== undefined ? { name: viewerName } : {}) } }\n : {}),\n ...(requestId !== undefined ? { requestId } : {}),\n });\n return show(context, link);\n },\n});\n","/**\n * Every command of `mostra` (D60, D140 item 13), in the order help lists them. Commands later\n * packages own (`review export`, `plugin`, `term`) join this list with their\n * packages, never as placeholders; `share` joined with WP-13, `mcp` with WP-15, and `export` (its `bundle` class) and `run`\n * with WP-29.\n */\nimport type { CommandDef } from \"../command.ts\";\nimport {\n daemonInstallCommand,\n daemonRestartCommand,\n daemonStartCommand,\n daemonStatusCommand,\n daemonStopCommand,\n daemonUninstallCommand,\n docsCommand,\n doctorCommand,\n gcCommand,\n hostCommand,\n listCommand,\n secretListCommand,\n secretRmCommand,\n secretSetCommand,\n statusCommand,\n telemetryOffCommand,\n telemetryOnCommand,\n telemetryStatusCommand,\n} from \"./admin.ts\";\nimport {\n addCommand,\n exportCommand,\n newCommand,\n publishCommand,\n runCommand,\n verifyCommand,\n} from \"./authoring.ts\";\nimport { devCommand } from \"./dev.ts\";\nimport {\n pushCommand,\n resultsCommand,\n stateGetCommand,\n statePatchCommand,\n stateSetCommand,\n waitCommand,\n} from \"./interaction.ts\";\nimport { mcpCommand } from \"./mcp.ts\";\nimport { loginCommand, logoutCommand, pauseCommand, resumeCommand } from \"./remote.ts\";\nimport { shareCommand, shareListCommand, shareStopCommand } from \"./sharing.ts\";\nimport { openCommand } from \"./viewing.ts\";\n\n/** The commands, in help's order: the authoring loop first. */\nexport const COMMANDS: readonly CommandDef[] = [\n newCommand,\n devCommand,\n verifyCommand,\n publishCommand,\n openCommand,\n shareCommand,\n shareStopCommand,\n shareListCommand,\n loginCommand,\n logoutCommand,\n pauseCommand,\n resumeCommand,\n waitCommand,\n resultsCommand,\n stateGetCommand,\n stateSetCommand,\n statePatchCommand,\n pushCommand,\n addCommand,\n exportCommand,\n runCommand,\n secretSetCommand,\n secretListCommand,\n secretRmCommand,\n listCommand,\n statusCommand,\n daemonStartCommand,\n daemonStopCommand,\n daemonRestartCommand,\n daemonStatusCommand,\n daemonInstallCommand,\n daemonUninstallCommand,\n hostCommand,\n mcpCommand,\n docsCommand,\n doctorCommand,\n gcCommand,\n telemetryStatusCommand,\n telemetryOnCommand,\n telemetryOffCommand,\n];\n","/**\n * Help, generated from the command definitions (D140 items 8 and 16): `--help` for people,\n * `--help --json` for agents (the definition itself), and `docs/reference/cli.md`, which CI\n * checks is current. The wording lives in the definitions; this module only lays it out.\n */\nimport { type CommandDef, commandName, type FlagDef } from \"./command.ts\";\nimport { EXIT } from \"./exit.ts\";\nimport { GLOBAL_FLAGS, topWords } from \"./parse.ts\";\n\nconst EXIT_MEANING: Readonly<Record<number, string>> = {\n [EXIT.ok]: \"success\",\n [EXIT.failure]:\n \"artifact failure (verify failed, publish refused, the artifact's state refused the request)\",\n [EXIT.usage]: \"usage error\",\n [EXIT.environment]:\n \"environment error (no runtime, browser or socket; the home; an unsupported platform)\",\n [EXIT.timeout]: \"timeout (--timeout passed)\",\n [EXIT.stillWaiting]: \"still waiting (the wait timed out; the result says where to resume)\",\n [EXIT.conflict]: \"conflict (already submitted, a compare-and-set mismatch, a reused request ID)\",\n};\n\n/** The usage line: `mostra open <artifact> [flags]`. */\nexport function usageLine(command: CommandDef): string {\n const args = (command.args ?? []).map((arg) => {\n const name = arg.variadic ? `<${arg.name}…>` : `<${arg.name}>`;\n return arg.optional ? `[${name}]` : name;\n });\n return [\n \"mostra\",\n ...command.path,\n ...args,\n ...((command.flags ?? []).length > 0 ? [\"[flags]\"] : []),\n ].join(\" \");\n}\n\nfunction flagLine(flag: FlagDef): string {\n const name = `--${flag.name}${flag.kind === \"boolean\" ? \"\" : ` ${flag.value ?? `<${flag.kind}>`}`}`;\n const choices = flag.choices ? ` (${flag.choices.join(\", \")})` : \"\";\n const fallback = flag.default !== undefined ? ` Default: ${flag.default}.` : \"\";\n return ` ${name.padEnd(28)} ${flag.summary}${choices}${fallback}`;\n}\n\n/** Commands that run until their connection or Ctrl-C ends them: `--timeout` doesn't bound them. */\nexport const UNBOUNDED: ReadonlySet<string> = new Set([\"host\", \"dev\", \"mcp\"]);\n\n/**\n * The global flags a command doesn't define again (`wait --timeout` is the wait's own); a command\n * `--timeout` doesn't bound has no `--timeout`.\n */\nfunction globalFlagsOf(command: CommandDef): FlagDef[] {\n const own = new Set((command.flags ?? []).map((flag) => flag.name));\n if (UNBOUNDED.has(command.path[0] ?? \"\")) own.add(\"timeout\");\n return GLOBAL_FLAGS.filter((flag) => !own.has(flag.name));\n}\n\n/** Every exit code a command can end with, sorted: `--timeout` can end any it bounds with 4. */\nexport function exitCodes(command: CommandDef): number[] {\n const bounded = !UNBOUNDED.has(command.path[0] ?? \"\") && command.path[0] !== \"wait\";\n return [\n ...new Set([\n EXIT.ok,\n ...command.exits,\n EXIT.usage,\n EXIT.environment,\n ...(bounded ? [EXIT.timeout] : []),\n ]),\n ].sort((a, b) => a - b);\n}\n\n/** One command's help, for people. */\nexport function commandHelp(command: CommandDef): string {\n const lines = [command.summary, \"\", \"Usage:\", ` ${usageLine(command)}`];\n if ((command.args ?? []).length > 0) {\n lines.push(\"\", \"Arguments:\");\n for (const arg of command.args ?? [])\n lines.push(` ${`<${arg.name}>`.padEnd(28)} ${arg.summary}`);\n }\n if ((command.flags ?? []).length > 0) {\n lines.push(\"\", \"Flags:\");\n for (const flag of command.flags ?? []) lines.push(flagLine(flag));\n }\n lines.push(\"\", \"Global flags:\");\n for (const flag of globalFlagsOf(command)) lines.push(flagLine(flag));\n lines.push(\"\", `Output: ${command.output.type} (mostra docs ${command.output.topic})`);\n lines.push(\"\", \"Exit codes:\");\n for (const code of exitCodes(command)) lines.push(` ${code} ${EXIT_MEANING[code] ?? \"\"}`);\n lines.push(\"\", \"Example:\", ` mostra ${command.example}`, \"\");\n return lines.join(\"\\n\");\n}\n\n/** A group's help (`mostra daemon --help`): its commands. */\nexport function groupHelp(commands: readonly CommandDef[], group: string): string {\n const members = commands.filter((command) => command.path[0] === group);\n return [\n `mostra ${group}: ${members.length} commands.`,\n \"\",\n ...members.map((command) => ` ${commandName(command).padEnd(22)} ${command.summary}`),\n \"\",\n `Run \"mostra ${group} <command> --help\" for one of them.`,\n \"\",\n ].join(\"\\n\");\n}\n\n/** The top-level help: every command. */\nexport function topHelp(commands: readonly CommandDef[]): string {\n return [\n \"Mostra, the agent artifact runtime: write ordinary React, verify it, publish it, share the link, wait for answers.\",\n \"\",\n \"Usage:\",\n \" mostra <command> [arguments] [flags]\",\n \"\",\n \"Commands:\",\n ...commands.map((command) => ` ${commandName(command).padEnd(22)} ${command.summary}`),\n \"\",\n \"Global flags:\",\n ...GLOBAL_FLAGS.map(flagLine),\n \"\",\n 'Run \"mostra <command> --help\" for a command, and \"mostra docs\" for the reference.',\n \"\",\n ].join(\"\\n\");\n}\n\n/** One command's machine-readable definition (`--help --json`). */\nexport function commandDefinition(command: CommandDef): Record<string, unknown> {\n return {\n command: commandName(command),\n summary: command.summary,\n usage: usageLine(command),\n args: (command.args ?? []).map((arg) => ({\n name: arg.name,\n summary: arg.summary,\n optional: arg.optional === true,\n variadic: arg.variadic === true,\n })),\n flags: [...(command.flags ?? []), ...globalFlagsOf(command)].map((flag) => ({\n name: flag.name,\n type: flag.kind,\n summary: flag.summary,\n ...(flag.choices ? { choices: flag.choices } : {}),\n ...(flag.default !== undefined ? { default: flag.default } : {}),\n global: GLOBAL_FLAGS.includes(flag),\n })),\n output: command.output,\n exitCodes: exitCodes(command).map((code) => ({ code, meaning: EXIT_MEANING[code] ?? \"\" })),\n stdin: typeof command.readsStdin === \"function\" ? \"sometimes\" : command.readsStdin === true,\n streams: command.streams === true,\n example: `mostra ${command.example}`,\n };\n}\n\n/** `docs/reference/cli.md`: every command's help as one page. */\nexport function referenceMarkdown(commands: readonly CommandDef[]): string {\n const sections = commands.map(\n (command) =>\n `## mostra ${commandName(command)}\\n\\n\\`\\`\\`text\\n${commandHelp(command).trimEnd()}\\n\\`\\`\\`\\n`,\n );\n return [\n \"# The mostra CLI\",\n \"\",\n \"<!-- Generated from the command definitions in packages/cli/src/commands/. Don't edit; run `pnpm fix`. -->\",\n \"\",\n 'Every command takes `--json`, which prints one envelope on stdout: `{ \"ok\": true, \"result\", \"instance\", \"warnings\" }` or `{ \"ok\": false, \"error\", \"warnings\" }`. Streaming commands print one envelope per line, the last one carrying `result` or `error`. Logs and progress go to stderr. Without a terminal, or with `--json`, no command asks a question.',\n \"\",\n `Commands: ${topWords(commands)\n .map((word) => `\\`${word}\\``)\n .join(\", \")}.`,\n \"\",\n ...sections,\n ].join(\"\\n\");\n}\n","/**\n * The runner (INTERFACES §9, D140 item 16): reads the command line, runs one command, and owns\n * everything commands share. stdout carries exactly one JSON value in `--json` mode (one per line\n * for a stream), whatever happens, usage errors and crashes included; logs, progress and warnings\n * go to stderr; the exit code comes from one table; telemetry's notice or question comes before\n * the command's work and its events after it.\n */\nimport { spawn } from \"node:child_process\";\nimport { resolve } from \"node:path\";\nimport { createInterface } from \"node:readline\";\nimport {\n createDiagnostic,\n type Diagnostic,\n type MethodDefinition,\n RpcError,\n} from \"@mostra/protocol\";\nimport { connect, type InstanceConnection, type InstanceSummary } from \"./client.ts\";\nimport {\n type CommandContext,\n type CommandDef,\n type CommandOutcome,\n commandName,\n} from \"./command.ts\";\nimport { COMMANDS } from \"./commands/index.ts\";\nimport { EXIT, exitCodeFor } from \"./exit.ts\";\nimport { commandDefinition, commandHelp, groupHelp, topHelp, UNBOUNDED } from \"./help.ts\";\nimport {\n configDir,\n type Environment,\n embeddedHome,\n locateRuntime,\n readHomeMarks,\n resolveHome,\n} from \"./home.ts\";\nimport { globalFlags, parseCommandLine } from \"./parse.ts\";\nimport { checkPlatform } from \"./platform.ts\";\nimport { telemetrySession } from \"./telemetry/index.ts\";\nimport { cliVersion } from \"./version.ts\";\n\n/** What the runner reads and writes; the binary passes the process's, tests their own. */\nexport interface RunnerIo {\n /** The words after mostra. */\n readonly argv: readonly string[];\n /** The environment. */\n readonly env: Environment;\n /** The working directory. */\n readonly cwd: string;\n /** Writes to stdout. */\n readonly stdout: (text: string) => void;\n /** Writes to stderr. */\n readonly stderr: (text: string) => void;\n /** Standard input. */\n readonly stdin: NodeJS.ReadableStream;\n /** Which of the streams are terminals. */\n readonly tty: { readonly stdin: boolean; readonly stdout: boolean; readonly stderr: boolean };\n /** The platform; default process.platform. */\n readonly platform?: string;\n /** The architecture; default process.arch. */\n readonly arch?: string;\n}\n\n/** The diagnostic an exception is, for the envelope: its own, or an internal error. */\nfunction diagnosticOf(error: unknown): Diagnostic {\n if (error instanceof RpcError) return error.diagnostic;\n return createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `mostra failed unexpectedly: ${error instanceof Error ? error.message : String(error)}`,\n });\n}\n\n/** A diagnostic for people, on stderr. */\nfunction describe(diagnostic: Diagnostic): string {\n const hint = diagnostic.hint ? `\\n ${diagnostic.hint}` : \"\";\n const fix =\n diagnostic.fix?.kind === \"command\" && diagnostic.fix.command\n ? `\\n Run: ${diagnostic.fix.command}`\n : \"\";\n return `${diagnostic.severity} ${diagnostic.code}: ${diagnostic.message}${hint}${fix}\\n ${diagnostic.docs}\\n`;\n}\n\n/** Reads the whole of stdin. */\nfunction readAll(stream: NodeJS.ReadableStream): Promise<string> {\n return new Promise((resolve, reject) => {\n const chunks: Buffer[] = [];\n stream.on(\"data\", (chunk: Buffer | string) =>\n chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)),\n );\n stream.on(\"end\", () => resolve(Buffer.concat(chunks).toString(\"utf8\")));\n stream.on(\"error\", reject);\n });\n}\n\n/** Asks one question on stderr, read from stdin: the answer, `undefined` after the timeout, or Ctrl-C. */\nfunction ask(\n io: RunnerIo,\n question: string,\n timeoutMs: number,\n): Promise<string | undefined | \"interrupt\"> {\n return new Promise((resolve) => {\n const rl = createInterface({ input: io.stdin, output: process.stderr, terminal: true });\n let done = false;\n const finish = (answer: string | undefined | \"interrupt\"): void => {\n if (done) return;\n done = true;\n clearTimeout(timer);\n rl.close();\n resolve(answer);\n };\n const timer = setTimeout(() => {\n io.stderr(\"\\n\");\n finish(undefined);\n }, timeoutMs);\n rl.on(\"SIGINT\", () => {\n io.stderr(\"\\n\");\n finish(\"interrupt\");\n });\n rl.on(\"close\", () => finish(\"\"));\n rl.question(question, (answer) => finish(answer));\n });\n}\n\n/** Runs one command line and returns its exit code. */\nexport async function run(io: RunnerIo): Promise<number> {\n const started = Date.now();\n const global = globalFlags(io.argv);\n const json = global.json;\n const warnings: Diagnostic[] = [];\n let summary: InstanceSummary | undefined;\n let connection: InstanceConnection | undefined;\n let streamed = false;\n\n const writeJson = (value: unknown): void => io.stdout(`${JSON.stringify(value)}\\n`);\n const fail = (diagnostic: Diagnostic): number => {\n if (json) {\n writeJson({\n ok: false,\n error: diagnostic,\n ...(summary && !streamed ? { instance: summary } : {}),\n warnings,\n });\n } else io.stderr(describe(diagnostic));\n return exitCodeFor(diagnostic.code);\n };\n\n // Every entry point fails closed on an unsupported platform before touching the home (D35).\n const platform = io.platform ?? process.platform;\n const unsupported = checkPlatform(platform, io.arch ?? process.arch);\n if (unsupported) return fail(unsupported);\n\n let parsed: ReturnType<typeof parseCommandLine>;\n try {\n parsed = parseCommandLine(COMMANDS, io.argv);\n } catch (error) {\n return fail(diagnosticOf(error));\n }\n if (parsed.kind === \"version\") {\n if (json) writeJson({ ok: true, result: { version: cliVersion() }, warnings });\n else io.stdout(`${cliVersion()}\\n`);\n return EXIT.ok;\n }\n if (parsed.kind === \"help\") {\n if (json) {\n const result = parsed.command\n ? commandDefinition(parsed.command)\n : {\n commands: COMMANDS.filter(\n (command) => !parsed.group || command.path[0] === parsed.group,\n ).map(commandDefinition),\n };\n writeJson({ ok: true, result, warnings });\n } else {\n io.stdout(\n parsed.command\n ? commandHelp(parsed.command)\n : parsed.group\n ? groupHelp(COMMANDS, parsed.group)\n : topHelp(COMMANDS),\n );\n }\n return EXIT.ok;\n }\n\n const { command } = parsed;\n if (global.timeoutMs !== undefined && UNBOUNDED.has(command.path[0] ?? \"\")) {\n return fail(\n createDiagnostic(\"MOSTRA_CLI_USAGE\", {\n message: `mostra ${commandName(command)} runs until Ctrl-C or its connection ends, so --timeout doesn't apply to it.`,\n }),\n );\n }\n // `wait --timeout` is the wait's own length, which ends with still_waiting (exit 5), never exit 4.\n const timeoutMs = command.path[0] === \"wait\" ? undefined : global.timeoutMs;\n const cwd = global.cwd !== undefined ? resolve(io.cwd, global.cwd) : io.cwd;\n const home = resolveHome({ home: global.home, env: io.env, cwd, platform });\n const config = configDir(io.env, cwd);\n const marks = readHomeMarks(home);\n const readsStdin =\n typeof command.readsStdin === \"function\"\n ? command.readsStdin(parsed.flags)\n : command.readsStdin === true;\n const telemetry = telemetrySession({\n env: io.env,\n configDir: config,\n command: commandName(command),\n json,\n tty: io.tty,\n readsStdin,\n quiet:\n typeof command.quiet === \"function\" ? command.quiet(parsed.flags) : command.quiet === true,\n hostHome: embeddedHome(marks),\n stderr: io.stderr,\n ask: (question, timeoutMs) => ask(io, question, timeoutMs),\n });\n\n let connectionClosed = false;\n // Whether this command is starting the home's daemon: a --timeout that runs out then says so.\n let startingDaemon = false;\n const getConnection = async (autostart = true): Promise<InstanceConnection | undefined> => {\n // A session the instance ended (`daemon stop` before `daemon restart`) is opened again.\n if (connection && !connectionClosed) return connection;\n connectionClosed = false;\n const opened = await connect({\n home,\n env: io.env,\n autostart,\n onStarting: (starting) => {\n startingDaemon = starting;\n },\n });\n if (!opened) return undefined;\n connection = opened;\n void opened.closed.then(() => {\n if (connection === opened) connectionClosed = true;\n });\n summary = opened.summary;\n for (const warning of opened.warnings) {\n warnings.push(warning);\n io.stderr(describe(warning));\n }\n return opened;\n };\n\n const context: CommandContext = {\n args: parsed.args,\n flags: parsed.flags,\n cwd,\n json,\n timeoutMs,\n env: io.env,\n tty: io.tty,\n home,\n configDir: config,\n stdout: io.stdout,\n stderr: io.stderr,\n async call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R> {\n const session = await getConnection();\n if (!session)\n throw new RpcError(\n createDiagnostic(\"MOSTRA_HOST_CONNECTION_CLOSED\", {\n message: \"No instance runs for this home.\",\n }),\n );\n const remaining =\n timeoutMs === undefined ? undefined : Math.max(1, timeoutMs - (Date.now() - started));\n return session.call(method, params, remaining);\n },\n connection: getConnection,\n readStdin: () => readAll(io.stdin),\n log: (line) => io.stderr(`${line}\\n`),\n emit(event, human) {\n if (json) {\n writeJson({ ok: true, event, ...(summary && !streamed ? { instance: summary } : {}) });\n streamed = true;\n } else if (human !== undefined) io.stdout(human);\n },\n warn(diagnostic) {\n warnings.push(diagnostic);\n io.stderr(describe(diagnostic));\n },\n record: (event) => telemetry.record(event),\n checkpoint(hostInstance) {\n try {\n telemetry.checkpoint({ hostInstance });\n } catch {\n // Telemetry never changes a command's outcome.\n }\n },\n runtime: (args, stdio = \"pipe\") => runRuntime(io, args, stdio),\n };\n\n let exit: number;\n let error: string | undefined;\n let ownHostInstance = false;\n try {\n // Telemetry never stops a command: a failure in it is a run without telemetry.\n if (!(await telemetry.begin().catch(() => true))) return 130;\n const outcome: CommandOutcome = await withTimeout(\n command,\n context,\n timeoutMs,\n () => startingDaemon,\n );\n exit = outcome.exit ?? EXIT.ok;\n ownHostInstance = outcome.hostInstance === true;\n // A command that wrote its own stdout (`host`, `mcp`) gets no envelope and no text.\n if (outcome.raw !== true) {\n if (json) {\n writeJson({\n ok: true,\n result: outcome.result ?? null,\n ...(summary && !streamed && command.local !== true ? { instance: summary } : {}),\n warnings,\n });\n } else io.stdout(outcome.human ?? `${JSON.stringify(outcome.result, null, 2)}\\n`);\n }\n } catch (caught) {\n const diagnostic = diagnosticOf(caught);\n error = diagnostic.code;\n exit = fail(diagnostic);\n } finally {\n connection?.close();\n }\n try {\n telemetry.end({\n exit,\n durationMs: Date.now() - started,\n hostInstance: summary?.mode === \"host\" || ownHostInstance,\n ...(error !== undefined ? { error } : {}),\n });\n } catch {\n // Telemetry never changes a command's outcome.\n }\n return exit;\n}\n\n/**\n * Runs a command, bounded by `--timeout` (exit 4 with `MOSTRA_HOST_TIMEOUT`). `host` and `dev` run\n * until their connection or Ctrl-C ends them, so `--timeout` bounds neither.\n */\nasync function withTimeout(\n command: CommandDef,\n context: CommandContext,\n timeoutMs: number | undefined,\n startingDaemon: () => boolean,\n): Promise<CommandOutcome> {\n if (timeoutMs === undefined || UNBOUNDED.has(command.path[0] ?? \"\")) return command.run(context);\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n command.run(context),\n new Promise<never>((_, reject) => {\n timer = setTimeout(\n () =>\n reject(\n new RpcError(\n createDiagnostic(\"MOSTRA_HOST_TIMEOUT\", {\n // One timer owns the deadline and names what was underway (Opus review\n // finding 7): starting the daemon, or the command itself.\n message: startingDaemon()\n ? `The home's daemon didn't start within ${timeoutMs} ms (--timeout).`\n : `mostra ${commandName(command)} didn't finish within --timeout (${timeoutMs} ms); what it asked for may still take effect.`,\n }),\n ),\n ),\n timeoutMs,\n );\n }),\n ]);\n } finally {\n clearTimeout(timer);\n }\n}\n\n/** Runs `mostra-runtime …` and collects its stdout. */\nasync function runRuntime(\n io: RunnerIo,\n args: readonly string[],\n stdio: \"pipe\" | \"inherit\",\n): Promise<{ code: number; stdout: string }> {\n const runtime = await locateRuntime(io.env);\n return new Promise((resolve) => {\n const child = spawn(runtime.node, [runtime.entry, ...args], {\n stdio: stdio === \"inherit\" ? \"inherit\" : [\"ignore\", \"pipe\", \"pipe\"],\n env: io.env as NodeJS.ProcessEnv,\n });\n let stdout = \"\";\n child.stdout?.setEncoding(\"utf8\");\n child.stdout?.on(\"data\", (chunk: string) => {\n stdout += chunk;\n });\n child.stderr?.setEncoding(\"utf8\");\n child.stderr?.on(\"data\", (chunk: string) => io.stderr(chunk));\n child.on(\"error\", () => resolve({ code: EXIT.environment, stdout }));\n // `close`, not `exit`: the line may still be in the pipe when the process has exited.\n child.on(\"close\", (code) => resolve({ code: code ?? EXIT.environment, stdout }));\n });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAaA,SAAgB,eAAuB;CACrC,MAAM,UAAU,KAAK,YAAY,GAAG,QAAQ,WAAW;CACvD,OAAO,CAAC,WAAW,KAAK,WAAW,OAAO,IACtC,UACA,KAAK,YAAY,GAAG,MAAM,MAAM,QAAQ,WAAW;AACzD;;AAGA,SAAgB,WAAmB;CACjC,MAAM,UAAU,KAAK,YAAY,GAAG,QAAQ,OAAO;CACnD,OA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qC;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,cAAiC;CAC5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;;;;;;;AClsBA,MAAM,YAAY,IAAI,IAAI,eAAe;AACzC,MAAM,QAAQ,IAAI,IAAI,WAAW;;AAYjC,SAAS,gBAAoC;CAC3C,IAAI;EACF,MAAM,SAAS,aAAa,gBAAgB;EAC5C,MAAM,KAAK,OAAO,YAAY,WAAW;EACzC,OAAO,OAAO,KAAK,KAAA,IAAY,OAAO,MAAM,KAAK,CAAk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