"use server"; import config from "@payload-config"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { getPayload } from "payload"; import type { User } from "@/payload-types"; import { emitGameEvent } from "@/utils/event-log/emit"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { notifyUser } from "@/lib/notifications"; import { collectNodeTokens, resolveNodeTexts } from "@/lib/npc-dialogue/interpolate"; import type { ResolvedNodeTexts } from "@/lib/npc-dialogue/interpolate"; import { applyFlagEffect, evaluateCondition, readFlag, resolveFlagOwner } from "@/lib/npc-dialogue/flags"; 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 { loadDialogueSettings } from "@/lib/npc-dialogue/generationSettings"; 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, FlowData, NpcDialogueEffect, } from "@/lib/npc-dialogue/dialogue"; import { hasEmptyConditionKey } from "@/lib/npc-dialogue/dialogue"; interface ActionResult { success: boolean; error?: string; data?: T; } async function authenticate() { const payloadConfig = await config; const payload = await getPayload({ config: payloadConfig }); const { headers } = await import("next/headers"); const hdrs = await headers(); const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false, }); if (!isPayloadUser(user)) { throw new Error("Unauthorized"); } return { payload, user }; } /** * Resolve the effect configured on a dialogue `event` node and run it. The * node is looked up server-side from the stored flowchart, so the client can * only trigger effects an admin has authored for this conversation. */ export async function triggerNpcDialogueEvent( npcId: number, nodeId: string, ): Promise { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; if (!flowData || !Array.isArray(flowData.nodes)) { return { success: false, error: "This contact has no conversation configured." }; } const node = flowData.nodes.find((n) => n.id === nodeId); if (!node || node.type !== "event" || !node.data.effect) { // Nothing to trigger (or the node isn't an event): treated as a no-op. return { success: true }; } const effect: NpcDialogueEffect = node.data.effect; await runEffect(payload, user.id as number, npcId, effect); return { success: true }; } 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 }; } } async function runEffect( payload: Awaited>, userId: number, npcId: number, effect: NpcDialogueEffect, ): Promise { switch (effect.type) { case "notify": { await notifyUser(payload, { userId, type: "npc:dialogue", title: effect.title ?? "Conversation", message: effect.message, }); break; } case "emit": { await emitGameEvent(payload, { type: EventTypes.NpcDialogue, message: effect.message ?? "NPC dialogue event", actor: userId, targetCollection: "game-npcs", targetId: npcId, data: { effect: "emit" }, // Author override: "public" puts the entry in every member's feed; // undefined keeps the restricted narrative default (see visibility.ts). visibility: effect.eventVisibility, discordRequested: effect.discord, }); break; } case "reward": { // LLM/reward seam intentionally left unconfigured (see Phase 5). await emitGameEvent(payload, { type: EventTypes.NpcDialogue, message: effect.message ?? "NPC dialogue reward (unconfigured)", actor: userId, targetCollection: "game-npcs", targetId: npcId, data: { effect: "reward", unconfigured: true }, visibility: effect.eventVisibility, discordRequested: effect.discord, }); break; } case "flag": { const key = effect.flagKey?.trim(); if (!key) break; const op: DialogueFlagOp = effect.flagOp ?? "set_true"; const amount = effect.flagAmount ?? 0; // Resolve who the flag belongs to (self / global / a specific user) so // same-named flags for different owners never collide. const owner = resolveFlagOwner(effect.flagTarget, effect.flagTargetUserId, userId); await applyFlagEffect( payload, owner, key, op, amount, effect.flagText, effect.flagDelayMinutes, ); await emitGameEvent(payload, { type: EventTypes.NpcDialogue, message: `Conversation set flag "${key}" (${op}).`, actor: userId, targetCollection: "game-npcs", targetId: npcId, data: { effect: "flag", key, op, amount }, visibility: effect.eventVisibility, discordRequested: effect.discord, }); break; } } } /** * Evaluate a dialogue `condition` node against the reading user's live * web-app state (player flags). The node is looked up server-side from the * stored flowchart, so the client can only evaluate conditions an admin * authored for this conversation. */ export async function evaluateNpcDialogueCondition( npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; const node = flowData?.nodes?.find((n) => n.id === nodeId); if (!node || node.type !== "condition" || !node.data.condition) { // Not a condition node: nothing to branch on. return { success: true, data: false }; } const value = await evaluateCondition(payload, user.id as number, node.data.condition); return { success: true, data: value }; } 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 }; } } /** * Evaluate every choice's visibility gate for a `choice` node in one round * trip. Ungated choices always pass; gated ones report whether the reading * user's flags satisfy their condition and whether a failing choice should * still render locked (with its authored hint) instead of hiding. The node is * looked up server-side from the stored flowchart, so clients never see gate * config for conversations an admin has not authored. */ export async function evaluateNpcDialogueChoices( npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; const node = flowData?.nodes?.find((n) => n.id === nodeId); if (!node || node.type !== "choice") { // Not a choice node: nothing to gate. return { success: true, data: [] }; } const gates: ChoiceGate[] = []; for (const choice of node.data.choices ?? []) { const showLocked = Boolean(choice.lockedHint?.trim()); if (!choice.condition || hasEmptyConditionKey(choice.condition)) { gates.push({ pass: true, showLocked }); continue; } const pass = await evaluateCondition(payload, user.id as number, choice.condition); gates.push({ pass, showLocked }); } return { success: true, data: gates }; } 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 }; } } /** * Resolve every interpolatable display string of one node against the reading * user's live flags. Tokens (`{{key}}`) are replaced server-side at render * time, so interpolated values may contain dialogue markup (colors) and stay * fresh when flags change mid-conversation. Only the flag keys a node actually * references are read; substituted values are never re-scanned for tokens. */ export async function resolveNpcDialogueTexts( npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; const node = flowData?.nodes?.find((n) => n.id === nodeId); if (!node) return { success: true, data: {} }; const keys = collectNodeTokens(node); const values: Record = {}; const countdowns: Record = {}; const truths: Record = {}; for (const key of keys) { const flag = await readFlag(payload, user.id as number, key); values[key] = flag.text; // Countdown leaf: pending flags tick toward activation, active ones read // "done", missing ones render nothing. countdowns[key] = flag.activatesAt ?? (flag.exists ? "done" : ""); // Truth inputs for ternary conditions (`{{ key ? .. : .. }}`). truths[key] = { bool: flag.bool, num: flag.num }; } const resolved = resolveNodeTexts(node, values, countdowns, truths); // Attachments ride the same round trip: ids become renderable file // references here, so the client never guesses media URLs and deleted // files simply drop off instead of rendering dead chips. const attachments = await resolveAttachments(payload, node.data.attachments); if (attachments.length > 0) resolved.attachments = attachments; return { success: true, data: resolved }; } 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 }; } } /** * Record that the reading user has seen one conversation node, so its NEW * badge clears on every device. Idempotent; the client fires this off * fire-and-forget as lines land in the log. */ export async function markNpcDialogueNodeRead( dialogueId: number, nodeId: string, ): Promise { try { const { payload, user } = await authenticate(); if (!Number.isInteger(dialogueId) || dialogueId <= 0 || !nodeId.trim()) { return { success: false, error: "Invalid conversation node reference." }; } await markNodeRead(payload, user.id as number, dialogueId, nodeId.trim()); return { success: true }; } 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 }; } } /** File types authors may attach to a conversation node. */ const ATTACHMENT_TYPES = new Set([ "text/plain", "application/pdf", "image/png", "image/jpeg", "image/webp", "image/gif", ]); /** * Upload a file to attach to a conversation node (intercept transcripts, * sealed orders, reference images). The bytes land in `media`; flowData only * keeps the returned pointer, and resolveNpcDialogueTexts turns it back into * a URL per read. Gated like dialogue authoring (npc-dialogues:update) since * this stores files the whole unit will be served. */ export async function uploadNpcDialogueAttachment( formData: FormData, ): Promise> { try { const { payload, user } = await authenticate(); const allowed = await hasPermission(payload, user, "npc-dialogues:update"); if (!allowed) { return { success: false, error: "You are not allowed to edit conversations." }; } const file = formData.get("file"); if (!(file instanceof File)) { return { success: false, error: "No file was provided." }; } if (!ATTACHMENT_TYPES.has(file.type)) { return { success: false, error: "Attachments must be text, PDF, or image files." }; } if (file.size > 8 * 1024 * 1024) { return { success: false, error: "Attachments must be 8 MB or smaller." }; } const doc = await payload.create({ collection: "media", data: { alt: file.name.replace(/\.[^/.]+$/, "").replace(/[^a-zA-Z0-9 _-]/g, "").trim() || "Attachment", }, file: { data: Buffer.from(await file.arrayBuffer()), mimetype: file.type, name: file.name, size: file.size, }, overrideAccess: true, }); if (!doc.filename) { return { success: false, error: "Upload failed: no file was stored." }; } return { success: true, data: { mediaId: doc.id, filename: doc.filename, mimeType: file.type }, }; } 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 }; } } /** 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; /** Which voice shaped the prompt, for the dialog's provenance line. */ promptSource: "builtin" | "global" | "dialogue"; promptRevision: number | null; /** True when the model hit its token cap, so the tail of the draft may be missing. */ truncated: boolean; } /** * The flag keys an author may reference in a generated conversation. Mirrors * the vocabulary `generateDialogueDraft` hands the model, so the dropdown and * the prompt cannot disagree. */ export async function listDialogueFlagKeys(): Promise< ActionResult<{ key: string; flagType: string }[]> > { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { return { success: false, error: "You do not have permission to edit conversations." }; } const res = await payload.find({ collection: "player-flags", limit: 200, depth: 0, pagination: false, overrideAccess: true, select: { key: true, flagType: true }, }); const seen = new Set(); const keys: { key: string; flagType: string }[] = []; for (const doc of res.docs) { const key = typeof doc.key === "string" ? doc.key.trim().toLowerCase() : ""; if (!key || seen.has(key)) continue; seen.add(key); keys.push({ key, flagType: String(doc.flagType ?? "boolean") }); } keys.sort((a, b) => a.key.localeCompare(b.key)); return { success: true, data: keys }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; if (message === "Unauthorized") { return { success: false, error: "You must be logged in." }; } return { success: false, error: message }; } } /** * The global prompt settings, for the dialogue editor's preview. * * Read-only and safe to expose to anyone who can author conversations: the voice * is copy, not a secret. The editor composes the preview client-side with the same * pure helpers the server uses, so unsaved voice edits show up immediately. */ export async function getDialoguePromptSettings(): Promise< ActionResult<{ voice: string | null; extraRules: string | null; revision: number | null }> > { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:read"))) { return { success: false, error: "You do not have permission to view conversations." }; } const settings = await loadDialogueSettings(payload); return { success: true, data: settings }; } 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, dialogueId?: number | null, ): Promise> { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { return { success: false, error: "You do not have permission to edit conversations." }; } if (!Number.isInteger(npcId) || npcId <= 0) { return { success: false, error: "Save this conversation against a contact first." }; } // Validate the brief before spending a model call on it: a vague brief // produces a vague draft, and the author cannot tell which was at fault. const goal = brief.goal?.trim() ?? ""; if (goal.length < 8) { return { success: false, error: "Describe what the player should learn or do." }; } if (!BRIEF_PURPOSES.includes(brief.purpose as BriefPurpose)) { return { success: false, error: "Pick a purpose for the conversation." }; } if (!BRIEF_TONES.includes(brief.tone as BriefTone)) { return { success: false, error: "Pick a tone for the conversation." }; } if (!BRIEF_OUTCOMES.includes(brief.outcome as BriefOutcome)) { return { success: false, error: "Pick an outcome for the conversation." }; } if (!DRAFT_SIZES.includes(brief.size as DraftSize)) { return { success: false, error: "Pick a conversation length." }; } if (brief.outcome === "set-flag" && !brief.flagKey?.trim()) { return { success: false, error: "Choose which flag the conversation should set." }; } const outcome = await generateDialogueDraft(payload, { npcId, brief: { ...brief, goal }, dialogueId: dialogueId ?? null, }); 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, promptSource: outcome.promptSource, promptRevision: outcome.promptRevision, 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; dialogueId?: number | null; }, ): Promise> { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { return { success: false, error: "You do not have permission to edit conversations." }; } if (!Number.isInteger(npcId) || npcId <= 0) { return { success: false, error: "Save this conversation against a contact first." }; } if (!REWRITE_ACTIONS.includes(input.action)) { return { success: false, error: "Unknown rewrite action." }; } const text = input.text?.trim() ?? ""; if (!text) { return { success: false, error: "Write a line first, then ask the model to work on it." }; } if (text.length > 2000) { return { success: false, error: "That line is too long to rewrite. Trim it first." }; } const outcome = await rewriteDialogueLine(payload, { npcId, action: input.action, text, nodeType: input.nodeType, previousLine: input.previousLine, dialogueId: input.dialogueId ?? null, }); 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 }; } }