diff --git a/src/agents/productionAgent/index.ts b/src/agents/productionAgent/index.ts index 434af18..21b5a9b 100644 --- a/src/agents/productionAgent/index.ts +++ b/src/agents/productionAgent/index.ts @@ -401,14 +401,18 @@ async function consumeFullStream( } else if (chunk.type === "text-delta") { text.append(chunk.text); fullResponse += chunk.text; + } else if (chunk.type === "error") { + throw chunk.error; } } text.complete(); msg.complete(); } catch (err: any) { thinking?.complete(); - text.complete(); - msg.stop(); + const errMsg = err?.message ?? String(err); + text.append(errMsg); + text.error(); + msg.error(); throw err; } diff --git a/src/agents/scriptAgent/index.ts b/src/agents/scriptAgent/index.ts index b4a0c76..57a8fd8 100644 --- a/src/agents/scriptAgent/index.ts +++ b/src/agents/scriptAgent/index.ts @@ -111,7 +111,7 @@ function createSubAgent(parentCtx: AgentContext) { parentCtx.msg.complete(); const subMsg = resTool.newMessage("assistant", name); - const { fullStream } = await u.Ai.Text("scriptAgent", parentCtx.thinkConfig.think, parentCtx.thinkConfig.thinlLevel ).stream({ + const { fullStream } = await u.Ai.Text("scriptAgent", parentCtx.thinkConfig.think, parentCtx.thinkConfig.thinlLevel).stream({ system, messages: messages ?? [{ role: "user", content: prompt }], abortSignal, @@ -260,14 +260,18 @@ async function consumeFullStream( } else if (chunk.type === "text-delta") { text.append(chunk.text); fullResponse += chunk.text; + } else if (chunk.type === "error") { + throw chunk.error; } } text.complete(); msg.complete(); } catch (err: any) { thinking?.complete(); - text.complete(); - msg.stop(); + const errMsg = err?.message ?? String(err); + text.append(errMsg); + text.error(); + msg.error(); throw err; } diff --git a/src/lib/fixDB.ts b/src/lib/fixDB.ts index 6ece49f..1f36766 100644 --- a/src/lib/fixDB.ts +++ b/src/lib/fixDB.ts @@ -4,6 +4,9 @@ import fs from "fs"; import { Knex } from "knex"; import db from "@/utils/db"; import { transform } from "sucrase"; +import rawVendorData from "./vendor.json"; + +const vendorData = rawVendorData as Record; export default async (knex: Knex): Promise => { const addColumn = async (table: string, column: string, type: string) => { @@ -65,17 +68,6 @@ export default async (knex: Knex): Promise => { data: `# 视频提示词生成 Skill\n\n你是**视频提示词生成 Agent**,专门负责根据指定的 AI 视频模型,读取分镜信息并输出该模型对应格式的视频提示词。\n\n---\n\n## 输入格式\n\n### 1. 模型与模式(必选)\n\n\n#### 模式路由规则\n\n| 条件 | 匹配模式 | 说明 |\n|------|----------|------|\n| 模型名为 \`seedance-2-0\` + \`多参:是\` / \`seedance 2.0\` + \`多参:是\` / \`即梦2.0\` + \`多参:是\` | **seedance-2-0*,不包含其他版本比如seedance-1-5/seedance-1-0 | 支持角色/场景/分镜图多参引用 |\n| 模型名为 \`Wan2.6\` / \`wan 2.6\` / \`万象2.6\` | **Wan 2.6** | 固定模式,单图(首帧)+ 叙事文本,无尾帧 |\n| 其他任何模型 + \`多参:是\` | **通用多参模式** | 支持角色/场景/分镜图多参引用 |\n| 其他任何模型/seedance-1-5/seedance-1-0 + \`多参:否\` | **通用首尾帧模式** | 首帧/首尾帧 + 纯文本描述 |\n\n> 模型名仅用于记录,实际提示词格式由匹配到的模式决定。Seedance 2.0 和 Wan 2.6 是指定模型名即确定模式的特例。\n\n### 2. 资产信息\n\n\`\`\`\n资产信息[id, type, name], [id, type, name], ...\n\`\`\`\n\n- \`id\`:资产唯一标识(如 \`A001\`)\n- \`type\`:资产类型,取值 \`role\`(角色)/ \`scene\`(场景)/ \`prop\`(道具)\n- \`name\`:资产名称(如 \`沈辞\`、\`城楼\`、\`长剑\`)\n\n### 3. 分镜信息\n\n分镜以 \`\` XML 标签列表的形式传入,每条分镜结构如下:\n\n\`\`\`xml\n\n\`\`\`\n\n#### 输入字段说明\n\n| 属性 | 说明 | 来源 |\n|------|------|------|\n| \`videoDesc\` | **核心输入**:分镜的结构化画面描述,包含画面描述、场景、关联资产名称、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效、关联资产ID | 用户/上游系统填写 |\n| \`prompt\` | **已有字段**:上游生成的分镜图提示词,作为辅助参考上下文,**不修改** | 上游系统已填写 |\n| \`track\` | 分镜分组标识 | 用户/上游系统填写 |\n| \`duration\` | 视频推荐时长(秒) | 用户/上游系统填写 |\n| \`associateAssetsIds\` | 该分镜关联的资产ID列表 | 用户/上游系统填写 |\n| \`shouldGenerateImage\` | 是否需要生成分镜图片,默认 \`true\` | 用户/上游系统填写 |\n\n---\n\n## 任务目标\n\n读取所有 \`\` 的属性,结合资产信息,根据指定模型的提示词格式,将全部分镜整合为一个完整的视频提示词。\n\n---\n\n## 输出格式\n\n将所有分镜整合为**一个完整的视频提示词**输出(非逐条独立):\n\n| 模式 | 整合方式 |\n|------|----------|\n| **通用多参模式** | \`[References]\` 汇总所有 \`@图N \` 引用;\`[Instruction]\` 按时间顺序描述完整叙事 |\n| **通用首尾帧模式** | 纯文本五维度(Visual / Motion / Camera / Audio / Narrative),不使用任何 \`@图N \` 引用,按时间轴连续编排(\`[Motion]\` 0s → 总时长,每段最低 1 秒),全程单一连贯镜头,不切镜 |\n| **Seedance 2.0** | \`生成一个由以下 N 个分镜组成的视频\`,每条对应 \`分镜N{N}s\` 段落 |\n| **Wan 2.6** | 单图首帧模式,每次仅输入一条分镜,输出一段叙事式英文提示词(三段式:风格基调 → 主体动作+场景环境+光线氛围 → 镜头收尾),不使用 \`@图N \` 引用 |\n\n- 仅输出视频提示词文本,不输出 XML 标签,不附加解释\n\n---\n\n## videoDesc 解析规则\n\n从 \`videoDesc\` 括号内按顿号分隔提取以下结构化字段:\n\n\`\`\`\n({画面描述}、{场景}、{关联资产名称}、{时长}、{景别}、{运镜}、{角色动作}、{情绪}、{光影氛围}、{台词}、{音效}、{关联资产ID})\n\`\`\`\n\n| 序号 | 字段 | 用途 | 示例 |\n|------|------|------|------|\n| 1 | 画面描述 | prompt 的叙事主干 | 沈辞独立城楼远眺苍茫大地 |\n| 2 | 场景 | 匹配场景资产 | 城楼 |\n| 3 | 关联资产名称 | 匹配角色/道具资产 | 沈辞/城楼 |\n| 4 | 时长 | 控制时长参数 | 4s |\n| 5 | 景别 | 控制镜头景别 | 全景 |\n| 6 | 运镜 | 控制运镜方式 | 静止 |\n| 7 | 角色动作 | prompt 动作描写 | 负手而立衣袂随风飘扬 |\n| 8 | 情绪 | prompt 情绪氛围 | 坚定决绝 |\n| 9 | 光影氛围 | prompt 光影描写 | 黄昏冷调侧逆光 |\n| 10 | 台词 | prompt 台词/音频段 | 无台词 / 具体台词内容 |\n| 11 | 音效 | prompt 音效描写 | 风声衣袂声 |\n| 12 | 关联资产ID | 用于资产ID↔角色标签映射 | A001/A002 |\n\n---\n\n## 资产引用编号规则\n\n所有模型统一使用 \`@图N \` 格式引用资产和分镜图,编号按输入顺序连续递增:\n\n1. **资产**:按资产信息中 \`[id, type, name]\` 的出现顺序,从 \`@图1 \` 开始编号(不区分 role / scene / prop)。**资产类型的出现顺序不固定**——可能先 scene 后 character,也可能 prop 在前、character 在后,或任意交替出现,编号严格按输入位置分配,不按类型归组\n2. **分镜图**:每条 \`\` 对应一张分镜图,编号接续资产之后\n3. **跳过无分镜图的条目**:当 \`shouldGenerateImage="false"\` 时,该分镜未生成图片,**不分配**分镜图编号,后续编号顺延\n\n#### 示例\n\n输入 3 个资产 + 2 条分镜:\n\`\`\`\n资产信息[A001, role, 沈辞], [A002, role, 苏锦], [A003, scene, 城楼]\n\`\`\`\n\`\`\`xml\n \n \n\`\`\`\n\n编号结果:\n\n| 输入项 | 引用标签 | 说明 |\n|--------|----------|------|\n| [A001, role, 沈辞] | \`@图1 \` | 角色·沈辞 参考图 |\n| [A002, role, 苏锦] | \`@图2 \` | 角色·苏锦 参考图 |\n| [A003, scene, 城楼] | \`@图3 \` | 场景·城楼 参考图 |\n| storyboardItem 第1条 | \`@图4 \` | 分镜图1 |\n| storyboardItem 第2条 | \`@图5 \` | 分镜图2 |\n\n**混合顺序示例**\n\n输入 3 个资产(场景在前)+ 2 条分镜:\n\`\`\`\n资产信息[A003, scene, 城楼], [A001, role, 沈辞], [A002, role, 苏锦]\n\`\`\`\n\`\`\`xml\n \n \n\`\`\`\n\n编号结果:\n\n| 输入项 | 引用标签 | 说明 |\n|--------|----------|------|\n| [A003, scene, 城楼] | \`@图1 \` | 场景·城楼 参考图 |\n| [A001, role, 沈辞] | \`@图2 \` | 角色·沈辞 参考图 |\n| [A002, role, 苏锦] | \`@图3 \` | 角色·苏锦 参考图 |\n| storyboardItem 第1条 | \`@图4 \` | 分镜图1 |\n| storyboardItem 第2条 | \`@图5 \` | 分镜图2 |\n\n> **关键**:此例中 \`@图1 \` 是场景而非角色,\`@图2 \` \`@图3 \` 才是角色。生成提示词时,必须根据资产的实际 \`type\` 字段确定引用方式,而非根据编号大小假定类型。\n\n---\n\n## 模型提示词生成规则\n\n### 一、通用多参模式\n\n#### 核心原则\n- MVL 多模态融合:自然语言 + 图像引用在同一语义空间\n- 分镜图序列负责动作/时间轴/构图,场景参考图负责环境一致性\n- 所有资产和分镜图统一用 \`@图N \` 引用\n- **严格遵循 videoDesc**:提示词内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段生成,不编造额外内容\n- **台词不可缺失**:videoDesc 中有台词的分镜,必须在 Instruction 中体现台词相关描述\n- **台词类型标注**:区分普通对白(dialogue)、内心独白(inner monologue OS)、画外音(voiceover VO),在 Instruction 中用括号标注\n\n#### prompt 生成模板\n\n> **注意**:\`[References]\` 中的 \`@图N\` 编号严格按资产输入顺序分配,角色/场景/道具可能出现在任意编号位置。生成时需根据每个资产的 \`type\` 字段确定其引用方式,不可假定固定的类型-编号对应关系。\n\n\`\`\`\n[References]\n@图{资产1编号} : [{资产1名称}参考图] ← 可能是 role/scene/prop 中的任意类型\n@图{资产2编号} : [{资产2名称}参考图]\n@图{资产3编号} : [{资产3名称}参考图]\n...\n@图{分镜图编号} : [分镜图1] ← 分镜图编号接续资产之后\n\n[Instruction]\nBased on the storyboard @图{分镜图编号} :\n@图{角色资产编号} {动作/状态描述(英文)},\nset in the {场景描述(英文)} of @图{场景资产编号} ,\n{镜头/运镜描述(英文)},\n{情感基调(英文)},\n{台词描述(英文,含 dialogue/OS/VO 标注)/ No dialogue},\n{音效描述(英文)}.\n\`\`\`\n\n#### 生成约束\n1. **Instruction 必须用英文**\n2. **严格遵循 videoDesc**:提示词内容严格基于 videoDesc 的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段,不编造额外信息\n3. **角色动作**从 videoDesc 的「角色动作」字段提取,翻译为简洁英文动作描述\n4. **台词不可缺失**:videoDesc 中有台词的分镜,必须在 Instruction 中体现台词内容(保持原始语言,不翻译)\n5. **台词类型标注**:普通对白标注 \`(dialogue)\`;内心独白标注 \`(inner monologue, OS)\`;画外音标注 \`(voiceover, VO)\`\n6. **镜头风格**使用标准标签:\`cinematic\` / \`wide-angle\` / \`close-up\` / \`slow motion\` / \`surround shooting\` / \`handheld\`\n7. **空间关系**使用标准动词:\`wearing\` / \`holding\` / \`standing on\` / \`following behind\` / \`sitting in\`\n8. 单条分镜对应单个 \`@图N \`,不做多帧跨镜描述\n9. 无需描述角色外观(由参考图负责)\n10. 无时长标注(由模型推断)\n11. **无分镜图时**:当 \`shouldGenerateImage="false"\` 时,该分镜无分镜图,\`[References]\` 中不列出该分镜图,\`[Instruction]\` 中不使用 \`@图N \` 引用该分镜图,改为纯文本描述画面内容\n\n#### KlingOmni 完整示例\n\n输入:\n\`\`\`\n模型:KlingOmni\n资产信息[A001, role, 沈辞], [A002, role, 苏锦], [A003, scene, 城楼]\n\`\`\`\n\`\`\`xml\n\n\n\`\`\`\n\n输出:\n\`\`\`\n[References]\n@图1 : [沈辞参考图]\n@图2 : [苏锦参考图]\n@图3 : [城楼参考图]\n@图4 : [分镜图1]\n@图5 : [分镜图2]\n\n[Instruction]\nBased on the storyboard from @图4 to @图5 :\n@图1 standing alone atop the city wall, hands clasped behind back, robes billowing in the wind, gazing across the vast land,\n@图2 ascending the steps toward @图1 , expression worried,\nset in the ancient city wall environment of @图3 ,\nwide shot transitioning to medium tracking shot, cinematic,\nresolute determination shifting to concerned anticipation, dusk cold-toned side-backlit atmosphere fading,\nno dialogue,\nwind howling, fabric flapping, footsteps on stone.\n\`\`\`\n\n---\n\n### 二、通用首尾帧模式\n\n#### 核心原则\n- **纯文本提示词**:提示词内**不使用任何 \`@图N \` 引用**(不引用角色资产、场景资产、也不引用分镜图),全部内容用纯文本描述\n- **五维度结构**:Visual / Motion / Camera / Audio / Narrative\n- **严格遵循 videoDesc**:提示词内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段生成,不编造额外内容\n- **台词不可缺失**:videoDesc 中有台词的分镜,必须在 \`[Audio]\` 中完整输出台词内容\n- **台词类型标注**:区分普通对白(dialogue, lip-sync active)、内心独白(inner monologue OS, silent lips)、画外音(voiceover VO, silent lips),并在 \`[Audio]\` 中明确标注\n- **不说话的主体标注 \`silent\`** — 防止误生口型\n- **全程单一连贯镜头**:从头到尾一个镜头,不存在切镜\n- **时间轴分段**:每段最低 1 秒,用 \`0s-Xs\` 标注\n\n#### prompt 生成模板\n\n\`\`\`\n[Visual]\n{主体A名}: {外观简述}, {站位/姿态}, {说话状态 speaking/silent}.\n{主体B名}: {外观简述}, {站位/姿态}, {说话状态}.\n{场景描述}, {道具描述}.\n{视觉风格标签}.\n\n[Motion]\n0s-{X}s: {主体A名} {动作描述段1}.\n{X}s-{Y}s: {主体B名} {动作描述段2}.\n\n[Camera]\n{镜头类型}, {运镜方式}, {全程单一连贯镜头描述}.\n\n[Audio]\n{Xs-Ys}: "{台词内容}" — {说话者名} ({dialogue / inner monologue OS / voiceover VO}), {lip-sync active / silent lips}.\n{音效描述}.\n\n[Narrative]\n{情节点概述}, {叙事位置}.\n\`\`\`\n\n#### 生成约束\n1. **全部用英文**\n2. **不使用任何 \`@图N \` 引用**:提示词内不引用角色资产、场景资产、分镜图,全部内容用纯文本描述\n3. **主体用文字描述**:在 [Visual] 中简要描述主体外观特征(如服饰、发型等关键辨识特征)\n4. **严格遵循 videoDesc**:提示词内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段,不编造额外信息\n5. **每个主体必须标注说话状态**:\`speaking\` / \`silent\` / \`speaking simultaneously\`\n6. **台词不可缺失**:videoDesc 中有台词的分镜,必须在 \`[Audio]\` 中完整输出台词内容(保持原始语言,不翻译)\n7. **台词类型标注**:普通对白标注 \`dialogue, lip-sync active\`;内心独白标注 \`inner monologue (OS), silent lips\`;画外音标注 \`voiceover (VO), silent lips\`\n8. **Motion 时间轴**每段最低 1 秒,不超过总时长\n9. **全程单一连贯镜头**:Camera 段落描述从头到尾的一个镜头,绝不切镜\n10. **视觉风格**参考 Assistant 中的「视觉风格约束」部分内容\n11. **镜头类型**从以下选取:\`Wide establishing shot / Over-the-shoulder / Medium shot / Close-up / Wide shot / POV / Dutch angle / Crane up / Dolly right / Whip pan / Handheld / Slow motion\`\n\n#### Seedance 1.5 Pro 完整示例\n\n输入:\n\`\`\`\n模型:Seedance1.5\n资产信息[A001, role, 沈辞], [A002, role, 苏锦], [A003, scene, 城楼]\n\`\`\`\n\`\`\`xml\n\n\n\`\`\`\n\n输出:\n\`\`\`\n[Visual]\nShen Ci: male, dark flowing robes, hair tied up, standing alone atop city wall, hands clasped behind back, robes billowing, silent.\nSu Jin: female, light-colored dress, hair partially down, ascending steps toward Shen Ci, expression worried, silent.\nAncient city wall, vast open land beyond, dusk sky fading.\nCinematic, photorealistic, 4K, high contrast, desaturated tones, shallow depth of field.\n\n[Motion]\n0s-4s: Shen Ci stands still on city wall edge, robes flutter in wind, hair sways gently. Gaze fixed on distant horizon.\n4s-8s: Su Jin climbs the last few steps onto the wall, walks toward Shen Ci. Shen Ci remains still, unaware. Su Jin slows as she approaches.\n\n[Camera]\nWide establishing shot, static for first 4 seconds capturing the lone figure. Then smooth transition to medium tracking shot following the woman ascending steps, single continuous take throughout, no cuts.\n\n[Audio]\n0s-4s: Wind howling across wall, fabric flapping rhythmically. No dialogue.\n4s-8s: Footsteps on stone, robes rustling. No dialogue.\nShen Ci — silent. Su Jin — silent.\n\n[Narrative]\nLone figure on city wall, then arrival of a companion. Tension between determination and concern. Single continuous take.\n\`\`\`\n\n---\n\n### 三、Seedance 2.0\n\n#### 核心原则\n- **结构化12维编码**:统一用 \`@图N \` 引用资产和分镜图,时长 \`{N}s\`\n- **最前面先定义图片映射**:先输出“图片定义”段,集中声明 \`@图N : 主体名字/场景名字,简述\`;后续分镜正文只使用主体名字,不再写 \`@图N \`\n- **音色参数9维度精细描述**(有台词时必填)\n- **秒级时长控制**:单分镜时长最低 1s\n- **中文提示词**\n- **严格遵循 videoDesc**:每条分镜的描述内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段生成,不编造额外内容\n- **台词不可缺失**:videoDesc 中有台词的分镜,必须完整输出台词和音色描述\n- **台词类型标注**:区分普通对白(直接使用「说:」)、内心独白(使用「内心OS:」)、画外音(使用「画外音VO:」),并匹配对应的嘴型状态描述\n\n#### prompt 生成模板\n\n> **注意**:\`@图{编号}\` 仅用于最前面的“图片定义”段。分镜正文中禁止再写 \`@图{编号}\`,统一改用主体名字/场景名字。\n\n**单分镜模板:**\n\`\`\`\n画面风格和类型: {风格}, {色调}, {类型}\n\n图片定义:\n@图1: {资产1名字},{简述}\n@图2: {资产2名字},{简述}\n@图N: {资产N名字},{简述}\n...\n\n生成一个由以下 1 个分镜组成的视频:\n\n场景:\n分镜过渡: 无\n\n分镜1 {N}s: 时间:{日/夜/晨/黄昏},场景:{场景名字},镜头:{景别},{角度},{运镜},{角色名字} {动作/表情/视线朝向/站位描述}。{台词与音色描述(如有)}。{背景环境补充}。{光影氛围}。{运镜补充}。\n\`\`\`\n\n**多分镜模板:**\n\`\`\`\n画面风格和类型: {风格}, {色调}, {类型}\n\n图片定义:\n@图1: {资产1名字},{简述}\n@图2: {资产2名字},{简述}\n@图N: {资产N名字},{简述}\n...\n\n生成一个由以下 {N} 个分镜组成的视频:\n\n场景:\n分镜过渡: {全局过渡描述}\n\n分镜1 {N}s: 时间:{...},场景:{场景名字},镜头:{...},{角色名字} {...}。{...}。\n分镜2{N}s: ...\n...\n\`\`\`\n\n#### 音色生成规则(有台词时必填)\n\n台词格式:\`{角色名字} 说:「{台词内容}」音色:{9维度描述}\`\n\n9维度按顺序填写:\n\`\`\`\n{性别},{年龄音色},{音调},{音色质感},{声音厚度},{发音方式},{气息},{语速},{特殊质感}\n\`\`\`\n\n> 当 desc 中未明确音色信息时,根据角色类型从以下参考表推断:\n\n| 角色类型特征 | 默认音色 |\n|------------|---------|\n| 男性权威/霸气角色 | 男声,中年音色,音调低沉,音色浑厚有力,声音厚重,发音标准,气息极其沉稳,语速偏慢 |\n| 女性温柔/甜美角色 | 女声,青年音色,音调中等偏高,音色质感明亮清脆,声音清亮柔和,气息充沛平稳,带温婉真诚感 |\n| 男性年轻/普通角色 | 男声,青年音色,音调中等,音色干净,声音厚度适中,发音清晰,气息平稳,语速适中 |\n| 女性活泼/外向角色 | 女声,青年音色,音调偏高,音色清脆活泼,声音轻盈,气息充沛,语速偏快,带笑意和感染力 |\n| 反派/冷酷角色 | 男声,中年音色,音调低沉,音色质感干燥偏暗,声音带沙砾感,气息平稳,语速极慢,有威胁感 |\n\n#### 无台词分镜处理\n- 不写 \`说:\` 和音色段落\n- 在动作描述后标注 \`无台词\`\n\n#### 台词类型格式\n\n| 台词类型 | 格式 | 嘴型描述 |\n|----------|------|----------|\n| 普通对白 | \`{角色名字} 说:「{台词}」音色:{9维度}\` | 角色嘴部开合说话 |\n| 内心独白 | \`{角色名字} 内心OS:「{台词}」音色:{9维度}\` | 角色嘴部紧闭不动 |\n| 画外音 | \`{角色名字} 画外音VO:「{台词}」音色:{9维度}\` | 角色嘴部紧闭不动(或角色不在画面中) |\n\n#### 生成约束\n1. **中文提示词**\n2. **直接输出视频提示词**:禁止输出任何分析过程、推理步骤、模型匹配说明、资产编号表、分隔线等非提示词内容。第一行必须是 \`画面风格和类型:\`\n3. **严格遵循 videoDesc**:每条分镜内容严格基于 videoDesc 的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段,不编造额外信息\n4. **台词不可缺失**:videoDesc 中有台词的分镜,必须完整输出台词和音色\n5. **台词类型正确标注**:普通对白用「说:」,内心独白用「内心OS:」,画外音用「画外音VO:」\n6. **先图片定义,后写分镜**:最前面必须先输出"图片定义"段,列出 \`@图N : 名字,描述\`\n7. **分镜正文禁用 \`@图N \`**:正文统一使用角色名/场景名,不写 \`@图1/@图2\` 等编号\n8. **单分镜时长最低 1s**\n9. **时长单位**:直接使用 videoDesc 中的秒数,格式为 \`{N}s\`(如 \`4s\`),最低 1s\n\n#### Seedance 2.0 完整示例\n\n输入:\n\`\`\`\n模型:Seedance2.0\n资产信息[A001, role, 沈辞], [A002, role, 苏锦], [A003, scene, 城楼]\n\`\`\`\n\`\`\`xml\n\n\n\`\`\`\n\n输出:\n\`\`\`\n画面风格和类型: 真人写实, 电影风格, 冷调, 古风\n\n参考定义:\n@图1: 沈辞,黑色长袍,气质冷峻的青年男性\n@图2: 苏锦,浅色衣裙,神情细腻的青年女性\n@图3: 城楼,古代砖石城楼与台阶场景\n\n生成一个由以下 2 个分镜组成的视频:\n\n场景:\n分镜过渡: 镜头平滑切换,从全景过渡到中景跟踪,焦点从沈辞独处转向苏锦到来。\n\n分镜1 4s: 时间:黄昏,场景:城楼,镜头:全景,平视略仰,静止镜头,沈辞独立城楼之上,负手而立,衣袂随风飘扬,目光远眺苍茫大地,神情肃然面容沉着,眼神坚定目光清冽,眉眼沉静气质凛然。无台词。背景是古城楼砖石纹理清晰,远方大地苍茫辽阔,天际线冷暖交替。黄昏斜射余晖侧逆光,冷调为主,长影拉伸,轮廓光微勾勒人物边缘,光感诗意。镜头静止。\n\n分镜2 4s: 时间:黄昏,场景:城楼,镜头:中景,平视,跟踪拍摄,苏锦拾级而上,走向城楼上的沈辞,面部朝向沈辞方向,神情微愣面色微变,眼神中带着担忧,苏锦说:「你又一个人在这里。」音色:女声,青年音色,音调中等偏高,音色质感明亮清脆,声音清亮柔和,发音方式干净,气息充沛平稳,语速适中,带温婉真诚感。背景城楼台阶纹理清晰,余晖渐暗,天际线冷暖交替加深。镜头跟踪苏锦移动。\n\`\`\`\n\n---\n\n### 四、Wan 2.6\n\n#### 核心原则\n- **单图首帧模式**:归类为首尾帧模式,但仅有首帧(分镜图),无尾帧\n- **单条分镜输入/输出**:每次仅输入一条 \`\` 及其关联资产信息,输出也仅为一段完整的叙事式提示词\n- **叙事式英文提示词**:像写小说一样描写画面,不使用标签罗列(不写 \`4K, cinematic, high quality\` 这类堆砌)\n- **三段式结构**:风格基调 → 主体动作 + 场景环境 + 光线氛围 → 镜头收尾\n- **纯文本提示词**:提示词内**不使用任何 \`@图N \` 引用**,全部内容用纯文本描述\n- **严格遵循 videoDesc**:提示词内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段生成,不编造额外内容\n- **台词不可缺失**:videoDesc 中有台词的分镜,必须在提示词中体现台词相关描述\n- **台词类型标注**:区分普通对白(dialogue)、内心独白(inner monologue OS)、画外音(voiceover VO),在提示词中用括号标注\n\n#### prompt 生成模板\n\n每次输入一条分镜,输出一段完整提示词(无编号前缀),格式如下:\n\n\`\`\`\n{风格基调一句话定性},\n{主体名} {外观简述}, {具体动作/姿态描述}, {情绪/表情用动作暗示}.\n{场景背景主体}, {具体环境物件}, {空间感}, {时间/天气}.\n{光线方向/色温} {质感描述}, {情绪暗示光影}.\n{台词描述(如有,含 dialogue/OS/VO 标注)/ No dialogue}.\n{音效描述}.\n{拍摄方式}, {景别}, {视角}, {运镜方式}.\n\`\`\`\n\n#### 叙事式写法要点\n\n| 原则 | 说明 | 示例 |\n|------|------|------|\n| 风格基调放最前 | 一句话定性整体气质 | \`A cinematic epic scene\` / \`A melancholic cinematic scene\` |\n| 主体+动作紧密绑定 | 主体后面直接跟动作,外观细节嵌入主体描述 | \`A young man in dark flowing robes stands alone atop the city wall, hands clasped behind back\` |\n| 情绪用动作暗示 | 不直接陈述「他很悲伤」 | ❌ \`He is sad.\` → ✅ \`head drops slowly, shoulders slumped\` |\n| 环境融入叙事 | 不罗列环境属性 | ❌ \`The sky is blue. The grass is green.\` → ✅ \`hazy blue sky stretches over the emerald valley\` |\n| 光线单独成句 | 光线方向+色温+质感+情绪 | \`Warm golden hour light streams from behind, casting long shadows across the stone floor\` |\n| 镜头语言收尾 | 一句话点睛 | \`Captured in a wide establishing shot from a low-angle perspective, static camera\` |\n| 禁止标签堆砌 | 不写 \`4K, cinematic, high quality\` | \`cinematic\` 融入风格基调即可 |\n\n#### 生成约束\n1. **全部用英文**\n2. **不使用任何 \`@图N \` 引用**:提示词内不引用角色资产、场景资产、分镜图,全部内容用纯文本描述\n3. **叙事式描写**:像写小说一样构建画面,禁止标签罗列和配置清单式写法\n4. **主体用文字描述**:简要描述主体外观特征(如服饰、发型等关键辨识特征),嵌入主体描述中\n5. **严格遵循 videoDesc**:提示词内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段,不编造额外信息\n6. **台词不可缺失**:videoDesc 中有台词的分镜,必须在提示词中完整输出台词内容(保持原始语言,不翻译)\n7. **台词类型标注**:普通对白标注 \`(dialogue)\`;内心独白标注 \`(inner monologue, OS)\`;画外音标注 \`(voiceover, VO)\`\n8. **单条输入/输出**:每次仅处理一条分镜,输出一段提示词,无编号前缀\n9. **无需标注时长**:时长由模型侧控制,提示词中不写时长参数\n10. **镜头描述融入叙事**:不用方括号标签,用完整句子描述镜头\n11. **视觉风格**参考 Assistant 中的「视觉风格约束」部分内容\n\n#### Wan 2.6 完整示例\n\n**示例1:无台词分镜**\n\n输入:\n\`\`\`\n模型:Wan2.6\n资产信息[A001, role, 沈辞], [A003, scene, 城楼]\n\`\`\`\n\`\`\`xml\n\n\`\`\`\n\n输出:\n\`\`\`\nA cinematic epic scene with a cold, desaturn\`ated palette,\nA lone man in dark flowing robes stands atop an ancient city wall, hands clasped behind his back, robes and hair billowing in the wind, gaze fixed on the vast land stretching to the horizon, jaw set firm, eyes unwavering.\nThe weathered stone battlements frame the endless expanse below, rolling terrain fading into haze beneath a heavy dusk sky, clouds layered in muted golds and slate greys.\nCold side-backlight from the setting sun carves a sharp silhouette, long shadows stretching across the stone floor, a faint warm rim outlining the figure against the cool atmosphere.\nNo dialogue.\nWind howling across the open wall, fabric flapping rhythmically.\nCaptured in a wide establishing shot from a slightly low angle, static camera, single continuous take.\n\`\`\`\n\n**示例2:有台词分镜**\n\n输入:\n\`\`\`\n模型:Wan2.6\n资产信息[A001, role, 沈辞], [A002, role, 苏锦], [A003, scene, 城楼]\n\`\`\`\n\`\`\`xml\n\n\`\`\`\n\n输出:\n\`\`\`\nA melancholic cinematic scene, dusk tones deepening,\nA young woman in a light-colored dress ascends the final stone steps onto the city wall, her gaze locked on the lone figure ahead, brow slightly furrowed, pace slowing as she approaches, lips parting softly.\nThe ancient city wall stretches behind her, weathered stairs leading up from below, the distant skyline dimming as the last traces of golden hour fade into twilight.\nFading warm light mingles with rising cool blue tones, the contrast between the two figures softened by the diffused remnants of sunset.\n"你又一个人在这里。" — Su Jin (dialogue).\nFootsteps on stone, wind sweeping across the battlements, fabric rustling.\nA medium tracking shot follows the woman from behind as she ascends and approaches, handheld camera with subtle movement, single continuous take.\n\`\`\`\n\n---\n\n## 景别 → 镜头标签映射\n\n| videoDesc 中的景别 | KlingOmni(英文标签) | Seedance 1.5(英文标签) | Seedance 2.0(中文描述) | Wan 2.6(英文叙事式) |\n|------|------|------|------|------|\n| 远景 | extreme wide shot | Extreme wide shot | 远景 | an extreme wide shot capturing the vast expanse |\n| 全景 | wide shot | Wide establishing shot | 全景 | a wide establishing shot |\n| 中景 | medium shot | Medium shot | 中景 | a medium shot |\n| 近景 | close-up | Close-up | 近景 | a close-up shot |\n| 特写 | close-up | Close-up | 特写 | a close-up capturing fine detail |\n| 大特写 | extreme close-up | Extreme close-up | 大特写 | an extreme close-up |\n\n## 运镜 → 镜头标签映射\n\n| videoDesc 中的运镜 | KlingOmni(英文标签) | Seedance 1.5(英文标签) | Seedance 2.0(中文描述) | Wan 2.6(英文叙事式) |\n|------|------|------|------|------|\n| 静止 | static camera | Static, no camera movement | 镜头静止 | static camera, locked off |\n| 推进 | dolly in / push in | Slow dolly forward | 镜头缓慢向前推进 | camera slowly pushing in |\n| 拉远 | dolly out / pull back | Slow dolly backward pull | 镜头缓慢向后拉远 | camera gently pulling back |\n| 跟踪 | tracking shot | Tracking shot, handheld | 跟踪拍摄 | tracking shot following the subject |\n| 摇镜 | pan left/right | Slow pan | 镜头缓慢摇移 | smooth pan across the scene |\n| 甩镜 | whip pan | Whip pan | 快速甩镜 | whip pan |\n| 升降 | crane up/down | Crane up/down | 镜头升降 | crane rising / descending |\n| 环绕 | surround shooting | Orbiting shot | 环绕拍摄 | orbiting around the subject |\n\n---\n\n## 执行流程\n\n1. **解析输入**:提取模型名和多参标志,按路由规则匹配模式;提取资产列表\n2. **构建 @图N 编号表**:资产按输入顺序从 \`@图1 \` 起编号,分镜图接续编号;\`shouldGenerateImage="false"\` 的分镜不分配分镜图编号\n3. **逐条解析 \`\`**:按 videoDesc 解析规则提取12个字段,结合 \`duration\`、\`associateAssetsIds\` 建立标签映射\n4. **整合为一个完整的视频提示词**:按目标模型格式编排全部分镜\n5. **输出视频提示词**\n\n---\n\n## 约束\n\n- **仅输出视频提示词**:不附加任何解释、注释、分析过程、推理步骤、模型匹配说明、资产编号表、分隔线(\`---\`)或额外说明,只输出视频提示词文本。禁止在提示词前后输出任何非提示词内容\n- **严格遵循 videoDesc**(全模式通用):提示词内容严格基于 videoDesc 中的画面描述、时长、景别、运镜、角色动作、情绪、光影氛围、台词、音效字段生成,不编造额外内容\n- **台词不可缺失**(全模式通用):videoDesc 中有台词的分镜,必须在提示词中完整体现台词内容,不得遗漏\n- **台词保持原始输入**(全模式通用):台词内容严禁翻译,必须保持 videoDesc 中的原始语言原样输出\n- **台词类型标注**(全模式通用):必须区分普通对白(dialogue / 说)、内心独白(OS / 内心OS)、画外音(VO / 画外音VO),并在提示词中正确标注\n- **时间跨度最低 1 秒**(全模式通用):所有模式中涉及时间分段(Motion 时间轴 / Seedance 2.0 分镜时长 {N}s)的最小粒度为 1 秒(1s),禁止出现 0.5 秒等低于 1 秒的间隔\n- **视觉风格**:风格相关描述参考 Assistant 中的「视觉风格约束」部分内容,不在本 Skill 内自行定义风格\n- **严格按匹配到的模式格式**,不混用不同模式的格式\n- **不修改原始输入**:不改写 \`\` 的任何字段;\`prompt\` 已有的分镜图提示词仅作画面参考\n- **不编造资产或台词**:只使用输入中的资产信息;无台词则标注「无台词」/ \`No dialogue\`\n- **时长单位**:Seedance 2.0 的分镜时长直接使用秒,格式为 \`{N}s\`(如 \`4s\`),最低 1s\n`, }); - const vendorData: any = { - "grsai.ts": "/**\r\n * Toonflow AI供应商模板\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\" //单图参考\r\n | \"startEndRequired\" //首尾帧(两张都得有)\r\n | \"endFrameOptional\" //首尾帧(尾帧可选)\r\n | \"startFrameOptional\" //首尾帧(首帧可选)\r\n | \"text\" //文本\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[]; //多参考(数字代表限制数量)\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string; //唯一ID,作为文件名存储用户磁盘上,禁止符号\r\n version: string; //版本号,格式为x.y,需遵守语义化版本控制\r\n name: string; //供应商名称\r\n author: string; //作者\r\n description?: string; //描述,支持Markdown格式\r\n icon?: string; //图标,仅支持Base64格式,建议尺寸为128x128像素\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any; // HTTP请求库\r\ndeclare const logger: (msg: string) => void; // 日志函数\r\ndeclare const jsonwebtoken: any; // JWT处理库\r\ndeclare const zipImage: (base64: string, size: number) => Promise; // 图片压缩函数,返回有头base64字符串\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise; // 图片分辨率调整函数,返回有头base64字符串\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise; // 图片合成函数,返回有头base64字符串\r\ndeclare const urlToBase64: (url: string) => Promise; // URL转Base64函数,返回有头base64字符串\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise; // 轮询函数,fn为异步函数,interval为轮询间隔,timeout为超时时间,返回fn的结果\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any; //文本模型\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise; //图片模型,返回有头base64字符串\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise; //视频模型,返回有头base64字符串\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise; //(暂未开放)语音模型,返回有头base64字符串\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>; //检查更新函数,返回是否有更新和最新版本号和更公告(支持Markdown格式)\r\n updateVendor?: () => Promise; //更新函数,返回最新的代码文本\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"grsai\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"Grsai\",\r\n description: \"Grsai AI平台适配,支持文生图、图生图、文生视频、Gemini兼容文本模型 \\n [前往中转平台](https://tf.grsai.ai/zh)\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"示例:https://grsai.dakka.com.cn\" },\r\n ],\r\n inputValues: { apiKey: \"\", baseUrl: \"https://grsai.dakka.com.cn\" },\r\n models: [\r\n { name: \"Nano Banana Fast\", modelName: \"nano-banana-fast\", type: \"image\", mode: [\"text\", \"singleImage\", \"multiReference\"] },\r\n { name: \"Nano Banana 2\", modelName: \"nano-banana-2\", type: \"image\", mode: [\"text\", \"singleImage\", \"multiReference\"] },\r\n { name: \"Nano Banana Pro\", modelName: \"nano-banana-pro\", type: \"image\", mode: [\"text\", \"singleImage\", \"multiReference\"] },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\nconst getHeaders = () => {\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return {\r\n \"Content-Type\": \"application/json\",\r\n Authorization: `Bearer ${apiKey}`,\r\n };\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createGoogleGenerativeAI({\r\n baseURL: `${vendor.inputValues.baseUrl}/v1beta`,\r\n apiKey,\r\n }).chat(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const headers = getHeaders();\r\n\r\n // 构造请求参数\r\n const requestBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n aspectRatio: config.aspectRatio,\r\n webHook: \"-1\",\r\n shutProgress: true,\r\n };\r\n\r\n // 补充模型专属参数\r\n if (model.modelName.startsWith(\"nano-banana\")) {\r\n requestBody.imageSize = config.size;\r\n } else {\r\n requestBody.size = config.aspectRatio;\r\n requestBody.variants = 1;\r\n }\r\n\r\n // 处理参考图\r\n if (config.referenceList && config.referenceList.length > 0) {\r\n requestBody.urls = config.referenceList.map((img) => img.base64);\r\n }\r\n\r\n // 选择接口路径\r\n const apiPath = model.modelName.startsWith(\"nano-banana\") ? \"/v1/draw/nano-banana\" : \"/v1/draw/completions\";\r\n\r\n logger(`开始提交图片生成任务,模型:${model.modelName}`);\r\n const submitResp = await axios.post(`${baseUrl}${apiPath}`, requestBody, { headers });\r\n if (submitResp.data.code !== 0) throw new Error(`任务提交失败:${submitResp.data.msg}`);\r\n\r\n const taskId = submitResp.data.data.id;\r\n logger(`图片任务提交成功,任务ID:${taskId}`);\r\n\r\n // 轮询结果\r\n const pollResult = await pollTask(\r\n async () => {\r\n const resp = await axios.post(`${baseUrl}/v1/draw/result`, { id: taskId }, { headers });\r\n if (resp.data.code !== 0) return { completed: true, error: resp.data.msg };\r\n\r\n const taskData = resp.data.data;\r\n if (taskData.status === \"failed\") return { completed: true, error: taskData.failure_reason || taskData.error };\r\n if (taskData.status === \"succeeded\") {\r\n const imgUrl = taskData.results?.[0]?.url || taskData.url;\r\n return { completed: true, data: imgUrl };\r\n }\r\n logger(`图片任务生成中,进度:${taskData.progress}%`);\r\n return { completed: false };\r\n },\r\n 3000,\r\n 600000,\r\n );\r\n\r\n if (pollResult.error) throw new Error(pollResult.error);\r\n logger(`图片生成完成,开始转换Base64`);\r\n return await urlToBase64(pollResult.data!);\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const headers = getHeaders();\r\n\r\n // 构造请求参数\r\n const requestBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n aspectRatio: config.aspectRatio,\r\n webHook: \"-1\",\r\n shutProgress: true,\r\n };\r\n\r\n // 处理参考资源\r\n if (config.referenceList && config.referenceList.length > 0) {\r\n const imageRefs = config.referenceList.filter((item) => item.type === \"image\") as Extract[];\r\n if (config.mode.includes(\"endFrameOptional\") && imageRefs.length >= 1) {\r\n requestBody.firstFrameUrl = imageRefs[0].base64;\r\n if (imageRefs.length >= 2) requestBody.lastFrameUrl = imageRefs[1].base64;\r\n } else if (config.mode.some((m) => Array.isArray(m) && m.includes(\"imageReference:3\"))) {\r\n requestBody.urls = imageRefs.map((img) => img.base64);\r\n }\r\n }\r\n\r\n logger(`开始提交视频生成任务,模型:${model.modelName}`);\r\n const submitResp = await axios.post(`${baseUrl}/v1/video/veo`, requestBody, { headers });\r\n if (submitResp.data.code !== 0) throw new Error(`任务提交失败:${submitResp.data.msg}`);\r\n\r\n const taskId = submitResp.data.data.id;\r\n logger(`视频任务提交成功,任务ID:${taskId}`);\r\n\r\n // 轮询结果\r\n const pollResult = await pollTask(\r\n async () => {\r\n const resp = await axios.post(`${baseUrl}/v1/draw/result`, { id: taskId }, { headers });\r\n if (resp.data.code !== 0) return { completed: true, error: resp.data.msg };\r\n\r\n const taskData = resp.data.data;\r\n if (taskData.status === \"failed\") return { completed: true, error: taskData.failure_reason || taskData.error };\r\n if (taskData.status === \"succeeded\") {\r\n return { completed: true, data: taskData.url };\r\n }\r\n logger(`视频任务生成中,进度:${taskData.progress}%`);\r\n return { completed: false };\r\n },\r\n 5000,\r\n 1800000,\r\n );\r\n\r\n if (pollResult.error) throw new Error(pollResult.error);\r\n logger(`视频生成完成,开始转换Base64`);\r\n return await urlToBase64(pollResult.data!);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"1.0\", notice: \"## 新版本更新公告\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};\r\n", - "klingai.ts": "/**\r\n * Toonflow AI供应商模板 - 可灵AI\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"klingai\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"可灵AI\",\r\n description:\r\n \"可灵AI视频生成\\n\\n支持可灵全系列视频模型,包括 kling-video-o1、kling-v3-omni、kling-v3、kling-v2-6、kling-v2-5-turbo、kling-v2-1、kling-v2-master、kling-v1-6、kling-v1-5、kling-v1 等。\\n\\n需要在[可灵AI开放平台](https://klingai.com)\\n\\n获取 Access Key 和 Secret Key。\",\r\n inputs: [\r\n { key: \"accessKey\", label: \"Access Key\", type: \"password\", required: true, placeholder: \"请输入可灵AI的Access Key\" },\r\n { key: \"secretKey\", label: \"Secret Key\", type: \"password\", required: true, placeholder: \"请输入可灵AI的Secret Key\" },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"默认:https://api-beijing.klingai.com\" },\r\n ],\r\n inputValues: { accessKey: \"\", secretKey: \"\", baseUrl: \"https://api-beijing.klingai.com\" },\r\n models: [\r\n // kling-video-o1 (Omni)\r\n {\r\n name: \"kling-video-o1 标准\",\r\n modelName: \"kling-video-o1:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-video-o1 专家\",\r\n modelName: \"kling-video-o1:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n // kling-v3-omni (Omni)\r\n {\r\n name: \"kling-v3-omni 标准\",\r\n modelName: \"kling-v3-omni:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v3-omni 专家\",\r\n modelName: \"kling-v3-omni:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n // kling-v3\r\n {\r\n name: \"kling-v3 标准\",\r\n modelName: \"kling-v3:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v3 专家\",\r\n modelName: \"kling-v3:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n // kling-v2-6\r\n {\r\n name: \"kling-v2-6 标准\",\r\n modelName: \"kling-v2-6:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v2-6 专家\",\r\n modelName: \"kling-v2-6:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-5-turbo\r\n {\r\n name: \"kling-v2-5-turbo 标准\",\r\n modelName: \"kling-v2-5-turbo:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n {\r\n name: \"kling-v2-5-turbo 专家\",\r\n modelName: \"kling-v2-5-turbo:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-1\r\n {\r\n name: \"kling-v2-1 标准\",\r\n modelName: \"kling-v2-1:std\",\r\n type: \"video\",\r\n mode: [\"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v2-1 专家\",\r\n modelName: \"kling-v2-1:pro\",\r\n type: \"video\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-1-master\r\n {\r\n name: \"kling-v2-1 Master\",\r\n modelName: \"kling-v2-1-master:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-master\r\n {\r\n name: \"kling-v2 Master\",\r\n modelName: \"kling-v2-master:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n // kling-v1-6\r\n {\r\n name: \"kling-v1-6 标准\",\r\n modelName: \"kling-v1-6:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", [\"imageReference:4\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v1-6 专家\",\r\n modelName: \"kling-v1-6:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"endFrameOptional\", [\"imageReference:4\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v1-5\r\n {\r\n name: \"kling-v1-5 标准\",\r\n modelName: \"kling-v1-5:std\",\r\n type: \"video\",\r\n mode: [\"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v1-5 专家\",\r\n modelName: \"kling-v1-5:pro\",\r\n type: \"video\",\r\n mode: [\"singleImage\", \"endFrameOptional\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v1\r\n {\r\n name: \"kling-v1 标准\",\r\n modelName: \"kling-v1:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v1 专家\",\r\n modelName: \"kling-v1:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\n/**\r\n * 生成可灵AI的JWT鉴权Token\r\n */\r\nconst generateAuthToken = (): string => {\r\n const now = Math.floor(Date.now() / 1000);\r\n const payload = {\r\n iss: vendor.inputValues.accessKey,\r\n exp: now + 1800,\r\n nbf: now - 5,\r\n };\r\n return jsonwebtoken.sign(payload, vendor.inputValues.secretKey, {\r\n algorithm: \"HS256\",\r\n header: { alg: \"HS256\", typ: \"JWT\" },\r\n });\r\n};\r\n\r\n/**\r\n * 获取基础请求地址\r\n */\r\nconst getBaseUrl = (): string => {\r\n return vendor.inputValues.baseUrl || \"https://api-beijing.klingai.com\";\r\n};\r\n\r\n/**\r\n * 从 ReferenceList 条目中提取可用的数据字符串\r\n * 对于 url 类型返回 url,对于 base64 类型返回纯 base64(去掉 data: 前缀)\r\n */\r\nconst extractRawBase64 = (ref: ReferenceList): string => {\r\n return ref.base64.replace(/^data:[^;]+;base64,/, \"\");\r\n};\r\n\r\n/**\r\n * 从 ReferenceList 条目中提取带头的 base64 或 url\r\n * 用于 omni-video 接口,该接口的 image_url 支持带前缀的 base64 和 url\r\n */\r\nconst extractImageUrl = (ref: ReferenceList): string => {\r\n return ref.base64.startsWith(\"data:\") ? ref.base64 : `data:image/jpeg;base64,${ref.base64}`;\r\n};\r\n\r\n/**\r\n * 提交任务并轮询获取结果的通用函数\r\n */\r\nconst submitAndPoll = async (submitUrl: string, queryUrlBase: string, requestBody: any): Promise => {\r\n const token = generateAuthToken();\r\n\r\n logger(`开始提交可灵AI视频生成任务: ${submitUrl}`);\r\n logger(\r\n `请求参数: ${JSON.stringify({\r\n ...requestBody,\r\n image: requestBody.image ? \"[BASE64]\" : undefined,\r\n image_tail: requestBody.image_tail ? \"[BASE64]\" : undefined,\r\n image_list: requestBody.image_list ? \"[IMAGES]\" : undefined,\r\n })}`,\r\n );\r\n\r\n const submitResp = await axios.post(submitUrl, requestBody, {\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n Authorization: `Bearer ${token}`,\r\n },\r\n });\r\n\r\n if (submitResp.data.code !== 0) {\r\n throw new Error(`提交任务失败: ${submitResp.data.message || JSON.stringify(submitResp.data)}`);\r\n }\r\n\r\n const taskId = submitResp.data.data.task_id;\r\n logger(`任务已提交,任务ID: ${taskId}`);\r\n\r\n const result = await pollTask(\r\n async () => {\r\n const freshToken = generateAuthToken();\r\n const queryResp = await axios.get(`${queryUrlBase}/${taskId}`, {\r\n headers: {\r\n Authorization: `Bearer ${freshToken}`,\r\n },\r\n });\r\n\r\n if (queryResp.data.code !== 0) {\r\n return { completed: true, error: `查询任务失败: ${queryResp.data.message}` };\r\n }\r\n\r\n const taskData = queryResp.data.data;\r\n const status = taskData.task_status;\r\n logger(`轮询中... 任务状态: ${status}`);\r\n\r\n if (status === \"succeed\") {\r\n const videoUrl = taskData.task_result?.videos?.[0]?.url;\r\n if (!videoUrl) {\r\n return { completed: true, error: \"任务完成但未获取到视频URL\" };\r\n }\r\n return { completed: true, data: videoUrl };\r\n }\r\n\r\n if (status === \"failed\") {\r\n return { completed: true, error: `视频生成失败: ${taskData.task_status_msg || \"未知错误\"}` };\r\n }\r\n\r\n return { completed: false };\r\n },\r\n 5000,\r\n 600000,\r\n );\r\n\r\n if (result.error) throw new Error(result.error);\r\n logger(`视频生成完成,正在转换为Base64...`);\r\n return await urlToBase64(result.data!);\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n throw new Error(\"可灵AI不支持文本模型\");\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n throw new Error(\"可灵AI不支持图片模型\");\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.accessKey) throw new Error(\"缺少Access Key\");\r\n if (!vendor.inputValues.secretKey) throw new Error(\"缺少Secret Key\");\r\n\r\n const baseUrl = getBaseUrl();\r\n\r\n // 解析 modelName,格式:kling-video-o1:pro => modelName=kling-video-o1, mode=pro\r\n const colonIdx = model.modelName.indexOf(\":\");\r\n const modelName = colonIdx > -1 ? model.modelName.substring(0, colonIdx) : model.modelName;\r\n const mode = colonIdx > -1 ? model.modelName.substring(colonIdx + 1) : \"pro\";\r\n\r\n // 判断是否为 Omni 模型\r\n const isOmniModel = modelName === \"kling-video-o1\" || modelName === \"kling-v3-omni\";\r\n\r\n // 判断当前选中的视频生成模式\r\n const currentMode = config.mode;\r\n const isText = currentMode.includes(\"text\");\r\n const isSingleImage = currentMode.includes(\"singleImage\");\r\n const isStartEndRequired = currentMode.includes(\"startEndRequired\");\r\n const isEndFrameOptional = currentMode.includes(\"endFrameOptional\");\r\n const isStartFrameOptional = currentMode.includes(\"startFrameOptional\");\r\n const hasMultiRef = currentMode.some((m) => Array.isArray(m));\r\n\r\n // 提取不同类型的引用\r\n const imageRefs = (config.referenceList || []).filter((r) => r.type === \"image\");\r\n const videoRefs = (config.referenceList || []).filter((r) => r.type === \"video\");\r\n\r\n // =====================================================\r\n // Omni 模型 —— 使用 /v1/videos/omni-video 接口\r\n // =====================================================\r\n if (isOmniModel) {\r\n const requestBody: any = {\r\n model_name: modelName,\r\n mode: mode,\r\n duration: String(config.duration),\r\n sound: config.audio === true ? \"on\" : \"off\",\r\n };\r\n\r\n if (config.prompt) {\r\n requestBody.prompt = config.prompt;\r\n }\r\n\r\n if (isSingleImage && imageRefs.length > 0) {\r\n const imageUrl = extractImageUrl(imageRefs[0]);\r\n requestBody.image_list = [{ image_url: imageUrl, type: \"first_frame\" }];\r\n if (!requestBody.prompt) requestBody.prompt = \"根据图片生成视频\";\r\n } else if (isStartEndRequired && imageRefs.length >= 2) {\r\n const firstUrl = extractImageUrl(imageRefs[0]);\r\n const endUrl = extractImageUrl(imageRefs[1]);\r\n requestBody.image_list = [\r\n { image_url: firstUrl, type: \"first_frame\" },\r\n { image_url: endUrl, type: \"end_frame\" },\r\n ];\r\n if (!requestBody.prompt) requestBody.prompt = \"根据首尾帧图片生成过渡视频\";\r\n } else if (isEndFrameOptional && imageRefs.length >= 1) {\r\n const firstUrl = extractImageUrl(imageRefs[0]);\r\n requestBody.image_list = [{ image_url: firstUrl, type: \"first_frame\" }];\r\n if (imageRefs.length >= 2) {\r\n const endUrl = extractImageUrl(imageRefs[1]);\r\n requestBody.image_list.push({ image_url: endUrl, type: \"end_frame\" });\r\n }\r\n if (!requestBody.prompt) requestBody.prompt = \"根据图片生成视频\";\r\n } else if (isStartFrameOptional && imageRefs.length >= 1) {\r\n if (imageRefs.length >= 2) {\r\n const firstUrl = extractImageUrl(imageRefs[0]);\r\n const endUrl = extractImageUrl(imageRefs[1]);\r\n requestBody.image_list = [\r\n { image_url: firstUrl, type: \"first_frame\" },\r\n { image_url: endUrl, type: \"end_frame\" },\r\n ];\r\n } else {\r\n const endUrl = extractImageUrl(imageRefs[0]);\r\n requestBody.image_list = [{ image_url: endUrl, type: \"end_frame\" }];\r\n }\r\n if (!requestBody.prompt) requestBody.prompt = \"根据图片生成视频\";\r\n } else if (hasMultiRef && (imageRefs.length > 0 || videoRefs.length > 0)) {\r\n requestBody.image_list = [];\r\n for (let i = 0; i < imageRefs.length; i++) {\r\n const imageUrl = extractImageUrl(imageRefs[i]);\r\n requestBody.image_list.push({ image_url: imageUrl });\r\n }\r\n if (!requestBody.prompt) {\r\n const refs = imageRefs.map((_, idx) => `<<>>`).join(\"、\");\r\n requestBody.prompt = `参考${refs}生成视频`;\r\n }\r\n }\r\n\r\n // 文生视频或无图片输入时需要设置宽高比\r\n const hasImageInput = requestBody.image_list && requestBody.image_list.length > 0;\r\n if (!hasImageInput) {\r\n requestBody.aspect_ratio = config.aspectRatio || \"16:9\";\r\n if (!requestBody.prompt) throw new Error(\"文生视频模式需要提供提示词\");\r\n }\r\n\r\n const apiPath = \"/v1/videos/omni-video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n // =====================================================\r\n // 非 Omni 模型 —— 根据模式选择不同接口\r\n // =====================================================\r\n\r\n // 多图参考模式 —— 使用 /v1/videos/multi-image2video 接口(仅 kling-v1-6 支持)\r\n if (hasMultiRef && imageRefs.length > 0) {\r\n const imageList = [];\r\n for (let i = 0; i < imageRefs.length; i++) {\r\n const rawBase64 = extractRawBase64(imageRefs[i]);\r\n imageList.push({ image: rawBase64 });\r\n }\r\n\r\n const requestBody: any = {\r\n model_name: modelName,\r\n image_list: imageList,\r\n prompt: config.prompt || \"根据参考图片生成视频\",\r\n mode: mode,\r\n duration: String(config.duration),\r\n aspect_ratio: config.aspectRatio || \"16:9\",\r\n };\r\n\r\n const apiPath = \"/v1/videos/multi-image2video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n // 文生视频模式 —— 使用 /v1/videos/text2video 接口\r\n if (isText) {\r\n if (!config.prompt) throw new Error(\"文生视频模式需要提供提示词\");\r\n\r\n const requestBody: any = {\r\n model_name: modelName,\r\n prompt: config.prompt,\r\n mode: mode,\r\n duration: String(config.duration),\r\n aspect_ratio: config.aspectRatio || \"16:9\",\r\n sound: config.audio === true ? \"on\" : \"off\",\r\n };\r\n\r\n const apiPath = \"/v1/videos/text2video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n // 图生视频模式(单图 / 首尾帧 / 尾帧可选等)—— 使用 /v1/videos/image2video 接口\r\n if ((isSingleImage || isStartEndRequired || isEndFrameOptional || isStartFrameOptional) && imageRefs.length > 0) {\r\n const requestBody: any = {\r\n model_name: modelName,\r\n prompt: config.prompt || \"根据图片生成视频\",\r\n mode: mode,\r\n duration: String(config.duration),\r\n sound: config.audio === true ? \"on\" : \"off\",\r\n };\r\n\r\n if (isSingleImage) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n } else if (isStartEndRequired && imageRefs.length >= 2) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n requestBody.image_tail = extractRawBase64(imageRefs[1]);\r\n } else if (isEndFrameOptional) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n if (imageRefs.length >= 2) {\r\n requestBody.image_tail = extractRawBase64(imageRefs[1]);\r\n }\r\n } else if (isStartFrameOptional) {\r\n if (imageRefs.length >= 2) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n requestBody.image_tail = extractRawBase64(imageRefs[1]);\r\n } else {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n }\r\n }\r\n\r\n const apiPath = \"/v1/videos/image2video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n throw new Error(\"不支持的视频生成模式或缺少必要的输入参数\");\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};", - "minimax.ts": "/**\r\n * Toonflow AI供应商模板 - MiniMax(海螺AI)\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n uploadReference: (base64: string, fileType: \"image\" | \"audio\" | \"video\") => Promise;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"minimax\",\r\n version: \"2.1\",\r\n author: \"Toonflow\",\r\n name: \"MiniMax(海螺AI)\",\r\n description: \"MiniMax官方接口适配,支持M系列推理文本模型、文生图/图生图、视频生成(文生视频、图生视频、首尾帧生成)能力 \\n [前往平台](https://minimaxi.com/)\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"示例:https://api.minimaxi.com\" },\r\n ],\r\n inputValues: { apiKey: \"\", baseUrl: \"https://api.minimaxi.com\" },\r\n models: [\r\n // 文本模型\r\n { name: \"MiniMax-M2.7 (推理版)\", modelName: \"MiniMax-M2.7\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.7 极速版 (推理版)\", modelName: \"MiniMax-M2.7-highspeed\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.5 (推理版)\", modelName: \"MiniMax-M2.5\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.5 极速版 (推理版)\", modelName: \"MiniMax-M2.5-highspeed\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.1 (编程版)\", modelName: \"MiniMax-M2.1\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.1 极速版 (编程版)\", modelName: \"MiniMax-M2.1-highspeed\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2 (Agent版)\", modelName: \"MiniMax-M2\", type: \"text\", think: false },\r\n // 图片模型\r\n { name: \"海螺图像V1\", modelName: \"image-01\", type: \"image\", mode: [\"text\", \"singleImage\"] },\r\n { name: \"海螺图像V1 Live版\", modelName: \"image-01-live\", type: \"image\", mode: [\"text\", \"singleImage\"], associationSkills: \"支持自定义画风\" },\r\n // 视频模型\r\n {\r\n name: \"海螺2.3\",\r\n modelName: \"MiniMax-Hailuo-2.3\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [\r\n { duration: [6], resolution: [\"768P\", \"1080P\"] },\r\n { duration: [10], resolution: [\"768P\"] },\r\n ],\r\n },\r\n {\r\n name: \"海螺2.3极速版\",\r\n modelName: \"MiniMax-Hailuo-2.3-Fast\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [\r\n { duration: [6], resolution: [\"768P\", \"1080P\"] },\r\n { duration: [10], resolution: [\"768P\"] },\r\n ],\r\n },\r\n {\r\n name: \"海螺02\",\r\n modelName: \"MiniMax-Hailuo-02\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [\r\n { duration: [6], resolution: [\"512P\", \"768P\", \"1080P\"] },\r\n { duration: [10], resolution: [\"512P\", \"768P\"] },\r\n ],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\n/**\r\n * 获取请求头\r\n */\r\nconst getHeaders = (): Record => {\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return {\r\n Authorization: `Bearer ${apiKey}`,\r\n \"Content-Type\": \"application/json\",\r\n };\r\n};\r\n\r\n/**\r\n * 获取基础请求地址\r\n */\r\nconst getBaseUrl = (): string => {\r\n return vendor.inputValues.baseUrl.replace(/\\/$/, \"\");\r\n};\r\n\r\n/**\r\n * 从 ReferenceList 条目中提取有头 base64 字符串\r\n */\r\nconst extractBase64WithHead = (ref: ReferenceList): string => {\r\n return ref.base64.startsWith(\"data:\") ? ref.base64 : `data:image/png;base64,${ref.base64}`;\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n const baseUrl = getBaseUrl();\r\n\r\n const openaiBaseUrl = `${baseUrl}/v1`;\r\n const extraBody = model.think ? { reasoning_split: true } : {};\r\n return createOpenAI({ baseURL: openaiBaseUrl, apiKey, extraBody }).chat(model.modelName);\r\n};\r\n\r\nconst uploadReference = async (base64: string, fileType: \"image\" | \"audio\" | \"video\"): Promise => {\r\n // MiniMax的图片接口直接接受 base64,压缩后原样返回\r\n if (fileType === \"image\") {\r\n const compressed = await zipImage(base64, 10 * 1024);\r\n return { type: \"image\", sourceType: \"base64\", base64: compressed };\r\n }\r\n // 视频接口的图片参数也是 base64,压缩到20MB\r\n return { type: fileType, sourceType: \"base64\", base64 } as ReferenceList;\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const reqBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n aspect_ratio: config.aspectRatio,\r\n response_format: \"base64\",\r\n n: 1,\r\n prompt_optimizer: true,\r\n aigc_watermark: false,\r\n };\r\n\r\n // 处理图生图参考\r\n const imageRefs = config.referenceList || [];\r\n if (imageRefs.length > 0) {\r\n const refBase64 = extractBase64WithHead(imageRefs[0]);\r\n reqBody.subject_reference = [{ type: \"character\", image_file: refBase64 }];\r\n }\r\n\r\n logger(\"开始提交MiniMax图像生成任务\");\r\n const resp = await axios.post(`${baseUrl}/v1/image_generation`, reqBody, { headers });\r\n if (resp.data.base_resp.status_code !== 0) {\r\n throw new Error(`图像生成失败:${resp.data.base_resp.status_msg}`);\r\n }\r\n if (resp.data.metadata.success_count === 0) {\r\n throw new Error(\"图像生成被安全策略拦截,请调整prompt或参考图\");\r\n }\r\n\r\n const imgBase64 = resp.data.data.image_base64[0];\r\n return imgBase64.startsWith(\"data:\") ? imgBase64 : `data:image/png;base64,${imgBase64}`;\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const reqBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n duration: config.duration,\r\n resolution: config.resolution,\r\n aigc_watermark: false,\r\n prompt_optimizer: true,\r\n };\r\n\r\n // 提取图片类型的引用\r\n const imageRefs = (config.referenceList || []).filter((r) => r.type === \"image\");\r\n\r\n if (imageRefs.length > 0) {\r\n // 压缩图片到20MB以内\r\n const compressedImages: string[] = [];\r\n for (const ref of imageRefs) {\r\n const base64 = extractBase64WithHead(ref);\r\n const compressed = await zipImage(base64, 20 * 1024);\r\n compressedImages.push(compressed);\r\n }\r\n\r\n if (config.mode.includes(\"startEndRequired\")) {\r\n if (compressedImages.length < 2) throw new Error(\"首尾帧模式需要上传两张图片\");\r\n reqBody.first_frame_image = compressedImages[0];\r\n reqBody.last_frame_image = compressedImages[1];\r\n } else if (config.mode.includes(\"singleImage\")) {\r\n reqBody.first_frame_image = compressedImages[0];\r\n }\r\n }\r\n\r\n logger(\"开始提交MiniMax视频生成任务\");\r\n const submitResp = await axios.post(`${baseUrl}/v1/video_generation`, reqBody, { headers });\r\n if (submitResp.data.base_resp.status_code !== 0) {\r\n throw new Error(`任务提交失败:${submitResp.data.base_resp.status_msg}`);\r\n }\r\n const taskId = submitResp.data.task_id;\r\n logger(`视频任务提交成功,任务ID: ${taskId}`);\r\n\r\n // 轮询任务状态\r\n const pollResult = await pollTask(\r\n async () => {\r\n const queryResp = await axios.get(`${baseUrl}/v1/query/video_generation`, {\r\n headers: getHeaders(),\r\n params: { task_id: taskId },\r\n });\r\n if (queryResp.data.base_resp.status_code !== 0) {\r\n return { completed: true, error: queryResp.data.base_resp.status_msg };\r\n }\r\n const status = queryResp.data.status;\r\n if (status === \"Success\") {\r\n return { completed: true, data: queryResp.data.file_id };\r\n }\r\n if (status === \"Fail\") {\r\n return { completed: true, error: \"视频生成失败\" };\r\n }\r\n logger(`视频任务生成中,当前状态:${status}`);\r\n return { completed: false };\r\n },\r\n 5000,\r\n 600000,\r\n );\r\n\r\n if (pollResult.error) throw new Error(pollResult.error);\r\n const fileId = pollResult.data!;\r\n logger(`视频任务生成成功,文件ID: ${fileId}`);\r\n\r\n // 获取下载地址\r\n const fileResp = await axios.get(`${baseUrl}/v1/files/retrieve`, {\r\n headers: getHeaders(),\r\n params: { file_id: fileId },\r\n });\r\n if (fileResp.data.base_resp.status_code !== 0) {\r\n throw new Error(`获取文件地址失败:${fileResp.data.base_resp.status_msg}`);\r\n }\r\n const downloadUrl = fileResp.data.file.download_url;\r\n logger(`视频下载地址获取成功,开始转Base64`);\r\n\r\n return await urlToBase64(downloadUrl);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return {\r\n hasUpdate: false,\r\n latestVersion: \"2.0\",\r\n notice:\r\n \"## 新版本更新公告\\n1. 适配新版模板架构,支持 ReferenceList 统一引用类型\\n2. 新增 uploadReference 前置处理器\\n3. 优化图片压缩和引用提取逻辑\",\r\n };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.uploadReference = uploadReference;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};", - "null.ts": "/**\r\n * Toonflow AI供应商模板\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\" //单图参考\r\n | \"startEndRequired\" //首尾帧(两张都得有)\r\n | \"endFrameOptional\" //首尾帧(尾帧可选)\r\n | \"startFrameOptional\" //首尾帧(首帧可选)\r\n | \"text\" //文本\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[]; //多参考(数字代表限制数量)\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string; //唯一ID,作为文件名存储用户磁盘上,禁止符号\r\n version: string; //版本号,格式为x.y,需遵守语义化版本控制\r\n name: string; //供应商名称\r\n author: string; //作者\r\n description?: string; //描述,支持Markdown格式\r\n icon?: string; //图标,仅支持Base64格式,建议尺寸为128x128像素\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any; // HTTP请求库\r\ndeclare const logger: (msg: string) => void; // 日志函数\r\ndeclare const jsonwebtoken: any; // JWT处理库\r\ndeclare const zipImage: (base64: string, size: number) => Promise; // 图片压缩函数,返回有头base64字符串\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise; // 图片分辨率调整函数,返回有头base64字符串\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise; // 图片合成函数,返回有头base64字符串\r\ndeclare const urlToBase64: (url: string) => Promise; // URL转Base64函数,返回有头base64字符串\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise; // 轮询函数,fn为异步函数,interval为轮询间隔,timeout为超时时间,返回fn的结果\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any; //文本模型\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise; //图片模型,返回有头base64字符串\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise; //视频模型,返回有头base64字符串\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise; //(暂未开放)语音模型,返回有头base64字符串\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>; //检查更新函数,返回是否有更新和最新版本号和更公告(支持Markdown格式)\r\n updateVendor?: () => Promise; //更新函数,返回最新的代码文本\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"null\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"空模板\",\r\n description: \"## 开发模板,您可以使用此模板进行Vibe Coding\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"示例:https://api.openai.com/v1\" },\r\n ],\r\n inputValues: { apiKey: \"\", baseUrl: \"https://api.openai.com/v1\" },\r\n models: [{ name: \"GPT-4o\", modelName: \"gpt-4o\", type: \"text\", think: false }],\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createOpenAI({ baseURL: vendor.inputValues.baseUrl, apiKey }).chat(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"## 新版本更新公告\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};\r\n\r\n/**\r\n * ============================================================\r\n * AI 代码生成指南\r\n * ============================================================\r\n *\r\n * 【概述】\r\n * 本文件是 Toonflow AI 供应商适配模板。AI 在生成新供应商适配代码时,\r\n * 必须严格遵守以下规则,并要求用户提供目标平台的 curl 调用示例或 API 文档信息作为输入依据。\r\n *\r\n * 【前置要求】\r\n * 在生成代码前,请向用户索要以下信息(至少其一):\r\n * 1. 目标 API 的 curl 请求示例(包含请求地址、Headers、Body 结构、响应结构)\r\n * 2. 目标 API 的官方文档链接或文档截图/文本内容\r\n * 3. 需要适配的模型类型(text / image / video / tts)及其能力说明\r\n * 没有足够信息时,应主动追问,不要凭空编造 API 结构。\r\n *\r\n * 【代码规则】\r\n *\r\n * 1. 禁止引入任何外部包\r\n * 不可使用 import / require,仅能使用本文件「全局声明」区域中已声明的方法和对象,\r\n * 包括:axios、logger、jsonwebtoken、zipImage、zipImageResolution、mergeImages、\r\n * urlToBase64、pollTask,以及 createOpenAI、createDeepSeek、createZhipu、createQwen、\r\n * createAnthropic、createOpenAICompatible、createXai、createMinimax、\r\n * createGoogleGenerativeAI 等 AI SDK 工厂函数。\r\n *\r\n * 2. 禁止在 exports.* 函数外部声明离散的全大写常量\r\n * 错误示例:const API_URL = \"https://...\"; const MAX_RETRY = 3;\r\n * 如果确实需要可配置的常量值,必须将其声明在 vendor.inputValues 中,\r\n * 通过 vendor.inputValues.xxx 访问,让用户可在界面上配置。\r\n * 如果是纯逻辑内部使用的临时变量,应内联在对应的 exports.* 函数体内部,使用小驼峰命名。\r\n *\r\n * 3. 逻辑尽量聚合在 exports.* 对应的函数内部\r\n * 每个适配函数(textRequest / imageRequest / videoRequest / ttsRequest)\r\n * 应自包含,将请求构造、发送、轮询、结果解析等逻辑写在函数体内,避免拆分出大量外部辅助函数。\r\n * 如果多个函数确实存在公共逻辑(如签名计算、Token 生成、请求头构造),\r\n * 可提取为文件内的小驼峰命名函数,放在「适配器函数」区块之前的「辅助工具」区块中,\r\n * 且不可使用全大写命名。\r\n *\r\n * 4. 命名规范\r\n * 所有变量、函数一律使用小驼峰命名(camelCase),禁止使用 UPPER_SNAKE_CASE。\r\n *\r\n * 5. 不需要重新声明类型\r\n * 本文件顶部已完整定义了所有接口和类型(VendorConfig、ImageConfig、VideoConfig、\r\n * TTSConfig、TextModel、ImageModel、VideoModel、TTSModel、ReferenceList、PollResult 等),\r\n * AI 生成代码时直接使用即可,不要重复声明。\r\n *\r\n * 6. 返回值规范\r\n * - textRequest(model):返回 AI SDK 的 chat model 实例(通过 createOpenAI 等工厂函数创建)。\r\n * - imageRequest(config, model):返回有头 base64 字符串(如 \"data:image/png;base64,...\")。\r\n * config.referenceList 为 Extract[] 类型,\r\n * 每个引用条目均为 base64 形式(sourceType 固定为 \"base64\")。\r\n * - videoRequest(config, model):返回有头 base64 字符串(如 \"data:video/mp4;base64,...\")。\r\n * config.referenceList 为 ReferenceList[] 类型,可包含 image / video / audio 三种引用,\r\n * 每个引用条目均为 base64 形式(sourceType 固定为 \"base64\")。\r\n * config.mode 为当前激活的视频模式数组,需根据 mode 决定如何使用 referenceList。\r\n * - ttsRequest(config, model):返回有头 base64 字符串(如 \"data:audio/mp3;base64,...\")。\r\n * config.referenceList 为 Extract[] 类型(音频参考)。\r\n * 当 API 返回的是 URL 而非二进制数据时,使用 urlToBase64(url) 转换。\r\n *\r\n * 7. ReferenceList 与 VideoMode 说明\r\n * ReferenceList 是统一的多媒体引用类型,每个条目包含:\r\n * - type: \"image\" | \"audio\" | \"video\"(媒体类型)\r\n * - sourceType: \"base64\"(当前模板固定为 base64)\r\n * - base64(对应的数据)\r\n *\r\n * VideoMode 定义了视频模型支持的输入模式:\r\n * - \"text\":纯文本生成视频\r\n * - \"singleImage\":单张首帧图片\r\n * - \"startEndRequired\":首尾帧(两张都必须提供)\r\n * - \"endFrameOptional\":首尾帧(尾帧可选)\r\n * - \"startFrameOptional\":首尾帧(首帧可选)\r\n * - 数组形式如 [\"imageReference:9\", \"videoReference:3\", \"audioReference:3\"]:\r\n * 多模态参考模式,数字表示该类型的最大数量限制。\r\n *\r\n * 在 videoRequest 中,config.mode 表示当前选择的模式,需根据其值决定:\r\n * - 如何从 config.referenceList 中提取对应类型的引用\r\n * - 如何构造 API 请求体中的图片/视频/音频参数\r\n *\r\n * 8. 异步任务处理\r\n * 对于视频生成等需要轮询的异步任务,使用全局的 pollTask 函数:\r\n * const result = await pollTask(async () => {\r\n * const resp = await axios.get(...);\r\n * if (resp.data.status === \"SUCCESS\") return { completed: true, data: resp.data.url };\r\n * if (resp.data.status === \"FAILED\") return { completed: true, error: resp.data.message };\r\n * return { completed: false };\r\n * }, 5000, 600000); // 每5秒轮询,10分钟超时\r\n * if (result.error) throw new Error(result.error);\r\n * return await urlToBase64(result.data!);\r\n *\r\n * 9. 错误处理\r\n * 在每个函数开头校验必需参数(如 API Key),缺失时使用 throw new Error(\"...\") 抛出。\r\n * API 请求失败时,从响应中提取有意义的错误信息抛出,不要吞掉异常。\r\n *\r\n * 10. 日志输出\r\n * 在关键步骤使用 logger(\"...\") 输出日志(如\"开始提交任务\"、\"任务ID: xxx\"、\"轮询中...\"),\r\n * 便于调试。\r\n *\r\n * 11. vendor 配置填写\r\n * - id:纯英文小写,作为文件名使用,禁止特殊符号和空格。\r\n * - version:语义化版本格式 \"x.y\"。\r\n * - inputs:根据目标 API 所需的认证信息配置(API Key、Secret、请求地址等)。\r\n * - models:根据目标平台支持的模型列表填写,注意正确设置 type 和各模型特有字段。\r\n * - VideoModel 的 mode 对应 API 支持的输入模式(参见规则 7 的 VideoMode 说明)。\r\n * - VideoModel 的 audio 字段:true(始终生成音频)、false(不生成)、\"optional\"(用户可选)。\r\n * - VideoModel 的 durationResolutionMap 对应各时长下可选的分辨率。\r\n * - VideoModel 的 associationSkills 可选,用于描述模型的特殊能力。\r\n * - ImageModel 的 mode 对应 API 支持的生图模式(\"text\" 纯文本、\"singleImage\" 单图参考、\"multiReference\" 多图参考)。\r\n * - TTSModel 的 voices 对应可选的音色列表。\r\n *\r\n * 12. 图片处理\r\n * - 需要压缩图片体积时使用 zipImage(base64, maxSizeKB)。\r\n * - 需要调整图片分辨率时使用 zipImageResolution(base64, width, height)。\r\n * - 需要将多张图片拼合为一张时使用 mergeImages(base64Arr, maxSize)。\r\n * - 以上函数均接收和返回有头 base64 字符串。\r\n *\r\n * 13. 文件结构\r\n * 生成的代码必须保持本模板的整体结构:\r\n * 类型定义区 → 全局声明区 → 供应商配置区 → [辅助工具区(可选)] → 适配器函数区 → 导出区\r\n * 不要打乱顺序,不要删除已有的结构注释分隔线。\r\n * 辅助工具区用于放置多个适配器函数共享的小驼峰命名辅助函数(如 getHeaders、getBaseUrl)。\r\n *\r\n * 14. 导出规范\r\n * 必须导出以下字段(通过 exports.xxx = xxx 赋值):\r\n * - exports.vendor(必须)\r\n * - exports.textRequest(必须)\r\n * - exports.imageRequest(必须)\r\n * - exports.videoRequest(必须)\r\n * - exports.ttsRequest(必须)\r\n * - exports.checkForUpdates(可选)\r\n * - exports.updateVendor(可选)\r\n * 未实现的适配器函数保留空实现(return \"\"),不可省略导出。\r\n * 文件末尾必须包含 export {}; 以确保文件被识别为模块。\r\n *\r\n * 【生成流程】\r\n * 当用户请求生成新的供应商适配时:\r\n * 1. 确认用户已提供 curl 示例或 API 文档。\r\n * 2. 分析 API 的认证方式、端点地址、请求/响应结构。\r\n * 3. 基于本模板结构,填充 vendor 配置和对应的适配器函数。\r\n * 4. 根据当前模板的 ReferenceList 定义,按 base64 形式构造和消费 referenceList。\r\n * 5. 仅实现用户需要的模型类型,未用到的函数保留空实现(return \"\")。\r\n * 6. 生成完整可用的代码,确保无语法错误、无遗漏导出。\r\n */\r\n", - "openai.ts": "/**\r\n * Toonflow AI供应商模板\r\n * @version 2.0\r\n */\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\ninterface ImageConfig {\r\n prompt: string;\r\n imageBase64: string[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n imageBase64?: string[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n}\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\nconst vendor: VendorConfig = {\r\n id: \"openai\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"OpenAI标准接口\",\r\n description: \"OpenAI标准格式接口,可修改请求地址并手动添加模型。\",\r\n icon: \"\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"以v1结束,示例:https://api.openai.com/v1\" },\r\n ],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://api.openai.com/v1\",\r\n },\r\n models: [\r\n { name: \"GPT-4o\", modelName: \"gpt-4o\", type: \"text\", think: false },\r\n { name: \"GPT-4.1\", modelName: \"gpt-4.1\", type: \"text\", think: false },\r\n { name: \"GPT-5.1\", modelName: \"gpt-5.1\", type: \"text\", think: false },\r\n { name: \"GPT-5.2\", modelName: \"gpt-5.2\", type: \"text\", think: false },\r\n { name: \"GPT-5.4\", modelName: \"gpt-5.4\", type: \"text\", think: false },\r\n ],\r\n};\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createOpenAI({ baseURL: vendor.inputValues.baseUrl, apiKey }).chat(model.modelName);\r\n};\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n return \"\";\r\n};\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n return \"\";\r\n};\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"\" };\r\n};\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\nexport {};", - "toonflow.ts": "/**\r\n * Toonflow官方中转平台 供应商适配\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"toonflow\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"Toonflow官方中转平台\",\r\n description:\r\n \"## Toonflow官方中转平台\\n\\nToonflow官方中转平台,提供**文本、图像、视频、音频**等多模态生成能力的中转服务,支持接入多个大模型供应商,方便用户统一管理和调用不同供应商的生成能力。\\n\\n🔗 [前往中转平台](https://api.toonflow.net/)\\n\\n如果这个项目对你有帮助,可以考虑支持一下我们的开发工作 ☕\",\r\n icon: \"\",\r\n inputs: [{ key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true }],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://api.toonflow.net/v1\",\r\n },\r\n models: [\r\n { name: \"claude-sonnet-4-6\", type: \"text\", modelName: \"claude-sonnet-4-6\", think: false },\r\n { name: \"claude-opus-4-6\", type: \"text\", modelName: \"claude-opus-4-6\", think: false },\r\n { name: \"claude-sonnet-4-5-20250929\", type: \"text\", modelName: \"claude-sonnet-4-5-20250929\", think: false },\r\n { name: \"claude-opus-4-5-20251101\", type: \"text\", modelName: \"claude-opus-4-5-20251101\", think: false },\r\n { name: \"claude-haiku-4-5-20251001\", type: \"text\", modelName: \"claude-haiku-4-5-20251001\", think: false },\r\n { name: \"gpt-5.4\", type: \"text\", modelName: \"gpt-5.4\", think: false },\r\n { name: \"gpt-5.2\", type: \"text\", modelName: \"gpt-5.2\", think: false },\r\n { name: \"MiniMax-M2.7\", type: \"text\", modelName: \"MiniMax-M2.7\", think: true },\r\n { name: \"MiniMax-M2.5\", type: \"text\", modelName: \"MiniMax-M2.5\", think: true },\r\n {\r\n name: \"Wan2.6 I2V 1080P (支持真人)\",\r\n type: \"video\",\r\n modelName: \"Wan2.6-I2V-1080P\",\r\n mode: [\"text\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"1080p\"] }],\r\n audio: true,\r\n },\r\n {\r\n name: \"Wan2.6 I2V 720P (支持真人)\",\r\n type: \"video\",\r\n modelName: \"Wan2.6-I2V-720P\",\r\n mode: [\"text\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n audio: true,\r\n },\r\n {\r\n name: \"Seedance 1.5 Pro\",\r\n type: \"video\",\r\n modelName: \"doubao-seedance-1-5-pro-251215\",\r\n mode: [\"text\", \"endFrameOptional\"],\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n audio: true,\r\n },\r\n {\r\n name: \"vidu2 turbo\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-turbo\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n audio: false,\r\n },\r\n {\r\n name: \"ViduQ3 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ3-pro\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n audio: false,\r\n },\r\n {\r\n name: \"ViduQ2 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-pro\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n audio: false,\r\n },\r\n {\r\n name: \"Doubao Seedream 5.0 Lite\",\r\n type: \"image\",\r\n modelName: \"Doubao-Seedream-5.0-Lite\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Doubao Seedream 4.5\",\r\n type: \"image\",\r\n modelName: \"doubao-seedream-4-5-251128\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\n// 从 markdown 内容中提取第一张图片\r\nfunction extractFirstImageFromMd(content: string) {\r\n const regex = /!\\[([^\\]]*)\\]\\((data:image\\/[^;]+;base64,[A-Za-z0-9+/=]+|https?:\\/\\/[^\\s)]+|\\/\\/[^\\s)]+|[^\\s)]+)\\)/;\r\n const match = content.match(regex);\r\n if (!match) return null;\r\n const raw = match[2].trim();\r\n const url = raw.startsWith(\"data:\") ? raw : raw.split(/\\s+/)[0];\r\n return { alt: match[1], url, type: url.startsWith(\"data:image\") ? \"base64\" : \"url\" };\r\n}\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createOpenAI({ baseURL: vendor.inputValues.baseUrl, apiKey }).chat(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const lowerName = model.modelName.toLowerCase();\r\n const imageBase64List = (config.referenceList ?? []).map((r) => r.base64);\r\n\r\n // Gemini / nano 系模型:走 chat/completions 接口,从返回的 markdown 中提取图片\r\n if (lowerName.includes(\"gemini\") || lowerName.includes(\"nano\")) {\r\n const imageConfigGoogle: Record = {\r\n aspect_ratio: config.aspectRatio,\r\n image_size: config.size,\r\n };\r\n const messages: any[] = [];\r\n if (imageBase64List.length) {\r\n messages.push({\r\n role: \"user\",\r\n content: imageBase64List.map((b) => ({ type: \"image_url\", image_url: { url: b } })),\r\n });\r\n }\r\n messages.push({ role: \"user\", content: config.prompt + \"请直接输出图片\" });\r\n const body = {\r\n model: model.modelName,\r\n messages,\r\n extra_body: { google: { image_config: imageConfigGoogle } },\r\n };\r\n logger(`[imageRequest] 使用 gemini 适配器,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/chat/completions`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const imageResult = extractFirstImageFromMd(data.choices[0].message.content);\r\n if (!imageResult) throw new Error(\"未能从响应中提取图片\");\r\n if (imageResult.type === \"base64\") return imageResult.url;\r\n return await urlToBase64(imageResult.url);\r\n }\r\n\r\n // 豆包 / seedream 系模型:走 images/generations 接口\r\n if (lowerName.includes(\"doubao\") || lowerName.includes(\"seedream\")) {\r\n const effectiveSize = config.size === \"1K\" ? \"2K\" : config.size;\r\n const sizeMap: Record> = {\r\n \"16:9\": { \"2K\": \"2848x1600\", \"4K\": \"4096x2304\" },\r\n \"9:16\": { \"2K\": \"1600x2848\", \"4K\": \"2304x4096\" },\r\n };\r\n const resolvedSize = sizeMap[config.aspectRatio]?.[effectiveSize];\r\n const body: Record = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n size: resolvedSize,\r\n response_format: \"url\",\r\n sequential_image_generation: \"disabled\",\r\n stream: false,\r\n watermark: false,\r\n ...(imageBase64List.length && { image: imageBase64List }),\r\n };\r\n logger(`[imageRequest] 使用 doubao 适配器,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/images/generations`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const resultUrl = data.data[0].url;\r\n return await urlToBase64(resultUrl);\r\n }\r\n\r\n throw new Error(`不支持的图像模型: ${model.modelName}`);\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const lowerName = model.modelName.toLowerCase();\r\n\r\n // 当前激活的单一 VideoMode(取第一个非数组模式,或数组模式)\r\n const activeMode = config.mode[0];\r\n const imageRefs = (config.referenceList ?? []).filter((r) => r.type === \"image\").map((r) => r.base64);\r\n const videoRefs = (config.referenceList ?? []).filter((r) => r.type === \"video\").map((r) => r.base64);\r\n const audioRefs = (config.referenceList ?? []).filter((r) => r.type === \"audio\").map((r) => r.base64);\r\n\r\n // 构建模型专属 metadata\r\n let metadata: Record = {};\r\n\r\n if (lowerName.includes(\"wan\")) {\r\n // 万象系列\r\n if (\r\n (activeMode === \"startEndRequired\" || activeMode === \"endFrameOptional\" || activeMode === \"startFrameOptional\") &&\r\n imageRefs.length >= 2\r\n ) {\r\n if (imageRefs[0]) metadata.first_frame_url = imageRefs[0];\r\n if (imageRefs[1]) metadata.last_frame_url = imageRefs[1];\r\n } else if (imageRefs.length) {\r\n metadata.img_url = imageRefs[0];\r\n }\r\n if (typeof config.audio === \"boolean\") metadata.audio = config.audio;\r\n\r\n // 万象需要额外传 size 字段\r\n const wanSizeMap: Record> = {\r\n \"480p\": { \"16:9\": \"832*480\", \"9:16\": \"480*832\" },\r\n \"720p\": { \"16:9\": \"1280*720\", \"9:16\": \"720*1280\" },\r\n \"1080p\": { \"16:9\": \"1920*1080\", \"9:16\": \"1080*1920\" },\r\n };\r\n const wanSize = wanSizeMap[config.resolution]?.[config.aspectRatio];\r\n const body: Record = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n duration: config.duration,\r\n size: wanSize,\r\n metadata,\r\n };\r\n logger(`[videoRequest] 提交万象视频任务,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/video/generations`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const taskId = data.id;\r\n logger(`[videoRequest] 万象任务ID: ${taskId}`);\r\n const res = await pollTask(async () => {\r\n const queryResponse = await fetch(`${baseUrl}/video/generations/${taskId}`, {\r\n method: \"GET\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n });\r\n if (!queryResponse.ok) {\r\n const errorText = await queryResponse.text();\r\n throw new Error(`轮询失败,状态码: ${queryResponse.status}, 错误信息: ${errorText}`);\r\n }\r\n const queryData = await queryResponse.json();\r\n const status = queryData?.status ?? queryData?.data?.status;\r\n switch (status) {\r\n case \"completed\":\r\n case \"SUCCESS\":\r\n case \"success\":\r\n return { completed: true, data: queryData.data.result_url };\r\n case \"FAILURE\":\r\n case \"failed\":\r\n return { completed: true, error: queryData?.data?.fail_reason ?? \"视频生成失败\" };\r\n default:\r\n return { completed: false };\r\n }\r\n });\r\n if (res.error) throw new Error(res.error);\r\n return await urlToBase64(res.data!);\r\n }\r\n\r\n if (lowerName.includes(\"doubao\") || lowerName.includes(\"seedance\")) {\r\n // 豆包/Seedance 系列\r\n metadata = {\r\n ...(typeof config.audio === \"boolean\" && { generate_audio: config.audio }),\r\n ratio: config.aspectRatio,\r\n image_roles: [] as string[],\r\n references: [] as string[],\r\n };\r\n if (Array.isArray(activeMode)) {\r\n // 多参考模式\r\n imageRefs.forEach((b) => metadata.references.push(b));\r\n videoRefs.forEach((b) => metadata.references.push(b));\r\n audioRefs.forEach((b) => metadata.references.push(b));\r\n } else if (activeMode === \"startEndRequired\" || activeMode === \"endFrameOptional\" || activeMode === \"startFrameOptional\") {\r\n imageRefs.forEach((_, i) => (metadata.image_roles as string[]).push(i === 0 ? \"first_frame\" : \"last_frame\"));\r\n } else if (activeMode === \"singleImage\") {\r\n imageRefs.forEach(() => (metadata.image_roles as string[]).push(\"reference_image\"));\r\n }\r\n } else if (lowerName.includes(\"vidu\")) {\r\n // Vidu 系列\r\n metadata = {\r\n aspect_ratio: config.aspectRatio,\r\n audio: config.audio ?? false,\r\n off_peak: false,\r\n };\r\n } else if (lowerName.includes(\"kling\")) {\r\n // 可灵系列\r\n metadata = { aspect_ratio: config.aspectRatio };\r\n if (Array.isArray(activeMode)) {\r\n metadata.reference = [...imageRefs, ...videoRefs, ...audioRefs];\r\n } else if (activeMode === \"endFrameOptional\" && imageRefs.length) {\r\n metadata.image_tail = imageRefs[0];\r\n } else if (activeMode === \"startEndRequired\" && imageRefs.length >= 2) {\r\n metadata.image_list = [\r\n { image_url: imageRefs[0], type: \"first_frame\" },\r\n { image_url: imageRefs[1], type: \"last_frame\" },\r\n ];\r\n } else if (activeMode === \"singleImage\" && imageRefs.length) {\r\n metadata.image = imageRefs[0];\r\n }\r\n }\r\n\r\n // 公共请求体(非万象通用路径)\r\n const publicBody: Record = {\r\n model: model.modelName,\r\n ...(!Array.isArray(activeMode) && imageRefs.length ? { images: imageRefs } : {}),\r\n prompt: config.prompt,\r\n duration: config.duration,\r\n metadata,\r\n };\r\n\r\n logger(`[videoRequest] 提交视频任务,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/video/generations`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(publicBody),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const taskId = data.id;\r\n logger(`[videoRequest] 任务ID: ${taskId}`);\r\n\r\n const res = await pollTask(async () => {\r\n const queryResponse = await fetch(`${baseUrl}/video/generations/${taskId}`, {\r\n method: \"GET\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n });\r\n if (!queryResponse.ok) {\r\n const errorText = await queryResponse.text();\r\n throw new Error(`轮询失败,状态码: ${queryResponse.status}, 错误信息: ${errorText}`);\r\n }\r\n const queryData = await queryResponse.json();\r\n const status = queryData?.status ?? queryData?.data?.status;\r\n switch (status) {\r\n case \"completed\":\r\n case \"SUCCESS\":\r\n case \"success\":\r\n return { completed: true, data: queryData.data.result_url };\r\n case \"FAILURE\":\r\n case \"failed\":\r\n return { completed: true, error: queryData?.data?.fail_reason ?? \"视频生成失败\" };\r\n default:\r\n return { completed: false };\r\n }\r\n });\r\n\r\n if (res.error) throw new Error(res.error);\r\n return await urlToBase64(res.data!);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\nexport {};", - "vidu.ts": "//如需遥测AI请使用在toonflow安装目录运行npx @ai-sdk/devtools (要求在其他设置中打开遥测功能,且toonflow有权限在安装目录创建.devtools文件夹)\r\n// ==================== 类型定义 ====================\r\n// 文本模型\r\ninterface TextModel {\r\n name: string; // 显示名称\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean; // 前端显示用\r\n}\r\n\r\n// 图像模型\r\ninterface ImageModel {\r\n name: string; // 显示名称\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string; // 关联技能,多个技能用逗号分隔\r\n}\r\n// 视频模型\r\ninterface VideoModel {\r\n name: string; // 显示名称\r\n modelName: string; //全局唯一\r\n type: \"video\";\r\n mode: (\r\n | \"singleImage\" // 单图\r\n | \"startEndRequired\" // 首尾帧(两张都得有)\r\n | \"endFrameOptional\" // 首尾帧(尾帧可选)\r\n | \"startFrameOptional\" // 首尾帧(首帧可选)\r\n | \"text\" // 文本生视频\r\n | (\"videoReference\" | \"imageReference\" | \"audioReference\" | \"textReference\")[] // 混合参考\r\n )[];\r\n associationSkills?: string; // 关联技能,多个技能用逗号分隔\r\n audio: \"optional\" | false | true; // 音频配置\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string; // 显示名称\r\n modelName: string;\r\n type: \"tts\";\r\n voices: {\r\n title: string; //显示名称\r\n voice: string; //说话人\r\n }[];\r\n}\r\n// 供应商配置\r\ninterface VendorConfig {\r\n id: string; //供应商唯一标识,必须全局唯一\r\n author: string;\r\n description?: string; //md5格式\r\n name: string;\r\n icon?: string; //仅支持base64格式\r\n inputs: {\r\n key: string;\r\n label: string;\r\n type: \"text\" | \"password\" | \"url\";\r\n required: boolean;\r\n placeholder?: string;\r\n }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel)[];\r\n}\r\n// ==================== 全局工具函数 ====================\r\n//Axios实例\r\n//压缩图片大小(1MB = 1 * 1024 * 1024)\r\ndeclare const zipImage: (completeBase64: string, size: number) => Promise;\r\n//压缩图片分辨率\r\ndeclare const zipImageResolution: (completeBase64: string, width: number, height: number) => Promise;\r\n//多图拼接乘单图 maxSize 最大输出大小,默认为 10mb\r\ndeclare const mergeImages: (completeBase64: string[], maxSize?: string) => Promise;\r\n//Url转Base64\r\ndeclare const urlToBase64: (url: string) => Promise;\r\n//轮询函数\r\ndeclare const pollTask: (\r\n fn: () => Promise<{ completed: boolean; data?: string; error?: string }>,\r\n interval?: number,\r\n timeout?: number,\r\n) => Promise<{ completed: boolean; data?: string; error?: string }>;\r\ndeclare const axios: any;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const logger: (logstring: string) => void;\r\ndeclare const jsonwebtoken: any;\r\n// ==================== 供应商数据 ====================\r\nconst vendor: VendorConfig = {\r\n id: \"vidu\",\r\n author: \"搬砖的Coder\",\r\n description:\r\n \"Vidu 官方视频生成平台。 [前往平台](https://platform.vidu.cn/login/)\",\r\n name: \"Vidu 开放平台\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true, placeholder: \"请到Vidu官方申请\" },\r\n { key: \"baseUrl\", label: \"接口路径\", type: \"url\", required: true, placeholder: \"https://api.vidu.cn/ent/v2\" },\r\n ],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://api.vidu.cn/ent/v2\",\r\n },\r\n models: [\r\n {\r\n name: \"ViduQ3 turbo\",\r\n type: \"video\",\r\n modelName: \"ViduQ3-turbo\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\", \"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ3 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ3-pro\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\", \"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ2 pro fast\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-pro-fast\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"viduQ2 turbo\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-turbo\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ2 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-pro\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"], //参考生视频无有效设置值\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ2\",\r\n type: \"video\",\r\n modelName: \"ViduQ2\",\r\n durationResolutionMap: [{ duration: [5], resolution: [\"1080p\"] }],\r\n mode: [\"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ1\",\r\n type: \"video\",\r\n modelName: \"ViduQ1\",\r\n durationResolutionMap: [{ duration: [5], resolution: [\"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\", \"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ1 classic\",\r\n type: \"video\",\r\n modelName: \"viduQ1-classic\",\r\n durationResolutionMap: [{ duration: [5], resolution: [\"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"Vidu2.0\",\r\n type: \"video\",\r\n modelName: \"vidu2.0\",\r\n durationResolutionMap: [{ duration: [4, 8], resolution: [\"360p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"viduq1 for image\",\r\n type: \"image\",\r\n modelName: \"viduq1\",\r\n mode: [\"text\"],\r\n },\r\n {\r\n name: \"viduq2 for image\",\r\n type: \"image\",\r\n modelName: \"viduq2\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n ],\r\n};\r\nexports.vendor = vendor;\r\n\r\n// ==================== 适配器函数 ====================\r\n\r\n// 文本请求函数\r\nconst textRequest: (textModel: TextModel) => { url: string; model: string } = (textModel) => {\r\n throw new Error(\"当前供应商仅支持视频大模型,谢谢!\");\r\n};\r\nexports.textRequest = textRequest;\r\n\r\n//图片请求函数\r\ninterface ImageConfig {\r\n prompt: string; //图片提示词\r\n imageBase64: string[]; //输入的图片提示词\r\n size: \"1K\" | \"2K\" | \"4K\"; // 图片尺寸\r\n aspectRatio: `${number}:${number}`; // 长宽比\r\n}\r\nconst imageRequest = async (imageConfig: ImageConfig, imageModel: ImageModel) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(\"Token \", \"\");\r\n\r\n const size = imageConfig.size === \"1K\" ? \"2K\" : imageConfig.size;\r\n const sizeMap: Record> = {\r\n \"16:9\": {\r\n \"1k\": \"1920x1080\",\r\n \"2K\": \"2848x1600\",\r\n \"4K\": \"4096x2304\",\r\n },\r\n \"9:16\": {\r\n \"1k\": \"1920x1080\",\r\n \"2K\": \"1600x2848\",\r\n \"4K\": \"2304x4096\",\r\n },\r\n };\r\n\r\n const body: Record = {\r\n model: imageModel.modelName,\r\n prompt: imageConfig.prompt,\r\n aspect_ratio: sizeMap[imageConfig.aspectRatio][size],\r\n seed: 0,\r\n resolution: size,\r\n ...(imageConfig.imageBase64 && { image: imageConfig.imageBase64 }),\r\n };\r\n\r\n const createImageUrl = vendor.inputValues.baseUrl + \"/reference2image\";\r\n const response = await fetch(createImageUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Token ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text(); // 获取错误信息\r\n console.error(\"请求失败,状态码:\", response.status, \", 错误信息:\", errorText);\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const res = await checkTaskResult(data.task_id);\r\n if (!res.data) {\r\n throw new Error(\"图片未能生成\");\r\n }\r\n const list = JSON.parse(JSON.stringify(res.data));\r\n return list[0].url;\r\n};\r\nexports.imageRequest = imageRequest;\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n imageBase64?: string[];\r\n audio?: boolean;\r\n mode:\r\n | \"singleImage\" // 单图\r\n | \"multiImage\" // 多图模式\r\n | \"gridImage\" // 网格单图(传入一张图片,但该图片是网格图)\r\n | \"startEndRequired\" // 首尾帧(两张都得有)\r\n | \"endFrameOptional\" // 首尾帧(尾帧可选)\r\n | \"startFrameOptional\" // 首尾帧(首帧可选)\r\n | \"text\" // 文本生视频\r\n | (\"video\" | \"image\" | \"audio\" | \"text\")[]; // 混合参考\r\n}\r\n\r\n// 构建 各个平台的metadata参数\r\n\r\nconst buildViduMetadata = (videoConfig: VideoConfig) => ({\r\n aspect_ratio: videoConfig.aspectRatio,\r\n audio: videoConfig.audio ?? false,\r\n off_peak: false,\r\n});\r\n\r\ntype MetadataBuilder = (config: VideoConfig) => Record;\r\nconst METADATA_BUILDERS: Array<[string, MetadataBuilder]> = [[\"vidu\", buildViduMetadata]];\r\nconst buildModelMetadata = (modelName: string, videoConfig: VideoConfig) => {\r\n const lowerName = modelName.toLowerCase();\r\n const match = METADATA_BUILDERS.find(([key]) => lowerName.includes(key));\r\n return match ? match[1](videoConfig) : {};\r\n};\r\n// 检查生成物结果\r\nconst checkTaskResult = async (taskId: string) => {\r\n const queryUrl = vendor.inputValues.baseUrl + \"/tasks/{id}/creations\";\r\n const apiKey = vendor.inputValues.apiKey;\r\n const res = await pollTask(async () => {\r\n const queryResponse = await fetch(queryUrl.replace(\"{id}\", taskId), {\r\n method: \"GET\",\r\n headers: { Authorization: `Token ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n });\r\n if (!queryResponse.ok) {\r\n const errorText = await queryResponse.text(); // 获取错误信息\r\n console.error(\"请求失败,状态码:\", queryResponse.status, \", 错误信息:\", errorText);\r\n throw new Error(`请求失败,状态码: ${queryResponse.status}, 错误信息: ${errorText}`);\r\n }\r\n const queryData = await queryResponse.json();\r\n const status = queryData?.state ?? queryData?.data?.state;\r\n const fail_reason = queryData?.data?.err_code ?? queryData?.data;\r\n switch (status) {\r\n case \"completed\":\r\n case \"SUCCESS\":\r\n case \"success\":\r\n return { completed: true, data: queryData.creations };\r\n case \"FAILURE\":\r\n case \"failed\":\r\n return { completed: false, error: fail_reason || \"生成失败\" };\r\n default:\r\n return { completed: false };\r\n }\r\n });\r\n if (res.error) throw new Error(res.error);\r\n return res;\r\n};\r\n\r\nconst videoRequest = async (videoConfig: VideoConfig, videoModel: VideoModel) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(\"Token \", \"\");\r\n\r\n // 构建每个模型对应的附加参数\r\n const metadata = buildModelMetadata(videoModel.modelName, videoConfig);\r\n\r\n //公共请求参数\r\n const publicBody = {\r\n model: videoModel.modelName,\r\n ...(videoConfig.imageBase64 && videoConfig.imageBase64.length ? { images: videoConfig.imageBase64 } : {}),\r\n prompt: videoConfig.prompt,\r\n size: videoConfig.resolution,\r\n duration: videoConfig.duration,\r\n metadata: metadata,\r\n };\r\n\r\n const requestUrl = vendor.inputValues.baseUrl + \"/start-end2video\";\r\n const response = await fetch(requestUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Token ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(publicBody),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text(); // 获取错误信息\r\n console.error(\"请求失败,状态码:\", response.status, \", 错误信息:\", errorText);\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const taskId = data.id;\r\n const result = await checkTaskResult(taskId);\r\n return result.data;\r\n};\r\nexports.videoRequest = videoRequest;\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n}\r\nconst ttsRequest = async (ttsConfig: TTSConfig, ttsModel: TTSModel) => {\r\n throw new Error(\"Vidu 暂不支持语音合成(TTS)\");\r\n};\r\n", - "volcengine.ts": "/**\r\n * Toonflow AI供应商模板 - 火山引擎(豆包)\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"volcengine\",\r\n version: \"2.2\",\r\n author: \"leeqi\",\r\n name: \"火山引擎(豆包)\",\r\n description:\r\n \"火山引擎豆包大模型,支持文本、图片生成、视频生成等能力。\\n\\n需要在[火山引擎控制台](https://console.volcengine.com/ark)获取API密钥。\",\r\n icon: \"\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true, placeholder: \"火山引擎API Key\" },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"以v3结束,示例:https://ark.cn-beijing.volces.com/api/v3\" },\r\n ],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://ark.cn-beijing.volces.com/api/v3\",\r\n },\r\n models: [\r\n // ===================== 文本模型 - 推荐 =====================\r\n { name: \"Doubao-Seed-2.0-Pro\", modelName: \"doubao-seed-2-0-pro-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-2.0-Lite\", modelName: \"doubao-seed-2-0-lite-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-2.0-Mini\", modelName: \"doubao-seed-2-0-mini-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-2.0-Code-Preview\", modelName: \"doubao-seed-2-0-code-preview-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-Character\", modelName: \"doubao-seed-character-251128\", type: \"text\", think: false },\r\n // ===================== 文本模型 - 往期 =====================\r\n { name: \"Doubao-Seed-1.8\", modelName: \"doubao-seed-1-8-251228\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-Code-Preview\", modelName: \"doubao-seed-code-preview-251028\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Lite\", modelName: \"doubao-seed-1-6-lite-251015\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Flash(0828)\", modelName: \"doubao-seed-1-6-flash-250828\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Vision\", modelName: \"doubao-seed-1-6-vision-250815\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6(1015)\", modelName: \"doubao-seed-1-6-251015\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6(0615)\", modelName: \"doubao-seed-1-6-250615\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Flash(0615)\", modelName: \"doubao-seed-1-6-flash-250615\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-Translation\", modelName: \"doubao-seed-translation-250915\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Pro-32K\", modelName: \"doubao-1-5-pro-32k-250115\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Pro-32K-Character(0715)\", modelName: \"doubao-1-5-pro-32k-character-250715\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Pro-32K-Character(0228)\", modelName: \"doubao-1-5-pro-32k-character-250228\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Lite-32K\", modelName: \"doubao-1-5-lite-32k-250115\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Vision-Pro-32K\", modelName: \"doubao-1-5-vision-pro-32k-250115\", type: \"text\", think: false },\r\n // ===================== 文本模型 - 第三方(火山引擎托管) =====================\r\n { name: \"GLM-4-7\", modelName: \"glm-4-7-251222\", type: \"text\", think: true },\r\n { name: \"DeepSeek-V3-2\", modelName: \"deepseek-v3-2-251201\", type: \"text\", think: true },\r\n { name: \"DeepSeek-V3-1-Terminus\", modelName: \"deepseek-v3-1-terminus\", type: \"text\", think: true },\r\n { name: \"DeepSeek-V3(0324)\", modelName: \"deepseek-v3-250324\", type: \"text\", think: false },\r\n { name: \"DeepSeek-R1(0528)\", modelName: \"deepseek-r1-250528\", type: \"text\", think: true },\r\n { name: \"Qwen3-32B\", modelName: \"qwen3-32b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen3-14B\", modelName: \"qwen3-14b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen3-8B\", modelName: \"qwen3-8b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen3-0.6B\", modelName: \"qwen3-0-6b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen2.5-72B\", modelName: \"qwen2-5-72b-20240919\", type: \"text\", think: false },\r\n { name: \"GLM-4.5-Air\", modelName: \"glm-4-5-air\", type: \"text\", think: false },\r\n // ===================== 图片生成模型 =====================\r\n {\r\n name: \"Seedream-5.0\",\r\n modelName: \"doubao-seedream-5-0-260128\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-5.0-Lite\",\r\n modelName: \"doubao-seedream-5-0-lite-260128\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-4.5\",\r\n modelName: \"doubao-seedream-4-5-251128\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-4.0\",\r\n modelName: \"doubao-seedream-4-0-250828\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-3.0-T2I\",\r\n modelName: \"doubao-seedream-3-0-t2i-250415\",\r\n type: \"image\",\r\n mode: [\"text\"],\r\n },\r\n // ===================== 视频生成模型 =====================\r\n {\r\n name: \"Seedance-2.0(音画同生)\",\r\n modelName: \"doubao-seedance-2-0-260128\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\", [\"imageReference:9\", \"videoReference:3\", \"audioReference:3\"]],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"480p\", \"720p\"] }],\r\n },\r\n {\r\n name: \"Seedance-2.0-Fast(音画同生)\",\r\n modelName: \"doubao-seedance-2-0-fast-260128\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\", [\"imageReference:9\", \"videoReference:3\", \"audioReference:3\"]],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"480p\", \"720p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.5-Pro(音画同生)\",\r\n modelName: \"doubao-seedance-1-5-pro-251215\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\"],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Pro\",\r\n modelName: \"doubao-seedance-1-0-pro-250528\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Pro-Fast\",\r\n modelName: \"doubao-seedance-1-0-pro-fast-251015\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Lite-T2V\",\r\n modelName: \"doubao-seedance-1-0-lite-t2v-250428\",\r\n type: \"video\",\r\n mode: [\"text\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Lite-I2V\",\r\n modelName: \"doubao-seedance-1-0-lite-i2v-250428\",\r\n type: \"video\",\r\n mode: [\"startFrameOptional\", [\"imageReference:4\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\nconst getHeaders = () => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n return {\r\n \"Content-Type\": \"application/json\",\r\n Authorization: `Bearer ${vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\")}`,\r\n };\r\n};\r\n\r\nconst getBaseUrl = () => vendor.inputValues.baseUrl.replace(/\\/+$/, \"\");\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n\r\n const effortMap: Record = {\r\n 0: \"minimal\",\r\n 1: \"low\",\r\n 2: \"medium\",\r\n 3: \"high\",\r\n };\r\n\r\n return createOpenAICompatible({\r\n name: \"volcengine\",\r\n baseURL: getBaseUrl(),\r\n apiKey,\r\n fetch: async (url: string, options?: RequestInit) => {\r\n const rawBody = JSON.parse((options?.body as string) ?? \"{}\");\r\n const modifiedBody = {\r\n ...rawBody,\r\n thinking: {\r\n type: \"enabled\",\r\n },\r\n reasoning_effort: effortMap[thinkLevel],\r\n };\r\n return await fetch(url, {\r\n ...options,\r\n body: JSON.stringify(modifiedBody),\r\n });\r\n },\r\n }).chatModel(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const body: any = {\r\n model: model.modelName,\r\n prompt: config.prompt || \"\",\r\n response_format: \"url\",\r\n watermark: false,\r\n };\r\n\r\n const isOldModel = model.modelName.includes(\"seedream-3-0\");\r\n const is5Lite = model.modelName.includes(\"seedream-5-0-lite\");\r\n\r\n // sequential_image_generation 仅 seedream 5.0-lite/4.5/4.0 支持\r\n if (!isOldModel) {\r\n body.sequential_image_generation = \"disabled\";\r\n }\r\n\r\n // 参考图片:单图为 string,多图为 array(seedream-3.0-t2i 不支持 image 参数)\r\n if (!isOldModel && config.referenceList && config.referenceList.length > 0) {\r\n const images = config.referenceList.map((ref) => ref.base64);\r\n body.image = images.length === 1 ? images[0] : images;\r\n }\r\n\r\n // 尺寸处理:优先使用推荐像素值,未匹配则直接传分辨率字符串让模型自行决定\r\n const [w, h] = config.aspectRatio.split(\":\").map(Number);\r\n const sizeTable: Record> = {\r\n \"1K\": {\r\n \"1:1\": \"1024x1024\",\r\n \"4:3\": \"1152x864\",\r\n \"3:4\": \"864x1152\",\r\n \"16:9\": \"1280x720\",\r\n \"9:16\": \"720x1280\",\r\n \"3:2\": \"1248x832\",\r\n \"2:3\": \"832x1248\",\r\n \"21:9\": \"1512x648\",\r\n },\r\n \"2K\": {\r\n \"1:1\": \"2048x2048\",\r\n \"4:3\": \"2304x1728\",\r\n \"3:4\": \"1728x2304\",\r\n \"16:9\": \"2848x1600\",\r\n \"9:16\": \"1600x2848\",\r\n \"3:2\": \"2496x1664\",\r\n \"2:3\": \"1664x2496\",\r\n \"21:9\": \"3136x1344\",\r\n },\r\n \"4K\": {\r\n \"1:1\": \"4096x4096\",\r\n \"4:3\": \"4704x3520\",\r\n \"3:4\": \"3520x4704\",\r\n \"16:9\": \"5504x3040\",\r\n \"9:16\": \"3040x5504\",\r\n \"3:2\": \"4992x3328\",\r\n \"2:3\": \"3328x4992\",\r\n \"21:9\": \"6240x2656\",\r\n },\r\n };\r\n\r\n const sizeKey = config.size || \"2K\";\r\n const ratioKey = config.aspectRatio;\r\n const table = sizeTable[sizeKey];\r\n\r\n if (table && table[ratioKey]) {\r\n // 推荐像素值匹配到了,但需要检查是否满足模型最低像素要求\r\n const [pw, ph] = table[ratioKey].split(\"x\").map(Number);\r\n const totalPixels = pw * ph;\r\n if (isOldModel) {\r\n // seedream-3.0-t2i: 像素范围 [512x512, 2048x2048]\r\n body.size = table[ratioKey];\r\n } else if (totalPixels < 3686400) {\r\n // 1K 像素值不满足新模型最低要求,直接传 \"2K\" 让模型自行决定\r\n body.size = \"2K\";\r\n } else if (is5Lite && totalPixels > 10404496) {\r\n // seedream-5.0-lite 最高 10404496,4K 超限,回退传 \"2K\"\r\n body.size = \"2K\";\r\n } else {\r\n body.size = table[ratioKey];\r\n }\r\n } else if (isOldModel) {\r\n // seedream-3.0-t2i: 像素范围 [512x512, 2048x2048],直接按比例计算\r\n const base = sizeKey === \"1K\" ? 1024 : 2048;\r\n const calcW = Math.min(2048, Math.round(base * Math.sqrt(w / h)));\r\n const calcH = Math.min(2048, Math.round(base * Math.sqrt(h / w)));\r\n body.size = `${Math.max(512, calcW)}x${Math.max(512, calcH)}`;\r\n } else {\r\n // 新模型未匹配推荐值时,直接传分辨率字符串(方式1),由模型根据 prompt 自行决定尺寸\r\n // seedream 5.0-lite 支持 \"2K\"/\"3K\",seedream 4.5 支持 \"2K\"/\"4K\",seedream 4.0 支持 \"1K\"/\"2K\"/\"4K\"\r\n if (is5Lite) {\r\n body.size = sizeKey === \"4K\" ? \"3K\" : sizeKey === \"1K\" ? \"2K\" : sizeKey;\r\n } else {\r\n body.size = sizeKey === \"1K\" ? \"2K\" : sizeKey;\r\n }\r\n }\r\n\r\n logger(`[图片生成] 请求模型: ${model.modelName}, 尺寸: ${body.size}`);\r\n\r\n const response = await axios.post(`${baseUrl}/images/generations`, body, { headers });\r\n const data = response.data;\r\n\r\n if (data?.error) {\r\n throw new Error(`图片生成失败:${data.error.message || data.error.code}`);\r\n }\r\n\r\n // 从 data 数组中提取第一张成功的图片\r\n if (data?.data && data.data.length > 0) {\r\n for (const item of data.data) {\r\n if (item.url) {\r\n return await urlToBase64(item.url);\r\n }\r\n if (item.b64_json) {\r\n return item.b64_json;\r\n }\r\n if (item.error) {\r\n throw new Error(`图片生成失败:${item.error.message || item.error.code}`);\r\n }\r\n }\r\n }\r\n\r\n throw new Error(\"图片生成失败:未返回有效结果\");\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const content: any[] = [];\r\n\r\n if (config.prompt) {\r\n content.push({ type: \"text\", text: config.prompt });\r\n }\r\n\r\n const activeMode = config.mode && config.mode.length > 0 ? config.mode[0] : \"text\";\r\n\r\n if (typeof activeMode === \"string\") {\r\n switch (activeMode) {\r\n case \"singleImage\": {\r\n const firstImage = config.referenceList?.find((r) => r.type === \"image\");\r\n if (firstImage) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: firstImage.base64 },\r\n role: \"first_frame\",\r\n });\r\n }\r\n break;\r\n }\r\n case \"startFrameOptional\": {\r\n const images = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n if (images.length > 0) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[0].base64 },\r\n role: \"first_frame\",\r\n });\r\n if (images.length > 1) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[1].base64 },\r\n role: \"last_frame\",\r\n });\r\n }\r\n }\r\n break;\r\n }\r\n case \"startEndRequired\": {\r\n const images = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n if (images.length >= 2) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[0].base64 },\r\n role: \"first_frame\",\r\n });\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[1].base64 },\r\n role: \"last_frame\",\r\n });\r\n }\r\n break;\r\n }\r\n case \"endFrameOptional\": {\r\n const images = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n if (images.length > 0) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[0].base64 },\r\n role: \"first_frame\",\r\n });\r\n if (images.length > 1) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[1].base64 },\r\n role: \"last_frame\",\r\n });\r\n }\r\n }\r\n break;\r\n }\r\n case \"text\":\r\n default:\r\n break;\r\n }\r\n } else if (Array.isArray(activeMode)) {\r\n // 多模态参考模式:按类型分别提取并添加\r\n const imageRefs = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n const videoRefs = config.referenceList?.filter((r) => r.type === \"video\") ?? [];\r\n const audioRefs = config.referenceList?.filter((r) => r.type === \"audio\") ?? [];\r\n\r\n for (const refDef of activeMode) {\r\n if (typeof refDef === \"string\") {\r\n if (refDef.startsWith(\"imageReference:\")) {\r\n const maxCount = parseInt(refDef.split(\":\")[1], 10);\r\n for (const ref of imageRefs.slice(0, maxCount)) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: ref.base64 },\r\n role: \"reference_image\",\r\n });\r\n }\r\n } else if (refDef.startsWith(\"videoReference:\")) {\r\n const maxCount = parseInt(refDef.split(\":\")[1], 10);\r\n for (const ref of videoRefs.slice(0, maxCount)) {\r\n content.push({\r\n type: \"video_url\",\r\n video_url: { url: ref.base64 },\r\n role: \"reference_video\",\r\n });\r\n }\r\n } else if (refDef.startsWith(\"audioReference:\")) {\r\n const maxCount = parseInt(refDef.split(\":\")[1], 10);\r\n for (const ref of audioRefs.slice(0, maxCount)) {\r\n content.push({\r\n type: \"audio_url\",\r\n audio_url: { url: ref.base64 },\r\n role: \"reference_audio\",\r\n });\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n const body: any = {\r\n model: model.modelName,\r\n content,\r\n ratio: config.aspectRatio,\r\n duration: config.duration,\r\n resolution: config.resolution || \"720p\",\r\n watermark: false,\r\n };\r\n\r\n if (model.audio === \"optional\") {\r\n body.generate_audio = config.audio !== false;\r\n } else if (model.audio === true) {\r\n body.generate_audio = true;\r\n } else {\r\n body.generate_audio = false;\r\n }\r\n\r\n logger(`[视频生成] 提交任务, 模型: ${model.modelName}, 时长: ${config.duration}s, 分辨率: ${config.resolution}`);\r\n\r\n const createResponse = await axios.post(`${baseUrl}/contents/generations/tasks`, body, { headers });\r\n const taskId = createResponse.data?.id;\r\n\r\n if (!taskId) {\r\n throw new Error(\"视频生成任务创建失败:未返回任务ID\");\r\n }\r\n\r\n logger(`[视频生成] 任务已创建, ID: ${taskId}`);\r\n\r\n const result = await pollTask(\r\n async (): Promise => {\r\n const queryResponse = await axios.get(`${baseUrl}/contents/generations/tasks/${taskId}`, { headers });\r\n const task = queryResponse.data;\r\n\r\n logger(`[视频生成] 任务状态: ${task.status}`);\r\n\r\n switch (task.status) {\r\n case \"succeeded\":\r\n if (task.content?.video_url) {\r\n return { completed: true, data: task.content.video_url };\r\n }\r\n return { completed: true, error: \"任务成功但未返回视频URL\" };\r\n case \"failed\":\r\n return { completed: true, error: task.error?.message || \"视频生成失败\" };\r\n case \"expired\":\r\n return { completed: true, error: \"视频生成任务超时\" };\r\n case \"cancelled\":\r\n return { completed: true, error: \"视频生成任务已取消\" };\r\n default:\r\n return { completed: false };\r\n }\r\n },\r\n 10000,\r\n 600000,\r\n );\r\n\r\n if (result.error) {\r\n throw new Error(result.error);\r\n }\r\n\r\n return await urlToBase64(result.data!);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\nexport {};\r\n" -}; - //迁移供应商函数 const data = await knex("o_vendorConfig").select("*"); for (const item of data) { diff --git a/src/lib/vendor.json b/src/lib/vendor.json new file mode 100644 index 0000000..1a0fb9c --- /dev/null +++ b/src/lib/vendor.json @@ -0,0 +1,10 @@ +{ + "grsai.ts": "/**\r\n * Toonflow AI供应商模板\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\" //单图参考\r\n | \"startEndRequired\" //首尾帧(两张都得有)\r\n | \"endFrameOptional\" //首尾帧(尾帧可选)\r\n | \"startFrameOptional\" //首尾帧(首帧可选)\r\n | \"text\" //文本\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[]; //多参考(数字代表限制数量)\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string; //唯一ID,作为文件名存储用户磁盘上,禁止符号\r\n version: string; //版本号,格式为x.y,需遵守语义化版本控制\r\n name: string; //供应商名称\r\n author: string; //作者\r\n description?: string; //描述,支持Markdown格式\r\n icon?: string; //图标,仅支持Base64格式,建议尺寸为128x128像素\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any; // HTTP请求库\r\ndeclare const logger: (msg: string) => void; // 日志函数\r\ndeclare const jsonwebtoken: any; // JWT处理库\r\ndeclare const zipImage: (base64: string, size: number) => Promise; // 图片压缩函数,返回有头base64字符串\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise; // 图片分辨率调整函数,返回有头base64字符串\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise; // 图片合成函数,返回有头base64字符串\r\ndeclare const urlToBase64: (url: string) => Promise; // URL转Base64函数,返回有头base64字符串\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise; // 轮询函数,fn为异步函数,interval为轮询间隔,timeout为超时时间,返回fn的结果\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any; //文本模型\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise; //图片模型,返回有头base64字符串\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise; //视频模型,返回有头base64字符串\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise; //(暂未开放)语音模型,返回有头base64字符串\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>; //检查更新函数,返回是否有更新和最新版本号和更公告(支持Markdown格式)\r\n updateVendor?: () => Promise; //更新函数,返回最新的代码文本\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"grsai\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"Grsai\",\r\n description: \"Grsai AI平台适配,支持文生图、图生图、文生视频、Gemini兼容文本模型 \\n [前往中转平台](https://tf.grsai.ai/zh)\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"示例:https://grsai.dakka.com.cn\" },\r\n ],\r\n inputValues: { apiKey: \"\", baseUrl: \"https://grsai.dakka.com.cn\" },\r\n models: [\r\n { name: \"Nano Banana Fast\", modelName: \"nano-banana-fast\", type: \"image\", mode: [\"text\", \"singleImage\", \"multiReference\"] },\r\n { name: \"Nano Banana 2\", modelName: \"nano-banana-2\", type: \"image\", mode: [\"text\", \"singleImage\", \"multiReference\"] },\r\n { name: \"Nano Banana Pro\", modelName: \"nano-banana-pro\", type: \"image\", mode: [\"text\", \"singleImage\", \"multiReference\"] },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\nconst getHeaders = () => {\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return {\r\n \"Content-Type\": \"application/json\",\r\n Authorization: `Bearer ${apiKey}`,\r\n };\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createGoogleGenerativeAI({\r\n baseURL: `${vendor.inputValues.baseUrl}/v1beta`,\r\n apiKey,\r\n }).chat(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const headers = getHeaders();\r\n\r\n // 构造请求参数\r\n const requestBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n aspectRatio: config.aspectRatio,\r\n webHook: \"-1\",\r\n shutProgress: true,\r\n };\r\n\r\n // 补充模型专属参数\r\n if (model.modelName.startsWith(\"nano-banana\")) {\r\n requestBody.imageSize = config.size;\r\n } else {\r\n requestBody.size = config.aspectRatio;\r\n requestBody.variants = 1;\r\n }\r\n\r\n // 处理参考图\r\n if (config.referenceList && config.referenceList.length > 0) {\r\n requestBody.urls = config.referenceList.map((img) => img.base64);\r\n }\r\n\r\n // 选择接口路径\r\n const apiPath = model.modelName.startsWith(\"nano-banana\") ? \"/v1/draw/nano-banana\" : \"/v1/draw/completions\";\r\n\r\n logger(`开始提交图片生成任务,模型:${model.modelName}`);\r\n const submitResp = await axios.post(`${baseUrl}${apiPath}`, requestBody, { headers });\r\n if (submitResp.data.code !== 0) throw new Error(`任务提交失败:${submitResp.data.msg}`);\r\n\r\n const taskId = submitResp.data.data.id;\r\n logger(`图片任务提交成功,任务ID:${taskId}`);\r\n\r\n // 轮询结果\r\n const pollResult = await pollTask(\r\n async () => {\r\n const resp = await axios.post(`${baseUrl}/v1/draw/result`, { id: taskId }, { headers });\r\n if (resp.data.code !== 0) return { completed: true, error: resp.data.msg };\r\n\r\n const taskData = resp.data.data;\r\n if (taskData.status === \"failed\") return { completed: true, error: taskData.failure_reason || taskData.error };\r\n if (taskData.status === \"succeeded\") {\r\n const imgUrl = taskData.results?.[0]?.url || taskData.url;\r\n return { completed: true, data: imgUrl };\r\n }\r\n logger(`图片任务生成中,进度:${taskData.progress}%`);\r\n return { completed: false };\r\n },\r\n 3000,\r\n 600000,\r\n );\r\n\r\n if (pollResult.error) throw new Error(pollResult.error);\r\n logger(`图片生成完成,开始转换Base64`);\r\n return await urlToBase64(pollResult.data!);\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const headers = getHeaders();\r\n\r\n // 构造请求参数\r\n const requestBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n aspectRatio: config.aspectRatio,\r\n webHook: \"-1\",\r\n shutProgress: true,\r\n };\r\n\r\n // 处理参考资源\r\n if (config.referenceList && config.referenceList.length > 0) {\r\n const imageRefs = config.referenceList.filter((item) => item.type === \"image\") as Extract[];\r\n if (config.mode.includes(\"endFrameOptional\") && imageRefs.length >= 1) {\r\n requestBody.firstFrameUrl = imageRefs[0].base64;\r\n if (imageRefs.length >= 2) requestBody.lastFrameUrl = imageRefs[1].base64;\r\n } else if (config.mode.some((m) => Array.isArray(m) && m.includes(\"imageReference:3\"))) {\r\n requestBody.urls = imageRefs.map((img) => img.base64);\r\n }\r\n }\r\n\r\n logger(`开始提交视频生成任务,模型:${model.modelName}`);\r\n const submitResp = await axios.post(`${baseUrl}/v1/video/veo`, requestBody, { headers });\r\n if (submitResp.data.code !== 0) throw new Error(`任务提交失败:${submitResp.data.msg}`);\r\n\r\n const taskId = submitResp.data.data.id;\r\n logger(`视频任务提交成功,任务ID:${taskId}`);\r\n\r\n // 轮询结果\r\n const pollResult = await pollTask(\r\n async () => {\r\n const resp = await axios.post(`${baseUrl}/v1/draw/result`, { id: taskId }, { headers });\r\n if (resp.data.code !== 0) return { completed: true, error: resp.data.msg };\r\n\r\n const taskData = resp.data.data;\r\n if (taskData.status === \"failed\") return { completed: true, error: taskData.failure_reason || taskData.error };\r\n if (taskData.status === \"succeeded\") {\r\n return { completed: true, data: taskData.url };\r\n }\r\n logger(`视频任务生成中,进度:${taskData.progress}%`);\r\n return { completed: false };\r\n },\r\n 5000,\r\n 1800000,\r\n );\r\n\r\n if (pollResult.error) throw new Error(pollResult.error);\r\n logger(`视频生成完成,开始转换Base64`);\r\n return await urlToBase64(pollResult.data!);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"1.0\", notice: \"## 新版本更新公告\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};\r\n", + "klingai.ts": "/**\r\n * Toonflow AI供应商模板 - 可灵AI\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"klingai\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"可灵AI\",\r\n description:\r\n \"可灵AI视频生成\\n\\n支持可灵全系列视频模型,包括 kling-video-o1、kling-v3-omni、kling-v3、kling-v2-6、kling-v2-5-turbo、kling-v2-1、kling-v2-master、kling-v1-6、kling-v1-5、kling-v1 等。\\n\\n需要在[可灵AI开放平台](https://klingai.com)\\n\\n获取 Access Key 和 Secret Key。\",\r\n inputs: [\r\n { key: \"accessKey\", label: \"Access Key\", type: \"password\", required: true, placeholder: \"请输入可灵AI的Access Key\" },\r\n { key: \"secretKey\", label: \"Secret Key\", type: \"password\", required: true, placeholder: \"请输入可灵AI的Secret Key\" },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"默认:https://api-beijing.klingai.com\" },\r\n ],\r\n inputValues: { accessKey: \"\", secretKey: \"\", baseUrl: \"https://api-beijing.klingai.com\" },\r\n models: [\r\n // kling-video-o1 (Omni)\r\n {\r\n name: \"kling-video-o1 标准\",\r\n modelName: \"kling-video-o1:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-video-o1 专家\",\r\n modelName: \"kling-video-o1:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n // kling-v3-omni (Omni)\r\n {\r\n name: \"kling-v3-omni 标准\",\r\n modelName: \"kling-v3-omni:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v3-omni 专家\",\r\n modelName: \"kling-v3-omni:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\", [\"imageReference:7\", \"videoReference:1\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n // kling-v3\r\n {\r\n name: \"kling-v3 标准\",\r\n modelName: \"kling-v3:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v3 专家\",\r\n modelName: \"kling-v3:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n },\r\n // kling-v2-6\r\n {\r\n name: \"kling-v2-6 标准\",\r\n modelName: \"kling-v2-6:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v2-6 专家\",\r\n modelName: \"kling-v2-6:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-5-turbo\r\n {\r\n name: \"kling-v2-5-turbo 标准\",\r\n modelName: \"kling-v2-5-turbo:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n {\r\n name: \"kling-v2-5-turbo 专家\",\r\n modelName: \"kling-v2-5-turbo:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-1\r\n {\r\n name: \"kling-v2-1 标准\",\r\n modelName: \"kling-v2-1:std\",\r\n type: \"video\",\r\n mode: [\"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v2-1 专家\",\r\n modelName: \"kling-v2-1:pro\",\r\n type: \"video\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-1-master\r\n {\r\n name: \"kling-v2-1 Master\",\r\n modelName: \"kling-v2-1-master:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v2-master\r\n {\r\n name: \"kling-v2 Master\",\r\n modelName: \"kling-v2-master:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n // kling-v1-6\r\n {\r\n name: \"kling-v1-6 标准\",\r\n modelName: \"kling-v1-6:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", [\"imageReference:4\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v1-6 专家\",\r\n modelName: \"kling-v1-6:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"endFrameOptional\", [\"imageReference:4\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v1-5\r\n {\r\n name: \"kling-v1-5 标准\",\r\n modelName: \"kling-v1-5:std\",\r\n type: \"video\",\r\n mode: [\"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v1-5 专家\",\r\n modelName: \"kling-v1-5:pro\",\r\n type: \"video\",\r\n mode: [\"singleImage\", \"endFrameOptional\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"1080p\"] }],\r\n },\r\n // kling-v1\r\n {\r\n name: \"kling-v1 标准\",\r\n modelName: \"kling-v1:std\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n {\r\n name: \"kling-v1 专家\",\r\n modelName: \"kling-v1:pro\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [5, 10], resolution: [\"720p\"] }],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\n/**\r\n * 生成可灵AI的JWT鉴权Token\r\n */\r\nconst generateAuthToken = (): string => {\r\n const now = Math.floor(Date.now() / 1000);\r\n const payload = {\r\n iss: vendor.inputValues.accessKey,\r\n exp: now + 1800,\r\n nbf: now - 5,\r\n };\r\n return jsonwebtoken.sign(payload, vendor.inputValues.secretKey, {\r\n algorithm: \"HS256\",\r\n header: { alg: \"HS256\", typ: \"JWT\" },\r\n });\r\n};\r\n\r\n/**\r\n * 获取基础请求地址\r\n */\r\nconst getBaseUrl = (): string => {\r\n return vendor.inputValues.baseUrl || \"https://api-beijing.klingai.com\";\r\n};\r\n\r\n/**\r\n * 从 ReferenceList 条目中提取可用的数据字符串\r\n * 对于 url 类型返回 url,对于 base64 类型返回纯 base64(去掉 data: 前缀)\r\n */\r\nconst extractRawBase64 = (ref: ReferenceList): string => {\r\n return ref.base64.replace(/^data:[^;]+;base64,/, \"\");\r\n};\r\n\r\n/**\r\n * 从 ReferenceList 条目中提取带头的 base64 或 url\r\n * 用于 omni-video 接口,该接口的 image_url 支持带前缀的 base64 和 url\r\n */\r\nconst extractImageUrl = (ref: ReferenceList): string => {\r\n return ref.base64.startsWith(\"data:\") ? ref.base64 : `data:image/jpeg;base64,${ref.base64}`;\r\n};\r\n\r\n/**\r\n * 提交任务并轮询获取结果的通用函数\r\n */\r\nconst submitAndPoll = async (submitUrl: string, queryUrlBase: string, requestBody: any): Promise => {\r\n const token = generateAuthToken();\r\n\r\n logger(`开始提交可灵AI视频生成任务: ${submitUrl}`);\r\n logger(\r\n `请求参数: ${JSON.stringify({\r\n ...requestBody,\r\n image: requestBody.image ? \"[BASE64]\" : undefined,\r\n image_tail: requestBody.image_tail ? \"[BASE64]\" : undefined,\r\n image_list: requestBody.image_list ? \"[IMAGES]\" : undefined,\r\n })}`,\r\n );\r\n\r\n const submitResp = await axios.post(submitUrl, requestBody, {\r\n headers: {\r\n \"Content-Type\": \"application/json\",\r\n Authorization: `Bearer ${token}`,\r\n },\r\n });\r\n\r\n if (submitResp.data.code !== 0) {\r\n throw new Error(`提交任务失败: ${submitResp.data.message || JSON.stringify(submitResp.data)}`);\r\n }\r\n\r\n const taskId = submitResp.data.data.task_id;\r\n logger(`任务已提交,任务ID: ${taskId}`);\r\n\r\n const result = await pollTask(\r\n async () => {\r\n const freshToken = generateAuthToken();\r\n const queryResp = await axios.get(`${queryUrlBase}/${taskId}`, {\r\n headers: {\r\n Authorization: `Bearer ${freshToken}`,\r\n },\r\n });\r\n\r\n if (queryResp.data.code !== 0) {\r\n return { completed: true, error: `查询任务失败: ${queryResp.data.message}` };\r\n }\r\n\r\n const taskData = queryResp.data.data;\r\n const status = taskData.task_status;\r\n logger(`轮询中... 任务状态: ${status}`);\r\n\r\n if (status === \"succeed\") {\r\n const videoUrl = taskData.task_result?.videos?.[0]?.url;\r\n if (!videoUrl) {\r\n return { completed: true, error: \"任务完成但未获取到视频URL\" };\r\n }\r\n return { completed: true, data: videoUrl };\r\n }\r\n\r\n if (status === \"failed\") {\r\n return { completed: true, error: `视频生成失败: ${taskData.task_status_msg || \"未知错误\"}` };\r\n }\r\n\r\n return { completed: false };\r\n },\r\n 5000,\r\n 600000,\r\n );\r\n\r\n if (result.error) throw new Error(result.error);\r\n logger(`视频生成完成,正在转换为Base64...`);\r\n return await urlToBase64(result.data!);\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n throw new Error(\"可灵AI不支持文本模型\");\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n throw new Error(\"可灵AI不支持图片模型\");\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.accessKey) throw new Error(\"缺少Access Key\");\r\n if (!vendor.inputValues.secretKey) throw new Error(\"缺少Secret Key\");\r\n\r\n const baseUrl = getBaseUrl();\r\n\r\n // 解析 modelName,格式:kling-video-o1:pro => modelName=kling-video-o1, mode=pro\r\n const colonIdx = model.modelName.indexOf(\":\");\r\n const modelName = colonIdx > -1 ? model.modelName.substring(0, colonIdx) : model.modelName;\r\n const mode = colonIdx > -1 ? model.modelName.substring(colonIdx + 1) : \"pro\";\r\n\r\n // 判断是否为 Omni 模型\r\n const isOmniModel = modelName === \"kling-video-o1\" || modelName === \"kling-v3-omni\";\r\n\r\n // 判断当前选中的视频生成模式\r\n const currentMode = config.mode;\r\n const isText = currentMode.includes(\"text\");\r\n const isSingleImage = currentMode.includes(\"singleImage\");\r\n const isStartEndRequired = currentMode.includes(\"startEndRequired\");\r\n const isEndFrameOptional = currentMode.includes(\"endFrameOptional\");\r\n const isStartFrameOptional = currentMode.includes(\"startFrameOptional\");\r\n const hasMultiRef = currentMode.some((m) => Array.isArray(m));\r\n\r\n // 提取不同类型的引用\r\n const imageRefs = (config.referenceList || []).filter((r) => r.type === \"image\");\r\n const videoRefs = (config.referenceList || []).filter((r) => r.type === \"video\");\r\n\r\n // =====================================================\r\n // Omni 模型 —— 使用 /v1/videos/omni-video 接口\r\n // =====================================================\r\n if (isOmniModel) {\r\n const requestBody: any = {\r\n model_name: modelName,\r\n mode: mode,\r\n duration: String(config.duration),\r\n sound: config.audio === true ? \"on\" : \"off\",\r\n };\r\n\r\n if (config.prompt) {\r\n requestBody.prompt = config.prompt;\r\n }\r\n\r\n if (isSingleImage && imageRefs.length > 0) {\r\n const imageUrl = extractImageUrl(imageRefs[0]);\r\n requestBody.image_list = [{ image_url: imageUrl, type: \"first_frame\" }];\r\n if (!requestBody.prompt) requestBody.prompt = \"根据图片生成视频\";\r\n } else if (isStartEndRequired && imageRefs.length >= 2) {\r\n const firstUrl = extractImageUrl(imageRefs[0]);\r\n const endUrl = extractImageUrl(imageRefs[1]);\r\n requestBody.image_list = [\r\n { image_url: firstUrl, type: \"first_frame\" },\r\n { image_url: endUrl, type: \"end_frame\" },\r\n ];\r\n if (!requestBody.prompt) requestBody.prompt = \"根据首尾帧图片生成过渡视频\";\r\n } else if (isEndFrameOptional && imageRefs.length >= 1) {\r\n const firstUrl = extractImageUrl(imageRefs[0]);\r\n requestBody.image_list = [{ image_url: firstUrl, type: \"first_frame\" }];\r\n if (imageRefs.length >= 2) {\r\n const endUrl = extractImageUrl(imageRefs[1]);\r\n requestBody.image_list.push({ image_url: endUrl, type: \"end_frame\" });\r\n }\r\n if (!requestBody.prompt) requestBody.prompt = \"根据图片生成视频\";\r\n } else if (isStartFrameOptional && imageRefs.length >= 1) {\r\n if (imageRefs.length >= 2) {\r\n const firstUrl = extractImageUrl(imageRefs[0]);\r\n const endUrl = extractImageUrl(imageRefs[1]);\r\n requestBody.image_list = [\r\n { image_url: firstUrl, type: \"first_frame\" },\r\n { image_url: endUrl, type: \"end_frame\" },\r\n ];\r\n } else {\r\n const endUrl = extractImageUrl(imageRefs[0]);\r\n requestBody.image_list = [{ image_url: endUrl, type: \"end_frame\" }];\r\n }\r\n if (!requestBody.prompt) requestBody.prompt = \"根据图片生成视频\";\r\n } else if (hasMultiRef && (imageRefs.length > 0 || videoRefs.length > 0)) {\r\n requestBody.image_list = [];\r\n for (let i = 0; i < imageRefs.length; i++) {\r\n const imageUrl = extractImageUrl(imageRefs[i]);\r\n requestBody.image_list.push({ image_url: imageUrl });\r\n }\r\n if (!requestBody.prompt) {\r\n const refs = imageRefs.map((_, idx) => `<<>>`).join(\"、\");\r\n requestBody.prompt = `参考${refs}生成视频`;\r\n }\r\n }\r\n\r\n // 文生视频或无图片输入时需要设置宽高比\r\n const hasImageInput = requestBody.image_list && requestBody.image_list.length > 0;\r\n if (!hasImageInput) {\r\n requestBody.aspect_ratio = config.aspectRatio || \"16:9\";\r\n if (!requestBody.prompt) throw new Error(\"文生视频模式需要提供提示词\");\r\n }\r\n\r\n const apiPath = \"/v1/videos/omni-video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n // =====================================================\r\n // 非 Omni 模型 —— 根据模式选择不同接口\r\n // =====================================================\r\n\r\n // 多图参考模式 —— 使用 /v1/videos/multi-image2video 接口(仅 kling-v1-6 支持)\r\n if (hasMultiRef && imageRefs.length > 0) {\r\n const imageList = [];\r\n for (let i = 0; i < imageRefs.length; i++) {\r\n const rawBase64 = extractRawBase64(imageRefs[i]);\r\n imageList.push({ image: rawBase64 });\r\n }\r\n\r\n const requestBody: any = {\r\n model_name: modelName,\r\n image_list: imageList,\r\n prompt: config.prompt || \"根据参考图片生成视频\",\r\n mode: mode,\r\n duration: String(config.duration),\r\n aspect_ratio: config.aspectRatio || \"16:9\",\r\n };\r\n\r\n const apiPath = \"/v1/videos/multi-image2video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n // 文生视频模式 —— 使用 /v1/videos/text2video 接口\r\n if (isText) {\r\n if (!config.prompt) throw new Error(\"文生视频模式需要提供提示词\");\r\n\r\n const requestBody: any = {\r\n model_name: modelName,\r\n prompt: config.prompt,\r\n mode: mode,\r\n duration: String(config.duration),\r\n aspect_ratio: config.aspectRatio || \"16:9\",\r\n sound: config.audio === true ? \"on\" : \"off\",\r\n };\r\n\r\n const apiPath = \"/v1/videos/text2video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n // 图生视频模式(单图 / 首尾帧 / 尾帧可选等)—— 使用 /v1/videos/image2video 接口\r\n if ((isSingleImage || isStartEndRequired || isEndFrameOptional || isStartFrameOptional) && imageRefs.length > 0) {\r\n const requestBody: any = {\r\n model_name: modelName,\r\n prompt: config.prompt || \"根据图片生成视频\",\r\n mode: mode,\r\n duration: String(config.duration),\r\n sound: config.audio === true ? \"on\" : \"off\",\r\n };\r\n\r\n if (isSingleImage) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n } else if (isStartEndRequired && imageRefs.length >= 2) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n requestBody.image_tail = extractRawBase64(imageRefs[1]);\r\n } else if (isEndFrameOptional) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n if (imageRefs.length >= 2) {\r\n requestBody.image_tail = extractRawBase64(imageRefs[1]);\r\n }\r\n } else if (isStartFrameOptional) {\r\n if (imageRefs.length >= 2) {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n requestBody.image_tail = extractRawBase64(imageRefs[1]);\r\n } else {\r\n requestBody.image = extractRawBase64(imageRefs[0]);\r\n }\r\n }\r\n\r\n const apiPath = \"/v1/videos/image2video\";\r\n return await submitAndPoll(`${baseUrl}${apiPath}`, `${baseUrl}${apiPath}`, requestBody);\r\n }\r\n\r\n throw new Error(\"不支持的视频生成模式或缺少必要的输入参数\");\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};", + "minimax.ts": "/**\r\n * Toonflow AI供应商模板 - MiniMax(海螺AI)\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n uploadReference: (base64: string, fileType: \"image\" | \"audio\" | \"video\") => Promise;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"minimax\",\r\n version: \"2.1\",\r\n author: \"Toonflow\",\r\n name: \"MiniMax(海螺AI)\",\r\n description: \"MiniMax官方接口适配,支持M系列推理文本模型、文生图/图生图、视频生成(文生视频、图生视频、首尾帧生成)能力 \\n [前往平台](https://minimaxi.com/)\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"示例:https://api.minimaxi.com\" },\r\n ],\r\n inputValues: { apiKey: \"\", baseUrl: \"https://api.minimaxi.com\" },\r\n models: [\r\n // 文本模型\r\n { name: \"MiniMax-M2.7 (推理版)\", modelName: \"MiniMax-M2.7\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.7 极速版 (推理版)\", modelName: \"MiniMax-M2.7-highspeed\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.5 (推理版)\", modelName: \"MiniMax-M2.5\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.5 极速版 (推理版)\", modelName: \"MiniMax-M2.5-highspeed\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.1 (编程版)\", modelName: \"MiniMax-M2.1\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2.1 极速版 (编程版)\", modelName: \"MiniMax-M2.1-highspeed\", type: \"text\", think: true },\r\n { name: \"MiniMax-M2 (Agent版)\", modelName: \"MiniMax-M2\", type: \"text\", think: false },\r\n // 图片模型\r\n { name: \"海螺图像V1\", modelName: \"image-01\", type: \"image\", mode: [\"text\", \"singleImage\"] },\r\n { name: \"海螺图像V1 Live版\", modelName: \"image-01-live\", type: \"image\", mode: [\"text\", \"singleImage\"], associationSkills: \"支持自定义画风\" },\r\n // 视频模型\r\n {\r\n name: \"海螺2.3\",\r\n modelName: \"MiniMax-Hailuo-2.3\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [\r\n { duration: [6], resolution: [\"768P\", \"1080P\"] },\r\n { duration: [10], resolution: [\"768P\"] },\r\n ],\r\n },\r\n {\r\n name: \"海螺2.3极速版\",\r\n modelName: \"MiniMax-Hailuo-2.3-Fast\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [\r\n { duration: [6], resolution: [\"768P\", \"1080P\"] },\r\n { duration: [10], resolution: [\"768P\"] },\r\n ],\r\n },\r\n {\r\n name: \"海螺02\",\r\n modelName: \"MiniMax-Hailuo-02\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\", \"startEndRequired\"],\r\n audio: false,\r\n durationResolutionMap: [\r\n { duration: [6], resolution: [\"512P\", \"768P\", \"1080P\"] },\r\n { duration: [10], resolution: [\"512P\", \"768P\"] },\r\n ],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\n/**\r\n * 获取请求头\r\n */\r\nconst getHeaders = (): Record => {\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return {\r\n Authorization: `Bearer ${apiKey}`,\r\n \"Content-Type\": \"application/json\",\r\n };\r\n};\r\n\r\n/**\r\n * 获取基础请求地址\r\n */\r\nconst getBaseUrl = (): string => {\r\n return vendor.inputValues.baseUrl.replace(/\\/$/, \"\");\r\n};\r\n\r\n/**\r\n * 从 ReferenceList 条目中提取有头 base64 字符串\r\n */\r\nconst extractBase64WithHead = (ref: ReferenceList): string => {\r\n return ref.base64.startsWith(\"data:\") ? ref.base64 : `data:image/png;base64,${ref.base64}`;\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n const baseUrl = getBaseUrl();\r\n\r\n const openaiBaseUrl = `${baseUrl}/v1`;\r\n const extraBody = model.think ? { reasoning_split: true } : {};\r\n return createOpenAI({ baseURL: openaiBaseUrl, apiKey, extraBody }).chat(model.modelName);\r\n};\r\n\r\nconst uploadReference = async (base64: string, fileType: \"image\" | \"audio\" | \"video\"): Promise => {\r\n // MiniMax的图片接口直接接受 base64,压缩后原样返回\r\n if (fileType === \"image\") {\r\n const compressed = await zipImage(base64, 10 * 1024);\r\n return { type: \"image\", sourceType: \"base64\", base64: compressed };\r\n }\r\n // 视频接口的图片参数也是 base64,压缩到20MB\r\n return { type: fileType, sourceType: \"base64\", base64 } as ReferenceList;\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const reqBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n aspect_ratio: config.aspectRatio,\r\n response_format: \"base64\",\r\n n: 1,\r\n prompt_optimizer: true,\r\n aigc_watermark: false,\r\n };\r\n\r\n // 处理图生图参考\r\n const imageRefs = config.referenceList || [];\r\n if (imageRefs.length > 0) {\r\n const refBase64 = extractBase64WithHead(imageRefs[0]);\r\n reqBody.subject_reference = [{ type: \"character\", image_file: refBase64 }];\r\n }\r\n\r\n logger(\"开始提交MiniMax图像生成任务\");\r\n const resp = await axios.post(`${baseUrl}/v1/image_generation`, reqBody, { headers });\r\n if (resp.data.base_resp.status_code !== 0) {\r\n throw new Error(`图像生成失败:${resp.data.base_resp.status_msg}`);\r\n }\r\n if (resp.data.metadata.success_count === 0) {\r\n throw new Error(\"图像生成被安全策略拦截,请调整prompt或参考图\");\r\n }\r\n\r\n const imgBase64 = resp.data.data.image_base64[0];\r\n return imgBase64.startsWith(\"data:\") ? imgBase64 : `data:image/png;base64,${imgBase64}`;\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const reqBody: any = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n duration: config.duration,\r\n resolution: config.resolution,\r\n aigc_watermark: false,\r\n prompt_optimizer: true,\r\n };\r\n\r\n // 提取图片类型的引用\r\n const imageRefs = (config.referenceList || []).filter((r) => r.type === \"image\");\r\n\r\n if (imageRefs.length > 0) {\r\n // 压缩图片到20MB以内\r\n const compressedImages: string[] = [];\r\n for (const ref of imageRefs) {\r\n const base64 = extractBase64WithHead(ref);\r\n const compressed = await zipImage(base64, 20 * 1024);\r\n compressedImages.push(compressed);\r\n }\r\n\r\n if (config.mode.includes(\"startEndRequired\")) {\r\n if (compressedImages.length < 2) throw new Error(\"首尾帧模式需要上传两张图片\");\r\n reqBody.first_frame_image = compressedImages[0];\r\n reqBody.last_frame_image = compressedImages[1];\r\n } else if (config.mode.includes(\"singleImage\")) {\r\n reqBody.first_frame_image = compressedImages[0];\r\n }\r\n }\r\n\r\n logger(\"开始提交MiniMax视频生成任务\");\r\n const submitResp = await axios.post(`${baseUrl}/v1/video_generation`, reqBody, { headers });\r\n if (submitResp.data.base_resp.status_code !== 0) {\r\n throw new Error(`任务提交失败:${submitResp.data.base_resp.status_msg}`);\r\n }\r\n const taskId = submitResp.data.task_id;\r\n logger(`视频任务提交成功,任务ID: ${taskId}`);\r\n\r\n // 轮询任务状态\r\n const pollResult = await pollTask(\r\n async () => {\r\n const queryResp = await axios.get(`${baseUrl}/v1/query/video_generation`, {\r\n headers: getHeaders(),\r\n params: { task_id: taskId },\r\n });\r\n if (queryResp.data.base_resp.status_code !== 0) {\r\n return { completed: true, error: queryResp.data.base_resp.status_msg };\r\n }\r\n const status = queryResp.data.status;\r\n if (status === \"Success\") {\r\n return { completed: true, data: queryResp.data.file_id };\r\n }\r\n if (status === \"Fail\") {\r\n return { completed: true, error: \"视频生成失败\" };\r\n }\r\n logger(`视频任务生成中,当前状态:${status}`);\r\n return { completed: false };\r\n },\r\n 5000,\r\n 600000,\r\n );\r\n\r\n if (pollResult.error) throw new Error(pollResult.error);\r\n const fileId = pollResult.data!;\r\n logger(`视频任务生成成功,文件ID: ${fileId}`);\r\n\r\n // 获取下载地址\r\n const fileResp = await axios.get(`${baseUrl}/v1/files/retrieve`, {\r\n headers: getHeaders(),\r\n params: { file_id: fileId },\r\n });\r\n if (fileResp.data.base_resp.status_code !== 0) {\r\n throw new Error(`获取文件地址失败:${fileResp.data.base_resp.status_msg}`);\r\n }\r\n const downloadUrl = fileResp.data.file.download_url;\r\n logger(`视频下载地址获取成功,开始转Base64`);\r\n\r\n return await urlToBase64(downloadUrl);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return {\r\n hasUpdate: false,\r\n latestVersion: \"2.0\",\r\n notice:\r\n \"## 新版本更新公告\\n1. 适配新版模板架构,支持 ReferenceList 统一引用类型\\n2. 新增 uploadReference 前置处理器\\n3. 优化图片压缩和引用提取逻辑\",\r\n };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.uploadReference = uploadReference;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};", + "null.ts": "/**\r\n * Toonflow AI供应商模板\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\" //单图参考\r\n | \"startEndRequired\" //首尾帧(两张都得有)\r\n | \"endFrameOptional\" //首尾帧(尾帧可选)\r\n | \"startFrameOptional\" //首尾帧(首帧可选)\r\n | \"text\" //文本\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[]; //多参考(数字代表限制数量)\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string; //唯一ID,作为文件名存储用户磁盘上,禁止符号\r\n version: string; //版本号,格式为x.y,需遵守语义化版本控制\r\n name: string; //供应商名称\r\n author: string; //作者\r\n description?: string; //描述,支持Markdown格式\r\n icon?: string; //图标,仅支持Base64格式,建议尺寸为128x128像素\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any; // HTTP请求库\r\ndeclare const logger: (msg: string) => void; // 日志函数\r\ndeclare const jsonwebtoken: any; // JWT处理库\r\ndeclare const zipImage: (base64: string, size: number) => Promise; // 图片压缩函数,返回有头base64字符串\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise; // 图片分辨率调整函数,返回有头base64字符串\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise; // 图片合成函数,返回有头base64字符串\r\ndeclare const urlToBase64: (url: string) => Promise; // URL转Base64函数,返回有头base64字符串\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise; // 轮询函数,fn为异步函数,interval为轮询间隔,timeout为超时时间,返回fn的结果\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any; //文本模型\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise; //图片模型,返回有头base64字符串\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise; //视频模型,返回有头base64字符串\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise; //(暂未开放)语音模型,返回有头base64字符串\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>; //检查更新函数,返回是否有更新和最新版本号和更公告(支持Markdown格式)\r\n updateVendor?: () => Promise; //更新函数,返回最新的代码文本\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"null\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"空模板\",\r\n description: \"## 开发模板,您可以使用此模板进行Vibe Coding\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"示例:https://api.openai.com/v1\" },\r\n ],\r\n inputValues: { apiKey: \"\", baseUrl: \"https://api.openai.com/v1\" },\r\n models: [{ name: \"GPT-4o\", modelName: \"gpt-4o\", type: \"text\", think: false }],\r\n};\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createOpenAI({ baseURL: vendor.inputValues.baseUrl, apiKey }).chat(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"## 新版本更新公告\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\n// 这行代码用于确保当前文件被识别为模块,避免全局变量冲突\r\nexport {};\r\n\r\n/**\r\n * ============================================================\r\n * AI 代码生成指南\r\n * ============================================================\r\n *\r\n * 【概述】\r\n * 本文件是 Toonflow AI 供应商适配模板。AI 在生成新供应商适配代码时,\r\n * 必须严格遵守以下规则,并要求用户提供目标平台的 curl 调用示例或 API 文档信息作为输入依据。\r\n *\r\n * 【前置要求】\r\n * 在生成代码前,请向用户索要以下信息(至少其一):\r\n * 1. 目标 API 的 curl 请求示例(包含请求地址、Headers、Body 结构、响应结构)\r\n * 2. 目标 API 的官方文档链接或文档截图/文本内容\r\n * 3. 需要适配的模型类型(text / image / video / tts)及其能力说明\r\n * 没有足够信息时,应主动追问,不要凭空编造 API 结构。\r\n *\r\n * 【代码规则】\r\n *\r\n * 1. 禁止引入任何外部包\r\n * 不可使用 import / require,仅能使用本文件「全局声明」区域中已声明的方法和对象,\r\n * 包括:axios、logger、jsonwebtoken、zipImage、zipImageResolution、mergeImages、\r\n * urlToBase64、pollTask,以及 createOpenAI、createDeepSeek、createZhipu、createQwen、\r\n * createAnthropic、createOpenAICompatible、createXai、createMinimax、\r\n * createGoogleGenerativeAI 等 AI SDK 工厂函数。\r\n *\r\n * 2. 禁止在 exports.* 函数外部声明离散的全大写常量\r\n * 错误示例:const API_URL = \"https://...\"; const MAX_RETRY = 3;\r\n * 如果确实需要可配置的常量值,必须将其声明在 vendor.inputValues 中,\r\n * 通过 vendor.inputValues.xxx 访问,让用户可在界面上配置。\r\n * 如果是纯逻辑内部使用的临时变量,应内联在对应的 exports.* 函数体内部,使用小驼峰命名。\r\n *\r\n * 3. 逻辑尽量聚合在 exports.* 对应的函数内部\r\n * 每个适配函数(textRequest / imageRequest / videoRequest / ttsRequest)\r\n * 应自包含,将请求构造、发送、轮询、结果解析等逻辑写在函数体内,避免拆分出大量外部辅助函数。\r\n * 如果多个函数确实存在公共逻辑(如签名计算、Token 生成、请求头构造),\r\n * 可提取为文件内的小驼峰命名函数,放在「适配器函数」区块之前的「辅助工具」区块中,\r\n * 且不可使用全大写命名。\r\n *\r\n * 4. 命名规范\r\n * 所有变量、函数一律使用小驼峰命名(camelCase),禁止使用 UPPER_SNAKE_CASE。\r\n *\r\n * 5. 不需要重新声明类型\r\n * 本文件顶部已完整定义了所有接口和类型(VendorConfig、ImageConfig、VideoConfig、\r\n * TTSConfig、TextModel、ImageModel、VideoModel、TTSModel、ReferenceList、PollResult 等),\r\n * AI 生成代码时直接使用即可,不要重复声明。\r\n *\r\n * 6. 返回值规范\r\n * - textRequest(model):返回 AI SDK 的 chat model 实例(通过 createOpenAI 等工厂函数创建)。\r\n * - imageRequest(config, model):返回有头 base64 字符串(如 \"data:image/png;base64,...\")。\r\n * config.referenceList 为 Extract[] 类型,\r\n * 每个引用条目均为 base64 形式(sourceType 固定为 \"base64\")。\r\n * - videoRequest(config, model):返回有头 base64 字符串(如 \"data:video/mp4;base64,...\")。\r\n * config.referenceList 为 ReferenceList[] 类型,可包含 image / video / audio 三种引用,\r\n * 每个引用条目均为 base64 形式(sourceType 固定为 \"base64\")。\r\n * config.mode 为当前激活的视频模式数组,需根据 mode 决定如何使用 referenceList。\r\n * - ttsRequest(config, model):返回有头 base64 字符串(如 \"data:audio/mp3;base64,...\")。\r\n * config.referenceList 为 Extract[] 类型(音频参考)。\r\n * 当 API 返回的是 URL 而非二进制数据时,使用 urlToBase64(url) 转换。\r\n *\r\n * 7. ReferenceList 与 VideoMode 说明\r\n * ReferenceList 是统一的多媒体引用类型,每个条目包含:\r\n * - type: \"image\" | \"audio\" | \"video\"(媒体类型)\r\n * - sourceType: \"base64\"(当前模板固定为 base64)\r\n * - base64(对应的数据)\r\n *\r\n * VideoMode 定义了视频模型支持的输入模式:\r\n * - \"text\":纯文本生成视频\r\n * - \"singleImage\":单张首帧图片\r\n * - \"startEndRequired\":首尾帧(两张都必须提供)\r\n * - \"endFrameOptional\":首尾帧(尾帧可选)\r\n * - \"startFrameOptional\":首尾帧(首帧可选)\r\n * - 数组形式如 [\"imageReference:9\", \"videoReference:3\", \"audioReference:3\"]:\r\n * 多模态参考模式,数字表示该类型的最大数量限制。\r\n *\r\n * 在 videoRequest 中,config.mode 表示当前选择的模式,需根据其值决定:\r\n * - 如何从 config.referenceList 中提取对应类型的引用\r\n * - 如何构造 API 请求体中的图片/视频/音频参数\r\n *\r\n * 8. 异步任务处理\r\n * 对于视频生成等需要轮询的异步任务,使用全局的 pollTask 函数:\r\n * const result = await pollTask(async () => {\r\n * const resp = await axios.get(...);\r\n * if (resp.data.status === \"SUCCESS\") return { completed: true, data: resp.data.url };\r\n * if (resp.data.status === \"FAILED\") return { completed: true, error: resp.data.message };\r\n * return { completed: false };\r\n * }, 5000, 600000); // 每5秒轮询,10分钟超时\r\n * if (result.error) throw new Error(result.error);\r\n * return await urlToBase64(result.data!);\r\n *\r\n * 9. 错误处理\r\n * 在每个函数开头校验必需参数(如 API Key),缺失时使用 throw new Error(\"...\") 抛出。\r\n * API 请求失败时,从响应中提取有意义的错误信息抛出,不要吞掉异常。\r\n *\r\n * 10. 日志输出\r\n * 在关键步骤使用 logger(\"...\") 输出日志(如\"开始提交任务\"、\"任务ID: xxx\"、\"轮询中...\"),\r\n * 便于调试。\r\n *\r\n * 11. vendor 配置填写\r\n * - id:纯英文小写,作为文件名使用,禁止特殊符号和空格。\r\n * - version:语义化版本格式 \"x.y\"。\r\n * - inputs:根据目标 API 所需的认证信息配置(API Key、Secret、请求地址等)。\r\n * - models:根据目标平台支持的模型列表填写,注意正确设置 type 和各模型特有字段。\r\n * - VideoModel 的 mode 对应 API 支持的输入模式(参见规则 7 的 VideoMode 说明)。\r\n * - VideoModel 的 audio 字段:true(始终生成音频)、false(不生成)、\"optional\"(用户可选)。\r\n * - VideoModel 的 durationResolutionMap 对应各时长下可选的分辨率。\r\n * - VideoModel 的 associationSkills 可选,用于描述模型的特殊能力。\r\n * - ImageModel 的 mode 对应 API 支持的生图模式(\"text\" 纯文本、\"singleImage\" 单图参考、\"multiReference\" 多图参考)。\r\n * - TTSModel 的 voices 对应可选的音色列表。\r\n *\r\n * 12. 图片处理\r\n * - 需要压缩图片体积时使用 zipImage(base64, maxSizeKB)。\r\n * - 需要调整图片分辨率时使用 zipImageResolution(base64, width, height)。\r\n * - 需要将多张图片拼合为一张时使用 mergeImages(base64Arr, maxSize)。\r\n * - 以上函数均接收和返回有头 base64 字符串。\r\n *\r\n * 13. 文件结构\r\n * 生成的代码必须保持本模板的整体结构:\r\n * 类型定义区 → 全局声明区 → 供应商配置区 → [辅助工具区(可选)] → 适配器函数区 → 导出区\r\n * 不要打乱顺序,不要删除已有的结构注释分隔线。\r\n * 辅助工具区用于放置多个适配器函数共享的小驼峰命名辅助函数(如 getHeaders、getBaseUrl)。\r\n *\r\n * 14. 导出规范\r\n * 必须导出以下字段(通过 exports.xxx = xxx 赋值):\r\n * - exports.vendor(必须)\r\n * - exports.textRequest(必须)\r\n * - exports.imageRequest(必须)\r\n * - exports.videoRequest(必须)\r\n * - exports.ttsRequest(必须)\r\n * - exports.checkForUpdates(可选)\r\n * - exports.updateVendor(可选)\r\n * 未实现的适配器函数保留空实现(return \"\"),不可省略导出。\r\n * 文件末尾必须包含 export {}; 以确保文件被识别为模块。\r\n *\r\n * 【生成流程】\r\n * 当用户请求生成新的供应商适配时:\r\n * 1. 确认用户已提供 curl 示例或 API 文档。\r\n * 2. 分析 API 的认证方式、端点地址、请求/响应结构。\r\n * 3. 基于本模板结构,填充 vendor 配置和对应的适配器函数。\r\n * 4. 根据当前模板的 ReferenceList 定义,按 base64 形式构造和消费 referenceList。\r\n * 5. 仅实现用户需要的模型类型,未用到的函数保留空实现(return \"\")。\r\n * 6. 生成完整可用的代码,确保无语法错误、无遗漏导出。\r\n */\r\n", + "openai.ts": "/**\r\n * Toonflow AI供应商模板\r\n * @version 2.0\r\n */\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\ninterface ImageConfig {\r\n prompt: string;\r\n imageBase64: string[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n imageBase64?: string[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n}\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\nconst vendor: VendorConfig = {\r\n id: \"openai\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"OpenAI标准接口\",\r\n description: \"OpenAI标准格式接口,可修改请求地址并手动添加模型。\",\r\n icon: \"\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"以v1结束,示例:https://api.openai.com/v1\" },\r\n ],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://api.openai.com/v1\",\r\n },\r\n models: [\r\n { name: \"GPT-4o\", modelName: \"gpt-4o\", type: \"text\", think: false },\r\n { name: \"GPT-4.1\", modelName: \"gpt-4.1\", type: \"text\", think: false },\r\n { name: \"GPT-5.1\", modelName: \"gpt-5.1\", type: \"text\", think: false },\r\n { name: \"GPT-5.2\", modelName: \"gpt-5.2\", type: \"text\", think: false },\r\n { name: \"GPT-5.4\", modelName: \"gpt-5.4\", type: \"text\", think: false },\r\n ],\r\n};\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createOpenAI({ baseURL: vendor.inputValues.baseUrl, apiKey }).chat(model.modelName);\r\n};\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n return \"\";\r\n};\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n return \"\";\r\n};\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"\" };\r\n};\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\nexport {};", + "toonflow.ts": "/**\r\n * Toonflow官方中转平台 供应商适配\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"toonflow\",\r\n version: \"2.0\",\r\n author: \"Toonflow\",\r\n name: \"Toonflow官方中转平台\",\r\n description:\r\n \"## Toonflow官方中转平台\\n\\nToonflow官方中转平台,提供**文本、图像、视频、音频**等多模态生成能力的中转服务,支持接入多个大模型供应商,方便用户统一管理和调用不同供应商的生成能力。\\n\\n🔗 [前往中转平台](https://api.toonflow.net/)\\n\\n如果这个项目对你有帮助,可以考虑支持一下我们的开发工作 ☕\",\r\n icon: \"\",\r\n inputs: [{ key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true }],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://api.toonflow.net/v1\",\r\n },\r\n models: [\r\n { name: \"claude-sonnet-4-6\", type: \"text\", modelName: \"claude-sonnet-4-6\", think: false },\r\n { name: \"claude-opus-4-6\", type: \"text\", modelName: \"claude-opus-4-6\", think: false },\r\n { name: \"claude-sonnet-4-5-20250929\", type: \"text\", modelName: \"claude-sonnet-4-5-20250929\", think: false },\r\n { name: \"claude-opus-4-5-20251101\", type: \"text\", modelName: \"claude-opus-4-5-20251101\", think: false },\r\n { name: \"claude-haiku-4-5-20251001\", type: \"text\", modelName: \"claude-haiku-4-5-20251001\", think: false },\r\n { name: \"gpt-5.4\", type: \"text\", modelName: \"gpt-5.4\", think: false },\r\n { name: \"gpt-5.2\", type: \"text\", modelName: \"gpt-5.2\", think: false },\r\n { name: \"MiniMax-M2.7\", type: \"text\", modelName: \"MiniMax-M2.7\", think: true },\r\n { name: \"MiniMax-M2.5\", type: \"text\", modelName: \"MiniMax-M2.5\", think: true },\r\n {\r\n name: \"Wan2.6 I2V 1080P (支持真人)\",\r\n type: \"video\",\r\n modelName: \"Wan2.6-I2V-1080P\",\r\n mode: [\"text\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"1080p\"] }],\r\n audio: true,\r\n },\r\n {\r\n name: \"Wan2.6 I2V 720P (支持真人)\",\r\n type: \"video\",\r\n modelName: \"Wan2.6-I2V-720P\",\r\n mode: [\"text\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"720p\"] }],\r\n audio: true,\r\n },\r\n {\r\n name: \"Seedance 1.5 Pro\",\r\n type: \"video\",\r\n modelName: \"doubao-seedance-1-5-pro-251215\",\r\n mode: [\"text\", \"endFrameOptional\"],\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n audio: true,\r\n },\r\n {\r\n name: \"vidu2 turbo\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-turbo\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n audio: false,\r\n },\r\n {\r\n name: \"ViduQ3 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ3-pro\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n audio: false,\r\n },\r\n {\r\n name: \"ViduQ2 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-pro\",\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n audio: false,\r\n },\r\n {\r\n name: \"Doubao Seedream 5.0 Lite\",\r\n type: \"image\",\r\n modelName: \"Doubao-Seedream-5.0-Lite\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Doubao Seedream 4.5\",\r\n type: \"image\",\r\n modelName: \"doubao-seedream-4-5-251128\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\n// 从 markdown 内容中提取第一张图片\r\nfunction extractFirstImageFromMd(content: string) {\r\n const regex = /!\\[([^\\]]*)\\]\\((data:image\\/[^;]+;base64,[A-Za-z0-9+/=]+|https?:\\/\\/[^\\s)]+|\\/\\/[^\\s)]+|[^\\s)]+)\\)/;\r\n const match = content.match(regex);\r\n if (!match) return null;\r\n const raw = match[2].trim();\r\n const url = raw.startsWith(\"data:\") ? raw : raw.split(/\\s+/)[0];\r\n return { alt: match[1], url, type: url.startsWith(\"data:image\") ? \"base64\" : \"url\" };\r\n}\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n return createOpenAI({ baseURL: vendor.inputValues.baseUrl, apiKey }).chat(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const lowerName = model.modelName.toLowerCase();\r\n const imageBase64List = (config.referenceList ?? []).map((r) => r.base64);\r\n\r\n // Gemini / nano 系模型:走 chat/completions 接口,从返回的 markdown 中提取图片\r\n if (lowerName.includes(\"gemini\") || lowerName.includes(\"nano\")) {\r\n const imageConfigGoogle: Record = {\r\n aspect_ratio: config.aspectRatio,\r\n image_size: config.size,\r\n };\r\n const messages: any[] = [];\r\n if (imageBase64List.length) {\r\n messages.push({\r\n role: \"user\",\r\n content: imageBase64List.map((b) => ({ type: \"image_url\", image_url: { url: b } })),\r\n });\r\n }\r\n messages.push({ role: \"user\", content: config.prompt + \"请直接输出图片\" });\r\n const body = {\r\n model: model.modelName,\r\n messages,\r\n extra_body: { google: { image_config: imageConfigGoogle } },\r\n };\r\n logger(`[imageRequest] 使用 gemini 适配器,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/chat/completions`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const imageResult = extractFirstImageFromMd(data.choices[0].message.content);\r\n if (!imageResult) throw new Error(\"未能从响应中提取图片\");\r\n if (imageResult.type === \"base64\") return imageResult.url;\r\n return await urlToBase64(imageResult.url);\r\n }\r\n\r\n // 豆包 / seedream 系模型:走 images/generations 接口\r\n if (lowerName.includes(\"doubao\") || lowerName.includes(\"seedream\")) {\r\n const effectiveSize = config.size === \"1K\" ? \"2K\" : config.size;\r\n const sizeMap: Record> = {\r\n \"16:9\": { \"2K\": \"2848x1600\", \"4K\": \"4096x2304\" },\r\n \"9:16\": { \"2K\": \"1600x2848\", \"4K\": \"2304x4096\" },\r\n };\r\n const resolvedSize = sizeMap[config.aspectRatio]?.[effectiveSize];\r\n const body: Record = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n size: resolvedSize,\r\n response_format: \"url\",\r\n sequential_image_generation: \"disabled\",\r\n stream: false,\r\n watermark: false,\r\n ...(imageBase64List.length && { image: imageBase64List }),\r\n };\r\n logger(`[imageRequest] 使用 doubao 适配器,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/images/generations`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const resultUrl = data.data[0].url;\r\n return await urlToBase64(resultUrl);\r\n }\r\n\r\n throw new Error(`不支持的图像模型: ${model.modelName}`);\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n const baseUrl = vendor.inputValues.baseUrl;\r\n const lowerName = model.modelName.toLowerCase();\r\n\r\n // 当前激活的单一 VideoMode(取第一个非数组模式,或数组模式)\r\n const activeMode = config.mode[0];\r\n const imageRefs = (config.referenceList ?? []).filter((r) => r.type === \"image\").map((r) => r.base64);\r\n const videoRefs = (config.referenceList ?? []).filter((r) => r.type === \"video\").map((r) => r.base64);\r\n const audioRefs = (config.referenceList ?? []).filter((r) => r.type === \"audio\").map((r) => r.base64);\r\n\r\n // 构建模型专属 metadata\r\n let metadata: Record = {};\r\n\r\n if (lowerName.includes(\"wan\")) {\r\n // 万象系列\r\n if (\r\n (activeMode === \"startEndRequired\" || activeMode === \"endFrameOptional\" || activeMode === \"startFrameOptional\") &&\r\n imageRefs.length >= 2\r\n ) {\r\n if (imageRefs[0]) metadata.first_frame_url = imageRefs[0];\r\n if (imageRefs[1]) metadata.last_frame_url = imageRefs[1];\r\n } else if (imageRefs.length) {\r\n metadata.img_url = imageRefs[0];\r\n }\r\n if (typeof config.audio === \"boolean\") metadata.audio = config.audio;\r\n\r\n // 万象需要额外传 size 字段\r\n const wanSizeMap: Record> = {\r\n \"480p\": { \"16:9\": \"832*480\", \"9:16\": \"480*832\" },\r\n \"720p\": { \"16:9\": \"1280*720\", \"9:16\": \"720*1280\" },\r\n \"1080p\": { \"16:9\": \"1920*1080\", \"9:16\": \"1080*1920\" },\r\n };\r\n const wanSize = wanSizeMap[config.resolution]?.[config.aspectRatio];\r\n const body: Record = {\r\n model: model.modelName,\r\n prompt: config.prompt,\r\n duration: config.duration,\r\n size: wanSize,\r\n metadata,\r\n };\r\n logger(`[videoRequest] 提交万象视频任务,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/video/generations`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const taskId = data.id;\r\n logger(`[videoRequest] 万象任务ID: ${taskId}`);\r\n const res = await pollTask(async () => {\r\n const queryResponse = await fetch(`${baseUrl}/video/generations/${taskId}`, {\r\n method: \"GET\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n });\r\n if (!queryResponse.ok) {\r\n const errorText = await queryResponse.text();\r\n throw new Error(`轮询失败,状态码: ${queryResponse.status}, 错误信息: ${errorText}`);\r\n }\r\n const queryData = await queryResponse.json();\r\n const status = queryData?.status ?? queryData?.data?.status;\r\n switch (status) {\r\n case \"completed\":\r\n case \"SUCCESS\":\r\n case \"success\":\r\n return { completed: true, data: queryData.data.result_url };\r\n case \"FAILURE\":\r\n case \"failed\":\r\n return { completed: true, error: queryData?.data?.fail_reason ?? \"视频生成失败\" };\r\n default:\r\n return { completed: false };\r\n }\r\n });\r\n if (res.error) throw new Error(res.error);\r\n return await urlToBase64(res.data!);\r\n }\r\n\r\n if (lowerName.includes(\"doubao\") || lowerName.includes(\"seedance\")) {\r\n // 豆包/Seedance 系列\r\n metadata = {\r\n ...(typeof config.audio === \"boolean\" && { generate_audio: config.audio }),\r\n ratio: config.aspectRatio,\r\n image_roles: [] as string[],\r\n references: [] as string[],\r\n };\r\n if (Array.isArray(activeMode)) {\r\n // 多参考模式\r\n imageRefs.forEach((b) => metadata.references.push(b));\r\n videoRefs.forEach((b) => metadata.references.push(b));\r\n audioRefs.forEach((b) => metadata.references.push(b));\r\n } else if (activeMode === \"startEndRequired\" || activeMode === \"endFrameOptional\" || activeMode === \"startFrameOptional\") {\r\n imageRefs.forEach((_, i) => (metadata.image_roles as string[]).push(i === 0 ? \"first_frame\" : \"last_frame\"));\r\n } else if (activeMode === \"singleImage\") {\r\n imageRefs.forEach(() => (metadata.image_roles as string[]).push(\"reference_image\"));\r\n }\r\n } else if (lowerName.includes(\"vidu\")) {\r\n // Vidu 系列\r\n metadata = {\r\n aspect_ratio: config.aspectRatio,\r\n audio: config.audio ?? false,\r\n off_peak: false,\r\n };\r\n } else if (lowerName.includes(\"kling\")) {\r\n // 可灵系列\r\n metadata = { aspect_ratio: config.aspectRatio };\r\n if (Array.isArray(activeMode)) {\r\n metadata.reference = [...imageRefs, ...videoRefs, ...audioRefs];\r\n } else if (activeMode === \"endFrameOptional\" && imageRefs.length) {\r\n metadata.image_tail = imageRefs[0];\r\n } else if (activeMode === \"startEndRequired\" && imageRefs.length >= 2) {\r\n metadata.image_list = [\r\n { image_url: imageRefs[0], type: \"first_frame\" },\r\n { image_url: imageRefs[1], type: \"last_frame\" },\r\n ];\r\n } else if (activeMode === \"singleImage\" && imageRefs.length) {\r\n metadata.image = imageRefs[0];\r\n }\r\n }\r\n\r\n // 公共请求体(非万象通用路径)\r\n const publicBody: Record = {\r\n model: model.modelName,\r\n ...(!Array.isArray(activeMode) && imageRefs.length ? { images: imageRefs } : {}),\r\n prompt: config.prompt,\r\n duration: config.duration,\r\n metadata,\r\n };\r\n\r\n logger(`[videoRequest] 提交视频任务,模型: ${model.modelName}`);\r\n const response = await fetch(`${baseUrl}/video/generations`, {\r\n method: \"POST\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(publicBody),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text();\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const taskId = data.id;\r\n logger(`[videoRequest] 任务ID: ${taskId}`);\r\n\r\n const res = await pollTask(async () => {\r\n const queryResponse = await fetch(`${baseUrl}/video/generations/${taskId}`, {\r\n method: \"GET\",\r\n headers: { Authorization: `Bearer ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n });\r\n if (!queryResponse.ok) {\r\n const errorText = await queryResponse.text();\r\n throw new Error(`轮询失败,状态码: ${queryResponse.status}, 错误信息: ${errorText}`);\r\n }\r\n const queryData = await queryResponse.json();\r\n const status = queryData?.status ?? queryData?.data?.status;\r\n switch (status) {\r\n case \"completed\":\r\n case \"SUCCESS\":\r\n case \"success\":\r\n return { completed: true, data: queryData.data.result_url };\r\n case \"FAILURE\":\r\n case \"failed\":\r\n return { completed: true, error: queryData?.data?.fail_reason ?? \"视频生成失败\" };\r\n default:\r\n return { completed: false };\r\n }\r\n });\r\n\r\n if (res.error) throw new Error(res.error);\r\n return await urlToBase64(res.data!);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\nexport {};", + "vidu.ts": "//如需遥测AI请使用在toonflow安装目录运行npx @ai-sdk/devtools (要求在其他设置中打开遥测功能,且toonflow有权限在安装目录创建.devtools文件夹)\r\n// ==================== 类型定义 ====================\r\n// 文本模型\r\ninterface TextModel {\r\n name: string; // 显示名称\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean; // 前端显示用\r\n}\r\n\r\n// 图像模型\r\ninterface ImageModel {\r\n name: string; // 显示名称\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string; // 关联技能,多个技能用逗号分隔\r\n}\r\n// 视频模型\r\ninterface VideoModel {\r\n name: string; // 显示名称\r\n modelName: string; //全局唯一\r\n type: \"video\";\r\n mode: (\r\n | \"singleImage\" // 单图\r\n | \"startEndRequired\" // 首尾帧(两张都得有)\r\n | \"endFrameOptional\" // 首尾帧(尾帧可选)\r\n | \"startFrameOptional\" // 首尾帧(首帧可选)\r\n | \"text\" // 文本生视频\r\n | (\"videoReference\" | \"imageReference\" | \"audioReference\" | \"textReference\")[] // 混合参考\r\n )[];\r\n associationSkills?: string; // 关联技能,多个技能用逗号分隔\r\n audio: \"optional\" | false | true; // 音频配置\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string; // 显示名称\r\n modelName: string;\r\n type: \"tts\";\r\n voices: {\r\n title: string; //显示名称\r\n voice: string; //说话人\r\n }[];\r\n}\r\n// 供应商配置\r\ninterface VendorConfig {\r\n id: string; //供应商唯一标识,必须全局唯一\r\n author: string;\r\n description?: string; //md5格式\r\n name: string;\r\n icon?: string; //仅支持base64格式\r\n inputs: {\r\n key: string;\r\n label: string;\r\n type: \"text\" | \"password\" | \"url\";\r\n required: boolean;\r\n placeholder?: string;\r\n }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel)[];\r\n}\r\n// ==================== 全局工具函数 ====================\r\n//Axios实例\r\n//压缩图片大小(1MB = 1 * 1024 * 1024)\r\ndeclare const zipImage: (completeBase64: string, size: number) => Promise;\r\n//压缩图片分辨率\r\ndeclare const zipImageResolution: (completeBase64: string, width: number, height: number) => Promise;\r\n//多图拼接乘单图 maxSize 最大输出大小,默认为 10mb\r\ndeclare const mergeImages: (completeBase64: string[], maxSize?: string) => Promise;\r\n//Url转Base64\r\ndeclare const urlToBase64: (url: string) => Promise;\r\n//轮询函数\r\ndeclare const pollTask: (\r\n fn: () => Promise<{ completed: boolean; data?: string; error?: string }>,\r\n interval?: number,\r\n timeout?: number,\r\n) => Promise<{ completed: boolean; data?: string; error?: string }>;\r\ndeclare const axios: any;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const logger: (logstring: string) => void;\r\ndeclare const jsonwebtoken: any;\r\n// ==================== 供应商数据 ====================\r\nconst vendor: VendorConfig = {\r\n id: \"vidu\",\r\n author: \"搬砖的Coder\",\r\n description:\r\n \"Vidu 官方视频生成平台。 [前往平台](https://platform.vidu.cn/login/)\",\r\n name: \"Vidu 开放平台\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true, placeholder: \"请到Vidu官方申请\" },\r\n { key: \"baseUrl\", label: \"接口路径\", type: \"url\", required: true, placeholder: \"https://api.vidu.cn/ent/v2\" },\r\n ],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://api.vidu.cn/ent/v2\",\r\n },\r\n models: [\r\n {\r\n name: \"ViduQ3 turbo\",\r\n type: \"video\",\r\n modelName: \"ViduQ3-turbo\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\", \"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ3 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ3-pro\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\", \"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ2 pro fast\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-pro-fast\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"viduQ2 turbo\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-turbo\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ2 pro\",\r\n type: \"video\",\r\n modelName: \"ViduQ2-pro\",\r\n durationResolutionMap: [{ duration: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], resolution: [\"540p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"], //参考生视频无有效设置值\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ2\",\r\n type: \"video\",\r\n modelName: \"ViduQ2\",\r\n durationResolutionMap: [{ duration: [5], resolution: [\"1080p\"] }],\r\n mode: [\"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ1\",\r\n type: \"video\",\r\n modelName: \"ViduQ1\",\r\n durationResolutionMap: [{ duration: [5], resolution: [\"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\", \"text\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"ViduQ1 classic\",\r\n type: \"video\",\r\n modelName: \"viduQ1-classic\",\r\n durationResolutionMap: [{ duration: [5], resolution: [\"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"Vidu2.0\",\r\n type: \"video\",\r\n modelName: \"vidu2.0\",\r\n durationResolutionMap: [{ duration: [4, 8], resolution: [\"360p\", \"720p\", \"1080p\"] }],\r\n mode: [\"singleImage\", \"startEndRequired\"],\r\n audio: true,\r\n },\r\n {\r\n name: \"viduq1 for image\",\r\n type: \"image\",\r\n modelName: \"viduq1\",\r\n mode: [\"text\"],\r\n },\r\n {\r\n name: \"viduq2 for image\",\r\n type: \"image\",\r\n modelName: \"viduq2\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n ],\r\n};\r\nexports.vendor = vendor;\r\n\r\n// ==================== 适配器函数 ====================\r\n\r\n// 文本请求函数\r\nconst textRequest: (textModel: TextModel) => { url: string; model: string } = (textModel) => {\r\n throw new Error(\"当前供应商仅支持视频大模型,谢谢!\");\r\n};\r\nexports.textRequest = textRequest;\r\n\r\n//图片请求函数\r\ninterface ImageConfig {\r\n prompt: string; //图片提示词\r\n imageBase64: string[]; //输入的图片提示词\r\n size: \"1K\" | \"2K\" | \"4K\"; // 图片尺寸\r\n aspectRatio: `${number}:${number}`; // 长宽比\r\n}\r\nconst imageRequest = async (imageConfig: ImageConfig, imageModel: ImageModel) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(\"Token \", \"\");\r\n\r\n const size = imageConfig.size === \"1K\" ? \"2K\" : imageConfig.size;\r\n const sizeMap: Record> = {\r\n \"16:9\": {\r\n \"1k\": \"1920x1080\",\r\n \"2K\": \"2848x1600\",\r\n \"4K\": \"4096x2304\",\r\n },\r\n \"9:16\": {\r\n \"1k\": \"1920x1080\",\r\n \"2K\": \"1600x2848\",\r\n \"4K\": \"2304x4096\",\r\n },\r\n };\r\n\r\n const body: Record = {\r\n model: imageModel.modelName,\r\n prompt: imageConfig.prompt,\r\n aspect_ratio: sizeMap[imageConfig.aspectRatio][size],\r\n seed: 0,\r\n resolution: size,\r\n ...(imageConfig.imageBase64 && { image: imageConfig.imageBase64 }),\r\n };\r\n\r\n const createImageUrl = vendor.inputValues.baseUrl + \"/reference2image\";\r\n const response = await fetch(createImageUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Token ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(body),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text(); // 获取错误信息\r\n console.error(\"请求失败,状态码:\", response.status, \", 错误信息:\", errorText);\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const res = await checkTaskResult(data.task_id);\r\n if (!res.data) {\r\n throw new Error(\"图片未能生成\");\r\n }\r\n const list = JSON.parse(JSON.stringify(res.data));\r\n return list[0].url;\r\n};\r\nexports.imageRequest = imageRequest;\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n imageBase64?: string[];\r\n audio?: boolean;\r\n mode:\r\n | \"singleImage\" // 单图\r\n | \"multiImage\" // 多图模式\r\n | \"gridImage\" // 网格单图(传入一张图片,但该图片是网格图)\r\n | \"startEndRequired\" // 首尾帧(两张都得有)\r\n | \"endFrameOptional\" // 首尾帧(尾帧可选)\r\n | \"startFrameOptional\" // 首尾帧(首帧可选)\r\n | \"text\" // 文本生视频\r\n | (\"video\" | \"image\" | \"audio\" | \"text\")[]; // 混合参考\r\n}\r\n\r\n// 构建 各个平台的metadata参数\r\n\r\nconst buildViduMetadata = (videoConfig: VideoConfig) => ({\r\n aspect_ratio: videoConfig.aspectRatio,\r\n audio: videoConfig.audio ?? false,\r\n off_peak: false,\r\n});\r\n\r\ntype MetadataBuilder = (config: VideoConfig) => Record;\r\nconst METADATA_BUILDERS: Array<[string, MetadataBuilder]> = [[\"vidu\", buildViduMetadata]];\r\nconst buildModelMetadata = (modelName: string, videoConfig: VideoConfig) => {\r\n const lowerName = modelName.toLowerCase();\r\n const match = METADATA_BUILDERS.find(([key]) => lowerName.includes(key));\r\n return match ? match[1](videoConfig) : {};\r\n};\r\n// 检查生成物结果\r\nconst checkTaskResult = async (taskId: string) => {\r\n const queryUrl = vendor.inputValues.baseUrl + \"/tasks/{id}/creations\";\r\n const apiKey = vendor.inputValues.apiKey;\r\n const res = await pollTask(async () => {\r\n const queryResponse = await fetch(queryUrl.replace(\"{id}\", taskId), {\r\n method: \"GET\",\r\n headers: { Authorization: `Token ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n });\r\n if (!queryResponse.ok) {\r\n const errorText = await queryResponse.text(); // 获取错误信息\r\n console.error(\"请求失败,状态码:\", queryResponse.status, \", 错误信息:\", errorText);\r\n throw new Error(`请求失败,状态码: ${queryResponse.status}, 错误信息: ${errorText}`);\r\n }\r\n const queryData = await queryResponse.json();\r\n const status = queryData?.state ?? queryData?.data?.state;\r\n const fail_reason = queryData?.data?.err_code ?? queryData?.data;\r\n switch (status) {\r\n case \"completed\":\r\n case \"SUCCESS\":\r\n case \"success\":\r\n return { completed: true, data: queryData.creations };\r\n case \"FAILURE\":\r\n case \"failed\":\r\n return { completed: false, error: fail_reason || \"生成失败\" };\r\n default:\r\n return { completed: false };\r\n }\r\n });\r\n if (res.error) throw new Error(res.error);\r\n return res;\r\n};\r\n\r\nconst videoRequest = async (videoConfig: VideoConfig, videoModel: VideoModel) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(\"Token \", \"\");\r\n\r\n // 构建每个模型对应的附加参数\r\n const metadata = buildModelMetadata(videoModel.modelName, videoConfig);\r\n\r\n //公共请求参数\r\n const publicBody = {\r\n model: videoModel.modelName,\r\n ...(videoConfig.imageBase64 && videoConfig.imageBase64.length ? { images: videoConfig.imageBase64 } : {}),\r\n prompt: videoConfig.prompt,\r\n size: videoConfig.resolution,\r\n duration: videoConfig.duration,\r\n metadata: metadata,\r\n };\r\n\r\n const requestUrl = vendor.inputValues.baseUrl + \"/start-end2video\";\r\n const response = await fetch(requestUrl, {\r\n method: \"POST\",\r\n headers: { Authorization: `Token ${apiKey}`, \"Content-Type\": \"application/json\" },\r\n body: JSON.stringify(publicBody),\r\n });\r\n if (!response.ok) {\r\n const errorText = await response.text(); // 获取错误信息\r\n console.error(\"请求失败,状态码:\", response.status, \", 错误信息:\", errorText);\r\n throw new Error(`请求失败,状态码: ${response.status}, 错误信息: ${errorText}`);\r\n }\r\n const data = await response.json();\r\n const taskId = data.id;\r\n const result = await checkTaskResult(taskId);\r\n return result.data;\r\n};\r\nexports.videoRequest = videoRequest;\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n}\r\nconst ttsRequest = async (ttsConfig: TTSConfig, ttsModel: TTSModel) => {\r\n throw new Error(\"Vidu 暂不支持语音合成(TTS)\");\r\n};\r\n", + "volcengine.ts": "/**\r\n * Toonflow AI供应商模板 - 火山引擎(豆包)\r\n * @version 2.0\r\n */\r\n\r\n// ============================================================\r\n// 类型定义\r\n// ============================================================\r\n\r\ntype VideoMode =\r\n | \"singleImage\"\r\n | \"startEndRequired\"\r\n | \"endFrameOptional\"\r\n | \"startFrameOptional\"\r\n | \"text\"\r\n | (`videoReference:${number}` | `imageReference:${number}` | `audioReference:${number}`)[];\r\n\r\ninterface TextModel {\r\n name: string;\r\n modelName: string;\r\n type: \"text\";\r\n think: boolean;\r\n}\r\n\r\ninterface ImageModel {\r\n name: string;\r\n modelName: string;\r\n type: \"image\";\r\n mode: (\"text\" | \"singleImage\" | \"multiReference\")[];\r\n associationSkills?: string;\r\n}\r\n\r\ninterface VideoModel {\r\n name: string;\r\n modelName: string;\r\n type: \"video\";\r\n mode: VideoMode[];\r\n associationSkills?: string;\r\n audio: \"optional\" | false | true;\r\n durationResolutionMap: { duration: number[]; resolution: string[] }[];\r\n}\r\n\r\ninterface TTSModel {\r\n name: string;\r\n modelName: string;\r\n type: \"tts\";\r\n voices: { title: string; voice: string }[];\r\n}\r\n\r\ninterface VendorConfig {\r\n id: string;\r\n version: string;\r\n name: string;\r\n author: string;\r\n description?: string;\r\n icon?: string;\r\n inputs: { key: string; label: string; type: \"text\" | \"password\" | \"url\"; required: boolean; placeholder?: string }[];\r\n inputValues: Record;\r\n models: (TextModel | ImageModel | VideoModel | TTSModel)[];\r\n}\r\n\r\ntype ReferenceList =\r\n | { type: \"image\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"audio\"; sourceType: \"base64\"; base64: string }\r\n | { type: \"video\"; sourceType: \"base64\"; base64: string };\r\n\r\ninterface ImageConfig {\r\n prompt: string;\r\n referenceList?: Extract[];\r\n size: \"1K\" | \"2K\" | \"4K\";\r\n aspectRatio: `${number}:${number}`;\r\n}\r\n\r\ninterface VideoConfig {\r\n duration: number;\r\n resolution: string;\r\n aspectRatio: \"16:9\" | \"9:16\";\r\n prompt: string;\r\n referenceList?: ReferenceList[];\r\n audio?: boolean;\r\n mode: VideoMode[];\r\n}\r\n\r\ninterface TTSConfig {\r\n text: string;\r\n voice: string;\r\n speechRate: number;\r\n pitchRate: number;\r\n volume: number;\r\n referenceList?: Extract[];\r\n}\r\n\r\ninterface PollResult {\r\n completed: boolean;\r\n data?: string;\r\n error?: string;\r\n}\r\n\r\n// ============================================================\r\n// 全局声明\r\n// ============================================================\r\n\r\ndeclare const axios: any;\r\ndeclare const logger: (msg: string) => void;\r\ndeclare const jsonwebtoken: any;\r\ndeclare const zipImage: (base64: string, size: number) => Promise;\r\ndeclare const zipImageResolution: (base64: string, w: number, h: number) => Promise;\r\ndeclare const mergeImages: (base64Arr: string[], maxSize?: string) => Promise;\r\ndeclare const urlToBase64: (url: string) => Promise;\r\ndeclare const pollTask: (fn: () => Promise, interval?: number, timeout?: number) => Promise;\r\ndeclare const createOpenAI: any;\r\ndeclare const createDeepSeek: any;\r\ndeclare const createZhipu: any;\r\ndeclare const createQwen: any;\r\ndeclare const createAnthropic: any;\r\ndeclare const createOpenAICompatible: any;\r\ndeclare const createXai: any;\r\ndeclare const createMinimax: any;\r\ndeclare const createGoogleGenerativeAI: any;\r\ndeclare const exports: {\r\n vendor: VendorConfig;\r\n textRequest: (m: TextModel, t: boolean, tl: 0 | 1 | 2 | 3) => any;\r\n imageRequest: (c: ImageConfig, m: ImageModel) => Promise;\r\n videoRequest: (c: VideoConfig, m: VideoModel) => Promise;\r\n ttsRequest: (c: TTSConfig, m: TTSModel) => Promise;\r\n checkForUpdates?: () => Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }>;\r\n updateVendor?: () => Promise;\r\n};\r\n\r\n// ============================================================\r\n// 供应商配置\r\n// ============================================================\r\n\r\nconst vendor: VendorConfig = {\r\n id: \"volcengine\",\r\n version: \"2.2\",\r\n author: \"leeqi\",\r\n name: \"火山引擎(豆包)\",\r\n description:\r\n \"火山引擎豆包大模型,支持文本、图片生成、视频生成等能力。\\n\\n需要在[火山引擎控制台](https://console.volcengine.com/ark)获取API密钥。\",\r\n icon: \"\",\r\n inputs: [\r\n { key: \"apiKey\", label: \"API密钥\", type: \"password\", required: true, placeholder: \"火山引擎API Key\" },\r\n { key: \"baseUrl\", label: \"请求地址\", type: \"url\", required: true, placeholder: \"以v3结束,示例:https://ark.cn-beijing.volces.com/api/v3\" },\r\n ],\r\n inputValues: {\r\n apiKey: \"\",\r\n baseUrl: \"https://ark.cn-beijing.volces.com/api/v3\",\r\n },\r\n models: [\r\n // ===================== 文本模型 - 推荐 =====================\r\n { name: \"Doubao-Seed-2.0-Pro\", modelName: \"doubao-seed-2-0-pro-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-2.0-Lite\", modelName: \"doubao-seed-2-0-lite-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-2.0-Mini\", modelName: \"doubao-seed-2-0-mini-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-2.0-Code-Preview\", modelName: \"doubao-seed-2-0-code-preview-260215\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-Character\", modelName: \"doubao-seed-character-251128\", type: \"text\", think: false },\r\n // ===================== 文本模型 - 往期 =====================\r\n { name: \"Doubao-Seed-1.8\", modelName: \"doubao-seed-1-8-251228\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-Code-Preview\", modelName: \"doubao-seed-code-preview-251028\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Lite\", modelName: \"doubao-seed-1-6-lite-251015\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Flash(0828)\", modelName: \"doubao-seed-1-6-flash-250828\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Vision\", modelName: \"doubao-seed-1-6-vision-250815\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6(1015)\", modelName: \"doubao-seed-1-6-251015\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6(0615)\", modelName: \"doubao-seed-1-6-250615\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-1.6-Flash(0615)\", modelName: \"doubao-seed-1-6-flash-250615\", type: \"text\", think: true },\r\n { name: \"Doubao-Seed-Translation\", modelName: \"doubao-seed-translation-250915\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Pro-32K\", modelName: \"doubao-1-5-pro-32k-250115\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Pro-32K-Character(0715)\", modelName: \"doubao-1-5-pro-32k-character-250715\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Pro-32K-Character(0228)\", modelName: \"doubao-1-5-pro-32k-character-250228\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Lite-32K\", modelName: \"doubao-1-5-lite-32k-250115\", type: \"text\", think: false },\r\n { name: \"Doubao-1.5-Vision-Pro-32K\", modelName: \"doubao-1-5-vision-pro-32k-250115\", type: \"text\", think: false },\r\n // ===================== 文本模型 - 第三方(火山引擎托管) =====================\r\n { name: \"GLM-4-7\", modelName: \"glm-4-7-251222\", type: \"text\", think: true },\r\n { name: \"DeepSeek-V3-2\", modelName: \"deepseek-v3-2-251201\", type: \"text\", think: true },\r\n { name: \"DeepSeek-V3-1-Terminus\", modelName: \"deepseek-v3-1-terminus\", type: \"text\", think: true },\r\n { name: \"DeepSeek-V3(0324)\", modelName: \"deepseek-v3-250324\", type: \"text\", think: false },\r\n { name: \"DeepSeek-R1(0528)\", modelName: \"deepseek-r1-250528\", type: \"text\", think: true },\r\n { name: \"Qwen3-32B\", modelName: \"qwen3-32b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen3-14B\", modelName: \"qwen3-14b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen3-8B\", modelName: \"qwen3-8b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen3-0.6B\", modelName: \"qwen3-0-6b-20250429\", type: \"text\", think: false },\r\n { name: \"Qwen2.5-72B\", modelName: \"qwen2-5-72b-20240919\", type: \"text\", think: false },\r\n { name: \"GLM-4.5-Air\", modelName: \"glm-4-5-air\", type: \"text\", think: false },\r\n // ===================== 图片生成模型 =====================\r\n {\r\n name: \"Seedream-5.0\",\r\n modelName: \"doubao-seedream-5-0-260128\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-5.0-Lite\",\r\n modelName: \"doubao-seedream-5-0-lite-260128\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-4.5\",\r\n modelName: \"doubao-seedream-4-5-251128\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-4.0\",\r\n modelName: \"doubao-seedream-4-0-250828\",\r\n type: \"image\",\r\n mode: [\"text\", \"singleImage\", \"multiReference\"],\r\n },\r\n {\r\n name: \"Seedream-3.0-T2I\",\r\n modelName: \"doubao-seedream-3-0-t2i-250415\",\r\n type: \"image\",\r\n mode: [\"text\"],\r\n },\r\n // ===================== 视频生成模型 =====================\r\n {\r\n name: \"Seedance-2.0(音画同生)\",\r\n modelName: \"doubao-seedance-2-0-260128\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\", [\"imageReference:9\", \"videoReference:3\", \"audioReference:3\"]],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"480p\", \"720p\"] }],\r\n },\r\n {\r\n name: \"Seedance-2.0-Fast(音画同生)\",\r\n modelName: \"doubao-seedance-2-0-fast-260128\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\", [\"imageReference:9\", \"videoReference:3\", \"audioReference:3\"]],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], resolution: [\"480p\", \"720p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.5-Pro(音画同生)\",\r\n modelName: \"doubao-seedance-1-5-pro-251215\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\"],\r\n audio: \"optional\",\r\n durationResolutionMap: [{ duration: [4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Pro\",\r\n modelName: \"doubao-seedance-1-0-pro-250528\",\r\n type: \"video\",\r\n mode: [\"text\", \"startFrameOptional\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Pro-Fast\",\r\n modelName: \"doubao-seedance-1-0-pro-fast-251015\",\r\n type: \"video\",\r\n mode: [\"text\", \"singleImage\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Lite-T2V\",\r\n modelName: \"doubao-seedance-1-0-lite-t2v-250428\",\r\n type: \"video\",\r\n mode: [\"text\"],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n {\r\n name: \"Seedance-1.0-Lite-I2V\",\r\n modelName: \"doubao-seedance-1-0-lite-i2v-250428\",\r\n type: \"video\",\r\n mode: [\"startFrameOptional\", [\"imageReference:4\"]],\r\n audio: false,\r\n durationResolutionMap: [{ duration: [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], resolution: [\"480p\", \"720p\", \"1080p\"] }],\r\n },\r\n ],\r\n};\r\n\r\n// ============================================================\r\n// 辅助工具\r\n// ============================================================\r\n\r\nconst getHeaders = () => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n return {\r\n \"Content-Type\": \"application/json\",\r\n Authorization: `Bearer ${vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\")}`,\r\n };\r\n};\r\n\r\nconst getBaseUrl = () => vendor.inputValues.baseUrl.replace(/\\/+$/, \"\");\r\n\r\n// ============================================================\r\n// 适配器函数\r\n// ============================================================\r\n\r\nconst textRequest = (model: TextModel, think: boolean, thinkLevel: 0 | 1 | 2 | 3) => {\r\n if (!vendor.inputValues.apiKey) throw new Error(\"缺少API Key\");\r\n const apiKey = vendor.inputValues.apiKey.replace(/^Bearer\\s+/i, \"\");\r\n\r\n const effortMap: Record = {\r\n 0: \"minimal\",\r\n 1: \"low\",\r\n 2: \"medium\",\r\n 3: \"high\",\r\n };\r\n\r\n return createOpenAICompatible({\r\n name: \"volcengine\",\r\n baseURL: getBaseUrl(),\r\n apiKey,\r\n fetch: async (url: string, options?: RequestInit) => {\r\n const rawBody = JSON.parse((options?.body as string) ?? \"{}\");\r\n const modifiedBody = {\r\n ...rawBody,\r\n thinking: {\r\n type: \"enabled\",\r\n },\r\n reasoning_effort: effortMap[thinkLevel],\r\n };\r\n return await fetch(url, {\r\n ...options,\r\n body: JSON.stringify(modifiedBody),\r\n });\r\n },\r\n }).chatModel(model.modelName);\r\n};\r\n\r\nconst imageRequest = async (config: ImageConfig, model: ImageModel): Promise => {\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const body: any = {\r\n model: model.modelName,\r\n prompt: config.prompt || \"\",\r\n response_format: \"url\",\r\n watermark: false,\r\n };\r\n\r\n const isOldModel = model.modelName.includes(\"seedream-3-0\");\r\n const is5Lite = model.modelName.includes(\"seedream-5-0-lite\");\r\n\r\n // sequential_image_generation 仅 seedream 5.0-lite/4.5/4.0 支持\r\n if (!isOldModel) {\r\n body.sequential_image_generation = \"disabled\";\r\n }\r\n\r\n // 参考图片:单图为 string,多图为 array(seedream-3.0-t2i 不支持 image 参数)\r\n if (!isOldModel && config.referenceList && config.referenceList.length > 0) {\r\n const images = config.referenceList.map((ref) => ref.base64);\r\n body.image = images.length === 1 ? images[0] : images;\r\n }\r\n\r\n // 尺寸处理:优先使用推荐像素值,未匹配则直接传分辨率字符串让模型自行决定\r\n const [w, h] = config.aspectRatio.split(\":\").map(Number);\r\n const sizeTable: Record> = {\r\n \"1K\": {\r\n \"1:1\": \"1024x1024\",\r\n \"4:3\": \"1152x864\",\r\n \"3:4\": \"864x1152\",\r\n \"16:9\": \"1280x720\",\r\n \"9:16\": \"720x1280\",\r\n \"3:2\": \"1248x832\",\r\n \"2:3\": \"832x1248\",\r\n \"21:9\": \"1512x648\",\r\n },\r\n \"2K\": {\r\n \"1:1\": \"2048x2048\",\r\n \"4:3\": \"2304x1728\",\r\n \"3:4\": \"1728x2304\",\r\n \"16:9\": \"2848x1600\",\r\n \"9:16\": \"1600x2848\",\r\n \"3:2\": \"2496x1664\",\r\n \"2:3\": \"1664x2496\",\r\n \"21:9\": \"3136x1344\",\r\n },\r\n \"4K\": {\r\n \"1:1\": \"4096x4096\",\r\n \"4:3\": \"4704x3520\",\r\n \"3:4\": \"3520x4704\",\r\n \"16:9\": \"5504x3040\",\r\n \"9:16\": \"3040x5504\",\r\n \"3:2\": \"4992x3328\",\r\n \"2:3\": \"3328x4992\",\r\n \"21:9\": \"6240x2656\",\r\n },\r\n };\r\n\r\n const sizeKey = config.size || \"2K\";\r\n const ratioKey = config.aspectRatio;\r\n const table = sizeTable[sizeKey];\r\n\r\n if (table && table[ratioKey]) {\r\n // 推荐像素值匹配到了,但需要检查是否满足模型最低像素要求\r\n const [pw, ph] = table[ratioKey].split(\"x\").map(Number);\r\n const totalPixels = pw * ph;\r\n if (isOldModel) {\r\n // seedream-3.0-t2i: 像素范围 [512x512, 2048x2048]\r\n body.size = table[ratioKey];\r\n } else if (totalPixels < 3686400) {\r\n // 1K 像素值不满足新模型最低要求,直接传 \"2K\" 让模型自行决定\r\n body.size = \"2K\";\r\n } else if (is5Lite && totalPixels > 10404496) {\r\n // seedream-5.0-lite 最高 10404496,4K 超限,回退传 \"2K\"\r\n body.size = \"2K\";\r\n } else {\r\n body.size = table[ratioKey];\r\n }\r\n } else if (isOldModel) {\r\n // seedream-3.0-t2i: 像素范围 [512x512, 2048x2048],直接按比例计算\r\n const base = sizeKey === \"1K\" ? 1024 : 2048;\r\n const calcW = Math.min(2048, Math.round(base * Math.sqrt(w / h)));\r\n const calcH = Math.min(2048, Math.round(base * Math.sqrt(h / w)));\r\n body.size = `${Math.max(512, calcW)}x${Math.max(512, calcH)}`;\r\n } else {\r\n // 新模型未匹配推荐值时,直接传分辨率字符串(方式1),由模型根据 prompt 自行决定尺寸\r\n // seedream 5.0-lite 支持 \"2K\"/\"3K\",seedream 4.5 支持 \"2K\"/\"4K\",seedream 4.0 支持 \"1K\"/\"2K\"/\"4K\"\r\n if (is5Lite) {\r\n body.size = sizeKey === \"4K\" ? \"3K\" : sizeKey === \"1K\" ? \"2K\" : sizeKey;\r\n } else {\r\n body.size = sizeKey === \"1K\" ? \"2K\" : sizeKey;\r\n }\r\n }\r\n\r\n logger(`[图片生成] 请求模型: ${model.modelName}, 尺寸: ${body.size}`);\r\n\r\n const response = await axios.post(`${baseUrl}/images/generations`, body, { headers });\r\n const data = response.data;\r\n\r\n if (data?.error) {\r\n throw new Error(`图片生成失败:${data.error.message || data.error.code}`);\r\n }\r\n\r\n // 从 data 数组中提取第一张成功的图片\r\n if (data?.data && data.data.length > 0) {\r\n for (const item of data.data) {\r\n if (item.url) {\r\n return await urlToBase64(item.url);\r\n }\r\n if (item.b64_json) {\r\n return item.b64_json;\r\n }\r\n if (item.error) {\r\n throw new Error(`图片生成失败:${item.error.message || item.error.code}`);\r\n }\r\n }\r\n }\r\n\r\n throw new Error(\"图片生成失败:未返回有效结果\");\r\n};\r\n\r\nconst videoRequest = async (config: VideoConfig, model: VideoModel): Promise => {\r\n const baseUrl = getBaseUrl();\r\n const headers = getHeaders();\r\n\r\n const content: any[] = [];\r\n\r\n if (config.prompt) {\r\n content.push({ type: \"text\", text: config.prompt });\r\n }\r\n\r\n const activeMode = config.mode && config.mode.length > 0 ? config.mode[0] : \"text\";\r\n\r\n if (typeof activeMode === \"string\") {\r\n switch (activeMode) {\r\n case \"singleImage\": {\r\n const firstImage = config.referenceList?.find((r) => r.type === \"image\");\r\n if (firstImage) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: firstImage.base64 },\r\n role: \"first_frame\",\r\n });\r\n }\r\n break;\r\n }\r\n case \"startFrameOptional\": {\r\n const images = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n if (images.length > 0) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[0].base64 },\r\n role: \"first_frame\",\r\n });\r\n if (images.length > 1) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[1].base64 },\r\n role: \"last_frame\",\r\n });\r\n }\r\n }\r\n break;\r\n }\r\n case \"startEndRequired\": {\r\n const images = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n if (images.length >= 2) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[0].base64 },\r\n role: \"first_frame\",\r\n });\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[1].base64 },\r\n role: \"last_frame\",\r\n });\r\n }\r\n break;\r\n }\r\n case \"endFrameOptional\": {\r\n const images = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n if (images.length > 0) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[0].base64 },\r\n role: \"first_frame\",\r\n });\r\n if (images.length > 1) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: images[1].base64 },\r\n role: \"last_frame\",\r\n });\r\n }\r\n }\r\n break;\r\n }\r\n case \"text\":\r\n default:\r\n break;\r\n }\r\n } else if (Array.isArray(activeMode)) {\r\n // 多模态参考模式:按类型分别提取并添加\r\n const imageRefs = config.referenceList?.filter((r) => r.type === \"image\") ?? [];\r\n const videoRefs = config.referenceList?.filter((r) => r.type === \"video\") ?? [];\r\n const audioRefs = config.referenceList?.filter((r) => r.type === \"audio\") ?? [];\r\n\r\n for (const refDef of activeMode) {\r\n if (typeof refDef === \"string\") {\r\n if (refDef.startsWith(\"imageReference:\")) {\r\n const maxCount = parseInt(refDef.split(\":\")[1], 10);\r\n for (const ref of imageRefs.slice(0, maxCount)) {\r\n content.push({\r\n type: \"image_url\",\r\n image_url: { url: ref.base64 },\r\n role: \"reference_image\",\r\n });\r\n }\r\n } else if (refDef.startsWith(\"videoReference:\")) {\r\n const maxCount = parseInt(refDef.split(\":\")[1], 10);\r\n for (const ref of videoRefs.slice(0, maxCount)) {\r\n content.push({\r\n type: \"video_url\",\r\n video_url: { url: ref.base64 },\r\n role: \"reference_video\",\r\n });\r\n }\r\n } else if (refDef.startsWith(\"audioReference:\")) {\r\n const maxCount = parseInt(refDef.split(\":\")[1], 10);\r\n for (const ref of audioRefs.slice(0, maxCount)) {\r\n content.push({\r\n type: \"audio_url\",\r\n audio_url: { url: ref.base64 },\r\n role: \"reference_audio\",\r\n });\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n const body: any = {\r\n model: model.modelName,\r\n content,\r\n ratio: config.aspectRatio,\r\n duration: config.duration,\r\n resolution: config.resolution || \"720p\",\r\n watermark: false,\r\n };\r\n\r\n if (model.audio === \"optional\") {\r\n body.generate_audio = config.audio !== false;\r\n } else if (model.audio === true) {\r\n body.generate_audio = true;\r\n } else {\r\n body.generate_audio = false;\r\n }\r\n\r\n logger(`[视频生成] 提交任务, 模型: ${model.modelName}, 时长: ${config.duration}s, 分辨率: ${config.resolution}`);\r\n\r\n const createResponse = await axios.post(`${baseUrl}/contents/generations/tasks`, body, { headers });\r\n const taskId = createResponse.data?.id;\r\n\r\n if (!taskId) {\r\n throw new Error(\"视频生成任务创建失败:未返回任务ID\");\r\n }\r\n\r\n logger(`[视频生成] 任务已创建, ID: ${taskId}`);\r\n\r\n const result = await pollTask(\r\n async (): Promise => {\r\n const queryResponse = await axios.get(`${baseUrl}/contents/generations/tasks/${taskId}`, { headers });\r\n const task = queryResponse.data;\r\n\r\n logger(`[视频生成] 任务状态: ${task.status}`);\r\n\r\n switch (task.status) {\r\n case \"succeeded\":\r\n if (task.content?.video_url) {\r\n return { completed: true, data: task.content.video_url };\r\n }\r\n return { completed: true, error: \"任务成功但未返回视频URL\" };\r\n case \"failed\":\r\n return { completed: true, error: task.error?.message || \"视频生成失败\" };\r\n case \"expired\":\r\n return { completed: true, error: \"视频生成任务超时\" };\r\n case \"cancelled\":\r\n return { completed: true, error: \"视频生成任务已取消\" };\r\n default:\r\n return { completed: false };\r\n }\r\n },\r\n 10000,\r\n 600000,\r\n );\r\n\r\n if (result.error) {\r\n throw new Error(result.error);\r\n }\r\n\r\n return await urlToBase64(result.data!);\r\n};\r\n\r\nconst ttsRequest = async (config: TTSConfig, model: TTSModel): Promise => {\r\n return \"\";\r\n};\r\n\r\nconst checkForUpdates = async (): Promise<{ hasUpdate: boolean; latestVersion: string; notice: string }> => {\r\n return { hasUpdate: false, latestVersion: \"2.0\", notice: \"\" };\r\n};\r\n\r\nconst updateVendor = async (): Promise => {\r\n return \"\";\r\n};\r\n\r\n// ============================================================\r\n// 导出\r\n// ============================================================\r\n\r\nexports.vendor = vendor;\r\nexports.textRequest = textRequest;\r\nexports.imageRequest = imageRequest;\r\nexports.videoRequest = videoRequest;\r\nexports.ttsRequest = ttsRequest;\r\nexports.checkForUpdates = checkForUpdates;\r\nexports.updateVendor = updateVendor;\r\n\r\nexport {};\r\n" +} \ No newline at end of file diff --git a/src/router.ts b/src/router.ts index 75869ff..2e05c13 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,8 +1,4 @@ -<<<<<<< HEAD -// @routes-hash 4d6cbfaad479bdfafe13bc61e7550f55 -======= -// @routes-hash e4baae699964f90e2e79664131c1c486 ->>>>>>> 00fb3993f5cea32d192ac8db82c2a1ae690e09a3 +// @routes-hash 0693afa45240a846389e06cf3b11dc91 import { Express } from "express"; import route1 from "./routes/agents/clearMemory"; @@ -53,50 +49,50 @@ import route45 from "./routes/novel/getNovelEventState"; import route46 from "./routes/novel/getNovelIndex"; import route47 from "./routes/novel/updateNovel"; import route48 from "./routes/other/deleteAllData"; -import route49 from "./routes/other/getModelDetails"; -import route50 from "./routes/other/getVersion"; -import route51 from "./routes/production/assets/batchGenerateAssetsImage"; -import route52 from "./routes/production/assets/deleteAssetsDireve"; -import route53 from "./routes/production/assets/getAssetsData"; -import route54 from "./routes/production/assets/pollingImage"; -import route55 from "./routes/production/assets/updateAssetsUrl"; -import route56 from "./routes/production/editImage/generateFlowImage"; -import route57 from "./routes/production/editImage/getImageDefaultModle"; -import route58 from "./routes/production/editImage/getImageFlow"; -import route59 from "./routes/production/editImage/saveImageFlow"; -import route60 from "./routes/production/editImage/updateImageFlow"; -import route61 from "./routes/production/editImage/uploadImage"; -import route62 from "./routes/production/getFlowData"; -import route63 from "./routes/production/getStoryboardData"; -import route64 from "./routes/production/saveFlowData"; -import route65 from "./routes/production/storyboard/addStoryboard"; -import route66 from "./routes/production/storyboard/batchAddStoryboardInfo"; -import route67 from "./routes/production/storyboard/batchGenerateImage"; -import route68 from "./routes/production/storyboard/downPreviewImage"; -import route69 from "./routes/production/storyboard/editStoryboardInfo"; -import route70 from "./routes/production/storyboard/getStoryboardData"; -import route71 from "./routes/production/storyboard/pollingImage"; -import route72 from "./routes/production/storyboard/previewImage"; -import route73 from "./routes/production/storyboard/removeFrame"; -import route74 from "./routes/production/storyboard/updateStoryboardUrl"; -import route75 from "./routes/production/workbench/addTrack"; -import route76 from "./routes/production/workbench/deleteTrack"; -import route77 from "./routes/production/workbench/delVideo"; -import route78 from "./routes/production/workbench/generateVideo"; -import route79 from "./routes/production/workbench/generateVideoPrompt"; -import route80 from "./routes/production/workbench/getGenerateData"; -import route81 from "./routes/production/workbench/getVideoList"; -import route82 from "./routes/production/workbench/selectVideo"; -import route83 from "./routes/production/workbench/updateVideoPrompt"; -import route84 from "./routes/project/addDirectorManual"; -import route85 from "./routes/project/addProject"; -import route86 from "./routes/project/addVisualManual"; -import route87 from "./routes/project/deleteDirectorManual"; -import route88 from "./routes/project/deleteVisualManual"; -import route89 from "./routes/project/delProject"; -import route90 from "./routes/project/editDirectorlManual"; -import route91 from "./routes/project/editProject"; -import route92 from "./routes/project/editVisualManual"; +import route49 from "./routes/other/getVersion"; +import route50 from "./routes/production/assets/batchGenerateAssetsImage"; +import route51 from "./routes/production/assets/deleteAssetsDireve"; +import route52 from "./routes/production/assets/getAssetsData"; +import route53 from "./routes/production/assets/pollingImage"; +import route54 from "./routes/production/assets/updateAssetsUrl"; +import route55 from "./routes/production/editImage/generateFlowImage"; +import route56 from "./routes/production/editImage/getImageDefaultModle"; +import route57 from "./routes/production/editImage/getImageFlow"; +import route58 from "./routes/production/editImage/saveImageFlow"; +import route59 from "./routes/production/editImage/updateImageFlow"; +import route60 from "./routes/production/editImage/uploadImage"; +import route61 from "./routes/production/getFlowData"; +import route62 from "./routes/production/getStoryboardData"; +import route63 from "./routes/production/saveFlowData"; +import route64 from "./routes/production/storyboard/addStoryboard"; +import route65 from "./routes/production/storyboard/batchAddStoryboardInfo"; +import route66 from "./routes/production/storyboard/batchGenerateImage"; +import route67 from "./routes/production/storyboard/downPreviewImage"; +import route68 from "./routes/production/storyboard/editStoryboardInfo"; +import route69 from "./routes/production/storyboard/getStoryboardData"; +import route70 from "./routes/production/storyboard/pollingImage"; +import route71 from "./routes/production/storyboard/previewImage"; +import route72 from "./routes/production/storyboard/removeFrame"; +import route73 from "./routes/production/storyboard/updateStoryboardUrl"; +import route74 from "./routes/production/workbench/addTrack"; +import route75 from "./routes/production/workbench/deleteTrack"; +import route76 from "./routes/production/workbench/delVideo"; +import route77 from "./routes/production/workbench/generateVideo"; +import route78 from "./routes/production/workbench/generateVideoPrompt"; +import route79 from "./routes/production/workbench/getGenerateData"; +import route80 from "./routes/production/workbench/getVideoList"; +import route81 from "./routes/production/workbench/selectVideo"; +import route82 from "./routes/production/workbench/updateVideoPrompt"; +import route83 from "./routes/project/addDirectorManual"; +import route84 from "./routes/project/addProject"; +import route85 from "./routes/project/addVisualManual"; +import route86 from "./routes/project/deleteDirectorManual"; +import route87 from "./routes/project/deleteVisualManual"; +import route88 from "./routes/project/delProject"; +import route89 from "./routes/project/editDirectorlManual"; +import route90 from "./routes/project/editProject"; +import route91 from "./routes/project/editVisualManual"; +import route92 from "./routes/project/getModelDetails"; import route93 from "./routes/project/getProject"; import route94 from "./routes/project/getVisualManual"; import route95 from "./routes/project/queryDirectorManual"; @@ -199,50 +195,50 @@ export default async (app: Express) => { app.use("/api/novel/getNovelIndex", route46); app.use("/api/novel/updateNovel", route47); app.use("/api/other/deleteAllData", route48); - app.use("/api/other/getModelDetails", route49); - app.use("/api/other/getVersion", route50); - app.use("/api/production/assets/batchGenerateAssetsImage", route51); - app.use("/api/production/assets/deleteAssetsDireve", route52); - app.use("/api/production/assets/getAssetsData", route53); - app.use("/api/production/assets/pollingImage", route54); - app.use("/api/production/assets/updateAssetsUrl", route55); - app.use("/api/production/editImage/generateFlowImage", route56); - app.use("/api/production/editImage/getImageDefaultModle", route57); - app.use("/api/production/editImage/getImageFlow", route58); - app.use("/api/production/editImage/saveImageFlow", route59); - app.use("/api/production/editImage/updateImageFlow", route60); - app.use("/api/production/editImage/uploadImage", route61); - app.use("/api/production/getFlowData", route62); - app.use("/api/production/getStoryboardData", route63); - app.use("/api/production/saveFlowData", route64); - app.use("/api/production/storyboard/addStoryboard", route65); - app.use("/api/production/storyboard/batchAddStoryboardInfo", route66); - app.use("/api/production/storyboard/batchGenerateImage", route67); - app.use("/api/production/storyboard/downPreviewImage", route68); - app.use("/api/production/storyboard/editStoryboardInfo", route69); - app.use("/api/production/storyboard/getStoryboardData", route70); - app.use("/api/production/storyboard/pollingImage", route71); - app.use("/api/production/storyboard/previewImage", route72); - app.use("/api/production/storyboard/removeFrame", route73); - app.use("/api/production/storyboard/updateStoryboardUrl", route74); - app.use("/api/production/workbench/addTrack", route75); - app.use("/api/production/workbench/deleteTrack", route76); - app.use("/api/production/workbench/delVideo", route77); - app.use("/api/production/workbench/generateVideo", route78); - app.use("/api/production/workbench/generateVideoPrompt", route79); - app.use("/api/production/workbench/getGenerateData", route80); - app.use("/api/production/workbench/getVideoList", route81); - app.use("/api/production/workbench/selectVideo", route82); - app.use("/api/production/workbench/updateVideoPrompt", route83); - app.use("/api/project/addDirectorManual", route84); - app.use("/api/project/addProject", route85); - app.use("/api/project/addVisualManual", route86); - app.use("/api/project/deleteDirectorManual", route87); - app.use("/api/project/deleteVisualManual", route88); - app.use("/api/project/delProject", route89); - app.use("/api/project/editDirectorlManual", route90); - app.use("/api/project/editProject", route91); - app.use("/api/project/editVisualManual", route92); + app.use("/api/other/getVersion", route49); + app.use("/api/production/assets/batchGenerateAssetsImage", route50); + app.use("/api/production/assets/deleteAssetsDireve", route51); + app.use("/api/production/assets/getAssetsData", route52); + app.use("/api/production/assets/pollingImage", route53); + app.use("/api/production/assets/updateAssetsUrl", route54); + app.use("/api/production/editImage/generateFlowImage", route55); + app.use("/api/production/editImage/getImageDefaultModle", route56); + app.use("/api/production/editImage/getImageFlow", route57); + app.use("/api/production/editImage/saveImageFlow", route58); + app.use("/api/production/editImage/updateImageFlow", route59); + app.use("/api/production/editImage/uploadImage", route60); + app.use("/api/production/getFlowData", route61); + app.use("/api/production/getStoryboardData", route62); + app.use("/api/production/saveFlowData", route63); + app.use("/api/production/storyboard/addStoryboard", route64); + app.use("/api/production/storyboard/batchAddStoryboardInfo", route65); + app.use("/api/production/storyboard/batchGenerateImage", route66); + app.use("/api/production/storyboard/downPreviewImage", route67); + app.use("/api/production/storyboard/editStoryboardInfo", route68); + app.use("/api/production/storyboard/getStoryboardData", route69); + app.use("/api/production/storyboard/pollingImage", route70); + app.use("/api/production/storyboard/previewImage", route71); + app.use("/api/production/storyboard/removeFrame", route72); + app.use("/api/production/storyboard/updateStoryboardUrl", route73); + app.use("/api/production/workbench/addTrack", route74); + app.use("/api/production/workbench/deleteTrack", route75); + app.use("/api/production/workbench/delVideo", route76); + app.use("/api/production/workbench/generateVideo", route77); + app.use("/api/production/workbench/generateVideoPrompt", route78); + app.use("/api/production/workbench/getGenerateData", route79); + app.use("/api/production/workbench/getVideoList", route80); + app.use("/api/production/workbench/selectVideo", route81); + app.use("/api/production/workbench/updateVideoPrompt", route82); + app.use("/api/project/addDirectorManual", route83); + app.use("/api/project/addProject", route84); + app.use("/api/project/addVisualManual", route85); + app.use("/api/project/deleteDirectorManual", route86); + app.use("/api/project/deleteVisualManual", route87); + app.use("/api/project/delProject", route88); + app.use("/api/project/editDirectorlManual", route89); + app.use("/api/project/editProject", route90); + app.use("/api/project/editVisualManual", route91); + app.use("/api/project/getModelDetails", route92); app.use("/api/project/getProject", route93); app.use("/api/project/getVisualManual", route94); app.use("/api/project/queryDirectorManual", route95); diff --git a/src/routes/assetsGenerate/batchGenerateImageAssets.ts b/src/routes/assetsGenerate/batchGenerateImageAssets.ts index 3a0bc67..b5d6f0c 100644 --- a/src/routes/assetsGenerate/batchGenerateImageAssets.ts +++ b/src/routes/assetsGenerate/batchGenerateImageAssets.ts @@ -141,7 +141,7 @@ export default router.post("/", validateFields(requestSchema), async (req, res) state: "已完成", filePath: imagePath, type: item.type, - model: model.split(":")[1], + model: model.split(/:(.+)/)[1], resolution, }); diff --git a/src/routes/assetsGenerate/generateAssets.ts b/src/routes/assetsGenerate/generateAssets.ts index 53f5834..9f180f9 100644 --- a/src/routes/assetsGenerate/generateAssets.ts +++ b/src/routes/assetsGenerate/generateAssets.ts @@ -123,7 +123,7 @@ export default router.post("/", validateFields(requestSchema), async (req, res) state: "已完成", filePath: imagePath, type, - model: model.split(":")[1], + model: model.split(/:(.+)/)[1], resolution, }); diff --git a/src/routes/other/getModelDetails.ts b/src/routes/project/getModelDetails.ts similarity index 71% rename from src/routes/other/getModelDetails.ts rename to src/routes/project/getModelDetails.ts index d411cf4..8dd5b30 100644 --- a/src/routes/other/getModelDetails.ts +++ b/src/routes/project/getModelDetails.ts @@ -8,11 +8,12 @@ const router = express.Router(); export default router.post( "/", validateFields({ - key: z.string().optional(), + key: z.enum(["scriptAgent", "productionAgent"]), }), async (req, res) => { const { key } = req.body; - const [id, modelName] = key ? key.split(":") : []; + const data = await u.db("o_agentDeploy").select("o_agentDeploy.*").where("o_agentDeploy.key", key).first(); + const [id, modelName] = data ? data.modelName.split(/:(.+)/) : []; const models = await u.vendor.getModelList(id); const model = models.find((m) => m.modelName === modelName); if (!model) return res.status(400).send(error("未找到模型")); diff --git a/src/socket/routes/productionAgent.ts b/src/socket/routes/productionAgent.ts index 06a92ee..a6877cd 100644 --- a/src/socket/routes/productionAgent.ts +++ b/src/socket/routes/productionAgent.ts @@ -78,10 +78,7 @@ export default (nsp: Namespace) => { await agent.runDecisionAI(ctx); } catch (err: any) { if (err.name !== "AbortError" && !currentController.signal.aborted) { - const errorMsg = u.error(err).message; - console.error("[productionAgent] chat error:", errorMsg); - ctx.msg.text(errorMsg).complete(); - ctx.msg.error(); + console.error("[productionAgent] chat error:", u.error(err).message); } } finally { if (abortController === currentController) { diff --git a/src/socket/routes/scriptAgent.ts b/src/socket/routes/scriptAgent.ts index feec101..44654ee 100644 --- a/src/socket/routes/scriptAgent.ts +++ b/src/socket/routes/scriptAgent.ts @@ -41,9 +41,9 @@ export default (nsp: Namespace) => { let abortController: AbortController | null = null; const thinkConfig: agent.AgentContext["thinkConfig"] = { - think:false, + think: false, thinlLevel: 0, - } + }; socket.on("chat", async (data: { content: string }) => { const { content } = data; @@ -67,10 +67,7 @@ export default (nsp: Namespace) => { await agent.runDecisionAI(ctx); } catch (err: any) { if (err.name !== "AbortError" && !currentController.signal.aborted) { - const errorMsg = u.error(err).message; - console.error("[scriptAgent] chat error:", errorMsg); - ctx.msg.text(errorMsg).complete(); - ctx.msg.error(); + console.error("[scriptAgent] chat error:", u.error(err).message); } } finally { if (abortController === currentController) { diff --git a/src/types/database.d.ts b/src/types/database.d.ts index 1995894..551db81 100644 --- a/src/types/database.d.ts +++ b/src/types/database.d.ts @@ -1,41 +1,6 @@ -<<<<<<< HEAD // @db-hash 9248d7bcfe0a1bc57e5b9bc33d8c7d83 -======= -// @db-hash 418553a1e8e732a796c512008db61467 ->>>>>>> 00fb3993f5cea32d192ac8db82c2a1ae690e09a3 //该文件由脚本自动生成,请勿手动修改 -export interface _o_project_old_20260404 { - 'artStyle'?: string | null; - 'createTime'?: number | null; - 'directorManual'?: string | null; - 'id'?: number | null; - 'imageModel'?: string | null; - 'imageQuality'?: string | null; - 'intro'?: string | null; - 'mode'?: string | null; - 'name'?: string | null; - 'projectType'?: string | null; - 'type'?: string | null; - 'userId'?: number | null; - 'videoModel'?: string | null; - 'videoRatio'?: string | null; -} -export interface _o_prompt_old_20260406 { - 'data'?: string | null; - 'id'?: number; - 'name'?: string | null; - 'type'?: string | null; - 'useData'?: string | null; -} -export interface _o_prompt_old_20260406_1 { - 'data'?: string | null; - 'id'?: number; - 'name'?: string | null; - 'TEXT'?: any | null; - 'type'?: string | null; - 'useData'?: string | null; -} export interface memories { 'content': string; 'createTime': number; @@ -264,9 +229,6 @@ export interface o_videoTrack { } export interface DB { - "_o_project_old_20260404": _o_project_old_20260404; - "_o_prompt_old_20260406": _o_prompt_old_20260406; - "_o_prompt_old_20260406_1": _o_prompt_old_20260406_1; "memories": memories; "o_agentDeploy": o_agentDeploy; "o_agentWorkData": o_agentWorkData; diff --git a/src/utils/ai.ts b/src/utils/ai.ts index e452fec..f2ca25c 100644 --- a/src/utils/ai.ts +++ b/src/utils/ai.ts @@ -105,6 +105,7 @@ class AiText { ...(input.tools && { stopWhen: stepCountIs(Object.keys(input.tools).length * 50) }), ...input, model: await this.resolveModel(), + temperature: 2, } as Parameters[0]); } async stream(input: Omit[0], "model">) { @@ -112,6 +113,9 @@ class AiText { ...(input.tools && { stopWhen: stepCountIs(Object.keys(input.tools).length * 50) }), ...input, model: await this.resolveModel(extractReasoningMiddleware({ tagName: "reasoning_content", separator: "\n" })), + topP: 1, + temperature: 2, + maxOutputTokens: 9999999999, } as Parameters[0]); } } @@ -151,7 +155,7 @@ class AiImage { const modelName = await resolveModelName(this.key); const exec = async (mn: `${string}:${string}`) => { const fn = await getVendorTemplateFn("imageRequest", mn); - await referenceList2imageBase642(mn.split(":")[0], input); + await referenceList2imageBase642(mn.split(/:(.+)/)[0], input); this.result = await fn(input); if (this.result.startsWith("http")) this.result = await urlToBase64(this.result); return this; @@ -195,7 +199,7 @@ class AiVideo { const modelName = await resolveModelName(this.key); const exec = async (mn: `${string}:${string}`) => { const fn = await getVendorTemplateFn("videoRequest", mn); - await referenceList2imageBase642(mn.split(":")[0], input); + await referenceList2imageBase642(mn.split(/:(.+)/)[0], input); this.result = await fn(input); if (this.result.startsWith("http")) this.result = await urlToBase64(this.result); return this; @@ -220,7 +224,7 @@ class AiAudio { const modelName = await resolveModelName(this.key); const exec = async (mn: `${string}:${string}`) => { const fn = await getVendorTemplateFn("ttsRequest", mn); - await referenceList2imageBase642(mn.split(":")[0], input); + await referenceList2imageBase642(mn.split(/:(.+)/)[0], input); this.result = await fn(input); if (this.result.startsWith("http")) this.result = await urlToBase64(this.result); return this;