/** * Generates a whole NPC conversation from an author brief, and holds the result * to the same structure the editor enforces. * * The review gate is structural rather than procedural: this module never writes * to `npc-dialogues`. It returns a `FlowData` value, and the only thing that can * persist it is the editor's own Save through the existing field value. A draft * that is rejected or abandoned therefore cannot reach a player, because it was * never stored. * * Server-only (Payload-dependent). */ import type { Payload } from "payload"; import { effectiveModel, generatePlainText, generateStructured, resolveModel, stripCodeFences, } from "@/lib/ai/generate"; import type { AiConnection } from "@/lib/ai/generate"; import { resolveConnection } from "@/lib/ai/connections"; import { lexicalToPlaintext } from "@/lib/lexical/text"; import { deriveEdges } from "./dialogue"; import type { FlowData } from "./dialogue"; import { dialogueFlowSchema, normalizeGeneratedFlow, validateGeneratedFlow } from "./generationSchema"; import type { RawDraftNode } from "./generationSchema"; import { buildGenerationPrompt, buildRewritePrompt, composeDialogueSystemPrompt, PROMPT_VERSION, } from "./generationPrompt"; import type { DialogueBrief, DraftScope, KnownFlag, NpcContext, RewriteAction, VoiceSource, } from "./generationPrompt"; import { resolveDialogueVoice } from "./generationSettings"; import { normalizeDashes } from "./normalize"; /** How many flag keys are handed to the model. Enough to cover a real flag * vocabulary, small enough to keep the prompt inside a 9B's comfort zone. */ const MAX_KNOWN_FLAGS = 80; /** A draft that fails validation is retried once with the errors attached. Two * attempts catches a formatting slip without burning minutes on a bad brief. */ const MAX_ATTEMPTS = 2; function relationName(value: unknown): string | null { if (!value || typeof value !== "object") return null; const candidate = value as { name?: unknown; designation?: unknown; title?: unknown }; for (const key of ["name", "designation", "title"] as const) { const field = candidate[key]; if (typeof field === "string" && field.trim()) return field.trim(); } return null; } function asText(value: unknown): string | null { if (typeof value === "string") return value.trim() || null; if (value && typeof value === "object") { const text = lexicalToPlaintext(value).trim(); return text || null; } return null; } /** * Everything the prompt needs about one NPC. */ export async function loadNpcContext(payload: Payload, npcId: number): Promise { const npcDoc = await payload.findByID({ collection: "game-npcs", id: npcId, depth: 1, overrideAccess: true, }); return { name: asText(npcDoc?.name), occupation: asText(npcDoc?.occupation), location: relationName(npcDoc?.location), faction: relationName(npcDoc?.faction), bio: asText(npcDoc?.bio), levelDescription: asText(npcDoc?.levelDescription), }; } /** * The live flag vocabulary the model must stay inside. Flags are deduplicated * by lowercased key because the same key can exist once per player and once as * the global fallback. */ export async function loadKnownFlags(payload: Payload): Promise { const flagDocs = await payload.find({ collection: "player-flags", limit: 200, depth: 0, pagination: false, overrideAccess: true, select: { key: true, flagType: true }, }); const flags: KnownFlag[] = []; const seen = new Set(); for (const doc of flagDocs.docs) { const key = typeof doc.key === "string" ? doc.key.trim() : ""; if (!key) continue; const normalized = key.toLowerCase(); if (seen.has(normalized)) continue; seen.add(normalized); flags.push({ key: normalized, flagType: String(doc.flagType ?? "boolean") }); if (flags.length >= MAX_KNOWN_FLAGS) break; } return flags; } /** * Everything the prompt needs about the NPC, plus the live flag vocabulary. */ export async function buildGenerationContext( payload: Payload, npcId: number, ): Promise<{ npc: NpcContext; flags: KnownFlag[] }> { const [npc, flags] = await Promise.all([loadNpcContext(payload, npcId), loadKnownFlags(payload)]); return { npc, flags }; } /** * The per-dialogue voice override, or null when this conversation has none (or * does not exist yet, which is the normal case before the first save). * * Reading it here rather than from the browser matters: the action receives an * unsaved canvas, so the only trustworthy source is the stored document. */ export async function loadDialogueVoiceOverride( payload: Payload, dialogueId: number | null | undefined, ): Promise { if (!dialogueId || !Number.isInteger(dialogueId) || dialogueId <= 0) return null; try { const doc = await payload.findByID({ collection: "npc-dialogues", id: dialogueId, depth: 0, overrideAccess: true, select: { voiceOverride: true }, }); const value = (doc as { voiceOverride?: unknown } | null)?.voiceOverride; return typeof value === "string" && value.trim() ? value.trim() : null; } catch { // A missing document (deleted mid-edit) must not block drafting: the global // or built-in voice is still a valid configuration. return null; } } export interface DraftRunnerInput { prompt: string; system: string; schema: Record; /** The resolved connection, or null for the env defaults. */ connection?: AiConnection | null; } export interface DraftRunnerResult { object: { nodes?: RawDraftNode[] }; truncated: boolean; } /** * The model call, injectable so tests exercise the validate-and-retry logic * without a network round trip (and without the model host being reachable). */ export type DraftRunner = (input: DraftRunnerInput) => Promise; export interface DraftOutcome { ok: boolean; /** Present only when `ok` is true. Never persisted by this module. */ flow?: FlowData; /** * Why the draft was rejected, in the model's own terms. Safe to show the * author: these name nodes and flags, never raw output. */ errors: string[]; attempts: number; truncated: boolean; model: string; promptVersion: string; /** Which voice shaped the prompt: built-in, the global setting, or this dialogue. */ promptSource: VoiceSource; /** The settings revision used, or null for the built-in voice. */ promptRevision: number | null; /** The admin connection used, or null for the env defaults. */ connectionLabel: string | null; } /** * Ceiling for one draft attempt. A draft is a few hundred lines of JSON, so a * model that has not produced it in four minutes is not going to; the retry * after a validation failure gets its own window. Without this the only bound * was the ten-minute default sized for long prose. */ const DRAFT_TIMEOUT_MS = 240_000; const defaultRunner: DraftRunner = (input) => generateStructured<{ nodes?: RawDraftNode[] }>({ ...input, model: effectiveModel(input.connection), maxTokens: 4000, temperature: 0.8, timeoutMs: DRAFT_TIMEOUT_MS, }); /** * Drafts one conversation. Retries once, feeding the validator's complaints back * to the model, then gives up rather than handing the editor a graph it would * have to fix by hand. */ export async function generateDialogueDraft( payload: Payload, input: { npcId: number; brief: DialogueBrief; dialogueId?: number | null; /** Whole conversation, or one branch to splice into an existing one. */ scope?: DraftScope; /** Fragment only: what the conversation is doing where the branch attaches. */ insertionHint?: string | null; }, run: DraftRunner = defaultRunner, ): Promise { const scope = input.scope ?? "full"; const { npc, flags } = await buildGenerationContext(payload, input.npcId); const basePrompt = buildGenerationPrompt({ npc, brief: input.brief, flags, scope, insertionHint: input.insertionHint, }); const knownKeys = flags.map((flag) => flag.key); // One connection per draft, resolved alongside the voice, so a retry cannot // silently land on a different provider than the attempt it is correcting. const connection = await resolveConnection(payload, "dialogue-draft"); const model = effectiveModel(connection); // The voice is resolved once per draft, not per attempt, so both attempts use // the same instruction and a retry cannot silently change register. const dialogueVoice = await loadDialogueVoiceOverride(payload, input.dialogueId); const resolved = await resolveDialogueVoice(payload, { dialogueVoice }); const system = composeDialogueSystemPrompt({ voice: resolved.voice, extraRules: resolved.extraRules, scope, }); let errors: string[] = []; for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt += 1) { const prompt = attempt === 1 ? basePrompt : `${basePrompt} YOUR PREVIOUS ATTEMPT WAS REJECTED ${errors.map((error) => `- ${error}`).join("\n")} Fix every problem above and return the whole ${ scope === "fragment" ? "branch" : "conversation" } again.`; let parsed: DraftRunnerResult; try { parsed = await run({ prompt, system, schema: dialogueFlowSchema, connection }); } catch (error) { errors = [ `The model's output could not be read as a conversation: ${ error instanceof Error ? error.message : "unknown error" }`, ]; continue; } const rawNodes = Array.isArray(parsed.object?.nodes) ? parsed.object.nodes : []; const normalized = normalizeGeneratedFlow(rawNodes); const validation = validateGeneratedFlow(normalized.nodes, knownKeys, { scope }); const combined = [...normalized.errors, ...validation.errors]; if (combined.length === 0) { return { ok: true, flow: { nodes: normalized.nodes, edges: deriveEdges(normalized.nodes) }, errors: [], attempts: attempt, truncated: parsed.truncated, model, promptVersion: PROMPT_VERSION, promptSource: resolved.source, promptRevision: resolved.revision, connectionLabel: connection?.label ?? null, }; } errors = combined; } // A custom prompt is the one failure cause the author can actually fix, so name // it instead of letting a bad voice block look like a broken model. if (resolved.source !== "builtin") { errors = [ ...errors, `This conversation used the ${resolved.source === "dialogue" ? "dialogue's own" : "global"} voice. If drafts keep failing, check that setting before blaming the model.`, ]; } return { ok: false, errors, attempts: MAX_ATTEMPTS, truncated: false, model, promptVersion: PROMPT_VERSION, promptSource: resolved.source, promptRevision: resolved.revision, connectionLabel: connection?.label ?? null, }; } /** Strips the quoting and prefixes a chat model adds despite being told not to. */ function cleanRewrittenLine(text: string): string { let out = stripCodeFences(text).trim(); const quoted = /^["\u201c']([\s\S]*)["\u201d']$/.exec(out); if (quoted) out = quoted[1].trim(); return normalizeDashes(out.replace(/^(replacement|rewritten line)\s*:\s*/i, "").trim()); } export type LineRunner = (input: { prompt: string; system: string; model: string; /** The resolved connection, or null for the env defaults. */ connection?: AiConnection | null; }) => Promise<{ text: string }>; const defaultLineRunner: LineRunner = ({ prompt, system, model, connection }) => generatePlainText(prompt, system, model, { maxTokens: 400, temperature: 0.8, connection, }); export interface LineRewriteOutcome { ok: boolean; /** The replacement line. Only meaningful when `ok` is true. */ text: string; error?: string; } /** * Rewrites one authored line in place. The result is handed back to the calling * textarea and is committed by the node dialog's own Save, so this cannot alter * a stored conversation either. * * `run` is injectable so tests cover the parsing and the guards without a * network round trip. */ export async function rewriteDialogueLine( payload: Payload, input: { npcId: number; action: RewriteAction; text: string; nodeType: string; previousLine?: string | null; dialogueId?: number | null; }, run: LineRunner = defaultLineRunner, ): Promise { const text = input.text?.trim() ?? ""; if (!text) { return { ok: false, text: "", error: "Write a line first, then ask the model to work on it." }; } const npc = await loadNpcContext(payload, input.npcId); const dialogueVoice = await loadDialogueVoiceOverride(payload, input.dialogueId); const resolved = await resolveDialogueVoice(payload, { dialogueVoice }); const { system, prompt } = buildRewritePrompt({ action: input.action, text, npc, nodeType: input.nodeType, previousLine: input.previousLine, voice: resolved.voice, }); // Rewrites are prose only, so they can point at a cheaper model than drafting. const connection = await resolveConnection(payload, "dialogue-line"); const result = await run({ prompt, system, model: effectiveModel(connection), connection, }); const cleaned = cleanRewrittenLine(result.text ?? ""); if (!cleaned) { return { ok: false, text: "", error: "The model returned nothing usable. Try again." }; } return { ok: true, text: cleaned }; }