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
This commit is contained in:
parent
9f192a8159
commit
4264431e4d
18 changed files with 48521 additions and 93 deletions
138
docs/npc-dialogue-ai.md
Normal file
138
docs/npc-dialogue-ai.md
Normal file
|
|
@ -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.
|
||||
|
|
@ -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<string>();
|
||||
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<ActionResult<GeneratedDialogueDraft>> {
|
||||
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<ActionResult<{ text: 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." };
|
||||
}
|
||||
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 };
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
|
|||
324
src/components/admin/npc-dialogue/GenerateDraftDialog.tsx
Normal file
324
src/components/admin/npc-dialogue/GenerateDraftDialog.tsx
Normal file
|
|
@ -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<DialogueBrief>(INITIAL_BRIEF);
|
||||
const [flags, setFlags] = useState<FlagOption[]>([]);
|
||||
const [flagsError, setFlagsError] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const set = useCallback(<K extends keyof DialogueBrief>(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 (
|
||||
<Dialog open={open} onOpenChange={(next) => (busy ? undefined : onOpenChange(next))}>
|
||||
<DialogContent className="sm:max-w-lg">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Sparkles className="size-4" />
|
||||
Draft a conversation
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
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.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-purpose">Purpose</Label>
|
||||
<Select
|
||||
value={brief.purpose}
|
||||
onValueChange={(value) => set("purpose", value as BriefPurpose)}
|
||||
>
|
||||
<SelectTrigger id="draft-purpose">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BRIEF_PURPOSES.map((purpose) => (
|
||||
<SelectItem key={purpose} value={purpose}>
|
||||
{PURPOSE_LABELS[purpose]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-tone">Tone</Label>
|
||||
<Select value={brief.tone} onValueChange={(value) => set("tone", value as BriefTone)}>
|
||||
<SelectTrigger id="draft-tone">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BRIEF_TONES.map((tone) => (
|
||||
<SelectItem key={tone} value={tone}>
|
||||
{TONE_LABELS[tone]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-goal">What should the player learn or do?</Label>
|
||||
<Textarea
|
||||
id="draft-goal"
|
||||
value={brief.goal}
|
||||
onChange={(e) => set("goal", e.target.value)}
|
||||
placeholder="Learn that the quartermaster is short on rifle magazines, and that the next resupply is delayed."
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-3">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-outcome">Outcome</Label>
|
||||
<Select
|
||||
value={brief.outcome}
|
||||
onValueChange={(value) => set("outcome", value as BriefOutcome)}
|
||||
>
|
||||
<SelectTrigger id="draft-outcome">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{BRIEF_OUTCOMES.map((outcome) => (
|
||||
<SelectItem key={outcome} value={outcome}>
|
||||
{OUTCOME_LABELS[outcome]}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-size">Length</Label>
|
||||
<Select
|
||||
value={String(brief.size)}
|
||||
onValueChange={(value) => set("size", Number(value) as DraftSize)}
|
||||
>
|
||||
<SelectTrigger id="draft-size">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{DRAFT_SIZES.map((size) => (
|
||||
<SelectItem key={size} value={String(size)}>
|
||||
About {size} nodes
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{brief.outcome === "set-flag" && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-flag">Flag to set</Label>
|
||||
<Select value={brief.flagKey} onValueChange={(value) => set("flagKey", value)}>
|
||||
<SelectTrigger id="draft-flag">
|
||||
<SelectValue placeholder="Choose a flag" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{flags.map((flag) => (
|
||||
<SelectItem key={flag.key} value={flag.key}>
|
||||
{flag.key} ({flag.flagType})
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{flagsError ??
|
||||
(flags.length === 0
|
||||
? "No player flags exist yet, so nothing can be set."
|
||||
: "Only existing keys work; a key that does not exist never fires.")}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label htmlFor="draft-must-include">Must include (optional)</Label>
|
||||
<Input
|
||||
id="draft-must-include"
|
||||
value={brief.mustInclude}
|
||||
onChange={(e) => set("mustInclude", e.target.value)}
|
||||
placeholder="A place, a name, or a number the line has to mention"
|
||||
/>
|
||||
</div>
|
||||
|
||||
{nodeCount > 0 && (
|
||||
<p className="rounded-md border border-amber-900/50 bg-amber-950/40 px-3 py-2 text-xs text-amber-200">
|
||||
Generating replaces the {nodeCount} node{nodeCount === 1 ? "" : "s"} on the canvas. The
|
||||
document is not saved until you save it, so closing without saving undoes this.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{error && <p className="text-sm text-red-400">{error}</p>}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} disabled={busy}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={() => void handleGenerate()} disabled={busy}>
|
||||
{busy ? (
|
||||
<>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
Drafting...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="size-4" />
|
||||
Generate
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
94
src/components/admin/npc-dialogue/LineAssist.tsx
Normal file
94
src/components/admin/npc-dialogue/LineAssist.tsx
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Loader2, Sparkles } from "lucide-react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
import { rewriteNpcDialogueLine } from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
import { REWRITE_ACTIONS, REWRITE_LABELS } from "@/lib/npc-dialogue/generationPrompt";
|
||||
import type { RewriteAction } from "@/lib/npc-dialogue/generationPrompt";
|
||||
|
||||
interface LineAssistProps {
|
||||
/** The contact being written for. Null until the document is saved. */
|
||||
readonly npcId: number | null;
|
||||
readonly nodeType: string;
|
||||
/** Current text of the field this control sits under. */
|
||||
readonly value: string;
|
||||
/** The line before this one, so the model does not restate it. */
|
||||
readonly previousLine?: string | null;
|
||||
/** Receives the replacement, which the caller writes into its draft state. */
|
||||
readonly onChange: (next: string) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rewrite controls for one authored line.
|
||||
*
|
||||
* The model's replacement goes straight into the caller's draft state, so it is
|
||||
* undone by the same means as typing (and committed only by the node dialog's
|
||||
* Save). Nothing here can alter a stored conversation.
|
||||
*/
|
||||
export function LineAssist({
|
||||
npcId,
|
||||
nodeType,
|
||||
value,
|
||||
previousLine,
|
||||
onChange,
|
||||
}: LineAssistProps) {
|
||||
const [busyAction, setBusyAction] = useState<RewriteAction | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const disabled = npcId === null || busyAction !== null || value.trim().length === 0;
|
||||
|
||||
async function run(action: RewriteAction) {
|
||||
if (npcId === null) return;
|
||||
setBusyAction(action);
|
||||
setError(null);
|
||||
try {
|
||||
const res = await rewriteNpcDialogueLine(npcId, {
|
||||
action,
|
||||
text: value,
|
||||
nodeType,
|
||||
previousLine: previousLine ?? undefined,
|
||||
});
|
||||
if (res.success && res.data) {
|
||||
onChange(res.data.text);
|
||||
} else {
|
||||
setError(res.error ?? "The model returned nothing usable.");
|
||||
}
|
||||
} finally {
|
||||
setBusyAction(null);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<span className="inline-flex items-center gap-1 text-[9px] uppercase tracking-wider text-white/35">
|
||||
<Sparkles size={10} />
|
||||
AI
|
||||
</span>
|
||||
{REWRITE_ACTIONS.map((action) => (
|
||||
<Button
|
||||
key={action}
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
title={
|
||||
npcId === null
|
||||
? "Save this conversation against a contact first"
|
||||
: `${REWRITE_LABELS[action]} this line`
|
||||
}
|
||||
onClick={() => void run(action)}
|
||||
className="h-6 border-white/15 px-2 text-[10px] text-white/70 hover:bg-zinc-800 disabled:opacity-30"
|
||||
>
|
||||
{busyAction === action ? <Loader2 className="size-3 animate-spin" /> : null}
|
||||
{REWRITE_LABELS[action]}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
{error && <p className="text-[10px] text-red-400">{error}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
"use client";
|
||||
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { ChevronDownIcon, ChevronUpIcon, XIcon } from "lucide-react";
|
||||
|
||||
import {
|
||||
|
|
@ -27,9 +27,10 @@ import type {
|
|||
NpcDialogueEffect,
|
||||
NpcDialogueNodeType,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { conditionSummary, EFFECT_TYPES } from "@/lib/npc-dialogue/dialogue";
|
||||
import { conditionSummary, EFFECT_TYPES, outgoingHops } from "@/lib/npc-dialogue/dialogue";
|
||||
import { reorderChoice } from "@/lib/npc-dialogue/reorder";
|
||||
import { MarkupEditor } from "./MarkupEditor";
|
||||
import { LineAssist } from "./LineAssist";
|
||||
import { uploadNpcDialogueAttachment } from "@/app/(frontend)/personnel/contacts/[id]/actions";
|
||||
|
||||
interface NodeEditDialogProps {
|
||||
|
|
@ -39,6 +40,8 @@ interface NodeEditDialogProps {
|
|||
readonly open: boolean;
|
||||
readonly onOpenChange: (open: boolean) => void;
|
||||
readonly onSave: (nodeId: string, data: DialogueNodeData) => void;
|
||||
/** The contact this flow belongs to, for the per-line AI controls. */
|
||||
readonly npcId: number | null;
|
||||
}
|
||||
|
||||
const EFFECT_LABELS: Record<NpcDialogueEffect["type"], string> = {
|
||||
|
|
@ -123,9 +126,27 @@ function nodeLabel(node: DialogueNode): string {
|
|||
}
|
||||
|
||||
/** Inline editor for a single dialogue node's data. */
|
||||
export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: NodeEditDialogProps) {
|
||||
export function NodeEditDialog({
|
||||
node,
|
||||
allNodes,
|
||||
open,
|
||||
onOpenChange,
|
||||
onSave,
|
||||
npcId,
|
||||
}: NodeEditDialogProps) {
|
||||
const [draft, setDraft] = useState<DialogueNodeData | null>(null);
|
||||
|
||||
// The line immediately before this node, so a rewrite does not restate it.
|
||||
// Reads the incoming hop's source rather than a separate "previous" prop,
|
||||
// because the graph already knows and nothing else does.
|
||||
const previousLine = useMemo(() => {
|
||||
if (!node) return null;
|
||||
const source = allNodes.find((candidate) =>
|
||||
outgoingHops(candidate).some((hop) => hop?.target === node.id),
|
||||
);
|
||||
return source?.data.body?.trim() || source?.data.leadIn?.trim() || null;
|
||||
}, [node, allNodes]);
|
||||
|
||||
// Users for the "Specific user" flag target. Fetched once per open; the
|
||||
// admin context is already authenticated, so cookie auth is enough.
|
||||
const [users, setUsers] = useState<{ id: number; username: string }[]>([]);
|
||||
|
|
@ -260,6 +281,16 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
textareaRef={lineRef}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
/>
|
||||
<LineAssist
|
||||
npcId={npcId}
|
||||
nodeType={node.type}
|
||||
value={draft.body ?? ""}
|
||||
previousLine={previousLine}
|
||||
onChange={(next) => {
|
||||
patch({ body: next || undefined });
|
||||
autoSizeLine();
|
||||
}}
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Line breaks are kept. **bold**, *italic*, {`{red}color{/}`} and {'`code`'} render
|
||||
in the conversation. Colors take a friendly name (red, amber, cyan, emerald,
|
||||
|
|
@ -285,6 +316,13 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
rows={2}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
/>
|
||||
<LineAssist
|
||||
npcId={npcId}
|
||||
nodeType={node.type}
|
||||
value={draft.leadIn ?? ""}
|
||||
previousLine={previousLine}
|
||||
onChange={(next) => patch({ leadIn: next || undefined })}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
|
|
@ -336,6 +374,15 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
placeholder="How do you respond?"
|
||||
className="bg-zinc-800 border-white/20 text-white placeholder:text-white/30"
|
||||
/>
|
||||
<LineAssist
|
||||
npcId={npcId}
|
||||
nodeType="choice"
|
||||
value={choice.label ?? ""}
|
||||
previousLine={previousLine}
|
||||
onChange={(next) =>
|
||||
setChoice(index, { ...choice, label: next || undefined })
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="text-[9px] uppercase tracking-wider text-white/40">
|
||||
|
|
@ -746,6 +793,13 @@ export function NodeEditDialog({ node, allNodes, open, onOpenChange, onSave }: N
|
|||
rows={3}
|
||||
className="rounded bg-zinc-800 border border-white/20 px-2 py-1.5 text-sm text-white placeholder:text-white/30 resize-y"
|
||||
/>
|
||||
<LineAssist
|
||||
npcId={npcId}
|
||||
nodeType={node.type}
|
||||
value={draft.closing ?? ""}
|
||||
previousLine={previousLine}
|
||||
onChange={(next) => patch({ closing: next || undefined })}
|
||||
/>
|
||||
<p className="text-[10px] text-white/40">
|
||||
Flag values insert as {'{{flag_key}}'}; markup renders like dialogue lines.
|
||||
</p>
|
||||
|
|
|
|||
|
|
@ -22,9 +22,10 @@ import {
|
|||
type XYPosition,
|
||||
} from "@xyflow/react";
|
||||
import "@xyflow/react/dist/style.css";
|
||||
import { Magnet, Maximize2, Minimize2 } from "lucide-react";
|
||||
import { Magnet, Maximize2, Minimize2, Sparkles } from "lucide-react";
|
||||
|
||||
import { useField } from "@payloadcms/ui";
|
||||
import { useDocumentInfo, useField } from "@payloadcms/ui";
|
||||
import type { NpcDialogue } from "@/payload-types";
|
||||
|
||||
import type {
|
||||
DialogueEdge,
|
||||
|
|
@ -34,9 +35,10 @@ import type {
|
|||
NpcDialogueNodeType,
|
||||
} from "@/lib/npc-dialogue/dialogue";
|
||||
import { deriveEdges, removeHopFromNode, validateGraph } from "@/lib/npc-dialogue/dialogue";
|
||||
import type { DialogueBrief } from "@/lib/npc-dialogue/generationPrompt";
|
||||
import type { RouteRect } from "@/lib/flow-edge-routing";
|
||||
import { NpcDialogueNode } from "./NpcDialogueNode";
|
||||
import { NodeEditDialog } from "./NodeEditDialog";
|
||||
import { NodeEditDialog } from "./NodeEditDialog";import { GenerateDraftDialog } from "./GenerateDraftDialog";
|
||||
import { RoutedFlowEdge } from "./RoutedFlowEdge";
|
||||
|
||||
const nodeTypes = {
|
||||
|
|
@ -84,6 +86,11 @@ const DEFAULT_DATA: Record<string, DialogueNodeData> = {
|
|||
|
||||
function FlowEditor() {
|
||||
const { value, setValue } = useField<FlowData>();
|
||||
// Sibling field on the same document: provenance for the draft that was
|
||||
// accepted. Written when a draft lands, persisted by the document's Save.
|
||||
const { setValue: setGeneration } = useField<NpcDialogue["generation"]>({
|
||||
path: "generation",
|
||||
});
|
||||
const rf = useReactFlow();
|
||||
|
||||
const initial: FlowData =
|
||||
|
|
@ -98,6 +105,23 @@ function FlowEditor() {
|
|||
const [expanded, setExpanded] = useState(false);
|
||||
const [snap, setSnap] = useState(true);
|
||||
const [selectedEdgeId, setSelectedEdgeId] = useState<string | null>(null);
|
||||
const [generateOpen, setGenerateOpen] = useState(false);
|
||||
// Set after a draft lands, cleared when the author dismisses it. Purely a
|
||||
// reminder: the document's own modified state is what actually guards saving.
|
||||
const [draftNotice, setDraftNotice] = useState<string | null>(null);
|
||||
|
||||
// The contact this conversation belongs to. It is a relationship field on the
|
||||
// same document, so the edited doc is the only place it can come from.
|
||||
const { data: docData } = useDocumentInfo();
|
||||
const npcId = useMemo(() => {
|
||||
const raw = (docData as Record<string, unknown> | undefined)?.npc;
|
||||
if (typeof raw === "number") return raw;
|
||||
if (raw && typeof raw === "object" && "id" in raw) {
|
||||
const id = (raw as { id?: unknown }).id;
|
||||
return typeof id === "number" ? id : null;
|
||||
}
|
||||
return null;
|
||||
}, [docData]);
|
||||
|
||||
const lastSerialized = useRef<string>("");
|
||||
const menuRef = useRef<HTMLDivElement | null>(null);
|
||||
|
|
@ -172,6 +196,37 @@ function FlowEditor() {
|
|||
}
|
||||
}, [setValue]);
|
||||
|
||||
/**
|
||||
* Drops a generated draft into the canvas. It travels the same `serialize`
|
||||
* path as a dragged node, so it becomes unsaved field state and nothing more:
|
||||
* the only way to persist it stays the document's own Save.
|
||||
*/
|
||||
const applyGeneratedDraft = useCallback(
|
||||
(result: { flow: FlowData; model: string; promptVersion: string; attempts: number; truncated: boolean }, brief: DialogueBrief) => {
|
||||
const incoming = result.flow.nodes as Node[];
|
||||
setNodes(incoming);
|
||||
serialize(incoming);
|
||||
// The `brief` field is a Payload `json` column, whose generated type is a
|
||||
// loose scalar/object union, so the object shape needs a double cast.
|
||||
setGeneration({
|
||||
model: result.model,
|
||||
promptVersion: result.promptVersion,
|
||||
attempts: result.attempts,
|
||||
generatedAt: new Date().toISOString(),
|
||||
brief,
|
||||
} as unknown as NpcDialogue["generation"]);
|
||||
setDraftNotice(
|
||||
result.truncated
|
||||
? "AI draft. The model hit its output limit, so the ending may be missing. Review every line before saving."
|
||||
: "AI draft. Review every line, then save the document to publish it.",
|
||||
);
|
||||
// Fit the new graph once React Flow has measured the nodes it was handed.
|
||||
window.setTimeout(() => {
|
||||
void rf.fitView({ padding: 0.2 });
|
||||
}, 0);
|
||||
},
|
||||
[setNodes, serialize, setGeneration, rf],
|
||||
);
|
||||
// Dragging fires a position change per mousemove; only the settled one
|
||||
// (dragging === false) is worth writing to the field value. The flag is
|
||||
// consumed by the effect below, which sees the updated nodes state.
|
||||
|
|
@ -540,6 +595,21 @@ function FlowEditor() {
|
|||
{NODE_LABELS.end}
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setGenerateOpen(true)}
|
||||
disabled={npcId === null}
|
||||
title={
|
||||
npcId === null
|
||||
? "Pick a contact on this conversation before generating"
|
||||
: "Draft a conversation from a brief"
|
||||
}
|
||||
className={`${buttonClass} inline-flex items-center gap-1 bg-fuchsia-950 border-fuchsia-700 text-fuchsia-200 hover:bg-fuchsia-900 disabled:opacity-40 disabled:cursor-not-allowed`}
|
||||
>
|
||||
<Sparkles size={12} />
|
||||
Generate
|
||||
</button>
|
||||
|
||||
<span className="ml-auto text-[10px] text-zinc-500">
|
||||
{nodes.length} node{nodes.length !== 1 ? "s" : ""}
|
||||
</span>
|
||||
|
|
@ -575,6 +645,21 @@ function FlowEditor() {
|
|||
</div>
|
||||
)}
|
||||
|
||||
{draftNotice && (
|
||||
<div className="flex items-start gap-2 px-2 py-1 bg-fuchsia-950/60 border border-fuchsia-900/50 text-xs text-fuchsia-200">
|
||||
<Sparkles size={12} className="mt-0.5 shrink-0" />
|
||||
<span className="flex-1">{draftNotice}</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDraftNotice(null)}
|
||||
className="shrink-0 text-fuchsia-300 hover:text-fuchsia-100 cursor-pointer"
|
||||
aria-label="Dismiss draft notice"
|
||||
>
|
||||
Dismiss
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div
|
||||
ref={canvasRef}
|
||||
className={`npc-dialogue-flow border border-zinc-700 overflow-hidden bg-zinc-950 ${
|
||||
|
|
@ -701,6 +786,15 @@ function FlowEditor() {
|
|||
if (draftIds.current.delete(id)) deleteNodes([id]);
|
||||
}}
|
||||
onSave={handleNodeSave}
|
||||
npcId={npcId}
|
||||
/>
|
||||
|
||||
<GenerateDraftDialog
|
||||
open={generateOpen}
|
||||
onOpenChange={setGenerateOpen}
|
||||
npcId={npcId}
|
||||
nodeCount={nodes.length}
|
||||
onGenerated={applyGeneratedDraft}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
179
src/lib/ai/generate.ts
Normal file
179
src/lib/ai/generate.ts
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
/**
|
||||
* Shared access to the Unsloth Studio model that powers every AI surface in the
|
||||
* app: the Compose field plugin in `payload.config.ts` and the NPC dialogue
|
||||
* drafting actions in `src/lib/npc-dialogue/generation.ts`.
|
||||
*
|
||||
* Everything here was lifted out of `payload.config.ts` unchanged. The only
|
||||
* additions are `generateStructured` (a non-streaming companion to the object
|
||||
* path Compose already used) and `resolveModel`, which keeps model selection in
|
||||
* one place so a caller can point a structured task at a different GGUF without
|
||||
* touching the prose default.
|
||||
*
|
||||
* Server-only: this reads UNSLOTH_* environment variables and talks to the
|
||||
* model host over the network.
|
||||
*/
|
||||
|
||||
import { createOpenAI } from "@ai-sdk/openai";
|
||||
import { jsonSchema, streamObject } from "ai";
|
||||
|
||||
/**
|
||||
* The model-id select and its Postgres enum use a stable internal key. Changing
|
||||
* that key requires a migration, so the served model is configured separately:
|
||||
* point UNSLOTH_MODEL at the GGUF loaded in Unsloth Studio.
|
||||
*/
|
||||
export const MODEL_ID = "unsloth/Ornith-1.0-9B-GGUF";
|
||||
|
||||
/** The served model for every AI surface unless a task overrides it. */
|
||||
export const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
|
||||
|
||||
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
|
||||
// readable name from UNSLOTH_MODEL, falling back to the bundled Ornith label.
|
||||
const prettifyModel = (id: string) =>
|
||||
(id.split("/").pop() || id).replace(/[-_]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
|
||||
|
||||
export const MODEL_LABEL =
|
||||
process.env.UNSLOTH_MODEL_NAME ||
|
||||
(process.env.UNSLOTH_MODEL ? prettifyModel(process.env.UNSLOTH_MODEL) : "Ornith 1.0 9B");
|
||||
|
||||
// Ornith is a reasoning model: it emits a long `reasoning_content` block before
|
||||
// the actual answer, and with a small token budget the reasoning consumes the
|
||||
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
|
||||
// `reasoning_effort: "none"` to turn thinking off for the request, so the model
|
||||
// behaves like a plain instruct model and small budgets still produce output.
|
||||
// Sent on every request; harmless on models that do not support it.
|
||||
export const REASONING_DISABLED = { reasoning_effort: "none" } as const;
|
||||
|
||||
/**
|
||||
* Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
|
||||
* apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
|
||||
* API. Point UNSLOTH_URL at that instance; the default is the LAN address of
|
||||
* the Apex box.
|
||||
*/
|
||||
export const UNSLOTH_BASE_URL = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
|
||||
|
||||
export const unslothProvider = createOpenAI({
|
||||
apiKey: process.env.UNSLOTH_API_KEY,
|
||||
baseURL: UNSLOTH_BASE_URL,
|
||||
});
|
||||
|
||||
/**
|
||||
* The model a structured (graph/schema) task should use. Falls through to the
|
||||
* shared default, so setting only UNSLOTH_MODEL changes every surface at once.
|
||||
* UNSLOTH_MODEL_STRUCTURED exists for the case where prose and structured work
|
||||
* want different GGUFs; leaving it unset changes nothing.
|
||||
*/
|
||||
export function resolveModel(): string {
|
||||
return process.env.UNSLOTH_MODEL_STRUCTURED || DEFAULT_MODEL;
|
||||
}
|
||||
|
||||
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
|
||||
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
|
||||
// paragraphs, so strip any markdown code fences before using the output.
|
||||
export const stripCodeFences = (text: string): string =>
|
||||
text
|
||||
.replace(/^```[a-zA-Z]*\s*\n?/, "")
|
||||
.replace(/\n?```\s*$/, "")
|
||||
.trim();
|
||||
|
||||
export type PlainTextResult = { text: string; truncated: boolean };
|
||||
|
||||
/**
|
||||
* Plain-completion call. Every Compose field runs through this: the model is
|
||||
* asked for prose and the handler wraps the result into the JSON the client
|
||||
* parses. The token cap and temperature mirror what the old structured path
|
||||
* used, and `finish_reason === "length"` is reported so the truncation marker
|
||||
* reaches the client.
|
||||
*/
|
||||
export async function generatePlainText(
|
||||
prompt: string,
|
||||
system: string,
|
||||
model: string,
|
||||
options: { maxTokens?: number; temperature?: number } = {},
|
||||
): Promise<PlainTextResult> {
|
||||
const response = await fetch(`${UNSLOTH_BASE_URL}/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + process.env.UNSLOTH_API_KEY,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: [
|
||||
{ role: "system", content: system || "You are a helpful assistant." },
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
stream: false,
|
||||
max_tokens: options.maxTokens ?? 5000,
|
||||
temperature: options.temperature ?? 0.7,
|
||||
...REASONING_DISABLED,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unsloth API error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
const choice = result.choices?.[0];
|
||||
return {
|
||||
text: stripCodeFences(choice?.message?.content ?? ""),
|
||||
truncated: choice?.finish_reason === "length",
|
||||
};
|
||||
}
|
||||
|
||||
export interface StructuredGenerationOptions {
|
||||
/** The user-turn instruction. */
|
||||
prompt: string;
|
||||
/** The task framing. Omit for the generic assistant prompt. */
|
||||
system?: string;
|
||||
/** A JSON schema (from `zod`-free callers, so a plain JSON schema object). */
|
||||
schema: Record<string, unknown>;
|
||||
/** Overrides `resolveModel()`. */
|
||||
model?: string;
|
||||
maxTokens?: number;
|
||||
temperature?: number;
|
||||
}
|
||||
|
||||
export interface StructuredResult<T> {
|
||||
object: T;
|
||||
/** True when the generator hit the token cap, so `object` may be incomplete. */
|
||||
truncated: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Non-streaming object generation using the same provider configuration the
|
||||
* Compose fallback already proved against Unsloth Studio: strict JSON schema,
|
||||
* structured outputs, and reasoning disabled.
|
||||
*
|
||||
* Throws when the model's output cannot be parsed into the schema. Callers that
|
||||
* want a retry should catch and re-prompt; see
|
||||
* `generateDialogueDraft` in `src/lib/npc-dialogue/generation.ts`.
|
||||
*/
|
||||
export async function generateStructured<T>(
|
||||
options: StructuredGenerationOptions,
|
||||
): Promise<StructuredResult<T>> {
|
||||
const result = streamObject({
|
||||
maxOutputTokens: options.maxTokens ?? 5000,
|
||||
model: unslothProvider(options.model || resolveModel()),
|
||||
onError: (error) => {
|
||||
console.error("Unsloth generateStructured: ", error);
|
||||
},
|
||||
prompt: options.prompt,
|
||||
schema: jsonSchema(options.schema),
|
||||
system: options.system || "You are a helpful assistant.",
|
||||
temperature: options.temperature ?? 0.7,
|
||||
providerOptions: {
|
||||
openai: {
|
||||
strictJsonSchema: true,
|
||||
structuredOutputs: true,
|
||||
...REASONING_DISABLED,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
// Awaiting `object` drives the stream to completion and resolves once the
|
||||
// final JSON parses; it rejects when the output never satisfied the schema.
|
||||
const object = (await result.object) as T;
|
||||
const finishReason = await result.finishReason;
|
||||
return { object, truncated: finishReason === "length" };
|
||||
}
|
||||
94
src/lib/npc-dialogue/AGENTS.md
Normal file
94
src/lib/npc-dialogue/AGENTS.md
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
# AGENTS.md: NPC Dialogue
|
||||
|
||||
> **Parent**: `../../AGENTS.md` (commands, RBAC, Payload config) and `../AGENTS.md` (lib conventions).
|
||||
|
||||
Two halves: the runtime that walks a stored conversation, and the authoring
|
||||
surface that builds one. The AI drafting tools are documented in full at
|
||||
`docs/npc-dialogue-ai.md`.
|
||||
|
||||
## Never-miss rules
|
||||
|
||||
1. **The stored `flowData` graph is the only thing players can see.** The runtime
|
||||
resolves every node server-side from the document, so an unsaved editor draft
|
||||
is unreachable by construction. Do not add a code path that lets the client
|
||||
name a node the document does not contain.
|
||||
2. **AI output never writes a document.** `generateNpcDialogueDraft` and
|
||||
`rewriteNpcDialogueLine` return values to the editor; only the editor's Save
|
||||
persists them. Keep it that way: a server action that saves on the model's
|
||||
behalf destroys the review gate.
|
||||
3. **Generated effects are limited to `notify` and `flag`.** `emit`, `reward` and
|
||||
`discord` write game state or post to Discord and are author-only. They are
|
||||
absent from the generation schema and rejected again by the validator.
|
||||
4. **Flag keys must already exist.** A condition or `{{token}}` naming a missing
|
||||
`player-flags` key never fires and the branch silently dead-ends. Anything that
|
||||
generates dialogue text checks against the live vocabulary.
|
||||
|
||||
## Files
|
||||
|
||||
```
|
||||
src/lib/npc-dialogue/
|
||||
dialogue.ts # Node/edge/effect types, hop projection, validateGraph (pure)
|
||||
generationSchema.ts # JSON schema, normalizer, draft validator (pure)
|
||||
generationPrompt.ts # Prompt text, brief/tone/outcome vocabularies (pure)
|
||||
generation.ts # Model calls, context loading, validate-and-retry (Payload)
|
||||
interpolate.ts # {{flag}}, {{countdown:key}}, {{ cond ? a : b }} (pure)
|
||||
flags.ts # Flag read/write, condition evaluation (Payload)
|
||||
selection.ts # Which conversation is offered to a player (Payload)
|
||||
states.ts # Per-player read markers (Payload)
|
||||
attachments.ts # media ids to URLs (Payload)
|
||||
reorder.ts, DialogueText.tsx (pure)
|
||||
|
||||
src/components/admin/npc-dialogue/
|
||||
NpcDialogueEditor.tsx # React Flow canvas, the custom field component
|
||||
NodeEditDialog.tsx # Per-node form, hosts LineAssist
|
||||
GenerateDraftDialog.tsx# The brief form for whole-conversation drafting
|
||||
LineAssist.tsx # Rewrite / Shorten / Sharpen for one field
|
||||
NpcDialogueNode.tsx, RoutedFlowEdge.tsx, MarkupEditor.tsx, types.ts
|
||||
|
||||
src/components/frontend/personnel/NpcConversation.tsx # Player-facing walker
|
||||
src/collections/game/NpcDialogues.ts # Collection + generation provenance
|
||||
```
|
||||
|
||||
## Data model in one paragraph
|
||||
|
||||
`flowData` is `{ nodes, edges }`. Edges are a **derived projection** of the node
|
||||
data (`deriveEdges`) and exist only for the canvas: hops live in the nodes
|
||||
(`next`, `choices`, `trueTarget`/`falseTarget`). Deleting an edge scrubs the hop
|
||||
it represents. Every hop projection goes through `outgoingHops` so the canvas,
|
||||
the validator and the runtime cannot disagree.
|
||||
|
||||
Node types: `dialogue`, `choice`, `event`, `end`, `delay`, `condition`. Effects
|
||||
(`notify`, `emit`, `reward`, `flag`) are configured on `event` nodes only and are
|
||||
executed by `triggerNpcDialogueEvent`, which re-reads the stored node rather than
|
||||
trusting the client.
|
||||
|
||||
Availability is double-gated: `game-npcs.canMessage` on the contact, and the
|
||||
`entryGate` / `priority` on the dialogue document selecting which of an NPC's
|
||||
conversations is offered.
|
||||
|
||||
## Text markup
|
||||
|
||||
Lines support `**bold**`, `*italic*`, `{red}color{/}`, `` `code` ``, ``,
|
||||
list prefixes, `{{flag}}`, `{{countdown:key}}`, and ternaries
|
||||
`{{ cond ? a : b }}` including numeric comparisons. Interpolation is a single
|
||||
pass server-side, so a flag value can never smuggle in another token.
|
||||
`DialogueText.tsx` is the only renderer; don't hand-roll one.
|
||||
|
||||
## AI drafting behaviour worth knowing
|
||||
|
||||
- Two attempts maximum: the second prompt carries the validator's complaints.
|
||||
A draft that fails twice is not shown at all.
|
||||
- `normalizeGeneratedFlow` assigns layout positions by breadth from the start
|
||||
node, so a draft opens as a readable chain.
|
||||
- Provenance is only written when a draft lands, so rejected drafts leave no
|
||||
trace.
|
||||
- Dashes in model output are normalised: em-dash to a comma, a remaining en-dash
|
||||
to a hyphen (it is a range). Shipped copy never carries an em-dash.
|
||||
- The model is reachable only through `src/lib/ai/generate.ts`. Do not call
|
||||
`fetch` against Unsloth anywhere else.
|
||||
|
||||
## Tests
|
||||
|
||||
`tests/int/npc-dialogue-*.int.spec.ts`: interpolate, attachments, condition
|
||||
groups, flag targets, remove-hop, reorder, and generation. The generation spec
|
||||
injects the model call, so it runs without the model host.
|
||||
310
src/lib/npc-dialogue/generation.ts
Normal file
310
src/lib/npc-dialogue/generation.ts
Normal file
|
|
@ -0,0 +1,310 @@
|
|||
/**
|
||||
* 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 { generatePlainText, generateStructured, resolveModel, stripCodeFences } from "@/lib/ai/generate";
|
||||
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,
|
||||
DIALOGUE_SYSTEM_PROMPT,
|
||||
PROMPT_VERSION,
|
||||
} from "./generationPrompt";
|
||||
import type { DialogueBrief, KnownFlag, NpcContext, RewriteAction } from "./generationPrompt";
|
||||
|
||||
/** 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<NpcContext> {
|
||||
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<KnownFlag[]> {
|
||||
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<string>();
|
||||
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 };
|
||||
}
|
||||
|
||||
export interface DraftRunnerInput { prompt: string;
|
||||
system: string;
|
||||
schema: Record<string, unknown>;
|
||||
}
|
||||
|
||||
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<DraftRunnerResult>;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const defaultRunner: DraftRunner = (input) =>
|
||||
generateStructured<{ nodes?: RawDraftNode[] }>({
|
||||
...input,
|
||||
model: resolveModel(),
|
||||
maxTokens: 4000,
|
||||
temperature: 0.8,
|
||||
});
|
||||
|
||||
/**
|
||||
* 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 },
|
||||
run: DraftRunner = defaultRunner,
|
||||
): Promise<DraftOutcome> {
|
||||
const { npc, flags } = await buildGenerationContext(payload, input.npcId);
|
||||
const basePrompt = buildGenerationPrompt({ npc, brief: input.brief, flags });
|
||||
const knownKeys = flags.map((flag) => flag.key);
|
||||
const model = resolveModel();
|
||||
|
||||
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 conversation again.`;
|
||||
|
||||
let parsed: DraftRunnerResult;
|
||||
try {
|
||||
parsed = await run({ prompt, system: DIALOGUE_SYSTEM_PROMPT, schema: dialogueFlowSchema });
|
||||
} 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);
|
||||
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,
|
||||
};
|
||||
}
|
||||
|
||||
errors = combined;
|
||||
}
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
errors,
|
||||
attempts: MAX_ATTEMPTS,
|
||||
truncated: false,
|
||||
model,
|
||||
promptVersion: PROMPT_VERSION,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The house rule is no em-dashes in anything shipped, and dialogue copy reaches
|
||||
* players verbatim. A dash out of the model is the one thing worth normalising
|
||||
* before it lands in the author's textarea; everything else is left exactly as
|
||||
* written so the author edits real output, not a rewrite of it.
|
||||
*/
|
||||
function normalizeDashes(text: string): string {
|
||||
return text
|
||||
// A spaced dash is punctuation: a comma reads correctly in dialogue.
|
||||
.replace(/\s+[\u2014\u2013]\s+/g, ", ")
|
||||
// Em-dashes are almost always unspaced punctuation.
|
||||
.replace(/\s*\u2014\s*/g, ", ")
|
||||
// A remaining en-dash is a range (1-20), so a hyphen is the honest swap.
|
||||
.replace(/\u2013/g, "-");
|
||||
}
|
||||
|
||||
/** 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;
|
||||
}) => Promise<{ text: string }>;
|
||||
|
||||
const defaultLineRunner: LineRunner = ({ prompt, system, model }) =>
|
||||
generatePlainText(prompt, system, model, { maxTokens: 400, temperature: 0.8 });
|
||||
|
||||
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;
|
||||
},
|
||||
run: LineRunner = defaultLineRunner,
|
||||
): Promise<LineRewriteOutcome> {
|
||||
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 { system, prompt } = buildRewritePrompt({
|
||||
action: input.action,
|
||||
text,
|
||||
npc,
|
||||
nodeType: input.nodeType,
|
||||
previousLine: input.previousLine,
|
||||
});
|
||||
|
||||
const result = await run({ prompt, system, model: resolveModel() });
|
||||
const cleaned = cleanRewrittenLine(result.text ?? "");
|
||||
|
||||
if (!cleaned) {
|
||||
return { ok: false, text: "", error: "The model returned nothing usable. Try again." };
|
||||
}
|
||||
|
||||
return { ok: true, text: cleaned };
|
||||
}
|
||||
289
src/lib/npc-dialogue/generationPrompt.ts
Normal file
289
src/lib/npc-dialogue/generationPrompt.ts
Normal file
|
|
@ -0,0 +1,289 @@
|
|||
/**
|
||||
* Prompt text for the two AI dialogue surfaces: drafting a whole conversation
|
||||
* from a brief, and rewriting a single line in place.
|
||||
*
|
||||
* Pure module: the vocabulary here is also what the admin form renders, so the
|
||||
* options the author picks and the instructions the model receives can never
|
||||
* drift apart.
|
||||
*
|
||||
* Voice rules mirror `AI_OUTPUT_RULES` in `composeSystem.ts`: plain prose, no
|
||||
* em-dashes, no obvious AI tells. A draft is edited by a human afterwards, but a
|
||||
* draft that reads like a changelog wastes their time.
|
||||
*/
|
||||
|
||||
/** Bump whenever the wording below changes, so stored provenance is meaningful. */
|
||||
export const PROMPT_VERSION = "npc-gen-v1";
|
||||
|
||||
export const BRIEF_PURPOSES = [
|
||||
"greet",
|
||||
"quest-hook",
|
||||
"warning",
|
||||
"rumor",
|
||||
"refusal",
|
||||
"recruitment",
|
||||
] as const;
|
||||
export type BriefPurpose = (typeof BRIEF_PURPOSES)[number];
|
||||
|
||||
export const PURPOSE_LABELS: Record<BriefPurpose, string> = {
|
||||
greet: "Greeting",
|
||||
"quest-hook": "Quest hook",
|
||||
warning: "Warning",
|
||||
rumor: "Rumor",
|
||||
refusal: "Refusal",
|
||||
recruitment: "Recruitment pitch",
|
||||
};
|
||||
|
||||
export const BRIEF_TONES = ["clipped", "tired", "bureaucratic", "hostile", "friendly"] as const;
|
||||
export type BriefTone = (typeof BRIEF_TONES)[number];
|
||||
|
||||
export const TONE_LABELS: Record<BriefTone, string> = {
|
||||
clipped: "Clipped and efficient",
|
||||
tired: "Tired and worn down",
|
||||
bureaucratic: "Bureaucratic and precise",
|
||||
hostile: "Hostile and dismissive",
|
||||
friendly: "Friendly and open",
|
||||
};
|
||||
|
||||
/** How the conversation is allowed to end. `set-flag` needs a flag key. */
|
||||
export const BRIEF_OUTCOMES = ["none", "set-flag", "notify"] as const;
|
||||
export type BriefOutcome = (typeof BRIEF_OUTCOMES)[number];
|
||||
|
||||
export const OUTCOME_LABELS: Record<BriefOutcome, string> = {
|
||||
none: "No side effect",
|
||||
"set-flag": "Set a player flag",
|
||||
notify: "Notify the player",
|
||||
};
|
||||
|
||||
export const DRAFT_SIZES = [3, 4, 6] as const;
|
||||
export type DraftSize = (typeof DRAFT_SIZES)[number];
|
||||
|
||||
export interface DialogueBrief {
|
||||
purpose: BriefPurpose;
|
||||
/** What the player should learn or do. Required. */
|
||||
goal: string;
|
||||
outcome: BriefOutcome;
|
||||
/** `player-flags` key written when outcome is `set-flag`. */
|
||||
flagKey: string;
|
||||
tone: BriefTone;
|
||||
size: DraftSize;
|
||||
/** Optional detail the dialogue must contain (a name, a place, a number). */
|
||||
mustInclude: string;
|
||||
}
|
||||
|
||||
/** The NPC context the prompt may reference. Every field is optional. */
|
||||
export interface NpcContext {
|
||||
name?: string | null;
|
||||
occupation?: string | null;
|
||||
location?: string | null;
|
||||
faction?: string | null;
|
||||
bio?: string | null;
|
||||
levelDescription?: string | null;
|
||||
}
|
||||
|
||||
/** One known `player-flags` key, so the model cannot invent a branch. */
|
||||
export interface KnownFlag {
|
||||
key: string;
|
||||
flagType: string;
|
||||
}
|
||||
|
||||
export const REWRITE_ACTIONS = ["rewrite", "shorten", "sharpen"] as const;
|
||||
export type RewriteAction = (typeof REWRITE_ACTIONS)[number];
|
||||
|
||||
export const REWRITE_LABELS: Record<RewriteAction, string> = {
|
||||
rewrite: "Rewrite",
|
||||
shorten: "Shorten",
|
||||
sharpen: "Sharpen",
|
||||
};
|
||||
|
||||
const REWRITE_INSTRUCTIONS: Record<RewriteAction, string> = {
|
||||
rewrite:
|
||||
"Rewrite the line so it says the same thing in fresher words. Keep its length and its intent.",
|
||||
shorten:
|
||||
"Cut the line down to its essentials. Aim for at most two thirds of the current length. Keep the intent.",
|
||||
sharpen:
|
||||
"Keep the meaning and the length, but make the voice more distinct and the wording more concrete. Cut hedging.",
|
||||
};
|
||||
|
||||
/**
|
||||
* One worked example, deliberately short. A 9B model follows an example far more
|
||||
* reliably than it follows a field-by-field description, and this one fixes the
|
||||
* id convention, the empty-string convention, and the register in a single shot.
|
||||
*/
|
||||
const EXAMPLE_FLOW = `{
|
||||
"nodes": [
|
||||
{
|
||||
"id": "n1", "type": "dialogue", "isStart": true,
|
||||
"speaker": "", "leadIn": "", "closing": "",
|
||||
"body": "You're the new one. Quartermaster's through that door, if he's still awake.",
|
||||
"choices": [], "nextLabel": "", "nextTarget": "n2",
|
||||
"effectType": "none", "effectTitle": "", "effectMessage": "",
|
||||
"effectFlagKey": "", "effectFlagOp": "set_true", "effectFlagAmount": 0, "effectFlagText": "",
|
||||
"conditionKey": "", "conditionOp": "is_true", "conditionAmount": 0,
|
||||
"trueTarget": "", "falseTarget": ""
|
||||
},
|
||||
{
|
||||
"id": "n2", "type": "choice", "isStart": false,
|
||||
"speaker": "", "closing": "",
|
||||
"leadIn": "He jerks a thumb at the door behind him and waits.",
|
||||
"body": "",
|
||||
"choices": [
|
||||
{ "label": "What's he short on?", "target": "n3", "tooltip": "Ask about supplies." },
|
||||
{ "label": "Later.", "target": "n4", "tooltip": "" }
|
||||
],
|
||||
"nextLabel": "", "nextTarget": "",
|
||||
"effectType": "none", "effectTitle": "", "effectMessage": "",
|
||||
"effectFlagKey": "", "effectFlagOp": "set_true", "effectFlagAmount": 0, "effectFlagText": "",
|
||||
"conditionKey": "", "conditionOp": "is_true", "conditionAmount": 0,
|
||||
"trueTarget": "", "falseTarget": ""
|
||||
},
|
||||
{
|
||||
"id": "n3", "type": "event", "isStart": false,
|
||||
"speaker": "", "leadIn": "", "closing": "",
|
||||
"body": "Rifle magazines, mostly. He'll tell you the rest himself.",
|
||||
"choices": [], "nextLabel": "", "nextTarget": "n4",
|
||||
"effectType": "notify", "effectTitle": "Supplies noted", "effectMessage": "You know what the quartermaster is short on.",
|
||||
"effectFlagKey": "", "effectFlagOp": "set_true", "effectFlagAmount": 0, "effectFlagText": "",
|
||||
"conditionKey": "", "conditionOp": "is_true", "conditionAmount": 0,
|
||||
"trueTarget": "", "falseTarget": ""
|
||||
},
|
||||
{
|
||||
"id": "n4", "type": "end", "isStart": false,
|
||||
"speaker": "", "body": "", "leadIn": "",
|
||||
"closing": "He turns back to his clipboard.",
|
||||
"choices": [], "nextLabel": "", "nextTarget": "",
|
||||
"effectType": "none", "effectTitle": "", "effectMessage": "",
|
||||
"effectFlagKey": "", "effectFlagOp": "set_true", "effectFlagAmount": 0, "effectFlagText": "",
|
||||
"conditionKey": "", "conditionOp": "is_true", "conditionAmount": 0,
|
||||
"trueTarget": "", "falseTarget": ""
|
||||
}
|
||||
]
|
||||
}`;
|
||||
|
||||
export const DIALOGUE_SYSTEM_PROMPT = `You write conversations for NPCs in an Arma 3 military unit roleplay.
|
||||
|
||||
VOICE
|
||||
Write like a soldier with limited patience: concrete, physical, unsentimental. Short sentences. No fantasy vendor patter, no exclamation marks, no em-dashes.
|
||||
Each NPC has an occupation and a place. Let that show in what they notice and what they dismiss.
|
||||
Never write a line that explains the mechanics to the player.
|
||||
|
||||
STRUCTURE
|
||||
Exactly one node has "isStart": true, and it is the opening line.
|
||||
Every "target" and "nextTarget" must name an id that exists in the same output.
|
||||
choice nodes need two or three choices, each with short button text.
|
||||
Use an end node to close a branch. Do not use delay nodes.
|
||||
Keep the conversation between the requested size bounds.
|
||||
|
||||
FIELDS
|
||||
Fields not used by a node's type must be empty: "" for strings, [] for arrays, 0 for numbers, "is_true" and "set_true" for the enum defaults.
|
||||
"body" carries the spoken line. "leadIn" carries the situation text above a choice. "closing" carries the last line before the conversation ends.
|
||||
Leave "speaker" empty so the NPC's own name is used.
|
||||
|
||||
STATE
|
||||
Use only the player flag keys listed in the brief. Never invent a flag key: a branch on a flag that does not exist never fires.
|
||||
Allowed effects are "none", "notify" and "flag". You may not log game events, post to Discord, or grant rewards.
|
||||
|
||||
OUTPUT
|
||||
Return one JSON object matching the provided schema. No commentary, no code fences.`;
|
||||
|
||||
/**
|
||||
* The user turn for a whole draft: the NPC, the brief, and the real flag
|
||||
* vocabulary.
|
||||
*/
|
||||
export function buildGenerationPrompt(input: {
|
||||
npc: NpcContext;
|
||||
brief: DialogueBrief;
|
||||
flags: KnownFlag[];
|
||||
}): string {
|
||||
const { npc, brief, flags } = input;
|
||||
|
||||
const npcLines = [
|
||||
`Name: ${npc.name?.trim() || "unnamed"}`,
|
||||
npc.occupation?.trim() ? `Occupation: ${npc.occupation.trim()}` : null,
|
||||
npc.location?.trim() ? `Stationed at: ${npc.location.trim()}` : null,
|
||||
npc.faction?.trim() ? `Faction: ${npc.faction.trim()}` : null,
|
||||
npc.levelDescription?.trim() ? `Standing: ${npc.levelDescription.trim()}` : null,
|
||||
npc.bio?.trim() ? `Background: ${npc.bio.trim()}` : null,
|
||||
].filter(Boolean);
|
||||
|
||||
const flagLines =
|
||||
flags.length > 0
|
||||
? flags.map((flag) => `- ${flag.key} (${flag.flagType})`).join("\n")
|
||||
: "- none exist yet, so write no flag effects and no flag tokens";
|
||||
|
||||
const outcomeLine =
|
||||
brief.outcome === "set-flag"
|
||||
? `Set the flag "${brief.flagKey}" when the conversation reaches the agreed point.`
|
||||
: brief.outcome === "notify"
|
||||
? "Notify the player once, at the moment of the reveal."
|
||||
: "No side effects.";
|
||||
|
||||
const briefLines = [
|
||||
`Purpose: ${PURPOSE_LABELS[brief.purpose]}`,
|
||||
`The player should come away knowing or doing: ${brief.goal.trim()}`,
|
||||
`Tone: ${TONE_LABELS[brief.tone]}`,
|
||||
`Length: about ${brief.size} nodes`,
|
||||
`Outcome: ${outcomeLine}`,
|
||||
brief.mustInclude.trim() ? `Must include: ${brief.mustInclude.trim()}` : null,
|
||||
].filter(Boolean);
|
||||
|
||||
return `Write one conversation.
|
||||
|
||||
NPC
|
||||
${npcLines.join("\n")}
|
||||
|
||||
BRIEF
|
||||
${briefLines.join("\n")}
|
||||
|
||||
KNOWN PLAYER FLAGS
|
||||
${flagLines}
|
||||
|
||||
Example of the expected shape (an unrelated conversation, do not copy its content):
|
||||
${EXAMPLE_FLOW}
|
||||
|
||||
Now write the conversation for this NPC and brief.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Instructions for rewriting one existing line. The previous line is supplied so
|
||||
* the model does not restate it; consecutive dialogue that repeats itself is the
|
||||
* most common tell in a generated draft.
|
||||
*/
|
||||
export function buildRewritePrompt(input: {
|
||||
action: RewriteAction;
|
||||
text: string;
|
||||
npc: NpcContext;
|
||||
nodeType: string;
|
||||
previousLine?: string | null;
|
||||
}): { system: string; prompt: string } {
|
||||
const { action, text, npc, nodeType, previousLine } = input;
|
||||
|
||||
const voice = [
|
||||
npc.name?.trim() ? `Name: ${npc.name.trim()}` : null,
|
||||
npc.occupation?.trim() ? `Occupation: ${npc.occupation.trim()}` : null,
|
||||
npc.faction?.trim() ? `Faction: ${npc.faction.trim()}` : null,
|
||||
npc.bio?.trim() ? `Background: ${npc.bio.trim()}` : null,
|
||||
].filter(Boolean);
|
||||
|
||||
const prompt = `Rewrite one line of NPC dialogue.
|
||||
|
||||
SPEAKER
|
||||
${voice.length > 0 ? voice.join("\n") : "An unnamed soldier in a military unit."}
|
||||
|
||||
NODE TYPE
|
||||
${nodeType}
|
||||
|
||||
${previousLine?.trim() ? `THE LINE JUST BEFORE THIS ONE (do not repeat it)\n"${previousLine.trim()}"\n` : ""}
|
||||
CURRENT LINE
|
||||
"${text.trim()}"
|
||||
|
||||
TASK
|
||||
${REWRITE_INSTRUCTIONS[action]}
|
||||
|
||||
Reply with the replacement line only. No quotes around it, no explanation, no prefixes.`;
|
||||
|
||||
return {
|
||||
system:
|
||||
"You edit dialogue lines for a military roleplay. Plain prose out, one line, no markdown, no em-dashes, no commentary.",
|
||||
prompt,
|
||||
};
|
||||
}
|
||||
373
src/lib/npc-dialogue/generationSchema.ts
Normal file
373
src/lib/npc-dialogue/generationSchema.ts
Normal file
|
|
@ -0,0 +1,373 @@
|
|||
/**
|
||||
* 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 };
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
|
|
@ -0,0 +1,19 @@
|
|||
import { MigrateUpArgs, MigrateDownArgs, sql } from '@payloadcms/db-postgres'
|
||||
|
||||
export async function up({ db, payload, req }: MigrateUpArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_model" varchar;
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_prompt_version" varchar;
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_attempts" numeric;
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_generated_at" timestamp(3) with time zone;
|
||||
ALTER TABLE "npc_dialogues" ADD COLUMN "generation_brief" jsonb;`)
|
||||
}
|
||||
|
||||
export async function down({ db, payload, req }: MigrateDownArgs): Promise<void> {
|
||||
await db.execute(sql`
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_model";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_prompt_version";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_attempts";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_generated_at";
|
||||
ALTER TABLE "npc_dialogues" DROP COLUMN "generation_brief";`)
|
||||
}
|
||||
|
|
@ -156,6 +156,7 @@ import * as migration_20261031_084725_add_mission_ratings from './20261031_08472
|
|||
import * as migration_20261031_085035_add_mission_rating_sent_at_marker from './20261031_085035_add_mission_rating_sent_at_marker';
|
||||
import * as migration_20261031_090000_add_missions_discord_modlist_buffer_sent_at from './20261031_090000_add_missions_discord_modlist_buffer_sent_at';
|
||||
import * as migration_20261101_210013_add_mission_command_links from './20261101_210013_add_mission_command_links';
|
||||
import * as migration_20261112_171955_add_npc_dialogue_generation_provenance from './20261112_171955_add_npc_dialogue_generation_provenance';
|
||||
|
||||
export const migrations = [
|
||||
{
|
||||
|
|
@ -946,6 +947,11 @@ export const migrations = [
|
|||
{
|
||||
up: migration_20261101_210013_add_mission_command_links.up,
|
||||
down: migration_20261101_210013_add_mission_command_links.down,
|
||||
name: '20261101_210013_add_mission_command_links'
|
||||
name: '20261101_210013_add_mission_command_links',
|
||||
},
|
||||
{
|
||||
up: migration_20261112_171955_add_npc_dialogue_generation_provenance.up,
|
||||
down: migration_20261112_171955_add_npc_dialogue_generation_provenance.down,
|
||||
name: '20261112_171955_add_npc_dialogue_generation_provenance'
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -3051,6 +3051,39 @@ export interface NpcDialogue {
|
|||
| number
|
||||
| boolean
|
||||
| null;
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
generation?: {
|
||||
/**
|
||||
* Served model id that produced the draft.
|
||||
*/
|
||||
model?: string | null;
|
||||
/**
|
||||
* Prompt contract version, so an old draft is comparable.
|
||||
*/
|
||||
promptVersion?: string | null;
|
||||
/**
|
||||
* 1 when the first output validated, 2 when it was retried.
|
||||
*/
|
||||
attempts?: number | null;
|
||||
/**
|
||||
* When the draft was generated.
|
||||
*/
|
||||
generatedAt?: string | null;
|
||||
/**
|
||||
* The form brief the author filled in when drafting.
|
||||
*/
|
||||
brief?:
|
||||
| {
|
||||
[k: string]: unknown;
|
||||
}
|
||||
| unknown[]
|
||||
| string
|
||||
| number
|
||||
| boolean
|
||||
| null;
|
||||
};
|
||||
updatedAt: string;
|
||||
createdAt: string;
|
||||
}
|
||||
|
|
@ -9965,6 +9998,15 @@ export interface NpcDialoguesSelect<T extends boolean = true> {
|
|||
amount?: T;
|
||||
};
|
||||
flowData?: T;
|
||||
generation?:
|
||||
| T
|
||||
| {
|
||||
model?: T;
|
||||
promptVersion?: T;
|
||||
attempts?: T;
|
||||
generatedAt?: T;
|
||||
brief?: T;
|
||||
};
|
||||
updatedAt?: T;
|
||||
createdAt?: T;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -118,39 +118,15 @@ import { mcpPlugin } from "@payloadcms/plugin-mcp";
|
|||
import { formBuilderPlugin } from "@payloadcms/plugin-form-builder";
|
||||
import { surveyFormBuilderConfig } from "@/lib/surveys/formBuilderConfig";
|
||||
import { buildComposeSystem, resolveProseShape, wrapProse } from "@/lib/ai/composeSystem";
|
||||
import { createOpenAI } from "@ai-sdk/openai";
|
||||
import { createTextStreamResponse, jsonSchema, streamObject } from "ai";
|
||||
|
||||
// Ornith-9B is served by the "Apex" Unsloth connection (a separate machine,
|
||||
// apex-lnx / 192.168.1.7), reached through Unsloth Studio's OpenAI-compatible
|
||||
// API. Point UNSLOTH_URL at that instance; the default is the LAN address of
|
||||
// the Apex box.
|
||||
const unslothProvider = createOpenAI({
|
||||
apiKey: process.env.UNSLOTH_API_KEY,
|
||||
baseURL: process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1",
|
||||
});
|
||||
|
||||
// The model-id select and its Postgres enum use a stable internal key. Changing
|
||||
// that key requires a migration, so the served model is configured separately:
|
||||
// point UNSLOTH_MODEL at the GGUF loaded in Unsloth Studio.
|
||||
const MODEL_ID = "unsloth/Ornith-1.0-9B-GGUF";
|
||||
const DEFAULT_MODEL = process.env.UNSLOTH_MODEL || MODEL_ID;
|
||||
|
||||
// Dropdown label for the model. UNSLOTH_MODEL_NAME wins; otherwise derive a
|
||||
// readable name from UNSLOTH_MODEL, falling back to the bundled Ornith label.
|
||||
const prettifyModel = (id: string) =>
|
||||
(id.split("/").pop() || id).replace(/[-_]+/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
|
||||
const MODEL_LABEL =
|
||||
process.env.UNSLOTH_MODEL_NAME ||
|
||||
(process.env.UNSLOTH_MODEL ? prettifyModel(process.env.UNSLOTH_MODEL) : "Ornith 1.0 9B");
|
||||
|
||||
// Ornith is a reasoning model: it emits a long `reasoning_content` block before
|
||||
// the actual answer, and with a small token budget the reasoning consumes the
|
||||
// whole allowance, leaving `content` empty. Unsloth Studio (llama.cpp) accepts
|
||||
// `reasoning_effort: "none"` to turn thinking off for the request, so the model
|
||||
// behaves like a plain instruct model and small budgets still produce output.
|
||||
// Sent on every request; harmless on models that do not support it.
|
||||
const REASONING_DISABLED = { reasoning_effort: "none" } as const;
|
||||
import {
|
||||
DEFAULT_MODEL,
|
||||
generatePlainText,
|
||||
MODEL_ID,
|
||||
MODEL_LABEL,
|
||||
REASONING_DISABLED,
|
||||
unslothProvider,
|
||||
} from "@/lib/ai/generate";
|
||||
|
||||
// AI Compose allowlist: the plugin's default init makes an LLM call per field
|
||||
// to seed prompts. Returning false here skips a field (no instruction row, no
|
||||
|
|
@ -246,60 +222,6 @@ const aiFieldSeedPrompts: SeedPromptFunction = ({ path, fieldType, fieldLabel })
|
|||
return false;
|
||||
};
|
||||
|
||||
// Gemma tends to answer schema-y prompts with fenced JSON blobs. The plain-text
|
||||
// fallback is meant to produce prose that plainTextToLexicalJson wraps into
|
||||
// paragraphs, so strip any markdown code fences before using the output.
|
||||
const stripCodeFences = (text: string): string =>
|
||||
text
|
||||
.replace(/^```[a-zA-Z]*\s*\n?/, "")
|
||||
.replace(/\n?```\s*$/, "")
|
||||
.trim();
|
||||
|
||||
type PlainTextResult = { text: string; truncated: boolean };
|
||||
|
||||
// Every Compose field now runs through this one call: the model is asked for
|
||||
// prose and the handler wraps the result into the JSON the client parses. The
|
||||
// token cap and temperature mirror what the old structured path used, and
|
||||
// `finish_reason === "length"` is reported so the truncation marker reaches the
|
||||
// client (the prose path previously swallowed it).
|
||||
async function generatePlainText(
|
||||
prompt: string,
|
||||
system: string,
|
||||
model: string,
|
||||
options: { maxTokens?: number; temperature?: number } = {},
|
||||
): Promise<PlainTextResult> {
|
||||
const baseUrl = process.env.UNSLOTH_URL || "http://192.168.1.7:8888/v1";
|
||||
const response = await fetch(`${baseUrl}/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: "Bearer " + process.env.UNSLOTH_API_KEY,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
model,
|
||||
messages: [
|
||||
{ role: "system", content: system || "You are a helpful assistant." },
|
||||
{ role: "user", content: prompt },
|
||||
],
|
||||
stream: false,
|
||||
max_tokens: options.maxTokens ?? 5000,
|
||||
temperature: options.temperature ?? 0.7,
|
||||
...REASONING_DISABLED,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Unsloth API error: ${response.statusText}`);
|
||||
}
|
||||
|
||||
const result = await response.json();
|
||||
const choice = result.choices?.[0];
|
||||
return {
|
||||
text: stripCodeFences(choice?.message?.content ?? ""),
|
||||
truncated: choice?.finish_reason === "length",
|
||||
};
|
||||
}
|
||||
|
||||
const filename = fileURLToPath(import.meta.url);
|
||||
const dirname = path.dirname(filename);
|
||||
const META_TITLE = "Polaris Task Force";
|
||||
|
|
|
|||
405
tests/int/npc-dialogue-generation.int.spec.ts
Normal file
405
tests/int/npc-dialogue-generation.int.spec.ts
Normal file
|
|
@ -0,0 +1,405 @@
|
|||
import type { Payload } from "payload";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { DialogueNode } from "@/lib/npc-dialogue/dialogue";
|
||||
import { generateDialogueDraft, rewriteDialogueLine } from "@/lib/npc-dialogue/generation";
|
||||
import type { DraftRunner, LineRunner } from "@/lib/npc-dialogue/generation";
|
||||
import {
|
||||
normalizeGeneratedFlow,
|
||||
validateGeneratedFlow,
|
||||
} from "@/lib/npc-dialogue/generationSchema";
|
||||
import type { RawDraftNode } from "@/lib/npc-dialogue/generationSchema";
|
||||
import type { DialogueBrief } from "@/lib/npc-dialogue/generationPrompt";
|
||||
|
||||
const TIMEOUT = 30_000;
|
||||
|
||||
const BRIEF: DialogueBrief = {
|
||||
purpose: "quest-hook",
|
||||
goal: "Learn that the quartermaster is short on magazines.",
|
||||
outcome: "set-flag",
|
||||
flagKey: "met_quartermaster",
|
||||
tone: "clipped",
|
||||
size: 3,
|
||||
mustInclude: "",
|
||||
};
|
||||
|
||||
/** Every field, because the model's schema is strict-safe (all required). */
|
||||
function rawNode(overrides: Partial<RawDraftNode> = {}): RawDraftNode {
|
||||
return {
|
||||
id: "n1",
|
||||
type: "dialogue",
|
||||
isStart: true,
|
||||
speaker: "",
|
||||
body: "You're the new one.",
|
||||
leadIn: "",
|
||||
closing: "",
|
||||
choices: [],
|
||||
nextLabel: "",
|
||||
nextTarget: "",
|
||||
effectType: "none",
|
||||
effectTitle: "",
|
||||
effectMessage: "",
|
||||
effectFlagKey: "",
|
||||
effectFlagOp: "set_true",
|
||||
effectFlagAmount: 0,
|
||||
effectFlagText: "",
|
||||
conditionKey: "",
|
||||
conditionOp: "is_true",
|
||||
conditionAmount: 0,
|
||||
trueTarget: "",
|
||||
falseTarget: "",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** A minimal two-node draft: one line, then an end node. */
|
||||
const TINY_DRAFT: RawDraftNode[] = [
|
||||
rawNode({ id: "n1", body: "You're the new one.", nextTarget: "n2" }),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "He turns away." }),
|
||||
];
|
||||
|
||||
function flowOf(raw: RawDraftNode[]) {
|
||||
return normalizeGeneratedFlow(raw);
|
||||
}
|
||||
|
||||
/** Stub payload: the draft service only needs one NPC and a flag list. */
|
||||
function stubPayload(): Payload {
|
||||
return {
|
||||
findByID: async () => ({
|
||||
name: "Sgt. Halden",
|
||||
occupation: "Quartermaster",
|
||||
location: { name: "Depot" },
|
||||
faction: { name: "Task Force" },
|
||||
bio: null,
|
||||
levelDescription: null,
|
||||
}),
|
||||
find: async () => ({
|
||||
docs: [{ key: "met_quartermaster", flagType: "boolean" }],
|
||||
}),
|
||||
} as unknown as Payload;
|
||||
}
|
||||
|
||||
describe("normalizeGeneratedFlow", () => {
|
||||
it("assembles node data, drops empty placeholders and lays the graph out by depth", () => {
|
||||
const { nodes, edges, errors } = flowOf(TINY_DRAFT);
|
||||
|
||||
expect(errors).toEqual([]);
|
||||
expect(nodes).toHaveLength(2);
|
||||
|
||||
const [first, second] = nodes;
|
||||
// Empty speaker/closing/leadIn must not land on the node.
|
||||
expect(first.data).toEqual({ body: "You're the new one.", isStart: true, next: { target: "n2" } });
|
||||
expect(second.data.closing).toBe("He turns away.");
|
||||
|
||||
// Start sits at the origin, its continuation one column to the right.
|
||||
expect(first.position).toEqual({ x: 0, y: 0 });
|
||||
expect(second.position.x).toBeGreaterThan(0);
|
||||
|
||||
expect(edges).toHaveLength(1);
|
||||
expect(edges[0]).toMatchObject({ source: "n1", target: "n2" });
|
||||
});
|
||||
|
||||
it("rejects duplicate node ids", () => {
|
||||
const { errors } = flowOf([
|
||||
rawNode({ id: "n1" }),
|
||||
rawNode({ id: "n1", type: "end", isStart: false }),
|
||||
]);
|
||||
expect(errors[0]).toContain('Duplicate node id "n1"');
|
||||
});
|
||||
|
||||
it("rejects a node type the generator may not produce", () => {
|
||||
const { errors } = flowOf([
|
||||
rawNode({ id: "n1" }),
|
||||
rawNode({ id: "n2", type: "delay" as RawDraftNode["type"], isStart: false }),
|
||||
]);
|
||||
expect(errors.join(" ")).toContain("unsupported node type");
|
||||
});
|
||||
|
||||
it("builds choice hops and keeps their labels", () => {
|
||||
const { nodes } = flowOf([
|
||||
rawNode({ id: "n1", type: "choice", body: "", leadIn: "He waits.", nextTarget: "" }),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Done." }),
|
||||
]);
|
||||
// Rewrite the choices properly, since the factory emits an empty list.
|
||||
const withChoices = flowOf([
|
||||
rawNode({
|
||||
id: "n1",
|
||||
type: "choice",
|
||||
body: "",
|
||||
leadIn: "He waits.",
|
||||
nextTarget: "",
|
||||
choices: [{ label: "What's he short on?", target: "n2", tooltip: "" }],
|
||||
}),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Done." }),
|
||||
]);
|
||||
expect(nodes).toHaveLength(2);
|
||||
expect(withChoices.nodes[0].data.choices).toEqual([
|
||||
{ label: "What's he short on?", target: "n2" },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("validateGeneratedFlow", () => {
|
||||
const KNOWN = ["met_quartermaster"];
|
||||
|
||||
it("accepts a clean draft", () => {
|
||||
const { nodes } = flowOf(TINY_DRAFT);
|
||||
expect(validateGeneratedFlow(nodes, KNOWN)).toEqual({ ok: true, errors: [] });
|
||||
});
|
||||
|
||||
it("reports dangling hop targets", () => {
|
||||
const { nodes } = flowOf([
|
||||
rawNode({ id: "n1", isStart: false, nextTarget: "n9" }),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }),
|
||||
]);
|
||||
const result = validateGeneratedFlow(nodes, KNOWN);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.errors.join(" ")).toContain('points to missing node "n9"');
|
||||
});
|
||||
|
||||
it("rejects an unknown flag key on a condition node", () => {
|
||||
const { nodes } = flowOf([
|
||||
rawNode({
|
||||
id: "n1",
|
||||
type: "condition",
|
||||
body: "",
|
||||
nextTarget: "",
|
||||
conditionKey: "invented_flag",
|
||||
conditionOp: "is_true",
|
||||
trueTarget: "n2",
|
||||
falseTarget: "n2",
|
||||
}),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }),
|
||||
]);
|
||||
const result = validateGeneratedFlow(nodes, KNOWN);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.errors.join(" ")).toContain('unknown flag "invented_flag"');
|
||||
});
|
||||
|
||||
it("rejects an unknown flag token in a line", () => {
|
||||
const { nodes } = flowOf([
|
||||
rawNode({ id: "n1", body: "Status reads {{reactor_state}}.", nextTarget: "n2" }),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }),
|
||||
]);
|
||||
const result = validateGeneratedFlow(nodes, KNOWN);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.errors.join(" ")).toContain('unknown flag "reactor_state"');
|
||||
});
|
||||
|
||||
it("skips the vocabulary check when no flags exist yet", () => {
|
||||
const { nodes } = flowOf([
|
||||
rawNode({ id: "n1", body: "Status reads {{anything}}.", nextTarget: "n2" }),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }),
|
||||
]);
|
||||
expect(validateGeneratedFlow(nodes, []).ok).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects effects the generator is not allowed to configure", () => {
|
||||
// `emit` is stripped by normalization only when unknown; here the effect is
|
||||
// built from `effectType`, so force an unauthorised kind onto the node.
|
||||
const { nodes } = flowOf(TINY_DRAFT);
|
||||
const forged: DialogueNode[] = nodes.map((node, index) =>
|
||||
index === 0
|
||||
? { ...node, data: { ...node.data, effect: { type: "emit", message: "x" } } }
|
||||
: node,
|
||||
);
|
||||
const result = validateGeneratedFlow(forged, KNOWN);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.errors.join(" ")).toContain('unauthorised effect "emit"');
|
||||
});
|
||||
|
||||
it("rejects a flag effect that names no key", () => {
|
||||
const { nodes } = flowOf(TINY_DRAFT);
|
||||
const forged: DialogueNode[] = nodes.map((node, index) =>
|
||||
index === 0
|
||||
? { ...node, data: { ...node.data, effect: { type: "flag", flagOp: "set_true" } } }
|
||||
: node,
|
||||
);
|
||||
expect(validateGeneratedFlow(forged, KNOWN).errors.join(" ")).toContain(
|
||||
"flag effect with no key",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("generateDialogueDraft", () => {
|
||||
it(
|
||||
"returns a flow on the first attempt when the model behaves",
|
||||
async () => {
|
||||
const calls: string[] = [];
|
||||
const run: DraftRunner = async (input) => {
|
||||
calls.push(input.prompt);
|
||||
return { object: { nodes: TINY_DRAFT }, truncated: false };
|
||||
};
|
||||
|
||||
const outcome = await generateDialogueDraft(
|
||||
stubPayload(),
|
||||
{ npcId: 1, brief: BRIEF },
|
||||
run,
|
||||
);
|
||||
|
||||
expect(outcome.ok).toBe(true);
|
||||
expect(outcome.attempts).toBe(1);
|
||||
expect(outcome.flow?.nodes).toHaveLength(2);
|
||||
expect(calls).toHaveLength(1);
|
||||
// The brief drove the prompt, and the real flag vocabulary was supplied.
|
||||
expect(calls[0]).toContain("Quartermaster");
|
||||
expect(calls[0]).toContain("met_quartermaster");
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"retries once with the validator's complaints attached",
|
||||
async () => {
|
||||
const prompts: string[] = [];
|
||||
const run: DraftRunner = async (input) => {
|
||||
prompts.push(input.prompt);
|
||||
if (prompts.length === 1) {
|
||||
// Invented flag: parsable, structurally fine, still unacceptable.
|
||||
return {
|
||||
object: {
|
||||
nodes: [
|
||||
rawNode({ id: "n1", body: "{{made_up_flag}}", nextTarget: "n2" }),
|
||||
rawNode({ id: "n2", type: "end", isStart: false, body: "", closing: "Bye." }),
|
||||
],
|
||||
},
|
||||
truncated: false,
|
||||
};
|
||||
}
|
||||
return { object: { nodes: TINY_DRAFT }, truncated: false };
|
||||
};
|
||||
|
||||
const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run);
|
||||
|
||||
expect(outcome.ok).toBe(true);
|
||||
expect(outcome.attempts).toBe(2);
|
||||
expect(prompts).toHaveLength(2);
|
||||
expect(prompts[1]).toContain("YOUR PREVIOUS ATTEMPT WAS REJECTED");
|
||||
expect(prompts[1]).toContain("made_up_flag");
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"gives up after two attempts instead of handing back a broken graph",
|
||||
async () => {
|
||||
const run: DraftRunner = async () => ({
|
||||
object: { nodes: [rawNode({ id: "n1", nextTarget: "ghost" })] },
|
||||
truncated: false,
|
||||
});
|
||||
|
||||
const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run);
|
||||
|
||||
expect(outcome.ok).toBe(false);
|
||||
expect(outcome.flow).toBeUndefined();
|
||||
expect(outcome.attempts).toBe(2);
|
||||
expect(outcome.errors.join(" ")).toContain('points to missing node "ghost"');
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"treats an unparsable generation as a failed attempt, not a crash",
|
||||
async () => {
|
||||
let calls = 0;
|
||||
const run: DraftRunner = async () => {
|
||||
calls += 1;
|
||||
if (calls === 1) throw new Error("Unexpected token in JSON");
|
||||
return { object: { nodes: TINY_DRAFT }, truncated: false };
|
||||
};
|
||||
|
||||
const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run);
|
||||
|
||||
expect(outcome.ok).toBe(true);
|
||||
expect(calls).toBe(2);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"reports truncation so a cut-off draft is not mistaken for a complete one",
|
||||
async () => {
|
||||
const run: DraftRunner = async () => ({ object: { nodes: TINY_DRAFT }, truncated: true });
|
||||
const outcome = await generateDialogueDraft(stubPayload(), { npcId: 1, brief: BRIEF }, run);
|
||||
expect(outcome.truncated).toBe(true);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
|
||||
describe("rewriteDialogueLine", () => {
|
||||
const INPUT = {
|
||||
npcId: 1,
|
||||
action: "rewrite" as const,
|
||||
text: "You're the new one. Quartermaster's through that door.",
|
||||
nodeType: "dialogue",
|
||||
};
|
||||
|
||||
it(
|
||||
"returns the model's line, stripped of the quoting it tends to add",
|
||||
async () => {
|
||||
const run: LineRunner = async () => ({ text: '"So you\'re the replacement. He\'s inside."' });
|
||||
const outcome = await rewriteDialogueLine(stubPayload(), INPUT, run);
|
||||
expect(outcome.ok).toBe(true);
|
||||
expect(outcome.text).toBe("So you're the replacement. He's inside.");
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"normalises em and en dashes, which must never reach shipped copy",
|
||||
async () => {
|
||||
const run: LineRunner = async () => ({ text: "He shrugs\u2014then points inside. Rounds 1\u201320." });
|
||||
const outcome = await rewriteDialogueLine(stubPayload(), INPUT, run);
|
||||
expect(outcome.text).toBe("He shrugs, then points inside. Rounds 1-20.");
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"refuses to spend a call on an empty field",
|
||||
async () => {
|
||||
let called = false;
|
||||
const run: LineRunner = async () => {
|
||||
called = true;
|
||||
return { text: "x" };
|
||||
};
|
||||
const outcome = await rewriteDialogueLine(stubPayload(), { ...INPUT, text: " " }, run);
|
||||
expect(outcome.ok).toBe(false);
|
||||
expect(called).toBe(false);
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"reports an empty completion instead of clearing the author's line",
|
||||
async () => {
|
||||
const run: LineRunner = async () => ({ text: "```\n\n```" });
|
||||
const outcome = await rewriteDialogueLine(stubPayload(), INPUT, run);
|
||||
expect(outcome.ok).toBe(false);
|
||||
expect(outcome.text).toBe("");
|
||||
expect(outcome.error).toContain("nothing usable");
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
|
||||
it(
|
||||
"sends the previous line so a rewrite does not restate it",
|
||||
async () => {
|
||||
let prompt = "";
|
||||
const run: LineRunner = async (input) => {
|
||||
prompt = input.prompt;
|
||||
return { text: "Fine." };
|
||||
};
|
||||
await rewriteDialogueLine(
|
||||
stubPayload(),
|
||||
{ ...INPUT, previousLine: "You're late." },
|
||||
run,
|
||||
);
|
||||
expect(prompt).toContain("You're late.");
|
||||
expect(prompt).toContain("Sgt. Halden");
|
||||
},
|
||||
TIMEOUT,
|
||||
);
|
||||
});
|
||||
Loading…
Reference in a new issue