@ninkch/dsh-infinite-canvas 0.20.1 → 0.20.2

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.
Files changed (4) hide show
  1. package/client.js +563 -137
  2. package/index.js +548 -93
  3. package/package.json +1 -1
  4. package/production.js +83 -6
package/index.js CHANGED
@@ -17,6 +17,7 @@ import { normalizeSkillProfile, DEFAULT_SKILL_PROFILE } from './index-core-skill
17
17
  import { initPackBase, packInventory, allowedIds } from './skill-pack-loader.js';
18
18
  import { buildSkillPack, SKILL_CATALOG, renderInventory, renderProfile } from './skill-pack.js';
19
19
  import { createProduction, PRODUCTION_STAGES, PRODUCTION_STAGE_ZH } from './production.js';
20
+ import { planShotSegments } from './shot-segments.js';
20
21
 
21
22
  /** 制作阶段机与流程闸门(0.20.0):deps 全是本模块的函数声明(已提升,运行时才调用)。 */
22
23
  const PROD = createProduction({
@@ -24,6 +25,7 @@ const PROD = createProduction({
24
25
  readToolDoc,
25
26
  readDoc,
26
27
  normalizeCanvasId,
28
+ readAssetIndexNames, // T8:预算单参考图行项要查「实体是否已有参考资产」
27
29
  });
28
30
 
29
31
  const NAME = 'infinite-canvas';
@@ -211,6 +213,60 @@ function sanitizeFolderName(name) {
211
213
  return (!s || s === '.' || s === '..') ? '未命名项目' : s;
212
214
  }
213
215
 
216
+ // ============================================================
217
+ // 提交留痕(0.20.2 能力③):视频提交请求的脱敏 JSONL 留底
218
+ // 客户端在 onTask(submitted)/终态(done)/失败(failed)时各写一条 entry;
219
+ // Host 统一 redact 后追加到 <项目目录>/submissions.jsonl,>500 行裁最旧。
220
+ // 红线条文(绝不落盘):apiKey / 回调令牌 / taskQueryUrl(带签名地址)/ 素材数据——
221
+ // entry 本身就不含这些字段,redact 再对一切字符串兜底(error 消息里可能内嵌 URL/token)。
222
+ // ============================================================
223
+ const SUBMISSION_LOG_FILE = 'submissions.jsonl';
224
+ const SUBMISSION_LOG_MAX_LINES = 500;
225
+ /** 单条文本脱敏(可单测):sk- 密钥、带签名参数的 URL、Bearer 令牌。正常文本不受影响。 */
226
+ function redactSubmissionText(text) {
227
+ let s = String(text ?? '');
228
+ // 带签名参数的 URL 整体替换为 [signed-url](X-Amz-Signature/Signature=AWS 系,sign=/token= 常见中转系)
229
+ s = s.replace(/https?:\/\/\S+/g, (u) => (/[?&](?:X-Amz-Signature|Signature|sign|token)=/i.test(u) ? '[signed-url]' : u));
230
+ s = s.replace(/Bearer \S+/gi, 'Bearer ***'); // 先于 sk-:Bearer 串里也可能内嵌 sk- 密钥
231
+ s = s.replace(/sk-[A-Za-z0-9]{8,}/g, 'sk-***');
232
+ return s;
233
+ }
234
+ /** entry 深度脱敏:所有字符串值逐个过 redactSubmissionText(嵌套对象/数组同样处理)。 */
235
+ function redactSubmissionValue(v) {
236
+ if (typeof v === 'string') return redactSubmissionText(v);
237
+ if (Array.isArray(v)) return v.map(redactSubmissionValue);
238
+ if (v && typeof v === 'object') {
239
+ const o = {};
240
+ for (const k of Object.keys(v)) o[k] = redactSubmissionValue(v[k]);
241
+ return o;
242
+ }
243
+ return v;
244
+ }
245
+ /** 追加一条留痕(宿主核心实现,abs 为项目绝对目录;可单测):
246
+ * - 追加 JSONL 一行(整行先深度 redact,再序列化)
247
+ * - 超过 500 行裁最旧(读全文重写;留痕是低频写,无需追加流优化)
248
+ * - 任何写失败返回 ok:false,绝不 throw(留痕不能挡住生成主链路) */
249
+ function submissionLogAppendImpl(abs, entry) {
250
+ if (!abs) return { ok: false, error: '项目目录不可用' };
251
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return { ok: false, error: '缺少 entry 对象' };
252
+ let clean;
253
+ try { clean = redactSubmissionValue(entry); } catch (e) { return { ok: false, error: 'redact 失败: ' + String((e && e.message) || e) }; }
254
+ let line;
255
+ try { line = JSON.stringify(clean); } catch (e) { return { ok: false, error: 'entry 无法序列化: ' + String((e && e.message) || e) }; }
256
+ if (!line) return { ok: false, error: 'entry 序列化为空' };
257
+ const file = path.join(abs, SUBMISSION_LOG_FILE);
258
+ let lines = [];
259
+ try {
260
+ mkdirSync(abs, { recursive: true });
261
+ try { lines = readFileSync(file, 'utf8').split('\n').filter((l) => l.trim()); } catch { /* 首次写入无文件 */ }
262
+ lines.push(line);
263
+ while (lines.length > SUBMISSION_LOG_MAX_LINES) lines.shift();
264
+ writeFileSync(file, lines.join('\n') + '\n', 'utf8');
265
+ } catch (e) { return { ok: false, error: '写入失败: ' + String((e && e.message) || e) }; }
266
+ return { ok: true, lines: lines.length, file };
267
+ }
268
+
269
+
214
270
  // ============================================================
215
271
  // 存储引擎 v2(0.18.0):SQLite(node:sqlite)+ 项目文件夹落盘
216
272
  // <dataRoot>/canvas.db 元数据 + 项目文档 = 唯一事实源
@@ -2885,7 +2941,10 @@ async function canvasRunNode(args) {
2885
2941
  /** 读取节点运行状态与产物(画布执行完成后会把结果推回 Host 文档)。 */
2886
2942
  /** 分镜一致性检查(与客户端 checkShotConsistency 同规则,Host 供状态查询/设定集更新后重算):
2887
2943
  * 检查 shots 的角色/场景/道具数组 **以及 visual/motion 文本里的 @提及** 是否都在设定集登记;
2888
- * 两级告警:「未登记」(设定集/资产都没有)与「已登记但描述为空」(待补全)。 */
2944
+ * 两级告警:「未登记」(设定集/资产都没有)与「已登记但描述为空」(待补全)。
2945
+ * 台词碎片豁免:名字以「的」结尾且出现在对白文本里的角色/场景/道具视为描述性片段(如台词
2946
+ * 「来了个带纸的」被抽成道具「带纸的」),未登记不告警——与客户端 client.js
2947
+ * checkShotConsistency 同规则,两边必须字面同构(防漂移)。 */
2889
2948
  function storyboardConsistencyWarnings(bible, shots, extraNames) {
2890
2949
  const entries = [];
2891
2950
  const addEntry = (kind, name, desc) => {
@@ -2899,7 +2958,13 @@ function storyboardConsistencyWarnings(bible, shots, extraNames) {
2899
2958
  const warnings = [];
2900
2959
  const seen = new Set();
2901
2960
  const warn = (line) => { if (!seen.has(line) && warnings.length < 12) { seen.add(line); warnings.push(line); } };
2902
- const check = (title, kind, name) => {
2961
+ // 台词碎片收集(与客户端 client.js checkShotConsistency 同规则——两边必须字面同构,防漂移):
2962
+ // 拼接同 shots 数组内全部对白文本;shots 无 dialogue 字段(旧数据)时按「无对白可查」自然不跳过。
2963
+ let dialogueAll = '';
2964
+ for (const sh of shots || []) {
2965
+ for (const d of ((sh && sh.dialogue) || [])) dialogueAll += ' ' + String((d && d.line) || '');
2966
+ }
2967
+ const check = (title, kind, name, entity) => {
2903
2968
  const q = String(name || '').trim().toLowerCase();
2904
2969
  if (!q) return;
2905
2970
  const exact = entries.find((e) => e.lower === q);
@@ -2907,14 +2972,16 @@ function storyboardConsistencyWarnings(bible, shots, extraNames) {
2907
2972
  if (!exact.desc.trim()) warn(`${title} · ${kind}「${exact.name}」已登记但描述为空(待补全)`);
2908
2973
  return;
2909
2974
  }
2975
+ // 台词碎片跳过:仅 角色/场景/道具 三类(entity=true);@提及 通道绝不跳过,「已登记但描述为空」路径(上方)不跳过
2976
+ if (entity && String(name || '').trim().endsWith('的') && dialogueAll.includes(String(name || '').trim())) return;
2910
2977
  for (const k of known) { if (k.includes(q) || q.includes(k)) return; }
2911
2978
  warn(`${title} · ${kind}「${String(name).trim()}」未在设定集中登记`);
2912
2979
  };
2913
2980
  for (const sh of shots || []) {
2914
2981
  const title = String((sh && sh.title) || '').trim() || '分镜';
2915
- for (const nm of (sh.characters || [])) check(title, '角色', nm);
2916
- check(title, '场景', sh && sh.scene);
2917
- for (const nm of (sh.props || [])) check(title, '道具', nm);
2982
+ for (const nm of (sh.characters || [])) check(title, '角色', nm, true);
2983
+ check(title, '场景', sh && sh.scene, true);
2984
+ for (const nm of (sh.props || [])) check(title, '道具', nm, true);
2918
2985
  // visual/motion 文本里的 @资产名@ 提及同样纳入检查(未登记的提示补充——与客户端 parseMentions 词法一致)
2919
2986
  const text = String((sh && sh.visual) || '') + ' ' + String((sh && sh.motion) || '');
2920
2987
  const seenMention = new Set();
@@ -2922,7 +2989,7 @@ function storyboardConsistencyWarnings(bible, shots, extraNames) {
2922
2989
  const nm = m.replace(/^@/, '').replace(/@$/, '');
2923
2990
  if (seenMention.has(nm)) continue;
2924
2991
  seenMention.add(nm);
2925
- check(title, '提及', nm);
2992
+ check(title, '提及', nm, false);
2926
2993
  }
2927
2994
  }
2928
2995
  return warnings;
@@ -3583,6 +3650,8 @@ export const inject = ['webServer', 'tools'];
3583
3650
  // 仅供诊断 / 自动化测试(不属于 RPC 面,运行时行为不受影响)
3584
3651
  export const _internals = { THUMB_MAX_SIDE, thumbRelOf, isDerivedMedia, updateCheck, updateInstall, npmLatestVersion, cmpVer, findPnpm, NPM_REGISTRIES, pickUpdateRegistry, registryCacheValid, pnpmAddArgs, getProfileDir: () => PROFILE_DIR, getVersion: () => VERSION, dataRoot, setDataRoot, dataRootMigrate, dataRootImport, ensureProjectFolder, physicalRel, mirrorProjectToDataRoot, writeAssetIndex, removeAssetIndexEntry, readDataRootMeta, removeDataRootProject, sqlDeleteProjectRows, deletedProjectIds, addDeletedProjectId, clearDeletedProjectId, fetchProxyForward, storyboardConsistencyWarnings, readAssetIndexNames, safeJoin, mimeOf, pipeFile, getIcConfigPath: () => CONFIG_PATH, canvasCreateProject, canvasWriteNode, canvasConnect, canvasDeleteProject, canvasDeleteNode, canvasRunNode, canvasNodeStatus, canvasGetBible, canvasUpdateBible, canvasCreateNode, canvasOpen, canvasesList, canvasCreate, canvasRename, canvasDelete, canvasDocId, isCanvasDocId, splitCanvasDocId, normalizeCanvasId, canvasRegistry, sanitizeCanvases, wsProjectsScan, isWsProject, wsProjectHome, wsWatchTick, wsProjectCreateAt, projectHomeDir, memoryRead, memoryWrite, bindingsRead, bindingSet, bindingClear, readCanvasDoc, writeCanvasDoc, deleteCanvasDocsForProject, projectsList, projectsPut, projectsGet, projectsDelete, projectsSync, sqliteAvailable: () => !!SQLITE, getDb, closeDb, dbAssetsList, dbAssetsGet, dbAssetNames, dbAssetCreate, dbAssetUpdate, dbAssetDelete, objectAbsFor, ftsReconcile, readDocOrNull, docExists, sqlActive, rpcMethods: () => _rpcMethods, canvasUpdateNode, canvasGenerateNode, production: PROD, productionStages: PRODUCTION_STAGES,
3585
3652
  canvasLayoutNode, canvasLayoutGet, canvasRelayout,
3653
+ // 提交留痕(0.20.2 T11):redact 可单测(sk- 密钥/签名 URL/Bearer 三条 + 正常文本不受影响)
3654
+ redactSubmissionText, redactSubmissionValue, submissionLogAppendImpl, SUBMISSION_LOG_MAX_LINES,
3586
3655
  __auto: __autoApi };
3587
3656
 
3588
3657
  function resolveModel(providers, want) {
@@ -3774,28 +3843,44 @@ export function apply(ctx) {
3774
3843
  const r = await complete({ system, user });
3775
3844
  return (r && r.text) || '';
3776
3845
  };
3777
- /** 从模型输出提取第一个平衡的 JSON 对象(容忍 ```json 围栏与前后闲话)。 */
3846
+ /** 从模型输出提取第一个可解析的平衡 JSON 对象(容忍 ```json 围栏、前后闲话与散文里的非 JSON 花括号)。 */
3778
3847
  function roomJson(text) {
3779
3848
  const s = String(text || '');
3780
3849
  const fence = s.match(/```(?:json)?\s*([\s\S]*?)```/i);
3781
- const src = fence ? fence[1] : s;
3782
- const start = src.indexOf('{');
3783
- if (start < 0) return null;
3784
- let depth = 0, inStr = false, esc = false;
3785
- for (let i = start; i < src.length; i++) {
3786
- const ch = src[i];
3787
- if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue; }
3788
- if (ch === '"') inStr = true;
3789
- else if (ch === '{') depth++;
3790
- else if (ch === '}') { depth--; if (depth === 0) { try { return JSON.parse(src.slice(start, i + 1)); } catch { return null; } } }
3850
+ // 围栏内扫不出可用 JSON 时退回全文扫描(散文先于/后于围栏出现花括号时,真 JSON 不被围栏边界误杀)
3851
+ for (const src of (fence ? [fence[1], s] : [s])) {
3852
+ // 循环所有 `{` 候选位:首个平衡对象解析失败就从下一个 `{` 继续,全失败才 null
3853
+ // (0.20.1 实机:散文「我认为{这是花括号}」先出现 → 第一个 `{` 被误当 JSON 起点 → 真 JSON 被误杀)
3854
+ let from = src.indexOf('{');
3855
+ while (from >= 0) {
3856
+ let depth = 0, inStr = false, esc = false; // 换起点时转义/字符串状态机完整重置
3857
+ for (let i = from; i < src.length; i++) {
3858
+ const ch = src[i];
3859
+ if (inStr) { if (esc) esc = false; else if (ch === '\\') esc = true; else if (ch === '"') inStr = false; continue; }
3860
+ if (ch === '"') inStr = true;
3861
+ else if (ch === '{') depth++;
3862
+ else if (ch === '}') { depth--; if (depth === 0) { try { return JSON.parse(src.slice(from, i + 1)); } catch { break; } } }
3863
+ }
3864
+ from = src.indexOf('{', from + 1);
3865
+ }
3791
3866
  }
3792
3867
  return null;
3793
3868
  }
3869
+ /** needJson 失败局部重试指令:追加在 user 尾部,测试以「只输出 JSON」识别重试轮。 */
3870
+ const AUTO_JSON_RETRY = '\n\n【格式重试】上一轮输出无法解析为 JSON。只输出 JSON 对象本身:不要任何解释文字、不要 markdown 代码围栏、不要前后缀。';
3794
3871
  async function autoRoomStep(run, role, system, user, needJson) {
3795
3872
  if (run.status !== 'running') throw new Error('aborted');
3796
3873
  const raw = await roomLlm({ system, user });
3797
3874
  const parsed = needJson ? (roomJson(raw) || {}) : null;
3798
- if (needJson && !Object.keys(parsed).length) throw new Error(role + ' 输出不是可用 JSON');
3875
+ if (needJson && !Object.keys(parsed).length) {
3876
+ // 局部重试一次:只坏这一轮就局部救,不炸整个 run(0.20.1 实机:监制轮散文输出直接 fail 全流水线)
3877
+ run.log.push({ at: Date.now(), role, summary: '输出无法解析为 JSON,自动重试一次(要求只输出 JSON)' });
3878
+ const raw2 = await roomLlm({ system, user: user + AUTO_JSON_RETRY });
3879
+ const reparsed = roomJson(raw2) || {};
3880
+ if (!Object.keys(reparsed).length) throw new Error(role + ' 输出不是可用 JSON'); // 重试仍失败 → 原错误抛出(fail 语义不变)
3881
+ run.log.push({ at: Date.now(), role, summary: String(raw2 || '').slice(0, 160) });
3882
+ return reparsed;
3883
+ }
3799
3884
  run.log.push({ at: Date.now(), role, summary: String(raw || '').slice(0, 160) });
3800
3885
  return parsed || raw;
3801
3886
  }
@@ -3837,42 +3922,106 @@ export function apply(ctx) {
3837
3922
  if (!out.length) return [{ no: 1, head: '【场1】', lines: [src] }];
3838
3923
  return out.map((s, i) => ({ no: s.no || i + 1, text: (s.head + '\n' + s.lines.join('\n')).trim() }));
3839
3924
  }
3840
- async function autoRoom(pid, cid, brief) {
3925
+ // 0.20.2 T10 断点续跑:免费段检查点的单位序(每完成一个单位就把 ps.autoRun 就地落盘一次)。
3926
+ // phase 语义 =「最后完成的单位名」,续跑从它的下一个单位继续;pitchA/pitchB 拆成两个单位,
3927
+ // 断在 A、B 之间只重跑 B。board 单位('board<k>')在 script 之后按场追加,数量随 scenes 定。
3928
+ const AUTO_CKPT_ORDER = ['research', 'pitchA', 'pitchB', 'critique', 'decide', 'writeback', 'script'];
3929
+ /** 持久化 run 形状校验:旧版/损坏/已完结 → 视同无持久化(全新启动),绝不带病续跑。 */
3930
+ const autoCkptValid = (c) => !!c && typeof c === 'object' && !c.completed
3931
+ && typeof c.brief === 'string' && c.brief.trim().length >= 4
3932
+ && !!c.outputs && typeof c.outputs === 'object' && !Array.isArray(c.outputs)
3933
+ && Array.isArray(c.boardIds);
3934
+ /** 已完成单位数(note/日志的「跳过 N 个已完成阶段」)。 */
3935
+ const autoCkptSkipCount = (c) => {
3936
+ const i = AUTO_CKPT_ORDER.indexOf(c.phase);
3937
+ if (i >= 0) return i + 1;
3938
+ return String(c.phase || '').indexOf('board') === 0 ? AUTO_CKPT_ORDER.length + c.boardIds.filter(Boolean).length : 0;
3939
+ };
3940
+ /** 断点的展示阶段(run.phase 仅供 autoStatus 观察;autoRoom 执行时会按实际阶段覆盖)。 */
3941
+ const autoCkptDisplayPhase = (c) => {
3942
+ if (c.phase === 'pitchA' || c.phase === 'pitchB') return 'pitch';
3943
+ if (AUTO_CKPT_ORDER.indexOf(c.phase) >= 0) return c.phase;
3944
+ return String(c.phase || '').indexOf('board') === 0 ? 'boards' : 'start';
3945
+ };
3946
+ // resume 非空 = 断点续跑(autoStart 已校验形状):已完成单位的产物直接吃检查点,不调 LLM、不重建节点。
3947
+ async function autoRoom(pid, cid, brief, resume) {
3841
3948
  const runKey = runKeyOf(pid, cid);
3842
3949
  const run = AUTO_RUNS.get(runKey);
3843
3950
  const BASE = '你是短剧创作团队的一员。流程与格式是硬要求;剧情创意只来自用户 brief,绝不套模板。输出只给 JSON。';
3951
+ // T10:run.ckpt = 制作状态文件 ps.autoRun 的内存镜像;ckptDone 每单位落盘一次
3952
+ //(try/catch:状态文件损坏/写失败不炸流水线,内存 run 照常推进)。
3953
+ run.ckpt = resume || { brief, phase: null, completed: false, outputs: {}, meetingNodeId: null, scriptNodeId: null, scenes: null, boardIds: [], startedAt: Date.now(), updatedAt: Date.now() };
3954
+ const ckptDone = (phase) => {
3955
+ run.ckpt.phase = phase;
3956
+ run.ckpt.updatedAt = Date.now();
3957
+ try {
3958
+ const ps = PROD.readState(pid, cid) || { version: 1, projectId: pid, canvasKey: (cid || 'default'), floor: 0, explicit: null, createdAt: Date.now(), updatedAt: 0, history: [], overrides: [] };
3959
+ ps.autoRun = JSON.parse(JSON.stringify(run.ckpt));
3960
+ ps.updatedAt = Date.now();
3961
+ PROD.writeState(pid, cid, ps);
3962
+ } catch { /* 检查点写失败不阻塞主流程 */ }
3963
+ };
3964
+ const ckptOut = (k) => ((resume && resume.outputs && resume.outputs[k]) || null);
3844
3965
  try {
3845
- // ① 调研(离线知识;联网调研随会话执行器上线)
3846
- run.phase = 'research';
3847
- const research = await autoRoomStep(run, '调研', BASE + '\n你是题材调研员(当前离线:基于既有知识,标注「离线调研」)。给出 3 个与 brief 相关的热门题材方向与 3 种视觉风格建议。',
3848
- '用户 brief:' + brief, true);
3849
- // ② 编剧 A / B 独立提案(互不可见)
3966
+ // ① 调研(离线知识;联网调研随会话执行器上线)——续跑时已完成单位直接吃检查点产物
3967
+ let research = ckptOut('research');
3968
+ if (!research) {
3969
+ run.phase = 'research';
3970
+ research = await autoRoomStep(run, '调研', BASE + '\n你是题材调研员(当前离线:基于既有知识,标注「离线调研」)。给出 3 个与 brief 相关的热门题材方向与 3 种视觉风格建议。',
3971
+ '用户 brief:' + brief, true);
3972
+ run.ckpt.outputs.research = research;
3973
+ ckptDone('research');
3974
+ }
3975
+ // ② 编剧 A / B 独立提案(互不可见)——A/B 是两个独立检查点单位
3850
3976
  run.phase = 'pitch';
3851
3977
  const ctxUser = '用户 brief:' + brief + '\n调研建议:' + JSON.stringify(research).slice(0, 1200);
3852
- const pitchA = await autoRoomStep(run, '编剧A', BASE + '\n你是编剧A(强冲突/强反转取向)。给出 logline(≤40字)与 3 个节拍。',
3853
- ctxUser + '\n输出 {"logline":"…","beats":["…","…","…"]}', true);
3854
- const pitchB = await autoRoomStep(run, '编剧B', BASE + '\n你是编剧B(人物动机/情感真实取向)。给出 logline(≤40字)与 3 个节拍。与常规方案反着来。',
3855
- ctxUser, true);
3978
+ let pitchA = ckptOut('pitchA');
3979
+ if (!pitchA) {
3980
+ pitchA = await autoRoomStep(run, '编剧A', BASE + '\n你是编剧A(强冲突/强反转取向)。给出 logline(≤40字)与 3 个节拍。',
3981
+ ctxUser + '\n输出 {"logline":"…","beats":["…","…","…"]}', true);
3982
+ run.ckpt.outputs.pitchA = pitchA;
3983
+ ckptDone('pitchA');
3984
+ }
3985
+ let pitchB = ckptOut('pitchB');
3986
+ if (!pitchB) {
3987
+ pitchB = await autoRoomStep(run, '编剧B', BASE + '\n你是编剧B(人物动机/情感真实取向)。给出 logline(≤40字)与 3 个节拍。与常规方案反着来。',
3988
+ ctxUser, true);
3989
+ run.ckpt.outputs.pitchB = pitchB;
3990
+ ckptDone('pitchB');
3991
+ }
3856
3992
  // ③ 互评
3857
- run.phase = 'critique';
3858
- const crit = await autoRoomStep(run, '互评', BASE + '\n你是剧评人。分别评 A、B 两案各 ≤3 条(冲突强度/动机可信/成本可行性)。',
3859
- 'A案:' + JSON.stringify(pitchA).slice(0, 800) + '\nB案:' + JSON.stringify(pitchB).slice(0, 800), true);
3993
+ let crit = ckptOut('crit');
3994
+ if (!crit) {
3995
+ run.phase = 'critique';
3996
+ crit = await autoRoomStep(run, '互评', BASE + '\n你是剧评人。分别评 A、B 两案各 ≤3 条(冲突强度/动机可信/成本可行性)。',
3997
+ 'A案:' + JSON.stringify(pitchA).slice(0, 800) + '\nB案:' + JSON.stringify(pitchB).slice(0, 800), true);
3998
+ run.ckpt.outputs.crit = crit;
3999
+ ckptDone('critique');
4000
+ }
3860
4001
  // ④ 监制决策
3861
- run.phase = 'decide';
3862
- // 技能遵循度:监制轮带上项目技能包配置(renderProfile 头),决策/设定集不得与项目技能配置脱节——
3863
- // 未配置技能包的项目如实说「未配置」,行为不变。
3864
- let skillLine = '';
3865
- try {
3866
- const doc0 = readDoc(pid);
3867
- const inv0 = packInventory(HERE);
3868
- const prof0 = normalizeSkillProfile(doc0.skillProfile, allowedIds(inv0));
3869
- skillLine = '\n【项目技能包配置·决策须与之一致】' + renderProfile(prof0, inv0, true)
3870
- + '\n题材/影调/规格按上述配置取材;brief 的剧情创意仍优先,配置只约束风格与世界观口径。';
3871
- } catch { /* 项目文档读不到时跳过(与未配置同等对待) */ }
3872
- const dec = await autoRoomStep(run, '监制', BASE + skillLine + '\n你是监制。择一或融合,给出决策与理由,并把世界观/风格/角色/场景/道具写成设定集草案(描述要可生成:年龄/发型/服装/材质/光线)。',
3873
- ctxUser + '\nA案:' + JSON.stringify(pitchA).slice(0, 800) + '\nB案:' + JSON.stringify(pitchB).slice(0, 800) + '\n互评:' + JSON.stringify(crit).slice(0, 800) +
3874
- '\n输出 {"decision":"A|B|merge","rationale":"…","logline":"…","beats":["…"],"scriptIdea":"(写给剧本节点的创作提示词,含两条叙事硬约束:每场结尾因果钩子、每场至少一个冲突点)","bible":{"worldview":"…","style":"…","characters":[{"name":"…","desc":"…"}],"scenes":[{"name":"…","desc":"…"}],"props":[{"name":"…","desc":"…"}]}}', true);
3875
- // ⑤ 落盘:讨论记录节点 + 设定集 + 剧本 idea
4002
+ let dec = ckptOut('dec');
4003
+ if (!dec) {
4004
+ run.phase = 'decide';
4005
+ // 技能遵循度:监制轮带上项目技能包配置(renderProfile 头),决策/设定集不得与项目技能配置脱节——
4006
+ // 未配置技能包的项目如实说「未配置」,行为不变。
4007
+ let skillLine = '';
4008
+ try {
4009
+ const doc0 = readDoc(pid);
4010
+ const inv0 = packInventory(HERE);
4011
+ const prof0 = normalizeSkillProfile(doc0.skillProfile, allowedIds(inv0));
4012
+ skillLine = '\n【项目技能包配置·决策须与之一致】' + renderProfile(prof0, inv0, true)
4013
+ + '\n题材/影调/规格按上述配置取材;brief 的剧情创意仍优先,配置只约束风格与世界观口径。';
4014
+ } catch { /* 项目文档读不到时跳过(与未配置同等对待) */ }
4015
+ dec = await autoRoomStep(run, '监制', BASE + skillLine + '\n你是监制。择一或融合,给出决策与理由,并把世界观/风格/角色/场景/道具写成设定集草案(描述要可生成:年龄/发型/服装/材质/光线)。',
4016
+ ctxUser + '\nA案:' + JSON.stringify(pitchA).slice(0, 800) + '\nB案:' + JSON.stringify(pitchB).slice(0, 800) + '\n互评:' + JSON.stringify(crit).slice(0, 800) +
4017
+ '\n输出 {"decision":"A|B|merge","rationale":"…","logline":"…","beats":["…"],"scriptIdea":"(写给剧本节点的创作提示词,含两条叙事硬约束:每场结尾因果钩子、每场至少一个冲突点)","bible":{"worldview":"…","style":"…","characters":[{"name":"…","desc":"…"}],"scenes":[{"name":"…","desc":"…"}],"props":[{"name":"…","desc":"…"}]}}' +
4018
+ // 0.20.2 T5 防线①:监制轮明写每场 ≤15 秒硬约束(实测项目指南「每场 ≤15 秒」被无视,产出了 40s 的场)。
4019
+ // 必须落进 scriptIdea,让剧本与分镜在源头就按短场写:剧情需要更长只能拆成多场,不能拖长单场。
4020
+ '\n【时长硬约束·写进 scriptIdea】每场总时长(由该场分镜镜头 duration 累加)不得超过 15 秒;剧情需要更长必须拆成多场,绝不生成超长场。', true);
4021
+ run.ckpt.outputs.dec = dec;
4022
+ ckptDone('decide');
4023
+ }
4024
+ // ⑤ 落盘:讨论记录节点 + 设定集 + 剧本 idea(writeback 已完成的续跑不重建节点、不重写设定集)
3876
4025
  run.phase = 'writeback';
3877
4026
  const transcript = [
3878
4027
  '用户 brief:' + brief,
@@ -3883,34 +4032,116 @@ export function apply(ctx) {
3883
4032
  '监制决策:' + dec.decision + '——' + (dec.rationale || ''),
3884
4033
  '定稿 logline:' + (dec.logline || ''),
3885
4034
  ].join('\n\n');
3886
- const meet = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'text', name: '编剧室会议' });
3887
- canvasWriteNode({ projectId: pid, canvasId: cid, nodeId: meet.nodeId, target: 'output', text: transcript.slice(0, 60000), overwrite: true });
3888
- const bi = dec.bible || {};
3889
- await canvasUpdateBible({ projectId: pid, bible: bi });
3890
- // scriptIdea 兼容两处:监制按指示写在根级,写歪时落到 bible 里(模型照抄示例的结构错误要容忍)
3891
- const idea = String(dec.scriptIdea || bi.scriptIdea || dec.logline || brief).slice(0, 4000);
3892
- const sc = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'script', name: '第1节剧本', prompt: idea });
4035
+ let meet = null;
4036
+ let sc = null;
4037
+ if (resume && resume.scriptNodeId) {
4038
+ // 断点续跑:会议/剧本节点上次已建(id 从检查点读),不再重建
4039
+ meet = { nodeId: resume.meetingNodeId || resume.scriptNodeId };
4040
+ sc = { nodeId: resume.scriptNodeId };
4041
+ } else {
4042
+ if (resume && resume.meetingNodeId) meet = { nodeId: resume.meetingNodeId }; // 断在 writeback 中途:会议节点复用,记录重写(幂等)
4043
+ else meet = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'text', name: '编剧室会议' });
4044
+ canvasWriteNode({ projectId: pid, canvasId: cid, nodeId: meet.nodeId, target: 'output', text: transcript.slice(0, 60000), overwrite: true });
4045
+ const bi = dec.bible || {};
4046
+ await canvasUpdateBible({ projectId: pid, bible: bi });
4047
+ // scriptIdea 兼容两处:监制按指示写在根级,写歪时落到 bible 里(模型照抄示例的结构错误要容忍)
4048
+ const idea = String(dec.scriptIdea || bi.scriptIdea || dec.logline || brief).slice(0, 4000);
4049
+ sc = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'script', name: '第1节剧本', prompt: idea });
4050
+ run.ckpt.meetingNodeId = meet.nodeId;
4051
+ run.ckpt.scriptNodeId = sc.nodeId;
4052
+ ckptDone('writeback');
4053
+ }
3893
4054
  // ⑥ 剧本自动生成 → 按场拆分 → 逐场分镜表(tail→prev 串联)→ 生成 → G2 校验
3894
- run.phase = 'script';
3895
- const st = await canvasExec(pid, cid, sc.nodeId, { timeoutMs: 10 * 60 * 1000 });
3896
- const scenes = splitScenes(st.output);
4055
+ // (剧本已生成过的续跑不再 exec:scenes 直接吃检查点)
4056
+ let scenes = (resume && Array.isArray(resume.scenes) && resume.scenes.length) ? resume.scenes : null;
4057
+ if (!scenes) {
4058
+ run.phase = 'script';
4059
+ const st = await canvasExec(pid, cid, sc.nodeId, { timeoutMs: 10 * 60 * 1000 });
4060
+ scenes = splitScenes(st.output);
4061
+ run.ckpt.scenes = scenes;
4062
+ ckptDone('script');
4063
+ }
3897
4064
  const boards = [];
3898
4065
  let prevBoard = null;
4066
+ // 0.20.2 T5 防线②:分镜产出后的场时长校验。切段算法与 client.js 同源(shot-segments.js),
4067
+ // 上限同式取分镜表节点 data.segMaxSeconds(缺省 15,不另立常量)。判据:切段段数 >1
4068
+ //(该场要拆多次生成才装得下)或任一单镜 duration 超上限 → 场超时长。
4069
+ const shotDurOf = (s) => Math.max(0.3, Math.round((Number(s && s.duration) || 3) * 10) / 10);
4070
+ const durCheck = (shots, cap) => {
4071
+ const plan = planShotSegments(shots, { maxSeconds: cap });
4072
+ const overShot = (Array.isArray(shots) ? shots : []).some((s) => shotDurOf(s) > cap);
4073
+ return { plan, overShot, ok: plan.segments.length <= 1 && !overShot };
4074
+ };
4075
+ // T10:读分镜表节点现况(该场已有 shots → 整场跳过;读不到按无处理)
4076
+ const sbShotsOf = (nodeId) => {
4077
+ try {
4078
+ const d = readToolDoc({ projectId: pid, canvasId: cid });
4079
+ const n = (d.nodes || {})[nodeId];
4080
+ return (n && n.data && Array.isArray(n.data.shots) && n.data.shots.length) ? n.data.shots : null;
4081
+ } catch { return null; }
4082
+ };
3899
4083
  for (let i = 0; i < scenes.length; i++) {
4084
+ const savedSbId = (resume && Array.isArray(resume.boardIds) && resume.boardIds[i]) || null;
4085
+ const savedShots = savedSbId ? sbShotsOf(savedSbId) : null;
4086
+ if (savedShots) { // T10 跳过语义:不建节点、不 exec、不注入,只按现况补记账(串联链以它为 prev)
4087
+ prevBoard = savedSbId;
4088
+ const g = PROD.gateStoryboard(savedShots);
4089
+ boards.push({ no: scenes[i].no, storyboardId: savedSbId, gate: g.ok, fails: g.fails });
4090
+ run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' 分镜已存在(断点续跑),跳过重新生成' });
4091
+ continue;
4092
+ }
3900
4093
  run.phase = 'boards ' + (i + 1) + '/' + scenes.length;
3901
4094
  const txt = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'text', name: '场' + scenes[i].no + '文本' });
3902
4095
  canvasWriteNode({ projectId: pid, canvasId: cid, nodeId: txt.nodeId, target: 'output', text: scenes[i].text, overwrite: true });
3903
4096
  const sb = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'storyboard', name: '场' + scenes[i].no + '分镜表', connectFrom: txt.nodeId });
