diff --git a/apps/detail-agent-pi/src/activity-event.mjs b/apps/detail-agent-pi/src/activity-event.mjs index c9f21e20..2687ee82 100644 --- a/apps/detail-agent-pi/src/activity-event.mjs +++ b/apps/detail-agent-pi/src/activity-event.mjs @@ -19,6 +19,9 @@ const labels = Object.freeze({ list_project_images: '翻看本项目候选图', read_archived_images: '参考同款历史候选图', stage_archived_image: '挑出历史候选图待验', read_output_screen: '看看当前整屏效果', check_output_screens: '逐屏检查画布效果', video_generate_clip: '生成视频片段', video_compose_timeline: '合成视频成品', video_inspect: '检视视频画面', + video_plan_storyboard: '规划视频分镜', video_slice_clip: '裁切视频片段', + video_extract_keyframes: '提取视频关键帧', video_package_delivery: '打包视频成品', + seeding_plan_pack: '规划种草套组', seeding_package_delivery: '打包种草成品', defer_production_output: '先存好当前草稿', check_image_slots: '检查出图质量', finish_production: '整理打包最终成品', write_copy_fields: '往画布里填写文案', }); @@ -54,7 +57,7 @@ const operationCategories = Object.freeze({ reconcile_image_slots:'remote_image', adopt_production_image:'canvas_write', write_copy_fields:'canvas_write', canvas_edit:'canvas_write', finish_production:'export', production_image_retired:'remote_image', whole_detail_review:'inference', check_output_screens:'inference', - video_compose_timeline:'export', + video_compose_timeline:'export', video_package_delivery:'export', seeding_package_delivery:'export', }); export const executionCategory = action => operationCategories[action] ?? 'ui_ack'; export const activityToolLabel = name => Object.hasOwn(labels, name) ? labels[name] : '工具'; diff --git a/apps/detail-agent-pi/src/agent.mjs b/apps/detail-agent-pi/src/agent.mjs index 0f6b0704..e99bfe4c 100644 --- a/apps/detail-agent-pi/src/agent.mjs +++ b/apps/detail-agent-pi/src/agent.mjs @@ -15,7 +15,7 @@ import { DEFAULT_STREAM_IDLE_TIMEOUT_MS, iterateWithIdleTimeout, parseRetryAfter import { protectSession, redact, redactText } from './credentials.mjs'; import { productionTools, callProductionTool, closeProductionTurn, lockProjectSession, productionGoalState, runProductionGoal, unfinishedProductionTurn } from './production-goal.mjs'; import { compactReceiptJson } from './production-receipts.mjs'; -import { productionVideoTools } from './production-operations.mjs'; +import { productionSeedingTools, productionVideoTools } from './production-operations.mjs'; import { createAgentSession, DEFAULT_COMPACTION_SETTINGS, DefaultResourceLoader, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent'; import { getSupportedThinkingLevels, StringEnum } from '@earendil-works/pi-ai'; import { streamSimple as streamAnthropic } from '@earendil-works/pi-ai/api/anthropic-messages'; @@ -389,7 +389,7 @@ function toolsFor(host) { return receipt ?? {toolCallId:id,found:false,matches:await host.store.search(query,host.manager)}; }), ]; - const projectResources = [...commands, ...productionVideoTools(host, make)]; + const projectResources = [...commands, ...productionVideoTools(host, make), ...productionSeedingTools(host, make)]; const productionKit = productionTools.map(([name, description, schema])=>({ ...make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal), ['read_output_screen','read_slot_images'].includes(name)?result=>result: @@ -553,11 +553,11 @@ function toolsFor(host) { /** Coding Agent SDK owns the transcript/compaction; our host owns all I/O boundaries. */ export class DetailPiAgent { - static async open({ store, broker, brokerInfo, canvas, transport, projectEvidence, documentId, productionGoal, productionSignal, videoRuntime, callBudget, onEvent = () => {} }) { + static async open({ store, broker, brokerInfo, canvas, transport, projectEvidence, documentId, productionGoal, productionSignal, videoRuntime, seedingRuntime, callBudget, onEvent = () => {} }) { assertPiNodeVersion(process.versions.node); if (callBudget !== undefined && (!Number.isSafeInteger(callBudget) || callBudget < 1)) throw Error('单轮模型调用预算无效'); const host = new DetailPiAgent(); - Object.assign(host, { canvasOperations:new CanvasOperations(), store, broker, canvas, onEvent, productionGoal, productionSignal, videoRuntime, callBudget, turnEpoch: 0, rounds: 0, text: '' }); + Object.assign(host, { canvasOperations:new CanvasOperations(), store, broker, canvas, onEvent, productionGoal, productionSignal, videoRuntime, seedingRuntime, callBudget, turnEpoch: 0, rounds: 0, text: '' }); host.releaseLock = await lockProjectSession(store.root,error => { host.compromised = error; host.session?.agent.abort(); diff --git a/apps/detail-agent-pi/src/image-context-pruning.mjs b/apps/detail-agent-pi/src/image-context-pruning.mjs index 0f317ee9..1b5fba22 100644 --- a/apps/detail-agent-pi/src/image-context-pruning.mjs +++ b/apps/detail-agent-pi/src/image-context-pruning.mjs @@ -1,6 +1,6 @@ const PRUNABLE_IMAGE_TOOLS = new Set([ 'read_output_screen', 'read_slot_images', 'canvas_template_image', 'canvas_candidate_image', - 'video_inspect', + 'video_inspect', 'video_extract_keyframes', ]); export function pruneHistoricalToolImages(messages, { keepLatest = 1 } = {}) { diff --git a/apps/detail-agent-pi/src/media-delivery.mjs b/apps/detail-agent-pi/src/media-delivery.mjs new file mode 100644 index 00000000..5182292e --- /dev/null +++ b/apps/detail-agent-pi/src/media-delivery.mjs @@ -0,0 +1,153 @@ +import { createHash } from 'node:crypto'; +import { createReadStream } from 'node:fs'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { BridgeError } from './bridge-error.mjs'; +import { atomic } from './store.mjs'; + +const invalid = message => new BridgeError(message, 'invalid_media_delivery'); +const sourceExtensions = /\.(?:psd|psb|pcraft)$/i; +const imageExtensions = new Set(['.jpg', '.jpeg', '.png', '.webp']); + +export function assertValidDeliveryName(name) { + if (typeof name !== 'string' || !name || name.includes('/') || name.includes('\\') + || /[<>:"/\\|?*\x00-\x1f]/.test(name) || ['.', '..'].includes(name) + || name.endsWith('.') || name.endsWith(' ') || /[a-f0-9]{64}/i.test(name)) { + throw invalid(`文件名无效或包含禁用字符:${name}`); + } + if (sourceExtensions.test(name)) { + throw invalid(`成品交付包只接收成品文件,不接收源文件:${name}`); + } +} + +export function parseJpegDimensions(bytes) { + if (bytes.length < 4 || bytes.readUInt16BE(0) !== 0xffd8) throw invalid('JPG 文件头无效'); + for (let offset = 2; offset < bytes.length;) { + if (bytes[offset++] !== 0xff) throw invalid('JPG 标记无效'); + while (bytes[offset] === 0xff) offset++; + const marker = bytes[offset++]; + if (marker === 0xda || marker === 0xd9) break; + const length = bytes.readUInt16BE(offset); + if (length < 2 || offset + length > bytes.length) throw invalid('JPG 段长度无效'); + if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) { + if (length < 11) throw invalid('JPG 帧头无效'); + const height = bytes.readUInt16BE(offset + 3); + const width = bytes.readUInt16BE(offset + 5); + if (!width || !height) throw invalid('JPG 尺寸无效'); + return { width, height }; + } + offset += length; + } + throw invalid('JPG 缺少尺寸信息'); +} + +export function parseImageDimensions(bytes, ext) { + const lower = ext.toLowerCase(); + if (lower === '.jpg' || lower === '.jpeg') return parseJpegDimensions(bytes); + if (lower === '.png') { + if (bytes.length < 24 || bytes.subarray(0, 8).toString('hex') !== '89504e470d0a1a0a') { + throw invalid('PNG 文件头无效'); + } + const width = bytes.readUInt32BE(16); + const height = bytes.readUInt32BE(20); + if (!width || !height) throw invalid('PNG 尺寸无效'); + return { width, height }; + } + if (lower === '.webp') { + if (bytes.length < 30 || bytes.toString('ascii', 0, 4) !== 'RIFF' || bytes.toString('ascii', 8, 12) !== 'WEBP') { + throw invalid('WEBP 文件头无效'); + } + const chunk = bytes.toString('ascii', 12, 16); + if (chunk === 'VP8X') { + return { width: 1 + bytes.readUIntLE(24, 3), height: 1 + bytes.readUIntLE(27, 3) }; + } + if (chunk === 'VP8 ') { + if (bytes.readUInt8(23) !== 0x9d || bytes.readUInt8(24) !== 0x01 || bytes.readUInt8(25) !== 0x2a) { + throw invalid('WEBP VP8 帧头无效'); + } + return { width: bytes.readUInt16LE(26) & 0x3fff, height: bytes.readUInt16LE(28) & 0x3fff }; + } + if (chunk === 'VP8L') { + const bits = bytes.readUInt32LE(21); + return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 }; + } + throw invalid('WEBP 格式不受支持'); + } + throw invalid(`不支持的图片格式:${ext}`); +} + +export async function sha256File(file) { + const hash = createHash('sha256'); + for await (const chunk of createReadStream(file)) hash.update(chunk); + return hash.digest('hex'); +} + +export async function verifyMediaFile(filePath, { media, signal, expectedKind } = {}) { + const absolute = path.resolve(filePath); + const fileName = path.basename(absolute); + assertValidDeliveryName(fileName); + const stat = await fs.stat(absolute).catch(error => { + if (error.code === 'ENOENT') throw invalid(`交付文件不存在:${fileName}`); + throw error; + }); + if (!stat.isFile() || !stat.size) throw invalid(`交付文件为空:${fileName}`); + const ext = path.extname(fileName).toLowerCase(); + let details = {}; + if (ext === '.mp4' || expectedKind === 'video') { + if (!media?.inspect) throw invalid('当前未配置媒体检视能力,无法校验视频成片'); + const info = await media.inspect(absolute, signal); + details = { + kind: 'video', width: info.width, height: info.height, fps: info.fps, + duration: info.duration, codec: info.codec, hasAudio: info.hasAudio, + }; + } else if (imageExtensions.has(ext)) { + const bytes = await fs.readFile(absolute); + const size = parseImageDimensions(bytes, ext); + details = { kind: 'image', width: size.width, height: size.height }; + } else if (ext === '.srt') { + const content = await fs.readFile(absolute, 'utf8'); + if (!content.trim()) throw invalid(`字幕文件为空:${fileName}`); + details = { kind: 'subtitle' }; + } else { + throw invalid(`不支持的交付文件类型:${fileName}`); + } + const sha256 = await sha256File(absolute); + return { fileName, path: absolute, fileSize: stat.size, sha256, verified: true, ...details }; +} + +export async function writeMediaDeliveryManifest({ + outputDir, manifestName, kind, identifier, outputId, variantId, files, extra = {}, +}) { + const root = path.resolve(outputDir); + await fs.mkdir(root, { recursive: true }); + const manifestPath = path.join(root, manifestName); + const manifest = { + version: 1, + kind, + outputId, + ...(variantId ? { variantId } : {}), + identifier, + generatedAt: new Date().toISOString(), + files: files.map(({ path: filePath, ...rest }) => ({ + ...rest, + relativePath: path.relative(root, filePath).split(path.sep).join('/'), + })), + ...extra, + }; + await atomic(manifestPath, manifest); + const uploadContract = { + kind, + identifier, + assets: { + files: files.map(({ fileName, fileSize, sha256, specId, variantId: fileVariantId, variantName }) => ({ + fileName, + fileSize, + sha256, + ...(specId ? { specId } : {}), + ...(fileVariantId ? { variantId: fileVariantId } : {}), + ...(variantName ? { variantName } : {}), + })), + }, + }; + return { deliveryDir: root, manifestPath, manifest, uploadContract }; +} diff --git a/apps/detail-agent-pi/src/production-operations.mjs b/apps/detail-agent-pi/src/production-operations.mjs index 600298ff..4388be18 100644 --- a/apps/detail-agent-pi/src/production-operations.mjs +++ b/apps/detail-agent-pi/src/production-operations.mjs @@ -18,6 +18,7 @@ import { canvasTransformArgs, reviewProductionCandidate } from './candidate-revi import { extractPageLiveCopy, resolveLiveSlotCopy } from './copy-image-alignment.mjs'; import { executeWorkflow } from './workflow-execute.mjs'; import { createVideoToolExecutors, videoTools } from './video-tools.mjs'; +import { createSeedingToolExecutors, seedingTools } from './seeding-tools.mjs'; import { activityToolLabel, COPY_UPDATE_LIMIT, copyUpdateItem } from './activity-event.mjs'; import { createTailWatcher } from './tail-watcher.mjs'; import { summarizeImageWait } from './image-wait-summary.mjs'; @@ -46,7 +47,29 @@ export function productionVideoTools(host, make) { ...make(name, description, schema, (args, signal) => { const signals = [signal, host.productionSignal].filter(Boolean); return execute[name](args, signals.length ? AbortSignal.any(signals) : undefined); - }, name === 'video_inspect' ? result => result : undefined), + }, ['video_inspect', 'video_extract_keyframes'].includes(name) + ? result => result?.content ? result : undefined + : undefined), + label: activityToolLabel(name), + })); +} + +export function productionSeedingTools(host, make) { + const { productionGoal, videoRuntime, seedingRuntime } = host; + const outputs = productionGoal?.requestedOutputs ?? []; + const isSeeding = id => id === 'seeding_images' || id === 'seeding_video'; + if (!seedingRuntime && !isSeeding(productionGoal?.outputId) && !outputs.some(row => isSeeding(row.outputId))) return []; + const execute = createSeedingToolExecutors({ + deliveryDir: productionGoal?.deliveryDir, + ...videoRuntime, + ...seedingRuntime, + ledgerDir: path.join(host.store.root, 'seeding-plans'), + }); + return seedingTools.map(([name, description, schema]) => ({ + ...make(name, description, schema, (args, signal) => { + const signals = [signal, host.productionSignal].filter(Boolean); + return execute[name](args, signals.length ? AbortSignal.any(signals) : undefined); + }), label: activityToolLabel(name), })); } diff --git a/apps/detail-agent-pi/src/seeding-tools.mjs b/apps/detail-agent-pi/src/seeding-tools.mjs new file mode 100644 index 00000000..2c289689 --- /dev/null +++ b/apps/detail-agent-pi/src/seeding-tools.mjs @@ -0,0 +1,199 @@ +import { StringEnum, validateToolArguments } from '@earendil-works/pi-ai'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import { Type } from '@sinclair/typebox'; +import { BridgeError } from './bridge-error.mjs'; +import { normalizeToolArgs } from './tool-schema.mjs'; +import { atomic } from './store.mjs'; +import { createVideoMedia } from './video-ffmpeg.mjs'; +import { assertValidDeliveryName, verifyMediaFile, writeMediaDeliveryManifest } from './media-delivery.mjs'; + +const object = fields => Type.Object(fields); +const text = Type.String({ minLength: 1 }); +const optional = Type.Optional; +const invalid = message => new BridgeError(message, 'invalid_seeding_input'); +const roles = ['cover', 'detail', 'scene', 'comparison', 'video']; + +export const seedingTools = [ + ['seeding_plan_pack', '校验种草图文或短视频套组的主题、受众、卖点覆盖、图位顺序与文案/花色绑定,生成结构化种草策划清单。', + object({ + outputId: StringEnum(['seeding_images', 'seeding_video']), + variantId: optional(text), + theme: text, + audience: text, + tone: optional(text), + sellingPoints: Type.Array(object({ + id: text, + text: text, + required: optional(Type.Boolean()), + }), { minItems: 1 }), + items: Type.Array(object({ + itemId: text, + role: StringEnum(roles), + intent: text, + variantId: optional(text), + barcode: optional(text), + copy: optional(text), + caption: optional(text), + sourcePath: optional(text), + sellingPointIds: optional(Type.Array(text)), + }), { minItems: 1 }), + packKey: optional(text), + outputDir: optional(text), + })], + ['seeding_package_delivery', '核验种草图文或短视频成品文件并写入种草交付清单与素材库入库契约。', + object({ + outputId: StringEnum(['seeding_images', 'seeding_video']), + identifier: text, + variantId: optional(text), + theme: optional(text), + items: Type.Array(object({ + path: text, + role: optional(StringEnum(roles)), + variantId: optional(text), + variantName: optional(text), + specId: optional(text), + barcode: optional(text), + }), { minItems: 1 }), + outputDir: optional(text), + })], +]; + +const schemas = new Map(seedingTools.map(([name, , schema]) => [name, schema])); +const validate = (name, input) => { + try { + const schema = schemas.get(name); + return validateToolArguments({ name, parameters: schema }, { name, arguments: normalizeToolArgs(input, schema) }); + } catch (error) { + throw invalid(error.message); + } +}; + +async function planSeedingPack(input, { ledgerDir, deliveryDir }) { + const pointMap = new Map(); + for (const point of input.sellingPoints) { + if (pointMap.has(point.id)) throw invalid(`卖点编号重复:${point.id}`); + pointMap.set(point.id, { id: point.id, text: point.text.trim(), required: point.required === true }); + } + const seenItems = new Set(); + const covered = new Set(); + const plannedItems = []; + + for (let i = 0; i < input.items.length; i++) { + const item = input.items[i]; + if (seenItems.has(item.itemId)) throw invalid(`种草内容编号重复:${item.itemId}`); + seenItems.add(item.itemId); + if (item.barcode) assertValidDeliveryName(`${item.barcode.trim()}.jpg`); + const sellingPointIds = item.sellingPointIds ?? []; + for (const pointId of sellingPointIds) { + if (!pointMap.has(pointId)) throw invalid(`种草条目 ${item.itemId} 引用了未知卖点:${pointId}`); + covered.add(pointId); + } + plannedItems.push({ + order: i + 1, + itemId: item.itemId, + role: item.role, + intent: item.intent.trim(), + ...(item.variantId ? { variantId: item.variantId } : {}), + ...(item.barcode ? { barcode: item.barcode.trim() } : {}), + ...(item.copy?.trim() ? { copy: item.copy.trim() } : {}), + ...(item.caption?.trim() ? { caption: item.caption.trim() } : {}), + ...(item.sourcePath ? { sourcePath: item.sourcePath } : {}), + sellingPointIds, + }); + } + + if (input.outputId === 'seeding_images' && !plannedItems.some(item => item.role === 'cover')) { + throw invalid('种草图套组至少需要一张封面图(role=cover)'); + } + + const uncoveredSellingPointIds = [...pointMap.keys()].filter(id => !covered.has(id)); + const uncoveredRequiredSellingPoints = [...pointMap.values()] + .filter(point => point.required && !covered.has(point.id)) + .map(point => point.id); + if (uncoveredRequiredSellingPoints.length) { + throw invalid(`种草策划未覆盖必选卖点:${uncoveredRequiredSellingPoints.join('、')}`); + } + + const plan = { + outputId: input.outputId, + ...(input.variantId ? { variantId: input.variantId } : {}), + theme: input.theme.trim(), + audience: input.audience.trim(), + ...(input.tone ? { tone: input.tone.trim() } : {}), + itemCount: plannedItems.length, + coveredSellingPointIds: [...covered], + uncoveredSellingPointIds, + items: plannedItems, + }; + + if (input.packKey) { + const dir = input.outputDir ?? deliveryDir ?? ledgerDir; + if (!dir) throw invalid('保存种草策划需要指定输出目录'); + assertValidDeliveryName(input.packKey); + const savedPath = path.join(path.resolve(dir), `${input.packKey}.seeding-pack.json`); + await fs.mkdir(path.dirname(savedPath), { recursive: true }); + await atomic(savedPath, plan); + return { ...plan, savedPath }; + } + return plan; +} + +async function packageSeedingDelivery(input, { media, deliveryDir }, signal) { + const outputDir = input.outputDir ?? deliveryDir; + if (!outputDir) throw invalid('请指定种草交付目录'); + const verifiedFiles = []; + const seenNames = new Set(); + for (const item of input.items) { + const verified = await verifyMediaFile(item.path, { media, signal }); + if (item.barcode) { + const expected = `${item.barcode.trim()}.jpg`; + if (verified.fileName !== expected) { + throw invalid(`绑定条码的成品文件名必须为 ${expected},当前为 ${verified.fileName}`); + } + } + const key = verified.fileName.toLowerCase(); + if (seenNames.has(key)) throw invalid(`种草交付包存在重复文件名:${verified.fileName}`); + seenNames.add(key); + verifiedFiles.push({ + ...verified, + ...(item.role ? { role: item.role } : {}), + ...(item.variantId ? { variantId: item.variantId } : {}), + ...(item.variantName ? { variantName: item.variantName } : {}), + ...(item.specId ? { specId: item.specId } : {}), + }); + } + const result = await writeMediaDeliveryManifest({ + outputDir, + manifestName: '种草交付清单.json', + kind: 'buyer_show', + identifier: input.identifier.trim(), + outputId: input.outputId, + variantId: input.variantId, + files: verifiedFiles, + extra: input.theme ? { theme: input.theme.trim() } : {}, + }); + return { + kind: 'buyer_show', + outputId: input.outputId, + identifier: input.identifier.trim(), + deliveryDir: result.deliveryDir, + manifestPath: result.manifestPath, + files: verifiedFiles, + uploadContract: result.uploadContract, + }; +} + +export function createSeedingToolExecutors({ ledgerDir, deliveryDir, ...ffmpeg } = {}) { + const media = createVideoMedia(ffmpeg); + return { + async seeding_plan_pack(input) { + input = validate('seeding_plan_pack', input); + return planSeedingPack(input, { ledgerDir, deliveryDir }); + }, + async seeding_package_delivery(input, signal) { + input = validate('seeding_package_delivery', input); + return packageSeedingDelivery(input, { media, deliveryDir }, signal); + }, + }; +} diff --git a/apps/detail-agent-pi/src/video-ffmpeg.mjs b/apps/detail-agent-pi/src/video-ffmpeg.mjs index 8d0ed89e..b4b05830 100644 --- a/apps/detail-agent-pi/src/video-ffmpeg.mjs +++ b/apps/detail-agent-pi/src/video-ffmpeg.mjs @@ -80,6 +80,9 @@ export function createVideoMedia({ async render(timeline, { cwd, signal }) { await ffmpeg(buildTimelineArgs(timeline), { cwd, signal, category: 'video_compose_failed' }); }, + async slice(spec, { cwd, signal }) { + await ffmpeg(buildSliceArgs(spec), { cwd, signal, category: 'video_compose_failed' }); + }, }; } @@ -162,3 +165,12 @@ export function buildTimelineArgs(timeline) { '-t', formatTime(duration), '-r', String(fps), '-c:v', 'libx264', '-crf', String(crf), '-pix_fmt', 'yuv420p', ...(hasAudio ? ['-c:a', 'aac', '-b:a', `${audioBitrateKbps}k`] : []), '-movflags', '+faststart', 'timeline.mp4']; } + +export function buildSliceArgs({ path: file, start = 0, duration, mute = false, hasAudio = false, crf = 20, audioBitrateKbps = 192 }) { + const keepAudio = hasAudio && !mute; + return ['-v', 'error', '-xerror', '-n', '-ss', formatTime(start), '-i', path.resolve(file), + '-t', formatTime(duration), '-map', '0:V:0', ...(keepAudio ? ['-map', '0:a:0'] : ['-an']), + '-c:v', 'libx264', '-crf', String(crf), '-pix_fmt', 'yuv420p', + ...(keepAudio ? ['-c:a', 'aac', '-b:a', `${audioBitrateKbps}k`] : []), + '-movflags', '+faststart', 'slice.mp4']; +} diff --git a/apps/detail-agent-pi/src/video-tools.mjs b/apps/detail-agent-pi/src/video-tools.mjs index 9b66e0f4..ea51d64f 100644 --- a/apps/detail-agent-pi/src/video-tools.mjs +++ b/apps/detail-agent-pi/src/video-tools.mjs @@ -8,6 +8,7 @@ import { BridgeError } from './bridge-error.mjs'; import { normalizeToolArgs } from './tool-schema.mjs'; import { atomic, digest } from './store.mjs'; import { buildTimelineFilter, createVideoMedia, videoTransitions } from './video-ffmpeg.mjs'; +import { assertValidDeliveryName, parseJpegDimensions, verifyMediaFile, writeMediaDeliveryManifest } from './media-delivery.mjs'; const object = fields => Type.Object(fields); const text = Type.String({ minLength: 1 }); @@ -42,6 +43,67 @@ export const videoTools = [ })], ['video_inspect', '完整解码磁盘上的 MP4,核对实际规格和音轨,并查看指定秒数的画面。', object({ path: text, frameTimes: optional(Type.Array(seconds, { maxItems: 8 })) })], + ['video_plan_storyboard', '校验分镜结构、口播/字幕时序与商品卖点覆盖率,并生成可直接用于时间线合成的字幕与分镜清单。', + object({ + outputId: StringEnum(['main_video', 'seeding_video']), + variantId: optional(text), + title: text, + aspectRatio: optional(text), + targetDuration: optional(duration), + sellingPoints: Type.Array(object({ + id: text, + text: text, + required: optional(Type.Boolean()), + }), { minItems: 1 }), + shots: Type.Array(object({ + shotId: text, + intent: text, + sellingPointIds: optional(Type.Array(text)), + narration: optional(text), + caption: optional(text), + duration, + sourceKind: StringEnum(['clip', 'still', 'generate']), + sourcePath: optional(text), + requestKey: optional(text), + transition: optional(object({ type: StringEnum(videoTransitions), duration })), + }), { minItems: 1 }), + storyboardKey: optional(text), + outputDir: optional(text), + })], + ['video_slice_clip', '从较长源视频中按起止时间精确裁切出可复用的 MP4 子片段,并校验编码与时长。', + object({ + path: text, + start: optional(seconds), + duration, + outputDir: optional(text), + name: filename, + mute: optional(Type.Boolean()), + crf: optional(Type.Integer({ minimum: 0, maximum: 51 })), + audioBitrateKbps: optional(Type.Integer({ minimum: 1 })), + sellingPointId: optional(text), + variantId: optional(text), + })], + ['video_extract_keyframes', '从视频提取关键帧保存为 JPG 文件,可用于生图首尾帧、封面或卖点素材复用。', + object({ + path: text, + frameTimes: optional(Type.Array(seconds, { minItems: 1, maxItems: 12 })), + count: optional(Type.Integer({ minimum: 1, maximum: 12 })), + outputDir: optional(text), + prefix: optional(filename), + sellingPointIds: optional(Type.Array(text)), + includeImages: optional(Type.Boolean()), + })], + ['video_package_delivery', '核验视频成片、封面与字幕文件并写入视频交付清单与上传契约。', + object({ + outputId: StringEnum(['main_video', 'seeding_video']), + identifier: text, + variantId: optional(text), + videoPath: text, + coverPath: optional(text), + subtitlePath: optional(text), + extraPaths: optional(Type.Array(text)), + outputDir: optional(text), + })], ]; const schemas = new Map(videoTools.map(([name, , schema]) => [name, schema])); @@ -209,6 +271,244 @@ async function composeTimeline(input, { media, deliveryDir }, signal) { } } +async function planStoryboard(input, { ledgerDir, deliveryDir }) { + const pointMap = new Map(); + for (const point of input.sellingPoints) { + if (pointMap.has(point.id)) throw invalid(`卖点编号重复:${point.id}`); + pointMap.set(point.id, { id: point.id, text: point.text.trim(), required: point.required === true }); + } + const seenShots = new Set(); + const covered = new Set(); + const timelineShots = []; + const captions = []; + let cursor = 0; + let totalNarrationChars = 0; + + for (let i = 0; i < input.shots.length; i++) { + const shot = input.shots[i]; + if (seenShots.has(shot.shotId)) throw invalid(`分镜编号重复:${shot.shotId}`); + seenShots.add(shot.shotId); + if (shot.duration <= 0) throw invalid(`分镜 ${shot.shotId} 时长必须大于 0`); + if (i === 0 && shot.transition) throw invalid('首个分镜没有可衔接的前一镜头'); + const overlap = shot.transition?.duration ?? 0; + if (shot.transition) { + const prev = input.shots[i - 1]; + const prevOverlap = prev.transition?.duration ?? 0; + if (overlap <= 0 || overlap >= prev.duration || overlap >= shot.duration || overlap + prevOverlap > prev.duration) { + throw invalid(`分镜 ${shot.shotId} 的转场时长超出相邻镜头范围`); + } + } + const sellingPointIds = shot.sellingPointIds ?? []; + for (const pointId of sellingPointIds) { + if (!pointMap.has(pointId)) throw invalid(`分镜 ${shot.shotId} 引用了未知卖点:${pointId}`); + covered.add(pointId); + } + const start = Number((cursor - overlap).toFixed(6)); + const end = Number((start + shot.duration).toFixed(6)); + cursor = end; + const spoken = shot.narration?.trim() ?? ''; + const subtitle = shot.caption?.trim() || spoken; + totalNarrationChars += spoken.length; + if (subtitle) captions.push({ start, end, text: subtitle }); + timelineShots.push({ + order: i + 1, + shotId: shot.shotId, + intent: shot.intent.trim(), + sourceKind: shot.sourceKind, + ...(shot.sourcePath ? { sourcePath: shot.sourcePath } : {}), + ...(shot.requestKey ? { requestKey: shot.requestKey } : {}), + start, + end, + duration: shot.duration, + sellingPointIds, + ...(spoken ? { narration: spoken } : {}), + ...(subtitle ? { caption: subtitle } : {}), + ...(shot.transition ? { transition: shot.transition } : {}), + }); + } + + const totalDuration = Number(cursor.toFixed(6)); + const uncoveredSellingPointIds = [...pointMap.keys()].filter(id => !covered.has(id)); + const uncoveredRequiredSellingPoints = [...pointMap.values()] + .filter(point => point.required && !covered.has(point.id)) + .map(point => point.id); + if (uncoveredRequiredSellingPoints.length) { + throw invalid(`分镜未覆盖必选卖点:${uncoveredRequiredSellingPoints.join('、')}`); + } + + const plan = { + outputId: input.outputId, + ...(input.variantId ? { variantId: input.variantId } : {}), + title: input.title.trim(), + ...(input.aspectRatio ? { aspectRatio: input.aspectRatio } : {}), + ...(input.targetDuration !== undefined ? { + targetDuration: input.targetDuration, + durationDelta: Number((totalDuration - input.targetDuration).toFixed(6)), + } : {}), + totalDuration, + shotCount: timelineShots.length, + coveredSellingPointIds: [...covered], + uncoveredSellingPointIds, + narrationStats: { + totalChars: totalNarrationChars, + charsPerSecond: totalDuration > 0 ? Number((totalNarrationChars / totalDuration).toFixed(2)) : 0, + }, + shots: timelineShots, + captions, + }; + + if (input.storyboardKey) { + const dir = input.outputDir ?? deliveryDir ?? ledgerDir; + if (!dir) throw invalid('保存分镜清单需要指定输出目录'); + assertValidDeliveryName(input.storyboardKey); + const savedPath = path.join(path.resolve(dir), `${input.storyboardKey}.storyboard.json`); + await fs.mkdir(path.dirname(savedPath), { recursive: true }); + await atomic(savedPath, plan); + return { ...plan, savedPath }; + } + return plan; +} + +async function sliceClip(input, { media, deliveryDir }, signal) { + const start = input.start ?? 0; + if (input.duration <= 0) throw invalid('切片时长必须大于 0'); + const outputDir = input.outputDir ?? deliveryDir; + if (!outputDir) throw invalid('请指定成品目录'); + assertValidDeliveryName(input.name); + const info = await media.probe(input.path, signal); + const stream = info.streams.find(row => row.codec_type === 'video' && !row.disposition?.attached_pic); + const available = Number(stream?.duration ?? info.format?.duration); + if (!stream || !Number.isFinite(available) || start + input.duration > available + 0.000001) { + throw invalid('切片范围超出源视频时长'); + } + const hasAudio = info.streams.some(row => row.codec_type === 'audio'); + const root = path.resolve(outputDir); + await fs.mkdir(root, { recursive: true }); + const stage = await fs.mkdtemp(path.join(root, '.slice-')); + const target = path.join(root, `${input.name}.mp4`); + try { + await media.slice({ + path: input.path, start, duration: input.duration, mute: input.mute === true, + hasAudio, crf: input.crf, audioBitrateKbps: input.audioBitrateKbps, + }, { cwd: stage, signal }); + const staged = path.join(stage, 'slice.mp4'); + const inspected = await media.inspect(staged, signal); + if (inspected.codec !== 'h264' || Math.abs(inspected.duration - input.duration) > 1 / inspected.fps + 0.05) { + throw new BridgeError('切片编码或时长与要求不一致', 'video_compose_failed'); + } + await fs.copyFile(staged, target, constants.COPYFILE_EXCL); + return { + clipId: input.name, + ...inspected, + path: target, + bytes: (await fs.stat(target)).size, + ...(input.sellingPointId ? { sellingPointId: input.sellingPointId } : {}), + ...(input.variantId ? { variantId: input.variantId } : {}), + }; + } catch (error) { + if (error.code === 'EEXIST') throw new BridgeError('切片文件名已存在,请使用新的文件名', 'video_output_exists'); + throw error; + } finally { + await fs.rm(stage, { recursive: true, force: true }); + } +} + +async function extractKeyframes(input, { media, deliveryDir }, signal) { + const outputDir = input.outputDir ?? deliveryDir; + if (!outputDir) throw invalid('请指定关键帧输出目录'); + const prefix = input.prefix ?? 'keyframe'; + assertValidDeliveryName(prefix); + const info = await media.inspect(input.path, signal); + let times; + if (input.frameTimes?.length) { + times = [...new Set(input.frameTimes)].sort((a, b) => a - b); + } else { + const count = input.count ?? 1; + times = count === 1 + ? [0] + : Array.from({ length: count }, (_, idx) => Number(((idx * info.duration * 0.9) / (count - 1)).toFixed(3))); + } + if (times.some(time => time < 0 || time >= info.duration)) throw invalid('抽帧时间超出视频范围'); + if (input.sellingPointIds && input.sellingPointIds.length !== times.length) { + throw invalid('卖点绑定列表长度必须与关键帧数量一致'); + } + + const root = path.resolve(outputDir); + await fs.mkdir(root, { recursive: true }); + const written = []; + const frames = []; + const images = []; + try { + for (let i = 0; i < times.length; i++) { + signal?.throwIfAborted(); + const time = times[i]; + const jpeg = await media.frame(info.path, time, signal); + const size = jpeg.length > 4 ? parseJpegDimensions(jpeg) : { width: info.width, height: info.height }; + const target = path.join(root, `${prefix}-${String(i + 1).padStart(2, '0')}.jpg`); + await fs.writeFile(target, jpeg, { flag: 'wx' }); + written.push(target); + const sellingPointId = input.sellingPointIds?.[i]; + frames.push({ + index: i + 1, + time, + path: target, + bytes: jpeg.length, + width: size.width, + height: size.height, + ...(sellingPointId ? { sellingPointId } : {}), + }); + if (input.includeImages) { + images.push({ type: 'image', mimeType: 'image/jpeg', data: jpeg.toString('base64') }); + } + } + const details = { videoPath: info.path, duration: info.duration, frames }; + return input.includeImages + ? { content: [{ type: 'text', text: JSON.stringify(details) }, ...images], details } + : details; + } catch (error) { + await Promise.all(written.map(file => fs.unlink(file).catch(() => {}))); + if (error.code === 'EEXIST') throw new BridgeError('关键帧文件已存在,请更换前缀或目录', 'video_output_exists'); + throw error; + } +} + +async function packageVideoDelivery(input, { media, deliveryDir }, signal) { + const outputDir = input.outputDir ?? deliveryDir; + if (!outputDir) throw invalid('请指定视频交付目录'); + const candidates = [ + await verifyMediaFile(input.videoPath, { media, signal, expectedKind: 'video' }), + ...(input.coverPath ? [await verifyMediaFile(input.coverPath, { media, signal, expectedKind: 'image' })] : []), + ...(input.subtitlePath ? [await verifyMediaFile(input.subtitlePath, { media, signal, expectedKind: 'subtitle' })] : []), + ...(await Promise.all((input.extraPaths ?? []).map(file => verifyMediaFile(file, { media, signal })))), + ]; + const seen = new Set(); + for (const file of candidates) { + const key = file.fileName.toLowerCase(); + if (seen.has(key)) throw invalid(`交付包存在重复文件名:${file.fileName}`); + seen.add(key); + } + const kind = input.outputId === 'seeding_video' ? 'buyer_show' : 'video'; + const result = await writeMediaDeliveryManifest({ + outputDir, + manifestName: '视频交付清单.json', + kind, + identifier: input.identifier.trim(), + outputId: input.outputId, + variantId: input.variantId, + files: candidates, + }); + return { + kind, + outputId: input.outputId, + identifier: input.identifier.trim(), + deliveryDir: result.deliveryDir, + manifestPath: result.manifestPath, + video: candidates[0], + files: candidates, + uploadContract: result.uploadContract, + }; +} + export function createVideoToolExecutors({ generator, ledgerDir, deliveryDir, ...ffmpeg } = {}) { const media = createVideoMedia(ffmpeg); return { @@ -234,5 +534,21 @@ export function createVideoToolExecutors({ generator, ledgerDir, deliveryDir, .. const details = { ...info, frameTimes }; return { content: [{ type: 'text', text: JSON.stringify(details) }, ...images], details }; }, + async video_plan_storyboard(input) { + input = validate('video_plan_storyboard', input); + return planStoryboard(input, { ledgerDir, deliveryDir }); + }, + async video_slice_clip(input, signal) { + input = validate('video_slice_clip', input); + return sliceClip(input, { media, deliveryDir }, signal); + }, + async video_extract_keyframes(input, signal) { + input = validate('video_extract_keyframes', input); + return extractKeyframes(input, { media, deliveryDir }, signal); + }, + async video_package_delivery(input, signal) { + input = validate('video_package_delivery', input); + return packageVideoDelivery(input, { media, deliveryDir }, signal); + }, }; } diff --git a/apps/detail-agent-pi/test/video-seeding-phase3.test.mjs b/apps/detail-agent-pi/test/video-seeding-phase3.test.mjs new file mode 100644 index 00000000..b49fa880 --- /dev/null +++ b/apps/detail-agent-pi/test/video-seeding-phase3.test.mjs @@ -0,0 +1,322 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs/promises'; +import path from 'node:path'; +import os from 'node:os'; +import { randomUUID } from 'node:crypto'; +import { buildSliceArgs } from '../src/video-ffmpeg.mjs'; +import { createVideoToolExecutors, videoTools } from '../src/video-tools.mjs'; +import { createSeedingToolExecutors, seedingTools } from '../src/seeding-tools.mjs'; +import { pruneHistoricalToolImages } from '../src/image-context-pruning.mjs'; +import { activitySummary, executionCategory } from '../src/activity-event.mjs'; +import { productionSeedingTools, productionVideoTools } from '../src/production-operations.mjs'; +import { openAgent } from './fake-canvas.mjs'; +import { ProjectStore } from '../src/store.mjs'; +import { cleanup } from './cleanup.mjs'; + +function makeMinimalJpeg(width = 720, height = 1280) { + return Buffer.from([ + 0xff, 0xd8, + 0xff, 0xc0, 0x00, 0x11, 0x08, + (height >> 8) & 0xff, height & 0xff, + (width >> 8) & 0xff, width & 0xff, + 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, + 0xff, 0xd9, + ]); +} + +function makeMinimalPng(width = 800, height = 1000) { + const buf = Buffer.alloc(24); + Buffer.from('89504e470d0a1a0a', 'hex').copy(buf, 0); + buf.writeUInt32BE(13, 8); + buf.write('IHDR', 12, 'ascii'); + buf.writeUInt32BE(width, 16); + buf.writeUInt32BE(height, 20); + return buf; +} + +async function fixture(t) { + const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-phase3-')); + t.after(() => cleanup(root)); + const script = path.join(root, 'mock-media.mjs'); + const log = path.join(root, 'commands.jsonl'); + const source = path.join(root, 'raw-product-video.mp4'); + const ledgerDir = path.join(root, 'ledger'); + const deliveryDir = path.join(root, 'delivery'); + await fs.writeFile(source, 'mock source video bytes'); + await fs.writeFile(script, String.raw` +import fs from 'node:fs'; +const [log, command, ...args] = process.argv.slice(2); +fs.appendFileSync(log, JSON.stringify({ command, args }) + '\n'); +if (command === 'probe') { + const file = args.at(-1); + const isSlice = file.endsWith('slice.mp4'); + const video = { index: 0, codec_type: 'video', codec_name: 'h264', width: 720, height: 1280, + avg_frame_rate: '30/1', duration: isSlice ? '2.5' : '6' }; + const audio = { index: 1, codec_type: 'audio', codec_name: 'aac', channels: 2, sample_rate: '48000' }; + fs.statSync(file); + console.log(JSON.stringify({ format: { format_name: 'mov,mp4,m4a' }, streams: [video, audio] })); +} else if (args.includes('image2pipe')) { + process.stdout.write(Buffer.from([ + 0xff, 0xd8, 0xff, 0xc0, 0x00, 0x11, 0x08, 0x05, 0x00, 0x02, 0xd0, + 0x03, 0x01, 0x11, 0x00, 0x02, 0x11, 0x01, 0x03, 0x11, 0x01, 0xff, 0xd9, + ])); +} else if (args.includes('slice.mp4')) { + fs.writeFileSync(args.at(-1), 'sliced mock mp4'); +} else if (args.includes('volumedetect')) { + console.error('mean_volume: -18.5 dB\nmax_volume: -2.0 dB'); +} +`); + const config = { + ffmpegPath: process.execPath, ffmpegPrefix: [script, log, 'ffmpeg'], + ffprobePath: process.execPath, ffprobePrefix: [script, log, 'probe'], + ledgerDir, deliveryDir, + }; + return { + root, source, config, ledgerDir, deliveryDir, + video: createVideoToolExecutors(config), + seeding: createSeedingToolExecutors(config), + async commands() { return (await fs.readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line)); }, + }; +} + +test('video_plan_storyboard 校验分镜、转场重叠、卖点覆盖并生成定时字幕', async t => { + const f = await fixture(t); + const plan = await f.video.video_plan_storyboard({ + outputId: 'main_video', + variantId: 'walnut-120', + title: '实木书桌主图视频', + aspectRatio: '3:4', + targetDuration: 6.5, + sellingPoints: [ + { id: 'sp-wood', text: 'FAS 级北美黑胡桃木', required: true }, + { id: 'sp-frame', text: '加厚碳钢桌腿承重稳固', required: true }, + { id: 'sp-cable', text: '隐藏式理线槽', required: false }, + ], + shots: [ + { + shotId: 'shot-1', intent: '整体亮相', sellingPointIds: ['sp-wood'], + narration: '精选北美黑胡桃木桌面', duration: 2.5, sourceKind: 'still', + }, + { + shotId: 'shot-2', intent: '桌腿承重特写', sellingPointIds: ['sp-frame'], + caption: '加厚碳钢桌腿稳固不晃', duration: 3, sourceKind: 'clip', + transition: { type: 'fade', duration: 0.5 }, + }, + { + shotId: 'shot-3', intent: '收尾展示', duration: 1.5, sourceKind: 'generate', + requestKey: 'tail-shot', + }, + ], + storyboardKey: 'main-video-plan', + }); + + assert.equal(plan.totalDuration, 6.5); + assert.equal(plan.durationDelta, 0); + assert.deepEqual(plan.coveredSellingPointIds, ['sp-wood', 'sp-frame']); + assert.deepEqual(plan.uncoveredSellingPointIds, ['sp-cable']); + assert.equal(plan.shots[1].start, 2); + assert.equal(plan.shots[1].end, 5); + assert.deepEqual(plan.captions, [ + { start: 0, end: 2.5, text: '精选北美黑胡桃木桌面' }, + { start: 2, end: 5, text: '加厚碳钢桌腿稳固不晃' }, + ]); + assert.ok(plan.savedPath.endsWith('main-video-plan.storyboard.json')); + assert.equal(JSON.parse(await fs.readFile(plan.savedPath, 'utf8')).shotCount, 3); + + await assert.rejects(f.video.video_plan_storyboard({ + outputId: 'main_video', + title: '缺少必选卖点', + sellingPoints: [{ id: 'sp-req', text: '必选卖点', required: true }], + shots: [{ shotId: 's1', intent: '开场', duration: 2, sourceKind: 'still' }], + }), { category: 'invalid_video_input' }); + + await assert.rejects(f.video.video_plan_storyboard({ + outputId: 'main_video', + title: '首镜转场非法', + sellingPoints: [{ id: 'sp-1', text: '卖点' }], + shots: [{ shotId: 's1', intent: '开场', sellingPointIds: ['sp-1'], duration: 2, sourceKind: 'still', transition: { type: 'fade', duration: 0.5 } }], + }), { category: 'invalid_video_input' }); +}); + +test('video_slice_clip 与 buildSliceArgs 精确切片并校验成片,不覆盖已有文件', async t => { + const f = await fixture(t); + const mutedArgs = buildSliceArgs({ path: f.source, start: 1.5, duration: 2.5, mute: true, hasAudio: true }); + assert.ok(mutedArgs.includes('-an')); + assert.ok(!mutedArgs.includes('aac')); + assert.equal(mutedArgs[mutedArgs.indexOf('-ss') + 1], '1.5'); + assert.equal(mutedArgs[mutedArgs.indexOf('-t') + 1], '2.5'); + + const receipt = await f.video.video_slice_clip({ + path: f.source, start: 1, duration: 2.5, name: '卖点切片-01', sellingPointId: 'sp-wood', variantId: 'walnut', + }); + assert.equal(receipt.clipId, '卖点切片-01'); + assert.equal(receipt.duration, 2.5); + assert.equal(receipt.width, 720); + assert.equal(receipt.height, 1280); + assert.equal(receipt.sellingPointId, 'sp-wood'); + assert.equal(receipt.variantId, 'walnut'); + assert.ok(receipt.path.endsWith('卖点切片-01.mp4')); + + await assert.rejects(f.video.video_slice_clip({ + path: f.source, start: 1, duration: 2.5, name: '卖点切片-01', + }), { category: 'video_output_exists' }); + + await assert.rejects(f.video.video_slice_clip({ + path: f.source, start: 4, duration: 3, name: '越界切片', + }), { category: 'invalid_video_input' }); +}); + +test('video_extract_keyframes 落盘关键帧并支持视觉上下文释放', async t => { + const f = await fixture(t); + const result = await f.video.video_extract_keyframes({ + path: f.source, + count: 2, + prefix: 'frame-cut', + sellingPointIds: ['sp-wood', 'sp-frame'], + includeImages: true, + }); + assert.equal(result.details.frames.length, 2); + assert.deepEqual(result.details.frames.map(row => row.sellingPointId), ['sp-wood', 'sp-frame']); + assert.equal(result.details.frames[0].width, 720); + assert.equal(result.details.frames[0].height, 1280); + assert.ok(result.details.frames[0].path.endsWith('frame-cut-01.jpg')); + assert.equal(result.content.filter(block => block.type === 'image').length, 2); + + const latest = await f.video.video_extract_keyframes({ path: f.source, frameTimes: [1], prefix: 'second', includeImages: true }); + const pruned = pruneHistoricalToolImages([ + { role: 'toolResult', toolName: 'video_extract_keyframes', ...result }, + { role: 'toolResult', toolName: 'video_extract_keyframes', ...latest }, + ]); + assert.ok(pruned[0].content.every(block => block.type === 'text')); + assert.equal(pruned[1].content.filter(block => block.type === 'image').length, 1); + + await assert.rejects(f.video.video_extract_keyframes({ + path: f.source, frameTimes: [0], prefix: 'frame-cut', + }), { category: 'video_output_exists' }); +}); + +test('video_package_delivery 核验成片、封面、字幕并输出视频/种草入库契约', async t => { + const f = await fixture(t); + await fs.mkdir(f.deliveryDir, { recursive: true }); + const cover = path.join(f.deliveryDir, '主图视频封面.jpg'); + const subtitle = path.join(f.deliveryDir, '主图视频字幕.srt'); + await fs.writeFile(cover, makeMinimalJpeg(720, 1280)); + await fs.writeFile(subtitle, '1\n00:00:00,000 --> 00:00:02,000\n北美黑胡桃木\n'); + + const receipt = await f.video.video_package_delivery({ + outputId: 'main_video', + identifier: 'SPU-DESK-01', + variantId: 'walnut', + videoPath: f.source, + coverPath: cover, + subtitlePath: subtitle, + }); + assert.equal(receipt.kind, 'video'); + assert.equal(receipt.files.length, 3); + assert.equal(receipt.uploadContract.kind, 'video'); + assert.equal(receipt.uploadContract.identifier, 'SPU-DESK-01'); + assert.equal(receipt.uploadContract.assets.files.length, 3); + assert.match(receipt.uploadContract.assets.files[0].sha256, /^[a-f0-9]{64}$/); + assert.equal(JSON.parse(await fs.readFile(receipt.manifestPath, 'utf8')).kind, 'video'); + + const seedingVideoReceipt = await f.video.video_package_delivery({ + outputId: 'seeding_video', + identifier: 'SPU-DESK-01', + videoPath: f.source, + }); + assert.equal(seedingVideoReceipt.kind, 'buyer_show'); + + const psd = path.join(f.deliveryDir, 'source.psd'); + await fs.writeFile(psd, 'mock psd'); + await assert.rejects(f.video.video_package_delivery({ + outputId: 'main_video', identifier: 'SPU-DESK-01', videoPath: f.source, extraPaths: [psd], + }), { category: 'invalid_media_delivery' }); +}); + +test('seeding_plan_pack 与 seeding_package_delivery 支持种草策划、条码规范与买家秀入库契约', async t => { + const f = await fixture(t); + const plan = await f.seeding.seeding_plan_pack({ + outputId: 'seeding_images', + theme: '居家办公原木桌面改造', + audience: '注重质感与收纳的家居设计师', + tone: '真实松弛、自然光实拍感', + sellingPoints: [ + { id: 'sp-grain', text: '自然木纹肌理', required: true }, + { id: 'sp-size', text: '1.4米宽敞台面', required: false }, + ], + items: [ + { itemId: 'seed-1', role: 'cover', intent: '首图场景种草', barcode: '6901234567890', sellingPointIds: ['sp-grain'], copy: '换了这张黑胡桃木书桌后每天都想坐着办公' }, + { itemId: 'seed-2', role: 'detail', intent: '木纹近景', sellingPointIds: ['sp-size'] }, + ], + packKey: 'xhs-pack-01', + }); + assert.equal(plan.itemCount, 2); + assert.deepEqual(plan.coveredSellingPointIds, ['sp-grain', 'sp-size']); + assert.ok(plan.savedPath.endsWith('xhs-pack-01.seeding-pack.json')); + + await fs.mkdir(f.deliveryDir, { recursive: true }); + const coverJpg = path.join(f.deliveryDir, '6901234567890.jpg'); + const detailPng = path.join(f.deliveryDir, '细节实拍图.png'); + await fs.writeFile(coverJpg, makeMinimalJpeg(1080, 1440)); + await fs.writeFile(detailPng, makeMinimalPng(1080, 1440)); + + const delivered = await f.seeding.seeding_package_delivery({ + outputId: 'seeding_images', + identifier: 'SPU-DESK-01', + theme: '居家办公原木桌面改造', + items: [ + { path: coverJpg, role: 'cover', barcode: '6901234567890', variantId: 'walnut', variantName: '胡桃色' }, + { path: detailPng, role: 'detail', variantId: 'walnut' }, + ], + }); + assert.equal(delivered.kind, 'buyer_show'); + assert.equal(delivered.files.length, 2); + assert.deepEqual(delivered.files.map(file => [file.width, file.height]), [[1080, 1440], [1080, 1440]]); + assert.equal(delivered.uploadContract.kind, 'buyer_show'); + assert.equal(delivered.uploadContract.assets.files[0].fileName, '6901234567890.jpg'); + assert.equal(JSON.parse(await fs.readFile(delivered.manifestPath, 'utf8')).theme, '居家办公原木桌面改造'); + + await assert.rejects(f.seeding.seeding_package_delivery({ + outputId: 'seeding_images', + identifier: 'SPU-DESK-01', + items: [{ path: detailPng, barcode: '6901234567890' }], + }), { category: 'invalid_seeding_input' }); +}); + +test('种草与视频 Phase 3 工具按需激活、零污染图文主线且符合白标要求', async t => { + const f = await fixture(t); + const allTools = [...videoTools, ...seedingTools]; + for (const [name, description] of allTools) { + assert.ok(!/Pi|PhotoCraft/.test(description), name); + assert.match(activitySummary({ type: 'tool_execution_start', toolName: name }), /^开始:/); + } + assert.equal(executionCategory('video_package_delivery'), 'export'); + assert.equal(executionCategory('seeding_package_delivery'), 'export'); + + const identity = { scope: 'a'.repeat(64), project: randomUUID() }; + const store = await ProjectStore.open(f.root, identity, { + brandId: 'qa', shopId: 'qa', categoryId: 'qa', platform: 'qa', version: '1', source: 'test', rules: [], + }); + const transport = { info: { accountScope: identity.scope, model: { id: 'qa-model', protocol: 'openai-chat' }, pending: [] } }; + const variantId = 'qa'; + const canvas = { detailImages() {} }; + const goal = outputIds => ({ variantId, workspaceId: 'qa', requestedOutputs: outputIds.map(outputId => ({ outputId, variantId })) }); + const active = async options => { + const host = await openAgent({ store, transport, canvas, ...options }); + try { return host.session.getActiveToolNames(); } + finally { await host.dispose(); } + }; + + const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) }); + for (const [name] of allTools) assert.ok(!plane.includes(name), `planar goal should not include ${name}`); + + const seedingOnly = await active({ productionGoal: goal(['seeding_images']) }); + assert.deepEqual(productionVideoTools({ productionGoal: goal(['seeding_images']) }, name => name), []); + assert.equal(productionSeedingTools({ productionGoal: goal(['detail']) }, name => name).length, 0); + for (const [name] of seedingTools) assert.ok(seedingOnly.includes(name)); + for (const [name] of videoTools) assert.ok(!seedingOnly.includes(name)); + + const explicitSeeding = await active({ seedingRuntime: { deliveryDir: f.deliveryDir } }); + for (const [name] of seedingTools) assert.ok(explicitSeeding.includes(name)); +}); diff --git a/apps/detail-agent-pi/test/video-tools.test.mjs b/apps/detail-agent-pi/test/video-tools.test.mjs index 1bffd0ae..a0d2b14b 100644 --- a/apps/detail-agent-pi/test/video-tools.test.mjs +++ b/apps/detail-agent-pi/test/video-tools.test.mjs @@ -14,7 +14,10 @@ import { openAgent } from './fake-canvas.mjs'; import { ProjectStore } from '../src/store.mjs'; import { cleanup } from './cleanup.mjs'; -const names = ['video_generate_clip', 'video_compose_timeline', 'video_inspect']; +const names = [ + 'video_generate_clip', 'video_compose_timeline', 'video_inspect', + 'video_plan_storyboard', 'video_slice_clip', 'video_extract_keyframes', 'video_package_delivery', +]; async function fixture(t) { const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-video-')); @@ -220,7 +223,7 @@ test('种草视频预检遵循发布绑定,三项工具活动使用白标标 }), { schemaVersion: 1, status: 'ready', issues: [] }); assert.deepEqual(videoTools.map(([name]) => name), names); assert.deepEqual(names.map(toolName => activitySummary({ type: 'tool_execution_start', toolName })), - ['开始:生成视频片段', '开始:合成视频成品', '开始:检视视频画面']); + ['开始:生成视频片段', '开始:合成视频成品', '开始:检视视频画面', '开始:规划视频分镜', '开始:裁切视频片段', '开始:提取视频关键帧', '开始:打包视频成品']); assert.ok(videoTools.every(([, description]) => !/Pi|PhotoCraft/.test(description))); }); @@ -244,14 +247,16 @@ test('真实会话按视频输出或显式运行时注册,平面工具清单 } finally { await host.dispose(); } } + const seedingNames = ['seeding_plan_pack', 'seeding_package_delivery']; const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) }); assert.ok(plane.includes('plan_production')); - assert.deepEqual(plane.filter(name => names.includes(name)), []); + assert.deepEqual(plane.filter(name => names.includes(name) || seedingNames.includes(name)), []); assert.deepEqual(productionVideoTools({ productionGoal: goal(['seeding_images']) }, name => name), []); for (const outputId of ['main_video', 'seeding_video']) { const video = await active({ productionGoal: goal([outputId]) }); - assert.deepEqual(video.filter(name => !names.includes(name)), plane); - assert.deepEqual(video.filter(name => names.includes(name)), names); + const expectedExtra = outputId === 'seeding_video' ? [...names, ...seedingNames] : names; + assert.deepEqual(video.filter(name => !expectedExtra.includes(name)), plane); + assert.deepEqual(video.filter(name => expectedExtra.includes(name)), expectedExtra); } const defaultChat = await active({}); const explicit = await active({ videoRuntime: { generator: { generate() { throw Error('无需提交'); } } } });