/** * The contract the model writes into, and the checks that contract is held to. * * Pure module: no Payload import, so the validator and the normalizer can be * unit-tested without booting a database. The service that actually calls the * model lives in `generation.ts`. * * Two shapes matter here: * * 1. `dialogueFlowSchema` is the JSON schema sent with the request. It is * deliberately strict-safe: every property is required and * `additionalProperties` is false, because OpenAI-style strict structured * outputs reject optional properties. "Absent" is expressed as an empty * string or an empty array and normalized away afterwards. * 2. `RawDraftNode` is what a successful parse produces. `normalizeGeneratedFlow` * turns that into real `DialogueNode`s with layout positions, and * `validateGeneratedFlow` decides whether the result may reach the canvas. */ import { deriveEdges, findStartNode, outgoingHops, validateGraph } from "./dialogue"; import type { DraftScope } from "./generationPrompt"; import type { DialogueNode, DialogueNodeData, DialogueNext, FlowData, NpcDialogueEffect, NpcDialogueNodeType, } from "./dialogue"; /** Node kinds the generator may produce. `delay` is omitted: timing in a * generated draft is noise the author has to delete anyway. */ export const DRAFT_NODE_TYPES = ["dialogue", "choice", "event", "end", "condition"] as const; /** Effects the generator may configure. `emit`, `reward` and `discord` write * game state or post to Discord, so they stay author-only. */ export const DRAFT_EFFECT_TYPES = ["none", "flag", "notify"] as const; const FLAG_OPS = ["set_true", "set_false", "set_number", "set_text", "add"] as const; const CONDITION_OPS = [ "is_true", "is_false", "is_defined", "is_undefined", "gte", "lte", "gt", "lt", "eq", ] as const; export interface RawDraftChoice { label: string; target: string; tooltip: string; } export interface RawDraftNode { id: string; type: (typeof DRAFT_NODE_TYPES)[number]; isStart: boolean; speaker: string; body: string; leadIn: string; closing: string; choices: RawDraftChoice[]; nextLabel: string; nextTarget: string; effectType: (typeof DRAFT_EFFECT_TYPES)[number]; effectTitle: string; effectMessage: string; effectFlagKey: string; effectFlagOp: (typeof FLAG_OPS)[number]; effectFlagAmount: number; effectFlagText: string; conditionKey: string; conditionOp: (typeof CONDITION_OPS)[number]; conditionAmount: number; trueTarget: string; falseTarget: string; } /** Builds a strict-compatible object schema: every property required. */ function strictObject(properties: Record): Record { return { type: "object", additionalProperties: false, properties, required: Object.keys(properties), }; } const choiceSchema = strictObject({ label: { type: "string", description: "Button text the player taps." }, target: { type: "string", description: "Id of the node this choice leads to." }, tooltip: { type: "string", description: "Optional hover hint. Empty when unused." }, }); const nodeSchema = strictObject({ id: { type: "string", description: "Unique short id, e.g. n1, n2." }, type: { type: "string", enum: [...DRAFT_NODE_TYPES] }, isStart: { type: "boolean", description: "True for exactly one node: the opening line." }, speaker: { type: "string", description: "Speaker label. Empty to use the NPC's own name.", }, body: { type: "string", description: "The spoken line, or narrative text for event nodes." }, leadIn: { type: "string", description: "Choice nodes only: text shown above the choices." }, closing: { type: "string", description: "End nodes only: closing line." }, choices: { type: "array", description: "Choice nodes only. Empty array otherwise.", items: choiceSchema, }, nextLabel: { type: "string", description: "Unused for single-hop continuations. Empty." }, nextTarget: { type: "string", description: "Single continuation for dialogue/event nodes. Empty when the node ends.", }, effectType: { type: "string", enum: [...DRAFT_EFFECT_TYPES] }, effectTitle: { type: "string", description: "notify only: notification title." }, effectMessage: { type: "string", description: "notify only: notification body." }, effectFlagKey: { type: "string", description: "flag only: player-flags key being written." }, effectFlagOp: { type: "string", enum: [...FLAG_OPS] }, effectFlagAmount: { type: "number", description: "set_number / add value. 0 when unused." }, effectFlagText: { type: "string", description: "set_text value. Empty when unused." }, conditionKey: { type: "string", description: "condition nodes only: player-flags key read." }, conditionOp: { type: "string", enum: [...CONDITION_OPS] }, conditionAmount: { type: "number", description: "Numeric comparisons only. 0 when unused." }, trueTarget: { type: "string", description: "condition nodes only: taken when the check passes." }, falseTarget: { type: "string", description: "condition nodes only: taken when it fails." }, }); export const dialogueFlowSchema: Record = strictObject({ nodes: { type: "array", minItems: 2, maxItems: 12, items: nodeSchema, }, }); /** Horizontal and vertical spacing for the auto-layout in `normalizeGeneratedFlow`. */ const LAYOUT_COLUMN_WIDTH = 360; const LAYOUT_ROW_HEIGHT = 220; /** * Converts a parsed draft into real nodes: assembles `DialogueNodeData` from the * flat schema fields, drops the empty-string placeholders, and assigns layout * positions by walking the graph from the start node. * * Ids are preserved (the model is told to use `n1`, `n2`, ...) but the caller * should still treat them as untrusted: `validateGeneratedFlow` rejects dangling * targets, and the editor merges the graph into an empty canvas. */ export function normalizeGeneratedFlow(raw: RawDraftNode[]): { nodes: DialogueNode[]; edges: FlowData["edges"]; errors: string[]; } { const errors: string[] = []; const seen = new Set(); const nodes: DialogueNode[] = []; raw.forEach((entry, index) => { const id = (entry.id ?? "").trim() || `n${index + 1}`; if (seen.has(id)) { errors.push(`Duplicate node id "${id}".`); return; } seen.add(id); const type = entry.type ?? "dialogue"; if (!DRAFT_NODE_TYPES.includes(type)) { errors.push(`"${id}" has an unsupported node type "${type}".`); return; } const data: DialogueNodeData = {}; if (entry.speaker?.trim()) data.speaker = entry.speaker.trim(); if (entry.body?.trim()) data.body = entry.body.trim(); if (entry.leadIn?.trim()) data.leadIn = entry.leadIn.trim(); if (entry.closing?.trim()) data.closing = entry.closing.trim(); if (entry.isStart) data.isStart = true; if (type === "choice") { const choices: DialogueNext[] = (entry.choices ?? []) .filter((choice) => choice && choice.target?.trim()) .map((choice) => ({ label: choice.label?.trim() || "Continue", target: choice.target.trim(), ...(choice.tooltip?.trim() ? { tooltip: choice.tooltip.trim() } : {}), })); data.choices = choices; } else if (type === "condition") { const key = entry.conditionKey?.trim(); if (key) { data.condition = { kind: "flag", key, op: entry.conditionOp ?? "is_true", ...(entry.conditionAmount ? { amount: entry.conditionAmount } : {}), }; } if (entry.trueTarget?.trim()) data.trueTarget = entry.trueTarget.trim(); if (entry.falseTarget?.trim()) data.falseTarget = entry.falseTarget.trim(); } else if (entry.nextTarget?.trim()) { data.next = { target: entry.nextTarget.trim() }; } const effect = buildEffect(entry); if (effect) data.effect = effect; nodes.push({ id, type: type as NpcDialogueNodeType, position: { x: 0, y: 0 }, data }); }); applyLayout(nodes); return { nodes, edges: deriveEdges(nodes), errors }; } /** Assembles an effect from the flat fields, or null when there is none. */ function buildEffect(entry: RawDraftNode): NpcDialogueEffect | null { if (entry.effectType === "notify") { return { type: "notify", title: entry.effectTitle?.trim() || "Message", message: entry.effectMessage?.trim() ?? "", }; } if (entry.effectType === "flag") { const flagKey = entry.effectFlagKey?.trim(); if (!flagKey) return null; return { type: "flag", flagKey, flagOp: entry.effectFlagOp ?? "set_true", ...(entry.effectFlagAmount ? { flagAmount: entry.effectFlagAmount } : {}), ...(entry.effectFlagText?.trim() ? { flagText: entry.effectFlagText.trim() } : {}), }; } return null; } /** * Lays the graph out left to right by breadth from the start node, so a * generated draft opens as a readable chain instead of a pile at the origin. * Nodes unreachable from the start land in a trailing column. */ function applyLayout(nodes: DialogueNode[]): void { if (nodes.length === 0) return; const byId = new Map(nodes.map((node) => [node.id, node])); const start = findStartNode(nodes); const placed = new Set(); const depthById = new Map(); const rowByDepth = new Map(); let frontier = start ? [start.id] : []; let depth = 0; while (frontier.length > 0) { const next: string[] = []; for (const id of frontier) { if (placed.has(id)) continue; placed.add(id); depthById.set(id, depth); const node = byId.get(id); const row = rowByDepth.get(depth) ?? 0; rowByDepth.set(depth, row + 1); if (node) { node.position = { x: depth * LAYOUT_COLUMN_WIDTH, y: row * LAYOUT_ROW_HEIGHT }; } if (!node) continue; for (const hop of outgoingHops(node)) { if (hop?.target && !placed.has(hop.target)) next.push(hop.target); } } frontier = next; depth += 1; } const orphanDepth = (rowByDepth.get(0) ?? 1) + 1; let orphanRow = 0; for (const node of nodes) { if (placed.has(node.id)) continue; node.position = { x: orphanDepth * LAYOUT_COLUMN_WIDTH, y: orphanRow * LAYOUT_ROW_HEIGHT }; orphanRow += 1; } } /** Every `{{flag}}` and `{{countdown:key}}` reference in one string. */ const FLAG_TOKEN = /\{\{\s*([a-zA-Z0-9_]+)\s*\}\}/g; const COUNTDOWN_TOKEN = /\{\{\s*countdown:\s*([a-zA-Z0-9_]+)\s*\}\}/g; function referencedFlags(text: string | undefined, into: Set): void { if (!text) return; for (const match of text.matchAll(FLAG_TOKEN)) into.add(match[1].toLowerCase()); for (const match of text.matchAll(COUNTDOWN_TOKEN)) into.add(match[1].toLowerCase()); } export interface DraftValidation { ok: boolean; errors: string[]; } /** * Decides whether a generated draft may replace the canvas. * * Structural checks reuse `validateGraph` (start node, resolved hops, labelled * choices) so the editor and the generator agree on what a valid graph is. On * top of that this rejects the ways a model goes wrong in ways the editor would * happily accept: invented flag keys, unauthorised effects, and references to * flags that do not exist yet. */ export function validateGeneratedFlow( nodes: DialogueNode[], knownFlagKeys: Iterable, options: { scope?: DraftScope } = {}, ): DraftValidation { const scope = options.scope ?? "full"; const errors: string[] = []; if (nodes.length < 2) { errors.push( scope === "fragment" ? "A generated branch needs at least two nodes." : "A generated conversation needs at least two nodes.", ); } if (nodes.length > 12) { errors.push("A generated draft is limited to 12 nodes."); } const structural = validateGraph(nodes, { requireStart: scope === "full" }); errors.push(...structural.errors); if (scope === "fragment") { // A branch must not claim the conversation's start: it is entered from a node // the author wires it to. Silently accepting the flag would make two starts // and the runtime would pick one at random. const marked = nodes.filter((node) => node.data.isStart === true); if (marked.length > 0) { errors.push( `A branch must not mark a start node, and "${marked[0]?.id ?? "?"}" does.`, ); } // Without an exit the branch is a pocket: the author has nowhere to wire it // onward, and every path loops inside it forever. if (!nodes.some((node) => outgoingHops(node).length === 0)) { errors.push( "Every path loops back inside the branch. End at least one branch with no continuation.", ); } } const allowed = new Set([...knownFlagKeys].map((key) => key.toLowerCase())); // Only enforce the vocabulary once flags exist. An empty flag table would // otherwise reject every draft for referencing anything at all. const enforceFlags = allowed.size > 0; const unknown = new Set(); const checkFlag = (key: string, where: string) => { if (!enforceFlags) return; const normalized = key.toLowerCase(); if (!allowed.has(normalized)) unknown.add(`${where} uses unknown flag "${normalized}"`); }; for (const node of nodes) { if (node.type === "delay") { errors.push(`"${node.id}" uses a delay node, which generated drafts may not contain.`); } const effect = node.data.effect; if (effect) { if (effect.type !== "flag" && effect.type !== "notify") { errors.push(`"${node.id}" uses an unauthorised effect "${effect.type}".`); } if (effect.type === "flag") { if (!effect.flagKey?.trim()) { errors.push(`"${node.id}" has a flag effect with no key.`); } else { checkFlag(effect.flagKey, `"${node.id}"`); } } } const condition = node.data.condition; if (condition) { const leaves = condition.kind === "group" ? condition.children : [condition]; if (leaves.length === 0) errors.push(`"${node.id}" has an empty condition group.`); for (const leaf of leaves) { if (!leaf.key?.trim()) errors.push(`"${node.id}" has a condition with no key.`); else checkFlag(leaf.key, `"${node.id}"`); } } const tokens = new Set(); referencedFlags(node.data.body, tokens); referencedFlags(node.data.leadIn, tokens); referencedFlags(node.data.closing, tokens); for (const choice of node.data.choices ?? []) { referencedFlags(choice.label, tokens); referencedFlags(choice.tooltip, tokens); } for (const key of tokens) checkFlag(key, `"${node.id}"`); } errors.push(...unknown); return { ok: errors.length === 0, errors }; }