3904
4097
  if (prevBoard) { try { canvasConnect({ projectId: pid, canvasId: cid, fromNode: prevBoard, toNode: sb.nodeId, fromPort: 'tail', toPort: 'prev' }); } catch { /* 端口异常不阻塞 */ } }
3905
4098
  prevBoard = sb.nodeId;
4099
+ // 0.20.2 T3:首轮 exec 前记下节点原有 requirement(重生成注入要在它基础上追加,复检后还原,不污染节点数据)
4100
+ let origReq = '';
4101
+ let segMax = 15;
4102
+ try {
4103
+ const sbDoc = readToolDoc({ projectId: pid, canvasId: cid });
4104
+ const sbNode0 = sbDoc.nodes[sb.nodeId];
4105
+ origReq = String((sbNode0 && sbNode0.data && sbNode0.data.requirement) || '');
4106
+ segMax = Number(sbNode0 && sbNode0.data && sbNode0.data.segMaxSeconds) || 15;
4107
+ } catch { /* 读不到按空处理 */ }
3906
4108
  let sbSt = await canvasExec(pid, cid, sb.nodeId, { timeoutMs: 10 * 60 * 1000 });
3907
4109
  let gate = PROD.gateStoryboard(sbSt.shots);
3908
- if (!gate.ok) { // 不过闸自动重生成一次(分镜重生成不花钱)
3909
- run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' G2 未过,自动重生成:' + gate.fails.slice(0, 2).join(';') });
3910
- sbSt = await canvasExec(pid, cid, sb.nodeId, { timeoutMs: 10 * 60 * 1000 });
3911
- gate = PROD.gateStoryboard(sbSt.shots);
4110
+ let dur = durCheck(sbSt.shots, segMax);
4111
+ if (!gate.ok || !dur.ok) { // 不过闸/超时长都自动重生成一次(两块合并注入,重跑上限仍是一次,不拆两次)
4112
+ const logParts = [];
4113
+ const injParts = [];
4114
+ if (!gate.ok) {
4115
+ logParts.push('G2 未过,自动重生成(已注入清单):' + gate.fails.slice(0, 2).join(';'));
4116
+ // 0.20.2 T3:重跑前把 gate.fails **全清单**写进分镜节点 requirement(客户端 aiStoryboardShots
4117
+ // 每次生成都读它拼进提示词)——不注入则重生成提示词与首轮逐字相同,模型原样再犯(实测 11 项依旧)。
4118
+ // 全清单逐条编号,不是 slice(0,2):日志可以截断,提示词不能。
4119
+ injParts.push('【G2 复检·必须逐项修复】上一版分镜未通过质量闸门,以下是全部不合规项,重新生成时逐项改正:\n' + gate.fails.map((f, j) => (j + 1) + '. ' + f).join('\n'));
4120
+ }
4121
+ if (!dur.ok) {
4122
+ // 0.20.2 T5:场超时长——事实与修复要求并入同一条 requirement(同一次重生成既修合规又修时长)。
4123
+ logParts.push('分镜超时长(' + dur.plan.total + ' 秒/' + dur.plan.segments.length + ' 段),自动重生成(已注入时长约束)');
4124
+ injParts.push('【时长约束】本场总时长 ' + dur.plan.total + ' 秒超过 ' + segMax + ' 秒上限:删减镜头或压缩每镜 duration,确保总时长 ≤' + segMax + ' 秒;若剧情需要更长必须拆成多场。超时明细:'
4125
+ + (Array.isArray(sbSt.shots) ? sbSt.shots : []).map((s, k) => '镜' + (k + 1) + '=' + shotDurOf(s) + 's').join(',')
4126
+ + '(切段 ' + dur.plan.segments.length + ' 段)');
4127
+ }
4128
+ run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' ' + logParts.join(';') });
4129
+ canvasUpdateNode({ projectId: pid, canvasId: cid, nodeId: sb.nodeId, patch: { requirement: (origReq ? origReq + '\n\n' : '') + injParts.join('\n\n') } });
4130
+ try {
4131
+ sbSt = await canvasExec(pid, cid, sb.nodeId, { timeoutMs: 10 * 60 * 1000 });
4132
+ gate = PROD.gateStoryboard(sbSt.shots);
4133
+ dur = durCheck(sbSt.shots, segMax);
4134
+ } finally {
4135
+ // 复检结束(无论过没过,重跑炸了也一样)还原 requirement 为原值;还原失败不阻塞
4136
+ try { canvasUpdateNode({ projectId: pid, canvasId: cid, nodeId: sb.nodeId, patch: { requirement: origReq } }); } catch { /* 还原失败不阻塞 */ }
4137
+ }
4138
+ }
4139
+ if (!dur.ok) { // 复检仍超时:不阻塞(预算单照出,场行 videoCalls 已如实反映成本),只记 log
4140
+ run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' 仍超时长(' + dur.plan.total + ' 秒/' + dur.plan.segments.length + ' 段)' });
3912
4141
  }
