infinite-creation
本地全链路「小说/剧本 → 漫剧/短视频」创作 Agent 解决方案。三种用法:①启动本项目一键跑;②不启动本项目,Agent 按本规范 + skills/ 技能库复刻全流程(剧本→人物圣经/风格→资产生图→分镜→逐镜视频→合并成片);③接入用户自定义的文生图/图生图/视频/语音 ComfyUI 工作流。当用户要克隆/安装/启动本项目、或用本项目方案生成漫剧/短视频、或接入自定义工作流时使用。
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Check it deeper on your machine
It has changed since its scan on 14 Nov 2026. Its scripts were only partly scanned.
As a Claude Code plugin, install it and then ask Claude Code:
/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/SwotAtmk/infinite-creation with scanskillsafety
Or from a terminal, clone it and run it:
git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/SwotAtmk/infinite-creation'
It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.
Badge for your README
Markdown
[](/listings/swotatmk--infinite-creation)HTML
<a href="/listings/swotatmk--infinite-creation"><img src="/api/listings/swotatmk--infinite-creation/badge.svg" alt="findsafeskills safety rating" /></a>Install
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
SKILL.md · Manifest · 162 lines
- ---
- name: infinite-creation
- description: 本地全链路「小说/剧本 → 漫剧/短视频」创作 Agent 解决方案。三种用法:①启动本项目一键跑;②不启动本项目,Agent 按本规范 + skills/ 技能库复刻全流程(剧本→人物圣经/风格→资产生图→分镜→逐镜视频→合并成片);③接入用户自定义的文生图/图生图/视频/语音 ComfyUI 工作流。当用户要克隆/安装/启动本项目、或用本项目方案生成漫剧/短视频、或接入自定义工作流时使用。
- ---
- # Agent无限创作 · 本地全链路漫剧/短视频创作 Agent 解决方案
- ## 一、项目介绍
- 把小说/剧本**全自动**生成带语音的漫剧/短视频成片,不限时长。本地跑通「ComfyUI(MiniMax H3 视频 + Qwen-Image 2.1 文生图/图生图 + Krea2 + Qwen3-TTS)+ Agent + Skill」的全链路。
- **核心流程(也是本方案可复刻的方法论)**:
- ```
- 小说/剧本/想法
- → 剧本 + 大纲
- → 人物圣经(bible)+ 风格指南(style) ← 一致性锚点
- → 人物/场景/道具/语音资产生成
- → 分镜脚本(长镜头聚合,不拆碎)
- → 逐镜视频(MiniMax H3 Ref2VA,参考图 + 参考音 → 带语音视频)
- → 自审重试
- → ffmpeg 合并成片
- ```
- **核心能力**:无限视频时长、自动分镜、项目隔离、人物一致性(canonical 参考图跨镜复用)、技能系统、自迭代技能工厂(工作流 → 技能)、断点续跑、分镜级审查/重生成、分阶段运行、显存维护、在线预览。
- **技术栈**:Node.js(Next.js 自定义 server)+ node:sqlite + ComfyUI REST/WebSocket + ffmpeg;Agent 自研 ReAct 循环;前端 Next.js 15 + React 18。
- ## 二、快速启动(启动本项目)
- ### 前置要求
- | 依赖 | 最低版本 | 用途 |
- |------|----------|------|
- | Node.js | ≥ 22 | 内置 `node:sqlite` |
- | pnpm | ≥ 9 | 依赖管理 |
- | Bun | 最新 | `pnpm install` 时自动构建 Agent 内核 |
- | ffmpeg | 最新 | 合并成片 |
- | ComfyUI | — | 生成图片/视频/语音必需(默认 `http://127.0.0.1:8188`) |
- ### 安装 / 配置 / 启动 / 验证
- ```bash
- git clone https://github.com/SwotAtmk/infinite-creation.git
- # 国内加速使用:https://gitcode.com/SwotAtmk/infinite-creation.git
- cd infinite-creation
- pnpm install # 自动构建 Agent 内核(首次较慢,需 bun)
- pnpm run install:skills # 可选:拉取 MiniMax-H3 官方技能(仓库已含离线快照)
- cp config.example.json config.json # 填 llm.apiKey 与 comfyui.baseUrl
- pnpm run dev # 前台启动 Studio(后端 4610 + 前端 4710,实时日志),打开 http://127.0.0.1:4710
- pnpm run dev:background # 后台启动 Studio(日志写入 logs/ 与 studio/logs/)
- pnpm run dev:classic # 经典界面:单端口 4600,打开 http://127.0.0.1:4600
- pnpm test # 单元测试
- curl http://127.0.0.1:4610/api/health # 期望 {"ok":true}
- ```
- ### 常见问题
- - 「未检测到 bun」→ 先装 Bun(https://bun.sh)
- - Agent 内核构建失败 → `pnpm run build:agent`
- - 生成不了图片/视频 → 确认 ComfyUI 已启动且 `comfyui.baseUrl` 正确
- - 端口占用 → 改 `config.json` 的 `server.port` 或设 `PORT`
- ## 三、全链路流程(可脱离本项目复刻的方法论)
- > 本节是核心方案。**不启动本项目**时,Agent 可照此流程 + `skills/` 技能库,在任意环境实现同样的「小说 → 视频」。
- 四阶段调度(本项目内由生成页勾选;复刻时按同样顺序编排):
- | 阶段 | 做什么 | 依赖 | 产出 |
- |------|--------|------|------|
- | `llm` 文本创作 | 写人物圣经/风格、资产提示词、拆分镜、写视频提示词 | LLM | 大纲、bible/style、分镜、prompt |
- | `image` 资产生图 | 人物/场景/道具出图 | ComfyUI 文生图/图生图 | 角色三视图、场景图、道具图、服装/年龄变体 |
- | `tts` 音色设计 | 人物音色样本 | ComfyUI TTS | 每个角色的 voice_ref |
- | `video` 分镜视频 | 逐镜出带语音视频 + 合并 | ComfyUI r2v + ffmpeg | 分镜视频、成片 |
- 分步约定(与 `skills/novel-to-video/SKILL.md` 一致):
- 1. **剧本/大纲**:输入小说或想法 → 产出 title/logline/characters/scenes/props/storyboard 大纲 JSON。
- 2. **一致性锚点**:`bible.md`(每个角色唯一外貌/配色/声音;默认一套着装,仅换装事件后补记新一套)+ `style.md`(统一画风/光线/色调/镜头语言)。
- 3. **资产生成**:先加载 `image-prompt-writing` 写图片提示词、`tts-voice-design` 写音色参数,再统一批量提交(文生图人物/场景/道具;仅确有换装事件/时间跳跃时才生成服装/年龄变体,避免冗余素材;TTS 音色)。
- 4. **分镜脚本**:加载 `story-pipeline-cn` 按「长镜头聚合」拆分(同一场景连续动作+多句对白合并,禁止一句一镜),字段含景别/运镜/光线/画面/对白/sub_shots 时间轴。
- 5. **视频提示词**:加载 `h3-prompt-writing`,逐镜写 `__MINIMAX_H3_REF_N__` 参考标签 + 英文平铺提示词,再整章批量生成。
- 6. **自审重试**:逐镜自审、失败重试。
- 7. **合并导出**:ffmpeg 合并成片。
- ## 四、技能库与使用规范
- ### 技能发现与加载
- - 技能库在 `skills/` 目录:每个子目录一份 `SKILL.md`(YAML frontmatter:`name` + `description`)+ 可选 `references/`(细分规范)。
- - 本项目内加载:`skill(name)` 读技能正文,`skill_reference(name, ref)` 读单个参考文件。
- - 脱离本项目时:直接把 `skills/` 当作可移植技能包使用(每个 `SKILL.md` 自带触发条件与执行步骤)。
- - **路由规则**:按任务关键词路由到对应技能;未命中时默认走 `novel-to-video`(总流水线)。
- ### 核心流程技能(5 个,必读)
- | 技能 | 用途 | 调用时机 |
- |------|------|----------|
- | `novel-to-video` | 总流水线(全链路编排) | 用户要「小说 → 成片」 |
- | `story-pipeline-cn` | 小说→剧本→分镜拆分(模式 A/B/C) | 写剧本、拆分镜 |
- | `image-prompt-writing` | 图片/图生图提示词规范 | 写资产生图/换装/年龄提示词 |
- | `h3-prompt-writing` | MiniMax H3 视频提示词 + 参考标签规范 | 写逐镜视频提示词 |
- | `tts-voice-design` | 人物音色设计规范 | 设计人物音色 |
- ### 其余技能库(按类别)
- - **剧本/编剧**:`0715-scriptwriter`、`script-master`、`novel-to-skitscreenplay`、`novel-to-storyboard`、`hf-drama-storyboard-script`。
- - **漫剧创作**:`manga-drama-generator`、`manju-director-agent`、`ai-manga-planner`、`comic-drama-generator`、`manga-full-stack`、`script-to-manga`、`cinematic-ai-comic-director`、`micro-drama-creator`。
- - **一致性/其它类型**:`era-consistency-optimizer`(年代一致)、`3d-animation-short-generator`、`papercraft-stop-motion-explainer`、`paper-collage-explainer-generator`、`music-video-subtitle-generator`、`minimalist-product-ad-generator`、`handdrawn-live-video-generator`、`co-op-game-intro-generator`、`brand-promo-video-generator`。
- - **小说写作(网文)**:`ultimate-novel`(路由)、`ultimate-novel-setup`、`ultimate-novel-market-data`、`ultimate-novel-benchmark`、`ultimate-novel-long-scan`、`ultimate-novel-long-analyze`、`ultimate-novel-long-write`、`ultimate-novel-short-scan`、`ultimate-novel-short-analyze`、`ultimate-novel-short-write`、`ultimate-novel-import`、`ultimate-novel-review`、`ultimate-novel-deslop`、`ultimate-novel-cover`、`ultimate-novel-performance-review`。
- - **导演分镜优化**:`storyboard_optimization_skill`(项导轻量版V1.8,已有资产/小说转分镜/最终视频提示词)。
- (完整技能清单以 `skills/` 目录实际为准,每个 `SKILL.md` 的 frontmatter `description` 是权威触发条件。)
- ## 五、自定义工作流接入
- 用户若有**自己的** ComfyUI 工作流,可按四类 `kind` 接入,替代默认工作流:
- | kind | 含义 | 典型产出 |
- |------|------|----------|
- | `t2i` | 文生图 | 角色/场景/道具图 |
- | `i2i` | 图生图 / 图像编辑 | 换装、年龄变体、参考图派生 |
- | `r2v` | 参考图/参考音 → 视频 | 分镜镜头视频 |
- | `tts` | 音色/语音 | 人物 voice_ref |
- ### 工作流规格(Workflow Spec)
- 每个工作流用一个「规格」描述如何往 ComfyUI JSON 里写参数。核心字段:
- - `roles`:语义角色 → `{ node, field, map? }`。常见角色:`positive_prompt`/`negative_prompt`/`width`/`height`/`seed`/`seconds`/`resolution`/`aspect_ratio`/`image`/`text`/`voice_description`/`filename_prefix`;`map` 用于枚举值翻译(如 `'16:9' → '16:9 (Widescreen)'`)。
- - `media`(可选,r2v 必需):参考素材绑定 —— `targetNode` + `mediaField`/`fieldsByType` + `loaders`(LoadImage/LoadAudio/LoadVideo)+ `reusePool` + `maxImages`(≤9)/`maxAudioVideo`(≤3)。
- - `outputs`:产物节点类(`SaveImage`/`SaveVideo`/`SaveAudio`/`SaveAnimatedWEBP`…)。
- - `prune`:需删除的节点 id(模板自带硬编码占位参考图/音、被覆盖的 LLM 改写链)。
- 参考示例见 `lib/core/workflow-specs.js` 的 `DEFAULT_SPECS`(内含 MiniMax H3 r2v、Qwen-Image 2.1/Krea2 t2i、Qwen-Image-Edit i2i、Qwen3-TTS tts 的完整规格)。
- ### 两种接入方式
- **方式 A · 启动本项目(推荐,自动)**:工作流页粘贴 ComfyUI 工作流 JSON → 「分析节点/角色」→「注册工作流 + 生成技能」。系统会:解析节点(加载器/提示词/尺寸/种子/保存)→ 推导规格 → 注册到 `workflows/` + DB → 调用 LLM 起草 `SKILL.md` 并安装为可路由技能 → Agent 立即可当新「工作模式」调用。
- **方式 B · 不启动本项目(Agent 手工映射)**:Agent 按上方「工作流规格」字段,把用户提供的 ComfyUI JSON 手动整理成规格(roles/media/outputs/prune),再复刻 `workflow-runner` 的「克隆模板 → 写 roles 参数 → 绑定 media 参考 → prune 无效节点 → 提交 ComfyUI」流程。解析逻辑参考 `analyzeWorkflow()`(识别 LoadImage/LoadAudio/LoadVideo、Save*、KSampler、prompt/text 字段、seed、尺寸)。
- ## 六、外部 Agent 通过 API 写入内容(harness 写入)
- 外部 harness(opencode 等)可以把**文本内容**写进一个正在运行的实例:新建项目、小说原文、剧本、分镜、人物圣经/风格。
- - **技能**:`harness-skills/ic-writer/SKILL.md`(端点速查 + 铁律;放在 `skills/` 之外,避免被 `scanSkills()` 当成应用内 Agent 的技能)。装到 harness 技能目录:`node scripts/install-writer-skill.mjs`(默认 `~/.agents/skills/ic-writer`,新技能需重启会话)。
- - **只走 API**:读写一律通过 `{base}/api/...`;**禁止**直连 `data/ic.db`(只读也不行)、手改 `data/` 下的文件或 `config.json`——绕过去就没有变更日志,既不可回滚,`source`/`batch_id` 也记不上。
- - **只写 LLM 文本**:小说/剧本/分镜/上下文/素材提示词;**禁止**触发生成与导出(`/run`、`/stages`、`/regenerate`、`/generate`、`/music`、`/export`)。图片、视频、语音、音乐、成片一律由用户在界面启动。
- - **可改写已有产物**:覆盖已生成章节的 `novel`/`script`、逐条改已有分镜正文与 `video_prompt`、覆盖 `bible`/`style`;但 `status/video_path` 等产物字段不可写。
- - **补齐的接口**:`PUT …/context`(上下文,落盘 `context/*.md`)、`POST/DELETE …/shots`、`PATCH …/shots/:sid`(可写分镜正文,产物字段不可写)、`PUT …/chapters/:cid/storyboard`(整章批量写分镜)、`GET …/logs`、`POST …/logs/rollback`。章节新增 `script` 字段承载剧本。
- - **可回滚日志**:内容表(projects/chapters/shots/assets/reference_images)的每次增删改都在 DB 层留原始行快照,UI / 内置 Agent / 外部 harness 三方写入全部覆盖;支持单条、整批(`batch_id`)、按时间点回滚,带漂移保护(变更之后又被改过 → 409 拒绝,`force:true` 才覆盖)。
- - **硬约束**:**没有任何 API 用于删除项目**;回滚也拒绝回滚「项目创建」。日志随用户手动删除项目一并清除,不自动清理。
- - 设计细节见 `docs/writer-api-plan.md`。
- ## 七、使用方式小结
- - **要跑本项目**:见「二、快速启动」。
- - **要脱离本项目、在自己 Agent 里实现同样方案**:读「三、全链路流程」+ 用「四」的 `skills/` 技能库,按五接入自己的工作流。
- - **要用自己的文生图/图生图/视频/语音工作流**:见「五、自定义工作流接入」。
README.md · README · 313 lines
- <div align="center">
- # Agent无限创作 · 把你的故事变成亿帧画面
- **免费开源本地 Agent 全自动视频生成 ✨**
- 上传小说 / 剧本,本地一键生成任意时长的成片,全程无人值守。
- <a href="https://github.com/SwotAtmk/infinite-creation/stargazers"><img alt="GitHub stars" src="https://img.shields.io/github/stars/SwotAtmk/infinite-creation?style=for-the-badge&color=F5B700&label=stars"></a> <a href="README_EN.md"><img alt="English" src="https://img.shields.io/badge/README-English-555?style=for-the-badge"></a> <a href="https://github.com/SwotAtmk/infinite-creation/blob/main/LICENSE"><img alt="MIT" src="https://img.shields.io/badge/licence-MIT-2EA44F?style=for-the-badge"></a> <a href="https://nodejs.org/"><img alt="Node.js" src="https://img.shields.io/badge/Node.js-%3E%3D22-339933?style=for-the-badge"></a><a href="https://space.bilibili.com/384196392?spm_id_from=333.1007.0.0"><img alt="我的B站" src="https://img.shields.io/badge/bilibili-SwotAtmk-blue?style=for-the-badge&logo=bilibili&logoColor=%2300A1D6"></a>
- </div>
- <p align="center">
- <a href="#快速开始"><strong>快速开始</strong></a>
- ·
- <a href="docs/technical.md">技术文档</a>
- ·
- <a href="#运行配置">运行配置</a>
- ·
- <a href="#交流群">加入交流群</a>
- </p>
- <p align="center">
- <img src="images/banner.jpg" alt="Agent无限创作" width="100%">
- </p>
- ## 赞助商
- <table>
- <tr>
- <td width="200" align="center" valign="top">
- <a href="https://admins.taoxiangyoushu.com/#/register?code=FzH3DEp"><img src="images/txlogo.png" alt="淘项有术" width="180"></a>
- </td>
- <td valign="top">
- <strong>淘项有术:AI 综合应用服务平台</strong><br>
- 聚合 AI 风口项目、副业轻创业社区与商业知识库等资源,帮助个人低成本上手 AI 项目、找到可落地的副业方向。<a href="https://admins.taoxiangyoushu.com/#/register?code=FzH3DEp">通过专属链接注册</a> 即可领取使用【7 天SVIP 会员】兑换码:TsHcxt0t
- </td>
- </tr>
- </table>
- 如果你或你的团队认可这个项目,欢迎成为赞助商,让项目走得更远:
- - 品牌 / 产品展示在本 README 顶部,随仓库被所有访客看到
- - 可附一段产品介绍与官网 / 注册链接
- - 赞助金额、周期与权益均可协商
- **合作洽谈**:[swotatmk@foxmail.com](mailto:swotatmk@foxmail.com)(邮件标题建议注明来意)
- ## 界面一览
- <table>
- <tr>
- <td width="50%"><img src="images/j1.png" alt="项目首页"></td>
- <td width="50%"><img src="images/j2.png" alt="章节管理"></td>
- </tr>
- <tr>
- <td width="50%"><img src="images/j3.png" alt="服务配置"></td>
- <td width="50%"><img src="images/j4.png" alt="素材库"></td>
- </tr>
- <tr>
- <td width="50%"><img src="images/j5.png" alt="分镜审查"></td>
- <td width="50%"><img src="images/j6.png" alt="导出成片"></td>
- </tr>
- </table>
- ## 案例
- <div align="center">
- <video src="https://github.com/user-attachments/assets/3ace95ff-1ec1-46b0-abab-115c76734ee3" width="70%" controls></video>
- </div>
- > 《妈妈的时间》
- <div align="center">
- <video src="https://github.com/user-attachments/assets/c415e1bb-ce1a-46fe-b97f-00362899eed3" width="70%" controls></video>
- </div>
- > 由体验官「闪电.」使用 infinite-creation 项目进行创作
- [更多样例](docs/run_demo.md) · 「无限・秩影」内置样例位于 `public/samples/`,在页面右上角「预览样例」可直接播放成片、查看素材与提示词,并「一键试用」。
- ## Agent无限创作是什么
- 面向小说改编、漫剧广告与故事讲解视频的开源本地工作台。它把内容分析、资产管理、分镜、媒体生成、费用追踪和导出组织成一条可审核、可中断恢复的生产流水线,不需要演员、配音、导演和剪辑师。
- - **两个创作工作台**:**Agent无限创作**(小说 / 剧本 → 长视频)与 **无限・秩影**(接入 lemo-opuscar 代码电影技能,66 个风格模板 + 任意素材 + 提示词,Agent 自动渲染风格化成片,无需 ComfyUI)。
- - **统一生产链路**:小说或剧本进入项目后,自动完成人物圣经、风格指南、人物 / 场景 / 道具 / 语音资产、分镜脚本、逐镜视频、背景音乐、字幕与 ffmpeg 合片。
- - **视觉一致、人工可控**:跨分镜复用 canonical 参考图与场景站位表,关键阶段可确认,单个分镜可重做,变更日志可回滚。
- - **本地与云端都能跑**:本地 ComfyUI(12G+ 显存)或 RunningHub 云端算力;也可把流水线交给本机 CLI Agent,通过 MCP 工具桥接管。
- - **交付可继续编辑**:自动字幕可开关(同时保留无字幕版本与 SRT),背景音乐库支持生成 / 预览 / 应用到多章节,成片支持单个或批量删除。
- ## 核心能力
- - **无限视频时长**:支持生成任意时长的视频,无需手动调整分镜脚本或视频参数,上传小说/剧本自动生成长视频。
- - **自动分镜**:根据人物动作、场景变化、道具移动等自动分镜,无需人工干预。
- - **项目隔离**:每个项目的素材文件 + Agent 上下文(人物圣经/风格指南/连续性记录)完全隔离,资源按分类整理(人物/场景/道具/语音/音乐/音效/其他)。
- - **人物一致性**:每人物一张 canonical 参考图跨分镜复用 + 统一外观描述 + H3 参考标签规则。
- - **技能系统**:默认预装 MiniMax-H3 视频 Skill + 本项目 novel-to-video 主技能;支持把 SKILL.md 丢进 skills/ 目录扩展。
- - **自迭代(技能工厂)**:上传一个新的 ComfyUI 工作流 JSON,自动解析节点 → 生成工作流规格 + 起草对应技能,Agent 立即可调用。
- - **断点续跑**:任务持久化 + 幂等跳过,进程崩溃/重启后可继续,不重复生成。
- - **审查/重生成**:分镜级预览与重生成(换种子 / 按反馈改写提示词)。
- - **背景音乐**:视频阶段自动生成纯音乐背景音乐并合成到成片;另有「背景音乐库」支持手动生成(可填 caption/歌词/时长)、预览、选择,并一次性应用到多个已完成的章节。
- - **自动字幕**:项目设置可开关「自动添加字幕」,设置页「字幕与语音识别」里可切换三种模式 —— **剧本台词(经典,默认)** 直接用分镜台词/旁白生成字幕,零依赖;**本地识别 whisper** 按成片实际音轨识别,需 Python 3.9+,本机没有 Python 时会自动下载便携运行时(约 25MB,解压到 data/subtitle/,不动系统 Python),首次使用自动装环境并下载模型(极速版 large-v3-turbo / 专业版 large-v3,默认极速版);**外部服务(audio2srt API)** 把音轨上传给已部署的 [audio2srt_service](https://github.com/SwotAtmk/audio2srt_service)(FastAPI,默认 8000 端口)转写,本机无需 Python,配置页可测试连通性与接口是否匹配。三种模式识别不可用时都会自动回退剧本台词,并保留不带字幕版本与 SRT 字幕文件;「成片」页可分别下载带字幕、不带字幕视频与 SRT,并支持单个/批量删除。
- - **分阶段运行**:生成拆成 文本创作 / 资产生图 / 音色设计 / 分镜视频 四个独立阶段,可任意勾选单独跑或续跑 —— 按显存约束自动拆批,不需要的阶段不拉起对应进程。
- - **显存维护**:设置页可配「每 N 个生成后自动释放 ComfyUI 显存」(默认 3,0 = 关闭),覆盖文生图/图生图/换装/音色/视频全部渲染——AMD Dynamic VRAM 的显存累积不只在视频触发;未启用 Dynamic VRAM 时界面会提示关闭。
- - **在线预览**:成片/分镜视频经后端 Range 流式传输,进度条可随意拖动、即时跳转。
- - **外部 Agent 运行时**:除内置 openclaude 外,可在设置页切换到本机已安装的 CLI Agent(Claude Code / Codex CLI / Gemini CLI / Qwen Code / Cursor Agent / Qoder CLI / Grok Build / Hermes / 自定义命令),通过本地 MCP stdio 服务把领域工具暴露给外部 Agent、由其完整接管流水线;模型账号与登录态走各自 CLI。
- - **无限・秩影(代码电影)**:接入 lemo-opuscar 技能,内置 66 个风格模板并支持分类筛选与自定义风格;上传图片/音频/视频/文档等任意素材 + 提示词后,由 Agent 在本机写渲染代码、调用 ffmpeg 输出对应风格成片。内置样例库支持预览与「一键试用」,生成记录支持查询、编辑、重新生成、停止与批量删除,且不占用 ComfyUI 渲染队列。
- ## 从输入到成片
- ```mermaid
- flowchart LR
- A["小说 / 剧本"] --> B["人物圣经 + 风格指南"]
- B --> C["人物 / 场景 / 道具 / 语音资产"]
- C --> D["分镜脚本"]
- D --> E["逐镜视频(MiniMax H3)"]
- E --> F["背景音乐 + 字幕"]
- F --> G["ffmpeg 合并成片"]
- C --> H["无限・秩影(代码电影)"]
- H --> G
- ```
- 每个阶段都可以由 Agent 自动编排,也可以由用户在工作台中审核、调整或重新生成。技术细节见[技术文档](docs/technical.md)。
- ## 快速开始
- **一行命令跑起来**
- ```bash
- git clone https://github.com/SwotAtmk/infinite-creation.git
- cd infinite-creation
- pnpm install # 安装依赖(会自动构建 Agent 内核)
- pnpm run install:skills # 可选:拉取 MiniMax-H3 官方技能
- pnpm run dev # 默认启动 Studio,打开 http://127.0.0.1:4710
- ```
- > 前置要求:Node.js ≥ 22、pnpm ≥ 9、Bun、ffmpeg。生产模式、Studio / 经典界面分别启动、Windows 一键脚本、数据库与 ComfyUI 配置等,见[技术文档](docs/technical.md)。
- **简单开始使用**
- - 打开 Trae、豆包、CodeX 等工具,打开豆包使用“工作模式”,并输入提示词
- ```text
- 帮我克隆这个项目https://github.com/SwotAtmk/infinite-creation.git到本地(这里填写要安装的项目目录),
- 并且在本地部署启动这个项目。
- ```
- - **国内使用:**
- ```text
- 帮我克隆这个项目https://gitcode.com/SwotAtmk/infinite-creation.git到本地(这里填写要安装的项目目录),
- 并且在本地部署启动这个项目。
- ```
- **使用 Agent 自动安装**
- ```text
- 请根据 https://gitcode.com/SwotAtmk/infinite-creation/releases/download/v1.0.0/install-skill.md,
- 从GitHub(国外)或者GitCode(国内)上安装SwotAtmk/infinite-creation 安装 infinite-creation 技能,并根据技能描述启动这个项目。
- ```
- ## 运行配置
- 我的电脑:
- ```text
- 系统:Windows 11(也支持在Linux/Mac上运行)
- CPU:12th Gen Intel(R) Core(TM) i5-12400F
- 显卡:NVIDIA GeForce RTX 3080 20G
- 内存:32GB DDR4 3200 MT/s (16GBx2)
- ```
- 本地运行所需最低配置:
- ```text
- 显卡:显卡最低需要12G+显存【有开发能力的可以自行适配8G可运行的版本】
- CPU:不挑处理器
- 内存:推荐32GB以上
- 硬盘:最少需要150G的空间
- ```
- **具体本地的显卡配置需要多大的显存,我这边暂时还没有做详细测试,如果你的电脑能够正常运行此项目,欢迎加入群聊分享你的最低可运行的配置**
- **注意**:须先安装 ffmpeg,否则可能会影响最后的合并成片的功能,下载地址:[https://ffmpeg.org/download.html](https://ffmpeg.org/download.html)
- ## ComfyUI 配置
- ### 所需工作流和模型
- 在首次运行项目前,必须先安装ComfyUI工具,如果没有安装的可以先到Comfyui官网下载安装,或者使用我提供的网盘链接一键安装包进行安装(一键安装包中包含所有工作流中用到的模型和工作流),一键安装包目前仅支持Windows系统,Mac系统建议到官网进行手动安装,并下载模型和跑通所有示例工作流。
- **第三方服务免责声明:ComfyUI一键整合包是请第三方大佬做的,可能会包含第三方网站涉及的一些收费相关问题,制作不易理性支持。请仔细查验以免被骗,不要相信任何加你联系方式的陌生人卖你的资料。**
- ```txt
- 我用夸克网盘给你分享了「Windows无限创作-ComfyUI一键安装部署」,点击链接或复制整段内容,打开「夸克APP」即可获取。
- /~c2d03b8qfM~:/
- 链接:https://pan.quark.cn/s/ed2afd0f6a4f?pwd=GVZe
- 提取码:GVZe
- ```
- 建议如果有ComfyUI相关技术的可以自行安装并补全相关插件和模型,跑通comfyui_original_workflows文件夹下的相关工作流,注意:区分英伟达NVIDIA显卡和AMD显卡的工作流
- 在使用此Agent项目工具之前,建议你先使用ComfyUI手动跑一遍所有工作流(即:跑通comfyui_original_workflows/目录下的所有工作流)之后使用Agent项目工具就能进行全自动生成。
- > 语音:MiniMax H3 依据「参考音色样本(flac 等,放 assets/voice/)+ 提示词对白」自行合成台词,无需单独 TTS。
- ### 接入云端算力 - 接入RunningHub原生ComfyUI接口
- - 如果本地电脑配置比较低无法运行的话,可以选择使用云端算力免费试用
- **领取RunningHub免费云端算力试用**
- > 打开链接:https://www.runninghub.cn?inviteCode=6to0etcb 现在注册还能领500RH币,可以免费生成不少图片和视频哦!
- - 浏览器打开 [https://www.runninghub.cn/call-api/bill-task?tab=keys&type=consumer](https://www.runninghub.cn/call-api/bill-task?tab=keys&type=consumer&inviteCode=6to0etcb) 获取RunningHub Api-Key
- 
- - 配置RunningHub Api-Key
- 
- - 我的RunningHub工作流主页:[https://www.runninghub.cn/user-center/2013421139631808514/webapp?inviteCode=6to0etcb](https://www.runninghub.cn/user-center/2013421139631808514/webapp?inviteCode=6to0etcb)
- ## 文档
- | 页面 | 内容 |
- |---|---|
- | [技术文档](docs/technical.md) | 技术栈、目录结构、环境准备与启动、首次配置、使用流程、API 一览、测试与限制 |
- | [Agent 架构](docs/agent-architecture.md) | Agent 内核、外部 CLI 运行时与 MCP 工具桥 |
- | [写作接口设计](docs/writer-api-plan.md) | 让 AI 编程工具直接写入内容的接口取舍与逐轮记录 |
- | [运行样例](docs/run_demo.md) | 生成效果与内置样例说明 |
- | [SKILL.md](SKILL.md) | 给 Agent 的完整调用契约 |
- | [English README](README_EN.md) | English documentation |
- ## 项目计划
- - [持续进行] 解决项目中存在的BUG
- - [计划中] 适配低显存的家用级显卡,博主的测试设备有限,需要更多的用户帮忙测试并反馈到仓库中的Issues多多反馈🙏🏻
- - [计划中] 解决并优化内部Agent存在的工具调用安全及上下文压缩等……问题
- - [计划中] 插件系统开发,支持插件上传、插件调用、插件框架……
- - [计划中] 自动流水线支持提示词自定义编排插件
- - [计划中] 收录更多高阶Skill技能,提升Agent技能视觉美感
- - [计划中] 工具Web页面美化工作,需要一个非常有美感的AI设计师
- - [计划中] 打包构建Docker部署、桌面端App
- - [计划中] 工作流接入视频超分,让生成的视频更加清晰
- - [计划中] 接入Seedance、kling、wan、MiniMax-H3在线版Api接口一键生成视频
- - [✅] 支持配置单分镜生成多个视频,根据分镜抽卡选优的模式
- - [✅] 支持互联网搜索技能,比如说生成素材支持搜索参考图片,比如说华为手机、苹果电脑等相关型号的图片用做参考图生成新的素材图片
- - [✅] 支持Agent自动根据实际应用场景调用文生视频、图生视频、首尾帧、数字人的功能(数字人模式暂为预留,不对接业务)
- - [✅] 支持上传txt文本文件,自动解析创建多章节并共享参考素材
- - [✅] 新增「场景站位一致性」Skill:为每个场景建立人物/道具站位表(空间锚点+角色方位+180度轴线),消除跨镜左右漂移与越轴等分镜一致性问题
- - [✅] 接入外部 Agent 运行时:支持本机 CLI Agent(Claude Code、Codex CLI、Gemini CLI、Qwen Code、Cursor Agent、Qoder CLI、Grok Build、Hermes、自定义命令)通过本地 MCP 工具桥接管「小说→视频」流水线,同时保留内置 openclaude 作为默认运行时
- - [✅] 支持自动生成视频字幕:项目级开关,把分镜台词/旁白按时间轴烧录进成片(自动隐藏角色名),同时保留不带字幕版本与 SRT 字幕文件供下载
- - [✅] 支持背景音乐管理,接入 MiniMax Music3 本地/云端自动生成背景音乐并合成到视频中,含「背景音乐库」(手动生成/预览/选择/应用到章节)
- - [✅] 添加Agent安全审批策略,防止Agent越权操作,删除项目或执行危险命令
- - [✅] 接入在线RunningHub-ComfyUI工作流生成,会员MiniMax-H3夜间免费运行
- - [✅] 把项目装进Skill技能,支持Agent一键调用
- - [✅] 把文生图、图生图工作流进行整合使用最新Qwen-Image2.1的文生图+图生图工作流
- - [✅] 接入Qwen-Image-2.1文生图+图生图工作流
- - [✅] 支持提交参考素材,及Agent整理参考素材
- - [✅] 优化本地MiniMax H3人物语音电流声或者语音不清晰的问题
- - [✅] 上传小说/剧本生成视频本地全链路Agent全自动工作流生成方案
- - [✅] 优化图片素材生成的质量
- - [✅] 优化人物参考音频的声音设计
- - [✅] 新增「无限・秩影」代码电影模式:接入 lemo-opuscar 的 66 个风格模板,支持预设/自定义风格、任意素材上传、样例预览与一键试用、生成记录查询/编辑/重新生成/停止/删除/批量删除
- - [✅] 支持人物服装管理,每个人物可以支持设计多套服装
- ## 交流群
- 扫码加入群聊,反馈问题或建议:
- 
- 遇到可以复现的 Bug 或明确的功能需求,也可以直接提交 [GitHub Issue](https://github.com/SwotAtmk/infinite-creation/issues)。
- ## 贡献
- 欢迎提交代码、文档、技能与问题复现。开发、测试与接口约定见[技术文档](docs/technical.md)。
- ## 参考项目,特别鸣谢
- - [nextjs](https://nextjs.org/) 提供了 Next.js 框架,用于构建 Web 应用
- - [MiniMax-H3 官方仓库:https://github.com/MiniMax-AI/MiniMax-H3](https://github.com/MiniMax-AI/MiniMax-H3) 提供了 H3 模型和Skill技能
- - [OpenClaude:https://github.com/Gitlawb/openclaude](https://github.com/Gitlawb/openclaude) 提供了 Agent 内核和工作流管理功能
- - [Comfy-Org/ComfyUI](https://github.com/Comfy-Org/ComfyUI) 提供了 ComfyUI 工作流和模型架构
- - [deepseek](https://www.deepseek.com/) 感谢Deepseek提供了 deepseek-v4-flash-vision-exp 模型
- - 参考开源Skill技能:[short-drama](https://github.com/0xsline/short-drama)、[manju-laoli-skill](https://github.com/lixiaoxiao9888-create/manju-laoli-skill)
- - [lemomo-ai/lemo-opuscar](https://github.com/lemomo-ai/lemo-opuscar) 为无限·秩影提供了核心框架
- 感谢这些项目为我提供了帮助,使项目能够快速迭代和改进。
- ## 作者致辞
- 欢迎各位同行多提提意见,多找找bug帮忙多多宣传,做出更好的产品让更多的人发现。项目刚开源里面可能会有很多地方需要调整优化的地方,欢迎各位提交issues或者在我的基础上做更多的优化,感谢每一位对这个项目做出贡献的人。
- 我的B站:[https://space.bilibili.com/384196392?spm_id_from=333.1007.0.0](https://space.bilibili.com/384196392?spm_id_from=333.1007.0.0)
- ## 致谢
- - 感谢开发者[taoxiangyoushu](https://github.com/taoxiangyoushu)为此项目做出的贡献,接入了图生视频+首尾帧的工作流模式并修复了部分bug
- - 感谢开发者 [happymy](https://github.com/happymy) 为此项目提供了AMD+GGUF适配的解决方案以及解决项目中存在的部分bug
- - 感谢以下开发者为项目做出的贡献:[thrasher824](https://github.com/thrasher824)、[remiliakui](https://github.com/remiliakui)、[ghshhf](https://github.com/ghshhf)、[binonxia](https://github.com/binonxia)、[anupamme](https://github.com/anupamme)
- ## Star 历史
- <a href="https://www.star-history.com/?repos=swotatmk%2Finfinite-creation&type=date&legend=bottom-right">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=swotatmk/infinite-creation&type=date&theme=dark&legend=bottom-right" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=swotatmk/infinite-creation&type=date&legend=bottom-right" />
- <img alt="Star History Chart" src="https://api.star-history.com/chart?repos=swotatmk/infinite-creation&type=date&legend=bottom-right" />
- </picture>
- </a>
- ## 开源协议
- 本项目基于 [MIT License](LICENSE) 协议进行开源,MIT是自由度最高的开源协议,你可以拿去商用和二次开发,但是必须保留原版声明
- Copyright (c) 2026 SwotAtmk
- > 说明:`skills/` 目录中的一些技能来源于 MiniMax-H3 官方仓库,`vendor/` 目录为第三方代码,均不在本项目的 MIT 授权范围内,请遵循其各自的授权条款。
lib/agent/agent-loop.js · Bundled script · 228 lines · 1 finding marked
- import { Chapters, ReferenceImages, buildNovelContextBlock, isValidNovelStep } from '../core/index.js';
- import { filterReferenceImages, SKILL_PIPELINE_NODES } from '../shared/index.js';
- import { loadSkill, listSkills } from './skill-engine.js';
- import { targetChapterIdSet } from './tools.js';
- export const REFERENCE_INSTRUCTION = `
- 【参考图片素材】用户本次上传了参考图片素材。请先用视觉能力逐张分析这些参考图的内容、画面风格、角色/场景/道具等元素,然后用 generate_asset_from_reference(图生图/i2i)以这些参考图为输入派生风格/设定一致的新素材(角色/场景/道具/服装等),而不是一律文生图。这些参考图仅作「生成新素材的参考」,不要把它们直接当成品素材使用,而是据此派生新素材。`;
- // 构造用户任务提示词(内置 Agent 与外部 Agent 共用,保证续跑语义一致)
- export function buildTaskPrompt(ctx) {
- let chapters = Chapters.list(ctx.projectId).map((c) => ({ id: c.id, title: c.title, novel: c.novel, hasScript: !!String(c.script || '').trim(), scriptChars: String(c.script || '').length }));
- const target = ctx.chapter || '';
- if (target) chapters = chapters.filter((c) => c.title === target || c.id === target);
- const seed = JSON.stringify({
- project: { name: ctx.project.name, style: ctx.project.style, idea: ctx.project.idea || '' },
- targetChapter: target || null,
- chapters,
- novel: chapters.map((c) => c.novel).join('\n\n').slice(0, 6000),
- });
- return (ctx.renderDisabled ? '开始执行:本批只做文本创作,不要调用任何渲染工具。\n' : '开始执行:请把下面的项目完成到成片导出。\n') + seed;
- }
- // 参考图的文本描述(外部 Agent 通过 view_project_references 查看图片,不内联图片块)
- export function buildReferenceDescription(ctx) {
- const refs = filterReferenceImages(ReferenceImages.list(ctx.projectId, { mode: 'reference' }), targetChapterIdSet(ctx));
- const lines = [];
- let idx = 0;
- for (const r of refs) {
- idx += 1;
- const parts = ['参考图' + idx + '(reference_id=' + r.id + '):' + (r.name || '未命名')];
- if (r.description) parts.push('用途/剧情定位:' + r.description);
- lines.push(parts.join(';'));
- }
- return { refs, descText: lines.join('\n') };
- }
- // 由 skillPipeline 配置生成「技能→任务映射」文案(替代原先硬编码在提示词里的映射)。
- // nodes 缺项/坏值时回退到节点默认;fallback 非 false 时额外提示「可自动匹配其它技能」。
- export function renderPipelineSkillMap(pipelineCfg) {
- const nodes = (pipelineCfg && pipelineCfg.nodes) || {};
- const lines = [];
- for (const meta of SKILL_PIPELINE_NODES) {
- // 「生成小说」是无限・卷轴专属环节,不属于视频流水线,不写进视频 Agent 的技能映射
- if (meta.id === 'novel') continue;
- const node = nodes[meta.id] || {};
- const skills = Array.isArray(node.skills) ? node.skills.map((s) => String(s).trim()).filter(Boolean) : [];
- const fallback = node.fallback !== false;
- if (!skills.length) {
- lines.push(meta.label + '(' + meta.desc + ')→' + (fallback ? '按技能目录自动匹配' : '未指定技能'));
- continue;
- }
- const refs = skills.map((s) => 'skill(' + s + ')').join('、');
- lines.push(meta.label + '(' + meta.desc + ')→先 ' + refs + (fallback ? '(这些用不上时自动匹配其它技能)' : ''));
- }
- return '技能→任务映射:' + lines.join(';') + '。';
- }
- export function buildSystemPrompt({ ctx, skillName, external }) {
- const skill = loadSkill(skillName || 'novel-to-video');
- const parts = [];
- parts.push('你是「无限创作」的自主创作 Agent,负责把小说/故事全自动改编为带语音的视频成片。你拥有调用本地 ComfyUI(MiniMax H3 视频 + Qwen-Image/Krea2 文生图/图生图 + Qwen3-TTS 音色)与 ffmpeg 的能力。');
- parts.push('铁律:全程自主决策,不要向用户询问中间确认;遇到失败先重试、再降级、最后记录并继续;操作必须幂等(已完成资产/分镜跳过),以便断点续跑。');
- parts.push('工具边界铁律:你只有下面列出的领域工具(以及用于按名字检索领域工具的 ToolSearch)。除 web_search(查资料/搜图)与 download_reference_image(下载一张图片到项目参考图)这两项联网能力外,你没有任何 shell/命令行/文件读写/子代理工具。技能文档里出现的 python / bash / npm / node / 脚本 等命令,或「运行脚本 / 执行命令 / 读文件」一类步骤,一律不要尝试执行(调用会被直接拒绝,反复尝试只会空转、浪费时间);凡文档声称「跑脚本才能得到」的产物,改用领域工具(list_*/get_*/generate_*/set_*/update_*/skill_reference 等)本身完成,或直接忽略该脚本步骤。web_search / download_reference_image 会由系统在后台替你执行,你只需按工具参数调用即可。');
- parts.push('【不确定就要搜】遇到你不知道或不确凿的事实——品牌名、产品型号、年代物品的真实外观、专业术语、历史/地理/科技细节、真实存在的服饰/道具样式等——必须先调用 web_search(type=web) 查证,再据结果理解上下文或改写描述/提示词,禁止凭空臆造年代/品牌/型号错误。需要某物品/服饰的参考图时,用 web_search(type=image) 搜图,再用 download_reference_image 下载为参考图(这些参考图会在后续「资产图」阶段用图生图自动派生为新素材)。若 web_search 返回 disabled,说明设置里关闭了联网搜索,此时改用你的既有知识继续、不要重试。');
- parts.push('【安全铁律】你没有任何删除/破坏类能力,也不得尝试越权:\n1. 禁止删除项目、清空素材库、批量删除分镜/资产/章节(没有对应工具,也不要试图用其他工具绕)。\n2. 禁止任何 shell/脚本/命令执行(rm、dd、mkfs、chmod、sudo、curl|sh、git force 等一律不做);技能文档里出现「运行脚本/执行命令/读写文件」类步骤一律忽略,用领域工具本身完成。\n3. 禁止路径越权:所有路径参数(voice_ref / reference_image_path 等)只能指向项目目录内的相对路径,不得包含 ../ 或绝对路径。\n4. 若某次调用返回「已拦截 / 安全拦截」,说明该操作被系统判定为危险,不要再重试同类操作,改用安全方式继续。');
- if (external) {
- parts.push('【外部 Agent 运行时】你的领域工具由本项目的本地 MCP 服务 ic 提供,工具名可能带 mcp__ic__ / ic__ / mcp_ic_ 等前缀,按同名工具调用即可。开始执行前先调用 get_project 验证 MCP 连通性。禁止使用你自身的 shell / 文件读写 / 联网 / 子代理工具;本任务的一切写入与生成都必须通过领域工具完成。');
- }
- if (skill) {
- parts.push('【当前工作模式技能:' + skill.name + '】\n' + skill.body);
- }
- const catalog = listSkills();
- if (catalog.length) {
- const lines = catalog.map((s) => {
- const d = String(s.description || '').replace(/\s+/g, ' ');
- return '- ' + s.name + ':' + (d.length > 220 ? d.slice(0, 220) + '…' : d);
- });
- parts.push('可用技能目录(仅摘要,禁止凭摘要臆测其规范;命中对应任务前必须先调用 skill(名字) 加载全文再遵循):\n' + lines.join('\n'));
- parts.push(renderPipelineSkillMap(ctx.cfg?.skillPipeline));
- parts.push('短剧/漫剧技能映射(项目为短剧/漫剧/剧本改编时命中,先 skill(名字) 加载全文再遵循,其 references 用 skill_reference(name, ref) 按需加载):短剧逐集编剧/大纲扩写→skill(0715-scriptwriter);剧本创作总控/交付→skill(script-master);小说改编剧本→skill(novel-to-skitscreenplay);剧本/小说转分镜→skill(novel-to-storyboard);文字分镜JSON→skill(hf-drama-storyboard-script);漫剧前期策划→skill(ai-manga-planner);漫剧导演→skill(manju-director-agent);漫剧全流程→skill(manga-drama-generator);脚本转漫剧→skill(script-to-manga);漫剧分镜解析/3D漫剧→skill(comic-drama-generator);影视级分镜+镜头库→skill(cinematic-ai-comic-director);道具/年代一致性→skill(era-consistency-optimizer);人物/道具站位一致性→skill(scene-blocking-consistency);全栈分镜提示词→skill(manga-full-stack)。');
- parts.push('漫剧老李套装(短剧/漫剧任务默认优先,体量大的总控只在明确要求整套流程时加载):全流程总控→skill(short-drama-director);剧本/分集/台词→skill(sd-script-engine);文戏分镜→skill(sd-storyboard-engine);资产三清单/出图提示词→skill(sd-asset-engine);打戏→skill(sd-combat-engine)(玄幻→skill(sd-xuanhuan-engine),真人→skill(sd-real-engine));投喂/提示词包→skill(sd-feed-engine);质检/连续性→skill(sd-qc-engine);机位选型→skill(sd-decision-engine);解说→skill(sd-jieshuo-engine);海外剧→skill(sd-overseas-engine);对标采风→skill(sd-recon-engine);微短剧 50-100 集剧本→skill(short-drama-scriptwriting)。套装里的 python 脚本一律不执行;其 Seedance 投喂规范只取镜头/节奏/资产方法,最终 video_prompt 必须按 h3-prompt-writing 的 __MINIMAX_H3_REF_N__ 规范落地。');
- }
- const c = ctx.project.context || {};
- if (c.bible) parts.push('【人物圣经(一致性锚点,后续所有生成必须遵守)】\n' + c.bible);
- if (c.style) parts.push('【风格指南(统一画风/光线/色调)】\n' + c.style);
- if (c.continuity) parts.push('【连续性记录】\n' + c.continuity);
- parts.push('【人物/道具站位一致性铁律】同一场景内所有镜头必须保持人物/道具相对站位与朝向一致:先为每个场景建立「站位表」(空间锚点+各角色默认方位+道具锚点+180度轴线与允许机位)写入人物圣经 bible 的「场景站位表」章节,之后每个镜头的 sub_shots / visual / video_prompt 都要明确复述各角色/道具相对左右方位与朝向,跨镜左右关系不得漂移(除非剧情明确走位/换位,且换位本身要写清路径)。拆分镜前先调用 skill(scene-blocking-consistency) 加载并遵循其规则。写分镜时按 idx 顺序逐条写,并自动判断前后两镜是否转场:比较前后两镜的 scene_name/场景头与时间——同场景且时间连续→必须参考站位(写每条前先回顾上一条 sub_shots 的结尾落幅,起幅=上一镜落幅,角色左右方位/朝向/道具位置/动作方向一致);发生转场(场景切换/地点变化/时间跳跃/淡入黑场)→不参考上一镜位置,为新场景重建站位表。');
- parts.push('【人物着装铁律】人物外貌/发型/配色必须与人物圣经一致。先用 generate_assets_batch 生成角色 canonical 图;是否额外生成服装取决于剧情:仅当剧情出现沐浴/洗澡/更衣/换衣/换装/换上一身等「真实换装事件」时,才用 change_outfit 或 design_outfits 为该角色生成对应的那套服装(category=costume,parent_id 指向角色,每套给短名+外观描述)。不同场景、不同镜头、不同机位、换场地拍摄都不算换装——没有换装事件的角色一律直接用 canonical 图,禁止为每个角色默认生成多套服装(避免素材冗余)。同一个角色在一个分镜里只引用一件服装,不要同时引用角色原图和服装图。写分镜时按剧情在 set_storyboard 的 costumes 字段引用该镜对应那套服装:换装事件之后的镜头引用新一套、之前的镜头不引用或用旧一套。');
- parts.push('【人物年龄/时期铁律】只有当剧情出现明确的时间跳跃或年龄变化(回忆/闪回、小时候/童年/幼年、多年前、年轻时、步入中年、老年/变老、多年后/长大等)时,才用 change_age 或 design_ages 为该角色生成对应时期的年龄变体(category=age,parent_id 指向角色,保持脸/五官/发型/画风一致、只改年龄)。「年轻」「少年」这类普通外貌描写不算时间跳跃,禁止凭此生成年龄变体;剧情没有涉及人物不同年龄段的,禁止生成年龄变体,直接用 canonical 图。同一个角色在同一时期只需要一个年龄变体,不要为同一角色生成多个年龄段;同一个角色在一个分镜里只引用一个年龄变体(且不要同时引用角色原图)。写分镜时在时间跳跃之后的镜头用 set_storyboard 的 ages 字段引用对应时期、之前的镜头不引用。');
- parts.push('项目参数:风格=' + (ctx.project.style || '未指定') + ',视频分辨率=' + (ctx.project.video_resolution || '480P') + ',宽高比=' + (ctx.project.video_aspect_ratio || '16:9'));
- parts.push('当前 LLM 支持图片输入:' + (ctx.cfg.llm?.vision ? '是' : '否') + (ctx.cfg.llm?.vision ? '。写视频提示词前,先用 list_assets 拿到全部资产,再用 view_asset 一次性查看每个唯一角色/场景/道具的参考图(每个资产只看一次并记住、后续所有镜头复用,禁止对同一张图反复查看);仅当某镜头引用了尚未查看过的资产时才用 view_shot_references(shot_id) 补看。只给 list_shots 中 has_prompt=false 的镜头写视频提示词(has_prompt=true 的跳过,用于断点续跑)。基于真实参考图写提示词,避免逐镜重复查看造成上下文膨胀。' : '。不要尝试查看图片,仅用文本描述写提示词。'));
- parts.push('【参考生成新素材(图生图)】若存在用户上传的参考图片素材(mode=reference):分析其内容/画风/元素后,用 generate_asset_from_reference(reference_id, category, name, ...) 以参考图为图生图(i2i)输入派生新素材,禁止一律用文生图重画;只有与参考图无关、纯靠文字描述的新素材才走 generate_assets_batch 文生图。参考图仅作参考、不直接当成品。');
- parts.push('【用户导入素材(优先绑定分镜)】list_assets 中 source=uploaded 且已有 image_path 的资产,是用户上传并「导入素材库」的设定(已由视觉模型自动命名并归类为 character/scene/prop 等,图片已随首条消息附带)。这些是用户指定的角色/场景/道具视觉锚点:先分析每张图的内容,把它绑定到最相关分镜——拆分镜写 set_storyboard 时必须在 characters/scenes/props 里按名字引用它们,禁止忽略或为同一主体重复生成同义资产。对 category=other 的导入素材,可先 view_asset 查看后作为风格/元素参考。');
- parts.push('【音频素材(音色参考)】素材库中 category=voice/music/sfx 且已有 audio_path/voice_ref 的资产是独立音频(旁白音色/背景音乐/音效),会作为 H3 音色参考输入。拆分镜时:有旁白(narration)的分镜,若素材库存在对应旁白音色(voice 类),用 set_storyboard 的 audios 字段按名字引用;需要背景音乐/音效烘托的分镜,同样用 audios 引用对应音乐/音效资产。audios 引用的是已存在的音频资产名,禁止编造不存在的名字。');
- parts.push('本次生成目标:' + (ctx.chapter ? ('章节「' + ctx.chapter + '」(只生成该章,其它章节不要动)') : '全部章节'));
- parts.push('【剧本流程(先剧本,后分镜)】每章必须先有剧本再拆分镜:\n1) 先用 get_chapter 读取本章 novel 与 script;\n2) script 已有内容:它是本章唯一权威的剧情蓝本,禁止用 novel 重写或覆盖(除非本轮用户明确要求重写剧本,才 set_chapter_script(overwrite=true);否则不要调用 set_chapter_script);拆分镜必须严格覆盖剧本中的全部场次/动作/台词/旁白,人物名、场景名、道具名与剧本保持一致;\n3) script 为空且项目「自动生成剧本」开启(当前:' + (ctx.project.auto_script !== false ? '开启' : '关闭') + '):依据 novel(novel 为空则用项目 idea)写一份完整中文剧本,用 set_chapter_script 保存,再按剧本拆分镜;\n4) script 为空且项目关闭自动生成:不要写剧本、不要拆分镜,用 report 说明「本章缺少剧本且项目未开启自动生成剧本」,跳过该章。\n剧本格式:【第N场|时间|地点】+ 出场人物 + 场景/动作描述 + 台词(人物名:台词)+ 必要旁白;台词口语化、可直接配音。');
- parts.push('若目标章节正文(novel)与剧本(script)都为空,则以项目「想法 idea」作为故事前提自行展开完整剧情;不要因为正文为空而拒绝生成。');
- // 只跑 LLM 的阶段(渲染另起一批):到此为止,不灌「成片导出」那段。
- // 否则 Agent 会为了达成「全部视频 done + 合并导出」而反复调用被 runTool 拦掉的渲染工具。
- if (ctx.renderDisabled) {
- parts.push('【本阶段只做文本创作,禁止一切渲染】本批没有启动 ComfyUI:LLM 与 ComfyUI 同时常驻会爆显存,所以渲染必须另起一批。');
- parts.push('本阶段职责:读入正文 → 写本章剧本(先按映射加载 sd-script-engine 或 short-drama-scriptwriting;已有剧本则直接使用、不要覆盖)→ 写人物圣经与风格 → 为每个资产写图片提示词与音色描述(update_asset 的 prompt / voice_description)→ 拆分镜(严格按剧本,set_storyboard,先 skill(story-pipeline-cn);短剧/漫剧优先 skill(sd-storyboard-engine))→ 为每镜写视频提示词(video_prompt,先 skill(h3-prompt-writing))→ 为每章写背景音乐(set_chapter_music:先 skill(ai-music-studio) 与 skill(music-caption-rewriter) 产出贴合本章剧情的结构化 caption;再用适合本章剧情的语言——华语普通话/粤语/英语等——写 lyrics 歌词;并给合适的 duration 时长)。若项目设置「是否生成背景音乐」为否,则跳过 set_chapter_music。');
- parts.push('以下工具已被禁用,调用只会返回「已跳过」,重试无意义,请不要调用:generate_asset_image、edit_asset_image、change_outfit、design_outfits、change_age、design_ages、generate_assets_batch、design_voice、generate_shot_video、regenerate_shot、generate_chapter_videos、generate_music、assemble_video。');
- parts.push('把所有文本写到数据库后就汇报「文本阶段完成」并结束本轮。不要等待渲染结果,也不要反复尝试被禁用的工具。待办会自动保留,由后续渲染阶段接手。');
- return parts.join('\n\n');
- }
- parts.push('硬性完成要求:分镜必须完整覆盖该章(按 story-pipeline-cn 模式C 长镜头聚合:同一场景连续动作+多句连贯对白合并成一镜,仅场景切换/时空断开才换镜,同一分镜最多 2 个说话人(≥3 人对话拆成多个分镜),禁止一句一镜/碎片化,也禁止压缩/省略/偷工)。**镜头时长必须贴合内容节奏,禁止为凑时长拖长**:时长 ≈ 台词字数÷4.5 + 动作/情绪缓冲 1–3 秒,取整后夹在 2–15 秒之间;一句短台词(约 8–15 字)只给 2–4 秒,绝不为凑 10 秒把短镜头拖长(拖长会产生呆板空镜、打乱节奏);只有真正的连续动作+多句对白才给长镜头(最长 15 秒)。每镜台词字数 ≤ 时长秒×5(中文旁白约 4-5 字/秒),超长台词必须拆镜或压缩台词,否则会被 H3/TTS 压缩成听不清的模糊声。**相邻镜头要衔接自然**:同场景连续镜头写视频提示词时保持人物位置/朝向/动作方向/光线色调连续,并写清本镜起幅与上一镜落幅的衔接关系(动作接续/视线匹配/运动方向连续),避免跳跃感。视频用 generate_chapter_videos(该章) 一次生成全部镜头,直到该章所有镜头 done(remaining=0)。**不因时间长短、镜头多少、失败次数而提前停止**——必须把该章全部分镜视频都生成完才进入导出。');
- parts.push('用工具完成整条流水线:读入大纲 → 写章节剧本(先按映射加载 sd-script-engine 或 short-drama-scriptwriting;已有剧本则直接使用)→ 写人物圣经/风格 → 写资产生图/音色提示词并生成 → 写分镜(严格按剧本,先 skill(story-pipeline-cn);短剧/漫剧优先 skill(sd-storyboard-engine))→ 写视频提示词(先 skill(h3-prompt-writing))→ generate_chapter_videos 生成该章全部视频 → set_chapter_music 写背景音乐(结构化 caption + 语言合适的 lyrics + duration,先加载音乐技能)→ generate_music 生成该章 BGM → assemble_video(该章) 合并成片(自动垫入 BGM)。若项目设置「是否生成背景音乐」为否,则跳过 set_chapter_music 与 generate_music。每一步用 report 汇报进度。');
- return parts.join('\n\n');
- }
- // ================= 「无限・秩影」lemo-opuscar 代码电影模式 =================
- // 与上面 ComfyUI 全链路完全独立:本模式脱离 ComfyUI,用 node/ffmpeg/three.js/python 渲染成片。
- export function buildOpuscarSystemPrompt({ ctx, external }) {
- const parts = [];
- parts.push('你是「无限・秩影」的自主创作导演,负责用 lemo-opuscar 技能把「所选风格 + 上传素材 + 用户提示词」用代码渲染做成成片视频(node / ffmpeg / three.js / python,脱离 ComfyUI)。');
- parts.push('铁律:全程自主决策,不要向用户询问中间确认;失败先读错误再重试、再降级、最后记录并继续;操作尽量幂等(已产出的文件跳过,便于断点续跑)。');
- parts.push('工具边界:你只有 opuscar_* 系列工具,外加 skill / skill_reference / get_project / list_assets / view_asset / report。禁止调用任何 ComfyUI 领域工具(本会话未注册,调用会被拒绝);不要用 opuscar 工具去读写项目数据库或碰 ComfyUI。');
- parts.push('安全铁律:opuscar_shell 的 cwd 只能是 lib(库根,默认)或 film(影片工作区);命令里的绝对路径必须落在 opuscar_init 返回的 lib_root / film_dir 之内;命令里禁止 ".." 路径段与 rm -rf / sudo / curl|sh 等危险命令(会被拦截)。opuscar_read_file / opuscar_write_file 的 path 只能写相对路径,禁止 ../ 与绝对路径。');
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 123 on GitHub
- parts.push('工作流(严格按序):\n1) opuscar_init 获取 lib_root 与 film_dir;\n2) 首次使用时若库内缺少 node_modules 或 .venv,先 opuscar_shell(cwd=lib, command=sh plugin/skills/lemo-opuscar/scripts/setup.sh deps) 装核心依赖(需要语音加 deps voice、配乐加 deps music);\n3) 读取风格规范:若任务消息给出的是「预设风格 slug」则用 opuscar_read_file 读库内 styles/<slug>/STYLE.md;若给出的是「自定义风格」描述(styleInfo.custom_style),则没有固定 STYLE.md,你要把该描述当作风格不变量自行设计页面(可参考 styles/README.md 选相近风格,或读任意一个 STYLE.md 学习页面契约与写法),其余流程相同;\n4) 在 film_dir 写 TREATMENT.md(三个候选结构 + 你的选择,先于 demo);\n5) 写影片页面代码 index.html(遵循 core/README.md 的「页面契约」:window.READY=true、window.render(t) 确定性逐帧绘制、window.DUR、可选 window.EV / window.TEXTS(t)),以及依赖的 JS/CSS/资源,全部写在 film_dir,不要改库内 styles/ 与 core/;\n6) 渲染:先 opuscar_shell(cwd=lib, command=node core/render/still.mjs "$LEMO_FILM" 1.5 抽帧自查风格是否符合 STYLE.md(或自定义风格描述),再 node core/render/video.mjs "$LEMO_FILM" --out "$LEMO_FILM/out/video.mp4");\n7) 需要语音时 opuscar_write_file 写 lines.json,再 opuscar_shell 跑 core/tts/tts.py 或 tts_zh.py 生成 wav;\n8) 合成:opuscar_shell(cwd=lib, command=sh core/render/mux.sh "$LEMO_FILM/out/video.mp4" "$LEMO_FILM/mix.wav" "$LEMO_FILM/out/final.mp4")(无配乐可跳过 mux,直接交付 video.mp4);\n9) opuscar_save_film 把成片落为项目视频资产。每一步用 report 汇报进度。');
- parts.push('素材语义:用户上传的素材可以是任意文件类型——图片/音频/视频/数据/扫描/CAD/字体/文档等,都已复制到影片工作区 film_dir/materials/ 下(相对路径见任务消息)。你必须逐一审视这些素材:先用 opuscar_read_file 读可读的文本/数据/JSON/字幕等;图片/视频/音频可被页面代码按相对路径引用(如 "materials/xxx.png");「剪辑与纪实 / Evidence Films」类风格(字幕新闻、新闻影片、视觉调查、卫星简报、产品拆解、档案灯台等)把上传素材当真实素材来源组织材料;其余风格把上传素材当参考/风格锚点(角色、场景、配色、构图)。用户提示词是主题与方向。所选风格 slug、用户提示词、素材清单见任务消息。');
- if (external) parts.push('【外部 Agent 运行时】你的领域工具由本地 MCP 服务 ic 提供,工具名可能带 mcp__ic__ / ic__ 等前缀,按同名工具调用即可;开始前先 opuscar_init 验证连通。禁止使用你自身的 shell / 文件读写 / 联网 / 子代理工具。');
- return parts.join('\n\n');
- }
- export function buildOpuscarTaskPrompt({ ctx, styleSlug, styleInfo, prompt, materials, history, continueMessage }) {
- const lines = [];
- const isContinuation = !!String(continueMessage || '').trim();
- if (isContinuation) {
- lines.push('这是在同一条影片记录上继续修改:此前已有一版成片,影片工作区 film_dir 里保留了上一版的 TREATMENT.md、index.html 与素材。');
- } else {
- lines.push('请用 lemo-opuscar 的代码渲染制作一支成片视频。');
- }
- if (styleInfo && styleInfo.custom_style) {
- lines.push('所选风格:自定义风格(无预设 STYLE.md)。\n自定义风格描述:' + styleInfo.custom_style);
- lines.push('请把上面的「自定义风格描述」当作本片的风格不变量(画风/配色/动效/镜头语法/声音调性等)自行实现,不要套用任何预设风格。');
- } else {
- const styleLabel = styleInfo ? (styleInfo.cn || styleInfo.en || '') : String(styleSlug || '');
- lines.push('所选风格:' + styleLabel + '(slug=' + styleSlug + ')' + (styleInfo && styleInfo.cat ? ',类别:' + styleInfo.cat : '') + (styleInfo && styleInfo.line_cn ? ';简介:' + styleInfo.line_cn : ''));
- }
- lines.push('用户提示词:' + (String(prompt || '').trim() || '(无)'));
- if (Array.isArray(materials) && materials.length) {
- const ms = materials.map((m, i) => (i + 1) + '. [' + (m.type || 'file') + '] ' + (m.name || m.filename || '') + '(相对路径:' + (m.filename || '') + ')');
- lines.push('已上传素材清单(均在 film_dir/materials/ 下,可读文本用 opuscar_read_file,图片/视频/音频可在页面代码里按相对路径引用):\n' + ms.join('\n'));
- } else {
- lines.push('已上传素材清单:(无)');
- }
- if (isContinuation) {
- if (Array.isArray(history) && history.length) {
- const hs = history.filter((m) => m && String(m.text || '').trim()).map((m, i) => (i + 1) + '. ' + String(m.text).trim());
- lines.push('此前的修改对话:\n' + hs.join('\n'));
- }
- lines.push('本轮修改要求:' + String(continueMessage).trim());
- lines.push('执行要求:先用 opuscar_read_file 读取 film_dir 里现有的 TREATMENT.md、index.html 及相关代码/素材,理解上一版的实现;只改本轮要求涉及的部分,保留其余内容与风格不变;改完重新渲染并合成,最后 opuscar_save_film 覆盖保存到同一条记录。除非本轮要求涉及画幅或时长,否则保持原有 DUR 与画面比例。');
- return lines.join('\n\n');
- }
- lines.push('请按系统提示词的工作流执行:先读所选风格 STYLE.md,再写 TREATMENT 与页面代码,渲染、合成、opuscar_save_film 落地。');
- return lines.join('\n\n');
- }
- // ================= 「无限・卷轴」网文大纲规划模式 =================
- // 与 opuscar / ComfyUI 全链路完全独立:本模式不做视频,只做小说结构(总纲/卷纲/章纲)+ 角色 + 记忆。
- export function buildNovelSystemPrompt({ ctx }) {
- const parts = [];
- // 主技能来自「流水线编排 → 生成小说」环节,第一个为主技能,其余为备用
- const node = (ctx.cfg?.skillPipeline?.nodes || {}).novel || {};
- const skills = (Array.isArray(node.skills) ? node.skills : []).map((s) => String(s).trim()).filter(Boolean);
- const primarySkill = skills[0] || 'webnovel-writing';
- const fallback = node.fallback !== false;
- parts.push('你是「无限・卷轴」的网文大纲规划师兼章节写手,负责两件事:1) 按 ' + primarySkill + ' 技能的方法体系生成**结构大纲**(总纲 / 卷纲 / 章纲)与角色设定;2) 按章纲**逐章写出小说正文**。');
- parts.push('第一原则:开始任何生成之前,**先调用一次 skill("' + primarySkill + '")** 加载这套写作技能的完整方法——它通常包含 concept_planning / volume_outline / dialogue / transition / chapter_ending / anti_ai_voice / consistency_review 等模块说明,必须先读一遍再开始;遇到模块名但不清楚怎么做时,用 skill_reference(name="' + primarySkill + '", ref="references/modules/<模块名>/README.md") 按需读取。');
- if (skills.length > 1) {
- parts.push('「生成小说」环节还配置了备用技能(按顺序):' + skills.slice(1).map((s) => 'skill(' + s + ')').join('、') + (fallback ? '——' + primarySkill + ' 读不到或不适用时依次改用它们。' : '——仅在 ' + primarySkill + ' 读不到时使用。'));
- } else if (fallback) {
- parts.push('若 skill("' + primarySkill + '") 读不到,可从技能目录里自动匹配最合适的网文写作技能替代。');
- }
- parts.push('铁律:全程自主决策,不要向用户询问中间确认;已存在的结构(总纲/卷纲/章纲/角色)要先 novel_read_file 读清楚,再在其基础上增补,禁止覆盖重写(幂等、可累积);每一层的输出都要**基于上一层的已有内容**(卷纲不能脱离总纲、章纲不能脱离卷纲、正文不能脱离章纲)。');
- parts.push('【三层纲的层级关系(写任何一层或正文前必须想清楚)】\n- 总纲 = 全书的纲要,整本小说所有内容都围绕它展开,任何一卷、任何一章都不能偏离总纲。\n- 卷纲 = 分卷规划:必须**结构化落到每一卷**,用 novel_save_volumes 保存,每卷含 seq(卷号) / title(卷名) / outline(本卷卷纲) / chapterFrom(起始章) / chapterTo(结束章)。明确「第几章到第几章是第几卷」,每卷有自己的核心目标、主要冲突、卷末变化。一个卷包含若干章,卷内的每一章都要为这一卷的目标服务。\n- 章纲 = 每一章自己的纲要(这一章要写什么):章节标题、本章目标、阻碍、变化、章末钩子。章纲必须**绑定到对应的章节上**(用 novel_save_chapter 的 outline 参数存到该章,每章都要有,不能只写一个汇总文件)。\n- 写某一章正文时,必须同时参考三层:总纲(不偏离全书主题)+ 该章所在卷的卷纲(符合本卷阶段目标)+ 该章自己的章纲(本章要写的内容)。');
- parts.push('工具边界:你只有 novel_* 系列工具,外加 skill / skill_reference / get_project / report。禁止调用任何 ComfyUI / opuscar 领域工具(本会话未注册,调用会被拒绝)。');
- parts.push('安全铁律:novel_write_file / novel_read_file 的 path 只能写相对 novel/ 目录的路径,禁止绝对路径与 "../";允许的顶层文件只有 总纲.md / 卷纲.md / 章纲.md,其他子目录文件统一放到 memory/ 下(如 memory/设定.md / memory/伏笔.md)。');
- parts.push('输出要求(严格按层级):\n\n【总纲】先 novel_write_file("总纲.md", ...),包含:一句话 hook / premise / 题材与卖点 / 故事引擎 / 目标长度判断(短/中/长/连载)/ 故事的核心冲突与第一卷目标。\n\n【分卷(卷纲)】在总纲之上展开:用 **novel_save_volumes** 把分卷结构化保存——每卷 seq(卷号) / title(卷名) / outline(本卷卷纲:核心目标+主要冲突+卷末变化) / chapterFrom(起始章序号) / chapterTo(结束章序号)。同时可把汇总写一份 卷纲.md 供人查看。\n\n【章纲】在分卷之上,**为每一章**写清「本章标题 / 本章目标 / 阻碍 / 变化 / 章末钩子」,并逐章用 **novel_save_chapter(title, volume, outline)** 落库(章纲绑定到每章,每章都必须带 outline 与所属 volume)——**不允许只写一个章纲.md 汇总就算完**。\n\n【角色】用 novel_save_characters 保存结构化角色列表,每项含 id(空即可, 自动分配) / name / role / description。主角、重要配角、反派都要覆盖;description 要写清楚:性格、背景、当前目标、与主角/其他角色的关系。\n\n【上下文记忆】每完成一层生成后,用 novel_write_file("memory/设定.md", ...) 记下世界观/规则设定、"memory/伏笔.md" 记下已埋下的伏笔、"memory/剧情进展.md" 记下当前到哪一卷哪一章。后续生成新层时先读这些记忆,保证不前后矛盾。');
- parts.push('工作流(严格按序):\n1) novel_init 确认目录与已有内容(含已有分卷与章节);\n2) skill("' + primarySkill + '") 加载技能;\n3) 根据任务要求的 step(outline/volumes/chapters/write/start/all),按 总纲 → novel_save_volumes 分卷 → 逐章 novel_save_chapter(带 volume+outline)→ 逐章写正文 顺序生成;\n4) 每生成一层都落库(novel_write_file / novel_save_volumes / novel_save_chapter / novel_save_characters)、更新记忆;\n5) report 汇报每层完成进度。');
- parts.push('【写正文职责】当任务要求写正文(step=write 或 start)时:先用 novel_get_volumes 读分卷、novel_list_chapters 看每一章的卷号/章纲(outline)/正文状态;**从第一个正文为空的章节开始逐章写**;写某章前,先读该章自己的 outline(章纲)+ 该章所属卷的卷纲(novel_get_volumes 里同 seq 的 outline)+ 总纲,三者同时参考;每章正文覆盖本章目标/阻碍/变化/章末钩子,人物按角色设定走、对白带身份感、章末留钩子(参考 dialogue / transition / chapter_ending 模块);写完整正文后用 novel_save_chapter(title, volume, outline, content) 落库(**必须保留该章原有 outline 与 volume**);每章写完按 consistency_review 过一遍六种一致性(剧情逻辑/人物目标/情绪关系/身体信息/场景转场/章末承接),不稳就回对应模块修;写完后用 novel_write_file("memory/剧情进展.md", ...) 更新进度。若任务指定了只写某一章,就只写那一章。');
- parts.push('【动态记忆铁律】记忆要随写随更,禁止只在全部结束时才更新一次:写每一章正文**前**,先 novel_get_memory 读一遍最新记忆(人物当前状态 / 已埋伏笔 / 剧情进展);写完该章**后**,立即用 novel_save_memory 更新——剧情进展(写到了第几卷第几章)、本章新埋的伏笔、人物状态/关系变化。后续章节写作前再读最新记忆,保证长篇创作前后一致、不遗忘伏笔。');
- return parts.join('\n\n');
- }
- export function buildNovelTaskPrompt({ ctx, step, message }) {
- const lines = [];
- const proj = ctx.project || {};
- lines.push('请为这本小说生成结构大纲。');
- lines.push('小说标题:' + (proj.name || '(未命名)'));
- lines.push('中心思想:' + (proj.idea || '(无)'));
- const s = String(step || '').toLowerCase();
- const levelText = {
- outline: '只生成【总纲】——先 concept_planning 把中心思想压成题材、卖点、hook、premise、故事引擎、目标长度与第一卷方向,再 novel_write_file("总纲.md")。',
- volumes: '在已有的总纲之上生成【分卷】——按 volume_outline 决定分几卷、每卷覆盖第几章到第几章、每卷核心目标/主要冲突/卷末变化,然后用 **novel_save_volumes** 结构化保存(每卷 seq/title/outline/chapterFrom/chapterTo),并把汇总写一份 卷纲.md。若还没有总纲,**先按 concept_planning 生成总纲落盘**,再继续分卷。',
- chapters: '在已有的分卷之上生成【章纲并绑定到每章】——先用 novel_get_volumes 读每卷的章节范围,再**为每一章**写清「本章标题 / 本章目标 / 阻碍 / 变化 / 章末钩子」,逐章用 **novel_save_chapter(title, volume, outline)** 落库(每章都必须带所属 volume 与本卷章纲 outline);最后把汇总写一份 章纲.md。若分卷缺失,**先补分卷再生成章纲**。',
- write: '写正文:先用 novel_get_volumes 读分卷、novel_list_chapters 看每一章的卷号/章纲/正文状态;**从第一个正文为空的章节开始逐章写**;写某章前先读该章的 outline + 所属卷的卷纲 + 总纲,三者同时参考;每章正文用 novel_save_chapter(title, volume, outline, content) 落库(保留原 outline 与 volume)、写完过 consistency_review、更新 memory/剧情进展.md。若任务指定了只写某一章,就只写那一章。',
- extend: '【扩写】沿现有剧情继续延伸后续内容。先用 novel_get_memory 读最新记忆、novel_get_volumes 读分卷、novel_list_chapters 看当前写到了第几章第几卷,据此决定:①若指定了章数 N,则新增 N 章(必要时新开一卷);②未指定章数,则由你根据现有剧情与卷末钩子新开一卷(章数自定)。为新章节生成章纲(novel_save_chapter 带 volume+outline,不传 content),再逐章写正文(参考 总纲 + 所属卷卷纲 + 本章章纲),每章写完立即 novel_save_memory 更新剧情进展。严禁改写/推翻已有章节的正文。',
- start: '生成整本小说(**支持断点续跑**):先 novel_init / novel_list_files / novel_get_volumes / novel_list_chapters 检查已有内容,**已存在的层直接跳过、只补缺失部分**(已有正文的章节不要重写,从第一章起找到第一个正文为空的章继续写)。严格按以下顺序执行,每完成一步用 report 汇报:①**生成大纲**(若总纲为空):基于「中心思想/故事概要」用 concept_planning 产出总纲 → novel_write_file("总纲.md");②**生成角色**(若角色为空):novel_save_characters 保存全部主要角色;③**创建卷**(若 volumes 为空):决定分几卷、每卷覆盖第几章到第几章、每卷卷纲 → novel_save_volumes 结构化保存;④**创建章节**(缺失的章):按分卷逐章 novel_save_chapter(title, volume) 建出全部章节(不传 content,避免清空正文);⑤**生成章纲**(缺失 outline 的章):为每一章写「本章目标/阻碍/变化/章末钩子」,novel_save_chapter(title, volume, outline) 逐章更新(不传 content);⑥**记忆**(缺失时):novel_write_file("memory/设定.md")、("memory/伏笔.md")、("memory/剧情进展.md");⑦**写正文**:从第一章起按顺序逐章写,跳过已有正文的章,每章参考「总纲 + 所属卷卷纲 + 本章章纲」,用 novel_save_chapter(title, volume, outline, content) 覆盖该章正文,写完过 consistency_review;全部完成汇报「整本小说生成完成」。',
- all: '完整生成全部三层:总纲 → 卷纲 → 章纲。每落盘一层都 report 一次进度。',
- }[isValidNovelStep(s) ? s : 'all'];
- lines.push('当前任务:' + levelText);
- if (s === 'write' && ctx.chapter) {
- lines.push('本次只写这一章:' + ctx.chapter);
- }
- // 上下文引擎:把已有结构拼进来,保证跨层一致
- const ctxBlock = buildNovelContextBlock(ctx.projectId);
- if (ctxBlock) {
- lines.push('—— 上下文引擎(当前已有的内容,必须在此基础上续写,禁止推翻重写)——\n' + ctxBlock);
- lines.push('—— 若上文某一段为空(总纲/卷纲/章纲/角色/记忆里某项缺失),那就是还没生成的层,你需要**先补齐缺失层**再继续当前层的生成,保证上下依赖不悬空。');
- } else {
- lines.push('当前小说目录下还没有任何内容,从零开始生成。');
- }
- if (String(message || '').trim()) {
- lines.push('用户补充要求:' + String(message).trim());
- }
- return lines.join('\n\n');
- }
lib/agent/tools.js · Bundled script · 2,658 lines · 1 finding marked
- import path from 'node:path';
- import fs from 'node:fs';
- import { spawn } from 'node:child_process';
- import {
- loadConfig, Projects, Assets, Shots, ShotVideos, Chapters, Workflows, ReferenceImages,
- logger, uid, slugify, randomSeed, chapterStats, Queue,
- SKILLS_DIR, ensureProjectDirs, projectDir, resolveProjectPath,
- assembleShotReferences, fallbackVideoPrompt, validateSubShots,
- dialogueSpeakerNames, MAX_SPEAKERS_PER_SHOT,
- SHOT_DIALOGUE_MAX_RATE, SHOT_DURATION_MIN, SHOT_DURATION_MAX, SHOT_DURATION_DEFAULT,
- fallbackAssetPrompt, llmChat, extractJson, CHARACTER_T2I_LAYOUT_CONSTRAINT,
- imageToDataUrl, buildVisionUserMessage,
- runWorkflow, pickOutput, downloadToFile, getSpecForKind, getR2vSpecForResolution, uploadTaskInput,
- mergeVideos, withWriteContext, resolveSubtitles, renderConcurrencyLimit, inferVideoMode,
- listNovelFiles, readNovelFile, writeNovelFile, loadNovelState, saveNovelState,
- } from '../core/index.js';
- import { PROJECT_ASSET_SUBDIRS, ASSET_CATEGORY_IDS, ratioToSize, inferVoiceBaseline, filterReferenceImages, CONTEXT_KEYS, textMentions, isVariantAssetCategory, VIDEO_MODES } from '../shared/index.js';
- import { loadSkillWithResources, renderSkillContent } from './skill-engine.js';
- import { guardToolCall } from './guard.js';
- import { searchWeb, searchImages, downloadImageSafe } from './search.js';
- // ================= 工具定义(OpenAI function-calling) =================
- export const TOOL_DEFINITIONS = [
- { type: 'function', function: { name: 'skill', description: '加载一个可用技能的完整说明与参考文件索引,返回技能正文后严格遵循;需要某个参考文件全文时再用 skill_reference。命中以下任务前必须先调用:写视频提示词→skill(h3-prompt-writing);拆分镜脚本→skill(story-pipeline-cn);写图片/图生图提示词→skill(image-prompt-writing);设计人物音色→skill(tts-voice-design);总流水线→skill(novel-to-video)。短剧/漫剧:短剧编剧→skill(0715-scriptwriter);剧本总控→skill(script-master);小说改编→skill(novel-to-skitscreenplay);转分镜→skill(novel-to-storyboard);文字分镜JSON→skill(hf-drama-storyboard-script);漫剧策划→skill(ai-manga-planner);漫剧导演→skill(manju-director-agent);漫剧全流程→skill(manga-drama-generator);脚本转漫剧→skill(script-to-manga);分镜解析→skill(comic-drama-generator);镜头库/影视级→skill(cinematic-ai-comic-director);道具年代一致→skill(era-consistency-optimizer);全栈分镜提示词→skill(manga-full-stack)。漫剧老李套装→skill(short-drama-director)(子技能 sd-script/sd-storyboard/sd-asset/sd-combat/sd-feed/sd-qc 等按目录选择);微短剧分集剧本→skill(short-drama-scriptwriting)。', parameters: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] } } },
- { type: 'function', function: { name: 'skill_reference', description: '加载某技能 references 目录下的单个参考文件全文(例如 skill_reference(name="script-master", ref="framework.md");子目录文件用相对路径,如 ref="style-bible/style-lock-protocol.md")。先用 skill() 查看该技能的参考文件索引,再按需加载单个文件。', parameters: { type: 'object', properties: { name: { type: 'string' }, ref: { type: 'string' } }, required: ['name', 'ref'] } } },
- { type: 'function', function: { name: 'get_project', description: '读取当前项目信息与上下文摘要(人物圣经/风格指南/连续性记录),含章节列表。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'list_chapters', description: '列出项目章节(每章的标题/序号/状态/该章分镜数/是否有剧本)。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'get_chapter', description: '读取某章的完整内容:小说原文 novel 与剧本 script。拆分镜前先读本章剧本;剧本为空且项目开启自动生成时,先写剧本再拆分镜。', parameters: { type: 'object', properties: { chapter: { type: 'string', description: '章节标题或 id(先用 list_chapters 查看本项目章节)' } }, required: ['chapter'] } } },
- { type: 'function', function: { name: 'set_chapter_script', description: '写入本章剧本(拆分镜的唯一剧情蓝本)。已有非空剧本时默认拒绝覆盖,仅当用户明确要求重写剧本时才传 overwrite:true。', parameters: { type: 'object', properties: { chapter: { type: 'string', description: '章节标题或 id' }, script: { type: 'string', description: '完整剧本文本:场次【第N场|时间|地点】+ 出场人物 + 场景/动作描述 + 台词(人物名:台词)+ 必要旁白' }, overwrite: { type: 'boolean', description: 'true=允许覆盖已有剧本(仅当用户明确要求重写剧本时)' } }, required: ['chapter', 'script'] } } },
- { type: 'function', function: { name: 'save_context', description: '写入项目上下文文件:bible(人物圣经)/ style(风格指南)/ continuity(连续性记录,追加)。', parameters: { type: 'object', properties: { key: { type: 'string', enum: ['bible', 'style', 'continuity'] }, content: { type: 'string' } }, required: ['key', 'content'] } } },
- { type: 'function', function: { name: 'report', description: '向任务进度汇报一条状态(阶段/详情)。', parameters: { type: 'object', properties: { phase: { type: 'string' }, detail: { type: 'string' } }, required: ['detail'] } } },
- { type: 'function', function: { name: 'list_assets', description: '列出项目资产,可按分类过滤。返回含 prompt/prompt_used/prompt_locked(prompt_locked=1 表示这是用户手动保存的提示词,权威,不要覆盖)。', parameters: { type: 'object', properties: { category: { type: 'string', enum: ASSET_CATEGORY_IDS } } } } },
- { type: 'function', function: { name: 'create_asset', description: '创建资产(人物/场景/道具/语音/其他)。category=costume(服装)/age(年龄)是「挂在角色下的变体」,必须用 parent_id 指向本项目的角色资产;否则该变体在生成阶段会被静默忽略(refs.js 只按 parent_id 把它映射到角色)。更推荐直接用 change_outfit/design_outfits(服装)或 change_age/design_ages(年龄)生成变体。', parameters: { type: 'object', properties: { category: { type: 'string', enum: ASSET_CATEGORY_IDS }, name: { type: 'string' }, description: { type: 'string' }, voice_desc: { type: 'string', description: '人物声音特征描述(仅人物):性别+年龄段+音色质感,如「青年男性,嗓音低沉」。后续 design_voice 会优先用它作为音色描述。' }, parent_id: { type: 'string', description: '仅服装(costume)/年龄(age)变体需要:所挂角色(character)资产的 id。缺了会被拒绝。' } }, required: ['category', 'name'] } } },
- { type: 'function', function: { name: 'update_asset', description: '更新资产字段(描述/提示词/参考语音/一致性锚点)。注意:用户若在素材库手动保存过该资产的提示词(prompt_locked=1),本工具不会覆盖它,只会更新其他字段——不要试图用本工具改写用户手写的提示词。', parameters: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' }, description: { type: 'string' }, voice_desc: { type: 'string', description: '人物声音特征描述:性别+年龄段+音色质感,如「青年男性,嗓音低沉」。' }, prompt: { type: 'string' }, negative_prompt: { type: 'string' }, voice_ref: { type: 'string' }, consistency_key: { type: 'string' } }, required: ['id'] } } },
- { type: 'function', function: { name: 'generate_asset_image', description: '文生图生成资产图片(Qwen-Image-2512)。prompt 为空时用资产描述兜底。', parameters: { type: 'object', properties: { asset_id: { type: 'string' }, prompt: { type: 'string' }, negative_prompt: { type: 'string' }, ratio: { type: 'string' } }, required: ['asset_id'] } } },
- { type: 'function', function: { name: 'edit_asset_image', description: '图生图/图像编辑(Qwen-Image-Edit-2511):以参考图 + 指令生成新图,用于一致性变体。reference_asset_id 传资产 id、reference_image_path 传参考图相对路径(二者选一,缺省用资产自身图)。', parameters: { type: 'object', properties: { asset_id: { type: 'string' }, prompt: { type: 'string' }, reference_asset_id: { type: 'string' }, reference_image_path: { type: 'string' } }, required: ['asset_id', 'prompt'] } } },
- { type: 'function', function: { name: 'change_outfit', description: '人物换装:以角色 canonical 参考图为参考,用图生图(Qwen-Image-Edit)生成该角色的一套新服装资产(category=costume,parent_id 指向角色),供分镜按章引用。label 为服装短名(如「进城旧衣」),用于资产命名与分镜引用;outfit 为服装外观描述。仅当剧情「确实发生换装事件」(沐浴/洗澡/更衣/换衣/换装/换上新衣)时才调用;不同场景、不同镜头、不同机位都不算换装,没有换装事件的角色一律直接用 canonical 图,禁止生成服装变体。剧情出现换装事件后,为对应角色生成一套新服装,并在换装事件之后的镜头用 set_storyboard 的 costumes 字段引用。同一个角色在一个分镜里只引用一件服装。', parameters: { type: 'object', properties: { character_id: { type: 'string' }, outfit: { type: 'string' }, label: { type: 'string' }, prompt: { type: 'string' } }, required: ['character_id', 'outfit'] } } },
- { type: 'function', function: { name: 'design_outfits', description: '仅当剧情确有换装事件(沐浴/更衣/换上新衣、时间跳跃后换装)时才调用。给角色一次性设计并生成多套服装资产(衣橱):以角色 canonical 参考图为参考,用图生图为每套服装生成一张服装图(category=costume,parent_id 指向角色),供分镜按服装名引用对应那套。不同场景、不同镜头、不同机位都不算换装;没有换装事件的角色不要调用(直接用 canonical 图,避免素材冗余)。同一角色的整套素材通常只需要 1 套服装,不要按场景给同一角色生成多套。outfits 传该角色真正需要的服装清单,每套含 name(服装短名,如「进城旧衣」「沐浴后家居服」)与 description(服装外观描述)。', parameters: { type: 'object', properties: { character_id: { type: 'string' }, outfits: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, description: { type: 'string' } }, required: ['name', 'description'] } } }, required: ['character_id', 'outfits'] } } },
- { type: 'function', function: { name: 'change_age', description: '人物年龄变体:以角色 canonical 参考图为参考,用图生图(Qwen-Image-Edit)生成该角色某一时期/年龄的样貌(category=age,parent_id 指向角色),保持脸/五官/发型/画风一致、只改年龄,供回忆/时间跳跃镜头按章引用。label 为年龄短名(如「年轻」「中年」「老年」),用于资产命名与分镜引用;age 为年龄/时期外观描述。仅当剧情「明确发生时间跳跃或年龄变化」(回忆/闪回、小时候、多年前、多年后、步入中老年等)时才调用;「年轻」「少年」这类普通外貌描写不算。同一个角色只需生成剧情真正需要的那一个时期变体,不要为同一角色生成多个年龄段。', parameters: { type: 'object', properties: { character_id: { type: 'string' }, age: { type: 'string' }, label: { type: 'string' }, prompt: { type: 'string' } }, required: ['character_id', 'age'] } } },
- { type: 'function', function: { name: 'design_ages', description: '仅当剧情明确展示角色不同年龄段/时期(回忆/闪回/时间跳跃/年龄变化)时才调用。给角色生成对应时期的年龄变体:以角色 canonical 参考图为参考,用图生图为每个时期生成一张年龄变体图(category=age,parent_id 指向角色),供分镜按变体名引用。剧情没有年龄变化、或只有「年轻/少年」这类普通外貌描写的角色不要调用(直接用 canonical 图,避免素材冗余);同一个角色只需一个真正需要的时期变体时,不要生成多个。ages 传该角色的时期清单,每项含 name(年龄短名,如「年轻」「中年」「老年」)与 description(年龄/时期外观描述)。', parameters: { type: 'object', properties: { character_id: { type: 'string' }, ages: { type: 'array', items: { type: 'object', properties: { name: { type: 'string' }, description: { type: 'string' } }, required: ['name', 'description'] } } }, required: ['character_id', 'ages'] } } },
- { type: 'function', function: { name: 'view_asset', description: '查看某资产的参考图(视觉模型):返回资产元数据与图片块;模型不支持图片输入时仅返回文本。', parameters: { type: 'object', properties: { asset_id: { type: 'string' } }, required: ['asset_id'] } } },
- { type: 'function', function: { name: 'view_shot_references', description: '查看某分镜的参考素材图(角色/场景/道具/服装,视觉模型):返回清单与 ≤9 张参考图;模型不支持图片输入时仅返回文本。', parameters: { type: 'object', properties: { shot_id: { type: 'string' } }, required: ['shot_id'] } } },
- { type: 'function', function: { name: 'view_project_references', description: '查看用户上传的参考图片素材(视觉模型):返回参考图清单与图片块,据此分析其内容/画风/元素并生成风格与设定一致的新素材;模型不支持图片输入时仅返回文本清单。', parameters: { type: 'object', properties: {} } } },
- { type: 'function', function: { name: 'register_voice', description: '登记资产(人物)的参考音色文件名(相对项目 assets/voice/)。', parameters: { type: 'object', properties: { asset_id: { type: 'string' }, voice_ref: { type: 'string' } }, required: ['asset_id', 'voice_ref'] } } },
- { type: 'function', function: { name: 'design_voice', description: '用 Qwen3 TTS 音色设计工作流为人物设计音色:text 是人物朗读的简短自我介绍文案(20~30 字,约 5 秒,禁止长篇大论),voice_description 是音色描述(不限制字数,可详细写;必须包含性别与年龄段,如「青年男性,嗓音低沉」,缺失会导致音色性别/年龄错乱)。生成语音样本并存为该项目 voice_ref。', parameters: { type: 'object', properties: { asset_id: { type: 'string' }, text: { type: 'string', description: '人物朗读的简短自我介绍,20~30 字,约 5 秒' }, voice_description: { type: 'string', description: '音色描述,不限制字数,必须包含性别与年龄段' } }, required: ['asset_id'] } } },
- { type: 'function', function: { name: 'generate_assets_batch', description: '按工作流类型分批统一生成项目素材:先文生图全部图片类资产(人物/场景/道具),再设计全部人物音色(Qwen3-TTS)。批次会一次性排入渲染槽位并发提交,实际并发上限由渲染槽位决定(RunningHub 按 runninghubConcurrency,本地 ComfyUI 恒为 1)。已生成成功的资产自动跳过(幂等)。only 可传 ["image"] 或 ["tts"] 只跑其中一类(用于把两类分到不同的 ComfyUI 实例)。', parameters: { type: 'object', properties: { only: { type: 'array', items: { type: 'string', enum: ['image', 'tts'] } } } } } },
- { type: 'function', function: { name: 'generate_asset_from_reference', description: '以某张用户上传的参考图为输入,用图生图(Qwen-Image-Edit)生成一个新素材资产(category/name 指定)。用于「参考生成新素材」:先分析参考图内容/风格,再据此派生新素材。category=costume/age 属「挂在角色下的变体」,必须用 parent_id 指向本项目的角色资产。', parameters: { type: 'object', properties: { reference_id: { type: 'string' }, category: { type: 'string', enum: ASSET_CATEGORY_IDS }, name: { type: 'string' }, prompt: { type: 'string' }, description: { type: 'string' }, parent_id: { type: 'string', description: '仅服装(costume)/年龄(age)变体需要:所挂角色(character)资产的 id。' } }, required: ['reference_id', 'category', 'name'] } } },
- { type: 'function', function: { name: 'set_storyboard', description: '写入/追加分镜列表(按章内 idx upsert,非破坏:已生成的分镜保留 status/video,新增章节按更高 idx 追加;每章分镜编号 idx 独立从 1 开始,不要跨章连续编号)。characters/scenes/props/costumes/ages/audios 传资产名数组(costumes 为换装后的服装资产名,沐浴/更衣/换装事件之后的镜头必须引用对应服装,事件之前的镜头不引用;同一角色每个分镜只引用一件服装。ages 为年龄/时期变体资产名,回忆/时间跳跃镜头引用对应时期;同一角色每个分镜只引用一个年龄变体,且不要与服装同时引用同一角色的两张图;audios 为独立音频素材名——旁白音色/背景音乐/音效,作为 H3 音色参考输入,有旁白的分镜引用旁白音色);chapter 传章节标题或章节 id(先用 list_chapters 看本项目章节);narration 传该镜旁白口播稿(没有旁白留空)。硬约束:dialogue 字数必须 ≤ duration×5(中文旁白约 4-5 字/秒),超长会被拒绝,需缩短台词或拆镜;每个分镜最多 2 个说话人,≥3 人对话会被拒绝,需拆成多个分镜(参考音频只提交有台词角色,单分镜 ≤3 段)。', parameters: { type: 'object', properties: { shots: { type: 'array', items: { type: 'object', properties: { idx: { type: 'number' }, chapter: { type: 'string' }, scene_name: { type: 'string' }, duration: { type: 'number' }, characters: { type: 'array', items: { type: 'string' } }, scenes: { type: 'array', items: { type: 'string' } }, props: { type: 'array', items: { type: 'string' } }, costumes: { type: 'array', items: { type: 'string' } }, ages: { type: 'array', items: { type: 'string' } }, audios: { type: 'array', items: { type: 'string' } }, sub_shots: { type: 'string' }, dialogue: { type: 'string' }, narration: { type: 'string' }, camera: { type: 'string' }, visual: { type: 'string' } } } }, clear: { type: 'boolean', description: '只清空本次写入涉及章节的现有分镜(按 idx 重写本章),其他章节的分镜一律保留;省略=追加/更新' } }, required: ['shots'] } } },
- { type: 'function', function: { name: 'list_shots', description: '列出项目分镜及其状态。', parameters: { type: 'object', properties: {} } } },
- { type: 'function', function: { name: 'update_shot', description: '更新某分镜字段(video_prompt 为按 h3-prompt-writing 技能写好的 H3 视频提示词,生成视频前必须先写入)。', parameters: { type: 'object', properties: { shot_id: { type: 'string' }, sub_shots: { type: 'string' }, dialogue: { type: 'string' }, narration: { type: 'string' }, camera: { type: 'string' }, visual: { type: 'string' }, duration: { type: 'number' }, video_prompt: { type: 'string' }, mode: { type: 'string', description: '生成模式(缺省 auto=按参考素材自动推断):reference=全能参考(多图+音视频);image=图生视频(1 张图);text=文生视频(不连接任何媒体节点);digital_human=数字人(预留,暂不对接业务)。首尾帧不在本工具内使用,只能由用户在「插入自定义分镜」里手动选择' } }, required: ['shot_id'] } } },
- { type: 'function', function: { name: 'generate_shot_video', description: '为某分镜生成视频(MiniMax H3 Ref2VA)。', parameters: { type: 'object', properties: { shot_id: { type: 'string' } }, required: ['shot_id'] } } },
- { type: 'function', function: { name: 'regenerate_shot', description: '重新生成某分镜视频,可带反馈文字(如「镜头拉近/让人物微笑」)。render=false 时只用 LLM 按反馈改写 video_prompt,不提交 ComfyUI 渲染。append=true 时把新视频追加为该分镜的新候选(保留旧候选),默认 false 为替换整批候选。', parameters: { type: 'object', properties: { shot_id: { type: 'string' }, feedback: { type: 'string' }, render: { type: 'boolean', description: 'false=只做 LLM 改写提示词,不渲染视频;默认 true' }, append: { type: 'boolean', description: 'true=追加为新候选(保留旧候选),false=替换整批候选(默认)' } }, required: ['shot_id'] } } },
- { type: 'function', function: { name: 'write_shot_video_prompt', description: '按 h3-prompt-writing 技能为某分镜撰写视频提示词(依据画面/台词/参考素材生成,含 __MINIMAX_H3_REF_N__ 占位符),写回 shot.video_prompt,不渲染。用于手工插入的分镜没有提示词时自动补全。', parameters: { type: 'object', properties: { shot_id: { type: 'string' } }, required: ['shot_id'] } } },
- { type: 'function', function: { name: 'generate_chapter_videos', description: '为指定章节一次性生成/补齐全部镜头视频(确定性批量循环,不省略任何镜头);无依赖关系的镜头会并发提交,引用资产尚未生成完成的镜头会暂缓(deferred)且不提交渲染;force=true 时强制重生成本章全部视频(含已 done)。失败的镜头标记为 failed 并继续,直到该章所有可跑镜头有结果。不受步数/时长限制。', parameters: { type: 'object', properties: { chapter: { type: 'string' }, force: { type: 'boolean' } }, required: ['chapter'] } } },
- { type: 'function', function: { name: 'assemble_video', description: '用 ffmpeg 合并本章分镜视频为成片,并垫入该章背景音乐(若有)。chapter 缺省时合并全部分镜(不混背景音乐)。', parameters: { type: 'object', properties: { chapter: { type: 'string' } } } } },
- { type: 'function', function: { name: 'set_chapter_music', description: '为指定章节撰写背景音乐:caption 为结构化音乐风格描述(先加载 skill(ai-music-studio) 与 skill(music-caption-rewriter),按其规范产出贴合本章剧情的 Global Metadata / Vocal Details / Arrangement),lyrics 为歌词(用适合本章剧情的语言:华语普通话/粤语/英语等),duration 为合适时长秒数。写入章节记录,后续 generate_music 据此生成。', parameters: { type: 'object', properties: { chapter: { type: 'string' }, caption: { type: 'string' }, lyrics: { type: 'string' }, duration: { type: 'number' } }, required: ['chapter', 'caption', 'lyrics'] } } },
- { type: 'function', function: { name: 'generate_music', description: '为指定章节生成带歌词的背景音乐(MiniMax Music3)。读取该章已写好的 caption/lyrics/duration(未写则用项目风格兜底、无歌词)。', parameters: { type: 'object', properties: { chapter: { type: 'string' } }, required: ['chapter'] } } },
- { type: 'function', function: { name: 'generate_music_asset', description: '为一条已创建的背景音乐资产(asset_id)生成音频。资产的 prompt(caption)/lyrics/max_duration 已写好;生成完成后写入音频并置 done,失败置 failed。', parameters: { type: 'object', properties: { asset_id: { type: 'string' } }, required: ['asset_id'] } } },
- { type: 'function', function: { name: 'apply_chapter_music', description: '把音乐库中选定的背景音乐(music_id)应用到多个章节(chapters 数组,仅已全部生成完成的章节会应用),并重新合成各章成片。', parameters: { type: 'object', properties: { music_id: { type: 'string' }, chapters: { type: 'array', items: { type: 'string' } } }, required: ['music_id', 'chapters'] } } },
- { type: 'function', function: { name: 'list_workflows', description: '列出已注册的 ComfyUI 工作流。', parameters: { type: 'object', properties: {} } } },
- { type: 'function', function: { name: 'web_search', description: '联网搜索。type=web 查资料/确认事实;type=image 搜参考图片(返回图片 URL 数组)。遇到你不知道或不确凿的事实——品牌名、产品型号、年代物品的真实外观、专业术语、历史/地理/科技细节、真实存在的服饰/道具样式等——必须先查证再写,禁止凭空臆造年代/品牌/型号错误。需要某物品/服饰的参考图时用 type=image 搜图,再配 download_reference_image 下载为参考图。若设置里关闭了联网搜索,本工具会返回 disabled(此时改用既有知识继续,不要重试)。', parameters: { type: 'object', properties: { query: { type: 'string', description: '搜索关键词' }, type: { type: 'string', enum: ['web', 'image'], description: 'web=文字资料搜索(默认),image=图片搜索' }, engine: { type: 'string', description: 'type=web 时指定引擎 id 逗号分隔(如 bing-cn,baidu);省略用国内引擎组合' }, limit: { type: 'number', description: '返回条数上限,默认 8' } }, required: ['query'] } } },
- { type: 'function', function: { name: 'download_reference_image', description: '把一张图片 URL 下载到本项目参考图(references/),登记为参考素材(origin=downloaded),供「资产图」阶段用图生图(generate_asset_from_reference)派生新素材。常用于把 web_search(type=image) 搜到的参考图(老电话/手机型号/服装等)落地。仅 http/https,下载会被 SSRF/大小/类型校验拦截。', parameters: { type: 'object', properties: { url: { type: 'string', description: '图片 URL(http/https)' }, name: { type: 'string', description: '参考图名称,如「诺基亚3310老手机」;缺省取 URL 文件名' }, category: { type: 'string', enum: ASSET_CATEGORY_IDS, description: '素材分类,默认 prop' }, description: { type: 'string', description: '参考图用途/内容描述' } }, required: ['url'] } } },
- { type: 'function', function: { name: 'opuscar_init', description: '初始化 lemo-opuscar 代码电影库:确认库根存在、创建影片工作区目录,返回 { lib_root, film_dir } 两个绝对路径(后续 opuscar_shell 的 cwd 与命令里的路径都要以这两个目录为界)。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'opuscar_shell', description: '在 lemo-opuscar 库根或影片工作区执行一条受控 shell 命令(渲染/合成/TTS 等)。cwd 只能 lib(库根,默认)或 film(影片工作区)。命令里的绝对路径必须落在 lib_root / film_dir 之内;危险命令(rm -rf / sudo / curl|sh 等)会被拦截。返回 { code, stdout, stderr }。可用 $LEMO_FILM 与 $LEMO_LIB 引用两个目录。', parameters: { type: 'object', properties: { command: { type: 'string', description: '要执行的命令,如 node core/render/video.mjs "$LEMO_FILM" --out "$LEMO_FILM/out/video.mp4"' }, cwd: { type: 'string', enum: ['lib', 'film'], description: '工作目录:lib=库根(默认),film=影片工作区' } }, required: ['command'] } } },
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 64 on GitHub
- { type: 'function', function: { name: 'opuscar_write_file', description: '向影片工作区写一个文本文件(TREATMENT.md / index.html / build.sh / content.json / lines.json 等)。path 为相对 film_dir 的路径。', parameters: { type: 'object', properties: { path: { type: 'string', description: '相对影片工作区(film_dir)的文件路径' }, content: { type: 'string', description: '文件完整内容' } }, required: ['path', 'content'] } } },
- { type: 'function', function: { name: 'opuscar_read_file', description: '读取 lemo-opuscar 库内或影片工作区内的文本文件(如 AGENTS.md、styles/<slug>/STYLE.md、DIRECTOR.md、TECHNIQUE.md、core/README.md、TREATMENT.md、index.html)。path 为相对路径:优先在库根下解析,其次在影片工作区下解析。', parameters: { type: 'object', properties: { path: { type: 'string', description: '相对库根或影片工作区的文件路径' } }, required: ['path'] } } },
- { type: 'function', function: { name: 'opuscar_save_film', description: '把影片工作区产出的成片(默认查找 film_dir/out/final.mp4、film_dir/out/video.mp4 等)复制为项目视频资产并置 done,供前端预览/下载。', parameters: { type: 'object', properties: { name: { type: 'string', description: '可选,成片显示名(缺省用资产名)' } }, required: [] } } },
- // —— 无限・卷轴:小说大纲规划工具 ——
- { type: 'function', function: { name: 'novel_init', description: '初始化小说工作台(无限・卷轴):确认项目存在、确保 novel/ 目录与 memory/ 子目录已创建,返回当前小说目录下的结构概览(已存在的总纲/卷纲/章纲、角色数量、记忆文件列表)。调用 novel_* 工具前应先调用一次。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'novel_write_file', description: '向小说工作台写一个文本文件。path 为相对 novel/ 的路径(如 总纲.md、memory/设定.md);路径禁止绝对路径与 "../"。', parameters: { type: 'object', properties: { path: { type: 'string', description: '相对 novel/ 目录的路径,如 总纲.md、memory/设定.md' }, content: { type: 'string', description: '文件完整内容' } }, required: ['path', 'content'] } } },
- { type: 'function', function: { name: 'novel_read_file', description: '读取小说工作台下的文本文件。path 为相对 novel/ 的路径(如 总纲.md、卷纲.md、章纲.md、memory/设定.md)。不存在返回空字符串。', parameters: { type: 'object', properties: { path: { type: 'string', description: '相对 novel/ 目录的路径' } }, required: ['path'] } } },
- { type: 'function', function: { name: 'novel_list_files', description: '递归列出 novel/ 目录下所有已存在文件(用于检查哪些层已经生成、哪些层还是空的)。返回形如 ["总纲.md","卷纲.md","memory/设定.md"]。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'novel_save_characters', description: '把角色列表写入 characters.json。characters 必须是数组,每项形如 { id, name, role, description, notes }。id 可省(空字符串即可);name / role / description 建议填。', parameters: { type: 'object', properties: { characters: { type: 'array', items: { type: 'object', properties: { id: { type: 'string' }, name: { type: 'string' }, role: { type: 'string' }, description: { type: 'string' }, notes: { type: 'string' } } } } }, required: ['characters'] } } },
- { type: 'function', function: { name: 'novel_get_characters', description: '读取当前小说的角色列表(从 characters.json)。返回数组;不存在或解析失败返回空数组。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'novel_list_chapters', description: '列出当前小说已建立的章节(含标题、卷号、序号、本章章纲、正文字数、是否已有正文)。用于判断哪些章节还没写正文、从哪里开始续写。返回 [{ title, seq, volume, outline, wordCount, hasContent }] 数组。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'novel_save_chapter', description: '保存/更新某一章(标题、所属卷号、本章章纲、正文)。title 为章节标题;volume 为该章所属卷号(从 1 开始);outline 为本章章纲(这一章要写什么);content 为本章正文。只更新章纲/卷号时请省略 content(省略=不改正文,避免把已写正文清空);传非空 content 才覆盖正文。标题已存在则更新,不存在则新建。', parameters: { type: 'object', properties: { title: { type: 'string', description: '章节标题,如「第1章 意外穿越」' }, volume: { type: 'integer', description: '所属卷号,从 1 开始' }, outline: { type: 'string', description: '本章章纲(这一章要写什么)' }, content: { type: 'string', description: '本章完整正文;只更新章纲/卷号时省略该参数' } }, required: ['title'] } } },
- { type: 'function', function: { name: 'novel_save_volumes', description: '保存结构化的分卷列表(覆盖写入 volumes.json)。每卷含:seq(卷号,从1开始)、title(卷名)、outline(本卷卷纲:这一卷要写什么/核心目标/卷末变化)、chapterFrom(起始章序号)、chapterTo(结束章序号)。用于把「第几章到第几章为一卷」以及每卷的卷纲绑定到卷上。', parameters: { type: 'object', properties: { volumes: { type: 'array', items: { type: 'object', properties: { seq: { type: 'integer', description: '卷号,从 1 开始' }, title: { type: 'string', description: '卷名,如「第一卷 山门」' }, outline: { type: 'string', description: '本卷卷纲:这一卷要写什么、核心目标、主要冲突、卷末变化' }, chapterFrom: { type: 'integer', description: '本卷起始章序号' }, chapterTo: { type: 'integer', description: '本卷结束章序号' } }, required: ['seq'] } } }, required: ['volumes'] } } },
- { type: 'function', function: { name: 'novel_get_volumes', description: '读取当前小说的结构化分卷列表(从 volumes.json)。返回 [{ seq, title, outline, chapterFrom, chapterTo }];不存在返回空数组。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'novel_get_memory', description: '读取当前小说的全部上下文记忆(memory/ 目录下所有文件),返回 [{ name, content }]。写每一章前用它读最新记忆,保证人物状态/伏笔/剧情进展不前后矛盾。', parameters: { type: 'object', properties: {}, required: [] } } },
- { type: 'function', function: { name: 'novel_save_memory', description: '写入/覆盖一个记忆文件。name 为记忆名(如 设定、伏笔、剧情进展;可带 .md 后缀或 memory/ 前缀,会自动规范到 memory/ 目录);content 为该记忆的完整最新内容。写每章后用它更新剧情进展/伏笔/人物状态。', parameters: { type: 'object', properties: { name: { type: 'string', description: '记忆名,如 设定、伏笔、剧情进展' }, content: { type: 'string', description: '该记忆的完整最新内容' } }, required: ['name', 'content'] } } },
- ];
- // 封闭参数白名单:从 TOOL_DEFINITIONS 的 parameters.properties 派生每个工具的顶层参数键。
- // 对齐「未知字段=硬错误」原则:模型幻觉出多余字段时直接拒绝,避免「看似成功实则写错字段」。
- // 工具 schema 是唯一权威来源,不另维护一份清单,防止漂移。
- const ALLOWED_ARG_KEYS = new Map(
- TOOL_DEFINITIONS.map((t) => [t.function.name, new Set(Object.keys(t.function.parameters?.properties || {}))])
- );
- // ================= 运行时上下文 =================
- // 需要拉起外部进程(ComfyUI / ffmpeg)的渲染类工具。
- // 本机 LLM 与 ComfyUI 无法同时常驻(27B GGUF 15.66GB 与 H3 出图峰值叠加会爆显存),
- // 故「只跑 LLM 文本」的阶段靠这张表在 runTool 层硬拦,见 runTool 的 renderDisabled 分支。
- export const RENDER_TOOLS = new Set([
- 'generate_asset_image', 'edit_asset_image', 'change_outfit', 'design_outfits',
- 'change_age', 'design_ages',
- 'generate_assets_batch', 'design_voice', 'generate_shot_video',
- 'generate_asset_from_reference',
- 'regenerate_shot', 'generate_chapter_videos', 'assemble_video',
- 'generate_music', 'generate_music_asset', 'apply_chapter_music',
- 'generate_video_asset', 'clone_voice', 'generate_digital_human',
- ]);
- // 走 generate_assets_batch 文生图的资产类别。服装走 change_outfit/design_outfits(图生图),
- // 不在此列 —— stages.pendingByStage 复用本常量,保证「待办数」与「实际会做什么」永远一致。
- export const IMAGE_ASSET_CATEGORIES = ['character', 'scene', 'prop', 'other'];
- // Qwen-Image 2.1 / Krea2 文生图工作流:生成「人物素材」时需强制注入统一构图约束(见 CHARACTER_T2I_LAYOUT_CONSTRAINT)
- const CHARACTER_T2I_WORKFLOWS = new Set(['krea2_hyperreal_t2i', 'qwen_image_2_1_t2i_api', 'qwen_image_2_1_t2i_gguf', 'qwen_image_2_1_t2i_gguf_q4']);
- export function createToolRuntime({ projectId, jobId, onProgress, isAborted, chapter, renderDisabled, llmDisabled, assetId }) {
- const cfg = loadConfig();
- const project = Projects.get(projectId);
- if (!project) throw new Error('项目不存在:' + projectId);
- ensureProjectDirs(projectId);
- return {
- cfg, project, projectId, jobId,
- chapter: chapter || '',
- assetId: assetId || '',
- renderDisabled: !!renderDisabled,
- // 与 renderDisabled 对称:渲染阶段 / 纯渲染任务置 true → 禁止调用 LLM。
- // LLM 与 ComfyUI 单卡不能同时常驻(见 stages.js 设计说明),故换装/年龄的视觉精修、
- // 视频提示词 LLM 改写等可选 LLM 步骤在此下跳过或直接拒绝。
- llmDisabled: !!llmDisabled,
- onProgress: onProgress || (() => {}),
- isAborted: isAborted || (() => false),
- report(patch) {
- if (this.onProgress) this.onProgress(patch);
- logger.info('agent: ' + (patch.phase || '') + ' ' + (patch.detail || ''), patch);
- },
- };
- }
- // ================= 内部辅助 =================
- function saveToProject(ctx, relPath, buf) {
- const abs = resolveProjectPath(ctx.projectId, relPath);
- if (!abs) throw new Error('非法保存路径:' + relPath);
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, buf);
- return relPath;
- }
- async function downloadOutputTo(ctx, out, relPath) {
- const abs = resolveProjectPath(ctx.projectId, relPath);
- if (!abs) throw new Error('非法输出路径:' + relPath);
- return downloadToFile(ctx.cfg, out, abs);
- }
- function assetFallback(asset, project) {
- return fallbackAssetPrompt({ type: asset.category, name: asset.name, description: asset.description, style: project.style });
- }
- // 新文字策略:素材允许保留与主体相关的真实文字(包装/标签/招牌/书名/品牌 logo 等)。
- // 历史资产里由旧模板写下的负向词条(text / letters / logo …)会继续把字擦掉,而负向提示词
- // 没有前端编辑入口,所以在提交渲染前统一剔除这些词条;其余负向词条原样保留。
- const LEGACY_TEXT_NEG_TOKENS = new Set(['text', 'subtitles', 'subtitle', 'caption', 'captions', 'letter', 'letters', 'word', 'words', 'text overlay', 'signature', 'logo']);
- function sanitizeNegativePrompt(neg) {
- if (!neg) return '';
- return String(neg)
- .split(',')
- .map((t) => t.trim())
- .filter(Boolean)
- .filter((t) => !LEGACY_TEXT_NEG_TOKENS.has(t.toLowerCase()))
- .join(', ');
- }
- export function visionEnabled(ctx) { return !!(ctx.cfg?.llm?.vision); }
- // 把本地图片绝对路径列表转成 { data, mimeType } 图片块(视觉模型投喂),跳过不可读/超大文件
- // 视觉投喂的参考图做限流:默认最多 6 张、单张 ≤2.5MB,避免大量超大图把对话上下文撑爆,
- // 进而触发 openclaude 的 active-message 安全上限(自动压缩压不动时直接停跑)。
- function imagesFromPaths(absPaths, max = 6) {
- const out = [];
- for (const p of (absPaths || [])) {
- if (out.length >= max) break;
- if (!p) continue;
- const img = imageToDataUrl(p, { maxBytes: 2.5 * 1024 * 1024 });
- if (img) out.push(img);
- }
- return out;
- }
- // 超时预算按本机实测吞吐给:视频单条 15-30 分钟,且 ComfyUI 队列串行,
- // 超时必须覆盖排队等待,否则产物已生成却无人回收。
- // 关闭「多用户排队调度」(单人自用)时不设生成超时:渲染再慢也一直等,
- // 只能由「停止」或 ComfyUI 任务丢失检测结束,避免正常出片被固定时长误杀。
- const QUEUE_SCHEDULING_OFF = (cfg) => cfg?.generation?.queue?.enabled === false;
- const IMG_TIMEOUT = (cfg) => (QUEUE_SCHEDULING_OFF(cfg) ? 0 : (Number(cfg?.generation?.imageTimeoutMinutes) || 30) * 60 * 1000);
- const VID_TIMEOUT = (cfg) => (QUEUE_SCHEDULING_OFF(cfg) ? 0 : (Number(cfg?.generation?.videoTimeoutMinutes) || 120) * 60 * 1000);
- // ================= 工具处理函数 =================
- // 章节进度摘要(列表里带 shotCount/doneCount/genStatus)统一走 lib/core 的 chapterStats:
- // 界面路由 GET /api/projects/:id/chapters 用的是同一份,避免「生成中」判定这种口径再各写一遍。
- // 章节收敛:ctx.chapter 可能是标题或 id;无目标(全部章节)返回 null。
- // 用于 get_project / list_chapters / list_shots 按目标章过滤,避免「每章一个会话」里仍返回
- // 全项目的章节正文与全部分镜,导致上下文随总章节数无界膨胀(15 集左右写视频提示词开始空/截断的根因)。
- function targetChapterTitle(ctx) {
- const want = String(ctx.chapter || '').trim();
- if (!want) return '';
- const c = Chapters.list(ctx.projectId).find((c) => c.title === want || c.id === want);
- return c ? c.title : want;
- }
- // 章节正文长度上限:与 buildTaskPrompt 的 .slice(0, 6000) 对齐,避免超长小说正文反复整段进上下文。
- const NOVEL_CAP = 6000;
- async function hGetProject(ctx) {
- const assets = Assets.list(ctx.projectId);
- const shots = Shots.list(ctx.projectId);
- const target = targetChapterTitle(ctx);
- const chapters = Chapters.list(ctx.projectId)
- .filter((c) => !target || c.title === target)
- .map((c) => { const st = chapterStats(ctx.projectId, c.title); return { id: c.id, title: c.title, seq: c.seq, status: c.status, novel: String(c.novel || '').slice(0, NOVEL_CAP), hasScript: !!String(c.script || '').trim(), scriptChars: String(c.script || '').length, shotCount: st.total, doneCount: st.done, genStatus: st.status }; });
- const shotList = target ? shots.filter((s) => s.chapter === target) : shots;
- return JSON.stringify({
- project: { id: ctx.project.id, name: ctx.project.name, style: ctx.project.style, video_resolution: ctx.project.video_resolution, video_aspect_ratio: ctx.project.video_aspect_ratio, enable_bgm: ctx.project.enable_bgm !== false },
- context: ctx.project.context || {},
- chapters,
- assets: assets.map((a) => ({ id: a.id, category: a.category, name: a.name, image_path: a.image_path, voice_ref: a.voice_ref, voice_desc: a.voice_desc, parent_id: a.parent_id || '', source: a.source || '', status: a.status })),
- shots: shotList.map((s) => ({ id: s.id, idx: s.idx, chapter: s.chapter || '', scene_name: s.scene_name, status: s.status, has_prompt: !!(s.video_prompt && String(s.video_prompt).trim()), video_path: s.video_path })),
- });
- }
- async function hListChapters(ctx) {
- const target = targetChapterTitle(ctx);
- return JSON.stringify(Chapters.list(ctx.projectId)
- .filter((c) => !target || c.title === target)
- .map((c) => { const st = chapterStats(ctx.projectId, c.title); return { id: c.id, title: c.title, seq: c.seq, status: c.status, novel: String(c.novel || '').slice(0, NOVEL_CAP), hasScript: !!String(c.script || '').trim(), scriptChars: String(c.script || '').length, shotCount: st.total, doneCount: st.done, genStatus: st.status }; }));
- }
- // 章节解析:标题或 id 都认(get_chapter / set_chapter_script 共用;与 set_storyboard 同口径)。
- function resolveChapterRef(ctx, raw) {
- const chs = Chapters.list(ctx.projectId);
- const want = String(raw == null ? '' : raw).trim() || String(ctx.chapter || '').trim();
- if (!want) throw new Error('缺少 chapter:请传章节标题或 id(可用 list_chapters 查看本项目章节)');
- const hit = chs.find((c) => c.title === want || c.id === want);
- if (!hit) throw new Error('章节不存在:' + want + '(本项目现有章节:' + chs.map((c) => c.title).join('、') + ')');
- return hit;
- }
- async function hGetChapter(ctx, args) {
- const c = resolveChapterRef(ctx, args.chapter);
- return JSON.stringify({ id: c.id, title: c.title, seq: c.seq, novel: c.novel || '', script: c.script || '' });
- }
- async function hSetChapterScript(ctx, args) {
- const c = resolveChapterRef(ctx, args.chapter);
- const script = String(args.script == null ? '' : args.script).trim();
- if (!script) throw new Error('剧本不能为空');
- const existing = String(c.script || '').trim();
- // 已有剧本是用户/AI 已确认的剧情蓝本:默认拒绝覆盖,避免流水线重跑把用户手改稿吞掉。
- if (existing && args.overwrite !== true) {
- throw new Error('本章已有剧本(' + existing.length + ' 字),请直接按现有剧本拆分镜;仅当用户明确要求重写剧本时才传 overwrite:true');
- }
- Chapters.update(c.id, { script });
- if (ctx.report) ctx.report({ phase: '剧本', detail: '已写入「' + c.title + '」剧本(' + script.length + ' 字)' });
- return JSON.stringify({ chapter: c.title, chars: script.length, overwritten: !!existing });
- }
- async function hSaveContext(ctx, args) {
- // key 值域与工具 schema 的 enum、以及 PUT /api/projects/:id/context 的 400 口径一致。
- // 不校验的话:key='bible2' 之类会当 style.md 落盘(写坏风格指南文件),DB 里却多出一个野键。
- if (!CONTEXT_KEYS.includes(args.key)) {
- throw new Error('key 只能是 ' + CONTEXT_KEYS.join('/') + '(当前:' + args.key + ')');
- }
- const dir = path.join(projectDir(ctx.projectId), 'context');
- fs.mkdirSync(dir, { recursive: true });
- if (args.key === 'continuity') {
- const f = path.join(dir, 'continuity.json');
- let arr = [];
- try { arr = JSON.parse(fs.readFileSync(f, 'utf8')); } catch {}
- // 文件可能是被手改坏的非数组 JSON:直接 push 会抛 TypeError,整次写入失败。
- // 与路由侧(context/route.js)一致,非数组一律当空列表重来。
- if (!Array.isArray(arr)) arr = [];
- arr.push({ t: Date.now(), content: args.content });
- fs.writeFileSync(f, JSON.stringify(arr, null, 2));
- } else {
- const f = path.join(dir, args.key === 'bible' ? 'bible.md' : 'style.md');
- fs.writeFileSync(f, args.content);
- }
- // 多章节并行时,各 Agent 手里的 ctx.project.context 可能是旧快照。
- // 只合并本次写入的 key,避免整段覆盖掉另一章刚写的 bible/style/continuity。
- const fresh = Projects.setContextKey(ctx.projectId, args.key, args.content);
- if (fresh) ctx.project.context = fresh;
- return '已保存上下文:' + args.key;
- }
- async function hLoadSkill(ctx, args) {
- const name = args.name;
- const skill = loadSkillWithResources(name);
- if (!skill) throw new Error('技能不存在:' + name);
- const NL = String.fromCharCode(10);
- const parts = [renderSkillContent(skill)];
- if (skill.references && skill.references.length) {
- parts.push('【技能参考文件索引】需要某个文件全文时,调用 skill_reference(name="' + name + '", ref="<文件名>"):');
- for (const r of skill.references) {
- const preview = String(r.content || '').slice(0, 160).replace(/\s+/g, ' ');
- parts.push('- ' + r.name + '(约 ' + r.content.length + ' 字)' + (preview ? ':' + preview : ''));
- }
- }
- const content = parts.join(NL + NL);
- return content.length > 120000 ? content.slice(0, 120000) + '…(截断)' : content;
- }
- async function hSkillReference(ctx, args) {
- const skill = loadSkillWithResources(args.name);
- if (!skill) throw new Error('技能不存在:' + args.name);
- const refs = skill.references || [];
- const ref = refs.find((r) => r.name === args.ref);
- if (!ref) throw new Error('参考文件不存在:' + args.ref + '。可用:' + refs.map((r) => r.name).join(', '));
- const content = String(ref.content || '');
- return content.length > 120000 ? content.slice(0, 120000) + '…(截断)' : content;
- }
- async function hReport(ctx, args) {
- ctx.report({ phase: args.phase || '', detail: args.detail || '' });
- return '已汇报';
- }
- async function hListAssets(ctx, args) {
- const assets = Assets.list(ctx.projectId, args.category);
- // 必须带上 prompt / prompt_used:LLM 看不到用户已保存的提示词,就会以为自己才是第一个写的人,
- // 用 update_asset 把用户的提示词覆盖掉(「保存了提示词却不生效」的一大来源)。
- return JSON.stringify(assets.map((a) => ({
- id: a.id, category: a.category, name: a.name, description: a.description, voice_desc: a.voice_desc,
- prompt: a.prompt || '', prompt_used: a.prompt_used || '', prompt_locked: a.prompt_locked ? 1 : 0,
- image_path: a.image_path, voice_ref: a.voice_ref, parent_id: a.parent_id || '', source: a.source || '', status: a.status,
- })));
- }
- // 资产写入前的 parent_id 统一校验(Agent 工具侧):
- // 变体(服装/年龄):必须用 parent_id 指向本项目的角色素材。refs.js 只按 parent_id 把变体映射到
- // 角色(镜头里有该角色时才拿它替换角色参考图),缺父/父不是角色的变体在生成阶段被完全忽略,
- // 却照样出现在素材库与分镜引用列表里 —— 用户以为绑上了、分镜也「更新成功」,实际静默无效。
- // db 层 Assets.create 会抛 BAD_VARIANT_PARENT,但那是「模型看不懂的 DB 错误」,这里给出可读指引,
- // 把 LLM 引导到只干这件事的专用工具(change_outfit / design_outfits / change_age / design_ages)。
- // 非变体分类:parent_id 无意义(只会让 Assets.remove 把它当子变体级联删、usageOf 把它计成 children),
- // 传了就直接拒绝,绝不静默丢弃(静默丢弃 = 模型以为写成功,是同一类坑)。
- function resolveAssetParent(ctx, category, parentId) {
- const pid = String(parentId || '').trim();
- if (!isVariantAssetCategory(category)) {
- if (pid) throw new Error('parent_id 只能用于服装(costume)/年龄(age)变体;' + category + ' 不挂在其它素材下,请去掉 parent_id');
- return '';
- }
- const parent = pid ? Assets.get(pid) : null;
- if (!parent || parent.project_id !== ctx.projectId || parent.category !== 'character') {
- const hint = category === 'costume'
- ? '生成服装建议改用 change_outfit / design_outfits(会以角色 canonical 图为参考出图)'
- : '生成年龄变体建议改用 change_age / design_ages(会以角色 canonical 图为参考出图)';
- throw new Error('服装/年龄变体必须用 parent_id 绑定到本项目的一个角色(character)资产;' + hint);
- }
- return pid;
- }
- async function hCreateAsset(ctx, args) {
- const parentId = resolveAssetParent(ctx, args.category, args.parent_id);
- const isVariant = isVariantAssetCategory(args.category);
- // 幂等:同分类+同名资产已存在则复用,避免续跑时重复建。
- // 变体(服装/年龄)还要按 parent_id 区分:同一套「旧衣」可能是不同角色各自的,
- // 只按 name 复用会把 A 角色的服装错算成 B 角色的(refs.js 按 parent_id 映射,挂到别的角色上)。
- const existing = Assets.list(ctx.projectId, args.category).find((a) => a.name === args.name && (!isVariant || (a.parent_id || '') === parentId));
- if (existing) {
- // 续跑复用:此前没写声音画像而这次提供了,补上(否则设计音色仍会性别错乱)
- if (existing.category === 'character' && args.voice_desc && !(existing.voice_desc || '').trim()) {
- Assets.update(existing.id, { voice_desc: args.voice_desc });
- logger.info('续跑资产补 voice_desc:' + existing.name);
- }
- return JSON.stringify({ id: existing.id, category: existing.category, name: existing.name, parent_id: existing.parent_id || '', reused: true, status: existing.status, image_path: existing.image_path });
- }
- const a = Assets.create(ctx.projectId, { category: args.category, name: args.name, description: args.description || '', voice_desc: args.voice_desc || '', parent_id: parentId });
- return JSON.stringify({ id: a.id, category: a.category, name: a.name, parent_id: a.parent_id || '', voice_desc: a.voice_desc });
- }
- // 用户在前端「素材库」手动保存过的提示词(prompt_locked=1)是权威,LLM 不得覆盖:
- // 否则用户改完提示词、再跑一次 LLM 阶段,提示词就被 LLM 重写回去了(用户看到的现象就是「改了不生效」)。
- // 想把提示词交回给 LLM 改写,只需在素材库里把提示词清空保存(清空即解锁)。
- export function keepsUserPrompt(asset) {
- return !!(asset && asset.prompt_locked && String(asset.prompt || '').trim());
- }
- async function hUpdateAsset(ctx, args) {
- const patch = {};
- for (const k of ['name', 'description', 'voice_desc', 'prompt', 'negative_prompt', 'voice_ref', 'consistency_key']) {
- if (args[k] != null) patch[k] = args[k];
- }
- const asset = Assets.get(args.id);
- if (!asset || asset.project_id !== ctx.projectId) throw new Error('资产不存在:' + args.id);
- let keptPrompt = false;
- const imgBusy = Queue.activeByDedupe('asset:' + asset.id);
- const voiceBusy = Queue.activeByDedupe('voice:' + asset.id);
- const deferred = [];
- // 正在渲染时不要改输入:否则出来的图/音色对应的是旧提示词,下一阶段又会重做一遍。
- if (patch.prompt != null && imgBusy) { delete patch.prompt; deferred.push('prompt'); }
- if (patch.voice_desc != null && voiceBusy) { delete patch.voice_desc; deferred.push('voice_desc'); }
- if (patch.prompt != null && keepsUserPrompt(asset) && String(patch.prompt) !== String(asset.prompt)) {
- delete patch.prompt;
- keptPrompt = true;
- }
- Assets.update(args.id, patch);
- if (deferred.length) {
- return '已更新资产 ' + args.id + '(' + deferred.join('/') + ' 正在渲染,本次未改动;请等渲染结束后再更新,避免成品与提示词不一致)';
- }
- return keptPrompt
- ? ('已更新资产 ' + args.id + '(提示词保持用户手写版本不变:素材库里手动保存的提示词优先于 LLM;如需让 LLM 改写,请在素材库把该资产的提示词清空保存)')
- : ('已更新资产 ' + args.id);
- }
- // 其他章节正在渲染同一素材时,等待它完成,而不是立刻跳过:
- // 跳过会让本批以为素材已就绪,后续视频阶段又因缺图失败/重试。最多等到队列超时。
- async function waitForActiveRender(dedupeKey, isAborted, maxMs = 30 * 60 * 1000) {
- const start = Date.now();
- while (Date.now() - start < maxMs) {
- if (isAborted && isAborted()) throw new Error('任务已停止(等待其他任务完成渲染)');
- if (!Queue.activeByDedupe(dedupeKey)) return true;
- await new Promise((r) => setTimeout(r, 1000));
- }
- return false;
- }
- function assetImageReady(asset) {
- return !!(asset && asset.image_path && asset.status === 'done' && (asset.prompt_used || '') === (asset.prompt || ''));
- }
- async function hGenerateAssetImage(ctx, args) {
- let asset = Assets.get(args.asset_id);
- if (!asset || asset.project_id !== ctx.projectId) throw new Error('资产不存在');
- const dedupeKey = 'asset:' + asset.id;
- if (Queue.activeByDedupe(dedupeKey)) {
- if (!(await waitForActiveRender(dedupeKey, ctx.isAborted))) throw new Error('等待其他任务完成该素材渲染超时');
- asset = Assets.get(asset.id) || asset;
- if (assetImageReady(asset)) {
- return JSON.stringify({ asset_id: asset.id, skipped: true, reason: '其他任务已完成该素材生成' });
- }
- }
- const fb = assetFallback(asset, ctx.project);
- // 资产自身的提示词优先(用户编辑过 / LLM 阶段写过的,都应盖过调用方这次的临时 prompt),args.prompt 仅作兜底
- const prompt = asset.prompt || args.prompt || fb.prompt;
- const negative_prompt = sanitizeNegativePrompt(asset.negative_prompt || args.negative_prompt || fb.negative_prompt);
- // 按资产类型选合适尺寸:人物三视图/场景用 16:9,道具白底用 1:1,其余默认 16:9;可用参数 args.ratio 覆盖
- const RATIO_BY_CATEGORY = { character: '16:9', scene: '16:9', prop: '1:1', other: '16:9' };
- const ratio = args.ratio || RATIO_BY_CATEGORY[asset.category] || '16:9';
- const [w, h] = ratioToSize(ratio);
- const spec = getSpecForKind(ctx.cfg, 't2i');
- // Qwen-Image 2.1 / Krea2 文生图生成「人物素材」时,强制注入统一构图约束(白底 + 左1/3面部特写 + 右2/3三视图)
- const positive_prompt = asset.category === 'character' && CHARACTER_T2I_WORKFLOWS.has(spec.id) && !prompt.includes('左侧1/3')
- ? prompt + '\n' + CHARACTER_T2I_LAYOUT_CONSTRAINT
- : prompt;
- const prefix = 'assets/' + slugify(asset.name) + '_' + uid().slice(0, 8);
- const prevImage = asset.image_path || '';
- const restoreAsset = (error = '') => Assets.update(asset.id, { status: prevImage ? 'done' : 'failed', error });
- ctx.report({ phase: '资产生成', detail: '文生图:' + asset.name });
- Assets.update(asset.id, { status: 'generating' });
- let outputs;
- for (let attempt = 0; attempt < 2; attempt++) {
- try {
- ({ outputs } = await runWorkflow(ctx.cfg, spec, {
- positive_prompt, negative_prompt, width: w, height: h, seed: randomSeed(), filename_prefix: prefix,
- }, { timeoutMs: IMG_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, jobId: ctx.jobId, projectId: ctx.projectId, chapter: '', subject: asset.name || asset.id, dedupeKey, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } }));
- break;
- } catch (e) {
- // 流水线 / 手动入口并发提交同一资产:等先到的任务完成;若已完成则跳过,不重复扣费。
- if (e && e.code === 'DUPLICATE_RENDER' && attempt === 0) {
- const ok = await waitForActiveRender(dedupeKey, ctx.isAborted);
- if (!ok) { restoreAsset('等待其他任务完成该素材渲染超时'); throw new Error('等待其他任务完成该素材渲染超时'); }
- const fresh = Assets.get(asset.id);
- if (assetImageReady(fresh)) {
- Assets.update(asset.id, { status: 'done', error: '' });
- return JSON.stringify({ asset_id: asset.id, skipped: true, reason: '其他任务已完成该素材生成' });
- }
- // 先到的任务失败/取消,或它生成后提示词又被改过:用本批的提示词再提交一次
- continue;
- }
- Assets.update(asset.id, { status: prevImage ? 'done' : 'failed', error: e.message });
- throw e;
- }
- }
- if (!outputs) { restoreAsset('资产生成未完成'); throw new Error('资产生成未完成'); }
- const img = pickOutput(outputs, 'images');
- if (!img) { restoreAsset('文生图工作流未返回图片'); throw new Error('文生图工作流未返回图片'); }
- const ext = path.extname(img.filename) || '.png';
- const relDir = 'assets/' + PROJECT_ASSET_SUBDIRS[asset.category] + '/';
- const relPath = relDir + slugify(asset.name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, img, relPath);
- Assets.update(asset.id, { image_path: relPath, source: 'generated', prompt, prompt_used: prompt, negative_prompt, status: 'done', error: '' });
- return JSON.stringify({ asset_id: asset.id, image_path: relPath });
- }
- // 复用:以参考图跑 Qwen-Image-Edit 图生图,返回产物 { img, ext }(调用方负责下载落盘)
- async function runI2iEdit(ctx, { refAbs, prompt, namePrefix, seed, dedupeKey }) {
- const refName = await uploadTaskInput(ctx.cfg, refAbs, 'ic_ref_' + ctx.projectId.slice(0, 8) + '_' + uid().slice(0, 8) + path.extname(refAbs));
- const spec = getSpecForKind(ctx.cfg, 'i2i');
- const prefix = namePrefix || ('assets/edit_' + uid().slice(0, 8));
- // 图生图没有负向提示词通道,文字只能靠正向指令保住:参考图上的文字/标签/包装信息默认保留,
- // 否则 Qwen-Image-Edit 会把产品包装、书封、招牌上的字当成噪声擦掉。
- const editPrompt = prompt + '\n参考图中已有的文字、标签、包装说明与 logo 保持原样(除非上面的指令明确要求改动),不要擦除或改写。';
- const { outputs } = await runWorkflow(ctx.cfg, spec, {
- positive_prompt: editPrompt, image: refName, seed: seed ?? randomSeed(), filename_prefix: prefix,
- }, { timeoutMs: IMG_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, jobId: ctx.jobId, projectId: ctx.projectId, dedupeKey, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } });
- const img = pickOutput(outputs, 'images');
- if (!img) throw new Error('图生图工作流未返回图片');
- return { img, ext: path.extname(img.filename) || '.png' };
- }
- async function hEditAssetImage(ctx, args) {
- const asset = Assets.get(args.asset_id);
- if (!asset || asset.project_id !== ctx.projectId) throw new Error('资产不存在');
- let refAbs;
- if (args.reference_image_path) {
- refAbs = resolveProjectPath(ctx.projectId, args.reference_image_path);
- } else {
- const refAsset = args.reference_asset_id ? Assets.get(args.reference_asset_id) : asset;
- // 参考资产必须属于本项目:跨项目 id 在下面按本项目路径解析,会指向本项目里的同名相对路径
- // (两个项目的 assets/character/xxx.png 都可能存在),等于拿错图当参考。
- if (!refAsset || refAsset.project_id !== ctx.projectId) throw new Error('参考资产不存在');
- refAbs = resolveProjectPath(ctx.projectId, refAsset.image_path);
- }
- if (!refAbs || !fs.existsSync(refAbs)) throw new Error('参考图不存在,请先生成/上传参考图');
- const fb = assetFallback(asset, ctx.project);
- // 资产自身的提示词优先(用户编辑过 / LLM 阶段写过的,都应盖过调用方这次的临时 prompt),args.prompt 仅作兜底
- const prompt = asset.prompt || args.prompt || fb.prompt;
- ctx.report({ phase: '资产生成', detail: '图生图:' + asset.name });
- const { img, ext } = await runI2iEdit(ctx, { refAbs, prompt, namePrefix: 'assets/' + slugify(asset.name) + '_edit_' + uid().slice(0, 8), dedupeKey: 'asset:' + asset.id });
- const relDir = 'assets/' + PROJECT_ASSET_SUBDIRS[asset.category] + '/';
- const relPath = relDir + slugify(asset.name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, img, relPath);
- // 追加版本,仍以最新为准
- const versions = [...(asset.versions || []), asset.image_path].filter(Boolean);
- Assets.update(asset.id, { image_path: relPath, source: 'generated', prompt, prompt_used: prompt, versions, status: 'done', error: '' });
- return JSON.stringify({ asset_id: asset.id, image_path: relPath });
- }
- // 变体(换装 / 年龄)是否可以直接复用已有图。
- // 复用条件必须包含「内容与提示词都没被改过」:用户可能在前端把变体的提示词改了并保存,
- // 这时 prompt ≠ prompt_used —— 直接复用旧图等于把用户的修改吞掉(就是「改了提示词不生效」)。
- export function variantReusable(existing, description, explicitPrompt) {
- if (!existing || !existing.image_path || existing.status !== 'done') return false;
- if (String(existing.description || '') !== String(description || '')) return false;
- if (String(existing.prompt || '') !== String(existing.prompt_used || '')) return false;
- if (explicitPrompt != null && String(existing.prompt || '') !== String(explicitPrompt)) return false;
- return true;
- }
- // 变体出图用的提示词:调用方显式给的 > 资产里被改过的(用户手改的优先)> 兜底/视觉精修。
- // 注意「被改过」= prompt ≠ prompt_used:只有这时资产自身的提示词才代表用户的新指令。
- export function variantPrompt(existing, explicitPrompt, fallback) {
- if (explicitPrompt != null && String(explicitPrompt).trim()) return String(explicitPrompt);
- const own = String((existing && existing.prompt) || '').trim();
- if (own && own !== String((existing && existing.prompt_used) || '')) return own;
- return fallback;
- }
- // 自动生成的 BGM 回写「背景音乐库」:同名资产复用(原地更新),否则每次重新生成都会新增一条
- // 同名资产——音乐库堆重复条目,audios 按名字映射时指向哪一条还取决于列表顺序。
- export function upsertMusicAsset(ctx, name, patch) {
- const dup = Assets.list(ctx.projectId, 'music').find((a) => a.name === name);
- const asset = dup || Assets.create(ctx.projectId, { category: 'music', name });
- Assets.update(asset.id, patch);
- return asset.id;
- }
- async function hChangeOutfit(ctx, args) {
- const char = Assets.get(args.character_id);
- if (!char || char.project_id !== ctx.projectId) throw new Error('角色资产不存在');
- if (char.category !== 'character') throw new Error('change_outfit 只能对角色(character)资产使用');
- const refAbs = resolveProjectPath(ctx.projectId, char.image_path);
- if (!refAbs || !fs.existsSync(refAbs)) throw new Error('角色参考图不存在,请先生成/上传角色 canonical 图');
- const outfit = String(args.outfit || '').trim();
- if (!outfit) throw new Error('请提供 outfit(服装描述)');
- const label = String(args.label || '').trim();
- const name = char.name + '-' + (label || outfit);
- // 同名变体(不限状态):内容/提示词改过就原地重做——既不新建重复资产,也不复用旧图吞掉修改。
- const existing = Assets.list(ctx.projectId, 'costume').find((a) => a.parent_id === char.id && a.name === name);
- if (variantReusable(existing, outfit, args.prompt)) {
- return JSON.stringify({ costume_id: existing.id, image_path: existing.image_path, parent_id: existing.parent_id, reused: true });
- }
- let prompt = variantPrompt(existing, args.prompt, '');
- if (!prompt) {
- const base = 'Keep the character identity, face, hairstyle, expression and art style exactly the same as the reference image; change only the clothing to: ' + outfit + '. Keep the pose and background unchanged.';
- // 视觉精修只要求「开了 vision 且配了 Base URL」:本地无鉴权的多模态端点(llama.cpp 等)
- // 本来就没有 api_key,卡 apiKey 会让这些用户的视觉精修永远静默降级。
- if (!ctx.llmDisabled && visionEnabled(ctx) && ctx.cfg.llm?.baseUrl) {
- try {
- const img = imageToDataUrl(refAbs);
- const dataUrls = img ? ['data:' + img.mimeType + ';base64,' + img.data] : [];
- const r = await llmChat(ctx.cfg.llm, [
- { role: 'system', content: '你是图生图(Qwen-Image-Edit)换装提示词专家。基于参考图与服装描述,输出一段英文编辑指令:保持角色身份/脸部/发型/画风一致,只更换服装;不要输出任何解释,只输出指令文本。' },
- buildVisionUserMessage('参考图如下。请为以下服装写英文图生图换装指令:' + outfit, dataUrls),
- ], { temperature: 0.5, maxTokens: 400 });
- prompt = (r.content || '').trim() || base;
- } catch (e) { logger.warn('换装视觉精修失败,用默认指令', { error: e.message }); prompt = base; }
- } else {
- prompt = base;
- }
- }
- ctx.report({ phase: '人物换装', detail: '为 ' + char.name + ' 生成服装「' + outfit + '」(图生图)' });
- const { img, ext } = await runI2iEdit(ctx, { refAbs, prompt, namePrefix: 'assets/costume_' + slugify(char.name) + '_' + uid().slice(0, 8), dedupeKey: 'outfit:' + char.id });
- const relPath = 'assets/' + PROJECT_ASSET_SUBDIRS.costume + '/' + slugify(name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, img, relPath);
- const costume = existing || Assets.create(ctx.projectId, { category: 'costume', name, description: outfit, prompt, parent_id: char.id });
- // prompt_used 必须落库(= 本次真正用于出图的提示词):批量/阶段判定「提示词是否改过」全靠它。
- Assets.update(costume.id, { image_path: relPath, source: 'generated', description: outfit, prompt, prompt_used: prompt, status: 'done', error: '' });
- return JSON.stringify({ costume_id: costume.id, image_path: relPath, parent_id: char.id, prompt });
- }
- // 一次性给角色设计并生成多套服装(衣橱):复用 change_outfit 的图生图换装,逐套生成服装资产
- async function hDesignOutfits(ctx, args) {
- const char = Assets.get(args.character_id);
- if (!char || char.project_id !== ctx.projectId) throw new Error('角色资产不存在');
- if (char.category !== 'character') throw new Error('design_outfits 只能对角色(character)资产使用');
- const outfits = Array.isArray(args.outfits) ? args.outfits : [];
- if (!outfits.length) throw new Error('请提供 outfits(该角色的多套服装清单)');
- // 依赖判定:服装变体是图生图,必须等父角色的 canonical 图完成,否则每一套都会失败。
- if (!(char.status === 'done' && char.image_path && fs.existsSync(resolveProjectPath(ctx.projectId, char.image_path)))) {
- return JSON.stringify({
- character_id: char.id, character_name: char.name,
- costumes: outfits.map((o) => ({ name: String((o && o.name) || ''), deferred: true })),
- note: '父角色 canonical 图尚未生成完成,服装变体暂缓:请先生成该角色图片',
- });
- }
- // 并发提交:真正限流的是 runWorkflow 的渲染槽位(RunningHub 按 runninghubConcurrency,
- // 本地 ComfyUI 恒为 1),这里一次性把整套服装排进队列即可。
- const results = await Promise.all(outfits.map(async (o) => {
- const name = String((o && o.name) || '').trim();
- const description = String((o && o.description) || name || '').trim();
- if (!description) return null;
- try {
- const r = await hChangeOutfit(ctx, { character_id: char.id, outfit: description, label: name });
- return { name: name || description, ...JSON.parse(r) };
- } catch (e) {
- logger.warn('design_outfits 单套生成失败:' + (name || description), { error: e.message });
- return { name: name || description, error: e.message };
- }
- }));
- const list = results.filter(Boolean);
- const okCount = list.filter((r) => !r.error).length;
- ctx.report({ phase: '人物换装', detail: '为 ' + char.name + ' 设计衣橱:生成 ' + okCount + '/' + outfits.length + ' 套服装' });
- return JSON.stringify({ character_id: char.id, character_name: char.name, costumes: list });
- }
- // 人物年龄变体:复用换装的图生图一致性思路,只把「换服装」改成「改年龄」。
- // 产出 category=age、parent_id 指向角色,供回忆/时间跳跃镜头按章引用。
- async function hChangeAge(ctx, args) {
- const char = Assets.get(args.character_id);
- if (!char || char.project_id !== ctx.projectId) throw new Error('角色资产不存在');
- if (char.category !== 'character') throw new Error('change_age 只能对角色(character)资产使用');
- const refAbs = resolveProjectPath(ctx.projectId, char.image_path);
- if (!refAbs || !fs.existsSync(refAbs)) throw new Error('角色参考图不存在,请先生成/上传角色 canonical 图');
- const age = String(args.age || '').trim();
- if (!age) throw new Error('请提供 age(年龄/时期描述)');
- const label = String(args.label || '').trim();
- const name = char.name + '-' + (label || age);
- // 同名变体(不限状态)优先;其次按描述精确匹配(避免旧数据命名不一致时重复生成)。
- // 不再用 name.includes(label) 这种模糊匹配 —— 它可能命中另一个变体,把改过的内容静默跳过。
- const ages = Assets.list(ctx.projectId, 'age').filter((a) => a.parent_id === char.id);
- const existing = ages.find((a) => a.name === name) || ages.find((a) => String(a.description || '') === age);
- if (variantReusable(existing, age, args.prompt)) {
- return JSON.stringify({ age_id: existing.id, image_path: existing.image_path, parent_id: existing.parent_id, reused: true });
- }
- let prompt = variantPrompt(existing, args.prompt, '');
- if (!prompt) {
- const base = 'Keep the character exactly the same species and identity as the reference image (a cat stays a cat, a human stays a human; never turn an animal into a human or a human into an animal). Keep the face, body structure, fur/feathers, hairstyle/fur pattern, and art style unchanged; change only the age/life stage to: ' + age + '. Keep the pose and outfit unchanged.';
- // 视觉精修只要求「开了 vision 且配了 Base URL」:本地无鉴权的多模态端点(llama.cpp 等)
- // 本来就没有 api_key,卡 apiKey 会让这些用户的视觉精修永远静默降级。
- if (!ctx.llmDisabled && visionEnabled(ctx) && ctx.cfg.llm?.baseUrl) {
- try {
- const img = imageToDataUrl(refAbs);
- const dataUrls = img ? ['data:' + img.mimeType + ';base64,' + img.data] : [];
- const r = await llmChat(ctx.cfg.llm, [
- { role: 'system', content: '你是图生图(Qwen-Image-Edit)年龄变体提示词专家。基于参考图与年龄描述,输出一段英文编辑指令:保持角色物种与身份一致(猫仍是猫、人仍是人,禁止把动物变成人或把人变成动物)、保持脸部/五官/发型/毛色/身体结构/画风一致,只改年龄/生命阶段;不要输出任何解释,只输出指令文本。' },
- buildVisionUserMessage('参考图如下。请为以下年龄/时期写英文图生图变体指令:' + age, dataUrls),
- ], { temperature: 0.5, maxTokens: 400 });
- prompt = (r.content || '').trim() || base;
- } catch (e) { logger.warn('年龄变体视觉精修失败,用默认指令', { error: e.message }); prompt = base; }
- } else {
- prompt = base;
- }
- }
- ctx.report({ phase: '人物年龄', detail: '为 ' + char.name + ' 生成年龄变体「' + age + '」(图生图)' });
- const { img, ext } = await runI2iEdit(ctx, { refAbs, prompt, namePrefix: 'assets/age_' + slugify(char.name) + '_' + uid().slice(0, 8), dedupeKey: 'age:' + char.id });
- const relPath = 'assets/' + PROJECT_ASSET_SUBDIRS.age + '/' + slugify(name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, img, relPath);
- const ageAsset = existing || Assets.create(ctx.projectId, { category: 'age', name, description: age, prompt, parent_id: char.id });
- Assets.update(ageAsset.id, { image_path: relPath, source: 'generated', description: age, prompt, prompt_used: prompt, status: 'done', error: '' });
- return JSON.stringify({ age_id: ageAsset.id, image_path: relPath, parent_id: char.id, prompt });
- }
- // 一次性给角色设计并生成多个时期/年龄变体:复用 change_age 的图生图变体,逐时期生成 age 资产
- async function hDesignAges(ctx, args) {
- const char = Assets.get(args.character_id);
- if (!char || char.project_id !== ctx.projectId) throw new Error('角色资产不存在');
- if (char.category !== 'character') throw new Error('design_ages 只能对角色(character)资产使用');
- const ages = Array.isArray(args.ages) ? args.ages : [];
- if (!ages.length) throw new Error('请提供 ages(该角色的多时期清单)');
- // 依赖判定:年龄变体同为图生图,必须等父角色 canonical 图完成。
- if (!(char.status === 'done' && char.image_path && fs.existsSync(resolveProjectPath(ctx.projectId, char.image_path)))) {
- return JSON.stringify({
- character_id: char.id, character_name: char.name,
- ages: ages.map((o) => ({ name: String((o && o.name) || ''), deferred: true })),
- note: '父角色 canonical 图尚未生成完成,年龄变体暂缓:请先生成该角色图片',
- });
- }
- const results = await Promise.all(ages.map(async (o) => {
- const name = String((o && o.name) || '').trim();
- const description = String((o && o.description) || name || '').trim();
- if (!description) return null;
- try {
- const r = await hChangeAge(ctx, { character_id: char.id, age: description, label: name });
- return { name: name || description, ...JSON.parse(r) };
- } catch (e) {
- logger.warn('design_ages 单时期生成失败:' + (name || description), { error: e.message });
- return { name: name || description, error: e.message };
- }
- }));
- const list = results.filter(Boolean);
- const okCount = list.filter((r) => !r.error).length;
- ctx.report({ phase: '人物年龄', detail: '为 ' + char.name + ' 设计年龄变体:生成 ' + okCount + '/' + ages.length + ' 个时期' });
- return JSON.stringify({ character_id: char.id, character_name: char.name, ages: list });
- }
- async function hViewAsset(ctx, args) {
- const a = Assets.get(args.asset_id);
- if (!a || a.project_id !== ctx.projectId) throw new Error('资产不存在');
- const text = JSON.stringify({ id: a.id, category: a.category, name: a.name, description: a.description, prompt: a.prompt || '', prompt_used: a.prompt_used || '', prompt_locked: a.prompt_locked ? 1 : 0, negative_prompt: a.negative_prompt || '', image_path: a.image_path, voice_desc: a.voice_desc || '', parent_id: a.parent_id || '', status: a.status });
- if (!visionEnabled(ctx)) return text + '(当前模型不支持图片输入,仅返回文本描述)';
- const abs = resolveProjectPath(ctx.projectId, a.image_path);
- const images = imagesFromPaths([abs], 1);
- return images.length ? { text, images } : text + '(该资产暂无参考图)';
- }
- async function hViewShotReferences(ctx, args) {
- const shot = Shots.get(args.shot_id);
- if (!shot || shot.project_id !== ctx.projectId) throw new Error('分镜不存在');
- const assets = Assets.list(ctx.projectId);
- const byId = (id) => assets.find((x) => x.id === id);
- const chars = (shot.character_ids || []).map(byId).filter(Boolean);
- const scenes = (shot.scene_ids || []).map(byId).filter(Boolean);
- const props = (shot.prop_ids || []).map(byId).filter(Boolean);
- const costumes = (shot.costume_ids || []).map(byId).filter(Boolean);
- const ages = (shot.age_ids || []).map(byId).filter(Boolean);
- const audios = (shot.audio_ids || []).map(byId).filter(Boolean);
- // 同一角色只给一张图:已挂服装/年龄变体时,变体图就是实际提交的角色参考图(服装优先于年龄),
- // 不再把角色原图也塞进图片块——否则模型会看到同一个人物的两张设定图。
- const costumeCharIds = new Set(costumes.map((a) => a.parent_id).filter(Boolean));
- const variantCharIds = new Set([...costumeCharIds, ...ages.map((a) => a.parent_id).filter(Boolean)]);
- const text = JSON.stringify({
- characters: chars.map((c) => ({ id: c.id, name: c.name, image_path: c.image_path })),
- scenes: scenes.map((s) => ({ id: s.id, name: s.name, image_path: s.image_path })),
- props: props.map((p) => ({ id: p.id, name: p.name, image_path: p.image_path })),
- costumes: costumes.map((c) => ({ id: c.id, name: c.name, image_path: c.image_path, parent_id: c.parent_id || '' })),
- ages: ages.map((a) => ({ id: a.id, name: a.name, image_path: a.image_path, parent_id: a.parent_id || '' })),
- audios: audios.map((a) => ({ id: a.id, name: a.name, category: a.category, audio_path: a.audio_path || a.voice_ref })),
- });
- if (!visionEnabled(ctx)) return text + '(当前模型不支持图片输入,仅返回文本清单)';
- const absPaths = [
- ...chars.filter((c) => !variantCharIds.has(c.id)),
- ...scenes, ...props,
- ...costumes,
- ...ages.filter((a) => !costumeCharIds.has(a.parent_id)),
- ].map((x) => resolveProjectPath(ctx.projectId, x.image_path)).filter(Boolean);
- const images = imagesFromPaths(absPaths, 6);
- return images.length ? { text, images } : text + '(该分镜暂无参考图)';
- }
- // 解析目标章节 id 集合:ctx.chapter 可能是标题或 id;无目标(全部章节)返回 null。
- export function targetChapterIdSet(ctx) {
- if (!ctx.chapter) return null;
- const set = new Set();
- for (const c of Chapters.list(ctx.projectId)) {
- if (c.title === ctx.chapter || c.id === ctx.chapter) set.add(c.id);
- }
- return set;
- }
- async function hViewProjectReferences(ctx) {
- const refs = filterReferenceImages(ReferenceImages.list(ctx.projectId, { mode: 'reference' }), targetChapterIdSet(ctx));
- const text = JSON.stringify(refs.map((r) => ({ id: r.id, chapter_id: r.chapter_id || '', name: r.name, image_path: r.image_path, category: r.category, description: r.description || '' })));
- if (!visionEnabled(ctx)) return text + '(当前模型不支持图片输入,仅返回文本清单)';
- const absPaths = refs.map((r) => resolveProjectPath(ctx.projectId, r.image_path)).filter(Boolean);
- const images = imagesFromPaths(absPaths, 6);
- return images.length ? { text, images } : text + '(暂无参考图)';
- }
- async function hWebSearch(ctx, args) {
- // 设置里关闭联网搜索时,两个工具都返回 disabled(不抛错),让 Agent 用既有知识继续、不要重试。
- if (ctx.cfg.search?.enabled === false) {
- return JSON.stringify({ disabled: true, message: '联网搜索已在设置中关闭。请改用你的既有知识继续,不要重试。' });
- }
- if (args.type === 'image') {
- return JSON.stringify(await searchImages(args.query, { limit: args.limit }));
- }
- return JSON.stringify(await searchWeb(args.query, { limit: args.limit, engine: args.engine }));
- }
- async function hDownloadReferenceImage(ctx, args) {
- if (ctx.cfg.search?.enabled === false) {
- return JSON.stringify({ disabled: true, message: '联网搜索已在设置中关闭,无法下载参考图。' });
- }
- const url = String(args.url || '').trim();
- if (!url) throw new Error('请提供图片 URL');
- const { buffer, ext } = await downloadImageSafe(url);
- // 参考图必须归属某章(references 上传链路要求 chapter_id 必填);优先当前目标章节,否则第一章。
- const chapters = Chapters.list(ctx.projectId);
- if (!chapters.length) throw new Error('项目还没有章节,无法登记参考图');
- const chapterId = (chapters.find((c) => c.title === ctx.chapter || c.id === ctx.chapter) || chapters[0]).id;
- const category = ASSET_CATEGORY_IDS.includes(args.category) ? args.category : 'prop';
- let baseName = String(args.name || '').trim();
- if (!baseName) {
- try {
- const p = new URL(url).pathname;
- const b = path.basename(p, path.extname(p));
- if (b) baseName = decodeURIComponent(b).slice(0, 40);
- } catch { /* 用兜底名 */ }
- }
- const name = (baseName || '下载参考图').trim();
- const relPath = 'references/' + slugify(name) + '_' + uid().slice(0, 8) + ext;
- const abs = resolveProjectPath(ctx.projectId, relPath);
- if (!abs) throw new Error('非法保存路径');
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, buffer);
- const ref = ReferenceImages.create(ctx.projectId, {
- chapter_id: chapterId,
- name,
- image_path: relPath,
- mode: 'reference',
- category,
- description: String(args.description || '').trim(),
- origin: 'downloaded',
- });
- ctx.report({ phase: '下载参考图', detail: '已下载并登记参考图:' + name });
- return JSON.stringify({ reference_id: ref.id, name: ref.name, image_path: relPath, category });
- }
- async function hGenerateAssetFromReference(ctx, args) {
- const ref = ReferenceImages.get(args.reference_id);
- if (!ref || ref.project_id !== ctx.projectId) throw new Error('参考素材不存在');
- const category = args.category || 'other';
- const name = String(args.name || '').trim();
- if (!name) throw new Error('请提供新素材名称 name');
- // 变体(服装/年龄)必须绑角色;非变体传了 parent_id 直接拒绝(见 resolveAssetParent)
- const parentId = resolveAssetParent(ctx, category, args.parent_id);
- const refAbs = resolveProjectPath(ctx.projectId, ref.image_path);
- if (!refAbs || !fs.existsSync(refAbs)) throw new Error('参考图不存在,请先上传参考图');
- const asset = Assets.create(ctx.projectId, { category, name, description: args.description || '', parent_id: parentId });
- const fb = fallbackAssetPrompt({ type: category, name, description: args.description || '', style: ctx.project.style });
- const prompt = args.prompt || fb.prompt;
- ctx.report({ phase: '资产生成', detail: '参考图生成新素材:' + name });
- const { img, ext } = await runI2iEdit(ctx, { refAbs, prompt, namePrefix: 'assets/' + slugify(name) + '_ref_' + uid().slice(0, 8), dedupeKey: 'ref-asset:' + asset.id });
- const relDir = 'assets/' + (PROJECT_ASSET_SUBDIRS[category] || 'other') + '/';
- const relPath = relDir + slugify(name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, img, relPath);
- Assets.update(asset.id, { image_path: relPath, source: 'generated', prompt, prompt_used: prompt, status: 'done', error: '' });
- return JSON.stringify({ asset_id: asset.id, image_path: relPath, reference_id: ref.id });
- }
- async function hRegisterVoice(ctx, args) {
- const a = Assets.get(args.asset_id);
- if (!a || a.project_id !== ctx.projectId) throw new Error('资产不存在');
- // 手填/上传的参考语音同样标记「声音限制已用」,避免音色阶段重复重做
- Assets.update(args.asset_id, { voice_ref: args.voice_ref, voice_desc_used: a.voice_desc || '' });
- return '已登记参考语音';
- }
- async function hDesignVoice(ctx, args) {
- let asset = Assets.get(args.asset_id);
- if (!asset || asset.project_id !== ctx.projectId) throw new Error('资产不存在');
- const dedupeKey = 'voice:' + asset.id;
- if (Queue.activeByDedupe(dedupeKey)) {
- if (!(await waitForActiveRender(dedupeKey, ctx.isAborted))) throw new Error('等待其他任务完成该角色音色超时');
- asset = Assets.get(asset.id) || asset;
- let exists = false;
- try { exists = !!(asset.voice_ref && fs.existsSync(resolveProjectPath(ctx.projectId, asset.voice_ref))); } catch {}
- if (exists && (asset.voice_desc_used || '') === (asset.voice_desc || '')) {
- return JSON.stringify({ asset_id: asset.id, skipped: true, reason: '其他任务已完成该角色音色' });
- }
- }
- // 朗读文案:优先显式传入;其次从声音画像取;绝不用「外貌描述」当朗读文案(那是给文生图的)。
- // 都缺时给通用自我介绍模板,避免批量阶段念出一段外貌描写。
- const MAX_TTS_TEXT = 30;
- let text = (args.text || '').trim();
- if (!text) text = (asset.voice_desc || '').trim() || ('你好,我是' + asset.name + '。很高兴认识你。');
- if (text.length > MAX_TTS_TEXT) {
- logger.warn('音色设计朗读文案过长(' + text.length + ' 字),已截断到 ' + MAX_TTS_TEXT + ' 字:' + asset.name);
- text = text.slice(0, MAX_TTS_TEXT);
- }
- // 音色描述:显式传入(含空串=用户想清空) > 资产声音画像(voice_desc) > 从名称/描述推断性别年龄 > 中性兜底。
- // 必须让性别/年龄显式进入 voice_description——缺失时 Qwen3-TTS 自由发挥,男主会变女声。
- const hasExplicitVoiceDesc = Object.prototype.hasOwnProperty.call(args, 'voice_description');
- const rawVoiceDesc = hasExplicitVoiceDesc ? (args.voice_description || '').trim() : '';
- const voice_description = rawVoiceDesc
- || (asset.voice_desc || '').trim()
- || inferVoiceBaseline(asset.name, asset.description)
- || '自然清晰的中性嗓音,无明显性别特征';
- // 若用户显式传了空串(想清空),用默认兜底且后续把 asset.voice_desc 设为空
- const explicitEmpty = hasExplicitVoiceDesc && rawVoiceDesc === '';
- if (!rawVoiceDesc && !(asset.voice_desc || '').trim()) {
- logger.warn('音色描述使用推断兜底(资产缺 voice_desc):' + asset.name + ' → ' + voice_description);
- }
- const spec = getSpecForKind(ctx.cfg, 'tts');
- const prefix = 'voice/' + slugify(asset.name) + '_' + uid().slice(0, 8);
- const prevRef = asset.voice_ref || asset.audio_path || '';
- ctx.report({ phase: '音色设计', detail: '设计音色:' + asset.name });
- Assets.update(asset.id, { status: 'generating' });
- try {
- const { outputs } = await runWorkflow(ctx.cfg, spec, {
- text, voice_description, seed: randomSeed(), filename_prefix: prefix,
- }, { timeoutMs: IMG_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, jobId: ctx.jobId, projectId: ctx.projectId, chapter: '', subject: asset.name || asset.id, dedupeKey: 'voice:' + asset.id, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } });
- const aud = pickOutput(outputs, 'audio');
- if (!aud) throw new Error('音色设计工作流未返回音频');
- const ext = path.extname(aud.filename) || '.wav';
- const relPath = 'assets/voice/' + slugify(asset.name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, aud, relPath);
- // 若用户显式传了空串(想清空),把 asset.voice_desc 设为空;否则写入生成时用的 voice_description
- const savedVoiceDesc = explicitEmpty ? '' : voice_description;
- Assets.update(asset.id, { voice_ref: relPath, audio_path: relPath, source: 'generated', status: 'done', voice_desc: savedVoiceDesc, voice_desc_used: voice_description, error: '' });
- return JSON.stringify({ asset_id: asset.id, voice_ref: relPath });
- } catch (e) {
- Assets.update(asset.id, { status: prevRef ? 'done' : 'failed', error: e.message });
- throw e;
- }
- }
- // —— 音色克隆(Qwen3-TTS Voice Clone)共享执行体 ——
- // 上传参考音色 → 跑 tts_clone 工作流 → 下载语音到 targetRelPath,返回最终相对路径。
- async function synthesizeClone(ctx, { text, refAbs, filenamePrefix, targetRelPath }) {
- const refExt = path.extname(refAbs) || '.wav';
- const refName = 'ic_vc_' + ctx.projectId.slice(0, 8) + '_' + uid().slice(0, 8) + refExt;
- const refFilename = await uploadTaskInput(ctx.cfg, refAbs, refName);
- const spec = getSpecForKind(ctx.cfg, 'tts_clone');
- const { outputs } = await runWorkflow(ctx.cfg, spec, {
- text,
- ref_audio: refFilename,
- seed: randomSeed(),
- filename_prefix: filenamePrefix,
- }, {
- timeoutMs: IMG_TIMEOUT(ctx.cfg),
- isAborted: ctx.isAborted,
- jobId: ctx.jobId,
- projectId: ctx.projectId,
- chapter: '',
- subject: '音色克隆',
- onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); },
- });
- const aud = pickOutput(outputs, 'audio');
- if (!aud) throw new Error('音色克隆工作流未返回音频');
- const ext = path.extname(aud.filename) || '.wav';
- await downloadOutputTo(ctx, aud, targetRelPath + ext);
- return targetRelPath + ext;
- }
- // 独立「音色克隆」工具:把参考音色克隆成朗读 text 的语音,落为 voice 资产。
- async function hCloneVoice(ctx, args) {
- const asset = Assets.get(args.asset_id);
- if (!asset || asset.project_id !== ctx.projectId || asset.category !== 'voice') throw new Error('语音资产不存在');
- const text = String(args.text || '').trim();
- if (!text) throw new Error('缺少说话内容 text');
- const refRel = String(args.ref_audio || asset.voice_ref || '').trim();
- if (!refRel) throw new Error('缺少参考音色 ref_audio');
- const refAbs = resolveProjectPath(args.ref_audio_project_id || ctx.projectId, refRel);
- if (!refAbs || !fs.existsSync(refAbs)) throw new Error('参考音色文件不存在:' + refRel);
- const prefix = 'assets/voice/' + slugify(asset.name) + '_' + uid().slice(0, 8);
- ctx.report({ phase: '音色克隆', detail: '克隆音色:' + asset.name });
- Assets.update(asset.id, { status: 'generating' });
- try {
- const relPath = await synthesizeClone(ctx, { text, refAbs, filenamePrefix: 'voice/' + uid().slice(0, 8), targetRelPath: prefix });
- Assets.update(asset.id, { voice_ref: relPath, audio_path: relPath, source: 'generated', status: 'done', params: { text, ref_audio: refRel, ref_audio_project_id: args.ref_audio_project_id || '' }, error: '' });
- return JSON.stringify({ asset_id: asset.id, voice_ref: relPath });
- } catch (e) {
- Assets.update(asset.id, { status: asset.voice_ref ? 'done' : 'failed', error: e.message });
- throw e;
- }
- }
- // 数字人两步流水线:① 语音克隆(参考音色 + 说话内容)→ 语音;② 头像 + 语音 → r2v 数字人视频。
- async function hGenerateDigitalHuman(ctx, args) {
- const asset = (args && args.asset_id) ? Assets.get(args.asset_id) : null;
- if (!asset || asset.project_id !== ctx.projectId || asset.category !== 'video') throw new Error('视频资产不存在');
- const text = String(args.text || '').trim();
- if (!text) throw new Error('缺少说话内容 text');
- const prompt = String(args.prompt || asset.prompt || '').trim();
- if (!prompt) throw new Error('缺少动作描述提示词 prompt');
- const avatarRel = String(args.avatar || '').trim();
- if (!avatarRel) throw new Error('缺少人物头像 avatar');
- const refRel = String(args.ref_audio || '').trim();
- if (!refRel) throw new Error('缺少参考音色 ref_audio');
- const avatarAbs = resolveProjectPath(ctx.projectId, avatarRel);
- if (!avatarAbs || !fs.existsSync(avatarAbs)) throw new Error('人物头像不存在:' + avatarRel);
- const refAbs = resolveProjectPath(args.ref_audio_project_id || ctx.projectId, refRel);
- if (!refAbs || !fs.existsSync(refAbs)) throw new Error('参考音色不存在:' + refRel);
- const reso = String(args.resolution || '480P');
- const ratio = String(args.aspect_ratio || '16:9');
- const seconds = Number(args.seconds) > 0 ? Number(args.seconds) : 5;
- ctx.report({ phase: '数字人', detail: '① 语音克隆:' + text });
- Assets.update(asset.id, { status: 'generating', prompt });
- try {
- const speechRel = await synthesizeClone(ctx, { text, refAbs, filenamePrefix: 'voice/' + uid().slice(0, 8), targetRelPath: 'uploads/dh_speech_' + uid().slice(0, 8) });
- const avatarName = 'ic_dh_' + ctx.projectId.slice(0, 8) + '_img_' + uid().slice(0, 8) + (path.extname(avatarAbs) || '.png');
- const avatarFilename = await uploadTaskInput(ctx.cfg, avatarAbs, avatarName);
- const speechAbs = resolveProjectPath(ctx.projectId, speechRel);
- const speechName = 'ic_dh_' + ctx.projectId.slice(0, 8) + '_audio_' + uid().slice(0, 8) + (path.extname(speechAbs) || '.wav');
- const speechFilename = await uploadTaskInput(ctx.cfg, speechAbs, speechName);
- const { spec, scale, resolution: wfResolution } = getR2vSpecForResolution(ctx.cfg, reso, 'digital_human', 1);
- ctx.report({ phase: '数字人', detail: '② 生成数字人视频' });
- const wfParams = {
- positive_prompt: prompt,
- seconds,
- aspect_ratio: ratio,
- resolution: wfResolution,
- seed: randomSeed(),
- filename_prefix: 'video/' + slugify(asset.name) + '_' + uid().slice(0, 8),
- references: [{ type: 'image', filename: avatarFilename }, { type: 'audio', filename: speechFilename }],
- mode: 'digital_human',
- };
- if (scale) wfParams.scale = scale;
- const { outputs } = await runWorkflow(ctx.cfg, spec, wfParams, { jobId: ctx.jobId, timeoutMs: VID_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } });
- const vid = pickOutput(outputs, 'videos');
- if (!vid) throw new Error('数字人工作流未返回视频文件');
- const ext = path.extname(vid.filename) || '.mp4';
- const relPath = 'assets/videos/' + slugify(asset.name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, vid, relPath);
- Assets.update(asset.id, { video_path: relPath, prompt_used: prompt, source: 'generated', status: 'done', params: { mode: 'digital_human_tts', text, prompt, avatar: avatarRel, ref_audio: refRel, ref_audio_project_id: args.ref_audio_project_id || '', seconds, resolution: reso, aspect_ratio: ratio } });
- return JSON.stringify({ asset_id: asset.id, name: asset.name, video_path: relPath });
- } catch (e) {
- const aborted = !!(ctx.isAborted && ctx.isAborted());
- if (aborted && asset.video_path) Assets.update(asset.id, { status: 'done' });
- else Assets.update(asset.id, { status: 'failed' });
- throw e;
- }
- }
- // 按工作流分批统一生成:① 文生图全部图片资产 → ② Qwen3-TTS 全部人物音色(同一工作流连续跑完再切下一类,省模型加载)
- // only 缺省时图+音色一起跑(Agent 原有行为不变);传 only 可只跑其中一类,
- // 供阶段调度把「资产图」和「音色」拆到不同的 ComfyUI 实例(CK 开关要求不同)
- async function hGenerateAssetsBatch(ctx, args) {
- const only = args && Array.isArray(args.only) ? args.only : null;
- // 值域与工具 schema 的 enum 一致:只有 image / tts 两类。写错(如 ['video'])时
- // 会两类都不跑,却回报一条「全部完成、0 失败」的成功结果,阶段调度据此以为已经做完了。
- if (only) {
- const bad = only.filter((k) => k !== 'image' && k !== 'tts');
- if (bad.length) throw new Error('only 只能是 image / tts(收到:' + bad.join('、') + ')');
- }
- const wantImage = !only || only.includes('image');
- const wantVoice = !only || only.includes('tts');
- const assets = Assets.list(ctx.projectId);
- const imageAssets = assets.filter((a) => IMAGE_ASSET_CATEGORIES.includes(a.category));
- const charAssets = assets.filter((a) => a.category === 'character');
- const res = { images: { total: 0, generated: 0, failed: 0 }, voices: { total: 0, generated: 0, failed: 0, skipped: 0 } };
- if (wantImage) {
- // 并发提交:真正限流的是 runWorkflow 里的渲染槽位(RunningHub 按 runninghubConcurrency,
- // 本地 ComfyUI 恒为 1),这里把整批一次性排进队列即可。
- // 跳过「已生成且提示词未变过」的资产;用户若改过 prompt(与上次生成用的 prompt_used 不同)则重新生成。
- const pending = imageAssets.filter((a) => !(a.image_path && a.status === 'done' && (a.prompt_used || '') === (a.prompt || '')));
- ctx.report({ phase: '资产生成', detail: '第1批·文生图:' + pending.length + ' 个图片资产(并发 ' + renderConcurrencyLimit(ctx.cfg) + ')' });
- await Promise.all(pending.map(async (a) => {
- if (ctx.isAborted && ctx.isAborted()) return;
- res.images.total++;
- try { await hGenerateAssetImage(ctx, { asset_id: a.id }); res.images.generated++; }
- catch (e) {
- if (ctx.isAborted && ctx.isAborted()) return;
- res.images.failed++; Assets.update(a.id, { status: 'failed', error: e.message }); ctx.report({ phase: '资产生成', detail: '图片失败 ' + a.name + ':' + e.message });
- }
- }));
- if (ctx.isAborted && ctx.isAborted()) return JSON.stringify({ ...res, aborted: true });
- }
- if (wantVoice) {
- // 音色同样按渲染槽位并发;跳过逻辑与串行版本一致。
- ctx.report({ phase: '音色设计', detail: '第2批·音色设计:' + charAssets.length + ' 个角色音色(并发 ' + renderConcurrencyLimit(ctx.cfg) + ')' });
- await Promise.all(charAssets.map(async (a) => {
- if (ctx.isAborted && ctx.isAborted()) return;
- // 跳过「已有音色且声音限制未变过」的角色;用户改过 voice_desc(与上次用的 voice_desc_used 不同)则重做
- if (a.voice_ref && fs.existsSync(resolveProjectPath(ctx.projectId, a.voice_ref)) && (a.voice_desc_used || '') === (a.voice_desc || '')) return;
- // 无声音画像且无法从名称/描述推断性别年龄 → 跳过并提示,不静默出性别错乱的音色
- const base = inferVoiceBaseline(a.name, a.description);
- if (!(a.voice_desc || '').trim() && !base) {
- res.voices.skipped++;
- ctx.report({ phase: '音色设计', detail: '跳过 ' + a.name + ':资产无声音特征描述(voice_desc),无法推断性别/年龄。请先在 LLM 阶段调用 create_asset/update_asset 补充 voice_desc 或用 design_voice 为其设计音色。' });
- return;
- }
- res.voices.total++;
- try { await hDesignVoice(ctx, { asset_id: a.id }); res.voices.generated++; }
- catch (e) {
- if (ctx.isAborted && ctx.isAborted()) return;
- res.voices.failed++; Assets.update(a.id, { status: 'failed', error: e.message }); ctx.report({ phase: '音色设计', detail: '音色失败 ' + a.name + ':' + e.message });
- }
- }));
- if (ctx.isAborted && ctx.isAborted()) return JSON.stringify({ ...res, aborted: true });
- }
- return JSON.stringify(res);
- }
- // —— 换装事件自动识别与服装资产生成(确定性兜底,不依赖 LLM 记忆) ——
- // 剧情里的「沐浴/洗澡/更衣/换衣/换装」意味着角色着装状态发生变化(洗澡后理应换干净衣服)。
- // 系统据此自动为对应角色生成一套服装资产(change_outfit,图生图保持脸/发型/画风一致),
- // 并自动绑定到「换装事件之后」的镜头;事件之前的镜头继续用角色原图或旧服装。
- // 「沐浴」单独出现不算换装(「沐浴在晨光里」「沐浴露」都是普通描写),但「在屋后沐浴」是动作本身。
- const OUTFIT_BATH_RE = /沐浴(?!在|露)|出浴|洗完澡|洗澡|浴桶/;
- const OUTFIT_CHANGE_RE = /更衣|换衣|换装|换衣服|换了衣服|换上一身|换了一身|换上一套|换了一套|换上新衣|换上新裳|换上新衣裳/;
- function detectOutfitChange(text) {
- if (!text) return null;
- const m = String(text).match(OUTFIT_BATH_RE);
- if (m) return { kind: 'bath', keyword: m[0] };
- const c = String(text).match(OUTFIT_CHANGE_RE);
- if (c) return { kind: 'change', keyword: c[0] };
- return null;
- }
- function inferOutfitDescription(text, kind, keyword) {
- if (kind === 'bath') return '沐浴后换上的干净衣裳';
- if (kind === 'change') {
- const t = String(text);
- const i = t.indexOf(keyword);
- if (i >= 0) {
- let seg = t.slice(i + keyword.length, i + keyword.length + 16);
- seg = seg.replace(/^[的了过,。;:!!??]+/, '').trim();
- const cut = seg.search(/[,。;:!!??]/);
- if (cut >= 0) seg = seg.slice(0, cut);
- if (seg.trim()) return seg.trim();
- }
- return '新换的衣裳';
- }
- return '新换的衣裳';
- }
- // 扫描本次写入分镜所属章节的换装事件,自动生成服装资产并绑定到事件之后的镜头。
- // 幂等:同名服装已存在则复用(change_outfit 内部去重);生成失败不阻塞分镜写入(该镜继续用角色原图兜底)。
- async function autoResolveOutfits(ctx, chapters) {
- const chapterSet = new Set((chapters || []).filter(Boolean).map(String));
- if (!chapterSet.size) return { generated: 0, bound: 0, notes: [] };
- const shots = Shots.list(ctx.projectId)
- .filter((s) => chapterSet.has(String(s.chapter || '')))
- .sort((a, b) => String(a.chapter || '').localeCompare(String(b.chapter || ''), 'zh') || (a.idx - b.idx));
- if (!shots.length) return { generated: 0, bound: 0, notes: [] };
- // 本阶段禁止渲染(LLM 创作阶段)时只检测、不生成:兜底要图生图出图,而那个阶段的硬约束是不碰
- // ComfyUI(见 runTool 对 RENDER_TOOLS 的拦截、agent-loop 系统提示「这些工具只会返回已跳过」)。
- // 原先 set_storyboard 直接调 hChangeOutfit,绕过了这层拦截:LLM 阶段照跑一次渲染,ComfyUI 没启动
- // 时会白等一次超时。生成改由「资产图」阶段执行(stages.js RENDER_STAGE_TOOLS.image →
- // resolveShotProvisions),那里才有 ComfyUI。这里把待兜底镜头数回报出去,免得静默消失。
- if (ctx.renderDisabled) {
- const pending = shots.filter((s) => detectOutfitChange([s.scene_name, s.visual, s.dialogue, s.sub_shots].filter(Boolean).join(' '))).length;
- return { generated: 0, bound: 0, notes: [], deferred: pending };
- }
- const assets = Assets.list(ctx.projectId);
- const byId = {};
- const charById = {};
- for (const a of assets) { byId[a.id] = a; if (a.category === 'character') charById[a.id] = a; }
- const currentCostume = {}; // charId -> costumeId(本章内当前着装)
- let prevChapter = null;
- let generated = 0, bound = 0;
- const notes = [];
- const textOf = (s) => [s.scene_name, s.visual, s.dialogue, s.sub_shots].filter(Boolean).join(' ');
- for (const s of shots) {
- // 用户已停止:不再往下识别/生成换装变体。每个事件都会真的提交一次图生图,
- // 停止之后继续跑等于白烧 GPU(已提交的项目会排在 ComfyUI 队列里被挨个执行)。
- if (ctx.isAborted && ctx.isAborted()) break;
- // 章节边界:重置「当前着装」状态(换装跟随剧情在同一章内连续)
- if (prevChapter !== null && s.chapter !== prevChapter) { for (const k of Object.keys(currentCostume)) delete currentCostume[k]; }
- prevChapter = s.chapter;
- const charIds = (s.character_ids || []).filter((id) => charById[id]);
- const charNames = charIds.map((id) => charById[id] && charById[id].name).filter(Boolean);
- const text = textOf(s);
- const costumeIds = new Set(s.costume_ids || []);
- // 已显式引用服装的角色(LLM 在 costumes 字段里绑定了服装资产)跳过自动兜底,避免重复生成。
- // 判定必须只看「库里已有的绑定」,即必须在并入 currentCostume 之前算:
- // currentCostume 是本函数刚刚自动生成/绑定出来的结果,把它一起算进去的话,同一章里
- // 第二次换装事件会被当成「已显式引用」直接 continue —— 服装只换一次,之后永不更新。
- const charHasCostume = {};
- for (const costumeId of costumeIds) { const a = byId[costumeId]; if (a && a.parent_id) charHasCostume[a.parent_id] = true; }
- // 1) 再应用当前着装到本镜(若此前已发生换装)
- for (const cid of charIds) if (currentCostume[cid]) costumeIds.add(currentCostume[cid]);
- // 2) 检测本镜是否发生换装事件,归属到具体角色并生成服装资产(自下一镜起生效)
- const evt = detectOutfitChange(text);
- if (evt) {
- for (const cid of charIds) {
- if (charHasCostume[cid]) continue;
- const char = charById[cid];
- // 归属判定用 textMentions:文本里「小明」提到的是「小明」,不是同场的短名「明」
- //(旧写法 text.includes(char.name) 会给「明」也错生成一套服装,并写进本镜 costume_ids)
- const named = charIds.length === 1 || textMentions(text, char.name, charNames);
- if (!named) continue;
- const outfit = inferOutfitDescription(text, evt.kind, evt.keyword);
- try {
- const r = await hChangeOutfit(ctx, { character_id: cid, outfit });
- const info = JSON.parse(r);
- currentCostume[cid] = info.costume_id;
- generated++;
- notes.push('自动换装:' + char.name + ' → ' + outfit);
- } catch (e) {
- logger.warn('自动换装失败:' + char.name + '(' + outfit + ')', { error: e.message });
- notes.push('自动换装失败:' + char.name + '(' + e.message + ')');
- }
- }
- }
- // 3) 写回本镜 costume_ids(含新生成/复用的服装)
- const existing = [...(s.costume_ids || [])].sort();
- const next = [...costumeIds].sort();
- if (JSON.stringify(existing) !== JSON.stringify(next)) {
- Shots.update(s.id, { costume_ids: next });
- bound++;
- }
- }
- return { generated, bound, notes };
- }
- // —— 年龄变化事件自动识别与年龄变体资产生成(确定性兜底,不依赖 LLM 记忆) ——
- // 剧情里的「回忆/年轻时/N年前/多年后/步入中年/步入老年」意味着角色年龄状态发生变化。
- // 系统据此以角色 canonical 图为参考自动生成年龄变体(change_age,图生图保持身份一致、只改年龄),
- // 并绑定到「时间跳跃之后」的镜头;事件之前的镜头继续用角色原图(或旧年龄变体)。
- // 只认「明确的时间跳跃/时期切换」,不认「年轻/少年/白发」这类外貌描写:
- // 它们经常只是普通形容词(「年轻女子」「少年感」「白发苍苍的老者」是角色设定而非时间跳跃),
- // 拿它们当触发词会把同一章所有角色都生成一遍年龄变体,产出大量用不上的素材。
- const AGE_OLD_RE = /老年时|步入老年|年迈|变老了?|老了|苍老/;
- const AGE_MID_RE = /中年时|步入中年|人到中年/;
- const AGE_YOUNG_RE = /小时候|童年时|幼年时|年轻时|少年时|少女时代|学生时代|闪回|时间回到|\d+\s*年前|多年前|当年/;
- const AGE_OLDER_RE = /长大后|成年后|多年后|数年后|\d+\s*年后/;
- function detectAgeChange(text) {
- if (!text) return null;
- const t = String(text);
- let m = t.match(AGE_OLD_RE); if (m) return { keyword: m[0], variant: { label: '老年', age: '老年时的样貌' } };
- m = t.match(AGE_MID_RE); if (m) return { keyword: m[0], variant: { label: '中年', age: '中年时的样貌' } };
- m = t.match(AGE_YOUNG_RE); if (m) return { keyword: m[0], variant: { label: '年轻', age: '年轻时的样貌' } };
- m = t.match(AGE_OLDER_RE); if (m) return { keyword: m[0], variant: { label: '更年长', age: '更年长时的样貌' } };
- return null;
- }
- // 扫描本次写入分镜所属章节的年龄变化事件,自动生成年龄变体并绑定到事件之后的镜头。
- // 幂等:同名年龄变体已存在则复用(change_age 内部去重);生成失败不阻塞分镜写入(该镜继续用角色原图兜底)。
- async function autoResolveAges(ctx, chapters) {
- const chapterSet = new Set((chapters || []).filter(Boolean).map(String));
- if (!chapterSet.size) return { generated: 0, bound: 0, notes: [] };
- const shots = Shots.list(ctx.projectId)
- .filter((s) => chapterSet.has(String(s.chapter || '')))
- .sort((a, b) => String(a.chapter || '').localeCompare(String(b.chapter || ''), 'zh') || (a.idx - b.idx));
- if (!shots.length) return { generated: 0, bound: 0, notes: [] };
- // 同 autoResolveOutfits:LLM 阶段(renderDisabled)只检测不生成,生成推迟到「资产图」阶段。
- if (ctx.renderDisabled) {
- const pending = shots.filter((s) => detectAgeChange([s.scene_name, s.visual, s.dialogue, s.sub_shots].filter(Boolean).join(' '))).length;
- return { generated: 0, bound: 0, notes: [], deferred: pending };
- }
- const assets = Assets.list(ctx.projectId);
- const byId = {};
- const charById = {};
- for (const a of assets) { byId[a.id] = a; if (a.category === 'character') charById[a.id] = a; }
- const currentAge = {}; // charId -> ageId(本章内当前年龄)
- let prevChapter = null;
- let generated = 0, bound = 0;
- const notes = [];
- const textOf = (s) => [s.scene_name, s.visual, s.dialogue, s.sub_shots].filter(Boolean).join(' ');
- for (const s of shots) {
- // 同 autoResolveOutfits:停止后不再继续生成年龄变体(每次都会真提交一次图生图)
- if (ctx.isAborted && ctx.isAborted()) break;
- if (prevChapter !== null && s.chapter !== prevChapter) { for (const k of Object.keys(currentAge)) delete currentAge[k]; }
- prevChapter = s.chapter;
- const charIds = (s.character_ids || []).filter((id) => charById[id]);
- const charNames = charIds.map((id) => charById[id] && charById[id].name).filter(Boolean);
- const text = textOf(s);
- const ageIds = new Set(s.age_ids || []);
- // 已显式引用年龄变体的角色(LLM 在 ages 字段里绑定)跳过自动兜底,避免重复生成。
- // 与服装同理:必须在并入 currentAge 之前判定,否则同一章内第二次时间跳跃会被跳过。
- const charHasAge = {};
- for (const ageId of ageIds) { const a = byId[ageId]; if (a && a.parent_id) charHasAge[a.parent_id] = true; }
- // 1) 再应用当前年龄到本镜(若此前已发生时间跳跃)
- for (const cid of charIds) if (currentAge[cid]) ageIds.add(currentAge[cid]);
- // 2) 检测本镜是否发生年龄变化事件,归属到具体角色并生成年龄变体(自下一镜起生效)
- const evt = detectAgeChange(text);
- if (evt) {
- for (const cid of charIds) {
- if (charHasAge[cid]) continue;
- const char = charById[cid];
- // 同 autoResolveOutfits:年龄变体只归属「文本真正提到」的角色(短名不被同场更长名吞掉)
- const named = charIds.length === 1 || textMentions(text, char.name, charNames);
- if (!named) continue;
- try {
- const r = await hChangeAge(ctx, { character_id: cid, age: evt.variant.age, label: evt.variant.label });
- const info = JSON.parse(r);
- currentAge[cid] = info.age_id;
- generated++;
- notes.push('自动年龄变体:' + char.name + ' → ' + evt.variant.age);
- } catch (e) {
- logger.warn('自动年龄变体失败:' + char.name + '(' + evt.variant.age + ')', { error: e.message });
- notes.push('自动年龄变体失败:' + char.name + '(' + e.message + ')');
- }
- }
- }
- // 3) 写回本镜 age_ids(含新生成/复用的年龄变体)
- const existing = [...(s.age_ids || [])].sort();
- const next = [...ageIds].sort();
- if (JSON.stringify(existing) !== JSON.stringify(next)) {
- Shots.update(s.id, { age_ids: next });
- bound++;
- }
- }
- return { generated, bound, notes };
- }
- // set_storyboard 每个分镜只认这些字段,与工具 schema 的 items.properties 一一对应。
- // 拼错/传错(visual 写成 sence_name 之外的名字、characters 写成 cast 等)原先会被静默丢弃:
- // 分镜照建、内容为空,回报却是「分镜已写入」——模型以为写好了,出片时才发现没有画面/角色。
- // 与外部写入 API(shot-write.js 对未声明字段直接 400)同口径:宁可当场报错让模型自纠。
- const SHOT_INPUT_KEYS = new Set(['idx', 'chapter', 'scene_name', 'duration', 'characters', 'scenes', 'props', 'costumes', 'ages', 'audios', 'sub_shots', 'dialogue', 'narration', 'camera', 'visual', 'mode']);
- // 分镜时长的唯一入口。非数字(模型爱写 "8秒"、"约 10 秒")必须当场拒绝:静默写成 NaN 会让这条
- // 分镜**永远出不了片** —— validateSubShots 里 parseFloat(NaN) || 0 = 0,任何子分镜都判「超过总时长」,
- // 重试多少次都一样,而错误信息里只有「超过」两个字,看不出根因在时长上。
- // 数字越界仍按原行为夹到 [SHOT_DURATION_MIN, SHOT_DURATION_MAX]。
- const durationOf = (sb) => {
- const raw = sb.duration;
- if (raw == null || raw === '') return SHOT_DURATION_DEFAULT;
- const n = Number(raw);
- if (!Number.isFinite(n)) throw new Error('分镜 duration 必须是数字(秒),当前:' + JSON.stringify(raw));
- return Math.min(SHOT_DURATION_MAX, Math.max(SHOT_DURATION_MIN, n));
- };
- async function hSetStoryboard(ctx, args) {
- // 字段白名单先于一切:不认的字段一律拒绝,避免「悄悄丢掉内容却回报成功」
- const unknownShotKeys = [];
- const badShots = [];
- (args.shots || []).forEach((sb, i) => {
- // 不是对象的元素必须当场拒绝:后面几轮校验直接按字段取值,遇到 null 会抛 TypeError
- // ("Cannot read properties of null"),模型看不出自己错在哪一条。
- if (!sb || typeof sb !== 'object' || Array.isArray(sb)) { badShots.push('第' + (i + 1) + '条'); return; }
- for (const k of Object.keys(sb)) if (!SHOT_INPUT_KEYS.has(k)) unknownShotKeys.push('第' + (i + 1) + '条.' + k);
- });
- if (badShots.length) {
- throw new Error('分镜必须是对象(每条含 chapter/idx/visual 等字段):' + badShots.join('、') + ' 不是对象');
- }
- if (unknownShotKeys.length) {
- throw new Error('分镜含未声明字段:' + [...new Set(unknownShotKeys)].join('、') + '。每条分镜只支持:' + [...SHOT_INPUT_KEYS].join('、'));
- }
- // 台词时长校验:中文旁白约 4-5 字/秒,超速会被 H3/TTS 压缩成听不清的模糊声。
- // 硬性拒绝,强制 Agent 缩短台词或拆分镜头,而不是生成后才发现语音对不上。
- const MAX_RATE = SHOT_DIALOGUE_MAX_RATE; // 字/秒(含说话人前缀「醉天:」的余量)
- const over = [];
- for (const sb of args.shots || []) {
- const dur = durationOf(sb);
- const chars = (sb.dialogue || '').length;
- if (chars && chars / dur > MAX_RATE) {
- over.push({ idx: sb.idx, durationSec: dur, dialogueChars: chars, maxChars: Math.floor(dur * MAX_RATE) });
- }
- }
- if (over.length) {
- throw new Error('台词与时长不匹配:中文旁白约 4-5 字/秒,超出会被压缩成听不清的模糊声。请把以下镜头的台词缩短到 maxChars 字以内(或拆成更多镜头 / 延长到最长 15 秒):' + JSON.stringify(over));
- }
- // 多人对话校验:单分镜最多 MAX_SPEAKERS_PER_SHOT 个说话人;≥3 人对话必须拆成多个分镜,
- // 避免参考音频超限(每说话人一段参考音色)且避免多人同框对话质量下降。
- const multiSpeaker = [];
- for (const sb of args.shots || []) {
- const speakers = dialogueSpeakerNames(sb.dialogue);
- if (speakers.length > MAX_SPEAKERS_PER_SHOT) {
- multiSpeaker.push({ idx: sb.idx, speakers });
- }
- }
- if (multiSpeaker.length) {
- throw new Error('分镜对话人数过多:每个分镜最多 ' + MAX_SPEAKERS_PER_SHOT + ' 个说话人,请把多人对话拆成多个分镜(每个分镜最多 ' + MAX_SPEAKERS_PER_SHOT + ' 人说话)。涉及分镜:' + JSON.stringify(multiSpeaker));
- }
- // 章节归属先整批解析:分镜是按「章节标题」挂到章节上的(chapter 就是业务键),所以 chapter 必须
- // 是本项目已存在的章节。模型可能传标题、也可能传 id(get_project / list_chapters 同时给出两者),
- // 两个都认。这一步必须在 clear 之前完成:否则一次非法写入会把整章分镜清空后才抛错。
- // 不做这一步的后果:写出「章节视图里看不到、也永远不会被生成」的孤儿分镜,却回报「分镜已写入」。
- const chapterMap = new Map();
- for (const c of Chapters.list(ctx.projectId)) { chapterMap.set(c.title, c.title); chapterMap.set(c.id, c.title); }
- const resolveChapter = (raw) => {
- const want = String(raw == null ? '' : raw).trim() || String(ctx.chapter || '').trim();
- if (!want) throw new Error('分镜缺少 chapter:请传章节标题或 id(可用 list_chapters 查看本项目章节)');
- const title = chapterMap.get(want);
- if (title === undefined) {
- throw new Error('章节不存在:' + want + '(本项目现有章节:' + [...new Set(chapterMap.values())].join('、') + ')');
- }
- return title;
- };
- const shotInputs = args.shots || [];
- const chapterTitles = shotInputs.map((sb) => resolveChapter(sb.chapter));
- const assets = Assets.list(ctx.projectId);
- const byName = (cat) => {
- const m = {};
- for (const a of assets) if (a.category === cat) m[a.name] = a.id;
- return m;
- };
- const charMap = byName('character'); const sceneMap = byName('scene'); const propMap = byName('prop'); const costumeMap = byName('costume'); const ageMap = byName('age');
- // 音频素材跨 voice/music/sfx 三类:统一按名字映射(作为 H3 音色参考)
- const audioMap = {};
- for (const a of assets) if (['voice', 'music', 'sfx'].includes(a.category)) audioMap[a.name] = a.id;
- // clear 只清「本次写入涉及的章节」:原先删的是整个项目的分镜,让「重新生成第2章分镜」把第1章
- // 已出片的镜头一并删掉,还回报「分镜已写入」——看起来完全正常。外部写入 API 的整章写入同口径
- // (app/api/.../storyboard/route.js 只删本章)。其他章节的分镜一律保留。
- const clearTitles = new Set(chapterTitles);
- let existing = Shots.list(ctx.projectId);
- if (args.clear) {
- // 断点续跑防护:clear 会删掉本章分镜(含已渲染的视频)。LLM 阶段重跑时模型若带 clear
- // 重写整章,已花钱出的视频会全部作废,下一次视频阶段又整章重跑。
- // 有成品/正在生成时一律拒绝清空,让模型改用「不带 clear 的 idx upsert」。
- const protectedShots = existing.filter(
- (s) => clearTitles.has(s.chapter) && (s.video_path || s.status === 'done' || s.status === 'generating' || s.status === 'queued'),
- );
- if (protectedShots.length) {
- throw new Error('本章已有 ' + protectedShots.length + ' 个已生成或生成中的分镜,clear 会删除这些成品视频;请去掉 clear,按 idx 更新已有分镜。');
- }
- for (const s of existing) if (clearTitles.has(s.chapter)) Shots.remove(s.id);
- existing = existing.filter((s) => !clearTitles.has(s.chapter));
- }
- // 每章独立 idx 空间:同一 (chapter, idx) 视为同一个镜头,不同章节互不干扰
- const key = (ch, idx) => String(ch || '') + '\u0000' + String(idx);
- const byKey = {}; for (const s of existing) byKey[key(s.chapter, s.idx)] = s;
- const chapterMax = {}; for (const s of existing) chapterMax[s.chapter || ''] = Math.max(chapterMax[s.chapter || ''] || 0, s.idx);
- // 镜号先整批归一(与外部写入 API 的 shot-write.js 同口径:≥1 的整数,章内唯一):
- // ① 分两遍:先把**全部**显式 idx 计入各章上限,再给省略 idx 的镜头续号。单遍分配时
- // 「自动号在前、显式号在后」会撞号([无 idx, idx:1] → [1,1]),后一条走 upsert 覆盖前一条,
- // 内容被静默丢掉;
- // ② 越界/非数字在这里拦下,避免 1.5 这类镜号落库后章内序号失去意义。
- for (let i = 0; i < shotInputs.length; i++) {
- const raw = shotInputs[i].idx;
- if (raw == null) continue;
- const n = Math.trunc(Number(raw));
- if (!Number.isFinite(n) || n < 1) throw new Error('分镜 idx 必须是 ≥1 的整数(当前:' + raw + ')');
- const ch = chapterTitles[i];
- chapterMax[ch] = Math.max(chapterMax[ch] || 0, n);
- }
- const idxs = chapterTitles.map((ch, i) => {
- const raw = shotInputs[i].idx;
- if (raw != null) return Math.trunc(Number(raw));
- const n = (chapterMax[ch] || 0) + 1; chapterMax[ch] = n; return n;
- });
- let added = 0, updated = 0;
- // 资产名按名字映射成 id;名字对不上(拼错、资产还没建)原先静默丢弃 —— 分镜照建、参考屏蔽,
- // 回报却是「分镜已写入」。这里收集未命中的名字,随结果一并回报(不拒绝整批:模型可先建资产再回填)。
- const missingRefs = [];
- const idsOf = (names, map, cat) => (names || []).map((n) => {
- const id = map[n];
- if (id === undefined) missingRefs.push(cat + '「' + n + '」');
- return id;
- }).filter(Boolean);
- const touched = [];
- const writtenChapters = new Set();
- for (let i = 0; i < shotInputs.length; i++) {
- const sb = shotInputs[i];
- const ch = chapterTitles[i];
- const idx = idxs[i];
- writtenChapters.add(ch);
- const fields = {
- chapter: ch,
- scene_name: sb.scene_name || ((sb.scenes || []).join('、')),
- camera: sb.camera || '', visual: sb.visual || '', dialogue: sb.dialogue || '', narration: sb.narration || '',
- sub_shots: sb.sub_shots || '', duration: durationOf(sb),
- character_ids: idsOf(sb.characters, charMap, '人物'),
- scene_ids: idsOf(sb.scenes, sceneMap, '场景'),
- prop_ids: idsOf(sb.props, propMap, '道具'),
- costume_ids: idsOf(sb.costumes, costumeMap, '服装'),
- age_ids: idsOf(sb.ages, ageMap, '年龄变体'),
- audio_ids: idsOf(sb.audios, audioMap, '音频'),
- resolution: ctx.project.video_resolution || '480P',
- aspect_ratio: ctx.project.video_aspect_ratio || '16:9',
- mode: sb.mode || '',
- };
- const k = key(ch, idx);
- if (byKey[k] !== undefined) {
- Shots.update(byKey[k].id, fields);
- updated++;
- touched.push({ id: byKey[k].id, idx, reused: true });
- } else {
- const shot = Shots.create(ctx.projectId, { ...fields, idx });
- // 新建的行必须登记回 byKey:否则同一次调用里出现两条 (chapter, idx) 相同的分镜时,
- // 两条都会走 create,落库成「同章同镜号」的重复镜头(注释里承诺的是「视为同一个镜头」)。
- byKey[k] = shot;
- added++;
- touched.push({ id: shot.id, idx: shot.idx });
- }
- }
- // 非破坏:仅新增/更新,绝不自动删除既有分镜(保证旧章节保留,多章节可继续追加)
- // 换装兜底:识别本次写入章节内的沐浴/更衣/换装事件,自动生成服装资产并绑定到事件之后的镜头。
- // 这里用「解析后的章节标题」而不是原始参数:模型传 id 时也要能定位到正确的章节。
- const chapters = [...writtenChapters];
- const outfitRes = await autoResolveOutfits(ctx, chapters);
- if (outfitRes.generated) ctx.report({ phase: '人物换装', detail: '自动识别换装事件,生成服装资产 ' + outfitRes.generated + ' 套' });
- const ageRes = await autoResolveAges(ctx, chapters);
- if (ageRes.generated) ctx.report({ phase: '人物年龄', detail: '自动识别年龄变化事件,生成年龄变体 ' + ageRes.generated + ' 个' });
- let out = '分镜已写入(新增 ' + added + ',更新 ' + updated + ')';
- if (outfitRes.generated) out += ';自动换装生成服装资产 ' + outfitRes.generated + ' 套、绑定 ' + outfitRes.bound + ' 镜';
- if (ageRes.generated) out += ';自动年龄变体生成 ' + ageRes.generated + ' 个、绑定 ' + ageRes.bound + ' 镜';
- // 本阶段不渲染(LLM 创作阶段)时兜底被推迟:把待处理的事件数回报出去,别让模型以为已经处理完
- if (outfitRes.deferred) out += ';检测到 ' + outfitRes.deferred + ' 个换装事件:服装资产将在「资产图」阶段生成并绑定(本阶段不渲染)';
- if (ageRes.deferred) out += ';检测到 ' + ageRes.deferred + ' 个年龄变化:年龄变体将在「资产图」阶段生成并绑定(本阶段不渲染)';
- // 兜底失败原先只写进 notes 且从不使用:服装/年龄变体没生成、镜头继续用原图出片,模型却看不到。
- if (missingRefs.length) out += ';未找到同名资产(已忽略):' + [...new Set(missingRefs)].join('、') + '。请先创建资产或修正名字';
- const failed = [...(outfitRes.notes || []), ...(ageRes.notes || [])].filter((n) => /失败/.test(n));
- if (failed.length) out += ';' + failed.join(';');
- return out;
- }
- // 换装/年龄兜底(原先在 set_storyboard 内联执行,见上面的 renderDisabled 分支):它要图生图出图,
- // 所以只能在有 ComfyUI 的阶段调用 —— 即「资产图」阶段(stages.js RENDER_STAGE_TOOLS.image)。
- // chapters 传章节标题数组;返回两个子结果(generated/bound/notes/deferred)与可展示的汇总文本。
- export async function resolveShotProvisions(ctx, chapters) {
- const outfit = await autoResolveOutfits(ctx, chapters);
- const age = await autoResolveAges(ctx, chapters);
- const lines = [];
- if (outfit.generated) lines.push('自动换装:生成服装资产 ' + outfit.generated + ' 套、绑定 ' + outfit.bound + ' 镜');
- if (age.generated) lines.push('自动年龄变体:生成 ' + age.generated + ' 个、绑定 ' + age.bound + ' 镜');
- const failed = [...(outfit.notes || []), ...(age.notes || [])].filter((n) => /失败/.test(n));
- if (failed.length) lines.push(failed.join(';'));
- return { outfit, age, text: lines.join(';') };
- }
- async function hListShots(ctx) {
- const target = targetChapterTitle(ctx);
- const shots = target
- ? Shots.list(ctx.projectId).filter((s) => s.chapter === target)
- : Shots.list(ctx.projectId);
- return JSON.stringify(shots.map((s) => ({ id: s.id, idx: s.idx, chapter: s.chapter || '', scene_name: s.scene_name, status: s.status, has_prompt: !!(s.video_prompt && String(s.video_prompt).trim()), has_video: !!s.video_path, error: s.error, duration: s.duration })));
- }
- async function hUpdateShot(ctx, args) {
- // 归属校验:与其他写工具同口径(generate_shot_video / update_asset 都先比对 project_id)。
- // 不校验的话,传入别的项目的 shot_id 会改掉那个项目的分镜,而变更日志记在本项目名下 ——
- // 回滚时两边都对不上。顺带把分镜读一次复用,不重复查库。
- const shot = Shots.get(args.shot_id);
- if (!shot || shot.project_id !== ctx.projectId) throw new Error('分镜不存在');
- const patch = {};
- for (const k of ['sub_shots', 'dialogue', 'narration', 'camera', 'visual', 'duration', 'video_prompt', 'mode']) if (args[k] != null) patch[k] = args[k];
- // 视频生成模式枚举校验:非空且不在 VIDEO_MODES 内即拒绝(空串 = auto,走确定性推断兜底)
- if (args.mode != null && String(args.mode) && !VIDEO_MODES.includes(String(args.mode))) {
- throw new Error('mode 只能是 ' + VIDEO_MODES.join('/') + '(当前:' + args.mode + ')');
- }
- // 时长归一化后再落库:原先只用「裁剪后的值」做台词/时长校验,却把原值写进 DB ——
- // 校验与落库不是同一个数(-5、0、'8秒' 都能入库)。负时长会被原样传给 H3(seconds=-5),
- // 也会把本章总时长算成负数(背景音乐时长按总时长算),而字符串时长在 REAL 列里退化。
- if (args.duration != null) {
- const d = Number(args.duration);
- if (!Number.isFinite(d)) throw new Error('duration 必须是数字(秒):' + args.duration);
- patch.duration = Math.min(SHOT_DURATION_MAX, Math.max(SHOT_DURATION_MIN, Math.trunc(d)));
- }
- // 若本次修改了台词或时长,同样做「台词字数 ≤ 时长×5」校验
- if (args.dialogue != null || args.duration != null) {
- // 时长缺省值与 db 层 / 外部写入 API 同一份(SHOT_DURATION_DEFAULT):原先这里写死 8,
- // 与 SHOT_DURATION_DEFAULT=5 漂移 —— 历史行 duration 为空时,两条写入路径按不同的上限判台词。
- const dur = patch.duration != null ? patch.duration : (Number(shot.duration) > 0 ? Number(shot.duration) : SHOT_DURATION_DEFAULT);
- const chars = (patch.dialogue != null ? patch.dialogue : (shot.dialogue || '')).length;
- if (chars && chars / dur > SHOT_DIALOGUE_MAX_RATE) {
- throw new Error('台词与时长不匹配:中文旁白约 4-5 字/秒,当前 ' + chars + ' 字 / ' + dur + ' 秒(上限 ' + Math.floor(dur * SHOT_DIALOGUE_MAX_RATE) + ' 字)超速,会被压缩成听不清的模糊声。请缩短台词或延长时长。');
- }
- }
- // 若本次修改了台词,校验说话人数 ≤ MAX_SPEAKERS_PER_SHOT(多人对话需拆镜)
- if (args.dialogue != null) {
- const speakers = dialogueSpeakerNames(patch.dialogue);
- if (speakers.length > MAX_SPEAKERS_PER_SHOT) {
- throw new Error('分镜对话人数过多:每个分镜最多 ' + MAX_SPEAKERS_PER_SHOT + ' 个说话人,请拆成多个分镜。当前说话人:' + speakers.join('、'));
- }
- }
- Shots.update(args.shot_id, patch);
- return '已更新分镜';
- }
- function shotImageAbsPaths(ctx, shot) {
- const assets = Assets.list(ctx.projectId);
- const byId = (id) => assets.find((x) => x.id === id);
- const ids = [...(shot.character_ids || []), ...(shot.scene_ids || []), ...(shot.prop_ids || []), ...(shot.costume_ids || [])];
- return ids.map(byId).filter(Boolean).map((a) => resolveProjectPath(ctx.projectId, a.image_path)).filter(Boolean);
- }
- const REF_PLACEHOLDER_RE = /__MINIMAX_H3_REF_\d+__/g;
- // 基于用户反馈重写视频提示词。要求 LLM 输出「完整重写结果」,并做三项校验:
- // 非空、未被截断(finish_reason !== 'length')、保留原提示词里的全部 __MINIMAX_H3_REF_N__ 占位符。
- // 任一不满足:用更严格的指令重试一次;仍不满足则抛错——绝不把半截/丢参考的结果覆盖进资产。
- // (实测踩坑:长提示词被模型摘缩成一句,REF_2/REF_3 全丢,视频随后「对不上」。)
- async function rewritePromptWithFeedback(ctx, basePrompt, feedback, imageAbsPaths) {
- // 本批禁用 LLM(渲染 job / 渲染阶段):不允许在渲染过程中拉起 LLM 抢显存。
- // 反馈改写是「可选 LLM 步骤」,此时要求走纯 LLM 批次改写后再渲染。
- if (ctx.llmDisabled) {
- throw new Error('本批已禁用 LLM(渲染批次):不能调用 LLM 改写提示词。请先用「仅 LLM 改写」批次改写,再渲染;或去掉反馈直接渲染。');
- }
- const buildMsgs = (strict) => {
- // 改写语言由设置项 llm.rewriteLanguage 决定(same=与原提示词一致 / zh / en)
- const lang = { same: '保持与原提示词相同的语言', zh: '用中文输出', en: '用英文输出' }[ctx.cfg.llm?.rewriteLanguage] || '保持与原提示词相同的语言';
- const sys = '你是视频提示词改写助手。基于原提示词与用户反馈,输出改写后的完整提示词(' + lang + ',保留 __MINIMAX_H3_REF_N__ 占位符与参考标签不变)。只输出提示词文本。'
- + (strict ? '必须完整保留原提示词的全部信息(镜头、画面、时间轴、声音、结尾约束)与所有 __MINIMAX_H3_REF_N__ 占位符,不得缩写、不得只写开头。' : '');
- const msgs = [{ role: 'system', content: sys }];
- if (visionEnabled(ctx)) {
- const dataUrls = imagesFromPaths(imageAbsPaths, 9).map((i) => 'data:' + i.mimeType + ';base64,' + i.data);
- msgs.push(buildVisionUserMessage('原提示词:\n' + basePrompt + '\n\n反馈:' + feedback + '\n\n(附该分镜参考图,供改写参考)', dataUrls));
- } else {
- msgs.push({ role: 'user', content: '原提示词:\n' + basePrompt + '\n\n反馈:' + feedback });
- }
- return msgs;
- };
- const want = new Set(String(basePrompt).match(REF_PLACEHOLDER_RE) || []);
- // 改写最大输出 token 由设置项决定(默认 4000):思考型模型的 reasoning 与正文共用该预算,
- // 预算不足时正文刚开头就被截断(改写只剩一两句、丢参考占位符)→ 视频画面对不上。
- const maxTokens = Math.max(256, Number(ctx.cfg.llm?.rewriteMaxTokens) || 4000);
- let reason = '未知原因';
- for (let attempt = 0; attempt < 2; attempt++) {
- const r = await llmChat(ctx.cfg.llm, buildMsgs(attempt > 0), { temperature: attempt > 0 ? 0.4 : 0.6, maxTokens });
- const out = String(r.content || '').trim();
- if (!out) { reason = 'LLM 返回为空'; continue; }
- if (r.finishReason === 'length') { reason = 'LLM 输出被截断(达到长度上限)'; continue; }
- const got = new Set(out.match(REF_PLACEHOLDER_RE) || []);
- const missing = [...want].filter((x) => !got.has(x));
- if (missing.length) { reason = 'LLM 改写丢失参考占位符 ' + missing.join('、'); continue; }
- return out;
- }
- throw new Error('LLM 改写提示词不可用(' + reason + '),已保留原提示词。请重试。');
- }
- // 视频任务的显存释放计数已上移到 workflow-runner.maybeFreeComfy(runWorkflow 统一出口),
- // 覆盖全部 ComfyUI 生成(文生图/图生图/换装/音色/视频),不再局限视频。
- // 准备单个分镜的渲染参数:组装参考素材 + 计算提示词/工作流/分辨率等,不写状态、不提交渲染。
- // render=false(仅 LLM 改写)时直接落库并返回 { done };否则返回渲染所需的 prepared 对象。
- async function prepareShotForRender(ctx, shotId, { feedback, render = true } = {}) {
- const shot = Shots.get(shotId);
- if (!shot || shot.project_id !== ctx.projectId) throw new Error('分镜不存在');
- const assets = Assets.list(ctx.projectId);
- // 文生视频(mode='text')不连接任何媒体节点:跳过参考素材组装(assembleShotReferences 会因
- // 「至少 1 张参考图」抛错),references 留空、不绑定 media_*。
- // 首尾帧(mode='first_last'):使用用户在「插入自定义分镜」时上传的首帧+尾帧两张图 + 视频提示词跑 FL2VA。
- // 非文生/首尾帧路径:render=false(仅 LLM 改写提示词)走纯文本,upload=false 不上传参考文件,
- // 但仍解析参考标签供 fallbackVideoPrompt 生成 __MINIMAX_H3_REF_N__ 占位符。
- const isText = shot.mode === 'text';
- const isFirstLast = shot.mode === 'first_last';
- const isImage = shot.mode === 'image';
- let references, characterName, characterDesc, sceneDesc, unmatchedSpeakers;
- if (isText) {
- ({ references, characterName, characterDesc, sceneDesc, unmatchedSpeakers } = { references: [], characterName: '', characterDesc: '', sceneDesc: '', unmatchedSpeakers: [] });
- } else if (isFirstLast) {
- ({ references, characterName, characterDesc, sceneDesc, unmatchedSpeakers } = { references: [], characterName: '', characterDesc: '', sceneDesc: '', unmatchedSpeakers: [] });
- if (render !== false) {
- const firstRel = shot.first_frame_path;
- const lastRel = shot.last_frame_path;
- if (!firstRel || !lastRel) throw new Error('首尾帧模式需要先上传首帧和尾帧两张图片(在「插入自定义分镜」时上传)');
- const firstName = await uploadTaskInput(ctx.cfg, resolveProjectPath(ctx.projectId, firstRel), 'ic_' + ctx.projectId.slice(0, 8) + '_frame_first_' + uid().slice(0, 8) + '.png');
- const lastName = await uploadTaskInput(ctx.cfg, resolveProjectPath(ctx.projectId, lastRel), 'ic_' + ctx.projectId.slice(0, 8) + '_frame_last_' + uid().slice(0, 8) + '.png');
- references = [
- { type: 'image', filename: firstName, label: '首帧' },
- { type: 'image', filename: lastName, label: '尾帧' },
- ];
- }
- } else if (isImage && shot.reference_image_path) {
- // 图生视频:使用用户在「插入自定义分镜」时上传的 1 张参考图
- ({ references, characterName, characterDesc, sceneDesc, unmatchedSpeakers } = { references: [], characterName: '', characterDesc: '', sceneDesc: '', unmatchedSpeakers: [] });
- if (render !== false) {
- const rel = shot.reference_image_path;
- const abs = resolveProjectPath(ctx.projectId, rel);
- if (!abs || !fs.existsSync(abs)) throw new Error('图生视频参考图不存在,请重新上传(在「插入自定义分镜」时上传)');
- const name = await uploadTaskInput(ctx.cfg, abs, 'ic_' + ctx.projectId.slice(0, 8) + '_img_' + uid().slice(0, 8) + '.png');
- references = [{ type: 'image', filename: name, label: '参考图' }];
- }
- } else {
- ({ references, characterName, characterDesc, sceneDesc, unmatchedSpeakers } = await assembleShotReferences({ cfg: ctx.cfg, project: ctx.project, shot, assets, upload: render !== false }));
- }
- // 对白说话人没匹配到本镜角色(如「李雷,韩梅梅:台词」这类一行多说话人标签)→ 音色被静默跳过,
- // 用户只会看到「这一镜没声音」。上报一条可读提示到运行日志,别让它无声无息。
- if (unmatchedSpeakers && unmatchedSpeakers.length) {
- ctx.report({ phase: '参考素材', detail: '对白说话人未匹配到本镜角色,音色不会被引用:' + unmatchedSpeakers.join('、') + '(每行台词只写一个说话人,多个说话人拆成多行/多镜)' });
- }
- const timeErr = validateSubShots(shot.duration, shot.sub_shots);
- if (timeErr) throw new Error(timeErr);
- const base = shot.video_prompt || fallbackVideoPrompt({ references, style: ctx.project.style, characterDesc, sceneDesc, subShots: shot.sub_shots, camera: shot.camera, visual: shot.visual, dialogue: shot.dialogue, characterName });
- const prompt = feedback ? await rewritePromptWithFeedback(ctx, base, feedback, shotImageAbsPaths(ctx, shot)) : base;
- // render=false:只做 LLM 改写提示词,不提交 ComfyUI(改写结果落库,供用户复核后再渲染)
- if (render === false) {
- if (!feedback) throw new Error('仅 LLM 改写模式需要反馈文字');
- Shots.update(shot.id, { video_prompt: prompt, error: '' });
- ctx.report({ phase: '分镜提示词', detail: 'LLM 改写完成(未渲染)分镜 ' + shot.idx });
- return { done: JSON.stringify({ shot_id: shot.id, idx: shot.idx, video_prompt: prompt, rendered: false }) };
- }
- // 实际写入节点 2.mode:显式指定且在值域内则直用;未指定/空串走确定性推断兜底
- // (text 经 spec 的 mode.map 映射成节点 image = 文生,不连媒体)。
- const mode = (shot.mode && VIDEO_MODES.includes(shot.mode)) ? shot.mode : inferVideoMode(references);
- // 图生/首尾帧(image)只接受图片,不接受音/视频:否则媒体槽绑定与 mode=image 语义矛盾
- if (mode === 'image' && references.some((r) => r.type === 'audio' || r.type === 'video')) {
- throw new Error('image 模式(图生/首尾帧)只接受 0~2 张图片,不能携带音频/视频参考');
- }
- // 尺寸以项目当前设置为权威(项目改了 9:16 后,旧分镜快照里的 16:9 不应再生效,否则同章会混入不同尺寸)。
- const reso = ctx.project.video_resolution || shot.resolution || '480P';
- const ratio = ctx.project.video_aspect_ratio || shot.aspect_ratio || '16:9';
- // 按分辨率选工作流:>768P 用二次采样超分(首遍 768P + mode.scale),≤768P 用普通 r2v
- const { spec, scale, resolution: wfResolution } = getR2vSpecForResolution(ctx.cfg, reso, mode, references.filter((r) => r.type === 'image').length);
- // 单个分镜生成 N 条候选视频(设置 → generation.videosPerShot,默认 1),用不同 seed 各渲染一条,
- // 用户随后在分镜审查页勾选一条优质候选用于导出成片。N 上限 10 防误配置爆炸。
- const shotsN = Math.max(1, Math.min(10, Math.floor(Number(ctx.cfg?.generation?.videosPerShot) || 1)));
- return { shot, prompt, mode, spec, reso, ratio, scale, wfResolution, shotsN, references, prevStatus: shot.status, prevVideo: shot.video_path };
- }
- // 渲染单个候选视频(候选 idx,追加模式下从旧候选之后续接),成功返回 { id, idx, video_path, seed };失败抛错。
- async function renderShotCandidate(ctx, prepared, idx) {
- const { shot, prompt, mode, spec, reso, ratio, references, scale, wfResolution } = prepared;
- const seed = randomSeed();
- const prefix = 'video/' + ctx.projectId.slice(0, 8) + '_shot' + shot.idx + '_' + uid().slice(0, 6);
- const wfParams = {
- positive_prompt: prompt,
- seconds: shot.duration || 5,
- aspect_ratio: ratio,
- resolution: wfResolution,
- mode,
- seed, filename_prefix: prefix, references,
- };
- if (scale) wfParams.scale = scale;
- // 自定义分辨率:resolution 固定为 custom,宽高取自项目配置
- if (reso === 'custom') {
- wfParams.width = Number(ctx.project.video_width) || 1024;
- wfParams.height = Number(ctx.project.video_height) || 576;
- }
- const { outputs, prompt_id } = await runWorkflow(ctx.cfg, spec, wfParams, { jobId: ctx.jobId, unitId: 'shot:' + shot.id + ':cand:' + idx, projectId: ctx.projectId, chapter: shot.chapter || '', subject: '第' + shot.idx + '镜', dedupeKey: 'shot:' + shot.id + ':cand:' + idx, timeoutMs: VID_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, onSubmitted: (pid) => Shots.update(shot.id, { prompt_id: pid }), onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); if (s.kind === 'waiting_release') ctx.report({ phase: '等待云端释放', detail: s.message }); } });
- const vid = pickOutput(outputs, 'videos');
- if (!vid) throw new Error('视频工作流未返回视频文件');
- const ext = path.extname(vid.filename) || '.mp4';
- const relPath = 'shots/shot' + shot.idx + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, vid, relPath);
- const sv = ShotVideos.create(ctx.projectId, shot.id, { idx, video_path: relPath, seed });
- Shots.update(shot.id, { seed, prompt_id: prompt_id || '' });
- return { id: sv.id, idx, video_path: relPath, seed };
- }
- // 收尾一个分镜:有候选则确定导出用候选、标 done;无候选按取消/失败复位。
- // 成功返回结果对象;无候选时抛错(中断或失败)。
- function finalizeShot(ctx, prepared, created, { aborted, interrupted, lastErr, append = false }) {
- const { shot, prompt, prevStatus, prevVideo } = prepared;
- if (created.length) {
- created.sort((a, b) => a.idx - b.idx); // 并发完成顺序不定,按候选序取第一条保证「默认选第一条」
- // 追加候选:保留用户之前勾选的候选(若有),否则选新增的第一条;替换/首次:默认选第一条。
- const keepSelected = append ? ShotVideos.selectedForShot(shot.id) : null;
- const first = keepSelected || created[0];
- ShotVideos.setSelected(shot.id, first.id);
- Shots.update(shot.id, { video_path: first.video_path, status: 'done', video_prompt_used: prompt, error: '', prompt_id: '' });
- return { shot_id: shot.id, idx: shot.idx, video_path: first.video_path, count: created.length };
- }
- if (aborted || interrupted) {
- if (prevStatus === 'done' && prevVideo) Shots.update(shot.id, { status: 'done', video_path: prevVideo, error: '' });
- else Shots.update(shot.id, { status: 'pending', video_path: prevVideo || '', error: '' });
- } else {
- Shots.update(shot.id, { status: 'failed', error: (lastErr && lastErr.message) ? lastErr.message : String(lastErr || '生成失败'), video_path: prevVideo || '' });
- }
- throw lastErr || new Error(interrupted ? '生成已中断' : '生成失败');
- }
- // 单个分镜生成 N 条候选(单镜工具 / 重生成入口):串行渲染该镜的 N 条候选。
- // append=true 时「追加为新候选」——保留旧候选、新候选 idx 续接,用于「生成候选」按钮;
- // append=false(默认)时「替换整批候选」——清掉旧候选、idx 从 0 起。
- async function generateShotVideo(ctx, shotId, { feedback, render = true, append = false } = {}) {
- const prepared = await prepareShotForRender(ctx, shotId, { feedback, render });
- if (prepared.done) return prepared.done;
- const { shot, prompt, reso, ratio, shotsN } = prepared;
- // 依赖闸门(与 hGenerateChapterVideos 的 pendingShotAssets 同口径):单镜直跑也不得在
- // 依赖资产(角色/场景/道具/服装/年龄)未生成完成时开渲染。否则 LLM Agent 会绕过
- // generate_chapter_videos 逐镜调用 generate_shot_video,导致「素材没生成完就出视频」。
- if (prepared.mode !== 'text') {
- const byId = new Map(Assets.list(ctx.projectId).map((a) => [a.id, a]));
- const pending = pendingShotAssets(ctx, shot, byId);
- if (pending.length) {
- throw new Error('分镜 ' + shot.idx + ' 依赖的资产尚未生成完成,请先生成资产图/服装再生成视频:' + pending.join('、'));
- }
- }
- const baseIdx = append ? ShotVideos.listByShot(shot.id).length : 0;
- Shots.update(shot.id, { status: 'generating', video_prompt: prompt, seed: 0, resolution: reso, aspect_ratio: ratio, error: '', prompt_id: '' });
- ctx.report({ phase: '分镜视频', detail: (append ? '追加候选 ' : '生成分镜 ') + shot.idx + (feedback ? '(重生成)' : '') + (shotsN > 1 ? ' ×' + shotsN + ' 条候选' : '') });
- // 追加模式保留旧候选;替换模式清空旧候选(旧候选磁盘文件按现状自然遗留)
- if (!append) ShotVideos.deleteByShot(shot.id);
- const created = [];
- let aborted = false;
- let interrupted = false;
- let lastErr = null;
- for (let i = 0; i < shotsN; i++) {
- if (aborted || interrupted || (ctx.isAborted && ctx.isAborted())) { aborted = true; break; }
- try {
- created.push(await renderShotCandidate(ctx, prepared, baseIdx + i));
- } catch (e) {
- if (ctx.isAborted && ctx.isAborted()) { aborted = true; break; }
- if (e && e.interrupted) { interrupted = true; lastErr = e; break; }
- lastErr = e;
- ctx.report({ phase: '分镜视频', detail: '分镜 ' + shot.idx + ' 候选 ' + (i + 1) + '/' + shotsN + ' 失败:' + (e && e.message ? e.message : String(e)) });
- }
- }
- if (created.length) return JSON.stringify(finalizeShot(ctx, prepared, created, { aborted, interrupted, lastErr, append }));
- finalizeShot(ctx, prepared, created, { aborted, interrupted, lastErr, append }); // 无候选 → 抛错
- }
- async function hGenerateShotVideo(ctx, args) { return generateShotVideo(ctx, args.shot_id); }
- async function hRegenerateShot(ctx, args) { return generateShotVideo(ctx, args.shot_id, { feedback: args.feedback, render: args.render !== false, append: !!args.append }); }
- // 给分镜写视频提示词:按 h3-prompt-writing 技能规范,由 LLM 依据本镜画面/台词/参考素材
- // 生成一条完整的 MiniMax H3 提示词(含 __MINIMAX_H3_REF_N__ 占位符),写回 shot.video_prompt。
- // 主要用途:手工插入的自定义分镜不填提示词时,让 Agent 按技能自动补全。
- const REF_PLACEHOLDER_RE_G = /__MINIMAX_H3_REF_\d+__/g;
- async function writeShotVideoPrompt(ctx, shotId) {
- const shot = Shots.get(shotId);
- if (!shot || shot.project_id !== ctx.projectId) throw new Error('分镜不存在');
- if (ctx.llmDisabled) throw new Error('本批已禁用 LLM(渲染批次):不能生成提示词。请在渲染之外的批次里生成。');
- const assets = Assets.list(ctx.projectId);
- // 只解析参考素材(不上传):占位符必须与真正会绑定的媒体顺序一致,否则提示词里引用的
- // __MINIMAX_H3_REF_N__ 会和实际传入的图/音对不上。
- const isText = shot.mode === 'text';
- const { references, characterDesc, sceneDesc } = isText
- ? { references: [], characterDesc: '', sceneDesc: '' }
- : await assembleShotReferences({ cfg: ctx.cfg, project: ctx.project, shot, assets, upload: false });
- const skill = loadSkillWithResources('h3-prompt-writing');
- const skillText = skill ? renderSkillContent({ ...skill, references: [] }) : '';
- const refLines = references.map((r, i) => '__MINIMAX_H3_REF_' + (i + 1) + '__ = ' + (r.type === 'audio' ? '音色:' : '图片:') + (r.label || '参考素材'));
- const sys = [
- skillText,
- '你是视频提示词撰写助手:严格按上面的技能规范,为一条 MiniMax H3 分镜写「完整的视频提示词」。',
- '要求:只输出提示词正文,不要任何解释、标题或 Markdown 围栏;',
- '参考素材按给出的顺序编号,必须逐个用 __MINIMAX_H3_REF_N__ 引用,不得新造编号;',
- '不要写任何画外字幕/水印/logo 要求。',
- ].filter(Boolean).join('\n\n');
- const user = [
- '项目风格:' + (ctx.project.style || '未指定'),
- '时长:' + (shot.duration || 5) + ' 秒',
- shot.scene_name ? '场景名:' + shot.scene_name : '',
- shot.camera ? '镜头:' + shot.camera : '',
- shot.visual ? '画面:' + shot.visual : '',
- shot.dialogue ? '台词:' + shot.dialogue : '',
- shot.sub_shots ? '子镜头时间轴:' + shot.sub_shots : '',
- characterDesc ? '角色一致性:' + characterDesc : '',
- sceneDesc ? '场景一致性:' + sceneDesc : '',
- refLines.length ? '参考素材(顺序固定):\n' + refLines.join('\n') : '参考素材:无(纯文生视频,不要写任何 __MINIMAX_H3_REF_N__ 占位符)',
- ].filter(Boolean).join('\n');
- const maxTokens = Math.max(512, Number(ctx.cfg.llm?.rewriteMaxTokens) || 4000);
- const want = new Set(refLines.map((l) => l.split(' =')[0]));
- let reason = '未知原因';
- for (let attempt = 0; attempt < 2; attempt++) {
- const r = await llmChat(ctx.cfg.llm, [{ role: 'system', content: sys }, { role: 'user', content: user }], {
- temperature: attempt > 0 ? 0.4 : 0.7,
- maxTokens,
- });
- const out = String(r.content || '').trim().replace(/^```[a-z]*\n?|```$/g, '').trim();
- if (!out) { reason = 'LLM 返回为空'; continue; }
- if (r.finishReason === 'length') { reason = 'LLM 输出被截断(达到长度上限)'; continue; }
- const got = new Set(out.match(REF_PLACEHOLDER_RE_G) || []);
- const missing = [...want].filter((x) => !got.has(x));
- if (missing.length) { reason = 'LLM 未引用参考占位符 ' + missing.join('、'); continue; }
- Shots.update(shot.id, { video_prompt: out, error: '' });
- ctx.report({ phase: '分镜提示词', detail: '已生成分镜 ' + shot.idx + ' 的视频提示词' });
- return JSON.stringify({ shot_id: shot.id, idx: shot.idx, video_prompt: out, refs: references.length });
- }
- throw new Error('生成视频提示词失败(' + reason + '),分镜 ' + shot.idx + ' 的提示词未改动。');
- }
- async function hWriteShotVideoPrompt(ctx, args) { return writeShotVideoPrompt(ctx, args.shot_id); }
- // 镜头依赖判定:镜头引用的角色/场景/道具(含服装/年龄变体)必须**已经生成完成**,
- // 该镜头才能进渲染队列。只统计「能解析到资产」的引用——悬空 id 不阻塞
- // (参考图组装时会直接跳过它,阻塞一个永远补不上的依赖没有意义)。
- function pendingShotAssets(ctx, shot, byId) {
- const pending = [];
- const check = (ids, label) => {
- for (const id of ids || []) {
- const a = byId.get(id);
- if (!a) continue;
- const done = a.status === 'done' && a.image_path && fs.existsSync(resolveProjectPath(ctx.projectId, a.image_path));
- if (!done) pending.push((a.name || a.id) + '·' + label);
- }
- };
- check(shot.character_ids, '角色');
- check(shot.scene_ids, '场景');
- check(shot.prop_ids, '道具');
- check(shot.costume_ids, '服装');
- check(shot.age_ids, '年龄');
- return pending;
- }
- async function hGenerateChapterVideos(ctx, args) {
- // chapter 与 set_chapter_music 统一走 chapterByRef:标题或 id 都认(get_project / list_chapters
- // 同时给出两者,模型传哪个都得对)。之前只按标题过滤分镜,模型传章节 id 时会静默返回
- // 「本章没有分镜」——一个看似正常的空结果,任务却什么都没做。
- const title = chapterByRef(ctx, args && args.chapter).title;
- const force = !!(args && args.force);
- const all = Shots.list(ctx.projectId).filter((s) => s.chapter === title);
- if (!all.length) return JSON.stringify({ chapter: title, total: 0, generated: 0, remaining: 0, note: '本章没有分镜' });
- // 未指定 force 时跳过「已出片且视频提示词未变过」的镜头;提示词被改写(如「仅 LLM 改写」)过就重渲染
- const target = force ? all : all.filter((s) => s.status !== 'done' || (s.video_prompt_used || '') !== (s.video_prompt || ''));
- const runCount = target.length;
- // 依赖感知调度:先把「引用的资产都已完成」的镜头挑出来,其余等待。
- // 章节视频无论本地 ComfyUI 还是云端 RunningHub,都按 idx 升序**逐镜串行**(见下方 runOne),
- // 否则每个分镜都会在抢槽前就被标成 generating,界面看起来像全部并发生成、顺序也乱。
- const byId = new Map(Assets.list(ctx.projectId).map((a) => [a.id, a]));
- const readiness = target.map((shot) => ({ shot, pending: pendingShotAssets(ctx, shot, byId) }));
- const ready = readiness.filter((r) => r.pending.length === 0).map((r) => r.shot);
- const waiting = readiness.filter((r) => r.pending.length > 0);
- if (waiting.length) {
- const sample = waiting.slice(0, 3).map((r) => '第' + r.shot.idx + '镜←' + r.pending.join('/')).join(';');
- ctx.report({ phase: '分镜视频', detail: '暂缓 ' + waiting.length + ' 镜(依赖资产未完成):' + sample + (waiting.length > 3 ? ' …' : '') });
- }
- if (!ready.length) {
- return JSON.stringify({
- chapter: title, total: all.length, generated: 0, failed: 0,
- remaining: all.filter((s) => s.status !== 'done').length,
- deferred: waiting.length,
- note: '本章所有待生成镜头都还有未完成的依赖资产,请先生成资产图/服装后再重试',
- });
- }
- // 1) 先为所有就绪分镜组装参考素材 / 提示词(prepare 只计算,不写状态、不提交渲染),
- // 这样候选渲染的「全局顺序」由下方队列决定,不受各镜参考图上传耗时影响。
- const preparedList = [];
- for (const s of ready) {
- if (ctx.isAborted && ctx.isAborted()) break;
- preparedList.push(await prepareShotForRender(ctx, s.id, {}));
- }
- // 2) 按分镜 idx 顺序逐镜生成:一个分镜的候选全部结束后,才开始下一镜。
- // 同一镜的候选可以并发(最多 limit 条),但不会让第 2 镜抢到第 1 镜前面。
- const limit = renderConcurrencyLimit(ctx.cfg);
- ctx.report({ phase: '分镜视频', detail: '按分镜顺序生成 ' + ready.length + '/' + runCount + ' 镜(每镜候选 ' + (preparedList[0]?.shotsN || 1) + ',并发 ' + limit + ')' });
- const started = new Set(); // 已标 generating 并清掉旧候选的分镜
- const okByShot = new Map(); // shotId -> [{id,idx,video_path,seed}]
- const errByShot = new Map(); // shotId -> [Error]
- const finalized = new Set(); // 已收尾的分镜
- let ok = 0, fail = 0, aborted = false;
- // 收尾单个分镜:有候选 → done 并默认选第一条;无候选 → 按取消/失败复位。
- const finalizeOne = (prepared) => {
- const shot = prepared.shot;
- const created = (okByShot.get(shot.id) || []).sort((a, b) => a.idx - b.idx);
- const errs = errByShot.get(shot.id) || [];
- if (created.length) {
- finalizeShot(ctx, prepared, created, { aborted: false, interrupted: false, lastErr: errs[0] || null });
- ok++;
- ctx.report({ phase: '分镜视频', detail: '已完成 ' + (ok + fail) + '/' + preparedList.length + ' 镜(成功 ' + ok + ' / 失败 ' + fail + ')' });
- } else if (aborted) {
- // 被停止/中断:只有真正进入过渲染(标过 generating)的分镜才复位;从未开始的分镜保持原状。
- if (started.has(shot.id)) {
- if (prepared.prevStatus === 'done' && prepared.prevVideo) Shots.update(shot.id, { status: 'done', video_path: prepared.prevVideo, error: '' });
- else Shots.update(shot.id, { status: 'pending', video_path: prepared.prevVideo || '', error: '' });
- }
- } else {
- fail++;
- Shots.update(shot.id, { status: 'failed', error: (errs[0] && errs[0].message) ? errs[0].message : '生成失败', video_path: prepared.prevVideo || '' });
- ctx.report({ phase: '分镜视频', detail: '第' + shot.idx + '镜失败:' + ((errs[0] && errs[0].message) || '生成失败') });
- }
- };
- for (const prepared of preparedList) {
- if (aborted || (ctx.isAborted && ctx.isAborted())) { aborted = true; break; }
- const shot = prepared.shot;
- started.add(shot.id);
- // 分镜进入渲染时才标 generating(并清掉上一版候选),「生成中」只落在真正在跑的分镜上。
- Shots.update(shot.id, { status: 'generating', video_prompt: prepared.prompt, seed: 0, resolution: prepared.reso, aspect_ratio: prepared.ratio, error: '', prompt_id: '' });
- ctx.report({ phase: '分镜视频', detail: '生成 ' + shot.idx + '/' + runCount + (prepared.shotsN > 1 ? '(×' + prepared.shotsN + ' 候选)' : '') });
- ShotVideos.deleteByShot(shot.id);
- const created = [];
- const errs = [];
- let next = 0;
- const worker = async () => {
- while (true) {
- const i = next++;
- if (i >= prepared.shotsN || aborted) break;
- if (ctx.isAborted && ctx.isAborted()) { aborted = true; break; }
- try {
- created.push(await renderShotCandidate(ctx, prepared, i));
- } catch (e) {
- if (ctx.isAborted && ctx.isAborted()) { aborted = true; break; }
- if (e && e.interrupted) { aborted = true; break; }
- errs.push(e);
- ctx.report({ phase: '分镜视频', detail: '分镜 ' + shot.idx + ' 候选 ' + (i + 1) + '/' + prepared.shotsN + ' 失败:' + (e && e.message ? e.message : String(e)) });
- }
- }
- };
- // 同一镜的候选并行度不超过配置的渲染并发;不同分镜之间严格串行。
- await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, prepared.shotsN)) }, () => worker()));
- okByShot.set(shot.id, created);
- errByShot.set(shot.id, errs);
- finalized.add(shot.id);
- finalizeOne(prepared);
- if (aborted) break;
- }
- // 被停止/中断时,有分镜的候选没跑满(worker 提前 break),这里兜底收尾:
- // 有成功候选 → done;无成功候选且进入过渲染 → 复位;从未渲染 → 保持原状。
- for (const p of preparedList) {
- if (finalized.has(p.shot.id)) continue;
- finalized.add(p.shot.id);
- finalizeOne(p);
- }
- const remaining = Shots.list(ctx.projectId).filter((s) => s.chapter === title && s.status !== 'done').length;
- const base = { chapter: title, total: all.length, generated: ok, failed: fail, remaining };
- if (aborted) return JSON.stringify({ ...base, aborted: true });
- if (waiting.length) return JSON.stringify({ ...base, deferred: waiting.length, note: '有 ' + waiting.length + ' 镜因依赖资产未完成而暂缓' });
- return JSON.stringify(base);
- }
- async function hAssembleVideo(ctx, args) {
- // 只有显式传了 chapter 才按章合并(不传 = 整片合并,沿用原行为);
- // 章节引用同样支持标题或 id —— 之前过滤分镜只按标题、找 BGM 却按「标题或 id」,
- // 传 id 时会报「章节没有已完成的分镜视频」,而该章其实有片子。
- const ch = (args && args.chapter) ? chapterByRef(ctx, args.chapter) : null;
- const chapter = ch ? ch.title : '';
- // 顺序:先章节 seq 再章内 idx(多章合并时按全局 idx 会交叉成「第1章第1镜、第2章第1镜…」)
- let done = Shots.listInNarrativeOrder(ctx.projectId).filter((s) => s.video_path && s.status === 'done');
- if (chapter) done = done.filter((s) => s.chapter === chapter);
- if (!done.length) throw new Error(chapter ? ('章节「' + chapter + '」没有已完成的分镜视频') : '没有已完成的分镜视频');
- const inputs = done.map((s) => resolveProjectPath(ctx.projectId, s.video_path)).filter(Boolean);
- const base = chapter ? slugify(ctx.project.name) + '_' + slugify(chapter) : slugify(ctx.project.name);
- const outRel = 'exports/' + base + '_' + uid().slice(0, 8) + '.mp4';
- const outAbs = resolveProjectPath(ctx.projectId, outRel);
- // 背景音乐:仅按章合并时,把该章已生成的 BGM 垫底混入
- let music;
- if (ch) {
- const musicAbs = ch.music_path ? resolveProjectPath(ctx.projectId, ch.music_path) : null;
- if (musicAbs && fs.existsSync(musicAbs)) music = { path: musicAbs, volume: 0.25 };
- }
- ctx.report({ phase: '导出', detail: '合并 ' + inputs.length + ' 段视频' + (music ? '(垫入背景音乐)' : '') });
- // 字幕:项目开启「自动添加字幕」时,按设置页选的模式生成——
- // script(经典,默认)用分镜台词/旁白,零依赖;whisper 用成片音轨识别,失败自动回退台词。
- // 字幕是烧进画面的,无法从成片里再去掉 → 同时单独合一份不带字幕的版本,供下载时二选一。
- let subtitles = '';
- if (ctx.project.enable_subtitles !== false) {
- const r = await resolveSubtitles({
- projectId: ctx.projectId,
- inputs,
- shots: done,
- isAborted: ctx.isAborted,
- onProgress: (d) => ctx.report({ phase: '字幕', detail: d }),
- });
- subtitles = r.srt;
- if (!subtitles && r.mode === 'whisper') {
- ctx.report({ phase: '字幕', detail: r.fallback ? '剧本台词为空,成片不烧录字幕' : '未识别到语音,成片不烧录字幕' });
- }
- }
- const noSubRel = outRel.replace(/(\.[^.]+)$/, '_nosub$1');
- await mergeVideos(inputs, outAbs, { music, isAborted: ctx.isAborted, subtitles });
- let srtRel = '';
- if (subtitles) {
- await mergeVideos(inputs, resolveProjectPath(ctx.projectId, noSubRel), { music, isAborted: ctx.isAborted });
- // 附带一份 SRT 字幕文件:不进成片列表,只作为「下载字幕」按钮的素材
- srtRel = outRel.replace(/\.[^.]+$/, '.srt');
- fs.writeFileSync(resolveProjectPath(ctx.projectId, srtRel), subtitles, 'utf8');
- }
- return JSON.stringify({ export_path: outRel, shots: done.length, chapter: chapter || null, music: !!music, subtitled: !!subtitles, nosub_path: subtitles ? noSubRel : '', srt_path: srtRel });
- }
- function chapterByRef(ctx, ref) {
- const title = String(ref || ctx.chapter || '').trim();
- if (!title) throw new Error('请指定章节 chapter');
- const ch = Chapters.list(ctx.projectId).find((c) => c.title === title || c.id === title);
- if (!ch) throw new Error('章节不存在:' + title);
- return ch;
- }
- async function hSetChapterMusic(ctx, args) {
- const ch = chapterByRef(ctx, args && args.chapter);
- const caption = String((args && args.caption) || '').trim();
- if (!caption) throw new Error('请提供音乐风格描述 caption');
- const lyrics = String((args && args.lyrics) || '').trim();
- const duration = (args && args.duration != null) ? Number(args.duration) : 0;
- Chapters.update(ch.id, { music_prompt: JSON.stringify({ caption, lyrics, duration }) });
- return JSON.stringify({ chapter: ch.title, caption, lyrics, duration });
- }
- async function hGenerateMusic(ctx, args) {
- // 项目设置「是否生成背景音乐」关闭时,自动流水线跳过(音乐库手动生成/应用不受此限制)
- if (ctx.project.enable_bgm === false) {
- return JSON.stringify({ chapter: args && args.chapter, skipped: true, note: '项目已关闭「是否生成背景音乐」' });
- }
- const ch = chapterByRef(ctx, args && args.chapter);
- let prompt = {};
- try { prompt = JSON.parse(ch.music_prompt || '{}'); } catch {}
- const caption = String(prompt.caption || '').trim()
- || ((ctx.project.style || '').trim() ? ctx.project.style + ',轻柔舒缓的背景音乐' : '轻柔舒缓的背景音乐');
- const lyrics = String(prompt.lyrics || '').trim();
- const promptKey = JSON.stringify({ caption, lyrics });
- // 幂等:已生成且提示词未变,直接跳过
- const existingAbs = ch.music_path ? resolveProjectPath(ctx.projectId, ch.music_path) : null;
- if ((ch.music_prompt_used || '') === promptKey && existingAbs && fs.existsSync(existingAbs)) {
- return JSON.stringify({ chapter: ch.title, music_path: ch.music_path, skipped: true });
- }
- const shots = Shots.list(ctx.projectId).filter((s) => s.chapter === ch.title);
- const total = shots.reduce((sum, s) => sum + (Number(s.duration) || 0), 0);
- if (total <= 0) return JSON.stringify({ chapter: ch.title, skipped: true, note: '本章没有分镜,无法确定背景音乐时长' });
- // 时长:优先 LLM 给的 duration,否则该章全部分镜 duration 之和(不封顶)
- const max_duration = Number(prompt.duration) > 0
- ? Math.max(1, Number(prompt.duration))
- : Math.max(1, Math.round(total * 10) / 10);
- const spec = getSpecForKind(ctx.cfg, 'music');
- const prefix = 'music/' + slugify(ctx.project.name) + '_' + slugify(ch.title) + '_' + uid().slice(0, 8);
- ctx.report({ phase: '背景音乐', detail: '生成背景音乐:' + ch.title });
- const { outputs } = await runWorkflow(ctx.cfg, spec, {
- caption, lyrics: lyrics || ' ', max_duration, seed: randomSeed(), filename_prefix: prefix,
- }, { timeoutMs: VID_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, jobId: ctx.jobId, projectId: ctx.projectId, chapter: ch.title, subject: ch.title + ' BGM', dedupeKey: 'music:' + ch.id, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } });
- const aud = pickOutput(outputs, 'audio');
- if (!aud) throw new Error('背景音乐工作流未返回音频');
- const ext = path.extname(aud.filename) || '.mp3';
- const relPath = 'assets/music/' + slugify(ctx.project.name) + '_' + slugify(ch.title) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, aud, relPath);
- Chapters.update(ch.id, { music_path: relPath, music_prompt_used: promptKey });
- // 自动生成的 BGM 也入库「背景音乐库」,便于用户预览/选择(同名复用,见 upsertMusicAsset)
- const assetId = upsertMusicAsset(ctx, ch.title + '背景音乐', { audio_path: relPath, prompt: caption, prompt_used: caption, lyrics, max_duration, source: 'generated', status: 'done' });
- return JSON.stringify({ chapter: ch.title, music_path: relPath, asset_id: assetId, duration: max_duration });
- }
- async function hGenerateMusicAsset(ctx, args) {
- const asset = (args && args.asset_id) ? Assets.get(args.asset_id) : null;
- if (!asset || asset.project_id !== ctx.projectId || asset.category !== 'music') throw new Error('背景音乐资产不存在');
- // 生成用文案:优先用 POST /music 按 music-caption-rewriter 技能预写好的结构化 caption/lyrics
- // (params.caption_rewrite,且其源描述仍与资产 prompt 一致);否则退回资产自身字段。
- const rewrite = (asset.params && asset.params.caption_rewrite) || null;
- const rewriteOk = !!(rewrite && rewrite.caption && String(rewrite.source_caption || '') === String(asset.prompt || '').trim());
- const caption = String((rewriteOk ? rewrite.caption : asset.prompt) || '').trim();
- if (!caption) throw new Error('缺少音乐描述 caption');
- const lyrics = String((rewriteOk ? rewrite.lyrics : asset.lyrics) || '').trim();
- // 时长:优先资产里写好的 max_duration;否则按项目总视频时长(不封顶);未生成视频时默认 60s
- const shots = Shots.list(ctx.projectId);
- const total = shots.reduce((sum, s) => sum + (Number(s.duration) || 0), 0);
- const max_duration = Number(asset.max_duration) > 0
- ? Math.max(1, Number(asset.max_duration))
- : (total > 0 ? Math.max(1, Math.round(total * 10) / 10) : 60);
- const spec = getSpecForKind(ctx.cfg, 'music');
- const prefix = 'music/' + slugify(asset.name) + '_' + uid().slice(0, 8);
- ctx.report({ phase: '背景音乐', detail: '生成背景音乐:' + asset.name });
- Assets.update(asset.id, { status: 'generating' });
- try {
- const { outputs } = await runWorkflow(ctx.cfg, spec, {
- caption, lyrics: lyrics || ' ', max_duration, seed: randomSeed(), filename_prefix: prefix,
- }, { timeoutMs: VID_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, jobId: ctx.jobId, projectId: ctx.projectId, chapter: '', subject: asset.name || asset.id, dedupeKey: 'music-asset:' + asset.id, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } });
- const aud = pickOutput(outputs, 'audio');
- if (!aud) throw new Error('背景音乐工作流未返回音频');
- const ext = path.extname(aud.filename) || '.mp3';
- const relPath = 'assets/music/' + slugify(asset.name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, aud, relPath);
- Assets.update(asset.id, { audio_path: relPath, prompt_used: caption, source: 'generated', status: 'done', error: '' });
- return JSON.stringify({ asset_id: asset.id, name: asset.name, music_path: relPath, duration: max_duration });
- } catch (e) {
- // 失败/被停止时不能把**已有的音频**一起作废:重新生成前资产上那条 audio_path 仍是可用产物
- // (列表里还在播、用户还等着用它「应用到章节」),置成 failed 会让「应用到」直接消失。
- // 与分镜同口径:取消时保留已完成结果,只在确实没有音频时才标失败。
- const aborted = !!(ctx.isAborted && ctx.isAborted());
- if (aborted && asset.audio_path) Assets.update(asset.id, { status: 'done', error: e.message });
- else Assets.update(asset.id, { status: 'failed', error: e.message });
- throw e;
- }
- }
- // 简单模式页(视频生成 / 数字人)的独立视频资产生成:不走分镜流水线,直接以「上传的参考物料 +
- // 模式」跑 r2v 工作流,产物落为 video 资产。数字人 = mode=digital_human(视觉参考 + 单条驱动音频)。
- async function hGenerateVideoAsset(ctx, args) {
- const asset = (args && args.asset_id) ? Assets.get(args.asset_id) : null;
- if (!asset || asset.project_id !== ctx.projectId || asset.category !== 'video') throw new Error('视频资产不存在');
- const mode = String((args && args.mode) || 'reference');
- if (!VIDEO_MODES.includes(mode)) throw new Error('mode 只能是 ' + VIDEO_MODES.join('/') + '(当前:' + mode + ')');
- const prompt = String((args && args.prompt) || asset.prompt || '').trim();
- if (!prompt) throw new Error('缺少视频提示词 prompt');
- // 上传本地物料到渲染后端,得到 ComfyUI 认识的输入文件名(Native=本地名,RunningHub=平台 fileName)
- const refs = Array.isArray(args.references) ? args.references : [];
- const references = [];
- for (const r of refs) {
- const type = r.type === 'audio' || r.type === 'video' ? r.type : 'image';
- const rel = String(r.filename || r.path || '').trim();
- if (!rel) continue;
- const abs = resolveProjectPath(ctx.projectId, rel);
- if (!abs || !fs.existsSync(abs)) throw new Error('参考物料不存在:' + rel);
- const ext = path.extname(abs) || (type === 'audio' ? '.flac' : type === 'video' ? '.mp4' : '.png');
- const name = 'ic_' + ctx.projectId.slice(0, 8) + '_' + type + '_' + uid().slice(0, 8) + ext;
- const filename = await uploadTaskInput(ctx.cfg, abs, name);
- references.push({ type, filename, label: type });
- }
- // 模式与物料组合约束
- const images = references.filter((r) => r.type === 'image').length;
- const audios = references.filter((r) => r.type === 'audio').length;
- const videos = references.filter((r) => r.type === 'video').length;
- if (mode === 'image') {
- if (audios || videos) throw new Error('图生/首尾帧模式只能连接图片(当前混入了音频/视频)');
- if (images < 1 || images > 2) throw new Error('图生/首尾帧模式需 1–2 张图片(当前 ' + images + ' 张)');
- } else if (mode === 'reference') {
- if (images + videos < 1) throw new Error('参考生视频模式至少需要 1 张图片或 1 段视频');
- if (images > 9) throw new Error('参考图片最多 9 张(当前 ' + images + ' 张)');
- if (audios + videos > 3) throw new Error('参考音视频最多 3 段(当前 ' + (audios + videos) + ' 段)');
- } else if (mode === 'digital_human') {
- if (images !== 1) throw new Error('数字人模式需 1 张视觉参考(头像),当前 ' + images + ' 张');
- if (audios !== 1 || videos) throw new Error('数字人模式需且仅需 1 条驱动音频,当前音频 ' + audios + ' / 视频 ' + videos);
- }
- const reso = String((args && args.resolution) || '480P');
- const ratio = String((args && args.aspect_ratio) || '16:9');
- const seconds = Number(args && args.seconds) > 0 ? Number(args.seconds) : 5;
- const { spec, scale, resolution: wfResolution } = getR2vSpecForResolution(ctx.cfg, reso, mode, images);
- const prefix = 'video/' + slugify(asset.name) + '_' + uid().slice(0, 8);
- ctx.report({ phase: '视频生成', detail: '生成视频:' + asset.name + '(' + mode + ')' });
- Assets.update(asset.id, { status: 'generating', prompt });
- try {
- const wfParams = { positive_prompt: prompt, seconds, aspect_ratio: ratio, resolution: wfResolution, seed: randomSeed(), filename_prefix: prefix, references, mode };
- if (scale) wfParams.scale = scale;
- const { outputs } = await runWorkflow(ctx.cfg, spec, wfParams, { jobId: ctx.jobId, timeoutMs: VID_TIMEOUT(ctx.cfg), isAborted: ctx.isAborted, onStatus: (s) => { if (s.kind === 'error') throw new Error(s.message); } });
- const vid = pickOutput(outputs, 'videos');
- if (!vid) throw new Error('视频工作流未返回视频文件');
- const ext = path.extname(vid.filename) || '.mp4';
- const relPath = 'assets/videos/' + slugify(asset.name) + '_' + uid().slice(0, 8) + ext;
- await downloadOutputTo(ctx, vid, relPath);
- Assets.update(asset.id, { video_path: relPath, prompt_used: prompt, source: 'generated', status: 'done' });
- return JSON.stringify({ asset_id: asset.id, name: asset.name, video_path: relPath, mode });
- } catch (e) {
- const aborted = !!(ctx.isAborted && ctx.isAborted());
- if (aborted && asset.video_path) Assets.update(asset.id, { status: 'done' });
- else Assets.update(asset.id, { status: 'failed' });
- throw e;
- }
- }
- async function hApplyChapterMusic(ctx, args) {
- const musicId = args && args.music_id;
- const music = musicId ? Assets.get(musicId) : null;
- if (!music || music.project_id !== ctx.projectId || music.category !== 'music') throw new Error('背景音乐不存在');
- if (!music.audio_path) throw new Error('该背景音乐还没有音频文件');
- const titles = (Array.isArray(args && args.chapters) ? args.chapters : []).filter(Boolean);
- if (!titles.length) throw new Error('请选择要应用的章节');
- const results = [];
- let aborted = false;
- for (const t of titles) {
- // 与 hGenerateChapterVideos 一致:停止后不再继续合并后续章节(每章合并都是一次数十秒的 ffmpeg)
- if (ctx.isAborted && ctx.isAborted()) { aborted = true; break; }
- const ch = Chapters.list(ctx.projectId).find((c) => c.title === t || c.id === t);
- if (!ch) { results.push({ chapter: t, error: '章节不存在' }); continue; }
- const shots = Shots.list(ctx.projectId).filter((s) => s.chapter === ch.title);
- if (!shots.length || shots.some((s) => s.status !== 'done' || !s.video_path)) {
- results.push({ chapter: ch.title, error: '尚未全部生成完成' });
- continue;
- }
- // 单章失败不能中断后续章节:这是批量动作,用户期望「能应用的都应用上,失败的列出来」。
- // 原先一次合并抛错会让后面所有章节都不再处理(前几章已改了 music_path,后面几章连碰都没碰)。
- try {
- Chapters.update(ch.id, { music_path: music.audio_path });
- const r = await hAssembleVideo(ctx, { chapter: ch.title });
- results.push({ chapter: ch.title, applied: true, export_path: JSON.parse(r).export_path });
- } catch (e) {
- results.push({ chapter: ch.title, error: '已写入背景音乐,但合并成片失败:' + e.message });
- }
- }
- // 全失败不能静默返回结果:任务会被记成 done,前端弹「任务完成」、按钮提示「已重新合成成片」,
- // 而用户其实什么都没得到。逐章原因带进错误里(日志/任务详情仍能看到是哪一章、为什么)。
- // aborted 时不抛:用户主动停止属于「取消」,不是失败(与阶段任务的停止语义一致)。
- if (!aborted && results.length && results.every((r) => r.error)) {
- throw new Error('所有章节都未能应用背景音乐:' + results.map((r) => r.chapter + '(' + r.error + ')').join(';'));
- }
- return JSON.stringify({ music_id: musicId, results, aborted });
- }
- async function hListWorkflows() {
- return JSON.stringify(Workflows.list().map((w) => ({ id: w.id, name: w.name, kind: w.kind, sourceFile: w.sourceFile })));
- }
- // ================= opuscar(lemo-opuscar 代码电影)工具 =================
- const OPUSCAR_LIB_ROOT = path.join(SKILLS_DIR, 'lemo-opuscar');
- // 每条影片记录(视频资产)一个独立工作区 film/<assetId>:多条记录互不覆盖,
- // 也让「继续修改」能读回自己上一版的页面代码。无 assetId 时回落到项目级 film/。
- function opuscarFilmDir(ctx) {
- const rel = ctx.assetId ? 'film/' + ctx.assetId : 'film';
- return resolveProjectPath(ctx.projectId, rel);
- }
- function isInsideDir(candidate, root) {
- const rel = path.relative(root, candidate);
- return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel));
- }
- async function hOpuscarInit(ctx) {
- if (!fs.existsSync(OPUSCAR_LIB_ROOT)) throw new Error('lemo-opuscar 技能库不存在:' + OPUSCAR_LIB_ROOT);
- const filmDir = opuscarFilmDir(ctx);
- if (!filmDir) throw new Error('影片工作区路径非法');
- fs.mkdirSync(filmDir, { recursive: true });
- return JSON.stringify({ lib_root: OPUSCAR_LIB_ROOT, film_dir: filmDir });
- }
- function opuscarShellTimeout(ctx) {
- // 视频渲染/合成耗时较长,给足超时(对齐 VID_TIMEOUT 语义),单条命令最长 30 分钟。
- return Number(ctx.cfg?.generation?.videoTimeoutMinutes) > 0
- ? Number(ctx.cfg.generation.videoTimeoutMinutes) * 60 * 1000
- : 30 * 60 * 1000;
- }
- async function hOpuscarShell(ctx, args) {
- const libRoot = OPUSCAR_LIB_ROOT;
- const filmDir = opuscarFilmDir(ctx);
- if (!filmDir) throw new Error('影片工作区路径非法');
- fs.mkdirSync(filmDir, { recursive: true });
- const cwd = args.cwd === 'film' ? filmDir : libRoot;
- const command = String(args.command || '').trim();
- if (!command) throw new Error('command 不能为空');
- if (command.includes('..')) throw new Error('命令含非法路径段 ".."');
- // 命令里出现的绝对路径必须落在 lib_root / film_dir 两个白名单根之内
- const absTokens = command.match(/(?:^|[\s"'=(])(\/[^\s"'=)]+)/g) || [];
- for (const tok of absTokens) {
- const p = tok.replace(/^[\s"'=(]+/, '');
- if (!isInsideDir(p, libRoot) && !isInsideDir(p, filmDir)) {
- throw new Error('命令引用了允许范围之外的绝对路径:' + p);
- }
- }
- const env = { ...process.env, LEMO_LIB: libRoot, LEMO_FILM: filmDir };
- // 用独立进程组执行,停止时整组 SIGKILL —— 只 kill 外层 /bin/sh 会留下 ffmpeg/node 子进程继续跑。
- return await new Promise((resolve, reject) => {
- const child = spawn('/bin/sh', ['-c', command], {
- cwd,
- env,
- detached: true,
- stdio: ['ignore', 'pipe', 'pipe'],
- });
- let stdout = '';
- let stderr = '';
- let done = false;
- let timer = null;
- let abortTimer = null;
- const killGroup = (sig) => {
- try { process.kill(-child.pid, sig); } catch { try { child.kill(sig); } catch { /* 进程已退出 */ } }
- };
- const finish = (payload, err) => {
- if (done) return;
- done = true;
- if (timer) clearTimeout(timer);
- if (abortTimer) clearInterval(abortTimer);
- if (err) reject(err);
- else resolve(JSON.stringify(payload));
- };
- timer = setTimeout(() => {
- killGroup('SIGKILL');
- finish({ code: 124, stdout: stdout.slice(-4000), stderr: stderr.slice(-4000), error: '命令超时' });
- }, opuscarShellTimeout(ctx));
- abortTimer = setInterval(() => {
- if (ctx.isAborted && ctx.isAborted()) {
- killGroup('SIGKILL');
- finish(null, new Error('任务已停止'));
- }
- }, 400);
- child.stdout.on('data', (d) => { stdout += d; if (stdout.length > 8 * 1024 * 1024) stdout = stdout.slice(-4 * 1024 * 1024); });
- child.stderr.on('data', (d) => { stderr += d; if (stderr.length > 8 * 1024 * 1024) stderr = stderr.slice(-4 * 1024 * 1024); });
- child.on('error', (e) => finish({ code: 1, stdout: '', stderr: '', error: String(e.message || e).slice(0, 500) }));
- child.on('close', (code, signal) => finish({
- code: code == null ? 1 : code,
- stdout: stdout.slice(-4000),
- stderr: stderr.slice(-4000),
- error: signal ? '命令被终止:' + signal : '',
- }));
- });
- }
- async function hOpuscarWriteFile(ctx, args) {
- const relPath = String(args.path || '').trim();
- if (!relPath) throw new Error('path 不能为空');
- const abs = resolveProjectPath(ctx.projectId, 'film/' + relPath);
- if (!abs) throw new Error('非法保存路径:' + relPath);
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.writeFileSync(abs, String(args.content ?? ''), 'utf8');
- return '已写入:' + relPath;
- }
- async function hOpuscarReadFile(ctx, args) {
- const relPath = String(args.path || '').trim();
- if (!relPath) throw new Error('path 不能为空');
- const libRoot = OPUSCAR_LIB_ROOT;
- const filmDir = opuscarFilmDir(ctx) || '';
- let abs = path.resolve(libRoot, relPath);
- if (!isInsideDir(abs, libRoot)) abs = path.resolve(filmDir, relPath);
- if (!isInsideDir(abs, libRoot) && !isInsideDir(abs, filmDir)) throw new Error('非法路径:' + relPath);
- if (!fs.existsSync(abs)) throw new Error('文件不存在:' + relPath);
- const content = fs.readFileSync(abs, 'utf8');
- return content.length > 120000 ? content.slice(0, 120000) + '…(截断)' : content;
- }
- async function hOpuscarSaveFilm(ctx, args) {
- const assetId = ctx.assetId;
- if (!assetId) throw new Error('未关联视频资产');
- const asset = Assets.get(assetId);
- if (!asset || asset.project_id !== ctx.projectId) throw new Error('视频资产不存在');
- const filmDir = opuscarFilmDir(ctx);
- if (!filmDir) throw new Error('影片工作区路径非法');
- const candidates = ['out/final.mp4', 'out/video.mp4', 'final.mp4', 'video.mp4'].map((p) => path.join(filmDir, p));
- const src = candidates.find((p) => fs.existsSync(p));
- if (!src) throw new Error('未找到成片文件(已查找 out/final.mp4、out/video.mp4、final.mp4、video.mp4)');
- const name = String(args.name || asset.name || 'film').trim();
- const rel = 'assets/videos/' + slugify(name || 'film') + '_' + uid().slice(0, 8) + '.mp4';
- const abs = resolveProjectPath(ctx.projectId, rel);
- if (!abs) throw new Error('非法输出路径');
- fs.mkdirSync(path.dirname(abs), { recursive: true });
- fs.copyFileSync(src, abs);
- Assets.update(assetId, { status: 'done', video_path: rel, name: name || asset.name });
- return '成片已保存:' + rel;
- }
- // —— 无限・卷轴 handler ——
- function novelRel(relPath) {
- const s = String(relPath || '').trim().replace(/\\/g, '/');
- if (!s) throw new Error('path 不能为空');
- if (path.isAbsolute(s) || s.startsWith('/')) throw new Error('path 禁止绝对路径:' + relPath);
- if (s.includes('..')) throw new Error('path 禁止 ".." 段:' + relPath);
- return s;
- }
- async function hNovelInit(ctx) {
- ensureProjectDirs(ctx.projectId);
- const state = loadNovelState(ctx.projectId);
- const files = listNovelFiles(ctx.projectId);
- return JSON.stringify({
- project_name: ctx.project?.name || '',
- project_idea: ctx.project?.idea || '',
- files,
- has_outline: !!state.structure.outline,
- has_volumes: !!state.structure.volumes,
- has_chapters: !!state.structure.chapters,
- character_count: state.characters.length,
- volume_count: state.volumes.length,
- volumes: state.volumes.map((v) => ({ seq: v.seq, title: v.title, chapterFrom: v.chapterFrom, chapterTo: v.chapterTo })),
- memory_files: state.memory.map((m) => m.name),
- });
- }
- async function hNovelWriteFile(ctx, args) {
- const rp = novelRel(args.path);
- const abs = writeNovelFile(ctx.projectId, rp, String(args.content ?? ''));
- if (!abs) throw new Error('非法保存路径:' + args.path);
- return '已写入:' + rp;
- }
- async function hNovelReadFile(ctx, args) {
- const rp = novelRel(args.path);
- const content = readNovelFile(ctx.projectId, rp);
- if (content == null) throw new Error('非法读取路径:' + args.path);
- if (!content) return '';
- return content.length > 120000 ? content.slice(0, 120000) + '\n…(截断)' : content;
- }
- async function hNovelListFiles(ctx) {
- return JSON.stringify(listNovelFiles(ctx.projectId));
- }
- async function hNovelSaveCharacters(ctx, args) {
- const chars = args.characters;
- if (!Array.isArray(chars)) throw new Error('characters 必须是数组');
- const cleaned = chars.map((c, i) => ({
- id: String(c?.id ?? ''),
- name: String(c?.name ?? '').trim(),
- role: String(c?.role ?? '').trim(),
- description: String(c?.description ?? '').trim(),
- notes: c?.notes != null ? String(c.notes) : '',
- })).filter((c) => c.name || c.role || c.description);
- const existing = loadNovelState(ctx.projectId).characters;
- // 给新角色分配稳定 id(空 id 且 name 没重复)
- const seen = new Set(existing.map((c) => c.id).filter(Boolean));
- for (const c of cleaned) {
- if (!c.id) {
- c.id = uid().slice(0, 8);
- while (seen.has(c.id)) c.id = uid().slice(0, 8);
- seen.add(c.id);
- } else {
- seen.add(c.id);
- }
- }
- saveNovelState(ctx.projectId, { characters: cleaned });
- return JSON.stringify({ count: cleaned.length, names: cleaned.map((c) => c.name) });
- }
- async function hNovelGetCharacters(ctx) {
- const state = loadNovelState(ctx.projectId);
- return JSON.stringify(state.characters);
- }
- async function hNovelSaveVolumes(ctx, args) {
- const vols = args.volumes;
- if (!Array.isArray(vols)) throw new Error('volumes 必须是数组');
- const cleaned = vols.map((v, i) => ({
- id: String(v?.id ?? ''),
- seq: Number.isFinite(Number(v?.seq)) && Number(v?.seq) >= 1 ? Math.floor(Number(v.seq)) : i + 1,
- title: String(v?.title ?? '').trim(),
- outline: String(v?.outline ?? '').trim(),
- chapterFrom: Number.isFinite(Number(v?.chapterFrom)) ? Math.floor(Number(v.chapterFrom)) : 0,
- chapterTo: Number.isFinite(Number(v?.chapterTo)) ? Math.floor(Number(v.chapterTo)) : 0,
- })).filter((v) => v.title || v.outline || v.chapterFrom || v.chapterTo);
- saveNovelState(ctx.projectId, { volumes: cleaned });
- return JSON.stringify({ count: cleaned.length, volumes: cleaned.map((v) => ({ seq: v.seq, title: v.title, chapterFrom: v.chapterFrom, chapterTo: v.chapterTo })) });
- }
- async function hNovelGetVolumes(ctx) {
- const state = loadNovelState(ctx.projectId);
- return JSON.stringify(state.volumes);
- }
- async function hNovelGetMemory(ctx) {
- const state = loadNovelState(ctx.projectId);
- return JSON.stringify(state.memory.map((m) => ({ name: m.name, content: m.content })));
- }
- async function hNovelSaveMemory(ctx, args) {
- const raw = String(args.name || '').trim().replace(/\\/g, '/');
- if (!raw) throw new Error('name 不能为空');
- // 规范成 memory/<name>.md:去掉可能的 memory/ 前缀与 .md 后缀
- let name = raw.replace(/^memory\//i, '').replace(/\.md$/i, '');
- if (!name) throw new Error('name 非法');
- const rel = 'memory/' + name + '.md';
- const abs = writeNovelFile(ctx.projectId, rel, String(args.content ?? ''));
- if (!abs) throw new Error('非法记忆路径:' + name);
- return '已更新记忆:' + rel;
- }
- async function hNovelListChapters(ctx) {
- const list = Chapters.list(ctx.projectId).map((c) => ({
- title: c.title || '',
- seq: c.seq || 0,
- volume: c.volume ?? 1,
- outline: c.outline || '',
- wordCount: String(c.novel || '').length,
- hasContent: !!String(c.novel || '').trim(),
- }));
- return JSON.stringify(list);
- }
- async function hNovelSaveChapter(ctx, args) {
- const title = String(args.title || '').trim();
- if (!title) throw new Error('章节标题不能为空');
- const volume = Number.isFinite(Number(args.volume)) && Number(args.volume) >= 1 ? Math.floor(Number(args.volume)) : 1;
- const outline = String(args.outline ?? '');
- // 只有显式传了非空 content 才写正文:避免「只更新章纲」时把已写正文清空
- const content = args.content !== undefined ? String(args.content ?? '') : undefined;
- const hasContent = content !== undefined && content.length > 0;
- const existing = Chapters.list(ctx.projectId).find((c) => c.title === title);
- if (existing) {
- const patch = {};
- if (hasContent) patch.novel = content;
- if (args.volume !== undefined) patch.volume = volume;
- if (args.outline !== undefined) patch.outline = outline;
- if (Object.keys(patch).length) Chapters.update(existing.id, patch);
- return JSON.stringify({ title, updated: true, volume, wordCount: (patch.novel ?? existing.novel ?? '').length });
- }
- const c = Chapters.create(ctx.projectId, { title, novel: hasContent ? content : '', volume, outline });
- return JSON.stringify({ title: c.title, created: true, volume, wordCount: String(c.novel || '').length });
- }
- const HANDLERS = {
- get_project: hGetProject,
- save_context: hSaveContext,
- skill: hLoadSkill,
- skill_reference: hSkillReference,
- report: hReport,
- list_chapters: hListChapters,
- get_chapter: hGetChapter,
- set_chapter_script: hSetChapterScript,
- list_assets: hListAssets,
- create_asset: hCreateAsset,
- update_asset: hUpdateAsset,
- generate_asset_image: hGenerateAssetImage,
- edit_asset_image: hEditAssetImage,
- change_outfit: hChangeOutfit,
- design_outfits: hDesignOutfits,
- change_age: hChangeAge,
- design_ages: hDesignAges,
- view_asset: hViewAsset,
- view_shot_references: hViewShotReferences,
- view_project_references: hViewProjectReferences,
- web_search: hWebSearch,
- download_reference_image: hDownloadReferenceImage,
- register_voice: hRegisterVoice,
- design_voice: hDesignVoice,
- generate_assets_batch: hGenerateAssetsBatch,
- generate_asset_from_reference: hGenerateAssetFromReference,
- set_storyboard: hSetStoryboard,
- list_shots: hListShots,
- update_shot: hUpdateShot,
- generate_shot_video: hGenerateShotVideo,
- regenerate_shot: hRegenerateShot,
- write_shot_video_prompt: hWriteShotVideoPrompt,
- generate_chapter_videos: hGenerateChapterVideos,
- assemble_video: hAssembleVideo,
- set_chapter_music: hSetChapterMusic,
- generate_music: hGenerateMusic,
- generate_music_asset: hGenerateMusicAsset,
- generate_video_asset: hGenerateVideoAsset,
- clone_voice: hCloneVoice,
- generate_digital_human: hGenerateDigitalHuman,
- apply_chapter_music: hApplyChapterMusic,
- list_workflows: hListWorkflows,
- opuscar_init: hOpuscarInit,
- opuscar_shell: hOpuscarShell,
- opuscar_write_file: hOpuscarWriteFile,
- opuscar_read_file: hOpuscarReadFile,
- opuscar_save_film: hOpuscarSaveFilm,
- novel_init: hNovelInit,
- novel_write_file: hNovelWriteFile,
- novel_read_file: hNovelReadFile,
- novel_list_files: hNovelListFiles,
- novel_save_characters: hNovelSaveCharacters,
- novel_get_characters: hNovelGetCharacters,
- novel_list_chapters: hNovelListChapters,
- novel_save_chapter: hNovelSaveChapter,
- novel_save_volumes: hNovelSaveVolumes,
- novel_get_volumes: hNovelGetVolumes,
- novel_get_memory: hNovelGetMemory,
- novel_save_memory: hNovelSaveMemory,
- };
- export async function runTool(ctx, name, args) {
- // 运行时安全守卫:扫描工具参数,命中危险命令/危险参数即拦截该次调用(不终止任务)。
- const g = guardToolCall(name, args || {});
- if (g.blocked) {
- const msg = '[安全拦截] 工具 ' + name + ' 命中危险规则 ' + g.rule + '(' + g.severity + '):' + g.message;
- logger.warn('guard: ' + msg, { name, rule: g.rule, severity: g.severity });
- if (ctx.report) ctx.report({ phase: '安全拦截', detail: msg });
- return JSON.stringify({ blocked: true, tool: name, rule: g.rule, severity: g.severity, message: g.message });
- }
- // 封闭参数校验:拒绝未在工具 schema 中声明的顶层参数字段(未知字段=硬错误,不静默丢弃)。
- const allowedKeys = ALLOWED_ARG_KEYS.get(name);
- if (allowedKeys) {
- const unknown = Object.keys(args || {}).filter((k) => !allowedKeys.has(k));
- if (unknown.length) {
- const msg = '[安全拦截] 工具 ' + name + ' 含未声明参数:' + unknown.join(', ');
- logger.warn('guard: ' + msg, { name, unknown });
- if (ctx.report) ctx.report({ phase: '安全拦截', detail: msg });
- return JSON.stringify({ blocked: true, tool: name, rule: 'unknown-args', message: '未声明的参数字段:' + unknown.join(', ') });
- }
- }
- const h = HANDLERS[name];
- if (!h) throw new Error('未知工具:' + name);
- // 只跑 LLM 的阶段:渲染工具一律跳过。这里刻意「返回」而不是抛错——
- // 抛错会让 Agent 把同一个必然失败的调用反复重试,白烧 token 且跑不到收尾。
- // 例外:regenerate_shot 的 render=false 是纯 LLM 改写提示词(不提交 ComfyUI),LLM 阶段放行。
- const llmOnlyCall = name === 'regenerate_shot' && args && args.render === false;
- if (ctx.renderDisabled && RENDER_TOOLS.has(name) && !llmOnlyCall) {
- const reason = '渲染需另起一批(ComfyUI 与 LLM 抢显存,本阶段不启动 ComfyUI)';
- logger.warn('stage: 跳过渲染工具', { name });
- if (ctx.report) ctx.report({ phase: '渲染已跳过', detail: name + ':' + reason });
- return JSON.stringify({ skipped: true, tool: name, reason });
- }
- logger.debug('agent tool', { name, args });
- // 内置 Agent 的内容写入同样进变更日志(source=agent:<tool>),与 UI / 外部 harness 一致
- return await withWriteContext('agent:' + name, () => h(ctx, args || {}));
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.