Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
ST9b: any length. src/state.ts: stateAt (what the systems hold just before a beat: knows, open, suspense, levels, tension, unpaid setups, unsettled wants, events ahead) and windowAt (that state, the events still usable and the beats around one, as story lines). The generator now writes a beat from its window; the extractor reads a script six beats at a time with what earlier steps found (models/lib.ts chunkSteps, merge exact on all 1,571 corpus stories), chained end to end by story_models.py chain through models/known.ts.
shinyobjectzdb596714ab72
diff --git a/sdk/story/models/known.ts b/sdk/story/models/known.tsnew file mode 100644index 00000000..21b30376--- /dev/null+++ b/sdk/story/models/known.ts@@ -0,0 +1,23 @@+// The chained extractor's helper (story_models.py chain): one JSON request a line on stdin, one JSON answer a line on+// stdout, so the story lines are written by raea/story alone.+// {"prompt": {"answers": [step answers so far], "script": "..."}} -> {"prompt": "KNOWN ... SCRIPT ..."}+// {"merge": [step answers]} -> {"story": {...}}+import { knownPrompt, mergeSteps } from "./lib.ts";++const dec = new TextDecoder();+let buf = "";+for await (const chunk of Bun.stdin.stream()) {+ buf += dec.decode(chunk);+ let i;+ while ((i = buf.indexOf("\n")) >= 0) {+ const line = buf.slice(0, i); buf = buf.slice(i + 1);+ if (!line.trim()) continue;+ let out: unknown;+ try {+ const q = JSON.parse(line);+ if (q.prompt) { const m = mergeSteps(q.prompt.answers); out = { prompt: knownPrompt({ values: m.values, facts: m.facts, agents: m.agents, world: m.world }, q.prompt.script) }; }+ else out = { story: mergeSteps(q.merge) };+ } catch (e) { out = { error: String(e) }; }+ process.stdout.write(JSON.stringify(out) + "\n");+ }+}diff --git a/sdk/story/models/lib.ts b/sdk/story/models/lib.tsindex 8d83bc96..9bcfa40a 100644--- a/sdk/story/models/lib.ts+++ b/sdk/story/models/lib.ts@@ -1,6 +1,6 @@// What the corpus rows (rows.ts) and a held-out story's rows (validate.ts) share: a telling as prose, the story as the// extractor answers it, and exact labels for a telling a viewer could see.-import { checkStory, fromData, type AnyStory } from "../src/index.ts";+import { checkStory, fromData, toLines, type AnyStory } from "../src/index.ts";type J = Record<string, any>;@@ -39,3 +39,96 @@ export const criticSchema = {type: "object", additionalProperties: false, required: ["breaks"],properties: { breaks: { type: "array", items: { type: "object", additionalProperties: false, required: ["beat", "check", "level"], properties: { beat: { anyOf: [{ type: "integer", minimum: 1 }, { type: "null" }] }, check: { type: "string", enum: CHECKS }, level: { type: "string", enum: ["error", "warn"] } } } } },};++// ---- the windowed extractor (docs/story.md, "Any length") ----+// A script read a chunk of beats at a time. Each step is handed what earlier steps found (KNOWN, as story lines: the+// values, facts, agents and events so far) and this chunk's prose, and answers only what's new (keys first met here)+// and this chunk's beats. A chained run merges the steps into one story; nothing a step reads grows with the telling+// but KNOWN, which grows with the world.+export const CHUNK = 6;++/** Which chunk introduces each key: an event where it's first shown (a cause no later than its effect; one never shown+ * with the next shown event after it in story order), an agent or fact with the first event or beat to use it. */+export function introductions(s: J, W = CHUNK): { events: Record<string, number>; agents: Record<string, number>; facts: Record<string, number>; values: Record<string, number>; n: number } {+ const beats: J[] = s.tellings.main;+ const n = Math.max(1, Math.ceil(beats.length / W));+ const keys = Object.keys(s.world);+ const ev: Record<string, number> = {};+ beats.forEach((b, i) => { for (const e of [].concat(b.shows ?? [])) ev[e] ??= Math.floor(i / W); });+ for (let i = keys.length - 1; i >= 0; i--) if (ev[keys[i]] === undefined) ev[keys[i]] = keys.slice(i + 1).map((k) => ev[k]).find((c) => c !== undefined) ?? n - 1;+ for (let pass = 0; pass < keys.length; pass++) {+ let moved = false;+ for (const k of keys) for (const c of [].concat(s.world[k].because ?? [])) if (ev[c] !== undefined && ev[c] > ev[k]) { ev[c] = ev[k]; moved = true; }+ if (!moved) break;+ }+ const ag: Record<string, number> = {}, fa: Record<string, number> = {}, va: Record<string, number> = {};+ const at = (m: Record<string, number>, k: string, c: number) => { if (m[k] === undefined || c < m[k]) m[k] = c; };+ for (const k of keys) {+ const e = s.world[k], c = ev[k];+ for (const a of [e.who, ...[].concat(e.with ?? []), ...Object.keys(e.ends ?? {})]) at(ag, a, c);+ for (const f of ["needs", "sets", "unsets", "learns", "proof"]) for (const x of [].concat(e[f] ?? [])) at(fa, x, c);+ for (const v of Object.keys(e.turns ?? {})) at(va, v, c);+ }+ beats.forEach((b, i) => {+ const c = Math.floor(i / W);+ for (const f of ["reveals", "hides", "asks"]) for (const x of [].concat(b[f] ?? [])) at(fa, x, c);+ for (const l of b.says ?? []) if (l.who !== "narrator") at(ag, l.who, c);+ });+ for (const [a, x] of Object.entries(s.agents as J)) { at(ag, a, n - 1); for (const f of [].concat(x.believes ?? [])) at(fa, f, ag[a]); }+ // a fact or value nothing uses, and the idea's value (the film is about it from the start), come in the first chunk+ for (const f of Object.keys(s.facts ?? {})) fa[f] ??= 0;+ for (const v of Object.keys(s.values)) va[v] ??= 0;+ if (s.idea?.value) va[s.idea.value] = 0;+ return { events: ev, agents: ag, facts: fa, values: va, n };+}++const pick = (o: J, ks: string[]) => Object.fromEntries(Object.keys(o ?? {}).filter((k) => ks.includes(k)).map((k) => [k, o[k]]));++/** One chunk's step: what's known before it (as data), its prose, and its answer. */+export function chunkSteps(s: J, W = CHUNK): { known: J; prompt: string; answer: J; from: number }[] {+ const intro = introductions(s, W);+ const beats: J[] = s.tellings.main;+ const b = bare(s);+ const sel = (m: Record<string, number>, test: (c: number) => boolean) => Object.keys(m).filter((k) => test(m[k]));+ return Array.from({ length: intro.n }, (_, j) => {+ const before = (c: number) => c < j, here = (c: number) => c === j;+ const known = { values: pick(b.values, sel(intro.values, before)), facts: pick(b.facts, sel(intro.facts, before)), agents: pick(b.agents, sel(intro.agents, before)), world: pick(b.world, sel(intro.events, before)) };+ const answer: J = {+ ...(j === 0 && b.title ? { title: b.title } : {}),+ ...(j === 0 && b.idea ? { idea: b.idea } : {}),+ values: pick(b.values, sel(intro.values, here)), facts: pick(b.facts, sel(intro.facts, here)),+ agents: pick(b.agents, sel(intro.agents, here)), world: pick(b.world, sel(intro.events, here)),+ beats: b.tellings.main.slice(j * W, (j + 1) * W),+ };+ const chunk = beats.slice(j * W, (j + 1) * W);+ const script = chunk.map((x, n) => prose([x]).replace(/^1\./, `${j * W + n + 1}.`)).join("\n");+ return { known, prompt: "", answer, from: j * W, script };+ }).map((st: J) => ({ ...st, prompt: knownPrompt(st.known, st.script) }));+}++/** The text a step reads: KNOWN as story lines, then the chunk's script. */+export function knownPrompt(known: J, script: string): string {+ const lines = Object.keys(known.values).length || Object.keys(known.agents).length || Object.keys(known.world).length+ ? toLines({ ...known, tellings: {} }).split("\n").filter((l) => !l.startsWith("TELLING")).join("\n")+ : "(nothing yet: this is the start)";+ return `KNOWN\n${lines}\nSCRIPT\n${script}`;+}++/** Steps merged into one story (a later step's key never overwrites an earlier one's). */+export function mergeSteps(answers: J[]): J {+ const out: J = { values: {}, facts: {}, agents: {}, world: {}, tellings: { main: [] } };+ for (const a of answers) {+ if (!a || typeof a !== "object") continue;+ if (a.title && !out.title) out.title = a.title;+ if (a.idea && !out.idea) out.idea = a.idea;+ for (const f of ["values", "facts", "agents", "world"]) for (const [k, v] of Object.entries((a[f] ?? {}) as J)) if (!(k in out[f])) out[f][k] = v;+ out.tellings.main.push(...(Array.isArray(a.beats) ? a.beats : []));+ }+ return out;+}++/** The step's answer shape: new keys and the chunk's beats. */+export function stepSchema(story: J): J {+ const p = story.properties;+ return { type: "object", additionalProperties: false, required: ["values", "facts", "agents", "world", "beats"], properties: { title: p.title, idea: p.idea, values: p.values, facts: p.facts, agents: p.agents, world: p.world, beats: p.tellings.additionalProperties } };+}diff --git a/sdk/story/models/rows.ts b/sdk/story/models/rows.tsindex df0cce4d..3cd27ee5 100644--- a/sdk/story/models/rows.ts+++ b/sdk/story/models/rows.ts@@ -2,7 +2,8 @@// by story (a story's rows are all in one of train, val and test), so a held-out number is on stories never seen.//// extract script prose -> the story as data (no onScreen or lines in the answer: they're the input)-// generate a story with one beat cut, and where -> that beat, as JSON under the story's own beat schema+// generate the story's state before a cut beat and the beats around it (src/state.ts windowAt) -> that beat, as+// JSON under the story's own beat schema// critic script prose -> where it breaks: [{beat, check, level}], labelled exactly by checkStory on the structure// behind the prose. Negatives are cuts a viewer could see: a beat cut, two beats swapped, a beat from// another story spliced in. A cut that breaks nothing is labelled clean, so the critic must read, not count.@@ -11,8 +12,8 @@import { mkdirSync, readFileSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";-import { beatSchema, rng, storySchema } from "../src/index.ts";-import { bare, breaks, criticSchema, name, prose } from "./lib.ts";+import { beatSchema, rng, storySchema, windowAt } from "../src/index.ts";+import { bare, breaks, CHUNK, chunkSteps, criticSchema, name, prose, stepSchema } from "./lib.ts";const arg = (k: string, d: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };const IN = arg("--in", join(homedir(), ".vd/story"));@@ -25,7 +26,7 @@ const stories: { i: number; s: J; premise: J }[] = readFileSync(join(IN, "storie/** The split a story falls in, by its index. */export const split = (i: number) => { const h = (Math.imul(i + 1, 2654435761) >>> 0) % 10; return h === 0 ? "test" : h === 1 ? "val" : "train"; };-const out: Record<string, Record<string, J[]>> = { extract: {}, generate: {}, critic: {} };+const out: Record<string, Record<string, J[]>> = { extract: {}, steps: {}, generate: {}, critic: {} };const push = (task: string, sp: string, row: J) => ((out[task][sp] ??= []).push(row));let clean = 0, broken = 0;@@ -38,14 +39,16 @@ for (const { i, s } of stories) {push("extract", sp, { i, kind: "script", prompt: p, answer: JSON.stringify(bare(s)) });// a transcript has the words alone: the same story from its lines, as a launch film's speech readsconst spoken = beats.flatMap((b) => (b.says ?? []).map((l: J) => `${name(l.who)}: ${l.says}`));+ // steps: the windowed extractor, a chunk at a time with what earlier chunks found (story_models.py chain runs it end to end)+ for (const [j, st] of chunkSteps(s).entries()) push("steps", sp, { i, at: j, of: Math.ceil(beats.length / CHUNK), prompt: st.prompt, script: st.script, answer: JSON.stringify(st.answer), gold: j === 0 ? JSON.stringify(bare(s)) : undefined });if (spoken.length >= 2) push("extract", sp, { i, kind: "lines", prompt: spoken.join("\n"), answer: JSON.stringify(bare(s)) });- // generate: each beat cut in turn on test and val; one at random on train (keeps the set balanced by story)- const cuts = sp === "train" ? [Math.floor(r() * beats.length)] : beats.map((_, k) => k);+ // generate, windowed: the story's state before the cut beat and the beats around it (windowAt), never the whole+ // telling, so a step reads the same amount at beat 5 or beat 500. Every beat on test and val; three at random on train.+ const cuts = sp === "train" ? [...new Set([0, 1, 2].map(() => Math.floor(r() * beats.length)))] : beats.map((_, k) => k);for (const k of cuts) {- const rest = beats.filter((_, n) => n !== k);- const partial = { ...s, tellings: { main: rest } };- push("generate", sp, { i, at: k, prompt: JSON.stringify({ story: partial, write: `the beat that goes at place ${k + 1} of ${beats.length}` }), answer: JSON.stringify(beats[k]), schema: beatSchema(s) });+ const partial = { ...s, tellings: { main: beats.filter((_, n) => n !== k) } };+ push("generate", sp, { i, at: k, prompt: windowAt(s, "main", k), story: partial, answer: JSON.stringify(beats[k]), schema: beatSchema(s) });}// critic: the story as written, then cuts a viewer could see@@ -71,7 +74,7 @@ for (const { i, s } of stories) {}}-writeFileSync(join(OUT, "schemas.json"), JSON.stringify({ extract: storySchema(), critic: criticSchema }, null, 1));+writeFileSync(join(OUT, "schemas.json"), JSON.stringify({ extract: storySchema(), steps: stepSchema(storySchema()), critic: criticSchema }, null, 1));for (const [task, sps] of Object.entries(out)) {mkdirSync(join(OUT, task), { recursive: true });for (const [sp, rows] of Object.entries(sps)) writeFileSync(join(OUT, task, `${sp}.jsonl`), rows.map((x) => JSON.stringify(x)).join("\n") + "\n");diff --git a/sdk/story/models/score.ts b/sdk/story/models/score.tsindex f96e57bb..a1d8fec1 100644--- a/sdk/story/models/score.ts+++ b/sdk/story/models/score.ts@@ -49,7 +49,7 @@ function scoreExtract(gold: J, pred: J | null): J {function scoreGenerate(row: J, pred: J | null): J {if (!pred) return { valid: 0, holds: 0, clean: 0, shows: 0 };- const { story: partial, write } = JSON.parse(row.prompt);+ const partial = row.story ?? JSON.parse(row.prompt).story;const at = row.at as number;const beats = [...partial.tellings.main.slice(0, at), pred, ...partial.tellings.main.slice(at)];const full = { ...partial, tellings: { main: beats } };@@ -59,7 +59,6 @@ function scoreGenerate(row: J, pred: J | null): J {const goldStory = fromData({ ...partial, tellings: { main: [...partial.tellings.main.slice(0, at), gold, ...partial.tellings.main.slice(at)] } }).story!;const holds = valid ? (errorsOf(story!).length ? 0 : 1) : 0;const warns = valid ? errorsOf(story!, "warn").length : 99, goldWarns = errorsOf(goldStory, "warn").length;- void write;return { valid, holds, clean: valid && warns <= goldWarns ? 1 : 0, shows: jac(new Set(pred.shows ?? []), new Set(gold.shows ?? [])) };}diff --git a/sdk/story/models/story_models.py b/sdk/story/models/story_models.pyindex c1938517..7025a739 100644--- a/sdk/story/models/story_models.py+++ b/sdk/story/models/story_models.py@@ -16,6 +16,7 @@ import jsonimport mathimport osimport re+import subprocessimport sysimport timeimport urllib.request@@ -31,10 +32,21 @@ SYSTEM = {"routine; turns move values -3..3) and tellings.main (the beats in the script's order, each {shows: [event ""keys], feel, reveals, hides, asks, setup, pays}). Keys are short camelCase words. Answer with JSON only."),+ "steps": (+ "You read a long film or game script a chunk at a time. You are given KNOWN, what earlier chunks found, in "+ "story lines (VALUE key: neg / pos, FACT key: text, AGENT key: want | need | lie | mask, EVENT key: who -- does "+ "| because | sets | turns), and the next SCRIPT chunk. Answer as raea/story JSON with only what's new in this "+ "chunk: values, facts, agents, world (events first met here, in the order they happen, each {who, does, because, "+ "sets, turns ...}; a cause can be a KNOWN event), and beats (this chunk's beats in order, each {shows: [event "+ "keys, KNOWN or new], feel, reveals, hides, asks, setup, pays}). Never repeat a KNOWN key. Keys are short "+ "camelCase words. Answer with JSON only."+ ),"generate": (- "You are given a story as raea/story JSON with one beat missing from tellings.main, and where it goes. Write "- "that beat as JSON: {shows: [event keys], feel, reveals, hides, asks, setup, pays, onScreen, says}. It must "- "follow from what's shown before it, turn a value or reveal something, and pay off what's still open. "+ "You are given a story in story lines: its values, facts, agents and the events it can still show; its STATE "+ "before the missing beat (value LEVELS, what the audience KNOWS, OPEN questions, SUSPENSE, UNPAID setups, "+ "UNSETTLED wants and needs, events AHEAD); the beats BEFORE it and AFTER it. Write the missing beat as JSON: "+ "{shows: [event keys], feel, reveals, hides, asks, setup, pays, onScreen, says}. It must follow from the beats "+ "before, lead into the beats after, turn a value or reveal something, and pay off what's still open. ""onScreen is what the viewer sees; says are the lines [{who, says}]. Answer with JSON only."),"critic": (@@ -230,6 +242,63 @@ def predict(a):print(f"predicted {n} -> {out}", flush=True)+def chain(a):+ """The windowed extractor end to end: each story's chunks in order, each step handed what the earlier steps found+ (as story lines, written by models/known.ts), then merged; written as extract predictions, scored by score.ts."""+ from mlx_lm import load, stream_generate+ from mlx_lm.sample_utils import make_sampler++ rd = rows_dir(a)+ schemas = json.load(open(rd / "schemas.json"))+ steps = read_jsonl(rd / "steps" / f"{a.split}.jsonl")+ stories = {}+ for r in steps:+ stories.setdefault(r["i"], []).append(r)+ ids = sorted(stories)[: a.limit or None]+ who = ("zero" if a.zero_shot else Path(a.adapter).name) + "-chain"+ model, tok = load(a.base, adapter_path=None if a.zero_shot else a.adapter)+ helper = subprocess.Popen(["bun", str(Path(__file__).parent / "known.ts")], stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True)++ def ask(q):+ helper.stdin.write(json.dumps(q) + "\n")+ helper.stdin.flush()+ return json.loads(helper.stdout.readline())++ out = rd / "extract" / f"pred-{who}-{a.split}.jsonl"+ done = {json.loads(l)["key"] for l in open(out)} if out.exists() else set()+ sampler = make_sampler(temp=0.0)+ t0 = time.time()+ with open(out, "a") as f:+ for n, i in enumerate(ids):+ key = f"{i}:script"+ if key in done:+ continue+ answers, t, bad = [], time.time(), 0+ for r in sorted(stories[i], key=lambda r: r["at"]):+ user = ask({"prompt": {"answers": answers, "script": r["script"]}})["prompt"]+ row = dict(r, prompt=user)+ if a.zero_shot:+ user = zero_shot_user("steps", row, schemas)+ proc = Constrained(tok, schema_for("steps", row, schemas))+ text = ""+ for resp in stream_generate(model, tok, prompt_text(tok, "steps", user), max_tokens=a.max_new, sampler=sampler, logits_processors=[proc]):+ text += resp.text+ if proc.m.is_stopped():+ break+ try:+ answers.append(json.loads(text))+ except json.JSONDecodeError:+ bad += 1+ answers.append({})+ story = ask({"merge": answers})["story"]+ f.write(json.dumps({"key": key, "i": i, "kind": "script", "pred": json.dumps(story), "steps": len(answers), "unparsed": bad, "secs": round(time.time() - t, 2)}) + "\n")+ f.flush()+ if (n + 1) % 5 == 0:+ print(f"{n + 1}/{len(ids)} stories in {time.time() - t0:.0f}s", flush=True)+ helper.stdin.close()+ print(f"chained {len(ids)} -> {out}", flush=True)++def frontier(a):rd = rows_dir(a)schemas = json.load(open(rd / "schemas.json"))@@ -269,7 +338,7 @@ def frontier(a):def export(a):import shutil- import subprocess+ad = Path(os.path.expanduser(a.adapter))fused, out = ad / "fused", ad / "onnx"@@ -317,8 +386,8 @@ def onnx_predict(a):def main():ap = argparse.ArgumentParser()- ap.add_argument("cmd", choices=["train", "predict", "frontier", "export", "onnx"])- ap.add_argument("task", choices=["extract", "generate", "critic"])+ ap.add_argument("cmd", choices=["train", "predict", "chain", "frontier", "export", "onnx"])+ ap.add_argument("task", choices=["extract", "steps", "generate", "critic"])ap.add_argument("--rows", default="~/.vd/story/rows")ap.add_argument("--base", default="Qwen/Qwen3-0.6B")ap.add_argument("--name", default="q06")@@ -335,7 +404,7 @@ def main():ap.add_argument("--zero-shot", dest="zero_shot", action="store_true")ap.add_argument("--model", default="anthropic/claude-sonnet-5.5")a = ap.parse_args()- {"train": train, "predict": predict, "frontier": frontier, "export": export, "onnx": onnx_predict}[a.cmd](a)+ {"train": train, "predict": predict, "chain": chain, "frontier": frontier, "export": export, "onnx": onnx_predict}[a.cmd](a)if __name__ == "__main__":diff --git a/sdk/story/models/validate.ts b/sdk/story/models/validate.tsindex 0e62ae6a..b3b0bb1d 100644--- a/sdk/story/models/validate.ts+++ b/sdk/story/models/validate.ts@@ -11,8 +11,8 @@import { copyFileSync, existsSync, mkdirSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { basename, join, resolve } from "node:path";-import { beatSchema, checkStory, LENSES, readThrough, toData, type AnyStory } from "../src/index.ts";-import { bare, breaks, prose } from "./lib.ts";+import { beatSchema, checkStory, LENSES, readThrough, toData, windowAt, type AnyStory } from "../src/index.ts";+import { bare, breaks, CHUNK, chunkSteps, prose } from "./lib.ts";type J = Record<string, any>;const arg = (k: string, d?: string) => { const i = process.argv.indexOf(k); return i > 0 ? process.argv[i + 1] : d; };@@ -42,8 +42,10 @@ const rowsDir = join(homedir(), ".vd/story/rows");if (existsSync(join(rowsDir, "schemas.json"))) copyFileSync(join(rowsDir, "schemas.json"), join(OUT, "schemas.json"));const write = (task: string, rows: J[]) => writeFileSync(join(OUT, task, `${NAME}.jsonl`), rows.map((r) => JSON.stringify(r)).join("\n") + "\n");+for (const t of ["steps"]) mkdirSync(join(OUT, t), { recursive: true });+write("steps", chunkSteps(s).map((st, j) => ({ i: 0, at: j, of: Math.ceil(beats.length / CHUNK), prompt: st.prompt, script: st.script, answer: JSON.stringify(st.answer), gold: j === 0 ? JSON.stringify(bare(s)) : undefined })));write("extract", [{ i: 0, kind: "script", prompt: prose(beats), answer: JSON.stringify(bare(s)) }]);-write("generate", beats.map((b, k) => ({ i: 0, at: k, prompt: JSON.stringify({ story: { ...s, tellings: { main: beats.filter((_, n) => n !== k) } }, write: `the beat that goes at place ${k + 1} of ${beats.length}` }), answer: JSON.stringify(b), schema: beatSchema(s) })));+write("generate", beats.map((b, k) => ({ i: 0, at: k, prompt: windowAt(s, "main", k), story: { ...s, tellings: { main: beats.filter((_, n) => n !== k) } }, answer: JSON.stringify(b), schema: beatSchema(s) })));const critic: J[] = [{ i: 0, kind: "clean", prompt: prose(beats), answer: JSON.stringify({ breaks: breaks(s, beats) }) }];beats.forEach((_, k) => { const b2 = beats.filter((_, n) => n !== k); critic.push({ i: 0, kind: `cut${k + 1}`, prompt: prose(b2), answer: JSON.stringify({ breaks: breaks(s, b2) }) }); });beats.slice(0, -1).forEach((_, k) => { const b2 = [...beats]; [b2[k], b2[k + 1]] = [b2[k + 1], b2[k]]; critic.push({ i: 0, kind: `swap${k + 1}`, prompt: prose(b2), answer: JSON.stringify({ breaks: breaks(s, b2) }) }); });diff --git a/sdk/story/src/index.ts b/sdk/story/src/index.tsindex 95de686c..5103ce4f 100644--- a/sdk/story/src/index.ts+++ b/sdk/story/src/index.ts@@ -17,3 +17,4 @@ export { compileScript, compileStorylets, dramaManager, toInk, toYarn, onScreenOexport { resolved, type RStory } from "./load.ts";export { toData, fromData, storySchema, beatSchema, beatShape, keysIn, type DataError } from "./data.ts";export { toLines, fromLines } from "./lines.ts";+export { stateAt, stateIn, stateLines, windowAt, type State } from "./state.ts";diff --git a/sdk/story/src/state.ts b/sdk/story/src/state.tsnew file mode 100644index 00000000..18f7c554--- /dev/null+++ b/sdk/story/src/state.ts@@ -0,0 +1,108 @@+// The story's state at a beat (docs/story.md, "Any length"): what the derived systems hold just before beat k, small+// enough to stand in for every beat before it. A model that writes, reads or judges a long telling is handed this and+// a few neighbouring beats, never the whole telling, so length is a number of steps, not a context window:+// knows facts the audience holds open questions still open suspense who lacks what+// levels each value's level tension 0 to 1 unpaid setups planted, not paid+// shown events seen so far (count) ahead events the telling hasn't shown yet+// unsettled each agent's want, need or lie no shown event has ended+// windowAt() is that state plus the beats around k as story lines: the prompt a windowed step reads.+import type { World } from "./ecs.ts";+import { analyze } from "./checks.ts";+import { beatsOf, eventsOf, keysOf, type RAgent } from "./load.ts";+import type { AnyStory } from "./model.ts";+import { listOf } from "./model.ts";+import { toData } from "./data.ts";+import { toLines } from "./lines.ts";+import type { Audience } from "./systems/know.ts";+import type { Curve } from "./systems/values.ts";++export type State = {+ at: number;+ knows: string[];+ open: string[];+ suspense: { who: string; fact: string }[];+ levels: Record<string, number>;+ tension: number;+ unpaid: string[];+ shown: number;+ ahead: string[];+ unsettled: Record<string, string[]>;+};++/** The state just before beat k (k = the beat count: after the last). */+export function stateIn(w: World, k: number): State {+ const beats = beatsOf(w);+ const prev = k > 0 ? beats[k - 1] : undefined;+ const a = prev ? w.must<Audience>(prev.e, "Audience") : { knows: [], open: [], suspense: [] };+ const curves = w.resource<Record<string, Curve>>("Curves") ?? {};+ const levels = Object.fromEntries(Object.entries(curves).map(([v, c]) => [v, c.levels[k] ?? 0]));+ const before = beats.slice(0, k);+ const shown = new Set(before.flatMap((b) => b.beat.shows));+ const planted = before.flatMap((b) => listOf(b.beat.setup).map(String));+ const paid = new Set(before.flatMap((b) => listOf(b.beat.pays).map(String)));+ const events = eventsOf(w).sort((x, y) => x.order - y.order);+ const ended: Record<string, Set<string>> = {};+ for (const { key, ev } of events) if (shown.has(key)) for (const [who, what] of Object.entries(ev.ends ?? {})) (ended[who] ??= new Set()).add(String(what).replace("-refused", ""));+ const unsettled: Record<string, string[]> = {};+ for (const [who, e] of Object.entries(keysOf(w).agents)) {+ const ag = w.must<RAgent>(e, "Agent");+ const left = (["want", "need", "lie"] as const).filter((t) => ag[t] && !ended[who]?.has(t));+ if (left.length) unsettled[who] = left;+ }+ return {+ at: k,+ knows: a.knows,+ open: a.open,+ suspense: a.suspense,+ levels,+ tension: prev ? (w.get<number>(prev.e, "Tension") ?? 0) : 0,+ unpaid: [...new Set(planted.filter((s) => !paid.has(s)))],+ shown: shown.size,+ ahead: events.map((x) => x.key).filter((key) => !shown.has(key)),+ unsettled,+ };+}++export const stateAt = (s: AnyStory, telling: string | undefined, k: number, seed = 0): State => stateIn(analyze(s, telling, seed), k);++/** A state as lines, in the story-lines style. */+export function stateLines(st: State): string {+ const out = [`STATE before beat ${st.at + 1}: shown ${st.shown} events | tension ${st.tension}`];+ if (Object.keys(st.levels).length) out.push(`LEVELS ${Object.entries(st.levels).map(([v, n]) => `${v}${n >= 0 ? "+" : ""}${n}`).join(" ")}`);+ if (st.knows.length) out.push(`KNOWS ${st.knows.join(",")}`);+ if (st.open.length) out.push(`OPEN ${st.open.join(",")}`);+ if (st.suspense.length) out.push(`SUSPENSE ${st.suspense.map((x) => `${x.who}:${x.fact}`).join(" ")}`);+ if (st.unpaid.length) out.push(`UNPAID ${st.unpaid.join(",")}`);+ if (Object.keys(st.unsettled).length) out.push(`UNSETTLED ${Object.entries(st.unsettled).map(([a, t]) => `${a}:${t.join("+")}`).join(" ")}`);+ if (st.ahead.length) out.push(`AHEAD ${st.ahead.join(",")}`);+ return out.join("\n");+}++/**+ * What a windowed step reads to write beat k: the story's world (values, facts, agents, and only the events a step+ * could use: the ones not yet shown and the ones its neighbours show), the state before k, and up to `before` beats+ * before and `after` beats after it, as story lines. Its size doesn't grow with the telling.+ */+export function windowAt(s: AnyStory | Record<string, any>, telling: string, k: number, o: { before?: number; after?: number; seed?: number; skip?: boolean } = {}): string {+ const before = o.before ?? 3, after = o.after ?? 2;+ const d: Record<string, any> = (s as AnyStory).kind === "story" ? toData(s as AnyStory, o.seed ?? 0) : s;+ const beats: any[] = d.tellings[telling];+ // skip: beat k is missing from the telling (the generator's task: write it back); else beat k is there, and left out+ const rest = o.skip ? beats : beats.filter((_, n) => n !== k);+ const w = analyze({ ...d, kind: "story", tellings: { [telling]: rest } } as unknown as AnyStory, telling, o.seed ?? 0);+ const st = stateIn(w, k);+ const near = [...rest.slice(Math.max(0, k - before), k), ...rest.slice(k, k + after)];+ const keep = new Set([...st.ahead, ...near.flatMap((b) => b.shows ?? [])]);+ const world = Object.fromEntries(Object.entries(d.world).filter(([key]) => keep.has(key)));+ const lines = toLines({ ...d, world, tellings: {} }).split("\n").filter((l) => !l.startsWith("TELLING"));+ const beatLines = (bs: any[]) => toLines({ values: {}, agents: {}, world: {}, tellings: { t: bs } }).split("\n").filter((l) => !l.startsWith("TELLING"));+ return [+ ...lines,+ stateLines(st),+ `BEFORE (beats ${Math.max(0, k - before) + 1} to ${k} of ${rest.length + 1})`,+ ...beatLines(rest.slice(Math.max(0, k - before), k)),+ `WRITE beat ${k + 1}`,+ `AFTER`,+ ...beatLines(rest.slice(k, k + after)),+ ].join("\n");+}diff --git a/sdk/story/test/lines.test.ts b/sdk/story/test/lines.test.tsindex 4591dead..358097db 100644--- a/sdk/story/test/lines.test.ts+++ b/sdk/story/test/lines.test.ts@@ -1,7 +1,7 @@import { expect, test } from "bun:test";import { existsSync, readFileSync } from "node:fs";import { homedir } from "node:os";-import { fromData, fromLines, storySchema, toData, toLines } from "../src/index.ts";+import { fromData, fromLines, stateAt, storySchema, toData, toLines, windowAt } from "../src/index.ts";// only what the schema defines (a corpus story can carry a field the model has no place for)const prune = (x: any, sc: any): any => {@@ -47,3 +47,20 @@ test.skipIf(!existsSync(corpus))("every corpus story reads back from its lines eif (bad.length) { const r = fromLines(toLines(bad[0])); console.log(r.errors.slice(0, 3)); const a = JSON.stringify(norm(toData(r.story!))), b = JSON.stringify(norm(prune(bad[0], storySchema()))); let i = 0; while (a[i] === b[i]) i++; console.log(i, a.slice(Math.max(0, i - 80), i + 80), "\n---\n", b.slice(Math.max(0, i - 80), i + 80)); }expect(bad.length).toBe(0);});++test("the state before a beat stands in for the beats before it", () => {+ const st0 = stateAt(launch, "30s", 0);+ expect(st0.shown).toBe(0);+ expect(st0.ahead.length).toBe(Object.keys(launch.world).length);+ const end = stateAt(launch, "30s", (launch.tellings["30s"] as unknown[]).length);+ expect(end.ahead).toEqual([]);+ expect(end.unpaid).toEqual([]);+ expect(end.unsettled.team ?? []).not.toContain("need");+});++test("a window holds the state and the beats around the one to write, not the whole telling", () => {+ const w = windowAt(launch, "30s", 2, { before: 1, after: 1 });+ expect(w).toContain("STATE before beat 3");+ expect(w).toContain("WRITE beat 3");+ expect(w.split("\n").filter((l) => l.startsWith("BEAT")).length).toBe(2);+});