1
0
Fork 0
polaris-task-force/src/lib/npc-dialogue/generationSchema.ts
Z8MB1E 4264431e4d feat(npc-dialogue): AI-assisted conversation drafting behind the review gate
Add a Generate button to the flow editor that drafts a whole conversation
from a form brief, and per-line Rewrite/Shorten/Sharpen controls in the node
dialog. Both land in unsaved field state, so a draft only reaches players when
an author saves the document: neither server action writes to npc-dialogues.

- src/lib/ai/generate.ts: extract the Unsloth client out of payload.config so
  Compose and dialogue drafting share one path; add generateStructured and
  resolveModel, with an optional UNSLOTH_MODEL_STRUCTURED override
- generationSchema.ts (pure): strict-safe JSON schema, normalizer with
  breadth layout, validator that rejects unknown flag keys, unauthorised
  effects, dangling hops and missing keys
- generation.ts: context loading, one validate-and-retry, then give up rather
  than hand back a broken graph; dash normalization keeps shipped copy clean
- effect vocabulary limited to notify and flag; emit, reward and discord stay
  author-only
- provenance group on npc-dialogues (migration 20261112_171955) records model,
  prompt version, attempts and the brief the draft was accepted from
- tests: 21 cases covering the normalizer, validator, retry paths and the
  rewrite parser, with the model call injected
- docs/npc-dialogue-ai.md and src/lib/npc-dialogue/AGENTS.md
2026-11-12 12:26:35 -05:00

373 lines
13 KiB
TypeScript

/**
* 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 {
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", "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<string, unknown>): Record<string, unknown> {
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<string, unknown> = 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<string>();
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<string>();
const depthById = new Map<string, number>();
const rowByDepth = new Map<number, number>();
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<string>): 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<string>,
): DraftValidation {
const errors: string[] = [];
if (nodes.length < 2) {
errors.push("A generated conversation needs at least two nodes.");
}
if (nodes.length > 12) {
errors.push("A generated conversation is limited to 12 nodes.");
}
const structural = validateGraph(nodes);
errors.push(...structural.errors);
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<string>();
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<string>();
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 };
}