[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75HPRNGCDJK430RP3K7J10N":3,"skill-same:01M75HPRNGCDJK430RP3K7J10N":98},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":14,"categories":15,"keywords":16,"publishedAt":17,"linkOnly":18,"markdownContent":19,"markdownBody":19,"frontMatter":20,"refName":21,"commitSha":22,"skillDirectory":23,"forksCount":12,"repositoryHtmlUrl":24,"repositoryHomepageUrl":24,"ownerHtmlUrl":25,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":26,"install":27,"resources":40},"01M75HPRNGCDJK430RP3K7J10N","seedance-story-engine",null,"geniusdapeng-collab\u002FStormaxeAIVideoSystem","geniusdapeng-collab","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F291670474?v=4","01M75HNC8B4WWDRP8E1HSJ3K0K","01M75HNC9FJYXT3E93SM6KRHRZ",0,"MIT","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"#!\u002Fusr\u002Fbin\u002Fenv node\n\u002F**\n * Seedance Render Engine v1.0-Core\n * 从 Director v4.2-Core Phase4 拆分独立的渲染引擎\n * \n * 职责：将分镜片段批量提交到 Seedance API，处理 Multi-Shot \u002F 单镜头策略，轮询下载，精确切分\n *\u002F\n\nconst fs = require('fs');\nconst path = require('path');\nconst { execAsync, shellQuote } = require('..\u002F..\u002Fseedance-director\u002Fscripts\u002Fexec-utils');\n\n\u002F\u002F ============ 配置（v5.1-Core: 接入配置中心） ============\nlet CONFIG, MODEL_PRIORITY, FALLBACK_ERRORS, MAX_CONCURRENT_DEFAULT, \n    RETRY_DELAY_MS, QUOTA_RETRY_DELAYS, BATCH_COOLDOWN_MS, \n    OUTPUT_ROOT, PROMPT_MAX_LENGTH, DEGRADATION_STEPS;\n\nfunction initConfig() {\n  const { CONFIG: cfg } = require('..\u002F..\u002Fseedance-director\u002Fscripts\u002Fconfig-center');\n  CONFIG = cfg;\n  \n  MODEL_PRIORITY = cfg.render.modelPriority.map((m, i) => ({ ...m, priority: i }));\n  FALLBACK_ERRORS = ['400', '429', '500', '503', '模型不可用', 'service_tier', \n                     'insufficient_quota', 'rate_limit', 'model_not_found'];\n  MAX_CONCURRENT_DEFAULT = cfg.render.maxConcurrent;\n  RETRY_DELAY_MS = 5000;\n  QUOTA_RETRY_DELAYS = cfg.render.retryDelays;\n  BATCH_COOLDOWN_MS = cfg.render.batchCooldown;\n  OUTPUT_ROOT = process.env.DIRECTOR_OUTPUT_ROOT || path.join(require('os').homedir(), '.openclaw\u002Fworkspace\u002Fproductions');\n  PROMPT_MAX_LENGTH = cfg.render.promptMaxLength;\n  DEGRADATION_STEPS = cfg.render.degradationSteps;\n}\n\n\u002F\u002F 启动时初始化配置\ninitConfig();\n\n\u002F\u002F 查找 seedance-wrapper\nconst WORKSPACE = path.join(require('os').homedir(), '.openclaw\u002Fworkspace');\nconst SEEDANCE_WRAPPER = path.join(WORKSPACE, 'skills\u002Fbyted-ark-seedance-skill\u002Fscripts\u002Fseedance-wrapper.js');\n\nfunction ensureDir(dir) {\n  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });\n}\n\nfunction sleep(ms) {\n  return new Promise(r => setTimeout(r, ms));\n}\n\nfunction log(tag, msg, level = 'info') {\n  const ts = new Date().toISOString().slice(0, 19).replace('T', ' ');\n  console.log(`[${ts}] [${tag}] ${msg}`);\n}\n\n\u002F\u002F 🔴 v5.1-Core: Prompt token估算（中文字符≈1token，英文≈1.5token）\nfunction estimatePromptTokens(prompt) {\n  if (!prompt) return 0;\n  let tokens = 0;\n  for (const char of prompt) {\n    const code = char.charCodeAt(0);\n    \u002F\u002F CJK字符（中文\u002F日文\u002F韩文）≈1 token\n    if (code >= 0x4e00 && code \u003C= 0x9fff) tokens += 1;\n    \u002F\u002F ASCII字符\n    else if (code \u003C 128) tokens += 0.5;\n    \u002F\u002F 其他Unicode字符\n    else tokens += 1;\n  }\n  \u002F\u002F 英文单词额外计数（空格分隔的平均长度≈5字符≈1.5token）\n  const englishWords = prompt.match(\u002F[a-zA-Z]+\u002Fg) || [];\n  tokens += englishWords.length * 0.3; \u002F\u002F 已计数字符，额外单词开销\n  \n  return Math.ceil(tokens);\n}\n\n\u002F\u002F 🔴 v5.1-Core: Prompt长度安全检查\nfunction validatePromptLength(prompt, maxLength = PROMPT_MAX_LENGTH) {\n  const tokens = estimatePromptTokens(prompt);\n  const length = prompt?.length || 0;\n  \n  if (length > maxLength) {\n    log('RenderEngine', `⚠️ Prompt超长(${length}\u002F${maxLength}字符, ~${tokens}tokens)，将截断`, 'warn');\n    return { \n      valid: false, \n      prompt: prompt.substring(0, maxLength - 3) + '...', \n      originalLength: length,\n      tokens \n    };\n  }\n  \n  if (tokens > maxLength * 1.5) {\n    log('RenderEngine', `⚠️ Prompt token估算偏高(~${tokens})，建议精简`, 'warn');\n  }\n  \n  return { valid: true, prompt, length, tokens };\n}\n\n\u002F\u002F 🔴 v5.1-Core: 429降级策略 — 降低motionStrength + 缩短prompt\nfunction applyDegradation(prompt, modelConfig, retryIndex) {\n  const step = DEGRADATION_STEPS[Math.min(retryIndex, DEGRADATION_STEPS.length - 1)];\n  if (!step) return { prompt, modelConfig };\n  \n  let degradedPrompt = prompt;\n  let degradedModel = { ...modelConfig };\n  \n  \u002F\u002F 缩短prompt\n  if (step.promptTrim > 0 && degradedPrompt.length > step.promptTrim + 10) {\n    degradedPrompt = degradedPrompt.substring(0, degradedPrompt.length - step.promptTrim) + '...';\n    log('RenderEngine', `🔧 降级: prompt缩短${step.promptTrim}字符(${prompt.length}→${degradedPrompt.length})`, 'warn');\n  }\n  \n  \u002F\u002F 降低motionStrength\n  if (step.motionStrength !== undefined) {\n    degradedModel = { ...degradedModel, motionStrength: step.motionStrength };\n    log('RenderEngine', `🔧 降级: motionStrength→${step.motionStrength}`, 'warn');\n  }\n  \n  \u002F\u002F 降低cfgScale\n  if (step.cfgScale !== undefined) {\n    degradedModel = { ...degradedModel, cfgScale: step.cfgScale };\n    log('RenderEngine', `🔧 降级: cfgScale→${step.cfgScale}`, 'warn');\n  }\n  \n  return { prompt: degradedPrompt, modelConfig: degradedModel };\n}\n\n\u002F\u002F ============ 渲染片段合并算法 v4.1-Core ============\nfunction createRenderSegments(shots, plan) {\n  const segments = [];\n  let currentSegment = { shots: [], totalDuration: 0, id: '' };\n\n  for (let i = 0; i \u003C shots.length; i++) {\n    const shot = shots[i];\n    const shotDuration = shot.duration || 5;\n    const isDialogueShot = shot.type?.includes('对白') || shot.description?.includes('对白');\n    const isLongShot = shotDuration > 15;\n    const actChange = currentSegment.shots.length > 0 &&\n                       currentSegment.shots[currentSegment.shots.length - 1].act !== shot.act;\n    const segmentFull = currentSegment.totalDuration + shotDuration > 15 ||\n                        currentSegment.shots.length >= 6;\n\n    if (currentSegment.shots.length > 0 && (segmentFull || actChange || isDialogueShot || isLongShot)) {\n      if (currentSegment.totalDuration \u003C 4 && !isLongShot && !isDialogueShot) {\n        \u002F\u002F 继续合并\n      } else {\n        currentSegment.id = `SEG${String(segments.length + 1).padStart(2, '0')}`;\n        segments.push(currentSegment);\n        currentSegment = { shots: [], totalDuration: 0, id: '' };\n      }\n    }\n\n    if (isLongShot || isDialogueShot) {\n      if (currentSegment.shots.length > 0) {\n        currentSegment.id = `SEG${String(segments.length + 1).padStart(2, '0')}`;\n        segments.push(currentSegment);\n        currentSegment = { shots: [], totalDuration: 0, id: '' };\n      }\n      currentSegment.shots.push(shot);\n      currentSegment.totalDuration = shotDuration;\n      currentSegment.id = `SEG${String(segments.length + 1).padStart(2, '0')}`;\n      segments.push(currentSegment);\n      currentSegment = { shots: [], totalDuration: 0, id: '' };\n    } else {\n      currentSegment.shots.push(shot);\n      currentSegment.totalDuration += shotDuration;\n    }\n  }\n\n  if (currentSegment.shots.length > 0) {\n    currentSegment.id = `SEG${String(segments.length + 1).padStart(2, '0')}`;\n    segments.push(currentSegment);\n  }\n\n  for (let i = 0; i \u003C segments.length; i++) {\n    if (segments[i].totalDuration \u003C 4 && segments[i].shots.length \u003C 6) {\n      if (i + 1 \u003C segments.length &&\n          segments[i].shots[0].act === segments[i + 1].shots[0].act &&\n          segments[i].totalDuration + segments[i + 1].totalDuration \u003C= 15) {\n        segments[i].shots.push(...segments[i + 1].shots);\n        segments[i].totalDuration += segments[i + 1].totalDuration;\n        segments.splice(i + 1, 1);\n        i--;\n      }\n    }\n  }\n\n  for (const segment of segments) {\n    segment.isMultiShot = shouldUseMultiShot(segment.shots);\n  }\n\n  log('RenderEngine', `🎬 渲染片段合并: ${shots.length}个镜头 → ${segments.length}个片段`, 'success');\n  for (const seg of segments) {\n    const shotIds = seg.shots.map(s => s.id).join('+');\n    const mode = seg.isMultiShot ? '🎬[Multi-Shot]' : '📷[单镜头]';\n    log('RenderEngine', `   ${seg.id}: ${seg.totalDuration}秒 ${mode} (${shotIds})`, 'info');\n  }\n\n  return segments;\n}\n\nfunction shouldUseMultiShot(shots) {\n  if (shots.length \u003C= 1) return false;\n  const hasDialogue = shots.some(s => s.type?.includes('对白') || s.description?.includes('对白'));\n  const hasSceneChange = shots.some((s, i) => i > 0 && s.act !== shots[i - 1].act);\n  const hasComplexMultiChar = shots.some(s => (s.characters || []).length > 3);\n  const hasVeryLongShot = shots.some(s => (s.duration || 5) > 12);\n  return !hasDialogue && !hasSceneChange && !hasComplexMultiChar && !hasVeryLongShot;\n}\n\n\u002F\u002F 生成多镜头片段提示词\nfunction generateSegmentPrompt(segment, plan, refsMap, promptEnhancements) {\n  const styleManifesto = plan?.styleManifesto || '写实风格';\n  const lighting = plan?.lightingThreeLayer || '自然光';\n  const styleNote = styleManifesto.length > 20 ? styleManifesto.split('，')[0] || styleManifesto.substring(0, 30) : styleManifesto;\n  const lightingShort = lighting.split('，')[0] || lighting;\n  \n  let prompt = '';\n  let currentTime = 0;\n  \n  for (let i = 0; i \u003C segment.shots.length; i++) {\n    const shot = segment.shots[i];\n    const start = currentTime;\n    const end = currentTime + (shot.duration || 5);\n    const shotPrompt = generateShotPrompt(shot, plan, (refsMap || {})[shot.id] || [], (promptEnhancements || {})[shot.id] || '');\n    if (i > 0) prompt += '；镜头切换：';\n    prompt += `${start}-${end}s：${shotPrompt}`;\n    currentTime = end;\n  }\n  \n  prompt += `，${styleNote}，${lightingShort}光影，电影级运镜`;\n  if (prompt.length > 380) prompt = prompt.replace(\u002F；镜头切换：\u002Fg, '；');\n  return prompt;\n}\n\nfunction generateShotPrompt(shot, plan, refs, dialogueEnhancement) {\n  const styleManifesto = plan?.styleManifesto || '写实风格';\n  const videoType = plan?.videoType || 'action';\n  const styleNote = styleManifesto.length > 20 ? styleManifesto.split('，')[0] || styleManifesto.substring(0, 30) : styleManifesto;\n  \n  \u002F\u002F 🔴 v5.1-Core: 角色视觉签名注入\n  let characterVisualNote = '';\n  const shotChars = shot.characters || [];\n  if (shotChars.length > 0 && plan?.characters) {\n    const charDescriptions = [];\n    for (const charName of shotChars) {\n      const charData = plan.characters.find(c => c.name === charName);\n      if (charData) {\n        const parts = [];\n        if (charData.species) parts.push(charData.species);\n        if (charData.features && charData.features.length > 0) parts.push(charData.features.join('，'));\n        if (charData.signature) parts.push(charData.signature);\n        if (parts.length > 0) {\n          charDescriptions.push(`${charName}(${parts.join('，')})`);\n        }\n      }\n    }\n    if (charDescriptions.length > 0) {\n      characterVisualNote = `角色形象：${charDescriptions.join('；')}。`;\n    }\n  }\n  \n  let subjectDesc = shot.description || '';\n  \u002F\u002F 🔴 v5.3-Core-fix: 彻底删除有缺陷的外貌过滤逻辑\n  \u002F\u002F    原逻辑把\"手持\"\"身穿\"等战斗描述整句误删，导致 prompt 只剩\"参考图+风格\"\n  \u002F\u002F    参考图只作为角色一致性辅助，绝不替代文字描述\n  if (subjectDesc.length > 100) subjectDesc = subjectDesc.substring(0, 100) + '...';\n  \n  const cameraDesc = shot.camera || '';\n  const shotSize = cameraDesc.match(\u002F(特写|近景|中景|全景|远景|大全景)\u002F)?.[0] || '';\n  const cameraMove = cameraDesc.match(\u002F(推|拉|摇|移|跟|升|降|环绕|航拍|手持|固定)\u002F)?.[0] || '';\n  const lensNote = [shotSize, cameraMove].filter(Boolean).join('，');\n  \n  const lighting = plan?.lightingThreeLayer || '自然光';\n  const lightingShort = lighting.split('，')[0] || lighting;\n  \n  let refNote = '';\n  if ((refs || []).length > 0) refNote = `参考${refs.length}张角色图片，`;\n  \n  let dialogueNote = '';\n  if (dialogueEnhancement) {\n    const clean = dialogueEnhancement.startsWith('，') ? dialogueEnhancement.slice(1) : dialogueEnhancement;\n    dialogueNote = clean.length > 50 ? clean.substring(0, 50) + '...' : clean;\n  }\n  \n  const parts = [\n    characterVisualNote,\n    refNote, subjectDesc, lensNote ? `(${lensNote})` : '',\n    dialogueNote ? `对白：\"${dialogueNote}\"` : '',\n    `${styleNote}，${lightingShort}光影`\n  ].filter(Boolean);\n  \n  let prompt = parts.join('，').replace(\u002F，{2,}\u002Fg, '，');\n  if (prompt.length > 400) prompt = prompt.substring(0, 400) + '...';\n  \n  \u002F\u002F 🔴 v5.1-Core: Token安全验证\n  const validation = validatePromptLength(prompt);\n  return validation.prompt;\n}\n\n\u002F\u002F 🔴 v5.1-Core: 自动发现角色定妆照（Seedream生成）\nfunction discoverCharacterRefs(productionDir, segment) {\n  const charDir = path.join(productionDir, '03-characters');\n  if (!fs.existsSync(charDir)) return [];\n  \n  const refs = [];\n  const files = fs.readdirSync(charDir);\n  \n  for (const shot of segment.shots) {\n    const shotChars = shot.characters || [];\n    for (const charName of shotChars) {\n      \u002F\u002F 查找匹配角色名的图片文件（支持：角色名-全身.png、角色名-特写.png等）\n      const matched = files.filter(f => {\n        const base = path.basename(f, path.extname(f));\n        return base.includes(charName) && \u002F\\.(png|jpg|jpeg|webp)$\u002Fi.test(f);\n      });\n      for (const m of matched) {\n        const fullPath = path.join(charDir, m);\n        if (!refs.includes(fullPath)) refs.push(fullPath);\n      }\n    }\n  }\n  \n  return refs;\n}\n\n\u002F\u002F ============ 主渲染函数 ============\nasync function render(segmentsData, options = {}) {\n  const {\n    productionDir,\n    skipRender = false,\n    seed = Math.floor(Math.random() * 2147483647),\n    maxConcurrent = MAX_CONCURRENT_DEFAULT,\n    generateAudio = true  \u002F\u002F 🔴 v5.3-Core-fix: 默认开启音频生成（原hasDialogueFn=null导致无声）\n  } = options;\n  \n  const rawDir = path.join(productionDir, '05-raw-shots');\n  ensureDir(rawDir);\n  \n  log('RenderEngine', `🎬 开始批量渲染: ${segmentsData.length}个片段...`, 'phase');\n  log('RenderEngine', `🎲 统一风格种子: ${seed}`, 'info');\n  \n  if (!fs.existsSync(SEEDANCE_WRAPPER)) {\n    throw new Error(`seedance-wrapper.js 未找到: ${SEEDANCE_WRAPPER}`);\n  }\n  \n  if (skipRender) {\n    log('RenderEngine', '⚠️ 跳过渲染模式，只生成命令', 'warn');\n  }\n  \n  const tasks = [];\n  for (let i = 0; i \u003C segmentsData.length; i += maxConcurrent) {\n    const batch = segmentsData.slice(i, i + maxConcurrent);\n    log('RenderEngine', `批次 ${Math.floor(i\u002FmaxConcurrent)+1}\u002F${Math.ceil(segmentsData.length\u002FmaxConcurrent)}`, 'progress');\n    \n    const batchPromises = batch.map(async ({ segment, prompt, refs }) => {\n      let lastError = null;\n      \n      for (let modelIdx = 0; modelIdx \u003C MODEL_PRIORITY.length; modelIdx++) {\n        const modelConfig = MODEL_PRIORITY[modelIdx];\n        const is2Point0 = modelConfig.id.includes('doubao-seedance-2-0');\n        const cmdParts = [\n          'node', SEEDANCE_WRAPPER, 'create',\n          '--prompt', `\"${(prompt || '').replace(\u002F\"\u002Fg, '\\\\\"')}\"`,\n          '--model', `\"${modelConfig.id}\"`,\n          '--seed', String(seed),\n          '--ratio', '\"16:9\"'\n        ];\n        if (!is2Point0) cmdParts.push('--service-tier', '\"flex\"');\n        cmdParts.push('--duration', String(segment.totalDuration || 5));\n        \n        const hasCameraMove = segment.shots.some(s => \u002F(推|拉|摇|移|跟|升|降|环绕|航拍|变焦|甩镜)\u002F.test(s.camera || ''));\n        if (hasCameraMove) cmdParts.push('--camera-fixed', '\"false\"');\n        \n        \u002F\u002F 🔴 v5.3-Core-fix: 默认开启音频生成\n        if (generateAudio) {\n          cmdParts.push('--generate-audio');\n        }\n        \n        const uniqueRefs = [...new Set(refs || [])];\n        \n        \u002F\u002F 🔴 v5.1-Core: 自动注入角色定妆照\n        const charRefs = discoverCharacterRefs(productionDir, segment);\n        for (const charRef of charRefs) {\n          if (!uniqueRefs.includes(charRef)) uniqueRefs.push(charRef);\n        }\n        if (charRefs.length > 0) {\n          log('RenderEngine', `🎭 ${segment.id} 注入${charRefs.length}张角色定妆照`, 'info');\n        }\n        \n        for (const ref of uniqueRefs) cmdParts.push('--image-file', `\"${ref}\"`);\n        \n        const cmd = cmdParts.join(' ');\n        \n        if (skipRender) {\n          const cmdFile = path.join(rawDir, `${segment.id}-command.sh`);\n          fs.writeFileSync(cmdFile, `#!\u002Fbin\u002Fbash\\n${cmd}\\n`);\n          log('RenderEngine', `📝 ${segment.id} 命令已保存`, 'info');\n          return { segment, taskId: `DRY-RUN-${segment.id}`, status: 'dry-run', prompt, cmd };\n        }\n        \n        try {\n          \u002F\u002F 🔴 v5.1-Core: 应用降级策略（如果这不是第一次尝试）\n          let currentPrompt = prompt;\n          let currentModel = modelConfig;\n          \n          \u002F\u002F 检查是否有之前的429重试记录\n          const retryCount = segment._429RetryCount || 0;\n          if (retryCount > 0) {\n            const degraded = applyDegradation(currentPrompt, currentModel, retryCount - 1);\n            currentPrompt = degraded.prompt;\n            currentModel = degraded.modelConfig;\n          }\n          \n          log('RenderEngine', `⏳ ${segment.id} 尝试 ${currentModel.name}...`, 'progress');\n          const output = await execAsync(cmd, { encoding: 'utf8', timeout: 30000 });\n          const match = output.match(\u002F任务 ID:\\s*(cgt-[a-z0-9-]+)\u002Fi);\n          const taskId = match ? match[1] : null;\n          \n          if (taskId) {\n            log('RenderEngine', `✅ ${segment.id} 已提交 (${taskId})`, 'success');\n            return { segment, taskId, status: 'submitted', prompt: currentPrompt, model: currentModel.name };\n          }\n          throw new Error('未能提取任务ID');\n        } catch (e) {\n          lastError = e;\n          const errorMsg = e.message || '';\n          \n          \u002F\u002F 🔴 v5.1-Core: 429配额超限 → 指数退避 + 降级重试\n          if (errorMsg.includes('429') || errorMsg.includes('QuotaExceeded') || errorMsg.includes('TooManyRequests')) {\n            const retryDelay = QUOTA_RETRY_DELAYS[Math.min(modelIdx, QUOTA_RETRY_DELAYS.length - 1)];\n            const retryCount = segment._429RetryCount || 0;\n            \n            if (retryCount \u003C DEGRADATION_STEPS.length) {\n              segment._429RetryCount = retryCount + 1;\n              log('RenderEngine', `⚠️ ${segment.id} 429配额超限(第${retryCount+1}次)，${retryDelay\u002F1000}s后降级重试...`, 'warn');\n              await sleep(retryDelay);\n              \u002F\u002F 不切换模型，应用降级后重试\n              modelIdx--; \u002F\u002F 抵消for循环的++\n              continue;\n            } else {\n              log('RenderEngine', `❌ ${segment.id} 429重试耗尽(${retryCount}次)，切换模型...`, 'error');\n            }\n          }\n          \n          const matchedError = FALLBACK_ERRORS.find(errCode => errorMsg.includes(errCode));\n          if (matchedError && modelIdx \u003C MODEL_PRIORITY.length - 1) {\n            log('RenderEngine', `⚠️ ${segment.id} ${modelConfig.name} 不可用，降级...`, 'warn');\n            await sleep(RETRY_DELAY_MS);\n            continue;\n          }\n          break;\n        }\n      }\n      \n      log('RenderEngine', `❌ ${segment.id} 提交失败: ${lastError?.message}`, 'error');\n      return { segment, taskId: null, status: 'failed', error: lastError?.message, prompt };\n    });\n    \n    const batchResults = await Promise.all(batchPromises);\n    tasks.push(...batchResults);\n    if (i + maxConcurrent \u003C segmentsData.length) await sleep(BATCH_COOLDOWN_MS);\n  }\n  \n  \u002F\u002F 轮询下载\n  log('RenderEngine', '开始轮询...', 'progress');\n  let completed = 0, failed = 0;\n  let pending = tasks.filter(t => t.status === 'submitted');\n  \n  while (pending.length > 0) {\n    log('RenderEngine', `轮询: 完成${completed} 失败${failed} 待处理${pending.length}`, 'progress');\n    \n    const checkPromises = pending.map(async (task) => {\n      try {\n        const output = await execAsync(`node ${SEEDANCE_WRAPPER} get --task-id ${task.taskId}`, { encoding: 'utf8', timeout: 10000 });\n        \n        if (output.includes('状态: 成功') || output.includes('✅')) {\n          const urlMatch = output.match(\u002Fhttps:\\\u002F\\\u002F[^\\s]+\\.mp4[^\\s]*\u002F);\n          const videoUrl = urlMatch ? urlMatch[0] : null;\n          \n          if (videoUrl) {\n            const segmentFile = path.join(rawDir, `${task.segment.id}.mp4`);\n            try {\n              await execAsync(`curl -L -o ${shellQuote(segmentFile)} ${shellQuote(videoUrl)}`, { timeout: 60000 });\n              let cutResults;\n              \n              \u002F\u002F 🛡️ v5.1-Core: 统一精确切分，无论MultiShot与否\n              cutResults = await cutSegmentToShots(segmentFile, task.segment, rawDir);\n              \n              return { ...task, status: 'completed', videoUrl, localPath: segmentFile, cutResults };\n            } catch (e) {\n              return { ...task, status: 'failed', error: `下载或切分失败: ${e.message}` };\n            }\n          }\n          return { ...task, status: 'completed', videoUrl };\n        } else if (output.includes('失败') || output.includes('❌')) {\n          return { ...task, status: 'failed', error: '渲染失败' };\n        }\n        return task;\n      } catch (e) { return task; }\n    });\n    \n    const results = await Promise.all(checkPromises);\n    completed = results.filter(r => r.status === 'completed').length;\n    failed = results.filter(r => r.status === 'failed').length;\n    pending = results.filter(r => r.status === 'submitted');\n    if (pending.length > 0) await sleep(30000);\n  }\n  \n  log('RenderEngine', `✅ 渲染完成: ${completed}成功, ${failed}失败`, 'success');\n  \n  const report = tasks.map(t => ({\n    segmentId: t.segment.id,\n    shotIds: t.segment.shots.map(s => s.id),\n    status: t.status,\n    videoUrl: t.videoUrl,\n    localPath: t.localPath,\n    cutResults: t.cutResults || [],\n    error: t.error\n  }));\n  \n  fs.writeFileSync(path.join(rawDir, 'render-report.json'), JSON.stringify(report, null, 2));\n  return report;\n}\n\n\u002F\u002F 精确切分\nasync function cutSegmentToShots(segmentFile, segment, rawDir) {\n  const results = [];\n  let currentTime = 0;\n  \n  for (let i = 0; i \u003C segment.shots.length; i++) {\n    const shot = segment.shots[i];\n    const shotDuration = shot.duration || 5;\n    const startSec = currentTime;\n    const shotFile = path.join(rawDir, `${shot.id}.mp4`);\n    \n    try {\n      \u002F\u002F 🛡️ v5.1-Core: 精确切分 — -ss after -i + re-encode，避免copy模式的关键帧漂移\n      const cmd = `ffmpeg -y -i ${shellQuote(segmentFile)} -ss ${startSec} -t ${shotDuration} -vf \"scale=1280:720\" -c:v libx264 -preset fast -crf 23 -pix_fmt yuv420p -r 24 -c:a aac -b:a 192k ${shellQuote(shotFile)} 2>> \u002Ftmp\u002Fffmpeg-cut.log`;\n      \u002F\u002F 🔴 v5.3-Core-fix: 原-an丢弃音频轨道，改为保留音频（-c:a aac -b:a 192k）\n      await execAsync(cmd, { timeout: 60000 });\n      \n      if (fs.existsSync(shotFile)) {\n        const stats = fs.statSync(shotFile);\n        log('RenderEngine', `✂️ ${shot.id} 切分完成`, 'success');\n        results.push({ shotId: shot.id, segmentId: segment.id, start: startSec, duration: shotDuration, file: shotFile, size: stats.size });\n      } else {\n        throw new Error('切分后文件不存在');\n      }\n    } catch (e) {\n      log('RenderEngine', `❌ ${shot.id} 切分失败: ${e.message}`, 'error');\n      results.push({ shotId: shot.id, segmentId: segment.id, error: e.message });\n    }\n    \n    currentTime += shotDuration;\n  }\n  \n  return results;\n}\n\n\u002F\u002F ============ CLI ============\nfunction parseArgs() {\n  const args = {};\n  for (let i = 3; i \u003C process.argv.length; i++) {\n    const rawKey = process.argv[i];\n    if (!rawKey.startsWith('--')) continue;\n    const key = rawKey.replace(\u002F^--\u002F, '').replace(\u002F-([a-z])\u002Fg, (_, letter) => letter.toUpperCase());\n    const value = process.argv[i + 1];\n    if (value !== undefined && !value.startsWith('--')) {\n      args[key] = value;\n      i++;\n    } else {\n      args[key] = true;\n    }\n  }\n  return args;\n}\n\nasync function main() {\n  const command = process.argv[2];\n  const args = parseArgs();\n  \n  switch (command) {\n    case 'render': {\n      if (!args.productionDir && !args.segmentsJson) {\n        console.error('❌ 需要 --production-dir 或 --segments-json');\n        process.exit(1);\n      }\n      \n      let segmentsData;\n      if (args.segmentsJson) {\n        const data = JSON.parse(fs.readFileSync(args.segmentsJson, 'utf8'));\n        segmentsData = (data.segments || data).map(s => {\n          const actualSegment = s.segment || s;\n          return {\n            segment: actualSegment,\n            prompt: s.prompt || actualSegment.prompt || '',\n            refs: s.refs || actualSegment.refs || []\n          };\n        });\n      } else {\n        \u002F\u002F 从生产目录读取\n        const promptsDir = path.join(args.productionDir, '04-prompts');\n        const segmentsFile = path.join(args.productionDir, '04-segments.json');\n        if (fs.existsSync(segmentsFile)) {\n          const data = JSON.parse(fs.readFileSync(segmentsFile, 'utf8'));\n          segmentsData = (data.segments || data).map(s => {\n          const actualSegment = s.segment || s;\n          return {\n            segment: actualSegment,\n            prompt: s.prompt || actualSegment.prompt || '',\n            refs: s.refs || actualSegment.refs || []\n          };\n        });\n        } else {\n          console.error('❌ 未找到片段定义文件');\n          process.exit(1);\n        }\n      }\n      \n      const report = await render(segmentsData, {\n        productionDir: args.productionDir || path.dirname(args.segmentsJson),\n        skipRender: args.skipRender === true || args.skipRender === 'true',\n        seed: parseInt(args.seed) || undefined,\n        maxConcurrent: parseInt(args.maxConcurrent) || MAX_CONCURRENT_DEFAULT\n      });\n      \n      console.log(`\\n✅ 渲染完成: ${report.filter(t => t.status === 'completed').length}\u002F${report.length}`);\n      break;\n    }\n    \n    case 'help':\n    default:\n      console.log(`\nSeedance Render Engine v1.0-Core\n\n用法:\n  node seedance-render-engine.js render --production-dir \u003Cdir> [options]\n  node seedance-render-engine.js render --segments-json \u003Cfile> [options]\n\n选项:\n  --production-dir   生产目录（读取 04-prompts\u002F，输出到 05-raw-shots\u002F）\n  --segments-json    片段定义 JSON 文件\n  --skip-render      跳过真实渲染（dry-run）\n  --seed             统一风格种子\n  --max-concurrent   最大并发数（默认1）\n`);\n  }\n}\n\nmain().catch(e => {\n  console.error(`\\n❌ 错误: ${e.message}`);\n  process.exit(1);\n});\n",{},"main","10f0163286ae2d330c2f4d85ebc068c2e214db4d","skills\u002Fseedance-story-engine","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab","2026-07-16 08:17:06",{"source":7,"skillName":5,"commands":28,"prompt":38,"zipAvailable":39},[29,32,35],{"tool":30,"command":31},"npx","npx skills add geniusdapeng-collab\u002FStormaxeAIVideoSystem --skill seedance-story-engine",{"tool":33,"command":34},"bunx","bunx skills add geniusdapeng-collab\u002FStormaxeAIVideoSystem --skill seedance-story-engine",{"tool":36,"command":37},"pnpm","pnpm dlx skills add geniusdapeng-collab\u002FStormaxeAIVideoSystem --skill seedance-story-engine","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002FSKILL.md",true,[41,47,51,55,59,63,67,71,75,78,82,86,90,94],{"path":42,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":45,"sourceHtmlUrl":46},"scripts\u002Fenhancers\u002Fhook-factory.js","SCRIPT","脚本",3803,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fenhancers\u002Fhook-factory.js",{"path":48,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":49,"sourceHtmlUrl":50},"scripts\u002Fenhancers\u002Fspectacle-designer.js",3983,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fenhancers\u002Fspectacle-designer.js",{"path":52,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":53,"sourceHtmlUrl":54},"scripts\u002Fnarrative-bridge.js",4050,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fnarrative-bridge.js",{"path":56,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":57,"sourceHtmlUrl":58},"scripts\u002Fstory-engine.js",47133,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-engine.js",{"path":60,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":61,"sourceHtmlUrl":62},"scripts\u002Fstory-plan-1778821724021.json",12100,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778821724021.json",{"path":64,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":65,"sourceHtmlUrl":66},"scripts\u002Fstory-plan-1778821784018.json",11386,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778821784018.json",{"path":68,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":69,"sourceHtmlUrl":70},"scripts\u002Fstory-plan-1778822032586.json",12208,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778822032586.json",{"path":72,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":73,"sourceHtmlUrl":74},"scripts\u002Fstory-plan-1778822063618.json",12169,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778822063618.json",{"path":76,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":73,"sourceHtmlUrl":77},"scripts\u002Fstory-plan-1778822079891.json","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778822079891.json",{"path":79,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":80,"sourceHtmlUrl":81},"scripts\u002Fstory-plan-1778844405980.json",18460,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778844405980.json",{"path":83,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":84,"sourceHtmlUrl":85},"scripts\u002Fstory-plan-1778845087615.json",18631,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778845087615.json",{"path":87,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":88,"sourceHtmlUrl":89},"scripts\u002Fstory-plan-1778845315186.json",18643,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778845315186.json",{"path":91,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":92,"sourceHtmlUrl":93},"scripts\u002Fstory-plan-1778845441359.json",18923,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778845441359.json",{"path":95,"resourceType":43,"resourceTypeDesc":44,"sizeBytes":96,"sourceHtmlUrl":97},"scripts\u002Fstory-plan-1778845518998.json",19214,"https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fseedance-story-engine\u002Fscripts\u002Fstory-plan-1778845518998.json",[99,105,111,117,124,131],{"skillNo":100,"name":101,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":17},"01M75HRKGPGEA2Q3PSH1NKBGB6","storyforge-pro","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fstoryforge-pro\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":17},"01M75HRHCY96SC1FTZ0D0F64P1","shanhaijing-voice-craft","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fshanhaijing-voice-craft\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":114,"categories":115,"keywords":116,"publishedAt":17},"01M75HRESW1P83ZD8ZPKHYV064","shanhaijing-storyforge-pro","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fshanhaijing-storyforge-pro\u002FSKILL.md",[],[],{"skillNo":118,"name":119,"nameZh":6,"description":120,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":121,"categories":122,"keywords":123,"publishedAt":17},"01M75HRBVW40M32Y6CTGS61HP6","seedance-sound-design","Seedance视频声音设计专家。为每个视频镜头规划专业级4层音轨（环境音+音效+音乐+对白），实现音画同步。当用户需要\"加声音\"\"配音乐\"\"音效设计\"\"音画同步\"\"声音设计\"\"配乐\"时激活。与seedance-director配合，让每个镜头都有专业声音。","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fshanhaijing-sound-design\u002FSKILL.md",[],[],{"skillNo":125,"name":126,"nameZh":6,"description":127,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":128,"categories":129,"keywords":130,"publishedAt":17},"01M75HR474KEGBRC8WBNS39JGM","seedance-shot-design","Professional-grade virtual film director and prompt engineer for Seedance 2.0 (即梦). Transforms vague ideas into cinematic, production-ready video prompts with Hollywood-caliber shot design. Covers every workflow — text-to-video, image-to-video, multi-modal references, video extension, character swap, dialogue-driven short films, and music-synced edits. Ships with a cinematography dictionary (50+ safe camera-move phrases), a director style library (Villeneuve, Wes Anderson, Shinkai, Wuxia & more), a 3-layer lighting & quality-anchor system that kills the \"plastic AI look,\" and a built-in structured validation checklist so every prompt passes before delivery. Supports bilingual output (Chinese\u002FEnglish) with smart >15 s auto-segmentation for long-form storytelling. Trigger words: Seedance, Shot Design, AI video, storyboard, video prompt, short film, cinematic prompt, 即梦, 视频提示词, 分镜, 视频脚本, AI视频, 短片脚本, 镜头设计, 运镜.","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fshanhaijing-shot-design\u002FSKILL.md",[],[],{"skillNo":132,"name":133,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":6,"repositoryNo":11,"starsCount":12,"licenseSpdxId":13,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":17},"01M75HR2K9VWZTPDF19EA98WE6","shanhaijing-render-engine","https:\u002F\u002Fgithub.com\u002Fgeniusdapeng-collab\u002FStormaxeAIVideoSystem\u002Fblob\u002Fmain\u002Fskills\u002Fshanhaijing-render-engine\u002FSKILL.md",[],[]]