408 lines · 20.5 KB · TypeScriptRaw
/** * Cotton Story's verbs over MCP, where the generic record tools cannot keep * the story's rules (apps/story/CORE.md, "MCP"): * * - `story_scene_write { id?, story?, after?, body?, heading?, setting?, place?, time?, summary?, status? }`: * writes a scene (a new one when `id` is absent: at the end of `story`, or * after scene `after`), keeps its heading and its setting, place and time in * step, works out its words, pages, minutes and speakers, and makes the * places and characters it names that the story has no row for; every * character's scenes and lines are counted again. * - `story_scene_move { id, by | to }`: a scene earlier or later, or to a * position from 1; the story's positions are written 1, 2, 3... * - `story_copy { story, language }`: a whole copy linked by translation_of, * for translating line by line. * - `story_fountain_write { story }`: the whole story as Fountain. * - `story_fountain_read { text, name? }`: a new story from a Fountain file. * * The rules are the phone's own (cotton_rules::story, as WASM). Story's * tables are sealed: each verb reads and writes inside the owner's window for * this assistant (request_unlock), as create_record and update_record do, and * writes the figures it works out as the object's own (PRODUCED_BY_THE_OBJECT). */import { rule } from "../../rules/index.ts";import type { StoredRow } from "../../store.ts";import { fail, optionalString, requireString, type Data, type Handler, type ToolContext } from "../context.ts";import { resolveTable } from "./records/table.ts";import { createRecord, updateRecord } from "./records/write.ts";import { openStored, windowFor } from "./window.ts";import { lay } from "./story_ink.ts";import storyLines from "../../../../../crates/cotton-core/kits/shell/lines/story.json";export const STORY = "story_story";export const SCENE = "story_scene";export const CHARACTER = "story_character";export const PLACE = "story_place";export const NOTE = "story_note";export const SEQUENCE = "story_sequence";export const ANSWER = "story_answer";export const SETTINGS = new Set(["INT.", "EXT.", "INT./EXT."]);interface Figures { words: number; pages: number; minutes: number; speakers: string[]; speeches: [string, number][];}export interface Parts { setting: string | null; place: string; time: string | null;}export interface SceneDoc { heading: string; summary?: string | null; body: string;}/** One `story` line by its dotted key, `{name}` filled: the kit's words. */export function say(line: string, fills: Record<string, string> = {}): string { let at: unknown = storyLines; for (const key of line.split(".")) at = at && typeof at === "object" ? (at as Record<string, unknown>)[key] : undefined; if (typeof at !== "string") return `story.${line}`; return at.replace(/\{(\w+)\}/g, (whole, name: string) => fills[name] ?? whole);}/** Two names are one: alike trimmed and lower-cased (cotton_rules::story::lines::same_name). */export function sameName(a: string, b: string): boolean { return a.trim() === b.trim() || a.trim().toLowerCase() === b.trim().toLowerCase();}export function str(data: Data, key: string): string { const v = data[key]; return typeof v === "string" ? v : "";}export function num(data: Data, key: string): number { const v = data[key]; return typeof v === "number" ? v : 0;}/** A row's data with its id, opened in the window. */export type Row = Data & { id: string };/** The live rows of `table` linking `story`, opened in this assistant's window. */export async function rowsOf(ctx: ToolContext, table: string, story: string, tool: string): Promise<Row[]> { const t = resolveTable(ctx, table); const keys = await windowFor(ctx, t, tool); const out: Row[] = []; for (const stored of ctx.where(t.id, "story", story)) { if (t.binned(stored) !== null) continue; const { row } = await openStored(ctx, t, keys, stored); out.push({ ...row.data, id: row.id, created_at: row.created_at }); } return out;}/** One live row, opened; a refusal in Story's words when there is none. */export async function rowOf(ctx: ToolContext, table: string, id: string, tool: string, missing: string): Promise<Row> { const t = resolveTable(ctx, table); // The window first: a sealed table says nothing of its rows without one. const keys = await windowFor(ctx, t, tool); const held: StoredRow | null = ctx.get(t.id, id); if (!held || t.binned(held) !== null) fail(missing); const { row } = await openStored(ctx, t, keys, held); return { ...row.data, id: row.id, created_at: row.created_at };}export async function scenesOf(ctx: ToolContext, story: string, tool: string): Promise<Row[]> { const scenes = await rowsOf(ctx, SCENE, story, tool); return scenes.sort((a, b) => num(a, "position") - num(b, "position") || str(a, "created_at").localeCompare(str(b, "created_at")));}export async function namesOf(ctx: ToolContext, story: string, tool: string): Promise<string[]> { return (await rowsOf(ctx, CHARACTER, story, tool)).map((row) => str(row, "name")).filter((name) => name.trim() !== "");}export async function make(ctx: ToolContext, table: string, data: Data): Promise<string> { const made = await createRecord(ctx, { table, data }, new Map(), true); const record = made.record as Data; return String(record.id);}export async function patch(ctx: ToolContext, table: string, id: string, values: Data): Promise<void> { if (!Object.keys(values).length) return; try { await updateRecord(ctx, { table, id, patch: values }, new Map(), true); } catch (error) { // A write that changes nothing is no failure here: the row already says it. if (error instanceof Error && error.message === "the patch changes nothing") return; throw error; }}/** The story's place by name, made when it has none. */export async function placeNamed(ctx: ToolContext, story: string, name: string, made: string[], tool: string): Promise<string | null> { const wanted = name.trim(); if (!wanted) return null; const found = (await rowsOf(ctx, PLACE, story, tool)).find((row) => sameName(str(row, "name"), wanted)); if (found) return found.id; const id = await make(ctx, PLACE, { story, name: wanted }); made.push(id); return id;}/** Count every character's scenes and speeches again, making one for a speaker the story has no row for. */export async function recount(ctx: ToolContext, story: string, made: string[], tool: string): Promise<void> { const names = await namesOf(ctx, story, tool); const tally: { name: string; scenes: number; lines: number }[] = []; for (const scene of await scenesOf(ctx, story, tool)) { const figures = rule<Figures>("story.figures", { heading: str(scene, "heading"), body: str(scene, "body"), names }); for (const [name, speeches] of figures.speeches) { const seen = tally.find((t) => sameName(t.name, name)); if (seen) { seen.scenes += 1; seen.lines += speeches; } else tally.push({ name, scenes: 1, lines: speeches }); } } const characters = await rowsOf(ctx, CHARACTER, story, tool); for (const t of tally) { if (!characters.some((row) => sameName(str(row, "name"), t.name))) made.push(await make(ctx, CHARACTER, { story, name: t.name, scenes: 0, lines: 0 })); } for (const character of await rowsOf(ctx, CHARACTER, story, tool)) { const t = tally.find((one) => sameName(one.name, str(character, "name"))); const values: Data = {}; if (num(character, "scenes") !== (t?.scenes ?? 0) || character.scenes === undefined) values.scenes = t?.scenes ?? 0; if (num(character, "lines") !== (t?.lines ?? 0) || character.lines === undefined) values.lines = t?.lines ?? 0; await patch(ctx, CHARACTER, character.id, values); }}export function derived(heading: string, body: string, names: string[]): Data { const f = rule<Figures>("story.figures", { heading, body, names }); return { words: f.words, pages: f.pages, minutes: f.minutes, speakers: f.speakers.join("\n") };}/** Make room at `from`: every scene of the story at or after it moves down one, the interval and the sequences' starts with them. */export async function makeRoom(ctx: ToolContext, story: string, from: number, tool: string): Promise<void> { for (const scene of await scenesOf(ctx, story, tool)) { if (num(scene, "position") >= from) await patch(ctx, SCENE, scene.id, { position: num(scene, "position") + 1 }); } const held = await rowOf(ctx, STORY, story, tool, say("refusal.no_story")); if (typeof held.interval_at === "number" && held.interval_at >= from) await patch(ctx, STORY, story, { interval_at: held.interval_at + 1 }); for (const sequence of await rowsOf(ctx, SEQUENCE, story, tool)) { if (num(sequence, "position") >= from) await patch(ctx, SEQUENCE, sequence.id, { position: num(sequence, "position") + 1 }); }}/** Where the interval and each sequence stand among the scenes: how many scenes come before each. */async function marksHeld(ctx: ToolContext, story: string, ordered: Row[], tool: string): Promise<{ table: string; id: string; column: string; before: number }[]> { const before = (at: number): number => ordered.filter((scene) => num(scene, "position") < at).length; const marks: { table: string; id: string; column: string; before: number }[] = []; const held = await rowOf(ctx, STORY, story, tool, say("refusal.no_story")); if (typeof held.interval_at === "number") marks.push({ table: STORY, id: story, column: "interval_at", before: before(held.interval_at) }); for (const sequence of await rowsOf(ctx, SEQUENCE, story, tool)) marks.push({ table: SEQUENCE, id: sequence.id, column: "position", before: before(num(sequence, "position")) }); return marks;}async function sceneWrite(ctx: ToolContext, args: Data): Promise<Data> { const tool = "story_scene_write"; let id = optionalString(args, "id"); if (!id) { const after = optionalString(args, "after"); let story: string; let position: number; if (after) { const row = await rowOf(ctx, SCENE, after, tool, say("refusal.no_scene")); story = str(row, "story"); position = num(row, "position") + 1; await makeRoom(ctx, story, position, tool); } else { story = requireString(args, "story", "a new scene names its story (list_records { table: \"story_story\" }), or the scene to follow (after)"); await rowOf(ctx, STORY, story, tool, say("refusal.no_story")); position = Math.max(0, ...(await scenesOf(ctx, story, tool)).map((s) => num(s, "position"))) + 1; } id = await make(ctx, SCENE, { story, position, setting: "INT.", status: "draft", words: 0, pages: 0, minutes: 0, speakers: "" }); } const row = await rowOf(ctx, SCENE, id, tool, say("refusal.no_scene")); const story = str(row, "story"); const values: Data = {}; const madePlaces: string[] = []; const madeCharacters: string[] = []; for (const key of ["summary", "status", "body"]) { if (typeof args[key] === "string" || args[key] === null) values[key] = args[key]; } if (typeof args.day === "number" || args.day === null) values.day = args.day; let parts: Parts | null = null; if (typeof args.heading === "string") { parts = rule<Parts>("story.heading.parse", { heading: args.heading }); if (!parts.setting && !args.heading.trim().startsWith(".")) parts.setting = str(row, "setting") || null; values.heading = args.heading.trim(); } else if (["setting", "place", "time"].some((key) => args[key] !== undefined)) { const placeId = str(row, "place"); const placeName = placeId ? str(await rowOf(ctx, PLACE, placeId, tool, say("refusal.no_story")), "name") : ""; parts = { setting: str(row, "setting") || null, place: placeName, time: str(row, "time") || null }; if (typeof args.setting === "string") parts.setting = args.setting; if (typeof args.place === "string") parts.place = args.place; if (args.time !== undefined) parts.time = typeof args.time === "string" && args.time.trim() ? args.time : null; values.heading = rule<string>("story.heading.compose", parts); } if (parts) { if (parts.setting && SETTINGS.has(parts.setting)) values.setting = parts.setting; values.time = parts.time ?? null; values.place = await placeNamed(ctx, story, parts.place, madePlaces, tool); } const heading = typeof values.heading === "string" ? values.heading : str(row, "heading"); const body = typeof values.body === "string" ? values.body : str(row, "body"); const names = await namesOf(ctx, story, tool); Object.assign(values, derived(heading, body, names)); // A cleared column is left out of a new value rather than written as null twice. for (const [key, value] of Object.entries(values)) if (value === null && (row[key] === undefined || row[key] === null)) delete values[key]; await patch(ctx, SCENE, id, values); await recount(ctx, story, madeCharacters, tool); // The body's lines are rows that keep their ids: lay it over them, and keep the body from them. if (typeof values.body === "string") await lay(ctx, id, tool); const now = await rowOf(ctx, SCENE, id, tool, say("refusal.no_scene")); return { scene: { id, story, heading: now.heading ?? null, setting: now.setting ?? null, place: now.place ?? null, time: now.time ?? null, words: now.words ?? 0, pages: now.pages ?? 0, minutes: now.minutes ?? 0, speakers: now.speakers ?? "" }, made: { characters: madeCharacters, places: madePlaces }, };}async function sceneMove(ctx: ToolContext, args: Data): Promise<Data> { const tool = "story_scene_move"; const id = requireString(args, "id", "id is the scene's id"); const row = await rowOf(ctx, SCENE, id, tool, say("refusal.no_scene")); const ordered = await scenesOf(ctx, str(row, "story"), tool); const at = ordered.findIndex((s) => s.id === id); let to: number; if (typeof args.by === "number" && Number.isInteger(args.by)) to = Math.min(ordered.length - 1, Math.max(0, at + args.by)); else if (typeof args.to === "number" && Number.isInteger(args.to)) to = Math.min(ordered.length - 1, Math.max(1, args.to) - 1); else fail("this names by (-1 earlier, 1 later) or to (a position from 1)"); const marks = await marksHeld(ctx, str(row, "story"), ordered, tool); const [moving] = ordered.splice(at, 1); ordered.splice(to, 0, moving!); const positions: Data[] = []; for (const [index, scene] of ordered.entries()) { if (num(scene, "position") !== index + 1) await patch(ctx, SCENE, scene.id, { position: index + 1 }); positions.push({ id: scene.id, position: index + 1 }); } // The scenes are 1, 2, 3 now: each mark stands just after the scenes it followed. for (const mark of marks) await patch(ctx, mark.table, mark.id, { [mark.column]: mark.before + 0.5 }); return { positions };}function copied(row: Data, keys: string[]): Data { const out: Data = {}; for (const key of keys) if (row[key] !== undefined && row[key] !== null) out[key] = row[key]; return out;}async function storyCopy(ctx: ToolContext, args: Data): Promise<Data> { const tool = "story_copy"; const id = requireString(args, "story", "story is the story's id (list_records { table: \"story_story\" })"); const language = requireString(args, "language", "language is the language the copy is for, like Telugu"); const story = await rowOf(ctx, STORY, id, tool, say("refusal.no_story")); const now = new Date().toISOString(); const copy = await make(ctx, STORY, { ...copied(story, ["logline", "written_by", "format", "interval_at"]), title: say("stories.copy_title", { title: str(story, "title"), language }), language, translation_of: id, made_at: now.slice(0, 10), chosen_at: now, }); const places = new Map<string, string>(); for (const place of await rowsOf(ctx, PLACE, id, tool)) places.set(place.id, await make(ctx, PLACE, { ...copied(place, ["name", "about"]), story: copy })); for (const character of await rowsOf(ctx, CHARACTER, id, tool)) await make(ctx, CHARACTER, { ...copied(character, ["name", "role", "about", "want", "picture", "scenes", "lines", "tint"]), story: copy }); const scenes = new Map<string, string>(); for (const scene of await scenesOf(ctx, id, tool)) { const data: Data = { ...copied(scene, ["position", "setting", "time", "day", "heading", "summary", "question", "body", "status", "words", "pages", "minutes", "speakers"]), story: copy }; const place = places.get(str(scene, "place")); if (place) data.place = place; scenes.set(scene.id, await make(ctx, SCENE, data)); } for (const note of await rowsOf(ctx, NOTE, id, tool)) { const data: Data = { ...copied(note, ["title", "body"]), story: copy }; const scene = scenes.get(str(note, "scene")); if (scene) data.scene = scene; await make(ctx, NOTE, data); } for (const sequence of await rowsOf(ctx, SEQUENCE, id, tool)) await make(ctx, SEQUENCE, { ...copied(sequence, ["title", "position", "folded"]), story: copy }); const originals = await scenesOf(ctx, id, tool); for (const answer of await rowsOf(ctx, ANSWER, id, tool)) { const made = await make(ctx, ANSWER, { ...copied(answer, ["question", "answer", "skipped", "answered_at"]), story: copy }); for (const scene of originals.filter((one) => str(one, "answer") === answer.id)) { const copiedScene = scenes.get(scene.id); if (copiedScene) await patch(ctx, SCENE, copiedScene, { answer: made }); } } for (const scene of await scenesOf(ctx, copy, tool)) await lay(ctx, scene.id, tool); return { story: copy, scenes: scenes.size };}export function fileName(title: string): string { const cleaned = title.replace(/[/\\:*?"<>|]/g, " ").trim(); return `${cleaned || "Story"}.fountain`;}async function fountainWrite(ctx: ToolContext, args: Data): Promise<Data> { const tool = "story_fountain_write"; const id = requireString(args, "story", "story is the story's id (list_records { table: \"story_story\" })"); const story = await rowOf(ctx, STORY, id, tool, say("refusal.no_story")); const title: [string, string][] = [["Title", str(story, "title")]]; const author = str(story, "written_by").trim(); if (author) { title.push(["Credit", say("script.title_page_by")]); title.push(["Author", author]); } const made = str(story, "made_at").trim(); if (made) title.push(["Draft date", made]); const scenes: SceneDoc[] = (await scenesOf(ctx, id, tool)).map((scene) => ({ heading: str(scene, "heading"), ...(str(scene, "summary").trim() ? { summary: str(scene, "summary") } : {}), body: str(scene, "body"), })); return { text: rule<string>("story.fountain.write", { title, scenes }), name: fileName(str(story, "title")) };}async function fountainRead(ctx: ToolContext, args: Data): Promise<Data> { const tool = "story_fountain_read"; const text = typeof args.text === "string" ? args.text : fail("text is the Fountain file's text"); const doc = rule<{ title: [string, string][]; scenes: SceneDoc[] }>("story.fountain.read", { text }); if (!doc.scenes.length && !doc.title.length) fail(say("fountain.unreadable")); const value = (key: string): string | null => doc.title.find(([k]) => k.toLowerCase() === key.toLowerCase())?.[1]?.trim() || null; const named = optionalString(args, "name")?.replace(/\.[^.]*$/, "").trim() || null; const now = new Date().toISOString(); const story = await make(ctx, STORY, { title: value("title")?.replace(/\n/g, " ") ?? named ?? "Story", ...(value("author") ?? value("authors") ? { written_by: value("author") ?? value("authors") } : {}), language: "English", format: "feature", made_at: /^\d{4}-\d{2}-\d{2}$/.test(value("draft date") ?? "") ? value("draft date") : now.slice(0, 10), chosen_at: now, }); const places: string[] = []; const characters: string[] = []; for (const [index, scene] of doc.scenes.entries()) { const parts = rule<Parts>("story.heading.parse", { heading: scene.heading }); const place = await placeNamed(ctx, story, parts.place, places, tool); await make(ctx, SCENE, { story, position: index + 1, heading: scene.heading, setting: parts.setting && SETTINGS.has(parts.setting) ? parts.setting : "INT.", body: scene.body, status: "draft", ...(place ? { place } : {}), ...(parts.time ? { time: parts.time } : {}), ...(scene.summary ? { summary: scene.summary } : {}), ...derived(scene.heading, scene.body, []), }); } await recount(ctx, story, characters, tool); for (const scene of await scenesOf(ctx, story, tool)) await lay(ctx, scene.id, tool); return { story, scenes: doc.scenes.length, characters: characters.length, places: places.length };}export const STORY_HANDLERS: Record<string, Handler> = { story_scene_write: sceneWrite, story_scene_move: sceneMove, story_copy: storyCopy, story_fountain_write: fountainWrite, story_fountain_read: fountainRead,};