3913
4142
  boards.push({ no: scenes[i].no, storyboardId: sb.nodeId, gate: gate.ok, fails: gate.fails });
4143
+ run.ckpt.boardIds[i] = sb.nodeId;
4144
+ ckptDone('board' + (i + 1));
3914
4145
  run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' 分镜:' + (gate.ok ? '过闸' : '仍有 ' + gate.fails.length + ' 项') });
3915
4146
  }
3916
4147
  // ⑦ 预算单(免费段终点)
@@ -3922,15 +4153,36 @@ export function apply(ctx) {
3922
4153
  run.scriptNodeId = sc.nodeId;
3923
4154
  run.status = 'done';
3924
4155
  run.phase = 'budget';
4156
+ // T10:免费段完结 → 检查点标 completed 而不是清掉:brief/产物/预算留作「上一集」记录
4157
+ //(autoStart 把 brief 落盘本就为重启后可查);completed 与「未完成才续跑」判定天然互斥,
4158
+ // 下次 autoStart 无论 brief 异同都是全新启动。
4159
+ run.ckpt.completed = true;
4160
+ run.ckpt.budget = run.budget;
4161
+ run.ckpt.boards = boards;
4162
+ ckptDone('budget');
3925
4163
  run.log.push({ at: Date.now(), role: 'runner', summary: '免费段完成:' + scenes.length + ' 场分镜 + 预算单(' + run.budget.videoCalls + ' 次视频调用 / ' + run.budget.totalSeconds + ' 秒)' });
3926
4164
  } catch (e) {
4165
+ // T10:失败/中止不清检查点——未完成的 ps.autoRun 留在状态文件里,
4166
+ // 下次 autoStart(不传 brief 或 brief 一致)从断点续跑。
3927
4167
  run.status = String((e && e.message) || e) === 'aborted' ? 'aborted' : 'failed';
3928
4168
  run.error = String((e && e.message) || e);
3929
4169
  run.log.push({ at: Date.now(), role: 'runner', summary: '失败:' + run.error });
3930
4170
  }
