@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.
Files changed (35) hide show
  1. package/dist/bin.js +2 -2
  2. package/dist/{bootstrap-_iCl_HaO.js → bootstrap-3_Tdfdg7.js} +3 -2
  3. package/dist/bootstrap-3_Tdfdg7.js.map +1 -0
  4. package/dist/bootstrap-C9a2gSWf.js +1 -0
  5. package/dist/{flush-D648gCYs.js → flush-TPaIdwjy.js} +2 -1
  6. package/dist/flush-TPaIdwjy.js.map +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +2 -2
  9. package/dist/reference/cli.md +112 -2
  10. package/dist/reference/diagnostics.json +29 -2
  11. package/dist/reference/errors/MOSTRA_REMOTE_QUEUE_FULL.md +2 -2
  12. package/dist/reference/errors/MOSTRA_TEAM_PRESENCE_RATE_LIMITED.md +23 -0
  13. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_POLICY.md +23 -0
  14. package/dist/reference/errors/MOSTRA_TEAM_ROSTER_TOO_LARGE.md +23 -0
  15. package/dist/reference/self-hosting.md +1 -1
  16. package/dist/{run-BxYL-DaX.js → run-CtR0PFMj.js} +248 -19
  17. package/dist/run-CtR0PFMj.js.map +1 -0
  18. package/dist/run-NWeQcyh9.js +1 -0
  19. package/dist/skill/SKILL.md +5 -3
  20. package/dist/skill/references/answers.md +3 -1
  21. package/dist/skill/references/mcp.md +2 -2
  22. package/dist/skill/references/teams.md +78 -0
  23. package/dist/telemetry/flush-main.js +1 -1
  24. package/package.json +5 -5
  25. package/src/commands/index.ts +4 -0
  26. package/src/commands/interaction.ts +43 -2
  27. package/src/commands/sharing.ts +19 -1
  28. package/src/commands/team.ts +191 -0
  29. package/src/detached.ts +1 -0
  30. package/src/exit.ts +2 -0
  31. package/dist/bootstrap-BStzS_41.js +0 -1
  32. package/dist/bootstrap-_iCl_HaO.js.map +0 -1
  33. package/dist/flush-D648gCYs.js.map +0 -1
  34. package/dist/run-Bpg_ZRY8.js +0 -1
  35. package/dist/run-BxYL-DaX.js.map +0 -1
package/dist/bin.js CHANGED
@@ -42,7 +42,7 @@ async function refuseOldNode() {
42
42
  }
43
43
  const code = nodeTooOld(process.versions.node) ? await refuseOldNode() : await start();
