接入小壹视频原子工具与种草视频预检
This commit is contained in:
parent
8a6ec37526
commit
cf630e2c15
@ -17,6 +17,7 @@ const labels = Object.freeze({
|
||||
await_image_slots: '等待子代理回执', adopt_production_image: '回填候选图片', reconcile_image_slots: '核查图片原请求',
|
||||
read_archived_images: '查找同款历史候选', stage_archived_image: '加入待验历史候选',
|
||||
read_output_screen: '查看实际画布', record_screen_check: '记录本屏复核', check_page_copy: '发起文案复核',
|
||||
video_generate_clip: '生成视频片段', video_compose_timeline: '合成视频成品', video_inspect: '检视视频画面',
|
||||
defer_production_output: '保留当前草稿', check_image_slots: '发起验图', finish_production: '提交成品导出',
|
||||
save_product_strategy: '保存商品策划', review_product_strategy: '核对卖点证据',
|
||||
plan_page_copy: '规划整页卖点', write_copy_fields: '填写画布文案', review_page_copy: '复核整页文案',
|
||||
@ -37,8 +38,10 @@ 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',
|
||||
video_compose_timeline:'export',
|
||||
});
|
||||
export const executionCategory = action => operationCategories[action] ?? 'ui_ack';
|
||||
export const activityToolLabel = name => Object.hasOwn(labels, name) ? labels[name] : '工具';
|
||||
|
||||
const inferencePhases = Object.freeze({
|
||||
provider_prepared:['prepare','prepared'], serialized_request:['serialize','prepared'],
|
||||
@ -92,7 +95,7 @@ function details(event) {
|
||||
const pending = typeof event.result?.details?.pendingOriginal === 'string';
|
||||
const status = event.type === 'tool_execution_start' ? 'started' : stopped ? 'stopped' :
|
||||
event.isError ? 'failed' : pending ? 'pending' : 'completed';
|
||||
const label = labels[toolName] || '工具';
|
||||
const label = activityToolLabel(toolName);
|
||||
const summary = `${{ started: '开始', stopped: '已停止', failed: '失败', pending: '待核查', completed: '完成' }[status]}:${label}`;
|
||||
return { toolName, status, summary };
|
||||
}
|
||||
|
||||
@ -14,6 +14,7 @@ import { BridgeError, stoppedCanvas } from './bridge-error.mjs';
|
||||
import { protectSession, redactText } from './credentials.mjs';
|
||||
import { productionTools, callProductionTool, closeProductionTurn, runPiProductionGoal,
|
||||
mayContinueProductionGoal, piGoalState } from './production-goal.mjs';
|
||||
import { productionVideoTools } from './production-operations.mjs';
|
||||
import { Agent, runToolCall } from '@earendil-works/pi-agent-core';
|
||||
import { createAgentSession, formatSkillsForPrompt, ModelRuntime, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
||||
import { retryAssistantCall } from '@earendil-works/pi-ai';
|
||||
@ -131,7 +132,7 @@ function toolsFor(host) {
|
||||
return receipt ?? {toolCallId:id,found:false,matches:await host.store.search(query,host.manager)};
|
||||
}),
|
||||
];
|
||||
const projectResources = [...commands, ...enterpriseTools(host, make)];
|
||||
const projectResources = [...commands, ...enterpriseTools(host, make), ...productionVideoTools(host, make)];
|
||||
if (host.productionGoal) return [
|
||||
...productionTools.map(([name, description, schema])=>
|
||||
make(name,description,schema,(args,signal)=>callProductionTool(host,name,args,signal),
|
||||
@ -317,12 +318,12 @@ 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, protocolMode = 'native-tools', callBudget, onEvent = () => {} }) {
|
||||
static async open({ store, broker, brokerInfo, canvas, transport, projectEvidence, documentId, productionGoal, productionSignal, videoRuntime, protocolMode = 'native-tools', callBudget, onEvent = () => {} }) {
|
||||
assertPiNodeVersion(process.versions.node);
|
||||
if (!['native-tools', 'structured-json'].includes(protocolMode)) throw Error('工具协议模式无效');
|
||||
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, protocolMode, callBudget, turnEpoch: 0, rounds: 0, inflight: null, text: '' });
|
||||
Object.assign(host, { canvasOperations:new CanvasOperations(), store, broker, canvas, onEvent, productionGoal, productionSignal, videoRuntime, protocolMode, callBudget, turnEpoch: 0, rounds: 0, inflight: null, text: '' });
|
||||
try { host.releaseLock = lockfile.lockSync(store.root, { stale: 15000, update: 4000, retries: 0, onCompromised: error => { host.compromised = error; host.session?.agent.abort(); } }); }
|
||||
catch { throw Error('此项目已有本地Agent在运行,请等待当前任务结束;未发起新请求'); }
|
||||
try {
|
||||
|
||||
@ -1,5 +1,6 @@
|
||||
const PRUNABLE_IMAGE_TOOLS = new Set([
|
||||
'read_output_screen', 'read_slot_images', 'canvas_template_image', 'canvas_candidate_image',
|
||||
'video_inspect',
|
||||
]);
|
||||
|
||||
export function pruneHistoricalToolImages(messages, { keepLatest = 1 } = {}) {
|
||||
|
||||
@ -12,6 +12,10 @@ const outputCapabilities = new Map([
|
||||
label: '种草图', templateRoles: ['original', 'mapping'],
|
||||
skillId: 'seeding-images-production', adapterId: 'seeding-images-render',
|
||||
}],
|
||||
['seeding_video', {
|
||||
label: '种草视频', templateRoles: ['original', 'mapping'],
|
||||
skillId: 'seeding-video-production', adapterId: 'seeding-video-render',
|
||||
}],
|
||||
]);
|
||||
|
||||
const issueSchema = Type.Object({
|
||||
|
||||
@ -1,3 +1,4 @@
|
||||
import path from 'node:path';
|
||||
import { CanvasOperations } from './canvas-operations.mjs';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
@ -9,6 +10,8 @@ import { productionKnowledge, knowledgeReadInstruction } from './production-know
|
||||
import { productRequestScope } from './production-recovery.mjs';
|
||||
import { canvasTransformArgs, copySignature, decideCandidateSet, readAutoAdoptionPolicy, reviewProductionCandidate } from './candidate-review.mjs';
|
||||
import { executeWorkflow, LOCAL_OPERATION_WAIT_MS, reconcileWorkflowReceipt } from './workflow-execute.mjs';
|
||||
import { createVideoToolExecutors, videoTools } from './video-tools.mjs';
|
||||
import { activityToolLabel } from './activity-event.mjs';
|
||||
|
||||
const obj=fields=>Type.Object(fields,{additionalProperties:false});
|
||||
const text=Type.String({minLength:1});
|
||||
@ -114,6 +117,25 @@ export const imageResult = ({images=[],...details})=>({
|
||||
content:[{type:'text',text:JSON.stringify(details)},...images],details,
|
||||
});
|
||||
|
||||
export function productionVideoTools(host, make) {
|
||||
const { productionGoal, videoRuntime } = host;
|
||||
const outputs = productionGoal?.requestedOutputs ?? [];
|
||||
const isVideo = id => id === 'main_video' || id === 'seeding_video';
|
||||
if (!videoRuntime && !isVideo(productionGoal?.outputId) && !outputs.some(row => isVideo(row.outputId))) return [];
|
||||
const execute = createVideoToolExecutors({
|
||||
deliveryDir: productionGoal?.deliveryDir,
|
||||
...videoRuntime,
|
||||
ledgerDir: path.join(host.store.root, 'video-requests'),
|
||||
});
|
||||
return videoTools.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);
|
||||
}, name === 'video_inspect' ? result => result : undefined),
|
||||
label: activityToolLabel(name),
|
||||
}));
|
||||
}
|
||||
|
||||
function productionInputs(plan,variantId){
|
||||
const brief=plan.productEvidence?.brief;
|
||||
if(!brief)return plan.revisions?.creation;
|
||||
|
||||
164
apps/detail-agent-pi/src/video-ffmpeg.mjs
Normal file
164
apps/detail-agent-pi/src/video-ffmpeg.mjs
Normal file
@ -0,0 +1,164 @@
|
||||
import { execFile } from 'node:child_process';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { BridgeError } from './bridge-error.mjs';
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const invalid = message => new BridgeError(message, 'invalid_video_input');
|
||||
const decodeFailed = () => new BridgeError('视频或音频解码失败,请检查源文件', 'video_decode_failed');
|
||||
const ffmpegArgs = ['-hide_banner', '-nostdin'];
|
||||
const executable = name => path.dirname(name) === '.' && path.basename(name) === name ? name : path.resolve(name);
|
||||
|
||||
export function createVideoMedia({
|
||||
ffmpegPath = process.env.XIAOYI_FFMPEG_PATH || 'ffmpeg',
|
||||
ffprobePath = process.env.XIAOYI_FFPROBE_PATH || 'ffprobe',
|
||||
ffmpegPrefix = [], ffprobePrefix = [],
|
||||
} = {}) {
|
||||
const run = async (name, binary, prefix, args, { signal, cwd, category } = {}) => {
|
||||
signal?.throwIfAborted();
|
||||
try {
|
||||
return await execute(executable(binary), [...prefix, ...args], {
|
||||
signal, cwd, encoding: 'buffer', maxBuffer: 32 * 1024 * 1024, windowsHide: true,
|
||||
});
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (['ENOENT', 'EACCES', 'EPERM', 'ENOEXEC', 'EINVAL', 'UNKNOWN'].includes(error.code)) {
|
||||
throw new BridgeError(`无法执行 ${name},请配置可运行的媒体工具路径`, 'missing_ffmpeg_binary');
|
||||
}
|
||||
if (category === 'video_decode_failed') throw decodeFailed();
|
||||
throw new BridgeError(`${name} 执行失败,请检查媒体文件及输出规格`, category ?? 'video_media_failed');
|
||||
}
|
||||
};
|
||||
const ffmpeg = (args, options) => run('ffmpeg', ffmpegPath, ffmpegPrefix, [...ffmpegArgs, ...args], options);
|
||||
const probe = async (file, signal) => {
|
||||
const { stdout } = await run('ffprobe', ffprobePath, ffprobePrefix,
|
||||
['-v', 'error', '-show_format', '-show_streams', '-of', 'json', path.resolve(file)], { signal });
|
||||
const info = JSON.parse(stdout.toString());
|
||||
if (!Array.isArray(info.streams)) throw decodeFailed();
|
||||
return info;
|
||||
};
|
||||
return {
|
||||
probe,
|
||||
async inspect(file, signal) {
|
||||
const absolute = path.resolve(file);
|
||||
const stat = await fs.stat(absolute);
|
||||
if (!stat.isFile() || !stat.size) throw decodeFailed();
|
||||
const info = await probe(absolute, signal);
|
||||
const video = info.streams.find(stream => stream.codec_type === 'video' && !stream.disposition?.attached_pic);
|
||||
const audios = info.streams.filter(stream => stream.codec_type === 'audio');
|
||||
const rate = video?.avg_frame_rate === '0/0' ? video.r_frame_rate : video?.avg_frame_rate ?? video?.r_frame_rate;
|
||||
const [numerator, denominator = 1] = (rate ?? '').split('/').map(Number);
|
||||
const fps = numerator / denominator;
|
||||
const duration = Number(video?.duration ?? info.format?.duration);
|
||||
if (!video?.width || !video.height || !(Number.isFinite(fps) && fps > 0) ||
|
||||
!(Number.isFinite(duration) && duration > 0) || !info.format?.format_name?.split(',').includes('mp4')) throw decodeFailed();
|
||||
const audioStreams = [];
|
||||
for (const [index, audio] of audios.entries()) {
|
||||
const { stderr } = await ffmpeg(['-v', 'info', '-xerror', '-i', absolute, '-map', `0:${audio.index}`,
|
||||
'-af', 'volumedetect', '-f', 'null', '-'], { signal, category: 'video_decode_failed' });
|
||||
const log = stderr.toString();
|
||||
const volume = key => {
|
||||
const value = log.match(new RegExp(`${key}: (-?[\\d.]+) dB`))?.[1];
|
||||
return value === undefined ? null : Number(value);
|
||||
};
|
||||
audioStreams.push({ index, codec: audio.codec_name, channels: audio.channels,
|
||||
sampleRate: Number(audio.sample_rate) || null, meanVolumeDb: volume('mean_volume'), maxVolumeDb: volume('max_volume') });
|
||||
}
|
||||
await ffmpeg(['-v', 'error', '-xerror', '-i', absolute, '-map', `0:${video.index}`, '-f', 'null', '-'],
|
||||
{ signal, category: 'video_decode_failed' });
|
||||
return { path: absolute, bytes: stat.size, width: video.width, height: video.height, codec: video.codec_name,
|
||||
fps, frameRate: rate, duration, hasAudio: audioStreams.length > 0, audioStreams, decoded: true };
|
||||
},
|
||||
async frame(file, time, signal) {
|
||||
const { stdout } = await ffmpeg(['-v', 'error', '-xerror', '-ss', String(time), '-i', path.resolve(file),
|
||||
'-map', '0:V:0', '-frames:v', '1', '-c:v', 'mjpeg', '-f', 'image2pipe', 'pipe:1'],
|
||||
{ signal, category: 'video_decode_failed' });
|
||||
if (stdout[0] !== 0xff || stdout[1] !== 0xd8 || stdout.at(-2) !== 0xff || stdout.at(-1) !== 0xd9) throw decodeFailed();
|
||||
return stdout;
|
||||
},
|
||||
async render(timeline, { cwd, signal }) {
|
||||
await ffmpeg(buildTimelineArgs(timeline), { cwd, signal, category: 'video_compose_failed' });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const videoTransitions = ['fade', 'wipeleft', 'wiperight', 'slideleft', 'slideright', 'dissolve'];
|
||||
const formatTime = value => Number(value.toFixed(6)).toString();
|
||||
const silence = duration => `anullsrc=r=48000:cl=stereo:d=${formatTime(duration)}`;
|
||||
const audioFormat = 'aformat=sample_fmts=fltp:sample_rates=48000:channel_layouts=stereo';
|
||||
|
||||
// Clips already carry probed durations and stream flags. All transition offsets
|
||||
// refer to the assembled timeline, including earlier overlaps.
|
||||
export function buildTimelineFilter({ clips, audioTracks = [], width, height, fps, burnSubtitles, muteSource = false }) {
|
||||
if (clips[0].transition) throw invalid('首个片段没有可衔接的前一片段');
|
||||
const filters = [];
|
||||
const canvas = `scale=${width}:${height}:force_original_aspect_ratio=decrease,pad=${width}:${height}:(ow-iw)/2:(oh-ih)/2,setsar=1`;
|
||||
const audio = !muteSource && clips.some(clip => clip.hasAudio);
|
||||
for (const [i, clip] of clips.entries()) {
|
||||
const { start = 0, duration, still, zoom, interpolate, hasAudio } = clip;
|
||||
const end = formatTime(start + duration);
|
||||
const trim = `trim=start=${formatTime(start)}:end=${end},setpts=PTS-STARTPTS`;
|
||||
const frames = Math.round(duration * fps);
|
||||
const zoomFilter = zoom
|
||||
? `zoompan=z='${zoom.from}+(${zoom.to}-${zoom.from})*on/${Math.max(1, frames - 1)}':x='iw/2-iw/zoom/2':y='ih/2-ih/zoom/2':d=${frames}:s=${width}x${height}:fps=${fps}`
|
||||
: `fps=${fps}`;
|
||||
const interpolateFrames = `tpad=stop_mode=clone:stop=3,minterpolate=fps=${fps}:mi_mode=mci`;
|
||||
const normalize = still
|
||||
? `${canvas},${zoomFilter},${trim}`
|
||||
: `${trim},${canvas},${interpolate ? interpolateFrames : `fps=${fps}`},tpad=stop_mode=clone:stop_duration=${formatTime(duration)},trim=duration=${formatTime(duration)}`;
|
||||
filters.push(`[${i}:V:0]${normalize},format=yuv420p,settb=AVTB,setpts=PTS-STARTPTS[v${i}]`);
|
||||
if (audio) {
|
||||
const source = hasAudio
|
||||
? `[${i}:a:0]atrim=start=${formatTime(start)}:end=${end},asetpts=PTS-STARTPTS,${audioFormat},apad,atrim=duration=${formatTime(duration)}`
|
||||
: `${silence(duration)},${audioFormat}`;
|
||||
filters.push(`${source}[a${i}]`);
|
||||
}
|
||||
}
|
||||
let video = 'v0';
|
||||
let sound = audio ? 'a0' : null;
|
||||
let duration = clips[0].duration;
|
||||
for (let i = 1; i < clips.length; i++) {
|
||||
const clip = clips[i];
|
||||
const overlap = clip.transition?.duration ?? 0;
|
||||
if (clip.transition && (!videoTransitions.includes(clip.transition.type) ||
|
||||
overlap < 1 / fps || overlap >= clips[i - 1].duration || overlap >= clip.duration ||
|
||||
overlap + (clips[i - 1].transition?.duration ?? 0) > clips[i - 1].duration)) {
|
||||
throw invalid('转场时长超出相邻片段可重叠的范围');
|
||||
}
|
||||
const transition = overlap
|
||||
? `xfade=transition=${clip.transition.type}:duration=${formatTime(overlap)}:offset=${formatTime(duration - overlap)}`
|
||||
: 'concat=n=2:v=1:a=0';
|
||||
filters.push(`[${video}][v${i}]${transition},settb=AVTB[mv${i}]`);
|
||||
video = `mv${i}`;
|
||||
if (audio) {
|
||||
filters.push(`[${sound}][a${i}]${overlap ? `acrossfade=d=${formatTime(overlap)}` : 'concat=n=2:v=0:a=1'}[ma${i}]`);
|
||||
sound = `ma${i}`;
|
||||
}
|
||||
duration += clip.duration - overlap;
|
||||
}
|
||||
filters.push(`[${video}]${burnSubtitles ? 'subtitles=timeline.srt,' : ''}format=yuv420p[outv]`);
|
||||
|
||||
const mix = sound ? [sound] : [];
|
||||
for (const [i, track] of audioTracks.entries()) {
|
||||
const { start = 0, offset = 0, gain = 1 } = track;
|
||||
if (offset >= duration) throw invalid('音轨起点超出时间线');
|
||||
filters.push(`[${clips.length + i}:a:0]atrim=start=${formatTime(start)},asetpts=PTS-STARTPTS,${audioFormat},volume=${gain},adelay=${Math.round(offset * 48000)}S:all=1,apad,atrim=duration=${formatTime(duration)}[mix${i}]`);
|
||||
mix.push(`mix${i}`);
|
||||
}
|
||||
if (mix.length) filters.push(`${mix.map(label => `[${label}]`).join('')}amix=inputs=${mix.length}:duration=longest[outa]`);
|
||||
return { filterComplex: filters.join(';'), hasAudio: mix.length > 0, duration };
|
||||
}
|
||||
|
||||
export function buildTimelineArgs(timeline) {
|
||||
const { clips, audioTracks = [], fps, crf = 20, audioBitrateKbps = 192 } = timeline;
|
||||
const { filterComplex, hasAudio, duration } = buildTimelineFilter(timeline);
|
||||
return ['-v', 'error', '-xerror', '-n', '-filter_complex_threads', '1',
|
||||
...clips.flatMap(({ path: file, still, zoom }) => [
|
||||
...(still && !zoom ? ['-loop', '1', '-framerate', String(fps)] : []), '-i', path.resolve(file),
|
||||
]),
|
||||
...audioTracks.flatMap(({ path: file }) => ['-i', path.resolve(file)]),
|
||||
'-filter_complex', filterComplex, '-map', '[outv]', ...(hasAudio ? ['-map', '[outa]'] : []),
|
||||
'-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'];
|
||||
}
|
||||
233
apps/detail-agent-pi/src/video-tools.mjs
Normal file
233
apps/detail-agent-pi/src/video-tools.mjs
Normal file
@ -0,0 +1,233 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import { constants } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import lockfile from 'proper-lockfile';
|
||||
import { Type } from '@sinclair/typebox';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { BridgeError } from './bridge-error.mjs';
|
||||
import { atomic, digest } from './store.mjs';
|
||||
import { buildTimelineFilter, createVideoMedia, videoTransitions } from './video-ffmpeg.mjs';
|
||||
|
||||
const object = fields => Type.Object(fields, { additionalProperties: false });
|
||||
const text = Type.String({ minLength: 1 });
|
||||
const seconds = Type.Number({ minimum: 0 });
|
||||
const duration = Type.Number({ exclusiveMinimum: 0 });
|
||||
const dimension = Type.Integer({ minimum: 2, multipleOf: 2 });
|
||||
const optional = Type.Optional;
|
||||
const invalid = message => new BridgeError(message, 'invalid_video_input');
|
||||
const filename = Type.String({ pattern: '^[^<>:"/\\\\|?*\\u0000-\\u001f]+$' });
|
||||
|
||||
export const videoTools = [
|
||||
['video_generate_clip', '按镜头描述与参考素材生成一个视频片段。同一 requestKey 用于读取或核查同一个原请求。',
|
||||
object({ requestKey: text, prompt: text, firstFrame: optional(text), lastFrame: optional(text),
|
||||
referenceImages: optional(Type.Array(text)), duration: optional(duration), aspectRatio: optional(text), model: optional(text) })],
|
||||
['video_compose_timeline', '按提供的时间线裁切、拼接、转场与混音,交付视频和封面。时间单位为秒。可传字幕文件或定时文字。',
|
||||
object({
|
||||
clips: Type.Array(object({
|
||||
path: text, start: optional(seconds), duration: optional(duration), still: optional(Type.Boolean()),
|
||||
zoom: optional(object({ from: Type.Number({ minimum: 1, maximum: 10 }), to: Type.Number({ minimum: 1, maximum: 10 }) })),
|
||||
interpolate: optional(Type.Boolean()),
|
||||
transition: optional(object({ type: Type.Union(videoTransitions.map(value => Type.Literal(value))), duration })),
|
||||
}), { minItems: 1 }),
|
||||
audioTracks: optional(Type.Array(object({ path: text, start: optional(seconds), offset: optional(seconds),
|
||||
gain: optional(Type.Number({ minimum: 0 })) }))),
|
||||
muteSource: optional(Type.Boolean()),
|
||||
subtitles: optional(object({ path: optional(text), captions: optional(Type.Array(
|
||||
object({ start: seconds, end: duration, text }), { minItems: 1 })),
|
||||
mode: Type.Union(['burn', 'sidecar', 'both'].map(value => Type.Literal(value))) })),
|
||||
outputDir: optional(text), name: filename, width: dimension, height: dimension,
|
||||
fps: Type.Integer({ minimum: 1, maximum: 120 }), coverTime: optional(seconds),
|
||||
crf: optional(Type.Integer({ minimum: 0, maximum: 51 })), audioBitrateKbps: optional(Type.Integer({ minimum: 1 })),
|
||||
})],
|
||||
['video_inspect', '完整解码磁盘上的 MP4,核对实际规格和音轨,并查看指定秒数的画面。',
|
||||
object({ path: text, frameTimes: optional(Type.Array(seconds, { maxItems: 8 })) })],
|
||||
];
|
||||
|
||||
const schemas = new Map(videoTools.map(([name, , schema]) => [name, schema]));
|
||||
const validate = (name, input) => {
|
||||
if (!Value.Check(schemas.get(name), input)) throw invalid('视频工具参数不符合要求');
|
||||
};
|
||||
|
||||
function videoRequestSpec({ prompt, firstFrame, lastFrame, referenceImages = [], duration, aspectRatio, model }) {
|
||||
return { prompt: prompt.trim(), firstFrame, lastFrame, referenceImages, duration, aspectRatio, model };
|
||||
}
|
||||
|
||||
const pendingOriginal = (requestKey, remoteTaskId) => ({ status: 'pending', pendingOriginal: requestKey,
|
||||
...(remoteTaskId ? { remoteTaskId } : {}), message: '视频生成结果待核查,请使用原请求编号' });
|
||||
|
||||
// Like image requests, commit identity before dispatch and query the original
|
||||
// after interruption. The lock serializes dispatch and recovery for this key.
|
||||
async function generateClip({ requestKey, ...input }, { generator, ledgerDir, media }, signal) {
|
||||
const spec = videoRequestSpec(input);
|
||||
if (!spec.prompt) throw invalid('请提供镜头描述');
|
||||
if (!ledgerDir) {
|
||||
if (!generator?.generate) throw new BridgeError('当前未配置视频生成服务', 'missing_video_generator_adapter');
|
||||
throw new BridgeError('当前未配置视频请求账本', 'missing_video_request_ledger');
|
||||
}
|
||||
const requestDigest = digest(spec);
|
||||
const file = path.join(ledgerDir, `${digest(requestKey)}.json`);
|
||||
await fs.mkdir(ledgerDir, { recursive: true });
|
||||
let unlock;
|
||||
try { unlock = await lockfile.lock(file, { realpath: false }); }
|
||||
catch (error) {
|
||||
if (error.code === 'ELOCKED') return pendingOriginal(requestKey);
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
let record = await fs.readFile(file, 'utf8').then(JSON.parse, error => {
|
||||
if (error.code !== 'ENOENT') throw error;
|
||||
});
|
||||
if (record && record.requestDigest !== requestDigest) {
|
||||
throw new BridgeError('此请求编号已绑定其他镜头参数,请使用原参数或为新镜头使用新编号', 'video_request_conflict');
|
||||
}
|
||||
if (!record?.receipt) {
|
||||
if (!record && !generator?.generate) {
|
||||
throw new BridgeError('当前未配置视频生成服务', 'missing_video_generator_adapter');
|
||||
}
|
||||
if (record && (!record.remoteTaskId || !generator?.recover)) return pendingOriginal(requestKey, record.remoteTaskId);
|
||||
signal?.throwIfAborted();
|
||||
const original = !!record;
|
||||
record ??= { requestKey, requestDigest, state: 'dispatching' };
|
||||
const onDispatched = async remoteTaskId => {
|
||||
if (typeof remoteTaskId !== 'string' || !remoteTaskId || record.remoteTaskId && record.remoteTaskId !== remoteTaskId) {
|
||||
throw Error('视频服务回执与原任务编号不一致');
|
||||
}
|
||||
record.remoteTaskId = remoteTaskId;
|
||||
await atomic(file, record);
|
||||
};
|
||||
if (!original) await atomic(file, record);
|
||||
try {
|
||||
const context = { signal, requestKey, requestDigest, onDispatched };
|
||||
const result = original
|
||||
? await generator.recover(record.remoteTaskId, context)
|
||||
: await generator.generate(spec, context);
|
||||
if (result?.remoteTaskId) await onDispatched(result.remoteTaskId);
|
||||
if (typeof result?.path !== 'string' || !result.path || typeof result.clipId !== 'string' ||
|
||||
!result.clipId || !record.remoteTaskId) return pendingOriginal(requestKey, record.remoteTaskId);
|
||||
const receipt = { clipId: result.clipId, path: path.resolve(result.path), remoteTaskId: record.remoteTaskId };
|
||||
await atomic(file, { ...record, state: 'received', receipt });
|
||||
record.receipt = receipt;
|
||||
} catch {
|
||||
signal?.throwIfAborted();
|
||||
return pendingOriginal(requestKey, record.remoteTaskId);
|
||||
}
|
||||
}
|
||||
return { requestKey, ...record.receipt, ...await media.inspect(record.receipt.path, signal) };
|
||||
} finally {
|
||||
await unlock();
|
||||
}
|
||||
}
|
||||
|
||||
const srtTime = seconds => {
|
||||
const ms = Math.round(seconds * 1000);
|
||||
return [Math.floor(ms / 3600000), Math.floor(ms / 60000) % 60, Math.floor(ms / 1000) % 60]
|
||||
.map(value => String(value).padStart(2, '0')).join(':') + ',' + String(ms % 1000).padStart(3, '0');
|
||||
};
|
||||
|
||||
async function subtitleText({ path: file, captions }, duration) {
|
||||
if (Boolean(file) === Boolean(captions)) throw invalid('请选择一个字幕文件或一组定时文字');
|
||||
if (file) {
|
||||
const content = await fs.readFile(file, 'utf8');
|
||||
if (!content.trim()) throw invalid('字幕文件为空');
|
||||
return content;
|
||||
}
|
||||
return captions.map(({ start, end, text }, index) => {
|
||||
if (end <= start || end > duration) throw invalid('字幕起止时间超出时间线');
|
||||
return `${index + 1}\n${srtTime(start)} --> ${srtTime(end)}\n${text}\n`;
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
async function composeTimeline(input, { media, deliveryDir }, signal) {
|
||||
const { clips, subtitles, outputDir = deliveryDir, name, coverTime = 0 } = input;
|
||||
if (!outputDir) throw invalid('请指定成品目录');
|
||||
if (name.endsWith('.') || name.endsWith(' ')) throw invalid('请填写有效的成品文件名');
|
||||
const resolved = await Promise.all(clips.map(async clip => {
|
||||
const start = clip.start ?? 0;
|
||||
if (clip.still) {
|
||||
if (!clip.duration || start || clip.interpolate) throw invalid('静图需要指定时长,可设置缩放关键帧');
|
||||
return clip;
|
||||
}
|
||||
if (clip.zoom) throw invalid('缩放关键帧适用于静图片段');
|
||||
const info = await media.probe(clip.path, signal);
|
||||
const stream = info.streams.find(stream => stream.codec_type === 'video' && !stream.disposition?.attached_pic);
|
||||
const available = Number(stream?.duration ?? info.format?.duration);
|
||||
const duration = clip.duration ?? available - start;
|
||||
if (!stream || !Number.isFinite(available) || duration < 1 / input.fps || start + duration > available + 0.000001) {
|
||||
throw invalid('片段裁切范围超出源视频或不足一帧');
|
||||
}
|
||||
return { ...clip, duration, hasAudio: info.streams.some(stream => stream.codec_type === 'audio') };
|
||||
}));
|
||||
if (resolved.some(clip => clip.duration < 1 / input.fps)) throw invalid('片段时长不足一帧');
|
||||
const frameDuration = time => Math.round(time * input.fps) / input.fps;
|
||||
const timeline = {
|
||||
...input,
|
||||
clips: resolved.map(clip => ({ ...clip, duration: frameDuration(clip.duration),
|
||||
...(clip.transition ? { transition: { ...clip.transition, duration: frameDuration(clip.transition.duration) } } : {}) })),
|
||||
burnSubtitles: ['burn', 'both'].includes(subtitles?.mode),
|
||||
};
|
||||
const { duration, hasAudio } = buildTimelineFilter(timeline);
|
||||
if (coverTime >= duration) throw invalid('封面时间超出成片范围');
|
||||
|
||||
const root = path.resolve(outputDir);
|
||||
await fs.mkdir(root, { recursive: true });
|
||||
const stage = await fs.mkdtemp(path.join(root, '.video-'));
|
||||
const staged = ext => path.join(stage, `timeline.${ext}`);
|
||||
const published = [];
|
||||
try {
|
||||
if (subtitles) await fs.writeFile(staged('srt'), await subtitleText(subtitles, duration));
|
||||
await media.render(timeline, { cwd: stage, signal });
|
||||
const video = await media.inspect(staged('mp4'), signal);
|
||||
if (video.width !== input.width || video.height !== input.height || Math.abs(video.fps - input.fps) > 0.001 ||
|
||||
Math.abs(video.duration - duration) > 1 / input.fps + 0.001 || video.hasAudio !== hasAudio ||
|
||||
video.codec !== 'h264' || video.audioStreams.some(stream => stream.codec !== 'aac')) {
|
||||
throw new BridgeError('成片编码或画面规格与输出要求不一致', 'video_compose_failed');
|
||||
}
|
||||
const cover = await media.frame(staged('mp4'), coverTime, signal);
|
||||
await fs.writeFile(staged('jpg'), cover);
|
||||
const extensions = ['jpg', ...(['sidecar', 'both'].includes(subtitles?.mode) ? ['srt'] : []), 'mp4'];
|
||||
const files = {};
|
||||
for (const ext of extensions) {
|
||||
signal?.throwIfAborted();
|
||||
const target = path.join(root, `${name}.${ext}`);
|
||||
// Publish the verified MP4 last. Existing deliveries keep their names and bytes.
|
||||
await fs.copyFile(staged(ext), target, constants.COPYFILE_EXCL);
|
||||
published.push(target);
|
||||
files[ext] = { path: target, bytes: (await fs.stat(target)).size };
|
||||
}
|
||||
return { video: { ...video, ...files.mp4 }, cover: { ...files.jpg, time: coverTime },
|
||||
...(files.srt ? { subtitles: files.srt } : {}) };
|
||||
} catch (error) {
|
||||
await Promise.all(published.map(file => fs.unlink(file)));
|
||||
if (error.code === 'EEXIST') throw new BridgeError('成品文件名已存在,请使用新的文件名', 'video_output_exists');
|
||||
throw error;
|
||||
} finally {
|
||||
await fs.rm(stage, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
export function createVideoToolExecutors({ generator, ledgerDir, deliveryDir, ...ffmpeg } = {}) {
|
||||
const media = createVideoMedia(ffmpeg);
|
||||
return {
|
||||
async video_generate_clip(input, signal) {
|
||||
validate('video_generate_clip', input);
|
||||
return generateClip(input, { media, generator, ledgerDir }, signal);
|
||||
},
|
||||
async video_compose_timeline(input, signal) {
|
||||
validate('video_compose_timeline', input);
|
||||
return composeTimeline(input, { media, deliveryDir }, signal);
|
||||
},
|
||||
async video_inspect(input, signal) {
|
||||
validate('video_inspect', input);
|
||||
const info = await media.inspect(input.path, signal);
|
||||
const frameTimes = [...new Set(input.frameTimes ?? [0])];
|
||||
if (frameTimes.some(time => time >= info.duration)) throw invalid('抽帧时间超出视频范围');
|
||||
const images = [];
|
||||
for (const time of frameTimes) {
|
||||
const frame = await media.frame(info.path, time, signal);
|
||||
images.push({ type: 'image', mimeType: 'image/jpeg', data: frame.toString('base64') });
|
||||
}
|
||||
const details = { ...info, frameTimes };
|
||||
return { content: [{ type: 'text', text: JSON.stringify(details) }, ...images], details };
|
||||
},
|
||||
};
|
||||
}
|
||||
256
apps/detail-agent-pi/test/video-tools.test.mjs
Normal file
256
apps/detail-agent-pi/test/video-tools.test.mjs
Normal file
@ -0,0 +1,256 @@
|
||||
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 { createVideoMedia, buildTimelineArgs } from '../src/video-ffmpeg.mjs';
|
||||
import { createVideoToolExecutors, videoTools } from '../src/video-tools.mjs';
|
||||
import { pruneHistoricalToolImages } from '../src/image-context-pruning.mjs';
|
||||
import { checkOutputCapabilities } from '../src/output-capabilities.mjs';
|
||||
import { activitySummary } from '../src/activity-event.mjs';
|
||||
import { productionOperationTools, productionVideoTools } from '../src/production-operations.mjs';
|
||||
import { DetailPiAgent } from '../src/agent.mjs';
|
||||
import { ProjectStore } from '../src/store.mjs';
|
||||
import { cleanup } from './cleanup.mjs';
|
||||
|
||||
const names = ['video_generate_clip', 'video_compose_timeline', 'video_inspect'];
|
||||
|
||||
async function fixture(t) {
|
||||
const root = await fs.mkdtemp(path.join(os.tmpdir(), 'jiansun-pi-video-'));
|
||||
t.after(() => cleanup(root));
|
||||
const script = path.join(root, 'mock-media.mjs');
|
||||
const log = path.join(root, 'commands.jsonl');
|
||||
const source = path.join(root, '源片段 & 参考.mp4');
|
||||
const ledgerDir = path.join(root, 'ledger');
|
||||
await fs.writeFile(source, 'mock 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 video = { index: 2, codec_type: 'video', codec_name: 'h264', width: 720, height: 1280,
|
||||
avg_frame_rate: '30/1', duration: file.endsWith('timeline.mp4') ? '4.5' : '3' };
|
||||
const audio = { index: 3, 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([255, 216, 255, 217]));
|
||||
} else if (args.includes('-filter_complex')) {
|
||||
if (args.includes('timeline.mp4')) fs.writeFileSync(args.at(-1), 'rendered mock mp4');
|
||||
} else if (args.includes('volumedetect')) {
|
||||
console.error('mean_volume: -22.8 dB\nmax_volume: -3.1 dB');
|
||||
} else if (args.some(arg => arg.endsWith('broken.mp4'))) {
|
||||
process.exitCode = 1;
|
||||
}
|
||||
`);
|
||||
const config = {
|
||||
ffmpegPath: process.execPath, ffmpegPrefix: [script, log, 'ffmpeg'],
|
||||
ffprobePath: process.execPath, ffprobePrefix: [script, log, 'probe'], ledgerDir,
|
||||
};
|
||||
return { root, source, config, ledgerDir, tools: createVideoToolExecutors(config),
|
||||
async commands() { return (await fs.readFile(log, 'utf8')).trim().split('\n').map(line => JSON.parse(line)); } };
|
||||
}
|
||||
|
||||
function timeline(source) {
|
||||
return { clips: [
|
||||
{ path: source, start: 0.5, duration: 2, interpolate: true },
|
||||
{ path: source, duration: 3, transition: { type: 'fade', duration: 0.5 } },
|
||||
], width: 720, height: 1280, fps: 30, name: '种草成品', coverTime: 1, crf: 18, audioBitrateKbps: 160 };
|
||||
}
|
||||
|
||||
test('时间线参数支持硬切、静图关键帧、转场、混音和字幕烧录', () => {
|
||||
const args = buildTimelineArgs({
|
||||
width: 720, height: 1280, fps: 30, burnSubtitles: true,
|
||||
clips: [
|
||||
{ path: '静图 & 1.png', still: true, zoom: { from: 1, to: 1.2 }, duration: 2 },
|
||||
{ path: '片段 ; 2.mp4', start: 1, duration: 3, hasAudio: true, interpolate: true },
|
||||
{ path: '片段 3.mp4', duration: 2, transition: { type: 'dissolve', duration: 0.5 } },
|
||||
],
|
||||
audioTracks: [{ path: '配音.m4a', offset: 0.25, start: 0.5, gain: 0.75 }],
|
||||
});
|
||||
const graph = args[args.indexOf('-filter_complex') + 1];
|
||||
assert.match(graph, /zoompan=z='1\+\(1\.2-1\)\*on\/59'/);
|
||||
assert.match(graph, /trim=start=1:end=4.*minterpolate=fps=30:mi_mode=mci/);
|
||||
assert.match(graph, /concat=n=2:v=1:a=0/);
|
||||
assert.match(graph, /xfade=transition=dissolve:duration=0\.5:offset=4\.5/);
|
||||
assert.match(graph, /acrossfade=d=0\.5/);
|
||||
assert.match(graph, /atrim=start=0\.5.*volume=0\.75,adelay=12000S:all=1/);
|
||||
assert.match(graph, /amix=inputs=2/);
|
||||
assert.match(graph, /subtitles=timeline\.srt/);
|
||||
assert.ok(args.includes(path.resolve('片段 ; 2.mp4')));
|
||||
assert.ok(args.includes('libx264') && args.includes('aac') && args.includes('+faststart'));
|
||||
});
|
||||
|
||||
test('合成后回读成片、封面和字幕,已存在的成品不被覆盖', async t => {
|
||||
const f = await fixture(t);
|
||||
const outputDir = path.join(f.root, '交付 & 封面');
|
||||
const input = { ...timeline(f.source), outputDir,
|
||||
subtitles: { mode: 'both', captions: [{ start: 0.25, end: 1.5, text: '商品细节' }] } };
|
||||
const receipt = await f.tools.video_compose_timeline(input);
|
||||
assert.deepEqual([receipt.video.width, receipt.video.height, receipt.video.fps, receipt.video.duration], [720, 1280, 30, 4.5]);
|
||||
assert.equal(receipt.video.codec, 'h264');
|
||||
assert.equal(receipt.video.decoded, true);
|
||||
assert.deepEqual(receipt.video.audioStreams, [{ index: 0, codec: 'aac', channels: 2, sampleRate: 48000, meanVolumeDb: -22.8, maxVolumeDb: -3.1 }]);
|
||||
assert.equal(receipt.cover.time, 1);
|
||||
assert.match(await fs.readFile(receipt.subtitles.path, 'utf8'), /00:00:00,250 --> 00:00:01,500\n商品细节/);
|
||||
for (const file of Object.values(receipt)) assert.equal(file.bytes, (await fs.stat(file.path)).size);
|
||||
await assert.rejects(f.tools.video_compose_timeline(input), { category: 'video_output_exists' });
|
||||
assert.deepEqual((await fs.readdir(outputDir)).sort(), ['种草成品.jpg', '种草成品.mp4', '种草成品.srt']);
|
||||
const commands = await f.commands();
|
||||
assert.ok(commands.some(({ command, args }) => command === 'probe' && args.includes('-show_streams') && args.includes(f.source)));
|
||||
assert.ok(commands.some(({ args }) => args.includes('-ss') && args[args.indexOf('-ss') + 1] === '1' && args.includes('mjpeg')));
|
||||
assert.ok(commands.some(({ args }) => args.includes('0:2') && args.includes('-xerror') && args.includes('null')));
|
||||
});
|
||||
|
||||
test('独立字幕复用原文件,非法时间线在渲染前失败', async t => {
|
||||
const f = await fixture(t);
|
||||
const input = { ...timeline(f.source), outputDir: f.root };
|
||||
await assert.rejects(f.tools.video_compose_timeline({ ...input, width: 721 }), { category: 'invalid_video_input' });
|
||||
await assert.rejects(f.tools.video_compose_timeline({ ...input, name: '..\\other' }), { category: 'invalid_video_input' });
|
||||
await assert.rejects(f.tools.video_compose_timeline({ ...input, clips: [{ path: f.source, duration: 4 }] }), { category: 'invalid_video_input' });
|
||||
await assert.rejects(f.tools.video_compose_timeline({ ...input, coverTime: 5 }), { category: 'invalid_video_input' });
|
||||
assert.ok((await f.commands()).every(({ command }) => command === 'probe'));
|
||||
const srt = path.join(f.root, '原始 : 字幕.srt');
|
||||
const content = '1\n00:00:00,000 --> 00:00:01,000\n本地字幕\n';
|
||||
await fs.writeFile(srt, content);
|
||||
const result = await f.tools.video_compose_timeline({ ...input, subtitles: { mode: 'sidecar', path: srt } });
|
||||
assert.equal(await fs.readFile(result.subtitles.path, 'utf8'), content);
|
||||
const { args } = (await f.commands()).find(({ args }) => args.includes('-filter_complex'));
|
||||
assert.doesNotMatch(args[args.indexOf('-filter_complex') + 1], /subtitles=/);
|
||||
});
|
||||
|
||||
test('媒体命令或适配器缺失提供结构化错误,解码失败不给出验收回执', async t => {
|
||||
const f = await fixture(t);
|
||||
const missing = path.join(f.root, 'missing.exe');
|
||||
await assert.rejects(createVideoMedia({ ...f.config, ffprobePath: missing }).inspect(f.source), { category: 'missing_ffmpeg_binary' });
|
||||
await assert.rejects(createVideoMedia({ ...f.config, ffmpegPath: missing }).inspect(f.source), { category: 'missing_ffmpeg_binary' });
|
||||
const request = { requestKey: 'shot-1', prompt: '商品慢推镜头' };
|
||||
await assert.rejects(f.tools.video_generate_clip(request), { category: 'missing_video_generator_adapter' });
|
||||
await assert.rejects(createVideoToolExecutors().video_generate_clip(request), { category: 'missing_video_generator_adapter' });
|
||||
assert.deepEqual(await fs.readdir(f.ledgerDir), []);
|
||||
const broken = path.join(f.root, 'broken.mp4');
|
||||
await fs.writeFile(broken, 'corrupt');
|
||||
await assert.rejects(f.tools.video_inspect({ path: broken }), { category: 'video_decode_failed' });
|
||||
});
|
||||
|
||||
test('同编号并发和重启后均复用原请求,参数冲突不会再派发', async t => {
|
||||
const f = await fixture(t);
|
||||
const input = { requestKey: 'shot/1', prompt: ' 商品慢推镜头 ', firstFrame: '首帧.jpg', lastFrame: '尾帧.jpg',
|
||||
referenceImages: ['参考图.jpg'], duration: 3, aspectRatio: '9:16', model: 'mock-video' };
|
||||
let posts = 0;
|
||||
const started = Promise.withResolvers();
|
||||
const finish = Promise.withResolvers();
|
||||
const generator = { async generate(spec, { requestKey, requestDigest, onDispatched }) {
|
||||
posts++;
|
||||
assert.equal(requestKey, input.requestKey);
|
||||
assert.match(requestDigest, /^[a-f0-9]{64}$/);
|
||||
assert.deepEqual(spec, { prompt: input.prompt.trim(), firstFrame: input.firstFrame, lastFrame: input.lastFrame,
|
||||
referenceImages: input.referenceImages, duration: 3, aspectRatio: '9:16', model: 'mock-video' });
|
||||
const [file] = (await fs.readdir(f.ledgerDir)).filter(file => file.endsWith('.json'));
|
||||
assert.equal(JSON.parse(await fs.readFile(path.join(f.ledgerDir, file), 'utf8')).state, 'dispatching');
|
||||
await onDispatched('task-1');
|
||||
started.resolve();
|
||||
await finish.promise;
|
||||
return { clipId: 'clip-1', path: f.source };
|
||||
}};
|
||||
const tools = createVideoToolExecutors({ ...f.config, generator });
|
||||
const pending = tools.video_generate_clip(input);
|
||||
await Promise.race([started.promise, pending]);
|
||||
try {
|
||||
assert.equal((await tools.video_generate_clip(input)).pendingOriginal, input.requestKey);
|
||||
} finally { finish.resolve(); }
|
||||
const first = await pending;
|
||||
assert.equal(first.clipId, 'clip-1');
|
||||
assert.equal(first.remoteTaskId, 'task-1');
|
||||
assert.equal(first.duration, 3);
|
||||
assert.deepEqual(await f.tools.video_generate_clip({ ...input, prompt: input.prompt.trim() }), first);
|
||||
await assert.rejects(tools.video_generate_clip({ ...input, duration: 4 }), { category: 'video_request_conflict' });
|
||||
assert.equal(posts, 1);
|
||||
});
|
||||
|
||||
test('中断仅查原任务,未知任务号继续等待且不会重派', async t => {
|
||||
const f = await fixture(t);
|
||||
let posts = 0;
|
||||
const make = generator => createVideoToolExecutors({ ...f.config, generator });
|
||||
const input = { requestKey: 'known', prompt: '观察镜头' };
|
||||
const disconnected = make({ async generate(_spec, { onDispatched }) {
|
||||
posts++;
|
||||
await onDispatched('task-original');
|
||||
throw Error('模拟断连');
|
||||
}});
|
||||
assert.equal((await disconnected.video_generate_clip(input)).remoteTaskId, 'task-original');
|
||||
assert.equal((await f.tools.video_generate_clip(input)).status, 'pending');
|
||||
const reconnected = make({ async recover(id) {
|
||||
assert.equal(id, 'task-original');
|
||||
return { clipId: 'recovered', path: f.source };
|
||||
}});
|
||||
assert.equal((await reconnected.video_generate_clip(input)).clipId, 'recovered');
|
||||
const unknown = { ...input, requestKey: 'unknown' };
|
||||
const lost = make({ async generate() { posts++; throw Error('模拟提交后的未知结果'); } });
|
||||
assert.equal((await lost.video_generate_clip(unknown)).status, 'pending');
|
||||
assert.equal((await lost.video_generate_clip(unknown)).pendingOriginal, 'unknown');
|
||||
assert.equal(posts, 2);
|
||||
});
|
||||
|
||||
test('检视返回图像及文本,新的查看结果释放旧视频帧', async t => {
|
||||
const f = await fixture(t);
|
||||
const first = await f.tools.video_inspect({ path: f.source, frameTimes: [0, 1, 1] });
|
||||
const latest = await f.tools.video_inspect({ path: f.source, frameTimes: [2] });
|
||||
assert.deepEqual(first.details.frameTimes, [0, 1]);
|
||||
assert.equal(JSON.parse(first.content[0].text).hasAudio, true);
|
||||
assert.ok(first.content.slice(1).every(block => block.type === 'image' && block.mimeType === 'image/jpeg'));
|
||||
const messages = [first, latest].map(result => ({ role: 'toolResult', toolName: 'video_inspect', ...result }));
|
||||
const pruned = pruneHistoricalToolImages(messages);
|
||||
assert.equal(pruned[0].content[0].text, first.content[0].text);
|
||||
assert.ok(pruned[0].content.every(block => block.type === 'text'));
|
||||
assert.equal(pruned[1], messages[1]);
|
||||
await assert.rejects(f.tools.video_inspect({ path: f.source, frameTimes: [3] }), { category: 'invalid_video_input' });
|
||||
});
|
||||
|
||||
test('种草视频预检遵循发布绑定,三项工具活动使用白标标题', () => {
|
||||
const outputs = [{ outputId: 'seeding_video', variantId: 'qa' }, { outputId: 'main_images', variantId: 'qa' }];
|
||||
const blocked = checkOutputCapabilities(outputs);
|
||||
assert.equal(blocked.schemaVersion, 1);
|
||||
assert.equal(blocked.status, 'blocked');
|
||||
assert.deepEqual(blocked.issues.map(issue => issue.code), ['missing_template_resource', 'missing_published_skill', 'missing_render_adapter']);
|
||||
assert.deepEqual(checkOutputCapabilities(outputs, {
|
||||
componentRoles: new Map([['seeding_video', new Set(['original', 'mapping'])]]),
|
||||
publishedSkills: new Set(['seeding-video-production']), renderAdapters: new Set(['seeding-video-render']),
|
||||
}), { 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)));
|
||||
});
|
||||
|
||||
test('真实会话按视频输出或显式运行时注册,平面工具清单一致', async t => {
|
||||
const f = await fixture(t);
|
||||
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 })) });
|
||||
async function active(options) {
|
||||
const host = await DetailPiAgent.open({ store, transport, canvas, ...options });
|
||||
try { return host.session.getActiveToolNames(); }
|
||||
finally { await host.dispose(); }
|
||||
}
|
||||
const plane = await active({ productionGoal: goal(['detail', 'main_images', 'sku_images']) });
|
||||
assert.ok(productionOperationTools.every(([name]) => plane.includes(name)));
|
||||
assert.deepEqual(plane.filter(name => names.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 defaultChat = await active({});
|
||||
const explicit = await active({ videoRuntime: { generator: { generate() { throw Error('无需提交'); } } } });
|
||||
assert.deepEqual(explicit.filter(name => !names.includes(name)), defaultChat);
|
||||
assert.deepEqual(explicit.filter(name => names.includes(name)), names);
|
||||
});
|
||||
Loading…
x
Reference in New Issue
Block a user