3931
4171
  }
3932
- /** 付费段 v1:批准后逐分镜表建视频节点 → 生成 → 轮询(失败重试 2 次)→ 成片节点。 */
3933
- async function autoPaid(pid, cid) {
4172
+ /** 付费段 v1:批准后按镜头切段逐段建视频节点 → 生成 → 轮询(失败重试 2 次)→ 成片节点。
4173
+ * 0.20.2 T6(#10):一个分镜表 ≠ 一次生成——planShotSegments 切出的每段各建一个 video 节点
4174
+ * (命名带「段k/N」、prompt 带镜头范围约束、data 带客户端 videoSegmentOf 消费的段键),
4175
+ * 长场(如 40s)不再整表一次请求撞厂商上限(实测中转站 400);finalcut 连最后一个完成的段节点。
4176
+ * 0.20.2 T8(#6/#7):参考图先行——有待生成段的场,先把 shots 里的 角色/场景/道具 实体建成
4177
+ * 「<品类>-<名> 设定图」image 节点(命名即分类数据契约,client.js L4931-4946)并出图,再建视频段;
4178
+ * 生成时参考图严格只取连线(collectRefs,client.js L4949-4953),所以 ref 线必须在视频 exec 之前
4179
+ * 用 canvasConnect(toPort:'ref') 接到该场每个 video 段节点。跨场共享实体只生成一次(run 级 Map);
4180
+ * 已有参考资产(资产名边界匹配)跳过;参考图失败不阻塞视频段。
4181
+ * 0.20.2 T9(#9):可选 scenes 选场执行——传入 1-based 场号数组时只跑选中场(boards[i] 场号 = i+1,
4182
+ * 与 quote scenes 序号一致):未选中场零视频节点、实体收集也不跑(连参考图都不生成);finalcut 仍连
4183
+ * 「最后一个完成的段节点」(本次执行范围内的)。批准令牌与指纹零改动:入口照旧按全量预算校验,
4184
+ * scenes 只是执行过滤器——不传 scenes 时行为逐字节不变。 */
4185
+ async function autoPaid(pid, cid, scenes) {
3934
4186
  const cfg = readIcConfig();
3935
4187
  const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
3936
4188
  const ap = PROD.approvalOf(pid, cid, price);
@@ -3941,29 +4193,173 @@ export function apply(ctx) {
3941
4193
  run.paid = 'running';
3942
4194
  run.paidAbort = false;
3943
4195
  run.paidLog = [{ at: Date.now(), text: '付费段启动(已批准预算 ' + ap.quoteId + ')' }];
4196
+ const abortNow = () => { run.paid = 'aborted'; run.paidPhase = 'aborted'; run.paidLog.push({ at: Date.now(), text: '已中止(保留已完成视频)' }); };
3944
4197
  (async () => {
3945
4198
  try {
3946
4199
  const doc = readToolDoc({ projectId: pid, canvasId: cid });
3947
4200
  const boards = Object.values(doc.nodes || {}).filter((n) => n.type === 'storyboard' && Array.isArray(n.data && n.data.shots) && n.data.shots.length);
4201
+ // T9 ②:选场执行——scenes 存在时按 boards 序号过滤(boards[i] 的场号 = i+1,与 quote scenes 序号一致);
4202
+ // 被排除的场不进循环:零视频节点、实体收集也不跑(连参考图都不生成)。批准令牌不受影响:
4203
+ // 本函数入口的 approvalOf 已按全量预算指纹校验(PROD.approve 语义零改动),scenes 只是执行过滤器。
4204
+ const picked = Array.isArray(scenes) && scenes.length ? scenes : null;
4205
+ if (picked) {
4206
+ const msg = '部分执行:本次跑 ' + boards.map((_b, i) => i + 1).filter((s) => picked.includes(s)).map((s) => '场' + s).join('/') + '(共 ' + boards.length + ' 场)';
4207
+ run.log.push({ at: Date.now(), role: 'runner', summary: msg });
4208
+ run.paidLog.push({ at: Date.now(), text: msg });
4209
+ }
4210
+ // T8:参考图 run 级状态——实体键「品类|名」→ image 节点;跨场共享同一实体只生成一次。
4211
+ // 「已有参考资产」读项目资产索引一次(角色-<名>/场景-<名>/道具-<名> 边界匹配,client.js L4078 同款)。
4212
+ const refImageByEntity = new Map();
4213
+ let refImagesMade = 0;
4214
+ let assetNames = [];
4215
+ try { assetNames = readAssetIndexNames(pid) || []; } catch { assetNames = []; }
4216
+ // 设定集实体描述(prompt 用;名字精确匹配,与 matchBibleEntity 同式的大小写不敏感)
4217
+ const bibleDescOf = (kind, name) => {
4218
+ const bible = (doc && doc.bible) || {};
4219
+ const key = kind === '角色' ? 'characters' : kind === '场景' ? 'scenes' : 'props';
4220
+ const q = String(name || '').trim().toLowerCase();
4221
+ const list = Array.isArray(bible[key]) ? bible[key] : [];
4222
+ const hit = list.find((it) => String((it && it.name) || '').trim().toLowerCase() === q);
4223
+ return String((hit && hit.desc) || '').trim();
4224
+ };
3948
4225
  let lastVideo = null;
3949
4226
  for (let i = 0; i < boards.length; i++) {
3950
- if (run.paidAbort) { run.paid = 'aborted'; run.paidPhase = 'aborted'; run.paidLog.push({ at: Date.now(), text: '已中止(保留已完成视频)' }); return; }
4227
+ if (picked && !picked.includes(i + 1)) continue; // T9 ②:未选中场零节点零参考图
4228
+ if (run.paidAbort) { abortNow(); return; }
3951
4229
  const sb = boards[i];
3952
4230
  run.paidPhase = 'video ' + (i + 1) + '/' + boards.length;
3953
- const hasVideo = (doc.edges || []).some((e) => e.fromNode === sb.id && doc.nodes[e.toNode] && doc.nodes[e.toNode].type === 'video');
3954
- if (hasVideo) continue;
3955
- const label = String((sb.data && sb.data.label) || ('场' + (i + 1))).replace(/分镜表$/, '') + '视频';
3956
- const v = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'video', name: label.slice(0, 40), connectFrom: sb.id });
3957
- if (v && v.ok === false) throw new Error('[' + v.gate + '] ' + v.error);
3958
- let done = false; let err = null;
3959
- for (let attempt = 0; attempt < 2 && !done; attempt++) {
3960
- if (attempt > 0 && run.paidAbort) { run.paid = 'aborted'; run.paidPhase = 'aborted'; run.paidLog.push({ at: Date.now(), text: '已中止(保留已完成视频)' }); return; }
3961
- try { await canvasExec(pid, cid, v.nodeId, { timeoutMs: 15 * 60 * 1000 }); done = true; }
3962
- catch (e) { err = e; run.paidLog.push({ at: Date.now(), text: label + ' 第 ' + (attempt + 1) + ' 次失败:' + String((e && e.message) || e) }); }
4231
+ const shots = Array.isArray(sb.data && sb.data.shots) ? sb.data.shots : [];
4232
+ const segMax = Number(sb.data && sb.data.segMaxSeconds) || 15;
4233
+ const plan = planShotSegments(shots, { maxSeconds: segMax });
4234
+ // 客户端兜底同款(production.quote 同式):切段为空但表里有镜头 → 整表按一段
4235
+ const segs = plan.segments.length ? plan.segments
4236
+ : [{ startIndex: 0, endIndex: shots.length - 1, duration: plan.total, needsTailChain: false, seamRisk: 'none' }];
4237
+ const segCount = segs.length;
4238
+ const baseLabel = String((sb.data && sb.data.label) || ('场' + (i + 1))).replace(/分镜表$/, '');
4239
+ // 段节点名(T6 原式提成函数:T8 判断「哪些段待生成」与建段要用同一个名字口径)
4240
+ const segLabelOf = (k) => {
4241
+ const suffix = segCount > 1 ? '视频 · 段' + (k + 1) + '/' + segCount : '视频';
4242
+ // 段序号后缀整体进名字(G4 禁「镜N」式逐镜命名,这里带的是段区间不是单镜);先切基础名保后缀完整
4243
+ return baseLabel.slice(0, Math.max(1, 40 - suffix.length)) + suffix;
4244
+ };
4245
+ // ③ 预算一致性(只记日志不阻塞):run.budget 是免费段终点的快照,镜头中途被用户改过就对不上;
4246
+ // 批准令牌的指纹校验已在 autoPaid 入口把守,这里只是日志诚实化。
4247
+ const budgetRow = run.budget && Array.isArray(run.budget.scenes) ? run.budget.scenes.find((r) => r && r.storyboardId === sb.id) : null;
4248
+ if (budgetRow && Number(budgetRow.videoCalls) !== segCount) {
4249
+ const msg = '预算与实际段数不一致(预算 ' + Number(budgetRow.videoCalls) + ' / 实际 ' + segCount + '),按实际执行';
4250
+ run.log.push({ at: Date.now(), role: 'runner', summary: baseLabel + ' ' + msg });
4251
+ run.paidLog.push({ at: Date.now(), text: msg });
4252
+ }
4253
+ // 断点续跑:旧版整表单节点(名字不带「段k/N」)→ 整场跳过(该场已有视频、预算已计 0);
4254
+ // 本 hotfix 的段节点 → 只跳过已存在的那几段,缺的段照建(重试语义按段保留)。
4255
+ const boardVideos = (doc.edges || []).filter((e) => e.fromNode === sb.id).map((e) => doc.nodes[e.toNode]).filter((n) => n && n.type === 'video');
4256
+ const segNumOf = (v) => { const m = String((v.data && v.data.label) || '').match(/ · 段(\d+)\/(\d+)$/); return m ? Number(m[1]) : 0; };
4257
+ if (boardVideos.length && !boardVideos.some((v) => segNumOf(v) > 0)) continue;
4258
+ // ── T8(#6/#7):参考图先行 ──────────────────────────────────────
4259
+ // 只有「有待生成段」的场才产生参考图需求(全完成/续跑完成的场不重复生成);
4260
+ // 该场的 image 设定图建好并出图之后,才轮到下面的 video 段节点——collectRefs 生成时
4261
+ // 严格只读连线,ref 线在建段后、段 exec 前接上(先连后生成)。
4262
+ const boardEntities = PROD.collectShotEntities(shots);
4263
+ const hasPendingSeg = segs.some((_s, k) => !boardVideos.some((v) => String((v.data && v.data.label) || '') === segLabelOf(k)));
4264
+ if (hasPendingSeg) {
4265
+ run.paidPhase = '参考图 ' + (i + 1) + '/' + boards.length;
4266
+ for (const ent of boardEntities) {
4267
+ if (run.paidAbort) { abortNow(); return; }
4268
+ if (refImageByEntity.has(ent.key)) continue; // 跨场共享:本 run 已生成,直接复用连线
4269
+ if (PROD.hasRefAssetName(assetNames, ent.kind, ent.name)) {
4270
+ const msg = ent.name + ' 已有参考资产,跳过';
4271
+ run.log.push({ at: Date.now(), role: 'runner', summary: msg });
4272
+ run.paidLog.push({ at: Date.now(), text: msg });
4273
+ continue;
4274
+ }
4275
+ const label = ent.kind + '-' + ent.name + ' 设定图';
4276
+ const desc = bibleDescOf(ent.kind, ent.name);
4277
+ const prompt = '设定图:' + ent.kind + ' ' + ent.name + (desc ? '。设定集描述:' + desc : '');
4278
+ let img = null;
4279
+ try { img = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'image', name: label, prompt, size: '2K', ratio: '16:9' }); }
4280
+ catch (e) { img = { ok: false, error: String((e && e.message) || e) }; }
4281
+ // 实测闸门行为:canvasCreateNode 的 G4(禁逐镜命名)没有 override 逃生舱(G2/G3 才有),
4282
+ // 规范「<品类>-<名> 设定图」命名天然过闸;真被拒说明实体名病态(含「镜N」)——记日志跳过,不阻塞视频段。
4283
+ if (!img || img.ok === false || !img.nodeId) {
4284
+ const msg = ent.name + '(' + ent.kind + ')参考图建点失败:' + String((img && img.error) || '未知');
4285
+ run.log.push({ at: Date.now(), role: 'runner', summary: msg });
4286
+ run.paidLog.push({ at: Date.now(), text: msg });
4287
+ continue;
4288
+ }
4289
+ let done = false; let err = null;
4290
+ for (let attempt = 0; attempt < 2 && !done; attempt++) {
4291
+ if (attempt > 0 && run.paidAbort) { abortNow(); return; }
4292
+ try { await canvasExec(pid, cid, img.nodeId, { timeoutMs: 10 * 60 * 1000 }); done = true; }
4293
+ catch (e) { err = e; run.paidLog.push({ at: Date.now(), text: label + ' 第 ' + (attempt + 1) + ' 次失败:' + String((e && e.message) || e) }); }
4294
+ }
4295
+ if (!done) {
4296
+ const msg = ent.name + '(' + ent.kind + ')参考图生成失败:' + String((err && err.message) || err);
4297
+ run.log.push({ at: Date.now(), role: 'runner', summary: msg });
4298
+ run.paidLog.push({ at: Date.now(), text: msg });
4299
+ continue; // 不入 Map、不连线、不阻塞视频段
4300
+ }
4301
+ refImageByEntity.set(ent.key, { nodeId: img.nodeId, label });
4302
+ refImagesMade++;
4303
+ run.paidLog.push({ at: Date.now(), text: label + ' 完成' });
4304
+ }
4305
+ run.paidPhase = 'video ' + (i + 1) + '/' + boards.length;
3963
4306
  }
3964
- if (!done) throw err;
3965
- lastVideo = v.nodeId;
3966
- run.paidLog.push({ at: Date.now(), text: label + ' 完成' });
4307
+ for (let k = 0; k < segCount; k++) {
4308
+ if (run.paidAbort) { abortNow(); return; }
4309
+ const seg = segs[k];
4310
+ const label = segLabelOf(k);
4311
+ if (boardVideos.some((v) => String((v.data && v.data.label) || '') === label)) continue;
4312
+ // G3 一表一视频的逃生舱只给「同场第 2 段起 / 续跑补建缺段」用;quote 引用用户批准过的预算单号(审计可查),
4313
+ // 绝不伪造用户原话。首段不传 override:G2 不过的场在这里照旧硬失败(分镜带病不下场)。
4314
+ const needOverride = boardVideos.length > 0 || k > 0;
4315
+ const segDuration = Math.max(1, Math.round(Number(seg.duration) || 0));
4316
+ const v = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'video', name: label, connectFrom: sb.id, duration: segDuration,
4317
+ ...(needOverride ? { override: { by: 'user-explicit', quote: '付费段按预算切段执行(批准单 ' + ap.quoteId + '):' + label } } : {}) });
4318
+ if (v && v.ok === false) throw new Error('[' + v.gate + '] ' + v.error);
4319
+ // ② 镜头区间元数据:prompt 通道(白名单内、画布可见;分镜表不在上游时它就是生成提示词)
4320
+ // + data 段键(client.js videoSegmentOf/segMeta 消费——上游分镜表在 prompt 口时由它决定只取本段镜头)。
4321
+ const shotFrom = Number.isFinite(Number(seg.startIndex)) ? Number(seg.startIndex) : 0;
4322
+ const shotTo = Number.isFinite(Number(seg.endIndex)) ? Number(seg.endIndex) : shots.length - 1;
4323
+ canvasUpdateNode({ projectId: pid, canvasId: cid, nodeId: v.nodeId, patch: { prompt: '【本段 ' + (k + 1) + '/' + segCount + '】本段覆盖分镜第 ' + (shotFrom + 1) + '-' + (shotTo + 1) + ' 镜(共 ' + shots.length + ' 镜),时长约 ' + seg.duration + ' 秒;只生成本段内容,不要越界到其他段的镜头。' } });
4324
+ try {
4325
+ const d2 = readToolDoc({ projectId: pid, canvasId: cid });
4326
+ const n2 = d2.nodes[v.nodeId];
4327
+ if (n2) {
4328
+ n2.data = { ...(n2.data || {}), segShotFrom: shotFrom, segShotTo: shotTo, segIndex: k, segCount, needsTailChain: seg.needsTailChain === true, seamRisk: String(seg.seamRisk || 'none') };
4329
+ writeToolDoc({ projectId: pid, canvasId: cid }, d2);
4330
+ }
4331
+ } catch { /* 段键写不进不阻塞:prompt 通道兜底 */ }
4332
+ // T8:先连后生成——collectRefs 生成时严格只读连线,本段 exec 前必须把该场实体的
4333
+ // 参考图全部接到 ref 口(Multi-input,可多张);连线失败只记日志,不阻塞视频段。
4334
+ for (const ent of boardEntities) {
4335
+ const hit = refImageByEntity.get(ent.key);
4336
+ if (!hit) continue;
4337
+ try {
4338
+ canvasConnect({ projectId: pid, canvasId: cid, fromNode: hit.nodeId, toNode: v.nodeId, toPort: 'ref' });
4339
+ } catch (e) {
4340
+ const msg = hit.label + ' → ' + label + ' ref 连线失败:' + String((e && e.message) || e);
4341
+ run.log.push({ at: Date.now(), role: 'runner', summary: msg });
4342
+ run.paidLog.push({ at: Date.now(), text: msg });
4343
+ }
4344
+ }
4345
+ let done = false; let err = null;
4346
+ for (let attempt = 0; attempt < 2 && !done; attempt++) {
4347
+ if (attempt > 0 && run.paidAbort) { abortNow(); return; }
4348
+ try { await canvasExec(pid, cid, v.nodeId, { timeoutMs: 15 * 60 * 1000 }); done = true; }
4349
+ catch (e) { err = e; run.paidLog.push({ at: Date.now(), text: label + ' 第 ' + (attempt + 1) + ' 次失败:' + String((e && e.message) || e) }); }
4350
+ }
4351
+ if (!done) throw err;
4352
+ lastVideo = v.nodeId;
4353
+ run.paidLog.push({ at: Date.now(), text: label + ' 完成' });
4354
+ }
4355
+ }
4356
+ // T8 ③:参考图预算偏差诚实化——run.budget.refImagesTotal 是免费段终点的快照,
4357
+ // 镜头/设定集中途变化就对不上;只记日志不阻塞(与段数偏差日志同一语义)。
4358
+ const budgetRefs = run.budget && Number.isFinite(Number(run.budget.refImagesTotal)) ? Number(run.budget.refImagesTotal) : null;
4359
+ if (budgetRefs != null && budgetRefs !== refImagesMade) {
4360
+ const msg = '参考图预算与实际不一致(预算 ' + budgetRefs + ' / 实际 ' + refImagesMade + ')';
4361
+ run.log.push({ at: Date.now(), role: 'runner', summary: msg });
4362
+ run.paidLog.push({ at: Date.now(), text: msg });
3967
4363
  }
3968
4364
  if (lastVideo) {
3969
4365
  const fc = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'finalcut', name: '成片', connectFrom: lastVideo });
