@mostra/runtime 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mostra/runtime",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "description": "The Mostra runtime: the supervisor that owns a home, its ledger, its child processes and the host protocol server (mostra-runtime host|daemon).",
5
5
  "license": "Apache-2.0",
6
6
  "author": "The Mostra Authors",
@@ -36,7 +36,7 @@
36
36
  "dependencies": {
37
37
  "@hono/node-server": "2.1.5",
38
38
  "@mdx-js/mdx": "3.1.1",
39
- "@mostra/protocol": "0.7.0",
39
+ "@mostra/protocol": "0.9.0",
40
40
  "@tailwindcss/vite": "4.3.3",
41
41
  "@vitejs/plugin-react": "6.1.2",
42
42
  "better-sqlite3": "13.0.3",
@@ -54,11 +54,11 @@
54
54
  "zod": "4.6.7"
55
55
  },
56
56
  "devDependencies": {
57
- "@mostra/shell": "0.7.0",
57
+ "@mostra/shell": "0.9.0",
58
58
  "@mostra/tools": "0.0.0",
59
- "@mostra/verify": "0.7.0",
59
+ "@mostra/verify": "0.9.0",
60
60
  "@mostra/warm": "0.0.0",
61
- "@mostra/worker": "0.7.0",
61
+ "@mostra/worker": "0.9.0",
62
62
  "@types/better-sqlite3": "9.6.0",
63
63
  "@types/node": "24.19.2",
64
64
  "@types/semver": "7.8.0",
@@ -6,6 +6,7 @@
6
6
  import type { ArtifactLink, ArtifactManifest, DeliveryStatus, Results } from "@mostra/protocol";
7
7
  import { createDiagnostic, RpcError } from "@mostra/protocol";
8
8
  import type { LedgerDb } from "../ledger/index.ts";
9
+ import { storedPolicy } from "./policy.ts";
9
10
  import {
10
11
  deliveriesOf,
11
12
  overallDelivery,
@@ -89,6 +90,19 @@ export function submissionFor(
89
90
  artifactId,
90
91
  );
91
92
  if (!row) {
93
+ if (submissionId === undefined) {
94
+ // A page whose policy in force is `none` never gets one (D63): say where its answers are,
95
+ // since waiting for a submission is refused too (#115).
96
+ const artifact = db.get<{ policy_json: string | null }>(
97
+ "SELECT policy_json FROM artifact WHERE id = ?",
98
+ artifactId,
99
+ );
100
+ if (artifact && storedPolicy(artifact.policy_json).policy === "none") {
101
+ throw notFound(
102
+ `The artifact ${artifactId} takes no submissions (its submission policy is none): what its viewers do is in its shared state and its signals, so read its state, or wait for one of its signals (signal:<name>), whose event carries the payload the page sent.`,
103
+ );
104
+ }
105
+ }
92
106
  throw notFound(
93
107
  submissionId === undefined
94
108
  ? `The artifact ${artifactId} has no submission yet.`
package/src/live/index.ts CHANGED
@@ -275,7 +275,13 @@ export function createLive(options: LiveOptions): Live {
275
275
  try {
276
276
  const handle = await pool.acquire(version);
277
277
  described.set(versionId, handle.started.live);
278
- if (!handle.started.live.some((source) => source.key === key)) return;
278
+ const source = handle.started.live.find((info) => info.key === key);
279
+ if (!source) return;
280
+ // A page that read it before its worker said may be waiting for a first load that won't
281
+ // come: a source that only streams. (A worker that doesn't say counts as loading, as
282
+ // `stateOf` reads it.)
283
+ if (source.load === false)
284
+ bus.publishLive(artifactId, { kind: "live", live: { key, awaiting: false } });
279
285
  // Known before it starts: its first value can arrive before the start's answer.
280
286
  running.set(id, { artifactId, key, versionId, handle });
281
287
  try {
@@ -379,6 +385,12 @@ export function createLive(options: LiveOptions): Live {
379
385
  key,
380
386
  );
381
387
  const failure = failures.get(keyOf(artifactId, key));
388
+ // Its first load is on its way when the latest version defines it and, once its worker said,
389
+ // has a `load` (a stream's first value may never come). A key only pushes write isn't.
390
+ const latest = options.latest(artifactId);
391
+ const producing =
392
+ latest?.sources.some((source) => source.key === key) === true &&
393
+ (described.get(latest.versionId)?.find((source) => source.key === key)?.load ?? true);
382
394
  const ring =
383
395
  window === undefined
384
396
  ? undefined
@@ -406,6 +418,7 @@ export function createLive(options: LiveOptions): Live {
406
418
  : {}),
407
419
  ...(ring ? { ring } : {}),
408
420
  ...(failure ? { error: failure } : {}),
421
+ ...(!row && !failure && producing ? { awaiting: true } : {}),
409
422
  };
410
423
  };
411
424
 
@@ -82,6 +82,7 @@ import {
82
82
  versionIdFor,
83
83
  } from "./digest.ts";
84
84
  import { extractManifest } from "./manifest.ts";
85
+ import { SCAFFOLD_PATHS, type ScaffoldInput, scaffoldFiles } from "./scaffold.ts";
85
86
  import {
86
87
  copySnapshot,
87
88
  listSource,
@@ -249,47 +250,55 @@ async function archiveSnapshot(
249
250
  return true;
250
251
  }
251
252
 
252
- /** The entry `artifact/create` writes: a manifest with the generated `id` and a minimal page. */
253
- function scaffold(artifactId: string, title: string): string {
254
- return [
255
- 'import { defineArtifact } from "@mostra/react";',
256
- "",
257
- "export const artifact = defineArtifact({",
258
- ` id: ${JSON.stringify(artifactId)},`,
259
- ` title: ${JSON.stringify(title)},`,
260
- "});",
261
- "",
262
- "export default function Page() {",
263
- " return (",
264
- ' <main className="mx-auto max-w-2xl p-8">',
265
- ' <h1 className="text-2xl font-semibold">{artifact.title}</h1>',
266
- " </main>",
267
- " );",
268
- "}",
269
- "",
270
- ].join("\n");
253
+ /**
254
+ * What `artifact/create` records for its `requestId`: its result, and the exact text of each file
255
+ * it writes, so a retry, by this runtime or a newer one, completes exactly the bytes the first
256
+ * attempt began (WP-14's GPT and Opus reviews).
257
+ */
258
+ interface CreateRecord {
259
+ readonly result: ArtifactCreateResult;
260
+ readonly scaffold: { readonly files: Readonly<Record<string, string>> };
261
+ }
262
+
263
+ /** The text of each of `paths` (of {@link scaffoldFiles}) for `input`. */
264
+ function scaffoldText(paths: readonly string[], input: ScaffoldInput): Record<string, string> {
265
+ const all = scaffoldFiles(input);
266
+ return Object.fromEntries(
267
+ paths.flatMap((path) => {
268
+ const text = all.get(path);
269
+ return text === undefined ? [] : [[path, text]];
270
+ }),
271
+ );
271
272
  }
272
273
 
273
274
  /**
274
- * Writes `artifact/create`'s entry into `dir`, completing an interrupted write: an existing file
275
- * that is the expected text or a prefix of it (a write cut short) ends as the expected text, and
276
- * anything else the author has written since is left alone.
275
+ * Writes `artifact/create`'s files (`files`, path to text) into `dir`, completing an interrupted
276
+ * write: an existing file whose bytes are the expected text's or a prefix of them (a write cut
277
+ * short, even inside a character) ends as the expected text, and anything else the author has
278
+ * written since is left alone.
277
279
  */
278
- async function writeScaffold(dir: string, artifactId: string, title: string): Promise<void> {
279
- const expected = scaffold(artifactId, title);
280
- const file = join(dir, "index.tsx");
280
+ async function writeScaffold(dir: string, files: Readonly<Record<string, string>>): Promise<void> {
281
281
  await mkdir(dir, { recursive: true });
282
- let current: string | undefined;
283
- try {
284
- current = await readFile(file, "utf8");
285
- } catch {
286
- current = undefined;
282
+ let wrote = false;
283
+ for (const [path, text] of Object.entries(files)) {
284
+ const expected = Buffer.from(text, "utf8");
285
+ const file = join(dir, path);
286
+ let current: Buffer | undefined;
287
+ try {
288
+ current = await readFile(file);
289
+ } catch {
290
+ current = undefined;
291
+ }
292
+ if (current !== undefined) {
293
+ const prefix =
294
+ current.length <= expected.length && expected.subarray(0, current.length).equals(current);
295
+ if (!prefix || current.length === expected.length) continue;
296
+ }
297
+ await writeFile(file, expected);
298
+ fsyncPath(file);
299
+ wrote = true;
287
300
  }
288
- if (current !== undefined && !expected.startsWith(current)) return;
289
- if (current === expected) return;
290
- await writeFile(file, expected);
291
- fsyncPath(file);
292
- fsyncPath(dir, true);
301
+ if (wrote) fsyncPath(dir, true);
293
302
  }
294
303
 
295
304
  /**
@@ -878,14 +887,32 @@ export function createPublisher(options: PublisherOptions): Publisher {
878
887
  }
879
888
 
880
889
  async function create(params: ArtifactCreateParams): Promise<ArtifactCreateResult> {
881
- // A retried request completes what the first attempt recorded (H-03): the entry is written
882
- // only after the result is durable, so a crash in between leaves something to finish.
890
+ // A retried request completes what the first attempt recorded (H-03): the files are written
891
+ // only after the result is durable, so a crash in between leaves something to finish. The
892
+ // record also keeps the files' exact text, so a retry by a newer runtime completes exactly
893
+ // what the first attempt began (WP-14's GPT and Opus reviews); the client gets the result
894
+ // alone.
883
895
  const key = requestKey("artifact/create", params);
884
896
  if (key !== undefined) {
885
- const result = ledger.read((db) => recordedResult<ArtifactCreateResult>(db, key));
886
- if (result !== undefined) {
887
- await writeScaffold(result.dir, result.artifactId, params.title ?? basename(result.dir));
888
- return result;
897
+ const recorded = ledger.read((db) =>
898
+ recordedResult<CreateRecord | ArtifactCreateResult>(db, key),
899
+ );
900
+ if (recorded !== undefined) {
901
+ if ("result" in recorded) {
902
+ await writeScaffold(recorded.result.dir, recorded.scaffold.files);
903
+ return recorded.result;
904
+ }
905
+ // A record from before WP-14 is the result itself, whose one file, the entry, names no
906
+ // release: it is written as this runtime writes it.
907
+ await writeScaffold(
908
+ recorded.dir,
909
+ scaffoldText(recorded.files, {
910
+ artifactId: recorded.artifactId,
911
+ title: params.title ?? basename(recorded.dir),
912
+ version: options.runtimeVersion,
913
+ }),
914
+ );
915
+ return recorded;
889
916
  }
890
917
  }
891
918
  if (params.template !== undefined) {
@@ -910,11 +937,17 @@ export function createPublisher(options: PublisherOptions): Publisher {
910
937
  const result: ArtifactCreateResult = {
911
938
  artifactId: ArtifactId.create(),
912
939
  dir,
913
- files: ["index.tsx"],
940
+ files: [...SCAFFOLD_PATHS],
914
941
  };
915
- record(key, result);
942
+ const files = scaffoldText(result.files, {
943
+ artifactId: result.artifactId,
944
+ title: params.title ?? basename(dir),
945
+ version: options.runtimeVersion,
946
+ });
947
+ const recordedCreate: CreateRecord = { result, scaffold: { files } };
948
+ record(key, recordedCreate);
916
949
  faults.at("create:after-record");
917
- await writeScaffold(dir, result.artifactId, params.title ?? basename(dir));
950
+ await writeScaffold(dir, files);
918
951
  return result;
919
952
  }
920
953
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * What `artifact/create` (`mostra new`) writes into an empty directory: the entry with the
3
+ * artifact's generated `id`, an `AGENTS.md` for the agent that edits it next (AX-06, WP-14), and a
4
+ * `CLAUDE.md` that imports it, since Claude Code loads a subdirectory's `CLAUDE.md` when it works
5
+ * there but not its `AGENTS.md`. Every file is source like any other: it is in the version's
6
+ * snapshot and its digest.
7
+ */
8
+
9
+ /** What a new artifact's files are made from. */
10
+ export interface ScaffoldInput {
11
+ readonly artifactId: string;
12
+ readonly title: string;
13
+ /** This runtime's release, which `npx -y @mostra/cli@<version>` pins. */
14
+ readonly version: string;
15
+ }
16
+
17
+ /** The files a new artifact gets, in the order `artifact/create` reports them. */
18
+ export const SCAFFOLD_PATHS: readonly string[] = ["index.tsx", "AGENTS.md", "CLAUDE.md"];
19
+
20
+ function entry({ artifactId, title }: ScaffoldInput): string {
21
+ return [
22
+ 'import { defineArtifact } from "@mostra/react";',
23
+ "",
24
+ "export const artifact = defineArtifact({",
25
+ ` id: ${JSON.stringify(artifactId)},`,
26
+ ` title: ${JSON.stringify(title)},`,
27
+ "});",
28
+ "",
29
+ "export default function Page() {",
30
+ " return (",
31
+ ' <main className="mx-auto max-w-2xl p-8">',
32
+ ' <h1 className="text-2xl font-semibold">{artifact.title}</h1>',
33
+ " </main>",
34
+ " );",
35
+ "}",
36
+ "",
37
+ ].join("\n");
38
+ }
39
+
40
+ /** A Markdown heading's text: one line, nothing that reads as Markdown syntax at its start. */
41
+ function headingText(title: string): string {
42
+ const line = title.replace(/\s+/g, " ").trim();
43
+ return line === "" ? "Mostra artifact" : line;
44
+ }
45
+
46
+ function agents({ title, version }: ScaffoldInput): string {
47
+ return [
48
+ `# ${headingText(title)}`,
49
+ "",
50
+ "This directory is a Mostra artifact: a page people open from a private link, read, answer and act on. Their answers come back to you as results.",
51
+ "",
52
+ "## Work on it",
53
+ "",
54
+ "1. Edit `index.tsx`: ordinary React 19 and TypeScript with Tailwind CSS 4, with no `package.json` or build configuration.",
55
+ "2. Run `mostra verify .` until it reports `pass`, and look at both screenshots it lists (`--screenshots always` lists them every time).",
56
+ "3. Run `mostra publish .`. It prints the private link: whoever holds it can use the page.",
57
+ "4. Give the link to the person, saying who is asking and why. Then run `mostra wait . --until submitted` and `mostra results .`.",
58
+ "",
59
+ `Where \`mostra\` isn't installed, run \`npx -y @mostra/cli@${version}\` in its place.`,
60
+ "",
61
+ "## Keep in mind",
62
+ "",
63
+ '- Every answer is a field with an ID that stays the same on every render and in every version: `useField("budget", 0, { label: "Budget" })`, or a template on your data\'s own ID for a list. Answers carry over to a new version by ID.',
64
+ "- Keep the `id` in `defineArtifact`: it is this artifact's identity. Manifest values are literals.",
65
+ '- Code that must run on this machine (send, save, call an API) goes in a module that starts with `"use server"`; live data in `live.ts`; static files in `public/`.',
66
+ "- Imports stay inside this directory, or name an npm package.",
67
+ "",
68
+ "## More",
69
+ "",
70
+ "`mostra docs guide` is the full guide to writing artifacts, and `mostra docs <CODE>` explains any diagnostic. The same guide is the Mostra Agent Skill: `npx skills add mostra-dev/mostra`.",
71
+ "",
72
+ ].join("\n");
73
+ }
74
+
75
+ /** The files of a new artifact, by path. */
76
+ export function scaffoldFiles(input: ScaffoldInput): Map<string, string> {
77
+ return new Map([
78
+ ["index.tsx", entry(input)],
79
+ ["AGENTS.md", agents(input)],
80
+ ["CLAUDE.md", "@AGENTS.md\n"],
81
+ ]);
82
+ }