diff --git a/docs/npc-dialogue-ai.md b/docs/npc-dialogue-ai.md new file mode 100644 index 00000000..123eef63 --- /dev/null +++ b/docs/npc-dialogue-ai.md @@ -0,0 +1,138 @@ +# AI-assisted NPC dialogue drafting + +Two authoring accelerators for NPC conversations, both fed by the local Unsloth +model and both behind the same review gate: **nothing the model writes is stored +until an author saves the dialogue document.** + +## Why the gate is structural + +`npc-dialogues.flowData` is the only source of what a player can see. The runtime +walks that stored graph server-side (`triggerNpcDialogueEvent` looks each node up +by id from the document), so text that exists only in the editor's unsaved form +state is unreachable. Neither feature below writes to `npc-dialogues`: + +- `generateNpcDialogueDraft` returns a `FlowData` value to the browser. +- `rewriteNpcDialogueLine` returns a string to the textarea it came from. + +Both land in the editor's field state through the existing `serialize` / +`patch` paths, so the document becomes dirty exactly as if the author had typed +the text. Saving is the publish step; there is no separate status field, because +an unsaved draft cannot leak. + +## The two surfaces + +### Draft a conversation + +Toolbar **Generate** button in the flow editor, enabled once the dialogue has a +`npc`. It opens a form (`GenerateDraftDialog.tsx`): + +| Field | Notes | +|---|---| +| Purpose | greet, quest hook, warning, rumor, refusal, recruitment pitch | +| What the player should learn or do | required, at least 8 characters | +| Outcome | none, set a player flag, notify the player | +| Flag to set | dropdown of real `player-flags` keys, only when the outcome needs one | +| Tone | clipped, tired, bureaucratic, hostile, friendly | +| Length | about 3, 4 or 6 nodes | +| Must include | optional detail the lines have to mention | + +The result replaces the canvas contents, is fitted into view, and raises an +unsaved-draft banner. If the model hit its token cap the banner says so, because +a truncated draft is missing its ending and must not be mistaken for a complete +one. + +### Rewrite one line + +Under the line, lead-in, choice-label and closing fields: **Rewrite**, +**Shorten**, **Sharpen**. The request carries the NPC's name, occupation, faction +and bio, the node type, the current line, and the line that immediately precedes +it (found by walking the incoming hop), so a rewrite does not restate its +neighbour. The replacement goes into the node dialog's draft state and is +committed by that dialog's Save. + +## The prompt contract + +`src/lib/npc-dialogue/generationPrompt.ts` owns the wording; bump +`PROMPT_VERSION` when it changes, because saved provenance records it. + +The system prompt states the register (soldier with limited patience, concrete, +no exclamation marks, no em-dashes), the structural rules (exactly one start +node, every hop resolves, choice nodes need labels, no delay nodes), the field +conventions (unused fields are empty strings or arrays), and the state rules. +The user turn adds the NPC, the brief, the **live flag vocabulary**, and one +short worked example. The example matters more than any instruction for a 9B +model: it fixes the id convention, the empty-string convention and the register +in one shot. + +### Effects are restricted + +The JSON schema only offers `none`, `notify` and `flag`. `emit`, `reward` and +`discord` are absent from the schema, and `validateGeneratedFlow` rejects them +again if a model smuggles one through an unknown key. Those write game state or +post to Discord and stay author-only. + +### Flags must already exist + +Every `{{token}}`, condition key and flag effect is checked against the real +`player-flags` keys (`loadKnownFlags`, deduplicated by lowercased key and capped +at 80). A branch on a flag that does not exist never fires, so inventing one +produces a conversation that silently dead-ends. The check is skipped entirely +when the flag table is empty, otherwise every draft would be rejected for +referencing anything at all. + +## Validation and retry + +`validateGeneratedFlow` (in `generationSchema.ts`, pure and unit-tested) runs +`validateGraph` for structure, then adds the draft-specific rules. A rejected +draft is retried **once** with the validator's complaints appended to the prompt. +A second failure returns the errors and changes nothing: the editor never +receives a graph it would have to repair by hand. + +`normalizeGeneratedFlow` assembles `DialogueNodeData` from the flat schema +(dropping empty placeholders), rejects duplicate ids, and lays nodes out left to +right by breadth from the start node. + +## Provenance + +`npc-dialogues.generation` (`model`, `promptVersion`, `attempts`, `generatedAt`, +`brief`) is written when a draft lands and persisted by the save that accepts it. +It describes the draft that was accepted, not every attempt. + +**Deliberate omission:** the model's raw pre-normalization output is not stored. +It duplicates the graph, is mostly placeholder empty strings, and would be +unreadable. If rejected-attempt auditing is ever wanted, the right home is a +separate generations log collection, not a field on the dialogue. + +## Models + +Everything resolves through `src/lib/ai/generate.ts`: + +- `MODEL_ID` (`unsloth/Ornith-1.0-9B-GGUF`) is a stable key in the Compose + model enum; changing it needs a migration. +- `UNSLOTH_MODEL` is what is actually served. Neither dialogue surface names a + model, so pointing this at a different GGUF changes Compose and dialogue + drafting together. +- `UNSLOTH_MODEL_STRUCTURED` (optional, unset) overrides the model for + structured work only, for the case where prose and graph generation want + different GGUFs. + +`reasoning_effort: "none"` is sent on every request. Ornith is a reasoning model +and with a small token budget its reasoning block consumes the whole allowance, +leaving `content` empty. + +## Tests + +`tests/int/npc-dialogue-generation.int.spec.ts` covers the normalizer, the +validator (unknown flags, invented effects, dangling hops, missing keys), the +retry path, the give-up path, truncation reporting, and the rewrite parser (quote +stripping, dash normalisation, empty completion). The model call is injected, so +none of these tests need the model host. + +## Changing the prompts safely + +1. Edit `generationPrompt.ts`, bump `PROMPT_VERSION`. +2. Run the integration spec (it pins the observable behaviour, not the wording). +3. Draft one conversation against a real contact and read the lines. + +A 9B model drifts badly past about ten nodes. Keep generated drafts short and let +authors extend the graph by hand. diff --git a/src/app/(frontend)/personnel/contacts/[id]/actions.ts b/src/app/(frontend)/personnel/contacts/[id]/actions.ts index 9757db6a..7ac09070 100644 --- a/src/app/(frontend)/personnel/contacts/[id]/actions.ts +++ b/src/app/(frontend)/personnel/contacts/[id]/actions.ts @@ -13,6 +13,22 @@ import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from " import { markNodeRead } from "@/lib/npc-dialogue/states"; import { resolveAttachments } from "@/lib/npc-dialogue/attachments"; import { hasPermission } from "@/utils/access-control/hasPermission"; +import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation"; +import { + BRIEF_OUTCOMES, + BRIEF_PURPOSES, + BRIEF_TONES, + DRAFT_SIZES, + REWRITE_ACTIONS, +} from "@/lib/npc-dialogue/generationPrompt"; +import type { + BriefOutcome, + BriefPurpose, + BriefTone, + DialogueBrief, + DraftSize, + RewriteAction, +} from "@/lib/npc-dialogue/generationPrompt"; import type { ChoiceGate, DialogueFlagOp, @@ -396,3 +412,190 @@ export async function uploadNpcDialogueAttachment( return { success: false, error: message }; } } + +/** What a successful draft hands back to the editor. */export interface GeneratedDialogueDraft { + /** The graph to drop into the canvas. Never persisted by the server action. */ + flow: FlowData; + attempts: number; + model: string; + promptVersion: string; + /** True when the model hit its token cap, so the tail of the draft may be missing. */ + truncated: boolean; +} + +/** + * The flag keys an author may reference in a generated conversation. Mirrors + * the vocabulary `generateDialogueDraft` hands the model, so the dropdown and + * the prompt cannot disagree. + */ +export async function listDialogueFlagKeys(): Promise< + ActionResult<{ key: string; flagType: string }[]> +> { + try { + const { payload, user } = await authenticate(); + if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { + return { success: false, error: "You do not have permission to edit conversations." }; + } + + const res = await payload.find({ + collection: "player-flags", + limit: 200, + depth: 0, + pagination: false, + overrideAccess: true, + select: { key: true, flagType: true }, + }); + + const seen = new Set(); + const keys: { key: string; flagType: string }[] = []; + for (const doc of res.docs) { + const key = typeof doc.key === "string" ? doc.key.trim().toLowerCase() : ""; + if (!key || seen.has(key)) continue; + seen.add(key); + keys.push({ key, flagType: String(doc.flagType ?? "boolean") }); + } + keys.sort((a, b) => a.key.localeCompare(b.key)); + + return { success: true, data: keys }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "Unauthorized") { + return { success: false, error: "You must be logged in." }; + } + return { success: false, error: message }; + } +} + +/** + * Drafts a conversation for one contact from an author brief. + * + * This does not touch the database: the draft comes back to the editor, lands in + * the unsaved canvas, and only reaches players if the author saves the document. + * That is the whole review gate, so keep this action write-free. + */ +export async function generateNpcDialogueDraft( + npcId: number, + brief: DialogueBrief, +): Promise> { + try { + const { payload, user } = await authenticate(); + + if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { + return { success: false, error: "You do not have permission to edit conversations." }; + } + if (!Number.isInteger(npcId) || npcId <= 0) { + return { success: false, error: "Save this conversation against a contact first." }; + } + + // Validate the brief before spending a model call on it: a vague brief + // produces a vague draft, and the author cannot tell which was at fault. + const goal = brief.goal?.trim() ?? ""; + if (goal.length < 8) { + return { success: false, error: "Describe what the player should learn or do." }; + } + if (!BRIEF_PURPOSES.includes(brief.purpose as BriefPurpose)) { + return { success: false, error: "Pick a purpose for the conversation." }; + } + if (!BRIEF_TONES.includes(brief.tone as BriefTone)) { + return { success: false, error: "Pick a tone for the conversation." }; + } + if (!BRIEF_OUTCOMES.includes(brief.outcome as BriefOutcome)) { + return { success: false, error: "Pick an outcome for the conversation." }; + } + if (!DRAFT_SIZES.includes(brief.size as DraftSize)) { + return { success: false, error: "Pick a conversation length." }; + } + if (brief.outcome === "set-flag" && !brief.flagKey?.trim()) { + return { success: false, error: "Choose which flag the conversation should set." }; + } + + const outcome = await generateDialogueDraft(payload, { + npcId, + brief: { ...brief, goal }, + }); + + if (!outcome.ok || !outcome.flow) { + return { + success: false, + error: + outcome.errors.slice(0, 3).join(" ") || + "The model could not produce a usable conversation. Try a more specific brief.", + }; + } + + return { + success: true, + data: { + flow: outcome.flow, + attempts: outcome.attempts, + model: outcome.model, + promptVersion: outcome.promptVersion, + truncated: outcome.truncated, + }, + }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "Unauthorized") { + return { success: false, error: "You must be logged in." }; + } + return { success: false, error: message }; + } +} + +/** + * Rewrites one line of an authored node in place. + * + * Like the draft action this writes nothing: the replacement comes back to the + * node dialog's textarea, and the dialog's own Save is what commits it. + */ +export async function rewriteNpcDialogueLine( + npcId: number, + input: { + action: RewriteAction; + text: string; + nodeType: string; + previousLine?: string; + }, +): Promise> { + try { + const { payload, user } = await authenticate(); + + if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { + return { success: false, error: "You do not have permission to edit conversations." }; + } + if (!Number.isInteger(npcId) || npcId <= 0) { + return { success: false, error: "Save this conversation against a contact first." }; + } + if (!REWRITE_ACTIONS.includes(input.action)) { + return { success: false, error: "Unknown rewrite action." }; + } + + const text = input.text?.trim() ?? ""; + if (!text) { + return { success: false, error: "Write a line first, then ask the model to work on it." }; + } + if (text.length > 2000) { + return { success: false, error: "That line is too long to rewrite. Trim it first." }; + } + + const outcome = await rewriteDialogueLine(payload, { + npcId, + action: input.action, + text, + nodeType: input.nodeType, + previousLine: input.previousLine, + }); + + if (!outcome.ok) { + return { success: false, error: outcome.error ?? "The model returned nothing usable." }; + } + + return { success: true, data: { text: outcome.text } }; + } catch (error) { + const message = error instanceof Error ? error.message : "Unknown error"; + if (message === "Unauthorized") { + return { success: false, error: "You must be logged in." }; + } + return { success: false, error: message }; + } +} diff --git a/src/collections/game/NpcDialogues.ts b/src/collections/game/NpcDialogues.ts index 42185e65..27c24148 100644 --- a/src/collections/game/NpcDialogues.ts +++ b/src/collections/game/NpcDialogues.ts @@ -110,5 +110,45 @@ export const NpcDialogues: CollectionConfig = { }, ], }, + { + name: "generation", + type: "group", + label: "AI Draft Provenance", + admin: { + readOnly: true, + description: + "Which model drafted this conversation and from what brief. Written when the document is saved, so it describes the draft that was accepted, not every attempt. Editing the flow by hand afterwards does not clear it.", + }, + fields: [ + { + name: "model", + type: "text", + admin: { description: "Served model id that produced the draft.", readOnly: true }, + }, + { + name: "promptVersion", + type: "text", + admin: { description: "Prompt contract version, so an old draft is comparable.", readOnly: true }, + }, + { + name: "attempts", + type: "number", + admin: { description: "1 when the first output validated, 2 when it was retried.", readOnly: true }, + }, + { + name: "generatedAt", + type: "date", + admin: { description: "When the draft was generated.", readOnly: true }, + }, + { + name: "brief", + type: "json", + admin: { + description: "The form brief the author filled in when drafting.", + readOnly: true, + }, + }, + ], + }, ], }; diff --git a/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx b/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx new file mode 100644 index 00000000..c3e371ef --- /dev/null +++ b/src/components/admin/npc-dialogue/GenerateDraftDialog.tsx @@ -0,0 +1,324 @@ +"use client"; + +import { useCallback, useEffect, useState } from "react"; +import { Loader2, Sparkles } from "lucide-react"; + +import { Button } from "@/components/ui/button"; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog"; +import { Input } from "@/components/ui/input"; +import { Label } from "@/components/ui/label"; +import { + Select, + SelectContent, + SelectItem, + SelectTrigger, + SelectValue, +} from "@/components/ui/select"; +import { Textarea } from "@/components/ui/textarea"; + +import { + BRIEF_OUTCOMES, + BRIEF_PURPOSES, + BRIEF_TONES, + DRAFT_SIZES, + OUTCOME_LABELS, + PURPOSE_LABELS, + TONE_LABELS, +} from "@/lib/npc-dialogue/generationPrompt"; +import type { + BriefOutcome, + BriefPurpose, + BriefTone, + DialogueBrief, + DraftSize, +} from "@/lib/npc-dialogue/generationPrompt"; +import { + generateNpcDialogueDraft, + listDialogueFlagKeys, +} from "@/app/(frontend)/personnel/contacts/[id]/actions"; +import type { GeneratedDialogueDraft } from "@/app/(frontend)/personnel/contacts/[id]/actions"; + +interface GenerateDraftDialogProps { + readonly open: boolean; + readonly onOpenChange: (open: boolean) => void; + /** The contact this conversation belongs to. Null until the doc is saved. */ + readonly npcId: number | null; + /** Nodes already on the canvas, so the author is warned about replacement. */ + readonly nodeCount: number; + /** Receives the draft and the brief that produced it. The caller drops the + * graph into the unsaved canvas and records provenance from the brief. */ + readonly onGenerated: (result: GeneratedDialogueDraft, brief: DialogueBrief) => void; +} + +interface FlagOption { + key: string; + flagType: string; +} + +const INITIAL_BRIEF: DialogueBrief = { + purpose: "greet", + goal: "", + outcome: "none", + flagKey: "", + tone: "clipped", + size: 4, + mustInclude: "", +}; + +/** + * The brief that seeds a generated conversation. + * + * The fields are deliberately narrow: a 9B model asked for "a conversation" with + * no shape produces something generic, while a brief that names the purpose, the + * takeaway and the outcome produces something an author can edit rather than + * rewrite. Nothing here reaches the database. Cancelling leaves the canvas as it + * was, and generating only touches unsaved field state. + */ +export function GenerateDraftDialog({ + open, + onOpenChange, + npcId, + nodeCount, + onGenerated, +}: GenerateDraftDialogProps) { + const [brief, setBrief] = useState(INITIAL_BRIEF); + const [flags, setFlags] = useState([]); + const [flagsError, setFlagsError] = useState(null); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(null); + + const set = useCallback((key: K, value: DialogueBrief[K]) => { + setBrief((current) => ({ ...current, [key]: value })); + }, []); + + // The flag list is only needed to populate the outcome dropdown, so it is + // fetched when the dialog opens rather than on every editor render. + useEffect(() => { + if (!open) return; + let cancelled = false; + void (async () => { + const res = await listDialogueFlagKeys(); + if (cancelled) return; + if (res.success && res.data) { + setFlags(res.data); + setFlagsError(null); + } else { + setFlags([]); + setFlagsError(res.error ?? "Could not load player flags."); + } + })(); + return () => { + cancelled = true; + }; + }, [open]); + + useEffect(() => { + if (open) setError(null); + }, [open]); + + async function handleGenerate() { + if (npcId === null) { + setError("Save this conversation against a contact first."); + return; + } + const goal = brief.goal.trim(); + if (goal.length < 8) { + setError("Describe what the player should learn or do."); + return; + } + if (brief.outcome === "set-flag" && !brief.flagKey) { + setError("Choose which flag the conversation should set."); + return; + } + + setBusy(true); + setError(null); + try { + const res = await generateNpcDialogueDraft(npcId, { ...brief, goal }); + if (!res.success || !res.data) { + setError(res.error ?? "The model could not produce a usable conversation."); + return; + } + onGenerated(res.data, { ...brief, goal }); + onOpenChange(false); + } finally { + setBusy(false); + } + } + + return ( + (busy ? undefined : onOpenChange(next))}> + + + + + Draft a conversation + + + Describe the beat you want. The model writes a flowchart into the canvas as an unsaved + draft, so nothing reaches players until you review it and save. + + + +
+
+
+ + +
+ +
+ + +
+
+ +
+ +