@@ -4024,6 +4420,13 @@ export function apply(ctx) {
4024
4420
  try { mkdirSync(abs, { recursive: true }); } catch { /* 目录建不出来交给调用方报错 */ }
4025
4421
  return { ok: true, projectId: pid, folder, abs, dataRoot: root, legacy: !entry };
4026
4422
  },
4423
+ /** 提交留痕(0.20.2 能力③):{projectId, entry} → 追加一行脱敏 JSONL 到 <项目目录>/submissions.jsonl。
4424
+ * 目录解析与 projectDirGet 同一基准;写失败返回 ok:false(客户端留痕是尽力而为,绝不挡生成)。 */
4425
+ async submissionLogAppend(args) {
4426
+ const dir = await methods.projectDirGet({ projectId: args && args.projectId });
4427
+ if (!dir || !dir.ok) return { ok: false, error: (dir && dir.error) || '项目目录不可用' };
4428
+ return submissionLogAppendImpl(dir.abs, args && args.entry);
4429
+ },
4027
4430
  // IC-B4:FTS 存量孤儿一次性清理(幂等,可重复调;无 SQLite 时明确说不适用)
4028
4431
  async ftsReconcile() {
4029
4432
  if (!sqlActive()) return { ok: false, error: '当前不是 SQLite 存储模式,无 FTS 需要清理', applicable: false };
@@ -4324,7 +4727,9 @@ export function apply(ctx) {
4324
4727
  writeIcConfig(cfg);
4325
4728
  return { ok: true, enabled };
4326
4729
  },
4327
- /** 预算单(免费段终点):场/镜/秒数/视频调用次数(+配置了单价时的估算金额)。 */
4730
+ /** 预算单(免费段终点):场/镜/秒数/视频调用次数(+配置了单价时的估算金额)。
4731
+ * 0.20.2 T9(#9):没配单价时 estimatedCost 为 null、金额行不显示(无法算钱是设计),
4732
+ * 但要在 note 追加配置引导(锚点词「视频每秒单价」)——note 不进预算指纹,批准校验不受影响。 */
4328
4733
  async autoQuote(args) {
4329
4734
  if (!autoEnabled()) return autoDisabled();
4330
4735
  const pid = String((args && args.projectId) || '');
@@ -4332,7 +4737,11 @@ export function apply(ctx) {
4332
4737
  const cfg = readIcConfig();
4333
4738
  const price = Number(args && args.unitPricePerSecond);
4334
4739
  const configured = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
4335
- return PROD.quote(pid, toolCanvasId(args), Number.isFinite(price) && price > 0 ? price : configured);
4740
+ const q = PROD.quote(pid, toolCanvasId(args), Number.isFinite(price) && price > 0 ? price : configured);
4741
+ if (q && q.ok && q.estimatedCost == null) {
4742
+ q.note = (q.note ? q.note + ';' : '') + '未配置视频单价——在画布设置 → 制作 → 视频每秒单价 填入后可显示估算金额';
4743
+ }
4744
+ return q;
4336
4745
  },
4337
4746
  /** 批准付费段:一次性令牌,绑定预算指纹;镜头/时长一变即失效(须重新复核)。 */
4338
4747
  async autoApprove(args) {
@@ -4343,12 +4752,34 @@ export function apply(ctx) {
4343
4752
  const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
4344
4753
  return PROD.approve(pid, toolCanvasId(args), String((args && args.quoteId) || ''), String((args && args.confirm) || ''), price);
4345
4754
  },
4346
- /** 付费段:批准后逐分镜表生成视频(真实计费);失败重试,全部完成建成片节点。 */
4755
+ /** 付费段:批准后逐分镜表生成视频(真实计费);失败重试,全部完成建成片节点。
4756
+ * 0.20.2 T9(#9):可选 scenes 选场执行——1-based 场号数组(对应预算单 scenes[].scene,
4757
+ * boards[i] 的场号 = i+1),不传 = 全量(现行为零变化);被排除的场不建视频节点、
4758
+ * 连参考图都不生成(实体收集只跑选中场)。批准令牌与指纹零改动:autoPaid 入口仍按
4759
+ * 全量预算校验,scenes 只是执行过滤器——镜头变了要重新复核。非法 scenes(非数组/
4760
+ * 空数组/含非正整数/场号越界)→ ok:false 业务错误,不启动。 */
4347
4761
  async autoGenerate(args) {
4348
4762
  if (!autoEnabled()) return autoDisabled();
4349
4763
  const pid = String((args && args.projectId) || '');
4350
4764
  if (!pid) return { ok: false, error: '缺少 projectId' };
4351
- return autoPaid(pid, toolCanvasId(args));
4765
+ let scenes = null;
4766
+ const rawScenes = args ? args.scenes : undefined;
4767
+ if (rawScenes != null) {
4768
+ if (!Array.isArray(rawScenes)) return { ok: false, error: 'scenes 必须是场号数组(1-based,对应预算单 scenes 的 scene 字段);不传跑全部' };
4769
+ if (!rawScenes.length) return { ok: false, error: 'scenes 不能是空数组:要么不传跑全部,要么至少给一个场号' };
4770
+ let sceneCount = 0;
4771
+ try {
4772
+ const doc = readToolDoc({ projectId: pid, canvasId: toolCanvasId(args) });
4773
+ sceneCount = Object.values(doc.nodes || {}).filter((n) => n.type === 'storyboard' && Array.isArray(n.data && n.data.shots) && n.data.shots.length).length;
4774
+ } catch { sceneCount = 0; }
4775
+ for (const s of rawScenes) {
4776
+ const n = Number(s);
4777
+ if (!Number.isInteger(n) || n <= 0) return { ok: false, error: 'scenes 含非法场号(必须是正整数,1-based):' + JSON.stringify(rawScenes) };
4778
+ if (n > sceneCount) return { ok: false, error: '场号 ' + n + ' 超出当前场数(当前 ' + sceneCount + ' 场分镜):先完成免费段生成分镜,或修正 scenes' };
4779
+ }
4780
+ scenes = rawScenes.map(Number);
4781
+ }
4782
+ return autoPaid(pid, toolCanvasId(args), scenes);
4352
4783
  },
4353
4784
  /** 自动创作总状态:开关 / 阶段 / 当前批准是否仍有效 / 编剧室运行状态 / 下一步。 */
4354
4785
  async autoStatus(args) {
@@ -4373,28 +4804,47 @@ export function apply(ctx) {
4373
4804
  };
4374
4805
  },
4375
4806
  /** 启动免费段(编剧室):调研 → 编剧A/B 独立提案 → 互评 → 监制决策 → 设定集+剧本 idea 落盘。
4376
- * 全程零付费;讨论记录写进「编剧室会议」文本节点;剧情走向只来自 brief。 */
4807
+ * 全程零付费;讨论记录写进「编剧室会议」文本节点;剧情走向只来自 brief。
4808
+ * 0.20.2 T10 断点续跑:制作状态文件里有**未完成的** ps.autoRun 且(未传 brief 或 brief 与存储一致)
4809
+ * → 从断点续跑(已完成阶段不调 LLM、不重建节点,log/note 注明跳过数);传了不同 brief → 全新启动
4810
+ * (检查点被覆盖——用户换创意是有意的);上次已完结(completed)/无持久化/形状损坏 → 现行为全新启动。
4811
+ * 续跑时 brief 非必需(用存储值)。 */
4377
4812
  async autoStart(args) {
4378
4813
  if (!autoEnabled()) return autoDisabled();
4379
4814
  const pid = String((args && args.projectId) || '');
4380
4815
  if (!pid) return { ok: false, error: '缺少 projectId' };
4381
- const brief = String((args && args.brief) || '').trim();
4382
- if (brief.length < 4) return { ok: false, error: '缺少 brief:请给一句话创意(至少 4 个字),它是剧情走向的唯一源头' };
4383
4816
  const cid = toolCanvasId(args);
4817
+ const brief = String((args && args.brief) || '').trim();
4818
+ // T10:读持久化 run(读失败/形状不对/已完结 → 视同无持久化,全新启动)
4819
+ let saved = null;
4820
+ try {
4821
+ const ps = PROD.readState(pid, cid);
4822
+ saved = (ps && ps.autoRun) || null;
4823
+ } catch { saved = null; }
4824
+ if (!autoCkptValid(saved)) saved = null;
4825
+ const resuming = !!saved && (!brief || brief === saved.brief);
4826
+ if (!resuming && brief.length < 4) return { ok: false, error: '缺少 brief:请给一句话创意(至少 4 个字),它是剧情走向的唯一源头' };
4384
4827
  const runKey = runKeyOf(pid, cid);
4385
4828
  const prev = AUTO_RUNS.get(runKey);
4386
4829
  if (prev && prev.status === 'running') return { ok: false, error: '该画布已有自动创作在跑(阶段 ' + prev.phase + '):先 autoAbort 或等待完成' };
4387
- const run = { status: 'running', phase: 'start', log: [{ at: Date.now(), role: 'runner', summary: '启动:' + brief.slice(0, 60) }], error: null, brief, startedAt: Date.now(), meetingNodeId: null, scriptNodeId: null };
4830
+ const effBrief = resuming ? saved.brief : brief;
4831
+ const skipN = resuming ? autoCkptSkipCount(saved) : 0;
4832
+ const run = { status: 'running', phase: resuming ? autoCkptDisplayPhase(saved) : 'start',
4833
+ log: [{ at: Date.now(), role: 'runner', summary: resuming ? '断点续跑:跳过 ' + skipN + ' 个已完成阶段' : '启动:' + effBrief.slice(0, 60) }],
4834
+ error: null, brief: effBrief, startedAt: resuming ? (Number(saved.startedAt) || Date.now()) : Date.now(), meetingNodeId: null, scriptNodeId: null };
4388
4835
  AUTO_RUNS.set(runKey, run);
4389
- // brief 记进制作状态(status 可见;重启后仍能查到这一集的创意源头)
4836
+ // brief + 检查点记进制作状态(status 可见;重启后仍能查到这一集的创意源头与断点)
4390
4837
  try {
4391
4838
  const ps = PROD.readState(pid, cid) || { version: 1, projectId: pid, canvasKey: (cid || 'default'), floor: 0, explicit: null, createdAt: Date.now(), updatedAt: 0, history: [], overrides: [] };
4392
- ps.brief = brief;
4839
+ ps.brief = effBrief;
4840
+ ps.autoRun = resuming ? JSON.parse(JSON.stringify(saved)) : { brief: effBrief, phase: null, completed: false, outputs: {}, meetingNodeId: null, scriptNodeId: null, scenes: null, boardIds: [], startedAt: run.startedAt, updatedAt: Date.now() };
4393
4841
  ps.updatedAt = Date.now();
4394
4842
  PROD.writeState(pid, cid, ps);
4395
4843
  } catch { /* 状态写入失败不阻塞启动 */ }
4396
- autoRoom(pid, cid, brief).catch(() => { /* 兜底:autoRoom 内部已捕获并落状态 */ });
4397
- return { ok: true, runId: runKey, status: 'running', note: '免费段已启动(调研→提案→互评→决策→落盘);用 autoStatus 查看进度' };
4844
+ autoRoom(pid, cid, effBrief, resuming ? JSON.parse(JSON.stringify(saved)) : null).catch(() => { /* 兜底:autoRoom 内部已捕获并落状态 */ });
4845
+ return { ok: true, runId: runKey, status: 'running', note: resuming
4846
+ ? '已从断点续跑(跳过 ' + skipN + ' 个已完成阶段);用 autoStatus 查看进度'
4847
+ : '免费段已启动(调研→提案→互评→决策→落盘)·全新启动;用 autoStatus 查看进度' };
4398
4848
  },
4399
4849
  /** 中止运行中的自动创作(免费段或付费段):保留已产出内容(讨论节点/设定集/节点/已完成视频)。 */
4400
4850
  async autoAbort(args) {
@@ -5244,11 +5694,13 @@ export function apply(ctx) {
5244
5694
  output: textOutput,
5245
5695
  timeoutMs: 15000,
5246
5696
  async execute(args) {
5247
- const r = await productionStatus(args);
5697
+ const r = await methods.productionStatus(args);
5248
5698
  if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '状态读取失败') };
5249
5699
  let capsLine = '';
5700
+ let capsMultiAgent; // undefined = 探针失败(未知);true/false = 探针实测
5250
5701
  try {
5251
- const caps = await productionCapabilities();
5702
+ const caps = await methods.productionCapabilities();
5703
+ capsMultiAgent = !!caps.multiAgent;
5252
5704
  capsLine = '\n多智能体能力:' + (caps.multiAgent ? '可用(宿主已暴露会话服务)' : '不可用(宿主未暴露会话服务——自动创作保持休眠)');
5253
5705
  } catch { /* 探针失败不影响状态输出 */ }
5254
5706
  const lines = [
@@ -5262,7 +5714,7 @@ export function apply(ctx) {
5262
5714
  lines.push('下一步:' + r.next);
5263
5715
  lines.push('ready=' + (r.ready ? 'true(可宣称完成/进入下一步)' : 'false(不得宣称完成)'));
5264
5716
  if (capsLine) lines.push(capsLine.trim());
5265
- return { ok: true, projectId: r.projectId, ...(r.canvasId ? { canvasId: r.canvasId } : {}), stage: r.stage, ready: r.ready, blockers: r.blockers, multiAgent: (() => { try { return capsLine.includes('可用('); } catch { return undefined; } })(), text: lines.join('\n') };
5717
+ return { ok: true, projectId: r.projectId, ...(r.canvasId ? { canvasId: r.canvasId } : {}), stage: r.stage, ready: r.ready, blockers: r.blockers, multiAgent: capsMultiAgent, text: lines.join('\n') };
5266
5718
  },
5267
5719
  });
5268
5720
  reg({
@@ -5282,7 +5734,7 @@ export function apply(ctx) {
5282
5734
  output: textOutput,
5283
5735
  timeoutMs: 15000,
5284
5736
  async execute(args) {
5285
- const r = await productionAdvance(args);
5737
+ const r = await methods.productionAdvance(args);
5286
5738
  if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '推进失败') };
5287
5739
  return { ok: true, projectId: args.projectId, stage: r.to, text: '✅ 阶段 ' + r.from + ' → ' + r.to + '(已记入审计)。' };
5288
5740
  },
@@ -5345,6 +5797,7 @@ export function apply(ctx) {
5345
5797
  if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '预算单生成失败') };
5346
5798
  const lines = ['预算单 ' + r.quoteId, '场 ' + r.sceneCount + ' / 镜 ' + r.shotCount + ' / ' + r.totalSeconds + ' 秒 / 待调用 ' + r.videoCalls + ' 次'];
5347
5799
  if (r.estimatedCost != null) lines.push('估算金额:' + r.estimatedCost + '(单价 ' + r.unitPricePerSecond + '/秒)');
5800
+ else lines.push('提示:未配置视频单价——在画布设置 → 制作 → 视频每秒单价 填入后可显示估算金额'); // T9 ①:没配单价时给配置引导
5348
5801
  lines.push('批准:调用 autoApprove 或在设置卡点「批准付费段」(必须带用户原话)');
5349
5802
  return { ok: true, quoteId: r.quoteId, budget: r, text: lines.join('\n') };
5350
5803
  },
@@ -5355,13 +5808,15 @@ export function apply(ctx) {
5355
5808
  parameters: { type: 'object', properties: {
5356
5809
  projectId: { type: 'string', description: '项目 id' },
5357
5810
  canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5811
+ scenes: { type: 'array', items: { type: 'integer' }, description: '可选:只跑指定场号(1-based,对应预算单 scenes 的 scene 字段);不传跑全部。批准令牌仍按全量预算校验——镜头变了要重新复核' },
5358
5812
  }, required: ['projectId'], additionalProperties: false },
5359
5813
  output: textOutput,
5360
5814
  timeoutMs: 30000,
5361
5815
  async execute(args) {
5362
5816
  const r = await methods.autoGenerate(args);
5363
5817
  if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '付费段启动失败') };
5364
- return { ok: true, projectId: args.projectId, status: r.status, text: '🎬 付费段已启动(逐场建视频节点并生成,失败重试 2 次)。用 canvas_auto_status 查看进度。' };
5818
+ const subset = Array.isArray(args.scenes) && args.scenes.length ? ',部分执行:本次跑 ' + args.scenes.map((n) => '场' + n).join('/') : ''; // T9 ②
5819
+ return { ok: true, projectId: args.projectId, status: r.status, text: '🎬 付费段已启动(逐场建视频节点并生成,失败重试 2 次' + subset + ')。用 canvas_auto_status 查看进度。' };
5365
5820
  },
5366
5821
  });
5367
5822
  reg({