"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 { canSeeTestingDialogues, loadPlayerDialogue } from "@/lib/npc-dialogue/visibility"; import { resolveAttachments, resolveVoiceClip } from "@/lib/npc-dialogue/attachments"; import { transcodeToMp3, MP3_MIMETYPE } from "@/lib/voiceover/transcode"; import { hasPermission } from "@/utils/access-control/hasPermission"; import { launchDialoguePoll } from "@/lib/polls/service"; 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( dialogueId: number, npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); // The client names the conversation it is in; the id is verified (right // NPC, and visible to this reader) instead of trusted, so an unreleased // testing conversation cannot be read by guessing a node id. const dialogue = await loadPlayerDialogue(payload, { npcId, dialogueId, userId: user.id as number, canSeeTesting: await canSeeTestingDialogues(payload, user), }); const flowData = dialogue?.flowData; 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; const result = await runEffect(payload, { userId: user.id as number, npcId, dialogueId, nodeId, effect, }); return { success: true, data: result }; } 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>, context: { userId: number; npcId: number; dialogueId: number; nodeId: string; effect: NpcDialogueEffect; }, ): Promise<{ pollId: number } | undefined> { const { userId, npcId, dialogueId, nodeId, effect } = context; 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; } case "poll": { // Idempotent: the node raises the poll once, and every later player who // reaches it joins the same poll instead of opening a second one. const { poll, created } = await launchDialoguePoll(payload, { dialogueId, nodeId, initiatorId: userId, config: effect.poll, }); // The conversation hands the player a durable way back to the poll, and // says whether they are the one who opened it. await notifyUser(payload, { userId, type: "poll:open", title: poll.title, message: created ? "The unit is being polled. Cast your vote." : "This poll is already open. Cast your vote.", link: `/polls/${poll.id}`, }); return { pollId: poll.id }; } } } /** * 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( dialogueId: number, npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); // The client names the conversation it is in; the id is verified (right // NPC, and visible to this reader) instead of trusted, so an unreleased // testing conversation cannot be read by guessing a node id. const dialogue = await loadPlayerDialogue(payload, { npcId, dialogueId, userId: user.id as number, canSeeTesting: await canSeeTestingDialogues(payload, user), }); const flowData = dialogue?.flowData; 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( dialogueId: number, npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); // The client names the conversation it is in; the id is verified (right // NPC, and visible to this reader) instead of trusted, so an unreleased // testing conversation cannot be read by guessing a node id. const dialogue = await loadPlayerDialogue(payload, { npcId, dialogueId, userId: user.id as number, canSeeTesting: await canSeeTestingDialogues(payload, user), }); const flowData = dialogue?.flowData; 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( dialogueId: number, npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); // The client names the conversation it is in; the id is verified (right // NPC, and visible to this reader) instead of trusted, so an unreleased // testing conversation cannot be read by guessing a node id. const dialogue = await loadPlayerDialogue(payload, { npcId, dialogueId, userId: user.id as number, canSeeTesting: await canSeeTestingDialogues(payload, user), }); const flowData = dialogue?.flowData; 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; // Voice clips resolve the same way: a pointer in flowData, a URL per read. const voice = await resolveVoiceClip(payload, node.data.voice); if (voice) resolved.voice = voice; 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 }; } } /** Audio container types a browser recording or an audio editor produces. */ const VOICE_INPUT_TYPES = new Set([ "audio/mpeg", "audio/mp3", "audio/wav", "audio/x-wav", "audio/webm", "audio/ogg", "audio/mp4", "audio/aac", "audio/flac", "video/webm", // Chrome reports MediaRecorder output as video/webm. ]); /** Hard cap on a raw upload; a line read is seconds, not minutes. */ const VOICE_MAX_BYTES = 12 * 1024 * 1024; /** * Store an audio file in `media` for a conversation line. * * Recordings arrive as WebM/Opus (or AAC in Safari), which iOS will not always * play and which bloats the page, so anything that is not already MP3 goes * through ffmpeg first. If transcoding fails the original is stored as-is * rather than losing the take, and the browser falls back to its own decoder. * * Gated like dialogue authoring: this stores a file the whole unit will hear. */ export async function uploadNpcDialogueVoice( formData: FormData, ): Promise> { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { 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 (!VOICE_INPUT_TYPES.has(file.type)) { return { success: false, error: "Voice clips must be audio files." }; } if (file.size > VOICE_MAX_BYTES) { return { success: false, error: "Voice clips must be 12 MB or smaller." }; } const original = Buffer.from(await file.arrayBuffer()); const isMp3 = file.type === "audio/mpeg" || file.type === "audio/mp3"; const mp3 = isMp3 ? null : await transcodeToMp3(original, file.name); const bytes = mp3?.buffer ?? original; const mimetype = mp3?.mimetype ?? file.type; const name = mp3?.name ?? file.name; const doc = await payload.create({ collection: "media", data: { alt: file.name.replace(/\.[^/.]+$/, "").slice(0, 80) || "Voice clip" }, file: { data: bytes, mimetype, name, size: bytes.length }, 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: mimetype } }; } 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 }; } } /** One accepted recording a line can borrow. */ export interface AcceptedVoiceTake { id: number; label: string; } /** * Accepted voiceover submissions, for the "import an accepted take" picker. * Recruiting is the existing flow: staff write a VoiceScript, players record * it, staff accept it, and the accepted audio becomes a candidate here. */ export async function listAcceptedVoiceTakes(): Promise> { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { return { success: false, error: "You are not allowed to edit conversations." }; } const res = await payload.find({ collection: "voice-submissions", where: { status: { equals: "accepted" } }, limit: 100, depth: 1, sort: "-createdAt", overrideAccess: true, }); return { success: true, data: res.docs.map((doc) => { const script = doc.script as unknown as { title?: string } | number | null; const title = typeof script === "object" && script ? (script.title ?? "Script") : "Script"; const submitter = doc.user as unknown as { username?: string } | number | null; const who = typeof submitter === "object" && submitter ? submitter.username ?? "unknown" : "unknown"; return { id: doc.id, label: `${title} - @${who} (#${doc.id})` }; }), }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; return { success: false, error: message }; } } /** * Copy an accepted voiceover take into `media` so a line can play it. * * The copy (rather than pointing at the submission) keeps one playback path and * one permission story: `media` is publicly readable, while `voice-submissions` * access is owner-scoped. Reviewer replays of the original keep working because * the submission itself is untouched. */ export async function importNpcDialogueVoice( submissionId: number, ): Promise> { try { const { payload, user } = await authenticate(); if (!(await hasPermission(payload, user, "npc-dialogues:update"))) { return { success: false, error: "You are not allowed to edit conversations." }; } const submission = await payload.findByID({ collection: "voice-submissions", id: submissionId, depth: 1, overrideAccess: true, }); if (!submission) return { success: false, error: "That take no longer exists." }; if (submission.status !== "accepted") { return { success: false, error: "Only accepted takes can be imported." }; } const filename = submission.filename; if (!filename) return { success: false, error: "That take has no audio file." }; const { readFile } = await import("node:fs/promises"); const path = await import("node:path"); const filePath = path.resolve(process.cwd(), "media", "voice-submissions", filename); let bytes: Buffer; try { bytes = await readFile(filePath); } catch { return { success: false, error: "That take's audio file is missing on disk." }; } // Normalise to MP3 so every line plays the same way on every device. const mp3 = submission.mimeType === MP3_MIMETYPE ? null : await transcodeToMp3(bytes, filename); const stored = mp3?.buffer ?? bytes; const mimetype = mp3?.mimetype ?? submission.mimeType ?? MP3_MIMETYPE; const name = mp3?.name ?? filename; const doc = await payload.create({ collection: "media", data: { alt: `Voice take #${submissionId}` }, file: { data: stored, mimetype, name, size: stored.length }, overrideAccess: true, }); if (!doc.filename) { return { success: false, error: "Import failed: no file was stored." }; } return { success: true, data: { mediaId: doc.id, filename: doc.filename, mimeType: mimetype } }; } 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"; /** Whether this is a whole conversation or one branch of one. */ scope: "full" | "fragment"; promptRevision: number | null; /** The admin connection that served the model, or null for the env defaults. */ connectionLabel: string | 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, options?: { scope?: "full" | "fragment"; insertionHint?: string | 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 scope = options?.scope === "fragment" ? "fragment" : "full"; const outcome = await generateDialogueDraft(payload, { npcId, brief: { ...brief, goal }, dialogueId: dialogueId ?? null, scope, insertionHint: options?.insertionHint ?? 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, connectionLabel: outcome.connectionLabel, scope, 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 }; } }