Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

feat: Phase 2 — Mastra agents, SSE streaming, generation routes

Connorcfb41f551abd
diff --git a/server/src/agents/index.ts b/server/src/agents/index.ts
new file mode 100644
index 0000000..0e62094
--- /dev/null
+++ b/server/src/agents/index.ts
@@ -0,0 +1,102 @@
+/**
+ * Mastra Agent 定义
+ */
+import { Agent } from '@mastra/core/agent'
+import { Mastra } from '@mastra/core'
+import { createOpenAI } from '@ai-sdk/openai'
+import { getTextConfig } from '../services/ai.js'
+
+// Tools
+import { readEpisodeScript, rewriteToScreenplay, saveScript } from './tools/script-tools.js'
+import { readScriptForExtraction, saveCharacters, saveScenes } from './tools/extract-tools.js'
+import { readStoryboardContext, saveStoryboards, updateStoryboard } from './tools/storyboard-tools.js'
+
+function getModel() {
+ const config = getTextConfig()
+ const provider = createOpenAI({
+ baseURL: config.baseUrl,
+ apiKey: config.apiKey,
+ })
+ return provider(config.model)
+}
+
+// 剧本改写 Agent
+export const scriptRewriter = new Agent({
+ id: 'script_rewriter',
+ name: '剧本改写',
+ instructions: `你是专业编剧,擅长将小说改编为短剧剧本。
+
+工作流程:
+1. 调用 read_episode_script 读取原始内容
+2. 根据内容进行改写(使用格式化剧本格式)
+3. 调用 save_script 保存改写结果
+
+格式化剧本格式:
+- 场景头:## S编号 | 内景/外景 · 地点 | 时间段
+- 动作描写:自然段落,不包含镜头语言
+- 对白:角色名:(状态/表情)台词内容
+- 每个场景 30-60 秒内容`,
+ model: getModel(),
+ tools: { readEpisodeScript, rewriteToScreenplay, saveScript },
+})
+
+// 角色场景提取 Agent
+export const extractor = new Agent({
+ id: 'extractor',
+ name: '角色场景提取',
+ instructions: `你是制片助理,擅长从剧本中提取角色和场景信息。
+
+工作流程:
+1. 调用 read_script_for_extraction 读取格式化剧本
+2. 分析剧本,提取所有角色(名字、角色定位、外貌描述、性格特征)
+3. 调用 save_characters 保存角色列表
+4. 分析剧本,提取所有场景(地点、时间、视觉描述)
+5. 调用 save_scenes 保存场景列表
+
+提取要求:
+- 角色要包含完整的外貌特征描述(发型、服装、体态等)
+- 场景要包含光线、色调、氛围等视觉信息
+- 不要遗漏任何有台词或重要动作的角色`,
+ model: getModel(),
+ tools: { readScriptForExtraction, saveCharacters, saveScenes },
+})
+
+// 分镜拆解 Agent
+export const storyboardBreaker = new Agent({
+ id: 'storyboard_breaker',
+ name: '分镜拆解',
+ instructions: `你是资深影视分镜师,擅长将剧本拆解为分镜方案。
+
+工作流程:
+1. 调用 read_storyboard_context 读取剧本、角色列表、场景列表
+2. 将剧本拆解为镜头序列(每个镜头 10-15 秒)
+3. 为每个镜头生成视频提示词(video_prompt)
+4. 调用 save_storyboards 保存所有分镜
+
+视频提示词格式:
+- 按 3 秒为一段,用时间标记分隔
+- 使用 <location>地点</location> 标记场景
+- 使用 <role>角色名</role> 标记角色
+- 使用 <voice>角色名</voice> 标记画外音
+- 用 <n> 分隔不同时间段
+
+示例:
+"0-3秒:<location>咖啡厅</location>,近景,<role>小明</role>低头看手机。<n>3-6秒:全景,<role>小红</role>推门走入。"
+
+分镜要素:shot_number, title, shot_type, location, time, action, dialogue, video_prompt, duration, scene_id(从场景列表匹配)`,
+ model: getModel(),
+ tools: { readStoryboardContext, saveStoryboards, updateStoryboard },
+})
+
+// Agent 注册表
+export const agents: Record<string, Agent> = {
+ script_rewriter: scriptRewriter,
+ extractor: extractor,
+ storyboard_breaker: storyboardBreaker,
+}
+
+export function getAgent(type: string): Agent | undefined {
+ return agents[type]
+}
+
+export const validAgentTypes = Object.keys(agents)
diff --git a/server/src/agents/tools/extract-tools.ts b/server/src/agents/tools/extract-tools.ts
new file mode 100644
index 0000000..12a3d1b
--- /dev/null
+++ b/server/src/agents/tools/extract-tools.ts
@@ -0,0 +1,112 @@
+/**
+ * 角色/场景提取 Agent 工具
+ */
+import { createTool } from '@mastra/core/tools'
+import { z } from 'zod'
+import { db, schema } from '../../db/index.js'
+import { eq } from 'drizzle-orm'
+import { now } from '../../utils/response.js'
+
+// 读取剧本用于提取
+export const readScriptForExtraction = createTool({
+ id: 'read_script_for_extraction',
+ description: 'Read the formatted screenplay of an episode for character/scene extraction.',
+ inputSchema: z.object({
+ episode_id: z.number().describe('Episode ID'),
+ }),
+ execute: async ({ episode_id }) => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episode_id)).all()
+ if (!ep) return { error: 'Episode not found' }
+
+ const content = ep.scriptContent || ep.content
+ if (!content) return { error: 'Episode has no script content' }
+
+ // 获取 drama_id
+ return { script: content, drama_id: ep.dramaId, episode_id: ep.id }
+ },
+})
+
+// 保存提取的角色
+export const saveCharacters = createTool({
+ id: 'save_characters',
+ description: 'Save extracted characters to the database. Each character has name, role, description, appearance.',
+ inputSchema: z.object({
+ drama_id: z.number().describe('Drama ID'),
+ characters: z.array(z.object({
+ name: z.string(),
+ role: z.string().optional(),
+ description: z.string().optional(),
+ appearance: z.string().optional(),
+ personality: z.string().optional(),
+ })).describe('List of characters to save'),
+ }),
+ execute: async ({ drama_id, characters }) => {
+ const ts = now()
+ let count = 0
+ for (const char of characters) {
+ // 检查是否已存在
+ const existing = db.select().from(schema.characters)
+ .where(eq(schema.characters.dramaId, drama_id))
+ .all()
+ .find(c => c.name === char.name)
+
+ if (existing) {
+ db.update(schema.characters)
+ .set({ ...char, updatedAt: ts })
+ .where(eq(schema.characters.id, existing.id))
+ .run()
+ } else {
+ db.insert(schema.characters)
+ .values({ ...char, dramaId: drama_id, createdAt: ts, updatedAt: ts })
+ .run()
+ }
+ count++
+ }
+ return { message: `Saved ${count} characters`, count }
+ },
+})
+
+// 保存提取的场景
+export const saveScenes = createTool({
+ id: 'save_scenes',
+ description: 'Save extracted scenes/backgrounds to the database. Each scene has location, time, prompt.',
+ inputSchema: z.object({
+ drama_id: z.number().describe('Drama ID'),
+ scenes: z.array(z.object({
+ location: z.string(),
+ time: z.string().optional(),
+ prompt: z.string().optional().describe('Visual description for image generation'),
+ })).describe('List of scenes to save'),
+ }),
+ execute: async ({ drama_id, scenes }) => {
+ const ts = now()
+ let count = 0
+ for (const scene of scenes) {
+ const existing = db.select().from(schema.scenes)
+ .where(eq(schema.scenes.dramaId, drama_id))
+ .all()
+ .find(s => s.location === scene.location)
+
+ if (existing) {
+ db.update(schema.scenes)
+ .set({ time: scene.time || existing.time, prompt: scene.prompt || existing.prompt, updatedAt: ts })
+ .where(eq(schema.scenes.id, existing.id))
+ .run()
+ } else {
+ db.insert(schema.scenes)
+ .values({
+ dramaId: drama_id,
+ location: scene.location,
+ time: scene.time || '',
+ prompt: scene.prompt || scene.location,
+ createdAt: ts,
+ updatedAt: ts,
+ })
+ .run()
+ }
+ count++
+ }
+ return { message: `Saved ${count} scenes`, count }
+ },
+})
diff --git a/server/src/agents/tools/script-tools.ts b/server/src/agents/tools/script-tools.ts
new file mode 100644
index 0000000..17376c6
--- /dev/null
+++ b/server/src/agents/tools/script-tools.ts
@@ -0,0 +1,80 @@
+/**
+ * 剧本改写 Agent 工具
+ */
+import { createTool } from '@mastra/core/tools'
+import { z } from 'zod'
+import { db, schema } from '../../db/index.js'
+import { eq } from 'drizzle-orm'
+import { getTextConfig } from '../../services/ai.js'
+import { now } from '../../utils/response.js'
+
+// 读取剧本内容
+export const readEpisodeScript = createTool({
+ id: 'read_episode_script',
+ description: 'Read the script content of an episode. Returns the raw story/novel text or formatted screenplay.',
+ inputSchema: z.object({
+ episode_id: z.number().describe('Episode ID'),
+ }),
+ execute: async ({ episode_id }) => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episode_id)).all()
+ if (!ep) return { error: `Episode not found (id=${episode_id})` }
+
+ // 优先返回原始内容,回退到格式化剧本
+ const content = ep.content || ep.scriptContent
+ if (!content) return { error: `Episode has no content (id=${episode_id})` }
+ return { content, word_count: content.length }
+ },
+})
+
+// AI 改写剧本
+export const rewriteToScreenplay = createTool({
+ id: 'rewrite_to_screenplay',
+ description: 'Use AI to rewrite novel text into formatted screenplay format. Reads the episode content and rewrites it.',
+ inputSchema: z.object({
+ episode_id: z.number().describe('Episode ID to rewrite'),
+ instructions: z.string().optional().describe('Additional instructions for the rewrite'),
+ }),
+ execute: async ({ episode_id, instructions }) => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episode_id)).all()
+ if (!ep) return { error: `Episode not found` }
+
+ const source = ep.content || ep.scriptContent
+ if (!source) return { error: `Episode has no content to rewrite` }
+
+ // 返回内容让 agent LLM 自己改写(工具提供数据,LLM 做改写)
+ return {
+ source_content: source,
+ instruction: `请将以下内容改写为格式化剧本。
+
+格式规范:
+- 场景头:## S编号 | 内景/外景 · 地点 | 时间段
+- 动作描写:自然段落,不包含镜头语言
+- 对白:角色名:(状态/表情)台词内容
+- 每个场景 30-60 秒内容
+
+${instructions || ''}
+
+【原始内容】
+${source}`,
+ }
+ },
+})
+
+// 保存剧本
+export const saveScript = createTool({
+ id: 'save_script',
+ description: 'Save the rewritten screenplay content to an episode.',
+ inputSchema: z.object({
+ episode_id: z.number().describe('Episode ID to save to'),
+ content: z.string().describe('The formatted screenplay content to save'),
+ }),
+ execute: async ({ episode_id, content }) => {
+ db.update(schema.episodes)
+ .set({ scriptContent: content, updatedAt: now() })
+ .where(eq(schema.episodes.id, episode_id))
+ .run()
+ return { message: `Script saved to episode ${episode_id}`, word_count: content.length }
+ },
+})
diff --git a/server/src/agents/tools/storyboard-tools.ts b/server/src/agents/tools/storyboard-tools.ts
new file mode 100644
index 0000000..b0847dc
--- /dev/null
+++ b/server/src/agents/tools/storyboard-tools.ts
@@ -0,0 +1,142 @@
+/**
+ * 分镜拆解 Agent 工具
+ */
+import { createTool } from '@mastra/core/tools'
+import { z } from 'zod'
+import { db, schema } from '../../db/index.js'
+import { eq } from 'drizzle-orm'
+import { now } from '../../utils/response.js'
+
+// 读取剧本 + 角色 + 场景(为分镜拆解提供完整上下文)
+export const readStoryboardContext = createTool({
+ id: 'read_storyboard_context',
+ description: 'Read the formatted screenplay, characters, and scenes for storyboard breakdown.',
+ inputSchema: z.object({
+ episode_id: z.number().describe('Episode ID'),
+ }),
+ execute: async ({ episode_id }) => {
+ const [ep] = db.select().from(schema.episodes)
+ .where(eq(schema.episodes.id, episode_id)).all()
+ if (!ep) return { error: 'Episode not found' }
+
+ const script = ep.scriptContent || ep.content
+ if (!script) return { error: 'Episode has no script' }
+
+ const chars = db.select().from(schema.characters)
+ .where(eq(schema.characters.dramaId, ep.dramaId)).all()
+ const scns = db.select().from(schema.scenes)
+ .where(eq(schema.scenes.dramaId, ep.dramaId)).all()
+
+ return {
+ script,
+ drama_id: ep.dramaId,
+ episode_id: ep.id,
+ characters: chars.map(c => ({ id: c.id, name: c.name })),
+ scenes: scns.map(s => ({ id: s.id, location: s.location, time: s.time })),
+ }
+ },
+})
+
+// 保存分镜列表
+export const saveStoryboards = createTool({
+ id: 'save_storyboards',
+ description: 'Save generated storyboards to the database. Replaces existing storyboards for the episode.',
+ inputSchema: z.object({
+ episode_id: z.number().describe('Episode ID'),
+ storyboards: z.array(z.object({
+ shot_number: z.number(),
+ title: z.string().optional(),
+ shot_type: z.string().optional(),
+ angle: z.string().optional(),
+ movement: z.string().optional(),
+ location: z.string().optional(),
+ time: z.string().optional(),
+ action: z.string().optional(),
+ dialogue: z.string().optional(),
+ description: z.string().optional(),
+ result: z.string().optional(),
+ atmosphere: z.string().optional(),
+ video_prompt: z.string().optional(),
+ duration: z.number().optional(),
+ scene_id: z.number().nullable().optional(),
+ characters: z.array(z.number()).optional(),
+ })).describe('List of storyboard shots'),
+ }),
+ execute: async ({ episode_id, storyboards }) => {
+ const ts = now()
+
+ // 删除旧分镜
+ db.delete(schema.storyboards)
+ .where(eq(schema.storyboards.episodeId, episode_id))
+ .run()
+
+ // 插入新分镜
+ let totalDuration = 0
+ for (const sb of storyboards) {
+ db.insert(schema.storyboards).values({
+ episodeId: episode_id,
+ storyboardNumber: sb.shot_number,
+ title: sb.title,
+ shotType: sb.shot_type,
+ angle: sb.angle,
+ movement: sb.movement,
+ location: sb.location,
+ time: sb.time,
+ action: sb.action,
+ dialogue: sb.dialogue,
+ description: sb.description,
+ result: sb.result,
+ atmosphere: sb.atmosphere,
+ videoPrompt: sb.video_prompt,
+ sceneId: sb.scene_id,
+ duration: sb.duration || 10,
+ createdAt: ts,
+ updatedAt: ts,
+ }).run()
+ totalDuration += sb.duration || 10
+ }
+
+ // 更新 episode 时长
+ db.update(schema.episodes)
+ .set({ duration: Math.ceil(totalDuration / 60), updatedAt: ts })
+ .where(eq(schema.episodes.id, episode_id))
+ .run()
+
+ return {
+ message: `Saved ${storyboards.length} storyboards`,
+ count: storyboards.length,
+ total_duration: totalDuration,
+ }
+ },
+})
+
+// 更新单个分镜
+export const updateStoryboard = createTool({
+ id: 'update_storyboard',
+ description: 'Update a specific storyboard shot.',
+ inputSchema: z.object({
+ storyboard_id: z.number().describe('Storyboard ID'),
+ title: z.string().optional(),
+ shot_type: z.string().optional(),
+ video_prompt: z.string().optional(),
+ description: z.string().optional(),
+ dialogue: z.string().optional(),
+ duration: z.number().optional(),
+ }),
+ execute: async ({ storyboard_id, ...fields }) => {
+ const updates: Record<string, any> = { updatedAt: now() }
+ if (fields.title) updates.title = fields.title
+ if (fields.shot_type) updates.shotType = fields.shot_type
+ if (fields.video_prompt) updates.videoPrompt = fields.video_prompt
+ if (fields.description) updates.description = fields.description
+ if (fields.dialogue) updates.dialogue = fields.dialogue
+ if (fields.duration) updates.duration = fields.duration
+
+ db.update(schema.storyboards)
+ .set(updates)
+ .where(eq(schema.storyboards.id, storyboard_id))
+ .run()
+
+ return { message: `Storyboard ${storyboard_id} updated` }
+ },
+})
diff --git a/server/src/index.ts b/server/src/index.ts
index 131db38..1c6c54d 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -4,19 +4,27 @@ import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import path from 'path'
-
-import dramas from './routes/dramas'
-import episodes from './routes/episodes'
-import storyboards from './routes/storyboards'
-import scenes from './routes/scenes'
-import aiConfigs, { aiProviders } from './routes/aiConfigs'
-import agentConfigs from './routes/agentConfigs'
+import { fileURLToPath } from 'url'
+
+import dramas from './routes/dramas.js'
+import episodes from './routes/episodes.js'
+import storyboards from './routes/storyboards.js'
+import scenes from './routes/scenes.js'
+import characters from './routes/characters.js'
+import images from './routes/images.js'
+import videos from './routes/videos.js'
+import aiConfigs, { aiProviders } from './routes/aiConfigs.js'
+import agentConfigs from './routes/agentConfigs.js'
+import agent from './routes/agent.js'
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url))
+const projectRoot = path.resolve(__dirname, '../..')
const app = new Hono()
// Middleware
app.use('*', cors({
- origin: ['http://localhost:3012', 'http://localhost:5678'],
+ origin: ['http://localhost:3012', 'http://localhost:5678', 'http://localhost:5679'],
credentials: true,
}))
app.use('*', logger())
@@ -25,29 +33,29 @@ app.use('*', logger())
app.get('/api/v1/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }))
// API routes
-const api = app.basePath('/api/v1')
+const api = new Hono()
api.route('/dramas', dramas)
api.route('/episodes', episodes)
api.route('/storyboards', storyboards)
api.route('/scenes', scenes)
+api.route('/characters', characters)
+api.route('/images', images)
+api.route('/videos', videos)
api.route('/ai-configs', aiConfigs)
api.route('/ai-providers', aiProviders)
api.route('/agent-configs', agentConfigs)
+api.route('/agent', agent)
-// TODO: Phase 2 routes
-// api.route('/images', images)
-// api.route('/videos', videos)
-// api.route('/video-merges', videoMerges)
-// api.route('/agent', agent)
-// api.route('/characters', characters)
+app.route('/api/v1', api)
-// Serve frontend static files
-app.use('/static/*', serveStatic({ root: './data' }))
-app.use('*', serveStatic({ root: './web/dist' }))
+// Serve static files (storage)
+app.use('/static/*', serveStatic({ root: path.join(projectRoot, 'data') }))
-// SPA fallback
-app.get('*', serveStatic({ root: './web/dist', path: 'index.html' }))
+// Serve frontend
+const distPath = path.join(projectRoot, 'web', 'dist')
+app.use('*', serveStatic({ root: distPath }))
+app.get('*', serveStatic({ root: distPath, path: 'index.html' }))
const port = Number(process.env.PORT || 5679)
-console.log(`🚀 Huobao Drama TS server running on http://localhost:${port}`)
+console.log(`🚀 Huobao Drama TS server on http://localhost:${port}`)
serve({ fetch: app.fetch, port })
diff --git a/server/src/routes/agent.ts b/server/src/routes/agent.ts
new file mode 100644
index 0000000..3736337
--- /dev/null
+++ b/server/src/routes/agent.ts
@@ -0,0 +1,93 @@
+/**
+ * Agent SSE 聊天路由
+ */
+import { Hono } from 'hono'
+import { streamSSE } from 'hono/streaming'
+import { getAgent, validAgentTypes } from '../agents/index.js'
+import { success, badRequest } from '../utils/response.js'
+
+const app = new Hono()
+
+// POST /agent/:type/chat — SSE 流式 Agent 对话
+app.post('/:type/chat', async (c) => {
+ const agentType = c.req.param('type')
+ if (!validAgentTypes.includes(agentType)) {
+ return badRequest(c, `Invalid agent type: ${agentType}`)
+ }
+
+ const body = await c.req.json()
+ const { message, drama_id, episode_id } = body
+
+ const agent = getAgent(agentType)
+ if (!agent) return badRequest(c, 'Agent not found')
+
+ // 构建消息,注入上下文
+ const contextInfo = `[Context: drama_id=${drama_id}, episode_id=${episode_id}]`
+ const fullMessage = `${contextInfo}\n\n${message}`
+
+ return streamSSE(c, async (stream) => {
+ try {
+ const result = await agent.stream([
+ { role: 'user', content: fullMessage },
+ ])
+
+ // Stream fullStream for tool calls + text
+ for await (const chunk of result.fullStream) {
+ if (chunk.type === 'text-delta') {
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: 'content',
+ data: chunk.textDelta,
+ }),
+ })
+ } else if (chunk.type === 'tool-call') {
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: 'tool_call',
+ data: JSON.stringify(chunk.args),
+ tool_name: chunk.toolName,
+ }),
+ })
+ } else if (chunk.type === 'tool-result') {
+ const resultStr = typeof chunk.result === 'string'
+ ? chunk.result
+ : JSON.stringify(chunk.result)
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: 'tool_result',
+ data: resultStr.length > 2000 ? resultStr.slice(0, 2000) + '...[truncated]' : resultStr,
+ tool_name: chunk.toolName,
+ }),
+ })
+ }
+ }
+
+ // Done
+ await stream.writeSSE({
+ data: JSON.stringify({ type: 'done', data: '' }),
+ })
+ } catch (err: any) {
+ await stream.writeSSE({
+ data: JSON.stringify({
+ type: 'error',
+ data: err.message || 'Agent execution failed',
+ }),
+ })
+ }
+ })
+})
+
+// GET /agent/:type/debug
+app.get('/:type/debug', async (c) => {
+ const agentType = c.req.param('type')
+ const agent = getAgent(agentType)
+ if (!agent) return badRequest(c, 'Invalid agent type')
+
+ return success(c, {
+ agent_type: agentType,
+ name: agent.name,
+ tools: Object.keys(agent.tools || {}),
+ })
+})
+
+export default app
diff --git a/server/src/routes/characters.ts b/server/src/routes/characters.ts
new file mode 100644
index 0000000..18ef4ef
--- /dev/null
+++ b/server/src/routes/characters.ts
@@ -0,0 +1,45 @@
+import { Hono } from 'hono'
+import { eq } from 'drizzle-orm'
+import { db, schema } from '../db/index.js'
+import { success, notFound, now } from '../utils/response.js'
+
+const app = new Hono()
+
+// PUT /characters/:id
+app.put('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ const body = await c.req.json()
+ const updates: Record<string, any> = { updatedAt: now() }
+ for (const key of ['name', 'role', 'description', 'appearance', 'personality', 'voiceStyle', 'imageUrl', 'localPath']) {
+ const snakeKey = key.replace(/[A-Z]/g, m => '_' + m.toLowerCase())
+ if (snakeKey in body) updates[key] = body[snakeKey]
+ else if (key in body) updates[key] = body[key]
+ }
+ await db.update(schema.characters).set(updates).where(eq(schema.characters.id, id))
+ return success(c)
+})
+
+// DELETE /characters/:id
+app.delete('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ await db.update(schema.characters).set({ deletedAt: now() }).where(eq(schema.characters.id, id))
+ return success(c)
+})
+
+// POST /characters/:id/generate-image (placeholder)
+app.post('/:id/generate-image', async (c) => {
+ const id = Number(c.req.param('id'))
+ await db.update(schema.characters)
+ .set({ imageGenerationStatus: 'pending', updatedAt: now() })
+ .where(eq(schema.characters.id, id))
+ return success(c, { message: 'Image generation queued' })
+})
+
+// POST /characters/batch-generate-images (placeholder)
+app.post('/batch-generate-images', async (c) => {
+ const body = await c.req.json()
+ const ids = body.character_ids || []
+ return success(c, { message: `Queued ${ids.length} characters`, count: ids.length })
+})
+
+export default app
diff --git a/server/src/routes/images.ts b/server/src/routes/images.ts
new file mode 100644
index 0000000..3f9a302
--- /dev/null
+++ b/server/src/routes/images.ts
@@ -0,0 +1,45 @@
+import { Hono } from 'hono'
+import { eq } from 'drizzle-orm'
+import { db, schema } from '../db/index.js'
+import { success, created, now } from '../utils/response.js'
+
+const app = new Hono()
+
+// POST /images — Generate image (placeholder)
+app.post('/', async (c) => {
+ const body = await c.req.json()
+ const ts = now()
+ const [result] = await db.insert(schema.imageGenerations).values({
+ storyboardId: body.storyboard_id,
+ dramaId: body.drama_id,
+ prompt: body.prompt,
+ model: body.model,
+ status: 'pending',
+ frameType: body.frame_type,
+ createdAt: ts,
+ updatedAt: ts,
+ }).returning()
+ return created(c, result)
+})
+
+// GET /images/:id
+app.get('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ const [row] = await db.select().from(schema.imageGenerations)
+ .where(eq(schema.imageGenerations.id, id))
+ return success(c, row || null)
+})
+
+// DELETE /images/:id
+app.delete('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ await db.delete(schema.imageGenerations).where(eq(schema.imageGenerations.id, id))
+ return success(c)
+})
+
+// POST /images/episode/:episode_id/batch (placeholder)
+app.post('/episode/:episode_id/batch', async (c) => {
+ return success(c, { message: 'Batch generation queued' })
+})
+
+export default app
diff --git a/server/src/routes/videos.ts b/server/src/routes/videos.ts
new file mode 100644
index 0000000..3b70510
--- /dev/null
+++ b/server/src/routes/videos.ts
@@ -0,0 +1,41 @@
+import { Hono } from 'hono'
+import { eq } from 'drizzle-orm'
+import { db, schema } from '../db/index.js'
+import { success, created, now } from '../utils/response.js'
+
+const app = new Hono()
+
+// POST /videos — Generate video (placeholder)
+app.post('/', async (c) => {
+ const body = await c.req.json()
+ const ts = now()
+ const [result] = await db.insert(schema.videoGenerations).values({
+ storyboardId: body.storyboard_id,
+ dramaId: body.drama_id,
+ prompt: body.prompt,
+ model: body.model,
+ referenceMode: body.reference_mode,
+ imageUrl: body.image_url,
+ status: 'pending',
+ createdAt: ts,
+ updatedAt: ts,
+ }).returning()
+ return created(c, result)
+})
+
+// GET /videos/:id
+app.get('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ const [row] = await db.select().from(schema.videoGenerations)
+ .where(eq(schema.videoGenerations.id, id))
+ return success(c, row || null)
+})
+
+// DELETE /videos/:id
+app.delete('/:id', async (c) => {
+ const id = Number(c.req.param('id'))
+ await db.delete(schema.videoGenerations).where(eq(schema.videoGenerations.id, id))
+ return success(c)
+})
+
+export default app
diff --git a/server/src/services/ai.ts b/server/src/services/ai.ts
new file mode 100644
index 0000000..18a6d29
--- /dev/null
+++ b/server/src/services/ai.ts
@@ -0,0 +1,50 @@
+/**
+ * AI 服务抽象层 — 从数据库配置中获取 provider 和 API key
+ */
+import { db, schema } from '../db/index.js'
+import { eq } from 'drizzle-orm'
+
+export interface AIConfig {
+ provider: string
+ baseUrl: string
+ apiKey: string
+ model: string
+}
+
+/**
+ * 获取指定服务类型的活跃 AI 配置
+ */
+export function getActiveConfig(serviceType: 'text' | 'image' | 'video'): AIConfig | null {
+ const rows = db.select().from(schema.aiServiceConfigs)
+ .where(eq(schema.aiServiceConfigs.serviceType, serviceType))
+ .all()
+
+ const active = rows.find(r => r.isActive)
+ if (!active) return null
+
+ const models = active.model ? JSON.parse(active.model) : []
+ return {
+ provider: active.provider || '',
+ baseUrl: active.baseUrl,
+ apiKey: active.apiKey,
+ model: models[0] || '',
+ }
+}
+
+/**
+ * 构建 Mastra 模型标识符
+ * 格式:provider/model(如 openai/gpt-4o)
+ * 对于 chatfire 等中转服务,使用 openai compatible 模式
+ */
+export function getModelId(serviceType: 'text' | 'image' | 'video' = 'text'): string {
+ const config = getActiveConfig(serviceType)
+ if (!config) throw new Error(`No active ${serviceType} AI config`)
+ // chatfire/openrouter 等中转站用 openai compatible 模式
+ return config.model
+}
+
+export function getTextConfig(): AIConfig {
+ const config = getActiveConfig('text')
+ if (!config) throw new Error('No active text AI config')
+ return config
+}