@xiaohhhh1/canvas-agent 0.4.82 → 0.4.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -18,6 +18,7 @@ export declare class VideoAnalysisJobs {
18
18
  private directory;
19
19
  private analyze;
20
20
  private active;
21
+ private live;
21
22
  private locks;
22
23
  constructor(directory: string, analyze: Analyze);
23
24
  get activeCount(): number;
@@ -6,6 +6,7 @@ export class VideoAnalysisJobs {
6
6
  directory;
7
7
  analyze;
8
8
  active = new Map();
9
+ live = new Map();
9
10
  locks = new Map();
10
11
  constructor(directory, analyze) {
11
12
  this.directory = directory;
@@ -27,7 +28,13 @@ export class VideoAnalysisJobs {
27
28
  return existing;
28
29
  const job = { id, attemptId: randomUUID(), requestId, status: "running", stage: "读取原片与抽帧", updatedAt: new Date().toISOString() };
29
30
  await this.save(job);
30
- const task = this.run(job, source).catch(() => undefined).finally(() => this.active.delete(id));
31
+ this.live.set(id, { ...job });
32
+ const task = this.run(job, source).catch(() => undefined).finally(() => {
33
+ if (this.active.get(id) === task) {
34
+ this.active.delete(id);
35
+ this.live.delete(id);
36
+ }
37
+ });
31
38
  this.active.set(id, task);
32
39
  return { ...job };
33
40
  });
@@ -43,6 +50,12 @@ export class VideoAnalysisJobs {
43
50
  async get(id) {
44
51
  if (!/^[a-f0-9]{64}$/.test(id))
45
52
  throw new Error("视频分析任务标识无效");
53
+ // Polling and duplicate starts must not read the JSON file while an
54
+ // atomic replacement is in progress. Windows can reject that rename
55
+ // with EPERM, which used to fail the live analysis and admit a retry.
56
+ const live = this.live.get(id);
57
+ if (live)
58
+ return { ...live };
46
59
  let job;
47
60
  try {
48
61
  job = JSON.parse(await readFile(path.join(this.directory, id + ".json"), "utf8"));
@@ -85,5 +98,9 @@ export class VideoAnalysisJobs {
85
98
  const temporary = file + "." + randomUUID() + ".tmp";
86
99
  await writeFile(temporary, JSON.stringify(job), { mode: 0o600 });
87
100
  await rename(temporary, file);
101
+ // Expose only the last successfully persisted snapshot. In particular,
102
+ // a completed result cannot reach the browser before its rename lands.
103
+ if (this.live.has(job.id))
104
+ this.live.set(job.id, { ...job });
88
105
  }
89
106
  }
@@ -1,5 +1,6 @@
1
1
  import type { AgentAttachment } from "../agent/types.js";
2
2
  import { type FastMossIntegration } from "../integrations/fastmoss.js";
3
+ export declare const VIDEO_ANALYSIS_MODEL_ARGS: string[];
3
4
  export type LocalVideoLearningSource = {
4
5
  id?: string;
5
6
  source?: string;
@@ -6,6 +6,7 @@ import os from "node:os";
6
6
  import path from "node:path";
7
7
  import { videoEvidenceTimestamps } from "../integrations/fastmoss.js";
8
8
  const ANALYSIS_TIMEOUT_MS = 10 * 60_000;
9
+ export const VIDEO_ANALYSIS_MODEL_ARGS = ["--model", "gpt-5.6-terra", "-c", 'model_reasoning_effort="medium"'];
9
10
  const TRANSCRIPT_LANGUAGES = "en.*,es.*,zh.*,pt.*,fr.*,de.*,vi.*,th.*,id.*,ms.*,ja.*,ko.*";
10
11
  const LOCAL_ASR_MODEL = "onnx-community/whisper-base";
11
12
  const VIDEO_INTELLIGENCE_SCHEMA_VERSION = "commerce-video-intelligence-v7";
@@ -493,7 +494,7 @@ async function runLocalCodexAnalysis(prompt, attachments, workDir, timeoutMs = A
493
494
  // local development may keep them at a different ancestor. Resolve from this
494
495
  // module instead of assuming a nested node_modules directory.
495
496
  const codexEntrypoint = resolveLocalCodexEntrypoint();
496
- const args = [codexEntrypoint, "exec", "--json", "--ephemeral", "--skip-git-repo-check", "--sandbox", "read-only", "--color", "never", "--output-last-message", outputFile];
497
+ const args = [codexEntrypoint, "exec", ...VIDEO_ANALYSIS_MODEL_ARGS, "--json", "--ephemeral", "--skip-git-repo-check", "--sandbox", "read-only", "--color", "never", "--output-last-message", outputFile];
497
498
  for (const attachment of attachments)
498
499
  args.push("--image", path.join(workDir, String(attachment.name)));
499
500
  args.push("-");
@@ -1,10 +1,11 @@
1
1
  /** 中心/MCP 兼容上限仍为 30;结构化 10 秒脚本按更小子批受控并行。 */
2
2
  export declare const FLOW_C_SCRIPT_CHUNK_MAX = 30;
3
+ export declare const FLOW_C_VIDEO_MODEL_CONTRACT_VERSION = "flow-c-video-models-v1";
3
4
  export declare const FLOW_C_SCRIPT_CHUNK_SIZES: readonly [10, 5, 1];
4
5
  /**
5
6
  * 直接蓝图契约不再重复 creativePlan、executionBindings 和 masterScript,
6
7
  * 20/30 秒可先尝试更大的低开销子批,失败仍逐级缩小到单条。
7
8
  */
8
- export declare function flowCScriptChunkSizes(durationSeconds: 10 | 20 | 30): readonly [10, 5, 1] | readonly [4, 2, 1] | readonly [2, 1];
9
+ export declare function flowCScriptChunkSizes(durationSeconds: 10 | 15 | 20 | 30): readonly [10, 5, 1] | readonly [4, 2, 1] | readonly [2, 1];
9
10
  /** 将当前缺失 ordinal 切成受控子批;长视频绝不恢复 30 条大回合。 */
10
- export declare function flowCScriptChunks(durationSeconds: 10 | 20 | 30, ordinals: number[], size?: number): number[][];
11
+ export declare function flowCScriptChunks(durationSeconds: 10 | 15 | 20 | 30, ordinals: number[], size?: number): number[][];
@@ -1,5 +1,6 @@
1
1
  /** 中心/MCP 兼容上限仍为 30;结构化 10 秒脚本按更小子批受控并行。 */
2
2
  export const FLOW_C_SCRIPT_CHUNK_MAX = 30;
3
+ export const FLOW_C_VIDEO_MODEL_CONTRACT_VERSION = "flow-c-video-models-v1";
3
4
  export const FLOW_C_SCRIPT_CHUNK_SIZES = [10, 5, 1];
4
5
  /**
5
6
  * 直接蓝图契约不再重复 creativePlan、executionBindings 和 masterScript,
@@ -2,7 +2,8 @@ export declare const FLOW_C_CONTENT_STRATEGY_VERSION = "flow-c-content-strategy-
2
2
  export declare const FLOW_C_GENERATED_MONTAGE_VERSION = "flow-c-generated-montage-v1";
3
3
  export declare const FLOW_C_GENERATED_MONTAGE_STYLE = "generated-montage";
4
4
  export declare const FLOW_C_GENERATED_MONTAGE_VERSION_UNSUPPORTED = "FLOW_C_GENERATED_MONTAGE_VERSION_UNSUPPORTED";
5
- export declare const FLOW_C_VOICE_PACING_REPAIR_MIN_WORDS_PER_SECOND = 3;
5
+ export declare const FLOW_C_VOICE_PACING_QUICK_WORDS_PER_SECOND = 3;
6
+ export declare const FLOW_C_VOICE_PACING_REPAIR_MIN_WORDS_PER_SECOND = 4;
6
7
  export declare const FLOW_C_VOICE_PACING_REPAIR_MIN_EXCESS_WORDS = 3;
7
8
  export type FlowCContentStrategy = {
8
9
  contractVersion: typeof FLOW_C_CONTENT_STRATEGY_VERSION;
@@ -42,6 +43,7 @@ export type FlowCContentAdvisory = {
42
43
  };
43
44
  export type FlowCVoicePacingRepairIssue = Required<Pick<FlowCContentAdvisory, "ordinal" | "segment" | "shot" | "wordCount" | "suggestedMaxWords" | "durationSeconds">> & {
44
45
  code: "voice_pacing";
46
+ endShot?: number;
45
47
  };
46
48
  /** Explicit styles are capability-versioned; an unknown pair must never silently fall back. */
47
49
  export declare function flowCGeneratedMontage(value: unknown): boolean;
@@ -50,7 +52,7 @@ export declare function flowCContentWritingReviewPrompt(strategy: FlowCContentSt
50
52
  frameworkOrdinals: readonly number[];
51
53
  }): string;
52
54
  /** Rules for the separately selected generated-montage content style. */
53
- export declare function flowCGeneratedMontagePrompt(ordinals: readonly number[]): string;
55
+ export declare function flowCGeneratedMontagePrompt(ordinals: readonly number[], segmentSeconds?: 10 | 15): string;
54
56
  /** Missing/unknown versions keep historical tasks on their exact original prompt. */
55
57
  export declare function flowCContentStrategy(value: unknown): FlowCContentStrategy | null;
56
58
  export declare function flowCContentDirection(value: unknown, strategy: FlowCContentStrategy | null): FlowCContentDirection | null;
@@ -66,7 +68,8 @@ export declare function flowCContentAdvisories(jobs: unknown, strategy: FlowCCon
66
68
  /**
67
69
  * A deliberately narrower pre-delivery repair trigger than the public pacing
68
70
  * advisory. It only covers explicit English/Spanish text that is both very fast
69
- * and materially over the normal two-words-per-second writing budget.
71
+ * and materially over a quick three-words-per-second writing budget. Normal
72
+ * quick speech remains advisory, and visual cuts never become speech deadlines.
70
73
  */
71
74
  export declare function flowCVoicePacingRepairIssues(jobs: unknown, options?: {
72
75
  targetLanguage?: unknown;
@@ -115,6 +118,7 @@ export declare function flowCVoicePacingRepairScaffold(value: unknown): {
115
118
  export declare function flowCVoicePacingRepairPrompt(jobs: unknown, options?: {
116
119
  targetLanguage?: unknown;
117
120
  frameworkOrdinals?: readonly number[];
121
+ segmentSeconds?: 10 | 15;
118
122
  }): string;
119
123
  export declare function flowCContentMethodPrompt(strategy: FlowCContentStrategy | null, options: {
120
124
  recentScripts?: unknown;
@@ -122,4 +126,5 @@ export declare function flowCContentMethodPrompt(strategy: FlowCContentStrategy
122
126
  ordinals: number[];
123
127
  frameworkOrdinals: number[];
124
128
  montageOrdinals?: number[];
129
+ segmentSeconds?: 10 | 15;
125
130
  }): string;
@@ -2,7 +2,9 @@ export const FLOW_C_CONTENT_STRATEGY_VERSION = "flow-c-content-strategy-v1";
2
2
  export const FLOW_C_GENERATED_MONTAGE_VERSION = "flow-c-generated-montage-v1";
3
3
  export const FLOW_C_GENERATED_MONTAGE_STYLE = "generated-montage";
4
4
  export const FLOW_C_GENERATED_MONTAGE_VERSION_UNSUPPORTED = "FLOW_C_GENERATED_MONTAGE_VERSION_UNSUPPORTED";
5
- export const FLOW_C_VOICE_PACING_REPAIR_MIN_WORDS_PER_SECOND = 3;
5
+ // Editorial estimates, not a certification of spoken-audio intelligibility.
6
+ export const FLOW_C_VOICE_PACING_QUICK_WORDS_PER_SECOND = 3;
7
+ export const FLOW_C_VOICE_PACING_REPAIR_MIN_WORDS_PER_SECOND = 4;
6
8
  export const FLOW_C_VOICE_PACING_REPAIR_MIN_EXCESS_WORDS = 3;
7
9
  function object(value) {
8
10
  return value && typeof value === "object" && !Array.isArray(value) ? value : {};
@@ -29,6 +31,31 @@ function voicePacingMeasurement(value, durationSeconds, targetLanguage) {
29
31
  const wordCount = (voice.match(/[\p{L}\p{N}]+(?:['’][\p{L}\p{N}]+)*/gu) || []).length;
30
32
  return { wordCount, suggestedMaxWords: Math.floor(seconds * 2), durationSeconds: seconds };
31
33
  }
34
+ /** A camera cut does not end narration; only pool adjacent explicitly voiced shots. */
35
+ function continuousVoicePacingRuns(shots, targetLanguage) {
36
+ const runs = [];
37
+ let previousEnd = Number.NaN;
38
+ for (const [index, shot] of shots.entries()) {
39
+ const start = Number(shot.startSeconds);
40
+ const end = Number(shot.endSeconds);
41
+ const pacing = voicePacingMeasurement(shot.voiceover, end - start, targetLanguage);
42
+ if (!pacing) {
43
+ previousEnd = Number.NaN;
44
+ continue;
45
+ }
46
+ const current = runs.at(-1);
47
+ if (current && Number.isFinite(start) && Math.abs(start - previousEnd) < 0.001) {
48
+ current.endShot = index + 1;
49
+ current.wordCount += pacing.wordCount;
50
+ current.durationSeconds += pacing.durationSeconds;
51
+ }
52
+ else {
53
+ runs.push({ shot: index + 1, endShot: index + 1, wordCount: pacing.wordCount, durationSeconds: pacing.durationSeconds });
54
+ }
55
+ previousEnd = end;
56
+ }
57
+ return runs;
58
+ }
32
59
  /** Explicit styles are capability-versioned; an unknown pair must never silently fall back. */
33
60
  export function flowCGeneratedMontage(value) {
34
61
  const input = object(value);
@@ -51,19 +78,20 @@ export function flowCContentWritingReviewPrompt(strategy, options) {
51
78
  return `同回合按“框架 → 可见因果 → 当地口播 → 逐句对照”完成创作与自审,不增加模型调用或输出字段:
52
79
  - 框架:creativeBrief 与用户框架 ordinal ${JSON.stringify(frameworkOrdinals)} 优先;保留其角色、开头、事件顺序、核心情节、锁定对白和结尾,只补留白,不为追求差异改掉已经合适的创意。
53
80
  - 可见因果:先把一个有商品事实或参考图依据的动作、镜头内可见结果和核心购买理由连起来;evidence 只描述同镜真正看见的依据,不把生成表演冒充实测,也不从“有动作+有结果”自动推断未经提供的因果。
54
- - 当地口播:只按显式 targetLanguage/targetLocale、creatorVoiceStyle 与 ctaStyle 写自然口语语序和常用短句,不从国家推断语言、族群或口音,不逐字翻译、不生造俚语。用户锁定对白即使偏密或证据不足也不得静默删除、换义或改写;先给承载锁定对白的镜头足够秒数,必要时合并相邻同动作镜头、压缩无声过渡,再安排其它非锁定台词,绝不能把锁定对白塞进过短镜头或用加速掩盖。锁定对白已经占用可说完的时长时,其余可选口播默认 none;未解决处保留给非阻断提示。
81
+ - 当地口播:只按显式 targetLanguage/targetLocale、creatorVoiceStyle 与 ctaStyle 写自然口语语序和常用短句,不从国家推断语言、族群或口音,不逐字翻译、不生造俚语。用户锁定对白即使偏密或证据不足也不得静默删除、换义或改写;先给承载锁定对白的镜头足够秒数,必要时合并相邻同动作镜头、压缩无声过渡,再安排其它非锁定台词。允许偶尔偏密和适度加快语速,只要吐字清楚、符合画面、不夸张赶话;一句话可在同段相邻有声镜头间连续说完。锁定对白已经占用可说完的时长时,其余可选口播默认 none;未解决处保留给非阻断提示。
55
82
  - 逐句对照:逐镜核对每个非 none 的 voiceover 片段与该镜 visual/evidence 及已知商品事实;商品事实句必须有同镜可见依据,处境、情绪或 CTA 不必伪装成产品证明但必须符合正在发生的画面。最后核对末镜实际动作、visual 末尾收尾短句与 endingState.endingFrame 精确同锚点;这里只做结构性自审,不声称靠词面规则完成语义验收。`;
56
83
  }
57
84
  /** Rules for the separately selected generated-montage content style. */
58
- export function flowCGeneratedMontagePrompt(ordinals) {
85
+ export function flowCGeneratedMontagePrompt(ordinals, segmentSeconds = 10) {
59
86
  const scoped = [...new Set((Array.isArray(ordinals) ? ordinals : []).map(Number).filter((ordinal) => Number.isInteger(ordinal) && ordinal > 0))].slice(0, 100);
60
87
  if (!scoped.length)
61
88
  return "";
89
+ const longDurationLabel = segmentSeconds === 15 ? "30 秒双段" : "20/30 秒";
62
90
  return `\n原创混剪(${FLOW_C_GENERATED_MONTAGE_VERSION},仅 ordinal ${JSON.stringify(scoped)}):
63
91
  - 围绕一个由当前商品事实支持的核心购买理由,选择抓眼但真实可执行的使用、细节、多个适用画面或可见结果镜头;每次切镜带来新的有用观察,不做无关美图轮播,也不强制编痛点剧情、完整人物故事或为了差异放弃好创意。
64
92
  - 跨镜、跨全片的人物、服装和场景一致性不是目标或验收门槛;用户框架明确指定角色/场景时仍严格尊重。每个单镜动作须自然,若一个动作明确跨相邻镜继续则保持该动作的手部、商品与物理状态连续;人物或地点变化时在下一 shot.visual 明写 HARD CUT,切后可直接进入新示例,但所有镜头的 SKU、颜色、结构、材质、数量、包装和表面文字图案始终不变。
65
- - 仍是每个局部 0–10 秒、1–8 个 shots。20/30 秒后一段 openingState 精确继承上一段 endingState 只是技术开场交接;紧接着可以明写 HARD CUT 进入新人物或新场景,不要求让上一段人物/场景贯穿下一段,也不得为连续剧情浪费本段秒数。
66
- - 一句自然口播可以跨镜延续,但每镜 voiceover 只保存该镜实际说出的完整词组/分句;按该镜真实时长留呼吸,不能把整句塞进一秒镜头再借后续静默时长冲抵。每个 10 秒段都以自然完整的句法边界收尾,不把半个词、未完短语或待补 CTA 留给另一次模型调用。
93
+ - 仍是每个局部 0–${segmentSeconds} 秒、1–8 个 shots。${longDurationLabel}后一段 openingState 精确继承上一段 endingState 只是技术开场交接;紧接着可以明写 HARD CUT 进入新人物或新场景,不要求让上一段人物/场景贯穿下一段,也不得为连续剧情浪费本段秒数。
94
+ - 一句自然口播可以跨镜延续,但每镜 voiceover 只保存该镜实际说出的完整词组/分句;镜头切换不强制口播停顿,相邻有声镜头按连续口播整体留呼吸,允许偶尔偏密和适度加快语速。明确标为 none 的镜头保留静默,不把整句塞进一秒镜头再假定后续静默仍在说话。每个 ${segmentSeconds} 秒段都以自然完整的句法边界收尾,不把半个词、未完短语或待补 CTA 留给另一次模型调用。
67
95
  - 这些规则只改变当前已选脚本的内容表达;不新增候选或模型阶段,不改严格输出 schema、首帧/分镜媒体依赖、收费、队列、重试或归档。`;
68
96
  }
69
97
  /** Missing/unknown versions keep historical tasks on their exact original prompt. */
@@ -170,7 +198,8 @@ export function flowCContentAdvisories(jobs, strategy, options = {}) {
170
198
  /**
171
199
  * A deliberately narrower pre-delivery repair trigger than the public pacing
172
200
  * advisory. It only covers explicit English/Spanish text that is both very fast
173
- * and materially over the normal two-words-per-second writing budget.
201
+ * and materially over a quick three-words-per-second writing budget. Normal
202
+ * quick speech remains advisory, and visual cuts never become speech deadlines.
174
203
  */
175
204
  export function flowCVoicePacingRepairIssues(jobs, options = {}) {
176
205
  if (!Array.isArray(jobs))
@@ -183,11 +212,11 @@ export function flowCVoicePacingRepairIssues(jobs, options = {}) {
183
212
  const segments = Array.isArray(job.segments) ? job.segments : job.segment ? [job.segment] : [];
184
213
  for (const [segmentIndex, segmentValue] of segments.entries()) {
185
214
  const shots = Array.isArray(object(segmentValue).shots) ? object(segmentValue).shots.map(object) : [];
186
- for (const [shotIndex, shot] of shots.entries()) {
187
- const pacing = voicePacingMeasurement(shot.voiceover, Number(shot.endSeconds) - Number(shot.startSeconds), options.targetLanguage);
188
- if (!pacing || pacing.wordCount / pacing.durationSeconds < FLOW_C_VOICE_PACING_REPAIR_MIN_WORDS_PER_SECOND || pacing.wordCount - pacing.suggestedMaxWords < FLOW_C_VOICE_PACING_REPAIR_MIN_EXCESS_WORDS)
215
+ for (const run of continuousVoicePacingRuns(shots, options.targetLanguage)) {
216
+ const suggestedMaxWords = Math.floor(run.durationSeconds * FLOW_C_VOICE_PACING_QUICK_WORDS_PER_SECOND);
217
+ if (run.wordCount / run.durationSeconds <= FLOW_C_VOICE_PACING_REPAIR_MIN_WORDS_PER_SECOND || run.wordCount - suggestedMaxWords < FLOW_C_VOICE_PACING_REPAIR_MIN_EXCESS_WORDS)
189
218
  continue;
190
- issues.push({ ordinal: Number(job.ordinal), code: "voice_pacing", segment: segmentIndex + 1, shot: shotIndex + 1, ...pacing });
219
+ issues.push({ ordinal: Number(job.ordinal), code: "voice_pacing", segment: segmentIndex + 1, ...run, suggestedMaxWords });
191
220
  }
192
221
  }
193
222
  }
@@ -235,13 +264,14 @@ export function flowCVoicePacingRepairPrompt(jobs, options = {}) {
235
264
  const issues = flowCVoicePacingRepairIssues(values, { targetLanguage: options.targetLanguage });
236
265
  const issueOrdinals = [...new Set(issues.map((issue) => issue.ordinal))];
237
266
  const frameworkOrdinals = [...new Set((Array.isArray(options.frameworkOrdinals) ? options.frameworkOrdinals : []).map(Number).filter((ordinal) => issueOrdinals.includes(ordinal)))];
267
+ const segmentSeconds = options.segmentSeconds === 15 ? 15 : 10;
238
268
  const payload = values.filter((value) => issueOrdinals.includes(Number(object(value).ordinal))).map(flowCVoicePacingRepairScaffold);
239
- return `这是 Flow C 首次回传前唯一一次、仅针对 ordinal ${JSON.stringify(issueOrdinals)} 的短镜口播定向修复。目标口播语言保持为 ${text(options.targetLanguage, 160) || "原稿的显式目标语言"}。只返回下方完整 strict jobs,不调用工具、不创建媒体、不输出分析或新增字段。
269
+ return `这是 Flow C 首次回传前唯一一次、仅针对 ordinal ${JSON.stringify(issueOrdinals)} 的极端过密口播定向修复。普通偏密与适度快语速只作提示,无需修复。目标口播语言保持为 ${text(options.targetLanguage, 160) || "原稿的显式目标语言"}。只返回下方完整 strict jobs,不调用工具、不创建媒体、不输出分析或新增字段。
240
270
  - 只允许修改每个 shot.voiceover;逐字复制其它所有字段,包括 ordinal/productIndex/sellingFormId、voiceProfile、openingState、segment/segments 数量、voiceCue、shots 数量和顺序、startSeconds/endSeconds、visual、onScreenText、evidence、soundBgm、emotionalNote 与 endingState。不得改画面、时轴、商品、事实、用户框架、所选结构、分段承接或末帧。
241
- - 保留原口播的核心购买理由、画面对应事实、语气、CTA 意图和目标语言。先把模型自行增加的赘词压成能自然说完的短句,再按完整词组或自然分句重分配到展示相关动作的镜头;不得截断单词、留下未完句、提高语速或把超载片段简单改成 none。若一个原本有口播的局部 10 秒段修后完全静默,视为失败。
242
- - 英语/西语逐镜以约 2 词/秒为写作目标并留呼吸;当前硬修复命中位置:${JSON.stringify(issues.map(({ ordinal, segment, shot, wordCount, suggestedMaxWords, durationSeconds }) => ({ ordinal, segment, shot, wordCount, suggestedMaxWords, durationSeconds })))}。不能用同段其它静默镜头抵消当前短镜超载。
243
- - 用户逐字框架 ordinal ${JSON.stringify(frameworkOrdinals)}:所有原口播文字与顺序必须保持,不能删、换词或压缩,只能在同一局部 10 秒段内按完整自然短语重新分配到语义相关、时长足够的镜头;无法容纳就原样返回,让 Agent 明确交给人工处理。
244
- - 其它 ordinal 可以压缩模型自增措辞,但不能通过删除整段口播来消除告警。每个 10 秒段仍须在自然句法边界收尾,segmentVoiceovers 与渲染 script 将由 Agent 从最终逐镜 voiceover 确定性重建。
271
+ - 保留原口播的核心购买理由、画面对应事实、语气、CTA 意图和目标语言。先把模型自行增加的赘词压成能自然说完的短句,再按完整词组或自然分句重分配到展示相关动作的镜头;允许适度快语速但必须清晰,不能夸张赶话、截断单词、留下未完句或把超载片段简单改成 none。若一个原本有口播的局部 ${segmentSeconds} 秒段修后完全静默,视为失败。
272
+ - 英语/西语以约 2–3 词/秒作为自然到轻快表达的参考,不是固定配额;连续有声镜头整体超过 4 词/秒且明显超出轻快预算才进入此次修复。当前命中范围(shot 至 endShot):${JSON.stringify(issues.map(({ ordinal, segment, shot, endShot, wordCount, suggestedMaxWords, durationSeconds }) => ({ ordinal, segment, shot, endShot, wordCount, suggestedMaxWords, durationSeconds })))}。镜头切换不强制口播停顿;允许同段相邻有声镜头之间自然延续,不能把明确静默镜头或下一独立段的时长计入口播预算。
273
+ - 用户逐字框架 ordinal ${JSON.stringify(frameworkOrdinals)}:所有原口播文字与顺序必须保持,不能删、换词或压缩,只能在同一局部 ${segmentSeconds} 秒段内按完整自然短语重新分配到语义相关、时长足够的镜头;无法容纳就原样返回,让 Agent 明确交给人工处理。
274
+ - 其它 ordinal 可以压缩模型自增措辞,但不能通过删除整段口播来消除告警。每个 ${segmentSeconds} 秒段仍须在自然句法边界收尾,segmentVoiceovers 与渲染 script 将由 Agent 从最终逐镜 voiceover 确定性重建。
245
275
  待修复的已校验原稿:${JSON.stringify({ jobs: payload })}`;
246
276
  }
247
277
  export function flowCContentMethodPrompt(strategy, options) {
@@ -256,6 +286,9 @@ export function flowCContentMethodPrompt(strategy, options) {
256
286
  const writingReview = flowCContentWritingReviewPrompt(strategy, { frameworkOrdinals: options.frameworkOrdinals });
257
287
  const montageOrdinals = [...new Set((Array.isArray(options.montageOrdinals) ? options.montageOrdinals : []).map(Number).filter((ordinal) => Number.isInteger(ordinal) && options.ordinals.includes(ordinal)))];
258
288
  const ordinaryOrdinals = options.ordinals.filter((ordinal) => !montageOrdinals.includes(ordinal));
289
+ const segmentSeconds = options.segmentSeconds === 15 ? 15 : 10;
290
+ const longDurationLabel = segmentSeconds === 15 ? "30秒双段" : "20/30秒";
291
+ const segmentPacingRule = `整段${segmentSeconds}秒按自然或轻快语速留足动作与呼吸,可以更少,不是最低字数要求`;
259
292
  const scenarioRule = montageOrdinals.length
260
293
  ? `1. 本条“先明确谁在生活节点遇到麻烦/需求”的剧情组织只适用于其余普通脚本 ordinal ${JSON.stringify(ordinaryOrdinals)};原创混剪 ordinal ${JSON.stringify(montageOrdinals)} 不强制痛点、麻烦、待解决问题或人物反转,可以从商品事实支持的好结果、真实使用动作或可见细节直接开场。普通脚本再选择地点里的动作坐标与必要可见物件;两类都用现有 shot.visual 写出具体微场景,不用“某人在家里”或泛气氛替代。人物是普通创作者/情景角色;真实身份、经历、用户证言、专家或权威背书只能来自明确提供的事实。缺非关键创意细节时用保守日常设定软适配,不追问、不拒绝、不编新事实。`
261
294
  : "1. 先明确谁在什么生活节点遇到什么具体麻烦/需求,再选择地点里的动作坐标与必要可见物件;用现有 shot.visual 写出微场景,不用“某人在家里”或泛气氛替代。人物是普通创作者/情景角色;真实身份、经历、用户证言、专家或权威背书只能来自明确提供的事实。缺非关键创意细节时用保守日常设定软适配,不追问、不拒绝、不编新事实。";
@@ -267,8 +300,8 @@ ${diversity}
267
300
  ${writingReview}
268
301
  ${scenarioRule}
269
302
  ${openingRule}
270
- 3. 分开检查叙事段落逻辑、每镜目的与口播呼吸节奏:段落负责铺垫/证明/收束,镜头负责展示动作与证据,一句口播不必切一镜、一镜也不必念完一段。保留选中蓝图的因果顺序、节拍与镜头能量;仍为每段局部0–10秒、1–8镜,20/30秒连续关系和三种媒体共同内容契约不变。
271
- 4. 自检上方已定稿的目标语言的自然短句,不再按镜头补新台词。逐镜按实际时长 endSeconds − startSeconds 检查,先为关键动作/可见结果留静默与呼吸。仅英语、西语等通常按空格分词的语言,以写作起点粗估约2词/秒,动作/结果镜头更少:1.5秒约2–3词,不塞完整8词问句;2秒约3–4词,不塞10词CTA;2.6秒约4–5词,不塞13词整句。整段10秒约12–20词只是起点,可以更少,不是最低字数要求;全段词数够少也不能把口播挤在一两个短镜头,不能借其它静默镜头的时长冲抵当前镜头超载。若用户锁定对白需要更多时间,先延长承载它的镜头并压缩无声过渡或合并相邻同动作镜头;不得改写锁定词,也不得先把它塞进短镜头再用后续静默冲抵。锁定对白分配妥当后才可加入其它口播,剩余时长不足就让其它镜头保持 none。不能套用到中文、日语等其它语言,不套统一英语词数或固定八秒模板。这是同轮软预算,不是语言验收拒绝条件或新重写环节;只在用户锁定内容之外收窄意图、缩短句子,不得提高语速硬塞。voiceProfile.speakingRate/pauseHabit 与 voiceCue 要符合实际可说完的语速,不得标成 unhurried/慢速却塞满台词,也不能用 brisk 掩盖超载;emotionalNote 只写镜头目的/情绪转折。不输出计算、推理或预算报告。
272
- 5. contentDirection 只细化既有蓝图可替换的人物、微场景、措辞和执行槽位,不改变商品身份、纹理文字、能力证据、0–10秒分段或媒体制作方式。creativeBrief 始终最高优先;用户框架 ordinal ${JSON.stringify(options.frameworkOrdinals)} 的开头、事件顺序、核心剧情和结尾不可被方向卡/避重覆盖,只能在其留白处具体化。
303
+ 3. 分开检查叙事段落逻辑、每镜目的与口播呼吸节奏:段落负责铺垫/证明/收束,镜头负责展示动作与证据,一句口播不必切一镜、一镜也不必念完一段。保留选中蓝图的因果顺序、节拍与镜头能量;仍为每段局部0–${segmentSeconds}秒、1–8镜,${longDurationLabel}连续关系和三种媒体共同内容契约不变。
304
+ 4. 自检上方已定稿的目标语言的自然短句,不再按镜头补新台词。逐镜按实际时长 endSeconds − startSeconds 检查,先为关键动作/可见结果留静默与呼吸;镜头切换不强制口播停顿,相邻有声镜头可连续说完一句。仅英语、西语等通常按空格分词的语言,约2–3词/秒是自然到轻快表达的写作参考,允许偶尔偏密和适度加快语速,只要清楚、符合画面、没有夸张赶话。${segmentPacingRule}。不要只因为某个短镜的词数较高而重写或打断整批;只对连续有声范围仍超过4词/秒且明显超量的极端情况收窄模型自增赘句。明确标为 none 的镜头和下一独立段不能计入口播时长。若用户锁定对白需要更多时间,先延长承载它的镜头并压缩无声过渡或合并相邻同动作镜头;不得改写锁定词。锁定对白分配妥当后才可加入其它口播,剩余时长不足就让其它镜头保持 none。不能套用到中文、日语等其它语言,不套统一英语词数或固定八秒模板。这是同轮软预算,不是语言验收拒绝条件或新重写环节;口播与画面脚本在同一次返回中完成。voiceProfile.speakingRate/pauseHabit 与 voiceCue 要如实写明 natural brisk-but-clear 等实际语速,不得标成 unhurried/慢速却塞满台词;emotionalNote 只写镜头目的/情绪转折。不输出计算、推理或预算报告。
305
+ 5. contentDirection 只细化既有蓝图可替换的人物、微场景、措辞和执行槽位,不改变商品身份、纹理文字、能力证据、0–${segmentSeconds}秒分段或媒体制作方式。creativeBrief 始终最高优先;用户框架 ordinal ${JSON.stringify(options.frameworkOrdinals)} 的开头、事件顺序、核心剧情和结尾不可被方向卡/避重覆盖,只能在其留白处具体化。
273
306
  返回前按以上内容要求自检,修正能在本次写作中修正的空泛描述。自检不是新验收闸门;只输出原严格 schema 的既有字段,不输出推理、自检报告、contentDirection 或其它新增字段。\n`;
274
307
  }
@@ -12,7 +12,7 @@ export declare const FLOW_C_VOICE_PACING_REVIEW_REQUIRED = "FLOW_C_VOICE_PACING_
12
12
  export declare const FLOW_C_LEGACY_DIRECT_CONTRACT_VERSION = "flow-c-template-direct-v2";
13
13
  export declare const FLOW_C_PRODUCT_PROFILE_DIRECT_CONTRACT_VERSION = "flow-c-product-profile-direct-v1";
14
14
  export declare const FLOW_C_CREATIVE_SOURCE_DIRECT_CONTRACT_VERSION = "flow-c-creative-source-direct-v1";
15
- type ScriptStatus = "queued" | "running" | "complete" | "error" | "expired";
15
+ type ScriptStatus = "queued" | "running" | "complete" | "review" | "error" | "expired";
16
16
  type DownloadStatus = "waiting" | "running" | "complete" | "error" | "expired";
17
17
  type ScriptRecord = {
18
18
  id: string;
@@ -36,6 +36,12 @@ type ScriptRecord = {
36
36
  candidateRevision: string;
37
37
  attempts: number;
38
38
  }>;
39
+ /** Only these failed revisions are excluded from automatic waves; clean siblings keep running. */
40
+ voicePacingReviewHolds?: Array<{
41
+ ordinal: number;
42
+ candidateRevision: string;
43
+ reason: string;
44
+ }>;
39
45
  contentStrategy?: FlowCContentStrategy;
40
46
  contentSummaries?: FlowCContentSummary[];
41
47
  contentAdvisories?: FlowCContentAdvisory[];
@@ -143,7 +149,8 @@ type ScriptTask = {
143
149
  creative_strategy?: unknown;
144
150
  content_recent_scripts?: FlowCContentSummary[];
145
151
  script_source_default?: FlowCScriptSource;
146
- duration_seconds?: 10 | 20 | 30;
152
+ duration_seconds?: 10 | 15 | 20 | 30;
153
+ video_model_key?: "veo-omni-flash" | "seedance-2.0-mini-15s" | "seedance-2.0-fast-15s";
147
154
  script_output_contract_version?: string;
148
155
  storyboard_layout_version?: StoryboardLayoutVersion;
149
156
  storyboardLayoutVersion?: StoryboardLayoutVersion;
@@ -227,6 +234,8 @@ export declare class WorkflowManager {
227
234
  status: ScriptStatus;
228
235
  requestedCount: number;
229
236
  received: number;
237
+ reviewOrdinals: number[];
238
+ reviewCount: number;
230
239
  threadId: string | undefined;
231
240
  chunkSize: number | null;
232
241
  activeChunks: number;
@@ -244,6 +253,8 @@ export declare class WorkflowManager {
244
253
  status: ScriptStatus;
245
254
  requestedCount: number;
246
255
  received: number;
256
+ reviewOrdinals: number[];
257
+ reviewCount: number;
247
258
  threadId: string | undefined;
248
259
  chunkSize: number | null;
249
260
  activeChunks: number;
@@ -261,6 +272,8 @@ export declare class WorkflowManager {
261
272
  status: ScriptStatus;
262
273
  requestedCount: number;
263
274
  received: number;
275
+ reviewOrdinals: number[];
276
+ reviewCount: number;
264
277
  threadId: string | undefined;
265
278
  chunkSize: number | null;
266
279
  activeChunks: number;
@@ -408,6 +421,7 @@ export declare class WorkflowManager {
408
421
  * restart or response loss can never replay an overcrowded draft as accepted.
409
422
  */
410
423
  private repairVoicePacingJobs;
424
+ private holdVoicePacingReview;
411
425
  private runVoicePacingRepairTurn;
412
426
  /** Nonblocking, text-free diagnostics for newly generated policy scripts only. */
413
427
  private noteScriptContentAdvisories;
@@ -435,7 +449,7 @@ export declare function voicePacingRepairAttemptCount(record: Pick<ScriptRecord,
435
449
  * field comes from the locally validated original and rendered projections are
436
450
  * rebuilt from that one final voice source.
437
451
  */
438
- export declare function applyFlowCVoicePacingRepair(originalValue: unknown, candidateValue: unknown, preserveExactTranscript?: boolean): DraftJob;
452
+ export declare function applyFlowCVoicePacingRepair(originalValue: unknown, candidateValue: unknown, preserveExactTranscript?: boolean, segmentSeconds?: 10 | 15): DraftJob;
439
453
  /** A deterministic response-format failure stops fallback isolation immediately. */
440
454
  export declare function terminalScriptChunkError(results: Array<{
441
455
  error?: string;
@@ -446,7 +460,7 @@ export declare function terminalScriptChunkFailure<T extends {
446
460
  terminal?: boolean;
447
461
  terminalKind?: ScriptChunkResult["terminalKind"];
448
462
  affectedOrdinals?: number[];
449
- }>(results: T[], receivedOrdinals?: number[]): T | undefined;
463
+ }>(results: T[], receivedOrdinals?: number[]): T;
450
464
  export declare function scriptCreativeReplanOrdinals(results: unknown[]): number[];
451
465
  /** Keep a mixed reset signal after an exact-duplicate rewrite finishes. */
452
466
  export declare function preserveScriptRecoveryReplans(result: ScriptChunkResult, error: unknown): ScriptChunkResult;
@@ -530,7 +544,7 @@ export declare function selectedCandidatePlan(value: SelectedCandidate | undefin
530
544
  * 已选创意永远优先进入脚本扩写;只有当前没有可写脚本时才生成下一小波候选。
531
545
  * 每次最多占用受控 worker 数量的子批,避免把整批候选提前塞满 worker 队列。
532
546
  */
533
- export declare function nextScriptPipelineWave(task: Pick<ScriptTask, "requested_count" | "selected_candidates">, receivedOrdinals: number[], durationSeconds: 10 | 20 | 30, scriptChunkSize: number, candidateChunkSize?: number, concurrency?: number): {
547
+ export declare function nextScriptPipelineWave(task: Pick<ScriptTask, "requested_count" | "selected_candidates">, receivedOrdinals: number[], durationSeconds: 10 | 15 | 20 | 30, scriptChunkSize: number, candidateChunkSize?: number, concurrency?: number): {
534
548
  stage: "script";
535
549
  chunks: number[][];
536
550
  } | {
@@ -9,13 +9,17 @@ import { FLOW_C_CODEX_MODEL, FLOW_C_CODEX_REASONING_EFFORT, FLOW_C_CODEX_WORKER_
9
9
  import { CONFIG_DIR, ensureSiteWorkspace } from "../config.js";
10
10
  import { logger } from "../utils/logger.js";
11
11
  import { windowsPowerShellExecutable } from "../utils/windows.js";
12
- import { FLOW_C_SCRIPT_CHUNK_MAX, flowCScriptChunks, flowCScriptChunkSizes } from "./constants.js";
12
+ import { FLOW_C_SCRIPT_CHUNK_MAX, FLOW_C_VIDEO_MODEL_CONTRACT_VERSION, flowCScriptChunks, flowCScriptChunkSizes } from "./constants.js";
13
13
  import { FLOW_C_CREATIVE_CANDIDATE_CONTRACT_VERSION, flowCCreativeCandidateOutputSchema, parseFlowCCreativeCandidateOutput } from "./creative-candidates.js";
14
14
  import { FLOW_C_LEGACY_PRODUCT_EXECUTION_PROFILE_CONTRACT_VERSION, FLOW_C_PRODUCT_EXECUTION_PROFILE_CONTRACT_VERSION, flowCProductExecutionProfileOutputSchema, parseFlowCProductExecutionProfileOutput } from "./product-profile.js";
15
15
  import { flowCScriptOutputSchema, parseFlowCScriptOutput } from "./script-output.js";
16
16
  import { commerceJson, CommerceRequestError } from "./commerce-http.js";
17
17
  import { FLOW_C_CONTENT_STRATEGY_VERSION, FLOW_C_GENERATED_MONTAGE_STYLE, FLOW_C_GENERATED_MONTAGE_VERSION, FLOW_C_GENERATED_MONTAGE_VERSION_UNSUPPORTED, flowCContentAdvisories, flowCContentDirection, flowCContentMethodPrompt, flowCContentStrategy, flowCGeneratedMontage, flowCGeneratedMontagePrompt, flowCVoicePacingRepairIssues, flowCVoicePacingRepairPrompt, flowCVoicePacingRepairScaffold, mergeFlowCContentSummaries } from "./content-method.js";
18
18
  const STATE_FILE = path.join(CONFIG_DIR, "workflow-state.json");
19
+ const FLOW_C_AGENT_CAPABILITY_HEADERS = {
20
+ "x-flow-c-montage-version": FLOW_C_GENERATED_MONTAGE_VERSION,
21
+ "x-flow-c-video-contract-version": FLOW_C_VIDEO_MODEL_CONTRACT_VERSION,
22
+ };
19
23
  export const FLOW_C_CODEX_TURN_TIMEOUT_MS = 8 * 60 * 1000;
20
24
  export const FLOW_C_SELECTED_BLUEPRINT_PROMPT_MAX_CHARS = 45_000;
21
25
  export const FLOW_C_SCRIPT_REWRITE_MAX_ATTEMPTS = 2;
@@ -33,6 +37,9 @@ function productProfileContractForTask(task) {
33
37
  ? FLOW_C_PRODUCT_EXECUTION_PROFILE_CONTRACT_VERSION
34
38
  : FLOW_C_LEGACY_PRODUCT_EXECUTION_PROFILE_CONTRACT_VERSION;
35
39
  }
40
+ function flowCTaskSegmentSeconds(task) {
41
+ return String(task.video_model_key || "veo-omni-flash").startsWith("seedance-2.0-") ? 15 : 10;
42
+ }
36
43
  /** 本机持久化的 Flow C 控制器:脚本交给本机 Codex,视频直接落盘。 */
37
44
  export class WorkflowManager {
38
45
  config;
@@ -74,6 +81,7 @@ export class WorkflowManager {
74
81
  pendingScriptJobs: previous?.pendingScriptJobs || [],
75
82
  ...(previous?.voicePacingReviewJobs ? { voicePacingReviewJobs: previous.voicePacingReviewJobs } : {}),
76
83
  ...(previous?.voicePacingRepairAttempts ? { voicePacingRepairAttempts: previous.voicePacingRepairAttempts } : {}),
84
+ ...(previous?.voicePacingReviewHolds ? { voicePacingReviewHolds: previous.voicePacingReviewHolds } : {}),
77
85
  ...(previous?.contentAdvisories ? { contentAdvisories: previous.contentAdvisories } : {}),
78
86
  lastFailure: previous?.lastFailure,
79
87
  priorityAt: now(),
@@ -116,7 +124,7 @@ export class WorkflowManager {
116
124
  /** MCP 读取服务端持久化的完整任务,不向模型暴露令牌。 */
117
125
  async scriptTask(idValue) {
118
126
  const record = this.scriptRecord(workflowId(idValue, "脚本交接 ID"));
119
- const data = await commerceJson(`${record.apiBase}/workflow-script-handoffs/${encodeURIComponent(record.id)}/task`, record.accessToken, "x-workflow-handoff-token", { headers: { "x-flow-c-montage-version": FLOW_C_GENERATED_MONTAGE_VERSION } }, this.scriptRequestOptions(record));
127
+ const data = await commerceJson(`${record.apiBase}/workflow-script-handoffs/${encodeURIComponent(record.id)}/task`, record.accessToken, "x-workflow-handoff-token", { headers: FLOW_C_AGENT_CAPABILITY_HEADERS }, this.scriptRequestOptions(record));
120
128
  const task = data.handoff;
121
129
  for (const candidate of task.selected_candidates || [])
122
130
  flowCGeneratedMontage(candidate);
@@ -135,6 +143,7 @@ export class WorkflowManager {
135
143
  if (!record.voicePacingReviewJobs.length)
136
144
  delete record.voicePacingReviewJobs;
137
145
  pruneVoicePacingRepairAttempts(record);
146
+ reconcileVoicePacingReviewHolds(record, task);
138
147
  record.expiresAt = task.expires_at;
139
148
  record.updatedAt = now();
140
149
  this.save();
@@ -152,7 +161,7 @@ export class WorkflowManager {
152
161
  pending.set(job.ordinal, structuredClone(job));
153
162
  record.pendingScriptJobs = [...pending.values()].sort((left, right) => left.ordinal - right.ordinal);
154
163
  this.save();
155
- const data = await commerceJson(`${record.apiBase}/workflow-script-handoffs/${encodeURIComponent(record.id)}/draft-chunks`, record.accessToken, "x-workflow-handoff-token", { method: "POST", headers: { "x-flow-c-montage-version": FLOW_C_GENERATED_MONTAGE_VERSION }, body: JSON.stringify({ jobs }) }, this.scriptRequestOptions(record));
164
+ const data = await commerceJson(`${record.apiBase}/workflow-script-handoffs/${encodeURIComponent(record.id)}/draft-chunks`, record.accessToken, "x-workflow-handoff-token", { method: "POST", headers: FLOW_C_AGENT_CAPABILITY_HEADERS, body: JSON.stringify({ jobs }) }, this.scriptRequestOptions(record));
156
165
  if (Array.isArray(data.receivedOrdinals))
157
166
  record.receivedOrdinals = [...new Set([...record.receivedOrdinals, ...data.receivedOrdinals.map(Number).filter(Number.isInteger)])].sort((left, right) => left - right);
158
167
  else {
@@ -170,6 +179,7 @@ export class WorkflowManager {
170
179
  if (!record.voicePacingReviewJobs.length)
171
180
  delete record.voicePacingReviewJobs;
172
181
  pruneVoicePacingRepairAttempts(record);
182
+ reconcileVoicePacingReviewHolds(record);
173
183
  record.status = data.status === "ready" ? "complete" : "running";
174
184
  record.message = data.status === "ready"
175
185
  ? flowCContentStrategy(record.contentStrategy) ? `全部 ${record.requestedCount} 条脚本已回传(内容语义仍需审阅)` : `全部 ${record.requestedCount} 条高质量脚本已回传`
@@ -215,7 +225,7 @@ export class WorkflowManager {
215
225
  activeScripts: workers.active,
216
226
  scriptConcurrencyLimit: workers.limit,
217
227
  queuedScripts: records.filter((record) => record.status === "queued" || record.status === "running").length,
218
- blockedScripts: records.filter((record) => record.status === "error").length,
228
+ blockedScripts: records.filter((record) => record.status === "error" || record.status === "review").length,
219
229
  };
220
230
  }
221
231
  startDownloadDirectorySelection() {
@@ -329,11 +339,12 @@ export class WorkflowManager {
329
339
  throw new Error("这是旧版候选/执行绑定脚本任务,已停止继续写入;请在网页放弃该任务并用新版直接蓝图重新创建");
330
340
  const workspace = ensureSiteWorkspace(this.config);
331
341
  const durationSeconds = Number(task.duration_seconds || 10);
342
+ const segmentSeconds = flowCTaskSegmentSeconds(task);
332
343
  const chunkSizes = flowCScriptChunkSizes(durationSeconds);
333
344
  // Fail locally before starting any worker if a future schema edit
334
345
  // violates strict response-format invariants.
335
346
  for (const chunkSize of new Set(chunkSizes))
336
- flowCScriptOutputSchema(durationSeconds, chunkSize);
347
+ flowCScriptOutputSchema(durationSeconds, chunkSize, segmentSeconds);
337
348
  if (isProductProfileDirectContract(task.script_output_contract_version))
338
349
  flowCProductExecutionProfileOutputSchema(1, productProfileContractForTask(task));
339
350
  record.activeChunks = 0;
@@ -345,10 +356,14 @@ export class WorkflowManager {
345
356
  const creativeReplanAttempts = new Map();
346
357
  while (record.receivedOrdinals.length < task.requested_count) {
347
358
  task = await this.scriptTask(id);
359
+ const settledOrdinals = [...record.receivedOrdinals, ...voicePacingHeldOrdinals(record)];
360
+ if (!missingOrdinals(task.requested_count, settledOrdinals).length)
361
+ break;
348
362
  const selectedBefore = selectedCandidateOrdinals(task);
349
- const wave = nextScriptPipelineWave(task, record.receivedOrdinals, durationSeconds, chunkSizes[chunkSizeIndex], candidateChunkSize);
363
+ const wave = nextScriptPipelineWave(task, settledOrdinals, durationSeconds, chunkSizes[chunkSizeIndex], candidateChunkSize);
350
364
  if (wave.stage === "candidate") {
351
365
  const receivedBefore = record.receivedOrdinals.length;
366
+ const heldBefore = voicePacingHeldOrdinals(record).length;
352
367
  record.message = `本机 Codex 正在选择下一小批创意(${selectedBefore.length}/${task.requested_count});选好后立即写对应脚本`;
353
368
  record.activeChunks = 0;
354
369
  record.updatedAt = now();
@@ -367,10 +382,8 @@ export class WorkflowManager {
367
382
  }));
368
383
  const results = pipelineResults.flat();
369
384
  task = await this.scriptTask(id);
370
- const terminalFailure = terminalScriptChunkFailure(results, this.scriptRecord(id).receivedOrdinals);
385
+ const terminalFailure = terminalScriptChunkFailure(results.filter((result) => result.terminalKind !== "review"), this.scriptRecord(id).receivedOrdinals);
371
386
  if (terminalFailure) {
372
- if (terminalFailure.terminalKind === "review")
373
- throw new Error(terminalFailure.error);
374
387
  if (terminalFailure.terminalKind === "delivery")
375
388
  throw new Error(terminalFailure.error);
376
389
  if (terminalFailure.terminalKind === "transport")
@@ -400,7 +413,7 @@ export class WorkflowManager {
400
413
  }
401
414
  if (record.receivedOrdinals.length > receivedBefore)
402
415
  chunkSizeIndex = 0;
403
- if (selectedCandidateOrdinals(task).length > selectedBefore.length) {
416
+ if (selectedCandidateOrdinals(task).length > selectedBefore.length || voicePacingHeldOrdinals(record).length > heldBefore) {
404
417
  candidateChunkSize = 2;
405
418
  continue;
406
419
  }
@@ -412,6 +425,7 @@ export class WorkflowManager {
412
425
  throw new Error(`创意候选阶段已隔离到单条仍失败(${lastError}),请点击重试`);
413
426
  }
414
427
  const before = record.receivedOrdinals.length;
428
+ const heldBefore = voicePacingHeldOrdinals(record).length;
415
429
  const chunkSize = chunkSizes[chunkSizeIndex];
416
430
  record.chunkSize = chunkSize;
417
431
  record.attempts += wave.chunks.length;
@@ -420,10 +434,8 @@ export class WorkflowManager {
420
434
  this.save();
421
435
  const results = await Promise.all(wave.chunks.map((ordinals) => this.runScriptChunk(id, task, ordinals, workspace.workspacePath)));
422
436
  task = await this.scriptTask(id);
423
- const terminalFailure = terminalScriptChunkFailure(results, this.scriptRecord(id).receivedOrdinals);
437
+ const terminalFailure = terminalScriptChunkFailure(results.filter((result) => result.terminalKind !== "review"), this.scriptRecord(id).receivedOrdinals);
424
438
  if (terminalFailure) {
425
- if (terminalFailure.terminalKind === "review")
426
- throw new Error(terminalFailure.error);
427
439
  if (terminalFailure.terminalKind === "delivery")
428
440
  throw new Error(terminalFailure.error);
429
441
  if (terminalFailure.terminalKind === "transport")
@@ -451,7 +463,7 @@ export class WorkflowManager {
451
463
  chunkSizeIndex = 0;
452
464
  continue;
453
465
  }
454
- const progressed = record.receivedOrdinals.length > before;
466
+ const progressed = record.receivedOrdinals.length > before || voicePacingHeldOrdinals(record).length > heldBefore;
455
467
  if (progressed) {
456
468
  chunkSizeIndex = 0;
457
469
  continue;
@@ -471,6 +483,10 @@ export class WorkflowManager {
471
483
  record.status = "complete";
472
484
  record.message = flowCContentStrategy(task.creative_strategy) ? `全部 ${task.requested_count} 条脚本已回传(内容语义仍需审阅)` : `全部 ${task.requested_count} 条高质量脚本已回传`;
473
485
  }
486
+ else if (voicePacingHeldOrdinals(record).length && !missingOrdinals(task.requested_count, [...record.receivedOrdinals, ...voicePacingHeldOrdinals(record)]).length) {
487
+ record.status = "review";
488
+ record.message = `已回传 ${record.receivedOrdinals.length}/${task.requested_count} 条;第 ${voicePacingHeldOrdinals(record).join("、")} 条口播仍明显超出可用时长,已单独保留待调整,其余脚本已处理完成。手动重试只处理这些未回传稿,已回传稿保持不变`;
489
+ }
474
490
  else
475
491
  throw new Error(`中心校验尚未通过(${record.receivedOrdinals.length}/${task.requested_count} 条),请点击重试`);
476
492
  }
@@ -655,6 +671,16 @@ export class WorkflowManager {
655
671
  const candidate = selectedForRecovery.get(job.ordinal);
656
672
  return String(job.expectedCandidateRevision || "") === String(candidate?.candidateRevision || "");
657
673
  });
674
+ // A newer pacing policy may accept an untouched old draft. Deliver
675
+ // that exact draft rather than regenerating its script or speech.
676
+ const acceptedStoredReview = storedReview.filter((job) => !flowCVoicePacingRepairIssues([job], { targetLanguage }).length);
677
+ if (acceptedStoredReview.length) {
678
+ this.noteScriptContentAdvisories(id, task, acceptedStoredReview);
679
+ await this.submitGeneratedScriptJobs(id, acceptedStoredReview);
680
+ ordinals = ordinals.filter((ordinal) => !this.scriptRecord(id).receivedOrdinals.includes(ordinal));
681
+ if (!ordinals.length)
682
+ return { terminal: false };
683
+ }
658
684
  const repairableStoredReview = storedReview.filter((job) => flowCVoicePacingRepairIssues([job], { targetLanguage }).length > 0);
659
685
  if (repairableStoredReview.length) {
660
686
  const reviewResult = await this.repairVoicePacingJobs(id, task, repairableStoredReview, cwd);
@@ -671,6 +697,7 @@ export class WorkflowManager {
671
697
  delete activeRecord.voicePacingReviewJobs;
672
698
  pruneVoicePacingRepairAttempts(activeRecord);
673
699
  const durationSeconds = Number(task.duration_seconds || 10);
700
+ const segmentSeconds = flowCTaskSegmentSeconds(task);
674
701
  let prompt;
675
702
  try {
676
703
  const promptTask = flowCContentStrategy(task.creative_strategy)
@@ -687,7 +714,7 @@ export class WorkflowManager {
687
714
  cwd,
688
715
  permissionMode: "full",
689
716
  timeoutMs: FLOW_C_CODEX_TURN_TIMEOUT_MS,
690
- outputSchema: flowCScriptOutputSchema(durationSeconds, ordinals.length),
717
+ outputSchema: flowCScriptOutputSchema(durationSeconds, ordinals.length, segmentSeconds),
691
718
  onThread: (threadId) => { this.scriptRecord(id).threadId = threadId; this.save(); },
692
719
  onWorkerStart: () => { const record = this.scriptRecord(id); record.activeChunks = Number(record.activeChunks || 0) + 1; record.updatedAt = now(); this.save(); },
693
720
  onWorkerFinish: () => { const record = this.scriptRecord(id); record.activeChunks = Math.max(0, Number(record.activeChunks || 0) - 1); record.updatedAt = now(); this.save(); },
@@ -701,7 +728,7 @@ export class WorkflowManager {
701
728
  return { error: "Codex 未返回可用的结构化脚本", terminal: false };
702
729
  const parseStartedAt = Date.now();
703
730
  const selected = selectedCandidatesForOrdinals(task, ordinals);
704
- const jobs = parseFlowCScriptOutput(result.text, ordinals).map((job) => ({
731
+ const jobs = parseFlowCScriptOutput(result.text, ordinals, segmentSeconds).map((job) => ({
705
732
  ...job,
706
733
  sellingFormId: selected.get(job.ordinal)?.sellingFormCardId || job.sellingFormId,
707
734
  expectedCandidateRevision: selected.get(job.ordinal)?.candidateRevision,
@@ -833,14 +860,15 @@ export class WorkflowManager {
833
860
  const eligible = current.filter((job) => voicePacingRepairAttemptCount(record, job) < FLOW_C_VOICE_PACING_REPAIR_MAX_ATTEMPTS);
834
861
  const exhausted = current.filter((job) => !eligible.includes(job));
835
862
  if (!eligible.length)
836
- return voicePacingReviewFailure(exhausted.map((job) => job.ordinal), "本机已记录本次自动修复机会,后台恢复不会再次调用模型");
863
+ return this.holdVoicePacingReview(id, exhausted.map((job) => job.ordinal), "本机已记录本次自动修复机会,后台恢复不会再次调用模型");
837
864
  const localization = compactTaskLocalization(task);
838
865
  const targetLanguage = localization.targetLanguage || task.target_language || localization.targetLocale;
839
866
  const selected = selectedCandidatesForOrdinals(task, eligible.map((job) => job.ordinal));
840
867
  const frameworkOrdinals = [...selected.values()].filter(isFlowCUserFrameworkCandidate).map((candidate) => candidate.ordinal);
841
868
  const ordinals = eligible.map((job) => job.ordinal);
842
869
  const durationSeconds = Number(task.duration_seconds || 10);
843
- const prompt = flowCVoicePacingRepairPrompt(eligible, { targetLanguage, frameworkOrdinals });
870
+ const segmentSeconds = flowCTaskSegmentSeconds(task);
871
+ const prompt = flowCVoicePacingRepairPrompt(eligible, { targetLanguage, frameworkOrdinals, segmentSeconds });
844
872
  for (const job of eligible)
845
873
  recordVoicePacingRepairAttempt(record, job);
846
874
  record.message = `正在为 ordinal ${ordinals.join(", ")} 做第 1/${FLOW_C_VOICE_PACING_REPAIR_MAX_ATTEMPTS} 次短镜口播定向修复;画面、时轴与已选框架保持不变`;
@@ -848,28 +876,28 @@ export class WorkflowManager {
848
876
  this.save();
849
877
  let result;
850
878
  try {
851
- result = await this.runVoicePacingRepairTurn(id, prompt, cwd, durationSeconds, ordinals.length);
879
+ result = await this.runVoicePacingRepairTurn(id, prompt, cwd, durationSeconds, ordinals.length, segmentSeconds);
852
880
  }
853
881
  catch (error) {
854
882
  const received = this.scriptRecord(id).receivedOrdinals;
855
883
  const missing = [...exhausted.map((job) => job.ordinal), ...ordinals].filter((ordinal) => !received.includes(ordinal));
856
- return missing.length ? voicePacingReviewFailure(missing, error instanceof Error ? error.message : "口播修复回合异常") : { terminal: false };
884
+ return missing.length ? this.holdVoicePacingReview(id, missing, error instanceof Error ? error.message : "口播修复回合异常") : { terminal: false };
857
885
  }
858
886
  this.emitScriptStage(id, ordinals, "voice_repair", result.timings.queueWaitMs + result.timings.threadStartMs + result.timings.modelMs);
859
887
  const missingAfterTurn = [...exhausted.map((job) => job.ordinal), ...ordinals].filter((ordinal) => !this.scriptRecord(id).receivedOrdinals.includes(ordinal));
860
888
  if (!missingAfterTurn.length)
861
889
  return { terminal: false };
862
890
  if (!result.ok)
863
- return voicePacingReviewFailure(missingAfterTurn, result.error || "Codex 未返回口播修复稿");
891
+ return this.holdVoicePacingReview(id, missingAfterTurn, result.error || "Codex 未返回口播修复稿");
864
892
  if (!result.text)
865
- return voicePacingReviewFailure(missingAfterTurn, "Codex 未返回口播修复稿");
893
+ return this.holdVoicePacingReview(id, missingAfterTurn, "Codex 未返回口播修复稿");
866
894
  let candidates;
867
895
  try {
868
- candidates = parseFlowCScriptOutput(result.text, ordinals);
896
+ candidates = parseFlowCScriptOutput(result.text, ordinals, segmentSeconds);
869
897
  }
870
898
  catch (error) {
871
899
  const missing = missingAfterTurn.filter((ordinal) => !this.scriptRecord(id).receivedOrdinals.includes(ordinal));
872
- return missing.length ? voicePacingReviewFailure(missing, error instanceof Error ? error.message : "口播修复稿未通过结构校验") : { terminal: false };
900
+ return missing.length ? this.holdVoicePacingReview(id, missing, error instanceof Error ? error.message : "口播修复稿未通过结构校验") : { terminal: false };
873
901
  }
874
902
  const byOrdinal = new Map(candidates.map((job) => [job.ordinal, job]));
875
903
  const accepted = [];
@@ -881,10 +909,10 @@ export class WorkflowManager {
881
909
  continue;
882
910
  }
883
911
  try {
884
- const repaired = applyFlowCVoicePacingRepair(original, candidate, frameworkOrdinals.includes(original.ordinal));
912
+ const repaired = applyFlowCVoicePacingRepair(original, candidate, frameworkOrdinals.includes(original.ordinal), segmentSeconds);
885
913
  const remaining = flowCVoicePacingRepairIssues([repaired], { targetLanguage });
886
914
  if (remaining.length) {
887
- failed.set(original.ordinal, `仍有 ${remaining.length} 个明显过密短镜`);
915
+ failed.set(original.ordinal, `仍有 ${remaining.length} 处极端过密口播`);
888
916
  continue;
889
917
  }
890
918
  accepted.push(repaired);
@@ -893,6 +921,10 @@ export class WorkflowManager {
893
921
  failed.set(original.ordinal, error instanceof Error ? error.message : "修复稿改变了受保护字段");
894
922
  }
895
923
  }
924
+ // Persist failed siblings before any repaired sibling's POST. A lost
925
+ // response must retain both the exact deliverable and isolated reviews.
926
+ if (failed.size)
927
+ this.holdVoicePacingReview(id, [...failed.keys()], [...failed.entries()].map(([ordinal, reason]) => `ordinal ${ordinal}: ${reason}`).join(";"));
896
928
  const stillMissing = accepted.filter((job) => !this.scriptRecord(id).receivedOrdinals.includes(job.ordinal));
897
929
  if (stillMissing.length) {
898
930
  this.noteScriptContentAdvisories(id, task, stillMissing);
@@ -901,16 +933,32 @@ export class WorkflowManager {
901
933
  for (const ordinal of this.scriptRecord(id).receivedOrdinals)
902
934
  failed.delete(ordinal);
903
935
  if (failed.size)
904
- return voicePacingReviewFailure([...failed.keys()], [...failed.entries()].map(([ordinal, reason]) => `ordinal ${ordinal}: ${reason}`).join(";"));
936
+ return this.holdVoicePacingReview(id, [...failed.keys()], [...failed.entries()].map(([ordinal, reason]) => `ordinal ${ordinal}: ${reason}`).join(";"));
905
937
  return { terminal: false };
906
938
  }
907
- runVoicePacingRepairTurn(id, prompt, cwd, durationSeconds, count) {
939
+ holdVoicePacingReview(id, ordinals, reason) {
940
+ const record = this.scriptRecord(id);
941
+ const missing = ordinals.filter((ordinal) => !record.receivedOrdinals.includes(ordinal));
942
+ if (!missing.length)
943
+ return { terminal: false };
944
+ const holds = new Map((record.voicePacingReviewHolds || []).map((hold) => [hold.ordinal, hold]));
945
+ for (const job of record.voicePacingReviewJobs || []) {
946
+ if (missing.includes(job.ordinal))
947
+ holds.set(job.ordinal, { ordinal: job.ordinal, candidateRevision: voicePacingCandidateRevision(job), reason });
948
+ }
949
+ record.voicePacingReviewHolds = [...holds.values()].sort((left, right) => left.ordinal - right.ordinal);
950
+ record.message = `第 ${missing.join("、")} 条口播需单独调整,已保留原稿;继续处理其余脚本(已回传 ${record.receivedOrdinals.length}/${record.requestedCount} 条)`;
951
+ record.updatedAt = now();
952
+ this.save();
953
+ return voicePacingReviewFailure(missing, reason);
954
+ }
955
+ runVoicePacingRepairTurn(id, prompt, cwd, durationSeconds, count, segmentSeconds) {
908
956
  return runCodexWorkflowTurn(prompt, this.emit, {
909
957
  cwd,
910
958
  permissionMode: "full",
911
959
  timeoutMs: FLOW_C_CODEX_TURN_TIMEOUT_MS,
912
960
  ...flowCVoicePacingRepairTurnOptions(),
913
- outputSchema: flowCScriptOutputSchema(durationSeconds, count),
961
+ outputSchema: flowCScriptOutputSchema(durationSeconds, count, segmentSeconds),
914
962
  onThread: (threadId) => { this.scriptRecord(id).threadId = threadId; this.save(); },
915
963
  onWorkerStart: () => { const next = this.scriptRecord(id); next.activeChunks = Number(next.activeChunks || 0) + 1; next.updatedAt = now(); this.save(); },
916
964
  onWorkerFinish: () => { const next = this.scriptRecord(id); next.activeChunks = Math.max(0, Number(next.activeChunks || 0) - 1); next.updatedAt = now(); this.save(); },
@@ -1131,6 +1179,30 @@ function pruneVoicePacingRepairAttempts(record) {
1131
1179
  }
1132
1180
  function resetVoicePacingRepairAttempts(record) {
1133
1181
  delete record.voicePacingRepairAttempts;
1182
+ delete record.voicePacingReviewHolds;
1183
+ }
1184
+ function voicePacingHeldOrdinals(record) {
1185
+ return [...new Set((record.voicePacingReviewHolds || []).map((hold) => hold.ordinal).filter((ordinal) => !record.receivedOrdinals.includes(ordinal)))].sort((left, right) => left - right);
1186
+ }
1187
+ /** ACK and exact pending delivery always win; holds belong to one candidate revision. */
1188
+ function reconcileVoicePacingReviewHolds(record, task) {
1189
+ if (!record.voicePacingReviewHolds)
1190
+ return;
1191
+ const selected = task ? selectedCandidatesForOrdinals(task, record.voicePacingReviewHolds.map((hold) => hold.ordinal)) : undefined;
1192
+ const localization = task ? compactTaskLocalization(task) : undefined;
1193
+ const targetLanguage = localization?.targetLanguage || task?.target_language || localization?.targetLocale;
1194
+ record.voicePacingReviewHolds = record.voicePacingReviewHolds.filter((hold) => {
1195
+ if (record.receivedOrdinals.includes(hold.ordinal) || record.pendingScriptJobs?.some((job) => job.ordinal === hold.ordinal))
1196
+ return false;
1197
+ const original = record.voicePacingReviewJobs?.find((job) => job.ordinal === hold.ordinal && voicePacingCandidateRevision(job) === hold.candidateRevision);
1198
+ if (!original)
1199
+ return false;
1200
+ if (selected && String(selected.get(hold.ordinal)?.candidateRevision || "") !== hold.candidateRevision)
1201
+ return false;
1202
+ return !task || flowCVoicePacingRepairIssues([original], { targetLanguage }).length > 0;
1203
+ });
1204
+ if (!record.voicePacingReviewHolds.length)
1205
+ delete record.voicePacingReviewHolds;
1134
1206
  }
1135
1207
  function pacingSegments(value) {
1136
1208
  const job = pacingObject(value);
@@ -1167,7 +1239,7 @@ function protectedPacingProjection(value) {
1167
1239
  * field comes from the locally validated original and rendered projections are
1168
1240
  * rebuilt from that one final voice source.
1169
1241
  */
1170
- export function applyFlowCVoicePacingRepair(originalValue, candidateValue, preserveExactTranscript = false) {
1242
+ export function applyFlowCVoicePacingRepair(originalValue, candidateValue, preserveExactTranscript = false, segmentSeconds = 10) {
1171
1243
  const original = pacingObject(originalValue);
1172
1244
  const candidate = pacingObject(candidateValue);
1173
1245
  const ordinal = Number(original.ordinal);
@@ -1205,7 +1277,7 @@ export function applyFlowCVoicePacingRepair(originalValue, candidateValue, prese
1205
1277
  });
1206
1278
  const patched = Array.isArray(original.segments) ? { ...original, segments: patchedSegments } : { ...original, segment: patchedSegments[0] };
1207
1279
  const scaffold = flowCVoicePacingRepairScaffold(patched);
1208
- const rendered = parseFlowCScriptOutput(JSON.stringify({ jobs: [scaffold] }), [ordinal])[0];
1280
+ const rendered = parseFlowCScriptOutput(JSON.stringify({ jobs: [scaffold] }), [ordinal], segmentSeconds)[0];
1209
1281
  const result = { ...original, ...rendered };
1210
1282
  if (JSON.stringify(protectedPacingProjection(result)) !== JSON.stringify(protectedPacingProjection(original)))
1211
1283
  throw new Error("修复稿改变了 VO 之外的受保护字段");
@@ -1214,7 +1286,7 @@ export function applyFlowCVoicePacingRepair(originalValue, candidateValue, prese
1214
1286
  function voicePacingReviewFailure(ordinals, reason) {
1215
1287
  const scoped = [...new Set(ordinals.map(Number).filter((ordinal) => Number.isInteger(ordinal) && ordinal > 0))].sort((left, right) => left - right);
1216
1288
  return {
1217
- error: `${FLOW_C_VOICE_PACING_REVIEW_REQUIRED}: ordinal ${scoped.join(", ")} 的短镜口播在唯一一次定向修复后仍未安全落入镜头时长;原稿仅保存在本机待审区,未作为可重传稿提交。${reason}。请人工审阅,或确认逐字框架可调整后手动重试`,
1289
+ error: `${FLOW_C_VOICE_PACING_REVIEW_REQUIRED}: ordinal ${scoped.join(", ")} 的口播在唯一一次定向调整后仍需单独检查;原稿保存在本机待审区,其余脚本继续处理。${reason}。可调整后手动重试,已回传稿保持不变`,
1218
1290
  terminal: true,
1219
1291
  terminalKind: "review",
1220
1292
  affectedOrdinals: scoped,
@@ -1226,12 +1298,15 @@ export function terminalScriptChunkError(results) {
1226
1298
  }
1227
1299
  export function terminalScriptChunkFailure(results, receivedOrdinals = []) {
1228
1300
  const received = new Set(receivedOrdinals.map(Number).filter(Number.isInteger));
1229
- return results.find((result) => {
1301
+ const failures = results.filter((result) => {
1230
1302
  if (!result.terminal)
1231
1303
  return false;
1232
1304
  const affected = Array.isArray(result.affectedOrdinals) ? result.affectedOrdinals.map(Number).filter((ordinal) => Number.isInteger(ordinal) && ordinal > 0) : [];
1233
1305
  return !affected.length || affected.some((ordinal) => !received.has(ordinal));
1234
1306
  });
1307
+ // An isolated review must not hide a sibling's genuine delivery/transport
1308
+ // failure when nested revision or rewrite results are aggregated.
1309
+ return failures.find((result) => result.terminalKind !== "review") || failures[0];
1235
1310
  }
1236
1311
  export function scriptCreativeReplanOrdinals(results) {
1237
1312
  return [...new Set(results.flatMap((result) => (result && typeof result === "object" ? result.replanOrdinals || [] : [])).filter((ordinal) => Number.isInteger(ordinal) && ordinal > 0))].sort((left, right) => left - right);
@@ -1387,15 +1462,17 @@ async function productImageAttachment(url, productIndex, imageIndex) {
1387
1462
  }
1388
1463
  export function scriptChunkPrompt(id, task, ordinals, rewriteAttempt = 0) {
1389
1464
  const duration = Number(task.duration_seconds || 10);
1465
+ const segmentSeconds = flowCTaskSegmentSeconds(task);
1466
+ const videoModelName = segmentSeconds === 15 ? "Seedance" : "Omni";
1390
1467
  const products = relevantProductInputs(task, ordinals);
1391
1468
  const productFacts = scriptPromptProductFacts(products, task.product_execution_profiles || []);
1392
1469
  const selected = selectedCandidatesForOrdinals(task, ordinals);
1393
1470
  if (selected.size !== ordinals.length)
1394
1471
  throw new Error("中心尚未为当前 ordinal 完成创意选题");
1395
1472
  const generatedMontageOrdinals = [...selected.values()].filter((candidate) => flowCGeneratedMontage(candidate)).map((candidate) => candidate.ordinal);
1396
- const durationRules = duration === 10
1397
- ? "每条只输出 openingState 和一个完整 0–10 秒 segment,不生成 masterScript。"
1398
- : `每条只输出 openingState 和 ${duration / 10} 个各自 0–10 秒的 segments;Agent 会确定性合成 masterScript,不得重复输出总稿,也不得写 10–20 或 20–30 全局时轴。`;
1473
+ const durationRules = duration === segmentSeconds
1474
+ ? `每条只输出 openingState 和一个完整 0–${segmentSeconds} 秒 segment,不生成 masterScript。`
1475
+ : `每条只输出 openingState 和 ${duration / segmentSeconds} 个各自 0–${segmentSeconds} 秒的 segments;Agent 会确定性合成 masterScript,不得重复输出总稿,也不得写跨段全局时轴。`;
1399
1476
  const rewriteInstruction = rewriteAttempt > 0
1400
1477
  ? `\n精确重复定向重写(第 ${rewriteAttempt}/${FLOW_C_SCRIPT_REWRITE_MAX_ATTEMPTS} 次):中心只因这些 ordinal 的完整脚本文本与同批已有结果完全相同而拒绝。必须继续使用上方同一 executionBlueprint、productAdaptation、商品身份、所选因果结构、节拍比例、动作强度、运镜和画质;禁止重新匹配、重新选题、降低镜头质量或改商品。把 ordinalBindings 中的 variationSeed 与本轮 rewriteSeed(${ordinals.map((ordinal) => `${ordinal}=rewrite-${rewriteAttempt}-ordinal-${ordinal}`).join(";")})同时视为强制差异指令,实质改写该商品的开场措辞、可见执行细节、口播表达、屏幕字及收束反应,使完整脚本明显不同但结构与质量不变;不得只改空格、标点或同义词。\n`
1401
1478
  : "";
@@ -1408,8 +1485,9 @@ export function scriptChunkPrompt(id, task, ordinals, rewriteAttempt = 0) {
1408
1485
  ordinals,
1409
1486
  frameworkOrdinals: [...selected.values()].filter(isFlowCUserFrameworkCandidate).map((candidate) => candidate.ordinal),
1410
1487
  montageOrdinals: generatedMontageOrdinals,
1488
+ segmentSeconds,
1411
1489
  });
1412
- const generatedMontageMethod = flowCGeneratedMontagePrompt(generatedMontageOrdinals);
1490
+ const generatedMontageMethod = flowCGeneratedMontagePrompt(generatedMontageOrdinals, segmentSeconds);
1413
1491
  return `你正在后台完成 Flow C 脚本交接 ${id},只写 ordinal:${ordinals.join(", ")};映射:${scriptProductAssignments(task.product_quantities, ordinals)}。
1414
1492
  目标市场:${task.market}。目标口播语言:${targetVoiceLanguage}。结构化当地化事实(国家、语言/locale、出镜者、受众、生活场景、创作者口吻和CTA彼此独立;不得从国家推断族群):${compactJson(localization, 3_000, "当前脚本子批的当地化事实")}。商品事实:${compactJson(productFacts, 12_000, "当前脚本子批的商品事实")}
1415
1493
  中心已完成当前 ordinal 的创意选择。executionBlueprints 只保存一次共享的模型无关创意蓝图(可能来自已学习爆款,也可能来自已筛选带货形式卡);productAdaptations 只保存一次每个不同的当前商品执行卡;ordinalBindings ${contentStrategy ? "用 blueprintRef/adaptationRef、variationSeed 和逐条 contentDirection" : "只用 blueprintRef/adaptationRef 和 variationSeed"} 映射到具体脚本。存在 blueprintRef 时,对应 executionBlueprint 是唯一结构权威;没有 blueprintRef 时,对应 productAdaptation 是用户框架的唯一执行权威。相同蓝图可供同一商品整批复用,直接替换成当前商品执行,不要生成候选、重新选题或重新评分:
@@ -1417,12 +1495,12 @@ ${compactJson(selectedBlueprintPromptPayload([...selected.values()], duration, c
1417
1495
  ${rewriteInstruction}
1418
1496
  ${durationRules}
1419
1497
  写作要求:
1420
- 1. visualHook、conflict、escalation/turn、productIntervention、visibleProof、purchaseReason、callbackMotivation 与所有 shots 必须执行选中卡的 visualPremise、firstFrame、spectacleEscalation、productProofAction、purchaseReason、truthBoundary 以及七项视觉执行字段;保留所选蓝图的因果时间线、节拍比例、镜头/剪辑节奏、动作压力、证明方式和购买逻辑,只替换当前商品、人物、场景与当地口播槽位,不得稀释构图或换成普通模板。爆款来源的旧商品身份/动作必须替换;形式卡只提供抽象创意结构,绝不能反向改变现有首帧、分段、Omni或参考图制作方式。形式库中的工厂、仓库、街访、使用者体验、主理人、探店、补货、对比、促销和耐用形式都可以用 AI 人物与场景正常演绎;缺少现实素材或事实证据不是脚本失败条件,必须按 executionBlueprint.executionAdaptation 保留所选形式,同时不把演绎的角色、地点、订单、库存、销量、价格、身份或经历写成已核验的现实事实。若 productAdaptation.templateMatch.actionCompatibility 的 openingAction、proofAction 或 spectacleAction 为 false,对应 productAdaptation 的 firstFrame、productProofAction 或 spectacleEscalation 对商品动作内容具有绝对优先级,必须删除其旧商品动作,不得折中混用。productProofAction 必须同时写清一个商品图或执行档案能支持的可见动作及其镜头内可见结果;purchaseReason 只解释该结果为何值得目标用户购买,不能变成泛泛 CTA。
1498
+ 1. visualHook、conflict、escalation/turn、productIntervention、visibleProof、purchaseReason、callbackMotivation 与所有 shots 必须执行选中卡的 visualPremise、firstFrame、spectacleEscalation、productProofAction、purchaseReason、truthBoundary 以及七项视觉执行字段;保留所选蓝图的因果时间线、节拍比例、镜头/剪辑节奏、动作压力、证明方式和购买逻辑,只替换当前商品、人物、场景与当地口播槽位,不得稀释构图或换成普通模板。爆款来源的旧商品身份/动作必须替换;形式卡只提供抽象创意结构,绝不能反向改变现有首帧、分段、${videoModelName}或参考图制作方式。形式库中的工厂、仓库、街访、使用者体验、主理人、探店、补货、对比、促销和耐用形式都可以用 AI 人物与场景正常演绎;缺少现实素材或事实证据不是脚本失败条件,必须按 executionBlueprint.executionAdaptation 保留所选形式,同时不把演绎的角色、地点、订单、库存、销量、价格、身份或经历写成已核验的现实事实。若 productAdaptation.templateMatch.actionCompatibility 的 openingAction、proofAction 或 spectacleAction 为 false,对应 productAdaptation 的 firstFrame、productProofAction 或 spectacleEscalation 对商品动作内容具有绝对优先级,必须删除其旧商品动作,不得折中混用。productProofAction 必须同时写清一个商品图或执行档案能支持的可见动作及其镜头内可见结果;purchaseReason 只解释该结果为何值得目标用户购买,不能变成泛泛 CTA。
1421
1499
  2. 严格执行 executionBlueprints 中的 sourceDurationSeconds → targetDurationSeconds 和 retimingMode:expand 只增加有用的证明停留、使用语境与购买理由,compress 只压缩重复、冗余铺垫和转场,same 保持原节拍比例;三种模式都必须保留 Hook、证明和购买因果,禁止整体拉伸、截断或机械加速。
1422
- 3. 每条生成一份稳定 voiceProfile;每段只写简短 voiceCue。口播必须使用${targetVoiceLanguage},并执行 creatorVoiceStyle/ctaStyle;未提供 creatorVoiceStyle 时使用当地 TikTok 带货创作者真实会说的口吻。${contentStrategy || generatedMontageOrdinals.length > 0 ? '不是逐字翻译。Hook → Body/visible proof → Close 是画面叙事结构,不等于口播结构;镜头数量不等于台词数量。先基于已经确定的画面,为每个局部10秒拟一份按实际镜头时长能自然说完的很短当地口播:用户锁定对白先以原词计入并优先给承载镜头足够秒数,不得删改;除此之外整段只留1–2个必要短句。再按完整词组或自然分句分配到真正展示相关动作/判断的镜头,允许一句在连续相关 cuts 间自然延续,但每镜 voiceover 只存该镜实际说出的片段,不逐镜复述 visual。镜头时长不足时先删除模型自行增加的赘句,不追加语速、不填满有声镜;其它镜头默认 voiceover="none",只在 soundBgm 保留动作现场声。结尾的一个简短自然 CTA 并入上述已定短句;若锁定对白占满可用口播时长就不再追加 CTA。用户锁定的对白、原框架和目标语言优先;上述拟稿与分配在同一次写作内完成,不输出中间声音轨。' : '不是逐字翻译,整条内容按 Hook → Body/visible proof → Close 组织,短句口语化且与当前镜头可见动作同步,结尾只给一个简短自然 CTA。'}只使用少量可信的 localSceneProfile/audienceContext 日常细节;presenterContext 没填写时使用普通创作者,不得把国家代码、语言或地区自动等同于人物族群。商品事实没有提供时不得编造价格、折扣、销量、库存或稀缺性。商品标题只用于理解商品类型与事实,所有输出不得主动写出或念出品牌名、品牌广告语、包装文案,也不得要求模型把品牌字样变得更清晰;商品外观与已有标识的位置、比例、颜色和版式只服从第1张产品参考图。TikTok/TikTok Shop 只用于定义这条写作规则,不得把平台名写入 voiceover、onScreenText、visual、soundBgm、emotionalNote、openingState、endingState 或任何会进入故事板/视频的导演字段。导演说明统一用简洁制作英文;这里只做写作指令,不做语言检测字段。
1423
- 4. 每段永远是独立 0–10 秒,含 1–8 个按剧情需要决定的 ${contentStrategy ? 'shots。每镜 voiceover 字段必须存在,但不等于必须有台词:只填上一步分配给该镜的原句,其余填非空静默标记 "none",绝不让配音念出 none;每镜同时给出准确 onScreenText、evidence、soundBgm、emotionalNote,并提供每段 endingState。先写末镜实际动作,再在末镜 visual 最后用一个短句明确第10秒的最终画面;endingState.endingFrame 逐字复用这个收尾短句,其余 endingState 字段也只描述同一瞬间,不另编姿势或动作。已走出画面的人不能仍在画内回头,已经落地的脚不能又悬在半空,已经完成的动作不能仍写为待完成;确已完成且无续接动作时 unfinishedAction 写 none。下一段首镜从这个真实终点继续,不重置人物、物体或动作;最终一段也要检查,不能只保证跨段字段相等' : 'shots、准确 voiceover、onScreenText、evidence、soundBgm、emotionalNote 与 endingState'};模型不要输出 continuity 或 continuityMode。
1500
+ 3. 每条生成一份稳定 voiceProfile;每段只写简短 voiceCue。口播必须使用${targetVoiceLanguage},并执行 creatorVoiceStyle/ctaStyle;未提供 creatorVoiceStyle 时使用当地 TikTok 带货创作者真实会说的口吻。${contentStrategy || generatedMontageOrdinals.length > 0 ? `不是逐字翻译。Hook → Body/visible proof → Close 是画面叙事结构,不等于口播结构;镜头数量不等于台词数量。先基于已经确定的画面,为每个局部${segmentSeconds}秒拟一份按实际镜头时长能自然说完的很短当地口播:用户锁定对白先以原词计入并优先给承载镜头足够秒数,不得删改;除此之外整段只留1–2个必要短句。再按完整词组或自然分句分配到真正展示相关动作/判断的镜头,允许一句在连续相关 cuts 间自然延续,但每镜 voiceover 只存该镜实际说出的片段,不逐镜复述 visual。允许符合当地带货口吻的自然偏快语速,偶尔密一点无需重写;不要夸张急促、吞字或失去可懂度。连续相关镜头可承接同一句口播;只有明显超出实际可用时长时才删除模型自行增加的赘句,不为填满有声镜硬塞台词;其它镜头默认 voiceover="none",只在 soundBgm 保留动作现场声。结尾的一个简短自然 CTA 并入上述已定短句;若锁定对白占满可用口播时长就不再追加 CTA。用户锁定的对白、原框架和目标语言优先;上述拟稿与分配在同一次写作内完成,不输出中间声音轨。` : '不是逐字翻译,整条内容按 Hook → Body/visible proof → Close 组织,短句口语化且与当前镜头可见动作同步,结尾只给一个简短自然 CTA。'}只使用少量可信的 localSceneProfile/audienceContext 日常细节;presenterContext 没填写时使用普通创作者,不得把国家代码、语言或地区自动等同于人物族群。商品事实没有提供时不得编造价格、折扣、销量、库存或稀缺性。商品标题只用于理解商品类型与事实,所有输出不得主动写出或念出品牌名、品牌广告语、包装文案,也不得要求模型把品牌字样变得更清晰;商品外观与已有标识的位置、比例、颜色和版式只服从第1张产品参考图。TikTok/TikTok Shop 只用于定义这条写作规则,不得把平台名写入 voiceover、onScreenText、visual、soundBgm、emotionalNote、openingState、endingState 或任何会进入故事板/视频的导演字段。导演说明统一用简洁制作英文;这里只做写作指令,不做语言检测字段。
1501
+ 4. 每段永远是独立 0–${segmentSeconds} 秒,含 1–8 个按剧情需要决定的 ${contentStrategy ? `shots。每镜 voiceover 字段必须存在,但不等于必须有台词:只填上一步分配给该镜的原句,其余填非空静默标记 "none",绝不让配音念出 none;每镜同时给出准确 onScreenText、evidence、soundBgm、emotionalNote,并提供每段 endingState。先写末镜实际动作,再在末镜 visual 最后用一个短句明确第${segmentSeconds}秒的最终画面;endingState.endingFrame 逐字复用这个收尾短句,其余 endingState 字段也只描述同一瞬间,不另编姿势或动作。已走出画面的人不能仍在画内回头,已经落地的脚不能又悬在半空,已经完成的动作不能仍写为待完成;确已完成且无续接动作时 unfinishedAction 写 none。下一段首镜从这个真实终点继续,不重置人物、物体或动作;最终一段也要检查,不能只保证跨段字段相等` : 'shots、准确 voiceover、onScreenText、evidence、soundBgm、emotionalNote 与 endingState'};模型不要输出 continuity 或 continuityMode。
1424
1502
  5. shot.visual 要直接写出主体位置、景别、光线、材质、动作峰值和当地自然环境,并保留真实皮肤、细发、布料/商品微纹理和实景混合光;禁止塑料蜡感、静态举产品、品牌广告片或电视购物。允许执行所选形式的 AI 工厂/仓库/零售/人物场景,但不得声称它们是该商家真实工厂、产地、生产档案、订单、库存、销量、实名客户证言或线下价格。
1425
- 6. 20/30 秒的后一段剧情承接前段 endingState,但每段仍只使用自己的局部 0–10 秒执行内容。
1503
+ 6. 多段视频的后一段剧情承接前段 endingState,但每段仍只使用自己的局部 0–${segmentSeconds} 秒执行内容。
1426
1504
  7. 不要输出 creativePlan、executionBindings 或 masterScript;这些字段由 Agent 从选中蓝图确定性回填/合成,避免重复 token 和脆弱的文字绑定校验。若 selectionMode=user-framework,用户原框架的开头、事件顺序、核心剧情和结尾仍是最高权威。
1427
1505
  8. 商品身份以按顺序提供的原商品图为最高权威:第1张是主SKU身份图,当前商品标题和大概类目只补充商品用途与事实,后续图片只是同一SKU补充视角。任何爆款源商品、首帧、故事板或上一段尾帧都不得改变商品颜色、款式、结构、比例、材质、包装、标识位置、部件、配件和实际套装数量;修正身份时不得降低动作、运镜、节奏、景深、真实感或画质。商品本体或包装表面的印花、图案、微纹理、已印文字/字符、图标、色块、行距、相对位置和朝向全部视为不可编辑的原图纹理;不得在 shot.visual、onScreenText、voiceover、evidence、openingState、endingState 或任何导演字段中要求重写、翻译、替换、删改、重排、镜像这些表面内容,也不得要求生成“另一段清晰可读文案”。新增屏幕字只能是与商品像素分离的场景叠加字幕,绝不能印到商品或包装上。旋转、翻转、弯折或开合商品时,完整表面纹理必须随实体整体运动,不能漂移、翻面后复写或重新生成。若 executionBlueprint 或 productAdaptation 与本规则冲突,只保留其钩子、动作因果和镜头节奏,改写构图、机位或表演,绝不改商品表面。
1428
1506
  ${contentMethod}${generatedMontageMethod}固定使用 GPT-5.6 Terra 中等推理。媒体制作方式与分镜布局由中心在脚本完成后管理,不得影响这里的创意、镜头、口播或结构化脚本。只返回当前结构化 jobs,不调用工具、不创建任何图片或视频任务。`;
@@ -1697,7 +1775,7 @@ export function nextScriptPipelineWave(task, receivedOrdinals, durationSeconds,
1697
1775
  if (scriptReady.length) {
1698
1776
  return { stage: "script", chunks: flowCScriptChunks(durationSeconds, scriptReady, scriptChunkSize).slice(0, concurrency) };
1699
1777
  }
1700
- const candidateMissing = missingOrdinals(task.requested_count, selected);
1778
+ const candidateMissing = missingOrdinals(task.requested_count, [...selected, ...receivedOrdinals]);
1701
1779
  return { stage: "candidate", chunks: chunkNumbers(candidateMissing, candidateChunkSize).slice(0, concurrency) };
1702
1780
  }
1703
1781
  export function immediateScriptOrdinals(task, receivedOrdinals, candidateOrdinals) {
@@ -1749,7 +1827,8 @@ function productIndexForOrdinal(productQuantities, ordinal) {
1749
1827
  return -1;
1750
1828
  }
1751
1829
  function publicScript(record) {
1752
- return { id: record.id, status: record.status, requestedCount: record.requestedCount, received: record.receivedOrdinals.length, threadId: record.threadId, chunkSize: record.chunkSize || null, activeChunks: Number(record.activeChunks || 0), message: record.message, expiresAt: record.expiresAt, updatedAt: record.updatedAt, ...(record.contentAdvisories ? { contentReview: { blocking: false, semanticAcceptance: "not-evaluated", advisories: record.contentAdvisories } } : {}) };
1830
+ const reviewOrdinals = voicePacingHeldOrdinals(record);
1831
+ return { id: record.id, status: record.status, requestedCount: record.requestedCount, received: record.receivedOrdinals.length, reviewOrdinals, reviewCount: reviewOrdinals.length, threadId: record.threadId, chunkSize: record.chunkSize || null, activeChunks: Number(record.activeChunks || 0), message: record.message, expiresAt: record.expiresAt, updatedAt: record.updatedAt, ...(record.contentAdvisories ? { contentReview: { blocking: false, semanticAcceptance: "not-evaluated", advisories: record.contentAdvisories } } : {}) };
1753
1832
  }
1754
1833
  function publicDownload(record) {
1755
1834
  return { batchId: record.batchId, status: record.status, downloaded: record.downloadedOrdinals.length, market: record.market, message: record.message, expiresAt: record.expiresAt, updatedAt: record.updatedAt };
@@ -1,12 +1,12 @@
1
1
  type JsonSchema = Record<string, unknown>;
2
2
  /** Codex app-server 的结构化脚本返回契约;回传由 Agent 完成,不依赖模型调用 MCP。 */
3
- export declare function flowCScriptOutputSchema(durationSeconds: 10 | 20 | 30, count: number): JsonSchema;
3
+ export declare function flowCScriptOutputSchema(durationSeconds: 10 | 15 | 20 | 30, count: number, segmentSeconds?: 10 | 15): JsonSchema;
4
4
  /**
5
5
  * OpenAI strict structured output requires every declared object property to
6
6
  * appear in `required`. Optional semantics must therefore be represented by a
7
7
  * required nullable field, never by omitting that key from `required`.
8
8
  */
9
9
  export declare function assertStrictResponseSchema(schemaValue: unknown, path?: string): asserts schemaValue is JsonSchema;
10
- export declare function parseFlowCScriptOutput(value: string, expectedOrdinals: number[]): unknown[];
11
- export declare function validateFlowCLocalSegmentTimeline(segmentValue: unknown, label?: string): unknown;
10
+ export declare function parseFlowCScriptOutput(value: string, expectedOrdinals: number[], segmentSeconds?: 10 | 15): unknown[];
11
+ export declare function validateFlowCLocalSegmentTimeline(segmentValue: unknown, label?: string, segmentSeconds?: 10 | 15): unknown;
12
12
  export {};
@@ -21,7 +21,7 @@ function voiceProfileSchema() {
21
21
  emotionalBaseline: text,
22
22
  });
23
23
  }
24
- function segmentSchema() {
24
+ function segmentSchema(segmentSeconds = 10) {
25
25
  return object({
26
26
  voiceCue: text,
27
27
  endingState: continuitySchema("endingFrame"),
@@ -30,8 +30,8 @@ function segmentSchema() {
30
30
  minItems: 1,
31
31
  maxItems: 8,
32
32
  items: object({
33
- startSeconds: { type: "number", minimum: 0, maximum: 10 },
34
- endSeconds: { type: "number", minimum: 0, maximum: 10 },
33
+ startSeconds: { type: "number", minimum: 0, maximum: segmentSeconds },
34
+ endSeconds: { type: "number", minimum: 0, maximum: segmentSeconds },
35
35
  visual: text,
36
36
  voiceover: text,
37
37
  onScreenText: text,
@@ -43,7 +43,7 @@ function segmentSchema() {
43
43
  });
44
44
  }
45
45
  /** Codex app-server 的结构化脚本返回契约;回传由 Agent 完成,不依赖模型调用 MCP。 */
46
- export function flowCScriptOutputSchema(durationSeconds, count) {
46
+ export function flowCScriptOutputSchema(durationSeconds, count, segmentSeconds = 10) {
47
47
  const properties = {
48
48
  ordinal: { type: "integer", minimum: 1 },
49
49
  productIndex: { type: "integer", minimum: 0 },
@@ -51,10 +51,10 @@ export function flowCScriptOutputSchema(durationSeconds, count) {
51
51
  voiceProfile: voiceProfileSchema(),
52
52
  openingState: openingStateSchema(),
53
53
  };
54
- if (durationSeconds === 10)
55
- properties.segment = segmentSchema();
54
+ if (durationSeconds === segmentSeconds)
55
+ properties.segment = segmentSchema(segmentSeconds);
56
56
  else {
57
- properties.segments = { type: "array", minItems: durationSeconds / 10, maxItems: durationSeconds / 10, items: segmentSchema() };
57
+ properties.segments = { type: "array", minItems: durationSeconds / segmentSeconds, maxItems: durationSeconds / segmentSeconds, items: segmentSchema(segmentSeconds) };
58
58
  }
59
59
  const schema = object({ jobs: { type: "array", minItems: count, maxItems: count, items: object(properties) } });
60
60
  assertStrictResponseSchema(schema);
@@ -93,7 +93,7 @@ export function assertStrictResponseSchema(schemaValue, path = "$") {
93
93
  branches.forEach((branch, index) => assertStrictResponseSchema(branch, `${path}.${branchKey}[${index}]`));
94
94
  }
95
95
  }
96
- export function parseFlowCScriptOutput(value, expectedOrdinals) {
96
+ export function parseFlowCScriptOutput(value, expectedOrdinals, segmentSeconds = 10) {
97
97
  const source = String(value || "").trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "");
98
98
  const parsed = JSON.parse(source);
99
99
  if (!Array.isArray(parsed.jobs) || !parsed.jobs.length)
@@ -113,7 +113,7 @@ export function parseFlowCScriptOutput(value, expectedOrdinals) {
113
113
  if (!accepted.has(ordinal))
114
114
  continue;
115
115
  try {
116
- valid.push(validateJobLocalTimelines(canonicalizeSegmentContinuity(accepted.get(ordinal)), ordinal));
116
+ valid.push(validateJobLocalTimelines(canonicalizeSegmentContinuity(accepted.get(ordinal), segmentSeconds), ordinal, segmentSeconds));
117
117
  }
118
118
  catch (error) {
119
119
  timelineError = error instanceof Error ? error : new Error(String(error));
@@ -123,17 +123,17 @@ export function parseFlowCScriptOutput(value, expectedOrdinals) {
123
123
  throw timelineError;
124
124
  return valid;
125
125
  }
126
- function validateJobLocalTimelines(jobValue, ordinal) {
126
+ function validateJobLocalTimelines(jobValue, ordinal, segmentSeconds) {
127
127
  const job = recordOf(jobValue);
128
128
  if (!job)
129
129
  return jobValue;
130
130
  if (Array.isArray(job.segments))
131
- job.segments.forEach((segment, index) => validateFlowCLocalSegmentTimeline(segment, `ordinal ${ordinal} segment ${index + 1}`));
131
+ job.segments.forEach((segment, index) => validateFlowCLocalSegmentTimeline(segment, `ordinal ${ordinal} segment ${index + 1}`, segmentSeconds));
132
132
  else if (recordOf(job.segment))
133
- validateFlowCLocalSegmentTimeline(job.segment, `ordinal ${ordinal} segment 1`);
133
+ validateFlowCLocalSegmentTimeline(job.segment, `ordinal ${ordinal} segment 1`, segmentSeconds);
134
134
  return jobValue;
135
135
  }
136
- export function validateFlowCLocalSegmentTimeline(segmentValue, label = "segment") {
136
+ export function validateFlowCLocalSegmentTimeline(segmentValue, label = "segment", segmentSeconds = 10) {
137
137
  const segment = recordOf(segmentValue);
138
138
  const shots = Array.isArray(segment?.shots) ? segment.shots : [];
139
139
  if (!shots.length || shots.length > 8)
@@ -143,13 +143,13 @@ export function validateFlowCLocalSegmentTimeline(segmentValue, label = "segment
143
143
  const shot = recordOf(shotValue);
144
144
  const startSeconds = preciseSecond(shot?.startSeconds);
145
145
  const endSeconds = preciseSecond(shot?.endSeconds);
146
- if (startSeconds !== cursor || startSeconds < 0 || startSeconds > 10 || endSeconds <= startSeconds || endSeconds > 10) {
147
- throw new Error(`${label} shot ${index + 1} must continue the local 0-10 second timeline without gaps or overlaps`);
146
+ if (startSeconds !== cursor || startSeconds < 0 || startSeconds > segmentSeconds || endSeconds <= startSeconds || endSeconds > segmentSeconds) {
147
+ throw new Error(`${label} shot ${index + 1} must continue the local 0-${segmentSeconds} second timeline without gaps or overlaps`);
148
148
  }
149
149
  cursor = endSeconds;
150
150
  }
151
- if (cursor !== 10)
152
- throw new Error(`${label} must end at exactly 10 seconds`);
151
+ if (cursor !== segmentSeconds)
152
+ throw new Error(`${label} must end at exactly ${segmentSeconds} seconds`);
153
153
  return segmentValue;
154
154
  }
155
155
  function preciseSecond(value) {
@@ -161,7 +161,7 @@ function preciseSecond(value) {
161
161
  * 文字复述角色/场景,中心严格校验时会误判不连续;这里复制模型自己写的
162
162
  * endingState,不发明新内容,同时保证生成阶段真正无缝承接。
163
163
  */
164
- function canonicalizeSegmentContinuity(jobValue) {
164
+ function canonicalizeSegmentContinuity(jobValue, segmentSeconds = 10) {
165
165
  const job = recordOf(jobValue);
166
166
  if (!job)
167
167
  return jobValue;
@@ -171,7 +171,7 @@ function canonicalizeSegmentContinuity(jobValue) {
171
171
  if (!segment)
172
172
  return jobValue;
173
173
  const canonical = { ...segment, continuityMode: "reset", continuity: continuityFromOpeningState(openingState) };
174
- const rendered = withLegacySegmentScript(canonical, 0, 1, job.voiceProfile);
174
+ const rendered = withLegacySegmentScript(canonical, 0, 1, job.voiceProfile, segmentSeconds);
175
175
  const { openingState: _openingState, segment: _segment, ...persistedJob } = job;
176
176
  return { ...persistedJob, script: recordOf(rendered)?.script, segmentVoiceovers: [segmentVoiceoverLines(canonical)], segment: rendered };
177
177
  }
@@ -190,7 +190,7 @@ function canonicalizeSegmentContinuity(jobValue) {
190
190
  return { ...segment, continuityMode: "continue", continuity };
191
191
  });
192
192
  const { openingState: _openingState, ...persistedJob } = job;
193
- const renderedSegments = segments.map((segment, index) => withLegacySegmentScript(segment, index, segments.length, job.voiceProfile));
193
+ const renderedSegments = segments.map((segment, index) => withLegacySegmentScript(segment, index, segments.length, job.voiceProfile, segmentSeconds));
194
194
  const masterScript = renderedSegments.map((segment) => String(recordOf(segment)?.script || "").trim()).filter(Boolean).join("\n\n");
195
195
  return { ...persistedJob, script: masterScript, masterScript, segmentVoiceovers: segments.map(segmentVoiceoverLines), segments: renderedSegments };
196
196
  }
@@ -208,7 +208,7 @@ function continuityFromOpeningState(openingState) {
208
208
  * 正式站可能仍运行只接收 segment.script 的旧协议。脚本正文直接由同一份
209
209
  * structured shots/continuity 渲染,既不要求模型重复输出,也不改变新协议内容。
210
210
  */
211
- function withLegacySegmentScript(segmentValue, segmentIndex, segmentCount, voiceProfileValue) {
211
+ function withLegacySegmentScript(segmentValue, segmentIndex, segmentCount, voiceProfileValue, segmentSeconds = 10) {
212
212
  const segment = recordOf(segmentValue);
213
213
  const continuity = recordOf(segment?.continuity);
214
214
  const endingState = recordOf(segment?.endingState);
@@ -220,7 +220,7 @@ function withLegacySegmentScript(segmentValue, segmentIndex, segmentCount, voice
220
220
  const ending = `CHARACTER: ${endingState.character}; WARDROBE: ${endingState.wardrobe}; LOCATION: ${endingState.location}; LIGHTING: ${endingState.lighting}; PRODUCT STATE: ${endingState.productState}; UNFINISHED ACTION: ${endingState.unfinishedAction}; NEXT GOAL: ${endingState.nextGoal}; ENDING FRAME: ${endingState.endingFrame}`;
221
221
  const voice = voiceProfile ? `GENDER: ${voiceProfile.gender}; AGE IMPRESSION: ${voiceProfile.ageImpression}; PITCH: ${voiceProfile.pitch}; TIMBRE: ${voiceProfile.timbre}; SPEAKING RATE: ${voiceProfile.speakingRate}; ACCENT: ${voiceProfile.accent}; PAUSE HABIT: ${voiceProfile.pauseHabit}; EMOTIONAL BASELINE: ${voiceProfile.emotionalBaseline}` : "Use the shared voice profile for this video";
222
222
  const timeline = shots.map((shot, index) => `SHOT ${index + 1} | ${shot.startSeconds}-${shot.endSeconds}s | VISUAL: ${shot.visual} | VO: ${shot.voiceover} | ON-SCREEN TEXT: ${shot.onScreenText} | EVIDENCE: ${shot.evidence} | SOUND/BGM: ${shot.soundBgm} | EMOTION: ${shot.emotionalNote}`).join("\n");
223
- return { ...segment, script: `FLOW C INDEPENDENT SEGMENT ${segmentIndex + 1}/${segmentCount}\nLOCAL TIMELINE: 0-10 seconds only. Never reference or draw a full-video timeline.\nVOICE PROFILE: ${voice}\nSEGMENT VOICE CUE: ${segment.voiceCue}\nOPENING CONTINUITY: ${context}\n${timeline}\nENDING STATE: ${ending}` };
223
+ return { ...segment, script: `FLOW C INDEPENDENT SEGMENT ${segmentIndex + 1}/${segmentCount}\nLOCAL TIMELINE: 0-${segmentSeconds} seconds only. Never reference or draw a full-video timeline.\nVOICE PROFILE: ${voice}\nSEGMENT VOICE CUE: ${segment.voiceCue}\nOPENING CONTINUITY: ${context}\n${timeline}\nENDING STATE: ${ending}` };
224
224
  }
225
225
  function recordOf(value) {
226
226
  return value && typeof value === "object" && !Array.isArray(value) ? value : null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xiaohhhh1/canvas-agent",
3
- "version": "0.4.82",
3
+ "version": "0.4.84",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",