Add AI-assisted world and character drafting flows
All checks were successful
CI / validate (push) Successful in 14m3s

This commit is contained in:
2026-08-17 09:25:37 +05:00
parent 830aa5dc1f
commit cdeea8653c
23 changed files with 811 additions and 92 deletions

View File

@@ -0,0 +1,77 @@
import { CharacterDraftSchema } from '@dng/shared'
import { z } from 'zod'
import { buildJsonCompletion, parseJsonCompletion } from '~/server/utils/ai-provider'
import {
requireCampaignAccess,
requireStageTwoSafeText,
requireStageTwoUser,
stageTwoApiError,
stageTwoDatabase,
stageTwoUuid,
} from '~/server/utils/stage-two-supabase'
const BodySchema = z.object({
concept: z.string().trim().max(600).default(''),
controller: z.enum(['human', 'ai']).default('human'),
}).strict()
export default defineEventHandler(async (event) => {
try {
const user = await requireStageTwoUser(event)
const campaignId = stageTwoUuid(getRouterParam(event, 'id'), 'campaign id')
const access = await requireCampaignAccess(campaignId, user.id)
const body = BodySchema.parse((await readBody(event)) ?? {})
if (body.controller === 'ai' && !access.owner) {
throw createError({ statusCode: 403, statusMessage: 'Only the campaign owner can add AI heroes.' })
}
if (body.concept) requireStageTwoSafeText(body.concept)
const worlds = await stageTwoDatabase<Array<Record<string, unknown>>>(
`worlds?select=title,genre,tone,premise,content_boundaries&` +
`id=eq.${String(access.campaign.world_id)}&limit=1`,
)
const world = worlds[0]
if (!world) throw createError({ statusCode: 404, statusMessage: 'Campaign world not found.' })
const completion = buildJsonCompletion(useRuntimeConfig(), {
system: `You create an original, editable Dungeons & Ground character draft for a private 13+ TTRPG campaign. Adapt archetype, equipment and voice to the supplied genre, but always use STR, DEX, CON, INT, WIS and CHA. Keep an alpha hero grounded: ability scores 716, max HP 820, Defense 1016, proficiency 2. Give 25 useful starting items and a distinctive persona. Never use protected franchise characters. Return only the requested JSON.`,
messages: [{
role: 'user',
content: JSON.stringify({
world,
currentScene: access.campaign.current_scene,
heroKind: body.controller === 'ai' ? 'persistent AI companion' : 'human player character',
requestedConcept: body.concept || 'Surprise me with a character who creates interesting choices for this party.',
}),
}],
schemaName: 'character_draft',
jsonSchema: CharacterDraftSchema.toJSONSchema(),
})
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 30_000)
let response: Response
try {
response = await fetch(completion.endpoint, {
method: 'POST',
headers: completion.headers,
body: JSON.stringify(completion.body),
signal: controller.signal,
})
} finally {
clearTimeout(timeout)
}
if (!response.ok) throw createError({ statusCode: 502, statusMessage: 'The character coauthor is temporarily unavailable.' })
let character
try {
character = CharacterDraftSchema.parse(parseJsonCompletion(await response.json()))
} catch {
throw createError({ statusCode: 502, statusMessage: 'The coauthor returned an invalid character draft.' })
}
requireStageTwoSafeText(JSON.stringify(character))
return { character }
} catch (error) {
stageTwoApiError(error)
}
})