44
44
  async function start() {
45
- const { bootstrap } = await import("./bootstrap-BStzS_41.js");
45
+ const { bootstrap } = await import("./bootstrap-C9a2gSWf.js");
46
46
  return await bootstrap({
47
47
  argv: process.argv.slice(2),
48
48
  env: process.env,
@@ -54,7 +54,7 @@ async function start() {
54
54
  },
55
55
  stderrTty: process.stderr.isTTY === true,
56
56
  terminal: process.stdin.isTTY === true || process.stdout.isTTY === true || process.stderr.isTTY === true
57
- }) ?? await (await import("./run-Bpg_ZRY8.js")).run({
57
+ }) ?? await (await import("./run-NWeQcyh9.js")).run({
58
58
  argv: process.argv.slice(2),
59
59
  env: process.env,
60
60
  cwd: process.cwd(),
@@ -63,7 +63,8 @@ const BY_AREA = {
63
63
  PLATFORM: EXIT.environment,
64
64
  ARTIFACT: EXIT.failure,
65
65
  CLI: EXIT.usage,
66
- REMOTE: EXIT.environment
66
+ REMOTE: EXIT.environment,
67
+ TEAM: EXIT.failure
67
68
  };
68
69
  /** Codes whose exit code isn't their area's. */
69
70
  const BY_CODE = {
@@ -420,4 +421,4 @@ async function runInBundle(io) {
420
421
  //#endregion
421
422
  export { GLOBAL_FLAGS as a, parseCommandLine as c, EXIT as d, exitCodeFor as f, servesBeforeBundle as i, topWords as l, defineCommand as m, needsBootstrap as n, durationMs as o, commandName as p, progressReporter as r, globalFlags as s, bootstrap as t, usage as u };
422
423
 
423
- //# sourceMappingURL=bootstrap-_iCl_HaO.js.map
424
+ //# sourceMappingURL=bootstrap-3_Tdfdg7.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bootstrap-3_Tdfdg7.js","names":[],"sources":["../src/command.ts","../src/exit.ts","../src/parse.ts","../src/bootstrap.ts"],"sourcesContent":["/**\n * What a command is (D140 items 13, 16): a definition the parser, the help, the reference page,\n * `--help --json`, telemetry's command names and the contract tests all read. Commands never\n * print or exit on their own; they return a result (or throw a diagnostic) and the runner decides\n * the envelope, the human text and the exit code.\n */\nimport type { Diagnostic, MethodDefinition } from \"@mostra/protocol\";\nimport type { InstanceConnection } from \"./client.ts\";\n\n/** A flag's value kind. Every flag is `--long`; booleans take no value. */\nexport type FlagKind = \"boolean\" | \"string\" | \"number\" | \"duration\" | \"list\";\n\n/** One flag of a command. */\nexport interface FlagDef {\n /** The flag's name, without the dashes. */\n readonly name: string;\n /** What it takes. */\n readonly kind: FlagKind;\n /** One line for help: what it does. */\n readonly summary: string;\n /** The placeholder in usage and help: `<path>`, `<d>` … */\n readonly value?: string;\n /** The allowed values, for a closed set. */\n readonly choices?: readonly string[];\n /** The default, as help shows it. */\n readonly default?: string;\n}\n\n/** One positional argument. */\nexport interface ArgDef {\n /** The argument's name, as help shows it. */\n readonly name: string;\n /** One line for help: what it is. */\n readonly summary: string;\n /** Whether it may be left out. */\n readonly optional?: boolean;\n /** Whether it takes every remaining word (`<package…>`). */\n readonly variadic?: boolean;\n}\n\n/** What the runner gives a command. */\nexport interface CommandContext {\n /** The positional arguments, after the command path, by name. */\n readonly args: Readonly<Record<string, string | readonly string[] | undefined>>;\n /** The command's flags, parsed by kind (durations in milliseconds, lists as arrays). */\n readonly flags: Readonly<\n Record<string, string | number | boolean | readonly string[] | undefined>\n >;\n /** The working directory relative paths resolve from (`--cwd`, else the process's). */\n readonly cwd: string;\n /** Whether `--json` was given. */\n readonly json: boolean;\n /** The request timeout from `--timeout`, in milliseconds. */\n readonly timeoutMs: number | undefined;\n /** Calls a host protocol method on the home's instance, starting its daemon when needed. */\n call<P, R>(method: MethodDefinition<P, R>, params: P): Promise<R>;\n /** Reads the whole of stdin, for commands that take a value there. */\n readStdin(): Promise<string>;\n /** Writes one line of progress or a log line to stderr (never stdout). */\n log(line: string): void;\n /** Emits one event of a streaming command (an NDJSON line in `--json` mode). */\n emit(event: unknown, human?: string): void;\n /** Adds a warning to the envelope (and stderr). */\n warn(diagnostic: Diagnostic): void;\n /** The environment the CLI runs in. */\n readonly env: Readonly<Record<string, string | undefined>>;\n /** Whether stdout and stdin are terminals. */\n readonly tty: { readonly stdin: boolean; readonly stdout: boolean; readonly stderr: boolean };\n /** The resolved home and the CLI's own facts, for commands that report them. */\n readonly home: string;\n /** Records a telemetry event of this command (D140 item 8), when telemetry allows it. */\n record(event: TelemetryEventInput): void;\n /**\n * Queues the events recorded so far, for a command that runs until it is stopped (`mcp`);\n * `hostInstance` says whether the instance it reached was host-spawned (then nothing is sent).\n */\n checkpoint(hostInstance: boolean): void;\n /**\n * The session with the home's instance, starting its daemon unless `autostart` is false; then\n * `undefined` when none runs. `call` uses the same session.\n */\n connection(autostart?: boolean): Promise<InstanceConnection | undefined>;\n /** Runs the runtime binary (`mostra-runtime …`) and returns its exit code and stdout. */\n runtime(\n args: readonly string[],\n stdio?: \"pipe\" | \"inherit\",\n ): Promise<{ code: number; stdout: string }>;\n /** The CLI's config directory (D140 item 5). */\n readonly configDir: string;\n /** Writes to stderr. */\n readonly stderr: (text: string) => void;\n /** Writes to stdout as the command runs (`host`, `dev`'s stream without `--json`). */\n readonly stdout: (text: string) => void;\n}\n\n/** A command-specific telemetry event: its name and its own fields. */\nexport interface TelemetryEventInput {\n /** The event's name. */\n readonly event: \"verify.result\" | \"publish.done\" | \"share.done\" | \"mcp.session\";\n /** Its own fields; the schema keeps only the published ones. */\n readonly fields: Readonly<Record<string, unknown>>;\n}\n\n/** What a command's run returns. */\nexport interface CommandOutcome {\n /** The `result` of the envelope. */\n readonly result: unknown;\n /** The text for people (stdout); default: the result as indented JSON. */\n readonly human?: string;\n /** The exit code when it isn't 0: a failing verdict (1), `still_waiting` (5), conflicts (6). */\n readonly exit?: number;\n /** The command wrote its own stdout (`host`): the runner prints no envelope and no text. */\n readonly raw?: boolean;\n /** The instance the command reached on a session of its own was host-spawned (`mcp`). */\n readonly hostInstance?: boolean;\n}\n\n/** One command. */\nexport interface CommandDef {\n /** Its words after `mostra`: `[\"daemon\", \"install\"]`. */\n readonly path: readonly string[];\n /** One line: what it does. */\n readonly summary: string;\n /** Its positional arguments, in order. */\n readonly args?: readonly ArgDef[];\n /** Its own flags, besides the global ones. */\n readonly flags?: readonly FlagDef[];\n /** The result type `--json` puts in `result`, and its `mostra docs` topic. */\n readonly output: { readonly type: string; readonly topic: string };\n /** The exit codes it can end with, besides 2 and 3, which every command can. */\n readonly exits: readonly number[];\n /** One example invocation, without `mostra`. */\n readonly example: string;\n /** It reads stdin, so telemetry's question is never asked before it (D140 item 11). */\n readonly readsStdin?: boolean | ((flags: CommandContext[\"flags\"]) => boolean);\n /** It never reaches an instance (`docs`, `telemetry`): no `instance` in its envelope. */\n readonly local?: boolean;\n /** It writes a stream of events before its result (NDJSON in `--json` mode). */\n readonly streams?: boolean;\n /**\n * Telemetry and its question leave it alone (`telemetry`, `docs`, D140 item 11), or, as a\n * function of its flags, when it runs on someone's behalf (`mcp --embedded`, D148).\n */\n readonly quiet?: boolean | ((flags: CommandContext[\"flags\"]) => boolean);\n /** Does the command's work. */\n run(context: CommandContext): Promise<CommandOutcome>;\n}\n\n/** Defines a command; the identity function, for types. */\nexport function defineCommand(command: CommandDef): CommandDef {\n return command;\n}\n\n/** The command path as one string: `daemon install`. */\nexport function commandName(command: Pick<CommandDef, \"path\">): string {\n return command.path.join(\" \");\n}\n","/**\n * The exit codes (INTERFACES §9, D140 item 16): one table keyed by diagnostic code, so every\n * command ends the same way for the same failure. Each area has a code, and a few codes differ\n * from their area; the table is total over the catalog by construction, and a test checks every\n * catalog code against it.\n */\nimport type { DiagnosticArea } from \"@mostra/protocol\";\n\n/** The exit codes of INTERFACES §9. */\nexport const EXIT = {\n /** Success, or `verify` passed. */\n ok: 0,\n /** Artifact failure: verify failed, publish refused, a request the artifact's state refused. */\n failure: 1,\n /** Usage error. */\n usage: 2,\n /** Environment error: no runtime, browser or socket; the home; an unsupported platform. */\n environment: 3,\n /** Timeout: `--timeout` passed before the instance answered. */\n timeout: 4,\n /** `wait` ended `still_waiting`: not an error, the status is in the result. */\n stillWaiting: 5,\n /** Conflict: `once` already submitted, a compare-and-set mismatch, a reused request ID. */\n conflict: 6,\n} as const;\n\n/** One of {@link EXIT}'s codes. */\nexport type ExitCode = (typeof EXIT)[keyof typeof EXIT];\n\n/** Each area's exit code. Every area is here: a new one fails the type check until it is. */\nconst BY_AREA: Readonly<Record<DiagnosticArea, ExitCode>> = {\n MANIFEST: EXIT.failure,\n BUILD: EXIT.failure,\n TYPE: EXIT.failure,\n LINT: EXIT.failure,\n DEP: EXIT.failure,\n KIT: EXIT.failure,\n FIELD: EXIT.failure,\n ACTION: EXIT.failure,\n LIVE: EXIT.failure,\n RUNTIME: EXIT.failure,\n CONSOLE: EXIT.failure,\n NETWORK: EXIT.failure,\n A11Y: EXIT.failure,\n VISUAL: EXIT.failure,\n SMOKE: EXIT.failure,\n REGRESSION: EXIT.failure,\n TERM: EXIT.failure,\n PUBLISH: EXIT.failure,\n SUBMIT: EXIT.failure,\n HOST: EXIT.environment,\n HOME: EXIT.environment,\n HYGIENE: EXIT.failure,\n SECRET: EXIT.failure,\n SHARE: EXIT.environment,\n VERIFY: EXIT.failure,\n TARGET: EXIT.failure,\n ENV: EXIT.environment,\n PLATFORM: EXIT.environment,\n ARTIFACT: EXIT.failure,\n CLI: EXIT.usage,\n // A remote server or the link to one: the environment, like a share's tunnel (D165).\n REMOTE: EXIT.environment,\n // A roster or a team wait the artifact can't take (D168): the artifact's, like a refused submit.\n TEAM: EXIT.failure,\n};\n\n/** Codes whose exit code isn't their area's. */\nconst BY_CODE: Readonly<Record<string, ExitCode>> = {\n MOSTRA_HOST_TIMEOUT: EXIT.timeout,\n // The CLI can't record a choice: its environment, not its command line.\n MOSTRA_CLI_CONFIG_UNWRITABLE: EXIT.environment,\n MOSTRA_HOST_INVALID_PARAMS: EXIT.usage,\n MOSTRA_HOST_REQUEST_ID_REUSED: EXIT.conflict,\n MOSTRA_HOST_CURSOR_COMPACTED: EXIT.failure,\n MOSTRA_HOST_SUBSCRIPTION_UNKNOWN: EXIT.usage,\n MOSTRA_SUBMIT_ALREADY: EXIT.conflict,\n MOSTRA_SUBMIT_REVISION_MOVED: EXIT.conflict,\n MOSTRA_FIELD_CONFLICT: EXIT.conflict,\n MOSTRA_FIELD_MUTATION_ID_REUSED: EXIT.conflict,\n MOSTRA_PUBLISH_ID_CONFLICT: EXIT.failure,\n MOSTRA_HOME_INTEGRITY: EXIT.failure,\n MOSTRA_HOME_NOT_ALWAYS_ON: EXIT.ok,\n MOSTRA_VERIFY_CRASHED: EXIT.environment,\n};\n\n/** The exit code a diagnostic ends a command with. An unknown area is an environment error. */\nexport function exitCodeFor(code: string): ExitCode {\n const exact = BY_CODE[code];\n if (exact !== undefined) return exact;\n const area = /^MOSTRA_([A-Z0-9]+)_/.exec(code)?.[1];\n return (area !== undefined ? BY_AREA[area as DiagnosticArea] : undefined) ?? EXIT.environment;\n}\n","/**\n * The command line, read against the command definitions (D140 item 13): the global flags, the\n * command path, its arguments and flags. Every failure is `MOSTRA_CLI_USAGE` or\n * `MOSTRA_CLI_UNKNOWN_COMMAND`, so `--json` mode reports it like any other error.\n */\nimport { parseArgs } from \"node:util\";\nimport { createDiagnostic, RpcError } from \"@mostra/protocol\";\nimport { type CommandDef, commandName, type FlagDef } from \"./command.ts\";\n\n/** The flags every command takes (INTERFACES §9). */\nexport const GLOBAL_FLAGS: readonly FlagDef[] = [\n {\n name: \"json\",\n kind: \"boolean\",\n summary: \"Print one JSON envelope on stdout (NDJSON for streams).\",\n },\n {\n name: \"home\",\n kind: \"string\",\n value: \"<dir>\",\n summary: \"Use this Mostra home instead of MOSTRA_HOME or the default.\",\n },\n {\n name: \"cwd\",\n kind: \"string\",\n value: \"<dir>\",\n summary: \"Resolve relative paths from this directory.\",\n },\n {\n name: \"timeout\",\n kind: \"duration\",\n value: \"<d>\",\n summary: \"Give up on the instance after this long (exit 4), such as 30s or 5m.\",\n },\n {\n name: \"help\",\n kind: \"boolean\",\n summary: \"Show this command's help; with --json, its definition.\",\n },\n];\n\n/** What the command line asks for. */\nexport type Parsed =\n | { readonly kind: \"version\" }\n | { readonly kind: \"help\"; readonly command?: CommandDef; readonly group?: string }\n | {\n readonly kind: \"run\";\n readonly command: CommandDef;\n readonly args: Record<string, string | readonly string[] | undefined>;\n readonly flags: Record<string, string | number | boolean | readonly string[] | undefined>;\n };\n\n/** The global flags' values, read before anything else so a usage error still honors them. */\nexport interface GlobalFlags {\n readonly json: boolean;\n readonly home?: string;\n readonly cwd?: string;\n readonly timeoutMs?: number;\n}\n\n/** A usage error. */\nexport function usage(message: string): RpcError {\n return new RpcError(createDiagnostic(\"MOSTRA_CLI_USAGE\", { message }));\n}\n\nconst DURATION = /^([1-9][0-9]*)(ms|s|m|h|d)$/;\nconst UNIT_MS: Readonly<Record<string, number>> = {\n ms: 1,\n s: 1000,\n m: 60_000,\n h: 3_600_000,\n d: 86_400_000,\n};\n\n/** A duration flag's milliseconds: `30s`, `5m`, `2h`, `7d`, `500ms`. */\nexport function durationMs(value: string): number {\n const match = DURATION.exec(value);\n if (!match)\n throw usage(`\"${value}\" isn't a duration; use a number with ms, s, m, h or d, such as 30s.`);\n return Number(match[1]) * (UNIT_MS[match[2] as string] as number);\n}\n\n/**\n * Reads the global flags wherever they stand, before the command is known: `--json` anywhere\n * before `--` makes even a usage error a JSON envelope (D140 item 16).\n */\nexport function globalFlags(argv: readonly string[]): GlobalFlags {\n const end = argv.indexOf(\"--\");\n const words = end === -1 ? argv : argv.slice(0, end);\n const value = (name: string): string | undefined => {\n for (let index = 0; index < words.length; index += 1) {\n const word = words[index] as string;\n if (word === `--${name}`) return words[index + 1];\n if (word.startsWith(`--${name}=`)) return word.slice(name.length + 3);\n }\n return undefined;\n };\n const timeout = value(\"timeout\");\n let timeoutMs: number | undefined;\n try {\n timeoutMs = timeout === undefined ? undefined : durationMs(timeout);\n } catch {\n timeoutMs = undefined;\n }\n const home = value(\"home\");\n const cwd = value(\"cwd\");\n return {\n json: words.includes(\"--json\"),\n ...(home !== undefined ? { home } : {}),\n ...(cwd !== undefined ? { cwd } : {}),\n ...(timeoutMs !== undefined ? { timeoutMs } : {}),\n };\n}\n\n/** The command that names `words`' longest prefix. */\nfunction findCommand(\n commands: readonly CommandDef[],\n words: readonly string[],\n): { command: CommandDef; used: number } | undefined {\n let best: { command: CommandDef; used: number } | undefined;\n for (const command of commands) {\n const { path } = command;\n if (path.length <= words.length && path.every((word, index) => words[index] === word)) {\n if (!best || path.length > best.used) best = { command, used: path.length };\n }\n }\n return best;\n}\n\n/** The first words of every command: the groups and the single-word commands. */\nexport function topWords(commands: readonly CommandDef[]): string[] {\n return [...new Set(commands.map((command) => command.path[0] as string))].sort();\n}\n\n/**\n * The command path's candidates: the leading words that aren't flags, with the global flags (and\n * their values) that may stand before them skipped, and where each stands in `argv`.\n */\nfunction leadingWords(argv: readonly string[]): { words: string[]; pathAt: number[] } {\n const words: string[] = [];\n const pathAt: number[] = [];\n for (let index = 0; index < argv.length; index += 1) {\n const word = argv[index] as string;\n if (word === \"--json\" || word === \"--help\" || word === \"-h\") continue;\n if (word === \"--home\" || word === \"--cwd\" || word === \"--timeout\") {\n index += 1;\n continue;\n }\n if (/^--(home|cwd|timeout)=/.test(word)) continue;\n if (word.startsWith(\"-\")) break;\n words.push(word);\n pathAt.push(index);\n }\n return { words, pathAt };\n}\n\n/** The words a command line starts its command with (`[\"mcp\"]`, `[\"share\", \"stop\", …]`). */\nexport function commandWords(argv: readonly string[]): string[] {\n return leadingWords(argv).words;\n}\n\n/** Parses the command line against the definitions. Throws a usage diagnostic. */\nexport function parseCommandLine(commands: readonly CommandDef[], argv: readonly string[]): Parsed {\n const bare = argv.filter((word) => word !== \"--json\");\n if (bare.length === 1 && (bare[0] === \"--version\" || bare[0] === \"-v\"))\n return { kind: \"version\" };\n // The command path is the leading words that aren't flags; global flags may stand before it.\n const { words, pathAt } = leadingWords(argv);\n const helpAsked = argv.includes(\"--help\") || argv.includes(\"-h\");\n if (words.length === 0) {\n if (helpAsked || argv.every((word) => word === \"--json\")) return { kind: \"help\" };\n throw usage(`Name a command first; ${argv[0]} isn't one.`);\n }\n const found = findCommand(commands, words);\n if (!found) {\n const group = commands.filter((command) => command.path[0] === words[0]);\n if (group.length > 0) {\n if (helpAsked) return { kind: \"help\", group: words[0] as string };\n throw usage(\n `\"mostra ${words[0]}\" needs one of: ${group.map((command) => command.path.slice(1).join(\" \")).join(\", \")}.`,\n );\n }\n throw new RpcError(\n createDiagnostic(\"MOSTRA_CLI_UNKNOWN_COMMAND\", {\n message: `\"${words[0]}\" isn't a mostra command. The commands are: ${topWords(commands).join(\", \")}.`,\n }),\n );\n }\n const { command } = found;\n if (helpAsked) return { kind: \"help\", command };\n const used = new Set(pathAt.slice(0, found.used));\n const rest = argv.filter((_, index) => !used.has(index));\n const flagDefs = [...GLOBAL_FLAGS, ...(command.flags ?? [])];\n let parsed: ReturnType<typeof parseArgs>;\n try {\n parsed = parseArgs({\n args: [...rest],\n allowPositionals: true,\n strict: true,\n options: Object.fromEntries(\n flagDefs.map((flag) => [\n flag.name,\n { type: flag.kind === \"boolean\" ? \"boolean\" : \"string\" },\n ]),\n ) as Parameters<typeof parseArgs>[0] extends { options?: infer O } ? NonNullable<O> : never,\n });\n } catch (error) {\n throw usage(\n `${(error as Error).message.split(\". To specify\")[0]}. Run \"mostra ${commandName(command)} --help\".`,\n );\n }\n const flags: Record<string, string | number | boolean | readonly string[] | undefined> = {};\n for (const flag of command.flags ?? []) {\n const raw = parsed.values[flag.name];\n if (raw === undefined) continue;\n if (flag.kind === \"boolean\") {\n flags[flag.name] = raw === true;\n continue;\n }\n const text = String(raw);\n if (flag.choices && !flag.choices.includes(text)) {\n throw usage(`--${flag.name} takes one of ${flag.choices.join(\", \")}; \"${text}\" isn't one.`);\n }\n if (flag.kind === \"number\") {\n const number = Number(text);\n if (!Number.isInteger(number) || number < 0)\n throw usage(`--${flag.name} takes a whole number; \"${text}\" isn't one.`);\n flags[flag.name] = number;\n } else if (flag.kind === \"duration\") {\n durationMs(text);\n flags[flag.name] = text;\n } else if (flag.kind === \"list\") {\n flags[flag.name] = text\n .split(\",\")\n .map((item) => item.trim())\n .filter((item) => item.length > 0);\n } else flags[flag.name] = text;\n }\n const positionals = [...parsed.positionals];\n const args: Record<string, string | readonly string[] | undefined> = {};\n for (const arg of command.args ?? []) {\n if (arg.variadic) {\n if (positionals.length === 0 && !arg.optional)\n throw usage(`\"mostra ${commandName(command)}\" needs <${arg.name}…>.`);\n args[arg.name] = positionals.splice(0);\n continue;\n }\n const value = positionals.shift();\n if (value === undefined && !arg.optional)\n throw usage(`\"mostra ${commandName(command)}\" needs <${arg.name}>.`);\n args[arg.name] = value;\n }\n if (positionals.length > 0) {\n throw usage(\n `\"mostra ${commandName(command)}\" takes no argument \"${positionals[0]}\". Run \"mostra ${commandName(command)} --help\".`,\n );\n }\n if (typeof parsed.values[\"timeout\"] === \"string\") durationMs(parsed.values[\"timeout\"]);\n return { kind: \"run\", command, args, flags };\n}\n","/**\n * The npm bootstrap (RT-01, D142): a `mostra` installed from npm runs on whatever Node.js the\n * system has, so before anything else it finds the runtime bundle its release pins (from the\n * cache, or downloaded once, with progress on stderr) and runs the bundle's own `mostra` with the\n * same arguments on the bundle's private Node.js. Every command, telemetry included, then runs in\n * the bundle, and this process only waits and passes the exit code on.\n *\n * Inside a bundle, in a development checkout, or with `MOSTRA_BUNDLE`/`MOSTRA_RUNTIME_BIN` set,\n * there is nothing to bootstrap and the CLI runs in this process.\n *\n * This module runs on the system's Node.js, so it uses nothing newer than Node.js 22.19 and loads\n * none of the CLI's commands.\n */\nimport { spawn } from \"node:child_process\";\nimport { constants } from \"node:os\";\nimport { createDiagnostic, type Diagnostic, RpcError } from \"@mostra/protocol\";\nimport { enclosingBundle, type InstallProgress, readPins, resolveRuntime } from \"@mostra/sdk\";\nimport { exitCodeFor } from \"./exit.ts\";\nimport type { Environment } from \"./home.ts\";\nimport { commandWords } from \"./parse.ts\";\n\n/** How the bootstrap talks to the terminal. */\nexport interface BootstrapIo {\n readonly argv: readonly string[];\n readonly env: Environment;\n readonly stdout: (text: string) => void;\n readonly stderr: (text: string) => void;\n /** Whether stderr is a terminal: progress then rewrites one line. */\n readonly stderrTty: boolean;\n /**\n * Whether a terminal is attached (stdin, stdout or stderr is one). Ctrl-C there signals the\n * whole foreground process group, the bundle's `mostra` included, so SIGINT isn't forwarded:\n * a second one would cut short a command that stops gracefully on the first (`mostra dev`).\n */\n readonly terminal: boolean;\n}\n\n/** Whether this CLI should move into its pinned bundle before running a command. */\nexport function needsBootstrap(env: Environment): boolean {\n if (env[\"MOSTRA_BUNDLE\"] || env[\"MOSTRA_RUNTIME_BIN\"]) return false;\n if (enclosingBundle() !== undefined) return false;\n return readPins(env) !== undefined;\n}\n\n/**\n * Whether the command serves in this process instead of in the bundle (D164 item 7): `mostra mcp`\n * answers its client at once and installs the bundle in the background, since a client gives a\n * server only seconds to start (Codex 10 s) and a first install takes minutes.\n */\nexport function servesBeforeBundle(argv: readonly string[]): boolean {\n return commandWords(argv)[0] === \"mcp\";\n}\n\n/** Progress lines for a person waiting on the first download. */\nexport function progressReporter(\n io: Pick<BootstrapIo, \"stderr\" | \"stderrTty\">,\n): (progress: InstallProgress) => void {\n let lastPercent = -1;\n let lastStep = \"\";\n return (progress) => {\n if (progress.step === \"download\") {\n const percent = Math.floor((progress.received / progress.total) * 100);\n const mb = (bytes: number): string => `${Math.round(bytes / 1e6)} MB`;\n if (io.stderrTty) {\n if (percent !== lastPercent)\n io.stderr(\n `\\rmostra: downloading the Mostra runtime, ${mb(progress.received)} of ${mb(progress.total)} (${percent}%)`,\n );\n } else if (\n lastStep !== \"download\" ||\n Math.floor(percent / 25) > Math.floor(lastPercent / 25)\n ) {\n io.stderr(`mostra: downloading the Mostra runtime (${mb(progress.total)}): ${percent}%\\n`);\n }\n lastPercent = percent;\n lastStep = \"download\";\n return;\n }\n if (progress.step === lastStep) return;\n if (lastStep === \"download\" && io.stderrTty) io.stderr(\"\\n\");\n lastStep = progress.step;\n const words: Partial<Record<InstallProgress[\"step\"], string>> = {\n files: \"checking the runtime's files\",\n browser: \"fetching the browser verify uses\",\n };\n const said = words[progress.step];\n if (said !== undefined) io.stderr(`mostra: ${said}…\\n`);\n };\n}\n\n/** The envelope `--json` promises, for a bootstrap that fails before any command runs. */\nfunction failed(io: BootstrapIo, diagnostic: Diagnostic): number {\n io.stderr(`mostra: ${diagnostic.message}\\n`);\n if (diagnostic.hint) io.stderr(`mostra: ${diagnostic.hint}\\n`);\n if (io.argv.includes(\"--json\")) {\n io.stdout(`${JSON.stringify({ ok: false, error: diagnostic, warnings: [] })}\\n`);\n }\n return exitCodeFor(diagnostic.code);\n}\n\n/**\n * When this copy needs the bundle its release pins (`needsBootstrap`), runs the bundle's\n * `mostra` with `io.argv` and resolves with its exit code; otherwise, or for `mostra mcp`, which\n * installs the bundle itself while it serves (`servesBeforeBundle`), resolves `undefined`, and the\n * caller runs the command itself. Any failure, deciding included, is a diagnostic (one envelope\n * with `--json`) and its exit code. Signals this process gets are passed on to the child.\n */\nexport async function bootstrap(io: BootstrapIo): Promise<number | undefined> {\n try {\n // Deciding is inside the boundary too: pins that can't be read are a diagnostic, never a\n // stack trace (GPT review finding 3).\n if (!needsBootstrap(io.env) || servesBeforeBundle(io.argv)) return undefined;\n return await runInBundle(io);\n } catch (error) {\n // Whatever goes wrong, `--json` still gets exactly one envelope (D140 item 16).\n if (error instanceof RpcError) return failed(io, error.diagnostic);\n return failed(\n io,\n createDiagnostic(\"MOSTRA_HOST_INTERNAL_ERROR\", {\n message: `The npm bootstrap failed: ${error instanceof Error ? error.message : String(error)}`,\n }),\n );\n }\n}\n\nasync function runInBundle(io: BootstrapIo): Promise<number> {\n const runtime = await resolveRuntime({ env: io.env, onProgress: progressReporter(io) });\n if (runtime.cliEntry === undefined) {\n throw new RpcError(\n createDiagnostic(\"MOSTRA_ENV_RUNTIME_MISSING\", {\n message: \"The runtime the bootstrap found has no CLI entry.\",\n }),\n );\n }\n const cli = runtime.cliEntry;\n return new Promise((resolve) => {\n const child = spawn(runtime.node, [cli, ...io.argv], {\n stdio: \"inherit\",\n env: io.env as NodeJS.ProcessEnv,\n });\n const forward = (signal: NodeJS.Signals): void => {\n if (signal === \"SIGINT\" && io.terminal) return; // the child got the terminal's own\n child.kill(signal);\n };\n const signals: NodeJS.Signals[] = [\"SIGINT\", \"SIGTERM\", \"SIGHUP\"];\n for (const signal of signals) process.on(signal, forward);\n let settled = false;\n const settle = (code: number): void => {\n if (settled) return;\n settled = true;\n for (const signal of signals) process.off(signal, forward);\n resolve(code);\n };\n child.on(\"error\", (error) =>\n settle(\n failed(\n io,\n createDiagnostic(\"MOSTRA_ENV_RUNTIME_MISSING\", {\n message: `The runtime bundle's CLI couldn't be started (${runtime.node}): ${error.message}`,\n }),\n ),\n ),\n );\n // A child ended by a signal exits as a shell reports it: 128 plus the signal's number.\n child.on(\"exit\", (code, signal) =>\n settle(code ?? 128 + (signal ? (constants.signals[signal] ?? 0) : 0)),\n );\n });\n}\n"],"mappings":";;;;;;;AAqJA,SAAgB,cAAc,SAAiC;CAC7D,OAAO;AACT;;AAGA,SAAgB,YAAY,SAA2C;CACrE,OAAO,QAAQ,KAAK,KAAK,GAAG;AAC9B;;;;ACnJA,MAAa,OAAO;;CAElB,IAAI;;CAEJ,SAAS;;CAET,OAAO;;CAEP,aAAa;;CAEb,SAAS;;CAET,cAAc;;CAEd,UAAU;AACZ;;AAMA,MAAM,UAAsD;CAC1D,UAAU,KAAK;CACf,OAAO,KAAK;CACZ,MAAM,KAAK;CACX,MAAM,KAAK;CACX,KAAK,KAAK;CACV,KAAK,KAAK;CACV,OAAO,KAAK;CACZ,QAAQ,KAAK;CACb,MAAM,KAAK;CACX,SAAS,KAAK;CACd,SAAS,KAAK;CACd,SAAS,KAAK;CACd,MAAM,KAAK;CACX,QAAQ,KAAK;CACb,OAAO,KA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AAM,KAAK,MAAM;EACnB;EACA,MAAM,UAA4B;GAAC;GAAU;GAAW;EAAQ;EAChE,KAAK,MAAM,UAAU,SAAS,QAAQ,GAAG,QAAQ,OAAO;EACxD,IAAI,UAAU;EACd,MAAM,UAAU,SAAuB;GACrC,IAAI,SAAS;GACb,UAAU;GACV,KAAK,MAAM,UAAU,SAAS,QAAQ,IAAI,QAAQ,OAAO;GACzD,QAAQ,IAAI;EACd;EACA,MAAM,GAAG,UAAU,UACjB,OACE,OACE,IACA,iBAAiB,8BAA8B,EAC7C,SAAS,iDAAiD,QAAQ,KAAK,KAAK,MAAM,UACpF,CAAC,CACH,CACF,CACF;EAEA,MAAM,GAAG,SAAS,MAAM,WACtB,OAAO,QAAQ,OAAO,SAAU,UAAU,QAAQ,WAAW,IAAK,EAAE,CACtE;CACF,CAAC;AACH"}
@@ -0,0 +1 @@
1
+ export { t as bootstrap } from "./bootstrap-3_Tdfdg7.js";
@@ -337,6 +337,7 @@ const PATH_VARIABLES = [
337
337
  "MOSTRA_TEST_BINDING_TRACE",
338
338
  "MOSTRA_TEST_BUNDLE_PINS",
339
339
  "MOSTRA_TEST_VERIFY_FAIL_ONCE",
340
+ "MOSTRA_TEST_VERIFY_COLLIDE_ONCE",
340
341
  "MOSTRA_TAILSCALE",
341
342
  "MOSTRA_CLOUDFLARED",
342
343
  "MOSTRA_TEST_TUNNELS",
@@ -923,4 +924,4 @@ function startFlusher(store, env, now) {
923
924
  //#endregion
924
925
  export { packageRoot as _, detachedEnvironment as a, durationBucket as c, mcpSessionFields as d, buildEndpoint as f, fromSource as g, cliVersion as h, detachedDirectory as i, minute as l, truthy as m, startFlusher as n, TelemetryEvent as o, decide as p, TelemetryStore as r, catalogCodes as s, flush as t, detectHarness as u };
925
926
 
926
- //# sourceMappingURL=flush-D648gCYs.js.map
927
+ //# sourceMappingURL=flush-TPaIdwjy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flush-TPaIdwjy.js","names":["httpsRequest","httpRequest"],"sources":["../src/version.ts","../src/telemetry/decision.ts","../src/telemetry/harness.ts","../src/telemetry/events.ts","../src/detached.ts","../src/telemetry/store.ts","../src/telemetry/flush.ts"],"sourcesContent":["/** The CLI's own package: its root directory and its release. */\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nlet found: { readonly root: string; readonly version: string } | undefined;\n\nfunction own(): { readonly root: string; readonly version: string } {\n if (found) return found;\n let dir = dirname(fileURLToPath(import.meta.url));\n for (;;) {\n try {\n const manifest = JSON.parse(readFileSync(join(dir, \"package.json\"), \"utf8\")) as {\n name?: string;\n version?: string;\n };\n if (manifest.name === \"@mostra/cli\" && manifest.version) {\n found = { root: dir, version: manifest.version };\n return found;\n }\n } catch {\n // Keep looking upwards.\n }\n const parent = dirname(dir);\n if (parent === dir) throw new Error(\"Couldn't find @mostra/cli's package.json.\");\n dir = parent;\n }\n}\n\n/** This CLI's version (`mostra --version`, the client version it reports, telemetry's `version`). */\nexport function cliVersion(): string {\n return own().version;\n}\n\n/** The CLI package's directory: its `dist/`, `src/` and bundled reference live under it. */\nexport function packageRoot(): string {\n return own().root;\n}\n\n/** Whether this CLI runs from its TypeScript sources (tests), not its build. */\nexport function fromSource(): boolean {\n return import.meta.url.endsWith(\".ts\");\n}\n","/**\n * Whether telemetry sends, and why (D140 item 3). The first match decides, so an explicit \"off\"\n * anywhere wins over any \"on\", and withdrawn consent sticks.\n */\nimport type { Environment } from \"../home.ts\";\nimport type { ReadSettings } from \"./store.ts\";\nimport type { TelemetryReason } from \"./words.ts\";\n\n/** The endpoint this build sends to, set only by the release workflow at bundle time (D140 item 7). */\ndeclare const __MOSTRA_TELEMETRY_ENDPOINT__: string | undefined;\n\n/** The build's endpoint: empty in this package and in every development build. */\nexport function buildEndpoint(): string {\n return typeof __MOSTRA_TELEMETRY_ENDPOINT__ === \"string\" ? __MOSTRA_TELEMETRY_ENDPOINT__ : \"\";\n}\n\n/** What the decision reads. */\nexport interface DecisionInputs {\n readonly env: Environment;\n /** The build's endpoint ({@link buildEndpoint}); tests pass their own. */\n readonly buildEndpoint: string;\n /** Whether this use is embedded: a host-spawned instance, or a home a host configures. */\n readonly embedded: boolean;\n readonly settings: ReadSettings;\n /** Whether this machine's time zone asks first. */\n readonly askFirst: boolean;\n}\n\n/** The decision. */\nexport interface TelemetryDecision {\n readonly enabled: boolean;\n readonly reason: TelemetryReason;\n readonly askFirst: boolean;\n /** The endpoint events go to, when there is one. */\n readonly endpoint?: string;\n /** For an enabled decision: whether the person said yes, or it is the default. */\n readonly consent?: \"explicit\" | \"default\";\n}\n\nconst OFF_VALUES = new Set([\"0\", \"false\", \"off\", \"no\"]);\nconst ON_VALUES = new Set([\"1\", \"true\", \"on\", \"yes\"]);\n\n/** `DO_NOT_TRACK` and `MOSTRA_OFFLINE`'s parser: set to anything but empty, `0` or `false`. */\nexport function truthy(value: string | undefined): boolean {\n if (value === undefined) return false;\n const normalized = value.trim().toLowerCase();\n return normalized !== \"\" && normalized !== \"0\" && normalized !== \"false\";\n}\n\n/**\n * The endpoint in use: `MOSTRA_TELEMETRY_ENDPOINT` when it is `https:` or `http:` to a loopback\n * address, else the build's; `undefined` when there is none (D140 item 7).\n */\nexport function endpointOf(env: Environment, build: string): string | undefined {\n const override = env[\"MOSTRA_TELEMETRY_ENDPOINT\"];\n const chosen = override !== undefined && override !== \"\" ? override : build;\n if (chosen === \"\") return undefined;\n let url: URL;\n try {\n url = new URL(chosen);\n } catch {\n return undefined;\n }\n if (url.username !== \"\" || url.password !== \"\") return undefined;\n if (url.protocol === \"https:\") return url.href;\n const loopback =\n url.hostname === \"127.0.0.1\" || url.hostname === \"[::1]\" || url.hostname === \"localhost\";\n return url.protocol === \"http:\" && loopback ? url.href : undefined;\n}\n\n/** Decides, in D140's order. */\nexport function decide(inputs: DecisionInputs): TelemetryDecision {\n const { askFirst } = inputs;\n const off = (reason: TelemetryReason): TelemetryDecision => ({\n enabled: false,\n reason,\n askFirst,\n });\n const endpoint = endpointOf(inputs.env, inputs.buildEndpoint);\n if (endpoint === undefined) return off(\"no-collector\");\n const at = { askFirst, endpoint };\n if (inputs.embedded) return { ...at, enabled: false, reason: \"embedded\" };\n if (truthy(inputs.env[\"DO_NOT_TRACK\"])) return { ...at, enabled: false, reason: \"do-not-track\" };\n const variable = inputs.env[\"MOSTRA_TELEMETRY\"];\n const normalized = variable?.trim().toLowerCase();\n if (normalized !== undefined && OFF_VALUES.has(normalized)) {\n return { ...at, enabled: false, reason: \"variable\" };\n }\n if (!inputs.settings.ok) return { ...at, enabled: false, reason: \"unreadable\" };\n const choice = inputs.settings.settings.choice;\n if (choice === \"off\") return { ...at, enabled: false, reason: \"setting\" };\n if (normalized !== undefined && normalized !== \"\") {\n return ON_VALUES.has(normalized)\n ? { ...at, enabled: true, reason: \"variable\", consent: \"explicit\" }\n : { ...at, enabled: false, reason: \"variable-invalid\" };\n }\n if (choice === \"on\") return { ...at, enabled: true, reason: \"setting\", consent: \"explicit\" };\n return askFirst\n ? { ...at, enabled: false, reason: \"default\" }\n : { ...at, enabled: true, reason: \"default\", consent: \"default\" };\n}\n","/**\n * Which agent ran the CLI (D140 item 9), from environment markers each agent documents or sets in\n * its source (VERIFIED_FACTS, WP-10). Only the agent's ID is ever sent, never a marker's value.\n */\nimport type { Environment } from \"../home.ts\";\n\n/** The agents Mostra recognizes, in the order their markers are checked. */\nexport const HARNESSES = [\"claude-code\", \"codex\", \"gemini-cli\", \"opencode\", \"cursor\"] as const;\n\n/** A recognized agent, `other` for an agent Mostra doesn't know, `none` for no agent at all. */\nexport type Harness = (typeof HARNESSES)[number] | \"other\" | \"none\";\n\n/** Each agent's own marker. */\nconst MARKERS: Readonly<Record<(typeof HARNESSES)[number], string>> = {\n \"claude-code\": \"CLAUDECODE\",\n codex: \"CODEX_THREAD_ID\",\n \"gemini-cli\": \"GEMINI_CLI\",\n opencode: \"OPENCODE\",\n cursor: \"CURSOR_AGENT\",\n};\n\nconst set = (value: string | undefined): boolean => value !== undefined && value !== \"\";\n\n/**\n * The agent that ran this process: `AI_AGENT` when it starts with a known ID (the convention\n * `@vercel/detect-agent` reads), else the first agent whose own marker is set, else `other` when\n * `AI_AGENT` or `AGENT` names something else, else `none`. Cursor's editor terminal sets\n * `CURSOR_TRACE_ID` without `CURSOR_AGENT`: that is a person, so it isn't `cursor`.\n */\nexport function detectHarness(env: Environment): Harness {\n const declared = env[\"AI_AGENT\"];\n if (set(declared)) {\n const known = HARNESSES.find((id) => declared?.startsWith(id));\n if (known) return known;\n }\n for (const id of HARNESSES) if (set(env[MARKERS[id]])) return id;\n if (set(declared) || set(env[\"AGENT\"])) return \"other\";\n return \"none\";\n}\n\n/**\n * The known agent an MCP client is, by the `clientInfo.name` it sends (D140 item 8, D164 item 4),\n * as each was observed (VERIFIED_FACTS, WP-15): Claude Code sends `claude-code`, Codex\n * `codex-mcp-client`. Any other name is `other`; the name itself is never sent, since it can name\n * a private tool.\n */\nconst MCP_CLIENTS: Readonly<Record<string, (typeof HARNESSES)[number]>> = {\n \"claude-code\": \"claude-code\",\n \"codex-mcp-client\": \"codex\",\n};\n\n/** `mcp.session`'s fields for a client: its agent's ID, and its version only for a known one. */\nexport function mcpSessionFields(client: { readonly name: string; readonly version?: string }): {\n readonly client: (typeof HARNESSES)[number] | \"other\";\n readonly clientVersion?: string;\n} {\n const known = Object.hasOwn(MCP_CLIENTS, client.name) ? MCP_CLIENTS[client.name] : undefined;\n if (known === undefined) return { client: \"other\" };\n const version = client.version;\n return version !== undefined && /^[0-9A-Za-z.+-]{1,32}$/.test(version)\n ? { client: known, clientVersion: version }\n : { client: known };\n}\n","/**\n * Telemetry's event schema 1 (D140 item 8), the one published in `docs/reference/telemetry.md`.\n * Every event is checked against it before it is queued and again before it is sent, so nothing\n * that isn't on that page can leave the machine: the objects are strict, every string is from a\n * closed set or a pattern, and no field takes free text.\n */\nimport { DIAGNOSTIC_AREAS } from \"@mostra/protocol\";\nimport * as z from \"zod\";\nimport { HARNESSES, type Harness } from \"./harness.ts\";\n\n/** The schema version every event carries. */\nexport const SCHEMA = 1;\n\n/** The duration buckets of `cli.command`. */\nexport const DURATIONS = [\"<1s\", \"1-5s\", \"5-30s\", \"30s-2m\", \"2-10m\", \">10m\"] as const;\n\n/** A command's duration bucket. */\nexport function durationBucket(ms: number): (typeof DURATIONS)[number] {\n if (ms < 1000) return \"<1s\";\n if (ms < 5000) return \"1-5s\";\n if (ms < 30_000) return \"5-30s\";\n if (ms < 120_000) return \"30s-2m\";\n if (ms < 600_000) return \"2-10m\";\n return \">10m\";\n}\n\n/** A catalog-shaped diagnostic code: `MOSTRA_<AREA>_<NAME>`, never a message. */\nconst code = z\n .string()\n .regex(new RegExp(`^MOSTRA_(${DIAGNOSTIC_AREAS.join(\"|\")})_[A-Z0-9_]{1,64}$`));\n\n/** A command path from the definitions: lowercase words. */\nconst command = z.string().regex(/^[a-z]+( [a-z]+)?$/);\n\nconst common = {\n schema: z.literal(SCHEMA),\n at: z.string().regex(/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:00Z$/),\n installId: z.uuid(),\n version: z.string().regex(/^\\d+\\.\\d+\\.\\d+(-[0-9A-Za-z.-]+)?$/),\n os: z.enum([\"darwin\", \"linux\", \"win32\"]),\n arch: z.string().regex(/^[a-z0-9]{2,12}$/),\n node: z.int().min(0).max(999),\n harness: z.enum([...HARNESSES, \"other\", \"none\"]),\n ci: z.boolean(),\n consent: z.enum([\"explicit\", \"default\"]),\n};\n\n/** The fields every event carries. */\nexport interface CommonFields {\n readonly schema: typeof SCHEMA;\n readonly at: string;\n readonly installId: string;\n readonly version: string;\n readonly os: \"darwin\" | \"linux\" | \"win32\";\n readonly arch: string;\n readonly node: number;\n readonly harness: Harness;\n readonly ci: boolean;\n readonly consent: \"explicit\" | \"default\";\n}\n\n/** One event, as sent (D140 item 8). */\nexport type TelemetryEvent = CommonFields &\n (\n | { readonly event: \"cli.first_run\" }\n | {\n readonly event: \"cli.command\";\n readonly command: string;\n readonly exit: number;\n readonly duration: (typeof DURATIONS)[number];\n readonly json: boolean;\n readonly error?: string | undefined;\n }\n | {\n readonly event: \"verify.result\";\n readonly status: \"pass\" | \"fail\";\n readonly codes: readonly string[];\n readonly codesTruncated: boolean;\n }\n | { readonly event: \"publish.done\"; readonly reused: boolean; readonly forced: boolean }\n | {\n readonly event: \"share.done\";\n readonly kind: \"tailnet\" | \"funnel\" | \"cloudflare\" | \"remote\";\n }\n | {\n readonly event: \"mcp.session\";\n readonly client: (typeof HARNESSES)[number] | \"other\";\n readonly clientVersion?: string | undefined;\n }\n );\n\n/** Every event Mostra may send, as a strict union on `event`. */\nexport const TelemetryEvent: z.ZodType<TelemetryEvent> = z.discriminatedUnion(\"event\", [\n z.strictObject({ ...common, event: z.literal(\"cli.first_run\") }),\n z.strictObject({\n ...common,\n event: z.literal(\"cli.command\"),\n command,\n exit: z.int().min(0).max(255),\n duration: z.enum(DURATIONS),\n json: z.boolean(),\n error: code.optional(),\n }),\n z.strictObject({\n ...common,\n event: z.literal(\"verify.result\"),\n status: z.enum([\"pass\", \"fail\"]),\n codes: z.array(code).max(50),\n codesTruncated: z.boolean(),\n }),\n z.strictObject({\n ...common,\n event: z.literal(\"publish.done\"),\n reused: z.boolean(),\n forced: z.boolean(),\n }),\n // Emitted by WP-13 and WP-29.\n z.strictObject({\n ...common,\n event: z.literal(\"share.done\"),\n kind: z.enum([\"tailnet\", \"funnel\", \"cloudflare\", \"remote\"]),\n }),\n // Emitted by WP-15: a known agent's ID for the MCP client, or `other`; its version only then.\n z.strictObject({\n ...common,\n event: z.literal(\"mcp.session\"),\n client: z.enum([...HARNESSES, \"other\"]),\n clientVersion: z\n .string()\n .regex(/^[0-9A-Za-z.+-]{1,32}$/)\n .optional(),\n }),\n]);\n\n/** `at`: now in UTC, rounded down to the minute. */\nexport function minute(now: Date): string {\n return `${now.toISOString().slice(0, 16)}:00Z`;\n}\n\n/** The distinct catalog codes of `codes`, sorted, at most 50, and whether some were left out. */\nexport function catalogCodes(\n codes: readonly string[],\n known: ReadonlySet<string>,\n): { codes: string[]; codesTruncated: boolean } {\n const distinct = [...new Set(codes.filter((value) => known.has(value)))].sort();\n return { codes: distinct.slice(0, 50), codesTruncated: distinct.length > 50 };\n}\n","/**\n * The directory and environment of the processes the CLI leaves running: its home's daemon and\n * the telemetry flusher. They run in their file system's root, because on Windows nobody can\n * rename or remove a running process's working directory, and they outlive the command (WP-W2,\n * D151 item 3). Every path the environment names relative to the command's directory is made\n * absolute first, so it still names what it named for the command (Opus review of WP-W2,\n * finding 3).\n */\nimport { isAbsolute, parse, resolve } from \"node:path\";\n\n/**\n * The variables whose values are paths: Mostra's own, as the runtime, the SDK and the CLI read\n * them. A test keeps the list complete.\n */\nexport const PATH_VARIABLES: readonly string[] = [\n \"MOSTRA_HOME\",\n \"MOSTRA_RUNTIME_DIR\",\n \"MOSTRA_CONFIG_DIR\",\n \"MOSTRA_CACHE_DIR\",\n \"MOSTRA_BUNDLE\",\n \"MOSTRA_RUNTIME_BIN\",\n \"MOSTRA_SHELL_DIR\",\n \"MOSTRA_WARM_DIR\",\n \"MOSTRA_WORKER_ENTRY\",\n \"MOSTRA_VERIFY_ENTRY\",\n \"MOSTRA_WIN_HELPER\",\n \"MOSTRA_TEST_WORKER_HOST\",\n \"MOSTRA_TEST_NETWORK_FILESYSTEM\",\n \"MOSTRA_TEST_BINDING_TRACE\",\n \"MOSTRA_TEST_BUNDLE_PINS\",\n \"MOSTRA_TEST_VERIFY_FAIL_ONCE\",\n \"MOSTRA_TEST_VERIFY_COLLIDE_ONCE\",\n \"MOSTRA_TAILSCALE\",\n \"MOSTRA_CLOUDFLARED\",\n \"MOSTRA_TEST_TUNNELS\",\n \"MOSTRA_MCP_WORKSPACE\",\n];\n\n/** `env` with every relative path variable resolved against `cwd`. */\nexport function detachedEnvironment(\n env: Readonly<Record<string, string | undefined>>,\n cwd: string = process.cwd(),\n): Record<string, string | undefined> {\n const result: Record<string, string | undefined> = { ...env };\n for (const name of PATH_VARIABLES) {\n const value = result[name];\n if (value !== undefined && value !== \"\" && !isAbsolute(value)) {\n result[name] = resolve(cwd, value);\n }\n }\n return result;\n}\n\n/** The working directory of a process the CLI leaves running: the root of `anchor`'s file system. */\nexport function detachedDirectory(anchor: string): string {\n return parse(resolve(anchor)).root;\n}\n","/**\n * Telemetry's files in the CLI's config directory (D140 item 5): `telemetry.json` (the choice,\n * when the notice was shown, when a flush last started), `telemetry-id` (the random install ID)\n * and `telemetry-queue.ndjson` (events waiting to be sent). The directory is 0700 and the files\n * 0600; `telemetry.json` and the queue are written by rename. The install ID is made by an\n * exclusive create (a hard link that fails when the file exists), so processes on a first run\n * agree on one ID whatever happens to the lock. Every other change goes through one lock file,\n * owned by a token and taken over only when its holder has died, so a flusher never loses an\n * event appended while it sends.\n */\nimport { randomUUID } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fstatSync,\n linkSync,\n mkdirSync,\n openSync,\n readdirSync,\n readFileSync,\n renameSync,\n rmSync,\n statSync,\n writeFileSync,\n} from \"node:fs\";\nimport { basename, dirname, join } from \"node:path\";\n\n/** What `telemetry.json` holds. */\nexport interface TelemetrySettings {\n /** The person's choice: `mostra telemetry on|off`, or their answer to the question. */\n readonly choice?: \"on\" | \"off\";\n /**\n * The random install ID, made on the first run that sends; deleted when telemetry turns off.\n * Read from `telemetry-id`, never written into `telemetry.json`.\n */\n readonly installId?: string;\n /**\n * When the notice of what is sent was shown where sending follows: the default notice, the\n * question, or `mostra telemetry on`'s. A `default`-consent event needs it (Opus review\n * finding 3).\n */\n readonly noticeShownAt?: string;\n /**\n * When the ask-first notice (\"Nothing is sent unless you run: mostra telemetry on\") was\n * shown. It never stands for the default notice: a later run where telemetry is on by default\n * still shows that one before anything is sent.\n */\n readonly askFirstNoticeShownAt?: string;\n /** When a flush last started. */\n readonly lastFlushAt?: string;\n}\n\n/** The settings, or why they can't be read (which means off, D140 item 5). */\nexport type ReadSettings =\n | { readonly ok: true; readonly settings: TelemetrySettings }\n | { readonly ok: false; readonly file: string };\n\n/** A lock older than this whose owner no longer runs is taken over as stale. */\nconst STALE_LOCK_MS = 10_000;\n/**\n * A lock older than this is taken over whoever it names: a held section takes milliseconds, and\n * a PID can name an unrelated live process once the owner died (in a container, PID 1 always\n * runs), which would otherwise hold every later command up forever (Opus review finding 5).\n */\nconst DEAD_LOCK_MS = 60_000;\n/** The queue's bounds (D140 item 6). */\nexport const QUEUE_MAX_EVENTS = 1000;\nexport const QUEUE_MAX_AGE_MS: number = 7 * 24 * 60 * 60 * 1000;\n\nconst UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;\n\n/** Telemetry's files in one config directory. */\nexport class TelemetryStore {\n readonly dir: string;\n readonly settingsFile: string;\n readonly queueFile: string;\n readonly idFile: string;\n readonly #lockFile: string;\n readonly #platform: string;\n\n /** `platform` is the system whose lock rules apply: this process's, but for tests. */\n constructor(dir: string, platform: string = process.platform) {\n this.dir = dir;\n this.#platform = platform;\n this.settingsFile = join(dir, \"telemetry.json\");\n this.queueFile = join(dir, \"telemetry-queue.ndjson\");\n this.idFile = join(dir, \"telemetry-id\");\n this.#lockFile = join(dir, \"telemetry.lock\");\n }\n\n /** The settings; a file that isn't telemetry settings is unreadable, never guessed at. */\n read(): ReadSettings {\n // A directory that can never exist (a part of its path is a file) is unreadable, never\n // \"nothing stored yet\". POSIX says so for every read (ENOTDIR); Windows answers ENOENT, which\n // would read as the default, on, though nothing could ever be recorded (WP-W2).\n if (blocked(this.dir)) return { ok: false, file: this.dir };\n const id = this.#readId();\n if (id === null) return { ok: false, file: this.idFile };\n let text: string;\n try {\n text = readFileSync(this.settingsFile, \"utf8\");\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\")\n return { ok: true, settings: id !== undefined ? { installId: id } : {} };\n return { ok: false, file: this.settingsFile };\n }\n try {\n const data = JSON.parse(text) as Record<string, unknown>;\n if (typeof data !== \"object\" || data === null || Array.isArray(data)) throw new Error();\n const { choice, noticeShownAt, askFirstNoticeShownAt, lastFlushAt } = data;\n const installId = id;\n if (choice !== undefined && choice !== \"on\" && choice !== \"off\") throw new Error();\n // An install ID belongs in `telemetry-id`; one here is a file Mostra didn't write.\n if (data[\"installId\"] !== undefined) throw new Error();\n if (noticeShownAt !== undefined && typeof noticeShownAt !== \"string\") throw new Error();\n if (askFirstNoticeShownAt !== undefined && typeof askFirstNoticeShownAt !== \"string\")\n throw new Error();\n if (lastFlushAt !== undefined && typeof lastFlushAt !== \"string\") throw new Error();\n return {\n ok: true,\n settings: {\n ...(choice !== undefined ? { choice } : {}),\n ...(installId !== undefined ? { installId } : {}),\n ...(noticeShownAt !== undefined ? { noticeShownAt } : {}),\n ...(askFirstNoticeShownAt !== undefined ? { askFirstNoticeShownAt } : {}),\n ...(lastFlushAt !== undefined ? { lastFlushAt } : {}),\n },\n };\n } catch {\n return { ok: false, file: this.settingsFile };\n }\n }\n\n /**\n * Changes the settings under the lock and returns what they became; `undefined` when the file\n * can't be read (nothing is written over it).\n */\n update(change: (current: TelemetrySettings) => TelemetrySettings): TelemetrySettings | undefined {\n return this.locked(() => {\n const current = this.read();\n if (!current.ok) return undefined;\n const next = change(current.settings);\n this.#write(next);\n return next;\n });\n }\n\n /**\n * The install ID, made when there is none yet. A new ID is written to a file of this process's\n * own, then hard-linked to `telemetry-id`, which fails when the file exists: of any processes\n * making one at once exactly one wins, and the others read the winner's. `undefined` when the\n * settings can't be read.\n */\n installId(): { readonly id: string; readonly created: boolean } | undefined {\n const current = this.read();\n if (!current.ok) return undefined;\n if (current.settings.installId !== undefined)\n return { id: current.settings.installId, created: false };\n const candidate = `${this.idFile}.${process.pid}.${randomUUID()}.tmp`;\n const id = randomUUID();\n try {\n this.#prepareDir();\n writeFileSync(candidate, `${id}\\n`, { mode: 0o600 });\n linkSync(candidate, this.idFile);\n return { id, created: true };\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== \"EEXIST\") return undefined;\n const winner = this.#readId();\n return winner ? { id: winner, created: false } : undefined;\n } finally {\n rmSync(candidate, { force: true });\n }\n }\n\n /** The install ID in `telemetry-id`: `undefined` when there is none, `null` when it's damaged. */\n #readId(): string | undefined | null {\n let text: string;\n // Windows refuses to open a file another process holds for a moment (an antivirus scan of the\n // new file, or the removal of the temporary name it was linked from) with `EPERM`, `EACCES` or\n // `EBUSY`: the read is tried again for up to a second, as renames are (#129).\n const deadline = Date.now() + 1000;\n for (let pause = 5; ; pause = Math.min(pause * 2, 100)) {\n try {\n text = readFileSync(this.idFile, \"utf8\");\n break;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return undefined;\n const shared = code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n if (this.#platform !== \"win32\" || !shared || Date.now() > deadline) return null;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, pause);\n }\n }\n const id = text.trim();\n return UUID.test(id) ? id : null;\n }\n\n /**\n * Replaces a file that can't be read with these settings; only `telemetry on|off` do, as the\n * person's explicit choice. Call it holding the lock.\n */\n reset(settings: TelemetrySettings): TelemetrySettings {\n const { installId: _id, ...rest } = settings;\n this.#write(rest);\n // A damaged install ID goes too; `on` makes a new one on its first send.\n rmSync(this.idFile, { force: true });\n if (settings.choice === \"off\") rmSync(this.queueFile, { force: true });\n return rest;\n }\n\n /** Turns telemetry off: the choice, and the install ID and the queue deleted at once. */\n turnOff(): boolean {\n return (\n this.locked(() => {\n const current = this.read();\n if (!current.ok) return false;\n const { installId: _id, ...rest } = current.settings;\n this.#write({ ...rest, choice: \"off\" });\n rmSync(this.idFile, { force: true });\n rmSync(this.queueFile, { force: true });\n return true;\n }) ?? false\n );\n }\n\n /** Appends events to the queue, keeping its bounds. */\n append(lines: readonly string[], now: number): void {\n if (lines.length === 0) return;\n this.locked(() => {\n const kept = bounded([...this.#queued(), ...lines], now);\n this.#writeQueue(kept);\n });\n }\n\n /** The queued events, within their bounds. */\n queued(now: number): string[] {\n return bounded(this.#queued(), now);\n }\n\n /**\n * Removes the lines a flush sent from the head of the queue, after pruning what expired or\n * fell outside the bounds, as {@link queued} did; how many sent lines were removed (0 when the\n * lock can't be had). A flusher stops when this is 0, so it never sends a batch twice.\n */\n drop(sent: readonly string[], now: number): number {\n return (\n this.locked(() => {\n const queued = bounded(this.#queued(), now);\n let index = 0;\n while (index < sent.length && queued[index] === sent[index]) index += 1;\n this.#writeQueue(queued.slice(index));\n return index;\n }) ?? 0\n );\n }\n\n #queued(): string[] {\n try {\n return readFileSync(this.queueFile, \"utf8\")\n .split(\"\\n\")\n .filter((line) => line.length > 0);\n } catch {\n return [];\n }\n }\n\n #writeQueue(lines: readonly string[]): void {\n if (lines.length === 0) {\n rmSync(this.queueFile, { force: true });\n return;\n }\n const temporary = `${this.queueFile}.${process.pid}.tmp`;\n writeFileSync(temporary, `${lines.join(\"\\n\")}\\n`, { mode: 0o600 });\n replace(temporary, this.queueFile, this.#platform);\n }\n\n #write(settings: TelemetrySettings): void {\n const { installId: _id, ...stored } = settings;\n const temporary = `${this.settingsFile}.${process.pid}.tmp`;\n writeFileSync(temporary, `${JSON.stringify(stored, null, 2)}\\n`, { mode: 0o600 });\n replace(temporary, this.settingsFile, this.#platform);\n }\n\n #prepareDir(): void {\n mkdirSync(this.dir, { recursive: true, mode: 0o700 });\n // Windows has no modes: the directory keeps the access list `%APPDATA%` hands down.\n if (this.#platform === \"win32\") return;\n try {\n chmodSync(this.dir, 0o700);\n } catch {\n // A directory someone else owns: the files below fail or succeed on their own terms.\n }\n }\n\n /**\n * Runs `fn` holding the lock file; `undefined` when the lock can't be had within 2 s, or the\n * directory or a file in it can't be written (a full disk, a directory someone else owns):\n * telemetry never stops a command (D140 item 5). The lock\n * holds its owner's PID and a token of its own, is released only by its owner, and is taken\n * over when it is older than 10 s and its owner is no longer running (a crash), or older than\n * 60 s whoever it names.\n */\n locked<T>(fn: () => T): T | undefined {\n try {\n this.#prepareDir();\n } catch {\n return undefined;\n }\n const token = `${process.pid} ${randomUUID()}`;\n const deadline = Date.now() + 2000;\n for (;;) {\n try {\n writeFileSync(this.#lockFile, token, { flag: \"wx\", mode: 0o600 });\n break;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (!held(code, this.#platform)) return undefined;\n // Every path back to the create checks the deadline, so nothing can hold the CLI here\n // (GPT review of WP-W2), and only a lock that just went is tried again without a pause,\n // so nothing spins either (Opus review of WP-W2, finding 2).\n if (Date.now() > deadline) return undefined;\n const next = this.#breakStale();\n if (next === \"absent\") {\n // No lock there, though the create was refused. After `EEXIST` it was removed in\n // between: try again. After access denied, either a lock Windows was deleting went in\n // between (twelve processes at once keep that happening), or this user can't write the\n // directory and waiting changes nothing (Opus review of WP-W2, finding 2). A file of\n // this process's own tells which, whatever the timing (MT-01: a count of such rounds\n // in a row still gave up under contention).\n if (code === \"EEXIST\") continue;\n if (!writable(this.dir)) return undefined;\n } else if (next === \"broken\") continue;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);\n }\n }\n try {\n return fn();\n } catch {\n return undefined;\n } finally {\n this.#release(token);\n }\n }\n\n /** Removes the lock when it is still this owner's. */\n #release(token: string): void {\n try {\n if (readFileSync(this.#lockFile, \"utf8\") === token) rmSync(this.#lockFile, { force: true });\n } catch {\n // Gone already.\n }\n }\n\n /**\n * Takes a crashed owner's lock away (#98). Only one process breaks locks at a time: it holds the\n * break lock while it judges the lock again and removes it. An owner removes only its own lock\n * and every other remover holds the break lock, so the lock judged is the lock removed: no\n * breaker ever moves a live owner's lock aside or brings back one its owner released.\n *\n * The break lock is never removed by anyone but its holder, since removing a file only if it is\n * the one judged can't be done atomically (Opus review of WP-13): break locks are numbered\n * (`telemetry.lock.break.<n>`), the highest is the one in force, and a crashed breaker's is\n * superseded, never removed, by creating the next number exclusively. Two that judged the same\n * one crashed race for the same next number, and one of them wins; one that created a number\n * below a higher one holds nothing. The holder removes the ones below its own, then its own\n * when done. A break lock is crashed by the lock's own rules (older\n * than 10 s with its owner gone, or older than 60 s).\n *\n * Answers `broken` when the caller should try again at once, `absent` when no lock file exists,\n * and `held` when the caller should wait: a live owner's lock, another breaker at work, or a\n * lock that can't be read (on Windows, a lock being deleted).\n */\n #breakStale(): \"broken\" | \"absent\" | \"held\" {\n const judged = judge(this.#lockFile);\n if (judged !== \"stale\") return judged;\n const dir = dirname(this.#lockFile);\n const prefix = `${basename(this.#lockFile)}.break.`;\n const numbered = (): number[] => {\n try {\n return readdirSync(dir)\n .filter(\n (name) =>\n name.startsWith(prefix) && /^[1-9][0-9]{0,15}$/.test(name.slice(prefix.length)),\n )\n .map((name) => Number(name.slice(prefix.length)))\n .sort((a, b) => a - b);\n } catch {\n return [];\n }\n };\n const file = (n: number): string => join(dir, `${prefix}${n}`);\n const below = numbered();\n const current = below.at(-1);\n if (current !== undefined) {\n // Another breaker is at work, or one crashed at it.\n if (judge(file(current)) !== \"stale\") return \"held\";\n pause(breakPauseMs());\n }\n const mine = (current ?? 0) + 1;\n const token = `${process.pid} ${randomUUID()}`;\n try {\n writeFileSync(file(mine), token, { flag: \"wx\", mode: 0o600 });\n } catch {\n // Another breaker took this number first, or the directory can't be written.\n return \"held\";\n }\n try {\n // A process that listed before a later number existed may create a lower one: the highest\n // holds, and this one, not the highest, never acts.\n if (numbered().some((n) => n > mine)) return \"held\";\n // The ones before are superseded: a crashed breaker's, or ones a holder left by crashing.\n for (const n of below) rmSync(file(n), { force: true });\n // Judged again under the break lock: the lock may have gone, or been replaced, meanwhile.\n const now = judge(this.#lockFile);\n if (now !== \"stale\") return now;\n pause(breakPauseMs());\n rmSync(this.#lockFile, { force: true });\n return \"broken\";\n } finally {\n rmSync(file(mine), { force: true });\n }\n }\n}\n\n/**\n * Whether a lock file may be taken away: `stale` when it is older than 10 s and its owner no\n * longer runs, or older than 60 s whoever it names; `held` while it is younger, its owner runs,\n * or it can't be read; `absent` when there is none. One descriptor reads the age and the\n * contents, so both describe the same file.\n */\nfunction judge(file: string): \"stale\" | \"absent\" | \"held\" {\n let handle: number | undefined;\n try {\n handle = openSync(file, \"r\");\n const age = Date.now() - fstatSync(handle).mtimeMs;\n if (age <= STALE_LOCK_MS) return \"held\";\n const seen = readFileSync(handle, \"utf8\");\n return age <= DEAD_LOCK_MS && ownerAlive(seen) ? \"held\" : \"stale\";\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"ENOENT\" ? \"absent\" : \"held\";\n } finally {\n if (handle !== undefined) closeSync(handle);\n }\n}\n\n/**\n * Renames `from` over `to`. Windows refuses to replace a file another process has open, as a\n * process reading the settings outside the lock does, with `EPERM` (MT-01: CI's install-ID race,\n * traced on `windows-latest`); the rename is tried again for up to a second, as the runtime's\n * renames are (D150 item 8), and never turned into a copy.\n */\nexport function replace(\n from: string,\n to: string,\n platform: string,\n rename: (from: string, to: string) => void = renameSync,\n): void {\n const deadline = Date.now() + 1000;\n for (let pause = 5; ; pause = Math.min(pause * 2, 100)) {\n try {\n rename(from, to);\n return;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n const shared = code === \"EPERM\" || code === \"EACCES\" || code === \"EBUSY\";\n if (platform !== \"win32\" || !shared || Date.now() > deadline) throw error;\n Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, pause);\n }\n }\n}\n\n/** Whether this process can create a file in `dir`: a probe of its own, removed at once. */\nexport function writable(\n dir: string,\n remove: (path: string) => void = (path) => rmSync(path, { force: true }),\n): boolean {\n const probe = join(dir, `.probe-${process.pid}-${randomUUID()}`);\n try {\n writeFileSync(probe, \"\", { flag: \"wx\", mode: 0o600 });\n } catch {\n return false;\n }\n // The probe was made, so the directory is writable whatever its removal meets: on Windows an\n // antivirus or the indexer may hold the new file for a moment (EBUSY, EPERM), and telemetry never\n // stops a command (D140 item 5; Opus review of MT-01, 8). An empty probe left behind is harmless.\n try {\n remove(probe);\n } catch {\n // Left for the next probe's directory to carry; nothing reads it.\n }\n return true;\n}\n\n/**\n * Whether a lock's exclusive create failed because another process holds it. On Windows a lock\n * its owner just removed stays \"delete pending\" while anyone still has it open (another process\n * judging its age), and creating it again meanwhile is refused as access denied, not `EEXIST`\n * (WP-W2: twelve first runs at once on an arm64 runner): that is contention too, never a reason\n * to give up.\n */\nfunction held(code: string | undefined, platform: string): boolean {\n return code === \"EEXIST\" || (platform === \"win32\" && (code === \"EPERM\" || code === \"EACCES\"));\n}\n\n/** Whether `dir` can never be created: its nearest existing ancestor isn't a directory. */\nfunction blocked(dir: string): boolean {\n for (let path = dir; ; path = dirname(path)) {\n try {\n return !statSync(path).isDirectory();\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"ENOTDIR\") return true;\n if (code !== \"ENOENT\") return false;\n }\n if (dirname(path) === path) return false;\n }\n}\n\n/** Whether the process a lock names still runs; a lock whose owner can't be read counts as live. */\nfunction ownerAlive(lock: string): boolean {\n const pid = Number(lock.split(\" \")[0]);\n if (!Number.isSafeInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return (error as NodeJS.ErrnoException).code === \"EPERM\";\n }\n}\n\n/** The newest events within 1,000, none older than 7 days; lines that aren't JSON go. */\nfunction bounded(lines: readonly string[], now: number): string[] {\n const fresh = lines.filter((line) => {\n try {\n const at = Date.parse((JSON.parse(line) as { at?: string }).at ?? \"\");\n return Number.isFinite(at) && now - at <= QUEUE_MAX_AGE_MS;\n } catch {\n return false;\n }\n });\n return fresh.slice(-QUEUE_MAX_EVENTS);\n}\n\n/**\n * A pause inside a breaker's step, for tests only (`MOSTRA_TEST_LOCK_BREAK_MS`): it widens the\n * window a slow machine opens between judging a lock and acting on it (#98).\n */\nconst BREAK_PAUSE_VARIABLE = \"MOSTRA_TEST_LOCK_BREAK_MS\";\nfunction breakPauseMs(): number {\n const value = Number(process.env[BREAK_PAUSE_VARIABLE] ?? \"0\");\n return Number.isFinite(value) && value > 0 ? Math.min(value, 5_000) : 0;\n}\nfunction pause(ms: number): void {\n if (ms > 0) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);\n}\n","/**\n * Sending the queue (D140 item 6): a detached process the CLI starts after a command, at most one\n * at a time and at most once a minute. It reads the decision again before it sends, so consent\n * withdrawn in between drops the events; it posts at most 100 events per request with no header\n * but `Content-Type`, `User-Agent` and the ones HTTP itself needs, and keeps what a failed\n * attempt couldn't send for the next flush.\n */\n\nimport { spawn } from \"node:child_process\";\nimport { request as httpRequest } from \"node:http\";\nimport { request as httpsRequest } from \"node:https\";\nimport { join } from \"node:path\";\nimport { detachedDirectory, detachedEnvironment } from \"../detached.ts\";\nimport type { Environment } from \"../home.ts\";\nimport { cliVersion, fromSource, packageRoot } from \"../version.ts\";\nimport { buildEndpoint, decide } from \"./decision.ts\";\nimport { TelemetryEvent } from \"./events.ts\";\nimport { QUEUE_MAX_EVENTS, type TelemetryStore } from \"./store.ts\";\n\n/** At most this many events per request. */\nexport const BATCH = 100;\n/** A flush starts at most this often. */\nexport const FLUSH_INTERVAL_MS = 60_000;\n/** The flush interval; `MOSTRA_TEST_FLUSH_INTERVAL_MS` shortens it, for tests only. */\nfunction flushInterval(env: Environment): number {\n const test = Number(env[\"MOSTRA_TEST_FLUSH_INTERVAL_MS\"]);\n return Number.isInteger(test) && test >= 0 && test < FLUSH_INTERVAL_MS ? test : FLUSH_INTERVAL_MS;\n}\n\n/** One request's limit. */\nconst REQUEST_TIMEOUT_MS = 5000;\n\n/** Posts one batch; resolves with whether the collector took it (any 2xx). */\nexport function post(endpoint: string, body: string): Promise<boolean> {\n return new Promise((resolve) => {\n const url = new URL(endpoint);\n const send = url.protocol === \"https:\" ? httpsRequest : httpRequest;\n const req = send(\n url,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": `mostra-cli/${cliVersion()}`,\n \"Content-Length\": Buffer.byteLength(body),\n },\n timeout: REQUEST_TIMEOUT_MS,\n },\n (response) => {\n response.resume();\n response.on(\"end\", () =>\n resolve((response.statusCode ?? 0) >= 200 && (response.statusCode ?? 0) < 300),\n );\n response.on(\"error\", () => resolve(false));\n },\n );\n req.on(\"timeout\", () => req.destroy());\n req.on(\"error\", () => resolve(false));\n req.end(body);\n });\n}\n\n/**\n * Sends the queue: the decision again, then batches until one fails. Events the schema refuses\n * never leave the machine.\n */\nexport async function flush(\n store: TelemetryStore,\n env: Environment,\n now: () => number,\n): Promise<void> {\n const settings = store.read();\n // The queue holds only events of uses that aren't embedded; the rest of the order applies again.\n const decision = decide({\n env,\n buildEndpoint: buildEndpoint(),\n embedded: false,\n settings,\n askFirst: false,\n });\n if (!decision.enabled || decision.endpoint === undefined) {\n // Consent withdrawn (or never given) since the events were queued: they go unsent.\n if (decision.reason !== \"no-collector\" && settings.ok) store.drop(store.queued(now()), now());\n return;\n }\n // The queue holds at most QUEUE_MAX_EVENTS, so a flush needs at most this many batches.\n for (let round = 0; round <= Math.ceil(QUEUE_MAX_EVENTS / BATCH); round += 1) {\n const lines = store.queued(now()).slice(0, BATCH);\n if (lines.length === 0) return;\n const events: unknown[] = [];\n for (const line of lines) {\n try {\n const parsed = TelemetryEvent.safeParse(JSON.parse(line));\n if (parsed.success) events.push(parsed.data);\n } catch {\n // Not an event: dropped with the batch.\n }\n }\n const sent = events.length === 0 || (await post(decision.endpoint, JSON.stringify({ events })));\n if (!sent) return;\n // Nothing removed (another process changed the queue, or the lock was out of reach): stop\n // rather than send the same batch again.\n if (store.drop(lines, now()) === 0) return;\n }\n}\n\n/** The flusher's entry in the CLI's package. */\nfunction flusherEntry(): { readonly entry: string; readonly nodeArgs: readonly string[] } {\n const root = packageRoot();\n return fromSource()\n ? {\n entry: join(root, \"src\", \"telemetry\", \"flush-main.ts\"),\n nodeArgs: [\"--conditions=@mostra/source\"],\n }\n : { entry: join(root, \"dist\", \"telemetry\", \"flush-main.js\"), nodeArgs: [] };\n}\n\n/**\n * Starts a flusher when the queue has events and no flush started in the last minute, fully\n * detached: no stdio, its own process group, never waited for, so `mostra … | jq` and every\n * harness reading to end of file finish when the command does.\n */\nexport function startFlusher(store: TelemetryStore, env: Environment, now: number): void {\n if (store.queued(now).length === 0) return;\n let due = false;\n store.update((current) => {\n const last = current.lastFlushAt === undefined ? 0 : Date.parse(current.lastFlushAt);\n if (Number.isFinite(last) && now - last < flushInterval(env)) return current;\n due = true;\n return { ...current, lastFlushAt: new Date(now).toISOString() };\n });\n if (!due) return;\n const { entry, nodeArgs } = flusherEntry();\n try {\n const child = spawn(process.execPath, [...nodeArgs, entry, store.dir], {\n detached: true,\n stdio: \"ignore\",\n // Not the command's directory but its file system's root, which always exists: on Windows\n // a process's working directory can't be removed or renamed while it runs, and the flusher\n // outlives the command (WP-W2).\n cwd: detachedDirectory(store.dir),\n env: detachedEnvironment({ ...process.env, ...env }) as NodeJS.ProcessEnv,\n });\n child.on(\"error\", () => {});\n child.unref();\n } catch {\n // Telemetry never changes a command's outcome.\n }\n}\n"],"mappings":";;;;;;;;;;;AAKA,IAAI;AAEJ,SAAS,MAA2D;CAClE,IAAI,OAAO,OAAO;CAClB,IAAI,MAAM,QAAQ,cAAc,YAAY,GAAG,CAAC;CAChD,SAAS;EACP,IAAI;GACF,MAAM,WAAW,KAAK,MAAM,aAAa,KAAK,KAAK,cAAc,GAAG,MAAM,CAAC;GAI3E,IAAI,SAAS,SAAS,iBAAiB,SAAS,SAAS;IACvD,QAAQ;KAAE,MAAM;KAAK,SAAS,SAAS;IAAQ;IAC/C,OAAO;GACT;EACF,QAAQ,CAER;EACA,MAAM,SAAS,QAAQ,GAAG;EAC1B,IAAI,WAAW,KAAK,MAAM,IAAI,MAAM,2CAA2C;EAC/E,MAAM;CACR;AACF;;AAGA,SAAgB,aAAqB;CACnC,OAAO,IAAI,CAAC,CAAC;AACf;;AAGA,SAAgB,cAAsB;CACpC,OAAO,IAAI,CAAC,CAAC;AACf;;AAGA,SAAgB,aAAsB;CACpC,OAAO,YAAY,IAAI,SAAS,KAAK;AACvC;;;;AC9BA,SAAgB,gBAAwB;CACtC,OAA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;AAC9E;;;;;;AAOA,SAAgB,aAAa,OAAuB,KAAkB,KAAmB;CACvF,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC,WAAW,GAAG;CACpC,IAAI,MAAM;CACV,MAAM,QAAQ,YAAY;EACxB,MAAM,OAAO,QAAQ,gBAAgB,KAAA,IAAY,IAAI,KAAK,MAAM,QAAQ,WAAW;EACnF,IAAI,OAAO,SAAS,IAAI,KAAK,MAAM,OAAO,cAAc,GAAG,GAAG,OAAO;EACrE,MAAM;EACN,OAAO;GAAE,GAAG;GAAS,aAAa,IAAI,KAAK,GAAG,CAAC,CAAC,YAAY;EAAE;CAChE,CAAC;CACD,IAAI,CAAC,KAAK;CACV,MAAM,EAAE,OAAO,aAAa,aAAa;CACzC,IAAI;EACF,MAAM,QAAQ,MAAM,QAAQ,UAAU;GAAC,GAAG;GAAU;GAAO,MAAM;EAAG,GAAG;GACrE,UAAU;GACV,OAAO;GAIP,KAAK,kBAAkB,MAAM,GAAG;GAChC,KAAK,oBAAoB;IAAE,GAAG,QAAQ;IAAK,GAAG;GAAI,CAAC;EACrD,CAAC;EACD,MAAM,GAAG,eAAe,CAAC,CAAC;EAC1B,MAAM,MAAM;CACd,QAAQ,CAER;AACF"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/home.ts","../src/client.ts","../src/command.ts","../src/commands/index.ts","../src/exit.ts","../src/help.ts","../src/run.ts"],"mappings":";;;;KAWY,cAAc,SAAS;;;;UCoBlB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;UAIM;;WAEN,SAAS;;WAET,mBAAmB;;EAE5B,KAAK,GAAG,GAAG,QAAQ,iBAAiB,GAAG,IAAI,QAAQ,GAAG,qBAAqB,QAAQ;;EAEnF,eAAe,gBAAgB,UAAU;;WAEhC,QAAQ;;EAEjB;;;;;KCjDU;;UAGK;;WAEN;;WAEA,MAAM;;WAEN;;WAEA;;WAEA;;WAEA;;;UAIM;;WAEN;;WAEA;;WAEA;;WAEA;;;UAIM;;WAEN,MAAM,SAAS;;WAEf,OAAO,SACd;;WAGO;;WAEA;;WAEA;;EAET,KAAK,GAAG,GAAG,QAAQ,iBAAiB,GAAG,IAAI,QAAQ,IAAI,QAAQ;;EAE/D,aAAa;;EAEb,IAAI;;EAEJ,KAAK,gBAAgB;;EAErB,KAAK,YAAY;;WAER,KAAK,SAAS;;WAEd;aAAgB;aAAyB;aAA0B;;;WAEnE;;EAET,OAAO,OAAO;;;;;EAKd,WAAW;;;;;EAKX,WAAW,sBAAsB,QAAQ;;EAEzC,QACE,yBACA,6BACC;IAAU;IAAc;;;WAElB;;WAEA,SAAS;;WAET,SAAS;;;UAIH;;WAEN;;WAEA,QAAQ,SAAS;;;UAIX;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;;UAIM;;WAEN;;WAEA;;WAEA,gBAAgB;;WAEhB,iBAAiB;;WAEjB;aAAmB;aAAuB;;;WAE1C;;WAEA;;WAEA,yBAAyB,OAAO;;WAEhC;;WAEA;;;;;WAKA,oBAAoB,OAAO;;EAEpC,IAAI,SAAS,iBAAiB,QAAQ;;;;;qBC/F3B,mBAAmB;;;;qBCzCnB;;WAEX;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;KAIU,mBAAmB,mBAAmB;;wBA0DlC,YAAY,eAAe;;;;wBCf3B,YAAY,SAAS;;wBAqDrB,kBAAkB,SAAS,aAAa;;wBA4BxC,kBAAkB,mBAAmB;;;;UC/GpC;;WAEN;;WAEA,KAAK;;WAEL;;WAEA,SAAS;;WAET,SAAS;;WAET,OAAO,OAAO;;WAEd;aAAgB;aAAyB;aAA0B;;;WAEnE;;WAEA;;;wBA+DW,IAAI,IAAI,WAAW"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/home.ts","../src/client.ts","../src/command.ts","../src/commands/index.ts","../src/exit.ts","../src/help.ts","../src/run.ts"],"mappings":";;;;KAWY,cAAc,SAAS;;;;UCoBlB;;WAEN;;WAE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,KAAK;;WAEL;;WAEA,SAAS;;WAET,SAAS;;WAET,OAAO,OAAO;;WAEd;aAAgB;aAAyB;aAA0B;;;WAEnE;;WAEA;;;wBA+DW,IAAI,IAAI,WAAW"}
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import { d as EXIT, f as exitCodeFor } from "./bootstrap-_iCl_HaO.js";
2
- import { a as COMMANDS, i as referenceMarkdown, n as commandDefinition, r as commandHelp, t as run } from "./run-BxYL-DaX.js";
1
+ import { d as EXIT, f as exitCodeFor } from "./bootstrap-3_Tdfdg7.js";
2
+ import { a as COMMANDS, i as referenceMarkdown, n as commandDefinition, r as commandHelp, t as run } from "./run-CtR0PFMj.js";
3
3
  export { COMMANDS, EXIT, commandDefinition, commandHelp, exitCodeFor, referenceMarkdown, run };
@@ -4,7 +4,7 @@
4
4
 
5
5
  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.
6
6
 
7
- Commands: `add`, `daemon`, `dev`, `docs`, `doctor`, `export`, `gc`, `host`, `list`, `login`, `logout`, `mcp`, `new`, `open`, `pause`, `publish`, `push`, `results`, `resume`, `run`, `secret`, `share`, `state`, `status`, `telemetry`, `verify`, `wait`.
7
+ Commands: `add`, `daemon`, `dev`, `docs`, `doctor`, `export`, `gc`, `host`, `list`, `login`, `logout`, `mcp`, `new`, `open`, `pause`, `publish`, `push`, `results`, `resume`, `roster`, `run`, `secret`, `share`, `state`, `status`, `telemetry`, `verify`, `wait`.
8
8
 
9
9
  ## mostra new
10
10
 
@@ -210,6 +210,7 @@ Flags:
210
210
  --scope <a,b> The link's scopes: view, draft, submit, review, signal, action:*. Default: all.
211
211
  --viewer <ref> The person the link is for, by your own stable key for them; without it, each link is a viewer of its own.
212
212
  --viewer-name <name> The display name of --viewer.
213
+ --respondent <ref,…> With --cloud, the people you expect answers from, by your own key for each: each gets a personal link (mostra roster).
213
214
  --request-id <id> Make a retried share return the same share instead of opening another.
214
215
 
215
216
  Global flags:
@@ -431,6 +432,113 @@ Example:
431
432
  mostra resume ./survey
432
433
  ```
433
434
 
435
+ ## mostra roster add
436
+
437
+ ```text
438
+ Name the people an artifact expects answers from; each gets a personal link that acts as them.
439
+
440
+ Usage:
441
+ mostra roster add <artifact> [<ref…>] [flags]
442
+
443
+ Arguments:
444
+ <artifact> The artifact: its source path or its ID.
445
+ <ref> Each respondent, by your own stable key for them (an email, an account ID).
446
+
447
+ Flags:
448
+ --name <name> The display name of the one respondent given.
449
+ --email <address> Where a remote server that sends invitations writes to the one respondent given.
450
+ --file <path> Read respondents from a JSON file: [{ ref, name?, email? }].
451
+ --stdin Read respondents as JSON from stdin.
452
+ --scope <a,b> The personal links' scopes: view, draft, submit, review, signal, action:*. Default: all.
453
+ --ttl <d> How long the personal links work, such as 7d. Default: no limit.
454
+ --request-id <id> Make a retry return the first attempt's links.
455
+
456
+ Global flags:
457
+ --json Print one JSON envelope on stdout (NDJSON for streams).
458
+ --home <dir> Use this Mostra home instead of MOSTRA_HOME or the default.
459
+ --cwd <dir> Resolve relative paths from this directory.
460
+ --timeout <d> Give up on the instance after this long (exit 4), such as 30s or 5m.
461
+ --help Show this command's help; with --json, its definition.
462
+
463
+ Output: RosterAddResult (mostra docs cli)
464
+
465
+ Exit codes:
466
+ 0 success
467
+ 1 artifact failure (verify failed, publish refused, the artifact's state refused the request)
468
+ 2 usage error
469
+ 3 environment error (no runtime, browser or socket; the home; an unsupported platform)
470
+ 4 timeout (--timeout passed)
471
+
472
+ Example:
473
+ mostra roster add ./retro ada@example.com grace@example.com
474
+ ```
475
+
476
+ ## mostra roster get
477
+
478
+ ```text
479
+ Show who an artifact expects answers from and where each stands: not opened, drafting or submitted.
480
+
481
+ Usage:
482
+ mostra roster get <artifact>
483
+
484
+ Arguments:
485
+ <artifact> The artifact: its source path or its ID.
486
+
487
+ Global flags:
488
+ --json Print one JSON envelope on stdout (NDJSON for streams).
489
+ --home <dir> Use this Mostra home instead of MOSTRA_HOME or the default.
490
+ --cwd <dir> Resolve relative paths from this directory.
491
+ --timeout <d> Give up on the instance after this long (exit 4), such as 30s or 5m.
492
+ --help Show this command's help; with --json, its definition.
493
+
494
+ Output: Roster (mostra docs cli)
495
+
496
+ Exit codes:
497
+ 0 success
498
+ 1 artifact failure (verify failed, publish refused, the artifact's state refused the request)
499
+ 2 usage error
500
+ 3 environment error (no runtime, browser or socket; the home; an unsupported platform)
501
+ 4 timeout (--timeout passed)
502
+
503
+ Example:
504
+ mostra roster get ./retro
505
+ ```
506
+
507
+ ## mostra roster remove
508
+
509
+ ```text
510
+ Stop expecting answers from respondents; their links, drafts and submissions stay as they are.
511
+
512
+ Usage:
513
+ mostra roster remove <artifact> <ref…> [flags]
514
+
515
+ Arguments:
516
+ <artifact> The artifact: its source path or its ID.
517
+ <ref> Each respondent to remove, by their ref.
518
+
519
+ Flags:
520
+ --request-id <id> Make a retry return the first attempt's result.
521
+
522
+ Global flags:
523
+ --json Print one JSON envelope on stdout (NDJSON for streams).
524
+ --home <dir> Use this Mostra home instead of MOSTRA_HOME or the default.
525
+ --cwd <dir> Resolve relative paths from this directory.
526
+ --timeout <d> Give up on the instance after this long (exit 4), such as 30s or 5m.
527
+ --help Show this command's help; with --json, its definition.
528
+
529
+ Output: RosterRemoveResult (mostra docs cli)
530
+
531
+ Exit codes:
532
+ 0 success
533
+ 1 artifact failure (verify failed, publish refused, the artifact's state refused the request)
534
+ 2 usage error
535
+ 3 environment error (no runtime, browser or socket; the home; an unsupported platform)
536
+ 4 timeout (--timeout passed)
537
+
538
+ Example:
539
+ mostra roster remove ./retro grace@example.com
540
+ ```
541
+
434
542
  ## mostra wait
435
543
 
436
544
  ```text
@@ -443,7 +551,7 @@ Arguments:
443
551
  <artifact> The artifact: its source path or its ID.
444
552
 
445
553
  Flags:
446
- --until <condition> submitted, signal:<name>, state:<fieldId> or event:<type>.
554
+ --until <condition> submitted, submitted:all (every expected respondent), submitted:<N>, signal:<name>, state:<fieldId> or event:<type>.
447
555
  --after <cursor> Wait for what comes after this cursor. Default: the latest publish.
448
556
  --timeout <d> Stop waiting after this long, with still_waiting and exit 5. Default: no limit.
449
557
 
@@ -479,6 +587,8 @@ Arguments:
479
587
 
480
588
  Flags:
481
589
  --submission <id> This submission instead of the latest.
590
+ --all Every submission, oldest first (a survey's, a team's), instead of the latest.
591
+ --after <cursor> With --all, only submissions after this cursor.
482
592
  --format <format> Markdown or JSON. Default: Markdown, or JSON with --json. (md, json)
483
593
 
484
594
  Global flags:
@@ -1194,8 +1194,8 @@
1194
1194
  "phase": "host",
1195
1195
  "title": "Too many runs wait for the owner",
1196
1196
  "hint": "Wait for the owner to come back and work through its queue, then press again.",
1197
- "explanation": "The artifact's owner instance is offline and as many runs as the server allows already wait for it, so this one was refused before anything was recorded. Runs already waiting keep their place.",
1198
- "fix": "Bring the owner instance back online: waiting runs then go out in the order they were made. The cap is the server's `relay.waitingRunsPerArtifact` setting."
1197
+ "explanation": "The artifact's owner instance is offline and as many runs as the server allows already wait for it, or the server's operator allows no more waiting runs for this account now (its `limits` port, `run.wait`, whose message is the operator's own), so this one was refused before anything was recorded. Runs already waiting keep their place.",
1198
+ "fix": "Bring the owner instance back online: waiting runs then go out in the order they were made. The cap is the server's `relay.waitingRunsPerArtifact` setting, or the operator's limit its message names; its `Retry-After`, when present, says when to try again."
1199
1199
  },
1200
1200
  {
1201
1201
  "code": "MOSTRA_REMOTE_RATE_LIMITED",
@@ -1458,6 +1458,33 @@
1458
1458
  "explanation": "The page called something that needs Mostra's server, such as a server function, and this delivery target doesn't provide it: a static export, a file opened from disk, or a runtime without server support. The page keeps working without it.",
1459
1459
  "fix": "Open the artifact through its Mostra link, where server functions, submissions and live data are available. In a static export, handle the error so the page explains what isn't available."
1460
1460
  },
1461
+ {
1462
+ "code": "MOSTRA_TEAM_PRESENCE_RATE_LIMITED",
1463
+ "severity": "error",
1464
+ "phase": "hygiene",
1465
+ "title": "Presence updates too fast",
1466
+ "hint": "Send presence at most 10 times a second; usePresence does this for you.",
1467
+ "explanation": "A page shares its viewer's cursor and selection through `POST /_mostra/v/<rev>/presence`. Each view may send 20 updates a second; past that the gateway answers 429 with `Retry-After`. Presence is never stored, so nothing is lost: the next update replaces the last one.",
1468
+ "fix": "Use `usePresence` from `@mostra/react`, which sends at most 10 updates a second, or throttle your own calls to the route."
1469
+ },
1470
+ {
1471
+ "code": "MOSTRA_TEAM_ROSTER_POLICY",
1472
+ "severity": "error",
1473
+ "phase": "host",
1474
+ "title": "This artifact's policy can't wait for every respondent",
1475
+ "hint": "Publish with the submission policy once per-viewer or epochs, then wait again; or wait for submitted.",
1476
+ "explanation": "`submitted:all` waits until every expected respondent has submitted, and `submitted:<N>` for N submissions. Both need a policy that takes a submission from each person: `once` with scope `per-viewer`, or `epochs`. Under `once` per-artifact the artifact takes one submission in all, so neither can be met beyond the first, and Mostra refuses the wait instead of letting it run forever.",
1477
+ "fix": "Publish again with `mostra publish <path> --policy once-per-viewer` (or `--policy epochs`), or wait for `submitted`."
1478
+ },
1479
+ {
1480
+ "code": "MOSTRA_TEAM_ROSTER_TOO_LARGE",
1481
+ "severity": "error",
1482
+ "phase": "host",
1483
+ "title": "Roster larger than 1,000 respondents",
1484
+ "hint": "Name at most 1,000 expected respondents; share one link for everyone else instead.",
1485
+ "explanation": "A roster lists the people an artifact expects answers from, each with a personal link and a status. It holds at most 1,000 of them. Nothing was added: the roster is as it was.",
1486
+ "fix": "Remove respondents you no longer expect (`mostra roster remove`), or, for a page many people answer, share one link and wait for `submitted:<N>` instead."
1487
+ },
1461
1488
  {
1462
1489
  "code": "MOSTRA_TYPE_ERROR",
1463
1490
  "severity": "error",
@@ -12,11 +12,11 @@ Too many runs wait for the owner. Severity: error. Phase: host.
12
12
 
13
13
  ## What it means
14
14
 
15
- The artifact's owner instance is offline and as many runs as the server allows already wait for it, so this one was refused before anything was recorded. Runs already waiting keep their place.
15
+ The artifact's owner instance is offline and as many runs as the server allows already wait for it, or the server's operator allows no more waiting runs for this account now (its `limits` port, `run.wait`, whose message is the operator's own), so this one was refused before anything was recorded. Runs already waiting keep their place.
16
16
 
17
17
  ## How to fix it
18
18
 
19
- Bring the owner instance back online: waiting runs then go out in the order they were made. The cap is the server's `relay.waitingRunsPerArtifact` setting.
19
+ Bring the owner instance back online: waiting runs then go out in the order they were made. The cap is the server's `relay.waitingRunsPerArtifact` setting, or the operator's limit its message names; its `Retry-After`, when present, says when to try again.
20
20
 
21
21
  ## Hint
22
22
 
@@ -0,0 +1,23 @@
1
+ ---
2
+ code: MOSTRA_TEAM_PRESENCE_RATE_LIMITED
3
+ severity: error
4
+ phase: hygiene
5
+ ---
6
+
7
+ <!-- Generated from packages/protocol/src/diagnostics/codes by `node tools/docs/diagnostics.ts write`. Edit the area file, not this page. -->
8
+
9
+ # MOSTRA_TEAM_PRESENCE_RATE_LIMITED
10
+
11
+ Presence updates too fast. Severity: error. Phase: hygiene.
12
+
13
+ ## What it means
14
+
15
+ A page shares its viewer's cursor and selection through `POST /_mostra/v/<rev>/presence`. Each view may send 20 updates a second; past that the gateway answers 429 with `Retry-After`. Presence is never stored, so nothing is lost: the next update replaces the last one.
16
+
17
+ ## How to fix it
18
+
19
+ Use `usePresence` from `@mostra/react`, which sends at most 10 updates a second, or throttle your own calls to the route.
20
+
21
+ ## Hint
22
+
23
+ Send presence at most 10 times a second; usePresence does this for you.
@@ -0,0 +1,23 @@
1
+ ---
2
+ code: MOSTRA_TEAM_ROSTER_POLICY
3
+ severity: error
4
+ phase: host
5
+ ---
6
+
7
+ <!-- Generated from packages/protocol/src/diagnostics/codes by `node tools/docs/diagnostics.ts write`. Edit the area file, not this page. -->
8
+
9
+ # MOSTRA_TEAM_ROSTER_POLICY
10
+
11
+ This artifact's policy can't wait for every respondent. Severity: error. Phase: host.
12
+
13
+ ## What it means
14
+
15
+ `submitted:all` waits until every expected respondent has submitted, and `submitted:<N>` for N submissions. Both need a policy that takes a submission from each person: `once` with scope `per-viewer`, or `epochs`. Under `once` per-artifact the artifact takes one submission in all, so neither can be met beyond the first, and Mostra refuses the wait instead of letting it run forever.
16
+
17
+ ## How to fix it
18
+
19
+ Publish again with `mostra publish <path> --policy once-per-viewer` (or `--policy epochs`), or wait for `submitted`.
20
+
21
+ ## Hint
22
+
23
+ Publish with the submission policy once per-viewer or epochs, then wait again; or wait for submitted.
@@ -0,0 +1,23 @@
1
+ ---
2
+ code: MOSTRA_TEAM_ROSTER_TOO_LARGE
3
+ severity: error
4
+ phase: host
5
+ ---
6
+
7
+ <!-- Generated from packages/protocol/src/diagnostics/codes by `node tools/docs/diagnostics.ts write`. Edit the area file, not this page. -->
8
+
9
+ # MOSTRA_TEAM_ROSTER_TOO_LARGE
10
+
11
+ Roster larger than 1,000 respondents. Severity: error. Phase: host.
12
+
13
+ ## What it means
14
+
15
+ A roster lists the people an artifact expects answers from, each with a personal link and a status. It holds at most 1,000 of them. Nothing was added: the roster is as it was.
16
+
17
+ ## How to fix it
18
+
19
+ Remove respondents you no longer expect (`mostra roster remove`), or, for a page many people answer, share one link and wait for `submitted:<N>` instead.
20
+
21
+ ## Hint
22
+
23
+ Name at most 1,000 expected respondents; share one link for everyone else instead.
@@ -39,7 +39,7 @@ The server reads a JSON file (`--config`) and `MOSTRA_SERVER_<KEY>` variables. A
39
39
  | `apiOrigin` | The API origin, `https:` |
40
40
  | `domains.active`, `domains.spares` | The user-content domain new links use, and older ones that issued links keep working on. To move off a domain, make a spare active and restart the server |
41
41
  | `trustedProxies` | Addresses or CIDR ranges whose `X-Forwarded-For` the server believes. It reads the header from the right and takes the first address that isn't a trusted proxy. Rate limits count IPv6 clients per /64 (`rateLimits.ipv6Prefix`) |
42
- | `identityProviders` | How people sign in: `github` (an OAuth app), `oidc` (any OpenID Connect provider: `issuer`, `clientId`, `clientSecretFile`) or `development` (trusts any typed name; for tests only, never on a public server) |
42
+ | `identityProviders` | How people sign in: `github` (an OAuth app), `oidc` (any OpenID Connect provider: `issuer`, `clientId`, `clientSecretFile`) or `development` (trusts any typed name; for tests only, never on a public server). An `oidc` entry's `claims` names up to 8 of its ID token's claims (such as `hd`, a Google Workspace account's domain) that an operator module then reads in the sign-in's `facts`. A page's sender line says the name was verified with the provider's `label`, as recorded when the person signed in, so renaming or removing a provider later leaves names already verified as they were |
43
43
  | `rateLimits` | Rates as `{ "count", "per" }`: `perIp.submissions` and `perLink.submissions` for answers, `perLink.relayedRuns` for actions, and `perIp.requests` for every request an address sends (a health check aside). Past a rate the answer is 429 with `Retry-After`; a page says to try again shortly and keeps the draft. A key left out is no limit |
44
44
  | `relay`, `homes`, `ledger` | The relay's waiting-run cap and drain rate, how long an idle hosted home stays open, and the ledger's WAL checkpoint (`0` for a backup replicator) |
45
45
  | `operator` | The path of an operator module, which adds limits, metering, accounts and abuse handling through the operator ports (`@mostra/protocol/operator`). Without one, every port keeps its no-op default |