@ninkch/dsh-infinite-canvas 0.19.21 → 0.20.1

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.
package/index.js CHANGED
@@ -16,10 +16,21 @@ import { createRequire } from 'node:module';
16
16
  import { normalizeSkillProfile, DEFAULT_SKILL_PROFILE } from './index-core-skill-profile.js';
17
17
  import { initPackBase, packInventory, allowedIds } from './skill-pack-loader.js';
18
18
  import { buildSkillPack, SKILL_CATALOG, renderInventory, renderProfile } from './skill-pack.js';
19
+ import { createProduction, PRODUCTION_STAGES, PRODUCTION_STAGE_ZH } from './production.js';
20
+
21
+ /** 制作阶段机与流程闸门(0.20.0):deps 全是本模块的函数声明(已提升,运行时才调用)。 */
22
+ const PROD = createProduction({
23
+ projectHomeDir,
24
+ readToolDoc,
25
+ readDoc,
26
+ normalizeCanvasId,
27
+ });
19
28
 
20
29
  const NAME = 'infinite-canvas';
21
30
  const HERE = path.dirname(fileURLToPath(import.meta.url));
22
31
  initPackBase(HERE); // 技能包加载器需要知道插件根目录
32
+ /** 自动创作测试挂点(apply 内赋值):runs=运行表引用,setRoomLlm=注入假 LLM 通道。 */
33
+ const __autoApi = { runs: null, setRoomLlm: null };
23
34
 
24
35
  // 版本单一来源 = 当前副本的 package.json(硬编码常量曾与包版本漂移)
25
36
  let VERSION = '0.0.0';
@@ -1194,7 +1205,11 @@ function wsProjectCreateAt(w) {
1194
1205
  const dir = path.join(String(w.path), WS_APP_DIR);
1195
1206
  try { mkdirSync(dir, { recursive: true }); } catch { /* 已存在 */ }
1196
1207
  const pid = 'ws' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
1197
- const name = (path.basename(w.path) || '画布项目').replace(/\s+/g, ' ').trim().slice(0, 80) || '画布项目';
1208
+ // 名字优先取工作区**显示名**(title,如 composer 里的 test-2),其次目录名,最后兜底。
1209
+ // 旧实现只用 basename(path):目录名是随机 id(wsmw3hao7et2ll)时项目名就成了乱码。
1210
+ const titleName = String(w.title || '').replace(/\s+/g, ' ').trim().slice(0, 80);
1211
+ const folderName = (path.basename(String(w.path || '')) || '').replace(/\s+/g, ' ').trim().slice(0, 80);
1212
+ const name = titleName || folderName || '画布项目';
1198
1213
  const doc = {
1199
1214
  id: pid, name, createdAt: Date.now(), updatedAt: Date.now(), source: 'agent',
1200
1215
  nodes: {}, edges: [], view: { x: 60, y: 40, scale: 1 },
@@ -2430,6 +2445,8 @@ async function canvasUpdateBible(args) {
2430
2445
  } catch { /* 重算失败不影响设定集写入 */ }
2431
2446
  writeIcDoc(id, doc);
2432
2447
  markDocChanged(id);
2448
+ // 阶段机:设定集落盘 → 本画布阶段 ≥ bible(只抬高,不回退)
2449
+ try { PROD.noteStage(id, toolCanvasId(args), 'bible', 'update_bible'); } catch { /* 阶段机故障不阻塞主流程 */ }
2433
2450
  return { projectId: id, bible: doc.bible, bibleUpdatedAt: doc.bibleUpdatedAt };
2434
2451
  }
2435
2452
  /** 通用建节点(供对话建角色/场景/道具参考图等);支持 script/text/image/video/storyboard/finalcut。
@@ -2446,6 +2463,11 @@ function canvasCreateNode(args) {
2446
2463
  const label = args && args.name ? String(args.name).slice(0, 40) : '';
2447
2464
  const prompt = String((args && args.prompt) || '');
2448
2465
  const connectFrom = String((args && args.connectFrom) || '');
2466
+ // G4 禁止逐镜节点:一致性靠参考图资产,不靠逐镜建点(高频走错路,这里直接封死)
2467
+ const g4 = PROD.gateShotNodeName(label, type);
2468
+ if (!g4.ok) {
2469
+ return { ok: false, gate: g4.code, projectId: id, ...(canvasId ? { canvasId } : {}), error: g4.error, fix: '改用规范资产命名(角色-<名> 设定图 / 场景-<名> / 道具-<名>),或为开场首帧建「<场次>-首帧」节点;确属用户明确要求逐镜节点时,向用户说明后果后再传 override:{by:\'user-explicit\',quote:\'用户原话\'} 重试' };
2470
+ }
2449
2471
  // 媒体节点:空态按「预览区比例 + 标题栏」给外框(没有操作栏就不加 NODE_FOOT_H),
2450
2472
  // 布点时用真实外框做碰撞检测,避免按 360×360 估小后与同列邻居重叠。
2451
2473
  const mediaSize = (type === 'image' || type === 'video')
@@ -2454,6 +2476,7 @@ function canvasCreateNode(args) {
2454
2476
  const pos = nextNodePos(doc, type, connectFrom, mediaSize);
2455
2477
  let connected = null;
2456
2478
  let autoConnected = null;
2479
+ let shotsGatePass = false; // 目标分镜表 shots 已过质量闸门(建点成功后据此抬升 shots_ready)
2457
2480
  let node;
2458
2481
  if (type === 'image') {
2459
2482
  node = agentNode('text', '', pos.x, pos.y, label || '图片节点');
@@ -2478,6 +2501,30 @@ function canvasCreateNode(args) {
2478
2501
  } else if (!hasPrompt && sbEmpty) {
2479
2502
  autoConnectId = sbEmpty.id; // 分镜表存在但 shots 为空:先连线占位(生成前需先拆解镜头)
2480
2503
  }
2504
+ // G2/G3:建视频节点前,目标分镜表的 shots 必须过质量闸门;且一个分镜表只允许一个视频节点。
2505
+ // 逃生舱:override:{by:'user-explicit',quote:'用户原话'}——用户明确要求时放行并记入审计。
2506
+ const sbTargetId = (connectFrom && doc.nodes[connectFrom] && doc.nodes[connectFrom].type === 'storyboard')
2507
+ ? connectFrom
2508
+ : autoConnectId;
2509
+ if (sbTargetId) {
2510
+ const ov = args && args.override;
2511
+ const ovOk = ov && ov.by === 'user-explicit' && String(ov.quote || '').trim();
2512
+ const g3 = PROD.gateOneVideoPerStoryboard(doc, sbTargetId);
2513
+ if (!g3.ok && !ovOk) {
2514
+ return { ok: false, gate: g3.code, projectId: id, ...(canvasId ? { canvasId } : {}), error: g3.error, existingVideoId: g3.existingVideoId, fix: '用 canvas_update_node 改现有视频节点的参数后重新生成;确需并排多个版本时,向用户说明后传 override:{by:\'user-explicit\',quote:\'用户原话\'}' };
2515
+ }
2516
+ const sbNode = doc.nodes[sbTargetId];
2517
+ const shots = sbNode && Array.isArray(sbNode.data && sbNode.data.shots) ? sbNode.data.shots : [];
2518
+ if (shots.length) {
2519
+ const g2 = PROD.gateStoryboard(shots);
2520
+ if (g2.ok) shotsGatePass = true;
2521
+ if (!g2.ok && !ovOk) {
2522
+ return { ok: false, gate: g2.code, projectId: id, ...(canvasId ? { canvasId } : {}), error: '分镜质量闸门未通过(' + g2.fails.length + ' 项)——分镜重生成不花钱,视频按秒计费,绝不带病生成', fails: g2.fails, warns: g2.warns || [], fix: 'canvas_run_node 重生成该分镜表,或 canvas_update_node 整表替换 shots 修复上述每一项;用户明确要求继续时传 override:{by:\'user-explicit\',quote:\'用户原话\'}' };
2523
+ }
2524
+ if (!g2.ok && ovOk) PROD.recordOverride(id, canvasId, 'G2', ov.quote, { node: label });
2525
+ }
2526
+ if (!g3.ok && ovOk) PROD.recordOverride(id, canvasId, 'G3', ov.quote, { node: label, storyboardId: sbTargetId });
2527
+ }
2481
2528
  node.data = { ...node.data, status: 'idle', error: null, prompt: autoConnectId ? '' : prompt, assetId: null, demo: false, duration: Number(args && args.duration) || 5, resolution: (args && args.resolution) || '720P', ratio: (args && args.ratio) || '16:9' };
2482
2529
  autoConnected = autoConnectId ? { from: autoConnectId, ignoredPrompt: forced && hasPrompt, emptyShots: !sbWithShots && !!sbEmpty } : null;
2483
2530
  } else if (type === 'storyboard') {
@@ -2519,6 +2566,13 @@ function canvasCreateNode(args) {
2519
2566
  }
2520
2567
  doc.updatedAt = Date.now();
2521
2568
  writeToolDoc(args, doc);
2569
+ // 阶段机:剧本/分镜表节点落盘 → 阶段 ≥ script / storyboard(只抬高;shots_ready 由运行/状态汇报再抬)
2570
+ try {
2571
+ if (type === 'script') PROD.noteStage(id, canvasId, 'script', 'create_script_node');
2572
+ else if (type === 'storyboard') PROD.noteStage(id, canvasId, 'storyboard', 'create_storyboard_node');
2573
+ // 建视频节点时目标分镜表已过质量闸门 → shots_ready(这是"分镜定稿"的机器证据)
2574
+ if (type === 'video' && shotsGatePass) PROD.noteStage(id, canvasId, 'shots_ready', 'create_video_gate_pass');
2575
+ } catch { /* 阶段机故障不阻塞建点 */ }
2522
2576
  const note = autoConnected && autoConnected.ignoredPrompt
2523
2577
  ? (type === 'video'
2524
2578
  ? '⚠️ 已强制连线到分镜表(多镜头工作流:一个分镜表 = 一个完整视频,镜头清单从分镜表读取),传入的 prompt 已忽略——不要手写视频提示词绕过分镜表。'
@@ -2541,8 +2595,11 @@ function canvasRelayout(args) {
2541
2595
  const id = String((args && args.projectId) || '');
2542
2596
  const canvasId = toolCanvasId(args);
2543
2597
  const doc = readToolDoc(args);
2544
- const nodes = Object.values(doc.nodes || {});
2545
- if (!nodes.length) return { ok: true, projectId: id, ...(canvasId ? { canvasId } : {}), moved: 0, rows: 0 };
2598
+ const all = Object.values(doc.nodes || {});
2599
+ // pinned 节点:用户/对话精摆过的位置,重排绝不覆盖(它也不参与分列与相对排序)
2600
+ const nodes = all.filter((n) => !(n.data && n.data.pinned));
2601
+ const skippedPinned = all.length - nodes.length;
2602
+ if (!nodes.length) return { ok: true, projectId: id, ...(canvasId ? { canvasId } : {}), moved: 0, rows: 0, skippedPinned };
2546
2603
  const VERT = new Set(['prev', 'frame']);
2547
2604
  const byId = new Map(nodes.map((n) => [n.id, n]));
2548
2605
  const depth = new Map(nodes.map((n) => [n.id, 0]));
@@ -2579,19 +2636,160 @@ function canvasRelayout(args) {
2579
2636
  const colX = new Map();
2580
2637
  let cx = 80;
2581
2638
  for (const d of [...colW.keys()].sort((a, b) => a - b)) { colX.set(d, cx); cx += (colW.get(d) || 280) + 60; }
2582
- let cy = 40;
2639
+ // 分带排列(0.20.0):一行 = 一个横向连通簇;行内按深度分列,**同深度的兄弟节点纵向堆叠**
2640
+ // (行高 = 各列堆叠高度的最大值),避让 pinned 节点;行自上而下堆,超过带高上限换右边新带。
2641
+ // 旧实现行内所有节点同一个 y → 分支结构(一上游连多个下游)会整叠重合。
2642
+ const MAX_BAND_H = 1800, BAND_GAP = 160, ROW_GAP = 40, SIB_GAP = 24;
2643
+ // pinned 作为障碍物:并列摆放时不得覆盖它们
2644
+ const obstacles = all
2645
+ .filter((n) => n.data && n.data.pinned)
2646
+ .map((n) => ({ x: Number(n.x) || 0, y: Number(n.y) || 0, w: Number(n.w) || 360, h: Number(n.h) || 360 }));
2647
+ let bandX = 80, bandY = 40, bandMaxW = 0, bandH = 0;
2583
2648
  let moved = 0;
2584
2649
  for (const row of rowList) {
2585
- const rowH = Math.max(200, ...row.ids.map((n) => Number(n.h) || 200));
2586
- for (const n of row.ids) { n.x = colX.get(depth.get(n.id) || 0); n.y = cy; moved++; }
2587
- cy += rowH + 40;
2650
+ const rowW = Math.max(...row.ids.map((n) => (colX.get(depth.get(n.id) || 0) || 80) + (Number(n.w) || 280))) - 80;
2651
+ // 行内按深度分列;每列内部按原 y 顺序堆叠
2652
+ const lanes = new Map();
2653
+ for (const n of row.ids) {
2654
+ const d = depth.get(n.id) || 0;
2655
+ if (!lanes.has(d)) lanes.set(d, []);
2656
+ lanes.get(d).push(n);
2657
+ }
2658
+ for (const lane of lanes.values()) lane.sort((a, b) => ((Number(a.y) || 0) - (Number(b.y) || 0)) || ((Number(a.x) || 0) - (Number(b.x) || 0)));
2659
+ let rowH = 200;
2660
+ for (const lane of lanes.values()) {
2661
+ const hSum = lane.reduce((a, n) => a + (Number(n.h) || 200) + SIB_GAP, 0) - SIB_GAP;
2662
+ rowH = Math.max(rowH, hSum);
2663
+ }
2664
+ // 避让钉住节点:整行下移,直到与任何 pinned 矩形不相交(上限 20 次防死循环)
2665
+ for (let guard = 0; guard < 20; guard++) {
2666
+ const bad = obstacles.some((o) => bandX < o.x + o.w && o.x < bandX + rowW && bandY < o.y + o.h && o.y < bandY + rowH);
2667
+ if (!bad) break;
2668
+ const pushTo = Math.max(...obstacles
2669
+ .filter((o) => bandX < o.x + o.w && o.x < bandX + rowW && bandY < o.y + o.h && o.y < bandY + rowH)
2670
+ .map((o) => o.y + o.h + ROW_GAP));
2671
+ bandY = pushTo;
2672
+ }
2673
+ if (bandH > 0 && bandH + ROW_GAP + rowH > MAX_BAND_H) {
2674
+ bandX += bandMaxW + BAND_GAP; bandY = 40; bandH = 0; bandMaxW = 0;
2675
+ // 新带起点也可能压在 pinned 上:同样下移避让
2676
+ for (let guard = 0; guard < 20; guard++) {
2677
+ const bad = obstacles.some((o) => bandX < o.x + o.w && o.x < bandX + rowW && bandY < o.y + o.h && o.y < bandY + rowH);
2678
+ if (!bad) break;
2679
+ bandY = Math.max(...obstacles
2680
+ .filter((o) => bandX < o.x + o.w && o.x < bandX + rowW && bandY < o.y + o.h && o.y < bandY + rowH)
2681
+ .map((o) => o.y + o.h + ROW_GAP));
2682
+ }
2683
+ }
2684
+ for (const [d, lane] of lanes) {
2685
+ let ly = bandY;
2686
+ for (const n of lane) {
2687
+ n.x = bandX + ((colX.get(d) || 80) - 80);
2688
+ n.y = ly;
2689
+ ly += (Number(n.h) || 200) + SIB_GAP;
2690
+ moved++;
2691
+ }
2692
+ }
2693
+ bandY += rowH + ROW_GAP;
2694
+ bandH += rowH + ROW_GAP;
2695
+ bandMaxW = Math.max(bandMaxW, rowW);
2588
2696
  }
2589
2697
  doc.updatedAt = Date.now();
2590
2698
  writeToolDoc(args, doc);
2591
- return { ok: true, projectId: id, ...(canvasId ? { canvasId } : {}), moved, rows: rowList.length };
2699
+ return { ok: true, projectId: id, ...(canvasId ? { canvasId } : {}), moved, rows: rowList.length, skippedPinned };
2700
+ }
2701
+
2702
+ /** 整画布几何视图(0.20.0):对话侧据此精确计算每个节点该放哪(x/y/w/h + pinned + 包围盒)。 */
2703
+ function canvasLayoutGet(args) {
2704
+ const pid = String((args && args.projectId) || '');
2705
+ const canvasId = toolCanvasId(args);
2706
+ const doc = readToolDoc(args);
2707
+ const nodes = Object.values(doc.nodes || {}).map((n) => ({
2708
+ nodeId: n.id,
2709
+ name: String((n.data && n.data.label) || n.id).slice(0, 60),
2710
+ type: n.type,
2711
+ x: Math.round(Number(n.x) || 0),
2712
+ y: Math.round(Number(n.y) || 0),
2713
+ w: Math.round(Number(n.w) || 360),
2714
+ h: Math.round(Number(n.h) || 360),
2715
+ pinned: !!(n.data && n.data.pinned),
2716
+ }));
2717
+ const bounds = nodes.length
2718
+ ? {
2719
+ minX: Math.min(...nodes.map((n) => n.x)), minY: Math.min(...nodes.map((n) => n.y)),
2720
+ maxX: Math.max(...nodes.map((n) => n.x + n.w)), maxY: Math.max(...nodes.map((n) => n.y + n.h)),
2721
+ }
2722
+ : null;
2723
+ return { ok: true, projectId: pid, ...(canvasId ? { canvasId } : {}), count: nodes.length, bounds, nodes };
2724
+ }
2725
+
2726
+ /** 精准摆放(0.20.0):批量设置节点坐标(媒体节点可同时改尺寸),pinned 钉住防 relayout 覆盖。
2727
+ * 允许重叠——精确摆放是调用方明确意图,不做碰撞拒绝。 */
2728
+ function canvasLayoutNode(args) {
2729
+ const pid = String((args && args.projectId) || '');
2730
+ const canvasId = toolCanvasId(args);
2731
+ const doc = readToolDoc(args);
2732
+ const list = (args && args.nodes) || [];
2733
+ if (!Array.isArray(list) || !list.length) throw new Error('nodes 需要非空数组:[{ nodeId, x, y, w?, h?, pinned? }]');
2734
+ const applied = [];
2735
+ for (const item of list) {
2736
+ const nodeId = String((item && item.nodeId) || '');
2737
+ const n = doc.nodes[nodeId];
2738
+ if (!n) throw new Error('节点不存在: ' + nodeId + '(先 canvas_layout_get 拿全图坐标)');
2739
+ const x = Number(item.x);
2740
+ const y = Number(item.y);
2741
+ if (!Number.isFinite(x) || !Number.isFinite(y)) throw new Error(nodeId + ' 的 x/y 必须是有限数字(可为负)');
2742
+ n.x = Math.round(x);
2743
+ n.y = Math.round(y);
2744
+ const entry = { nodeId, x: n.x, y: n.y };
2745
+ if (item.w !== undefined || item.h !== undefined) {
2746
+ const isMedia = n.type === 'image' || n.type === 'video';
2747
+ if (!isMedia) throw new Error(nodeId + '(' + n.type + ')不支持改尺寸:只有 image/video 媒体节点可设 w/h');
2748
+ // 媒体节点预览区必须保持画面比例(normalizeMediaNodeSize 会强制):只给一维时按比例补另一维,
2749
+ // 两维都给了就必须与比例一致(误差 ≤2%),否则明确拒绝而不是被静默重置。
2750
+ const d = n.data || {};
2751
+ const ratio = mediaRatioOf(n);
2752
+ const [rw, rh] = String(ratio).split(':').map(Number);
2753
+ const chrome = NODE_HDR_H + (d.assetId ? NODE_FOOT_H : 0);
2754
+ let w = item.w !== undefined ? Number(item.w) : null;
2755
+ let h = item.h !== undefined ? Number(item.h) : null;
2756
+ if (w !== null && h === null) {
2757
+ if (!Number.isFinite(w) || w < 160) throw new Error(nodeId + ' 的 w 非法(≥160)');
2758
+ h = Math.round((w * rh) / rw + chrome);
2759
+ } else if (h !== null && w === null) {
2760
+ if (!Number.isFinite(h) || h - chrome < 120) throw new Error(nodeId + ' 的 h 非法(预览高 ≥120)');
2761
+ w = Math.round(((h - chrome) * rw) / rh);
2762
+ } else {
2763
+ const ph = h - chrome;
2764
+ const okRatio = Number.isFinite(w) && Number.isFinite(h) && ph > 0 && Math.abs(w / ph - rw / rh) / (rw / rh) <= 0.02;
2765
+ if (!okRatio) {
2766
+ throw new Error(nodeId + ' 的 w/h 与画面比例 ' + ratio + ' 不匹配:只传 w 或只传 h 会自动按比例补齐(例如 w=520 → h=' + Math.round((520 * rh) / rw + chrome) + ')');
2767
+ }
2768
+ }
2769
+ n.w = Math.round(w);
2770
+ n.h = Math.round(h);
2771
+ entry.w = n.w;
2772
+ entry.h = n.h;
2773
+ }
2774
+ if (item.pinned !== undefined) {
2775
+ n.data = n.data || {};
2776
+ n.data.pinned = !!item.pinned;
2777
+ entry.pinned = !!n.data.pinned;
2778
+ }
2779
+ applied.push(entry);
2780
+ }
2781
+ doc.updatedAt = Date.now();
2782
+ writeToolDoc(args, doc);
2783
+ return { ok: true, projectId: pid, ...(canvasId ? { canvasId } : {}), applied, moved: applied.length };
2592
2784
  }
2593
2785
  async function canvasDeleteProject(args) {
2594
2786
  const id = String((args && args.projectId) || '');
2787
+ // G5 破坏性操作确认:删项目不可逆(全部画布/资产/记忆)。必须携带用户确认原话,写入审计。
2788
+ const g5quote = String((args && args.confirm) || '').trim();
2789
+ if (!g5quote) {
2790
+ return { ok: false, gate: 'G5', projectId: id, error: '删除项目是破坏性操作(全部画布、资产与记忆一并删除,不可恢复)。仅当用户明确要求删除整个项目时才执行:调用时必须携带 confirm 参数(填用户的确认原话)。', fix: '向用户确认后,携带 confirm 重试同一调用' };
2791
+ }
2792
+ try { PROD.recordOverride(id, null, 'G5', g5quote, { op: 'delete_project' }); } catch { /* 审计失败不阻塞 */ }
2595
2793
  let name = id;
2596
2794
  const prevDoc = readDocOrNull(id);
2597
2795
  if (prevDoc && prevDoc.name) name = prevDoc.name;
@@ -2621,6 +2819,12 @@ async function canvasDeleteNode(args) {
2621
2819
  const id = String((args && args.projectId) || '');
2622
2820
  const nodeId = String((args && args.nodeId) || '');
2623
2821
  const canvasId = toolCanvasId(args);
2822
+ // G5 破坏性操作确认:删除不可逆(连带连线)。必须携带用户确认原话,写入审计。
2823
+ const g5quote = String((args && args.confirm) || '').trim();
2824
+ if (!g5quote) {
2825
+ return { ok: false, gate: 'G5', projectId: id, ...(canvasId ? { canvasId } : {}), nodeId, error: '删除是破坏性操作(节点连同连线,不可恢复)。仅当用户明确要求删除时才执行:调用时必须携带 confirm 参数(填用户的确认原话,如 confirm:\'把这场视频删掉\')。改内容/改参数请用 canvas_update_node,不需要删除。', fix: '向用户确认后,携带 confirm 重试同一调用' };
2826
+ }
2827
+ try { PROD.recordOverride(id, canvasId, 'G5', g5quote, { op: 'delete_node', nodeId }); } catch { /* 审计失败不阻塞 */ }
2624
2828
  const doc = readToolDoc(args);
2625
2829
  if (!doc.nodes[nodeId]) throw new Error('节点不存在: ' + nodeId);
2626
2830
  delete doc.nodes[nodeId];
@@ -2639,9 +2843,43 @@ async function canvasRunNode(args) {
2639
2843
  const doc = readToolDoc(args);
2640
2844
  const node = doc.nodes[nodeId];
2641
2845
  if (!node) throw new Error('节点不存在: ' + nodeId);
2846
+ // ── 流程闸门(0.20.0):只拦"生成"与"花钱",不拦节点搭建。逃生舱见各 fix 字段。 ──
2847
+ {
2848
+ const ov = args && args.override;
2849
+ const ovOk = ov && ov.by === 'user-explicit' && String(ov.quote || '').trim();
2850
+ // G1 设定集先行:剧本/分镜表**生成内容**前必须有世界观+风格+≥1 角色
2851
+ if (node.type === 'script' || node.type === 'storyboard') {
2852
+ const g1 = PROD.gateBible(doc.bible);
2853
+ if (!g1.ok && !ovOk) {
2854
+ return { ok: false, gate: g1.code, projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, missing: g1.missing, error: '设定集先行:' + g1.missing.join('、') + ' 尚未补全——先 canvas_get_bible 读现状、canvas_update_bible 补全后再生成。跨镜一致性全靠它。', fix: 'canvas_update_bible 补全缺失项(用户已给创意按其创意写,不要另起一套);用户明确说"先随便生成"时传 override:{by:\'user-explicit\',quote:\'用户原话\'}' };
2855
+ }
2856
+ if (!g1.ok && ovOk) PROD.recordOverride(pid, canvasId, 'G1', ov.quote, { node: node.type });
2857
+ }
2858
+ // G2/G6 视频生成:镜头清单必须来自已过闸门的分镜表;自由 prompt 视频(无分镜上游)不受此限
2859
+ if (node.type === 'video') {
2860
+ const sbEdge = (doc.edges || []).filter((e) => e && e.toNode === nodeId && doc.nodes[e.fromNode] && doc.nodes[e.fromNode].type === 'storyboard').pop();
2861
+ const sbNode = sbEdge ? doc.nodes[sbEdge.fromNode] : null;
2862
+ if (sbNode) {
2863
+ const shots = Array.isArray(sbNode.data && sbNode.data.shots) ? sbNode.data.shots : [];
2864
+ const g2 = PROD.gateStoryboard(shots);
2865
+ if (!g2.ok && !ovOk) {
2866
+ return { ok: false, gate: g2.code, projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, error: '分镜质量闸门未通过(' + g2.fails.length + ' 项)——分镜重生成不花钱,视频按秒计费,绝不带病生成', fails: g2.fails, warns: g2.warns || [], fix: 'canvas_run_node 重生成该分镜表,或 canvas_update_node 整表替换 shots;用户明确要求继续时传 override:{by:\'user-explicit\',quote:\'用户原话\'}' };
2867
+ }
2868
+ if (!g2.ok && ovOk) PROD.recordOverride(pid, canvasId, 'G2', ov.quote, { nodeId });
2869
+ if (g2.ok) { try { PROD.noteStage(pid, canvasId, 'shots_ready', 'storyboard_gate_pass'); } catch { /* 忽略 */ } }
2870
+ const g6 = PROD.gateStage(pid, canvasId, 'shots_ready');
2871
+ if (!g6.ok && !ovOk) {
2872
+ return { ok: false, gate: g6.code, projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, error: '阶段越序:当前阶段「' + g6.at + '」尚未到达「shots_ready」——先完成分镜并通过质量闸门,再触发视频生成(视频按秒计费)。', fix: '用 canvas_production_status 查看缺口;用户明确要求跳过时传 override:{by:\'user-explicit\',quote:\'用户原话\'}' };
2873
+ }
2874
+ if (!g6.ok && ovOk) PROD.recordOverride(pid, canvasId, 'G6', ov.quote, { nodeId });
2875
+ }
2876
+ }
2877
+ }
2642
2878
  const cfg = readIcConfig();
2643
2879
  cfg.ui = { ...(cfg.ui || {}), runRequest: { projectId: pid, canvasId, nodeId, at: Date.now() } };
2644
2880
  writeIcConfig(cfg);
2881
+ // 阶段机:视频触发 → ≥ generating
2882
+ try { if (node.type === 'video') PROD.noteStage(pid, canvasId, 'generating', 'video_run'); } catch { /* 忽略 */ }
2645
2883
  return { ok: true, projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, type: node.type, label: (node.data && node.data.label) || '' };
2646
2884
  }
2647
2885
  /** 读取节点运行状态与产物(画布执行完成后会把结果推回 Host 文档)。 */
@@ -2744,10 +2982,29 @@ async function canvasNodeStatus(args) {
2744
2982
  }))
2745
2983
  : undefined;
2746
2984
  const d = n.data || {};
2985
+ // 阶段机:读取即观测——分镜出镜头且过质量闸 → shots_ready;剧本有成稿 → script;视频完成 → qc;成片完成 → post。
2986
+ // stage 随每次状态轮询返回:模型随时知道"自己在哪一步",不需要额外调用。
2987
+ let productionStage = null;
2988
+ try {
2989
+ if (n.type === 'storyboard' && Array.isArray(d.shots) && d.shots.length && PROD.gateStoryboard(d.shots).ok) {
2990
+ PROD.noteStage(pid, canvasId, 'shots_ready', 'storyboard_shots_ok');
2991
+ } else if (n.type === 'script' && String(d.output || '').trim()) {
2992
+ PROD.noteStage(pid, canvasId, 'script', 'script_output');
2993
+ } else if (n.type === 'video' && String(d.status) === 'done') {
2994
+ PROD.noteStage(pid, canvasId, 'qc', 'video_done');
2995
+ } else if (n.type === 'finalcut' && String(d.status) === 'done') {
2996
+ PROD.noteStage(pid, canvasId, 'post', 'finalcut_done');
2997
+ }
2998
+ const st = PROD.stageOf(pid, canvasId);
2999
+ productionStage = { stage: st.stage, stageZh: PRODUCTION_STAGE_ZH[st.stage] || st.stage };
3000
+ } catch { /* 阶段机故障不影响状态读取 */ }
2747
3001
  return {
2748
3002
  projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, type: n.type, label: d.label || '',
2749
3003
  status: d.status || 'idle',
2750
3004
  aiStatus: d.aiStatus || 'idle',
3005
+ // 制作阶段(0.20.0 阶段机):brief/bible/assets/script/storyboard/shots_ready/generating/qc/post/delivered
3006
+ stage: productionStage ? productionStage.stage : undefined,
3007
+ stageZh: productionStage ? productionStage.stageZh : undefined,
2751
3008
  // 布局事实:坐标与外框尺寸只读透出(改布局走 canvas_relayout;canvas_update_node 仍禁改结构字段)
2752
3009
  x: Number(n.x) || 0,
2753
3010
  y: Number(n.y) || 0,
@@ -2876,6 +3133,8 @@ async function canvasGenerateNode(args) {
2876
3133
  const baseline = await canvasNodeStatus({ projectId: pid, canvasId, nodeId }).catch(() => null);
2877
3134
  const baseUpdatedAt = Number(baseline && baseline.docUpdatedAt) || 0;
2878
3135
  const run = await canvasRunNode({ projectId: pid, canvasId, nodeId });
3136
+ // 闸门拒绝(G1/G2/G6)原样透传:调用方拿到 gate/fails/fix 结构化字段
3137
+ if (run && run.ok === false) return run;
2879
3138
  if (!waitSec) {
2880
3139
  return { ok: true, triggered: true, finished: false, projectId: pid, nodeId, type: run.type, label: run.label, status: 'running', note: '已触发执行;画布需处于打开状态才会真正执行,可用 canvas_node_status 查询进度' };
2881
3140
  }
@@ -3322,7 +3581,9 @@ async function updateInstall() {
3322
3581
  export const inject = ['webServer', 'tools'];
3323
3582
 
3324
3583
  // 仅供诊断 / 自动化测试(不属于 RPC 面,运行时行为不受影响)
3325
- 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 };
3584
+ 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
+ canvasLayoutNode, canvasLayoutGet, canvasRelayout,
3586
+ __auto: __autoApi };
3326
3587
 
3327
3588
  function resolveModel(providers, want) {
3328
3589
  const byProvider = want && want.provider
@@ -3497,6 +3758,228 @@ export function apply(ctx) {
3497
3758
  };
3498
3759
  /** 工作区注册表条目的对外视图(不泄漏内部字段)。 */
3499
3760
  const wsView = (w) => ({ id: w && w.id, path: w && w.path, title: (w && w.title) || '' });
3761
+ /** 自动创作开关(实验,默认关闭):关闭时所有 auto* RPC 一律拒绝——零成本、零干扰。 */
3762
+ const autoEnabled = () => {
3763
+ try { const cfg = readIcConfig(); return !!(cfg.ui && cfg.ui.autoMode); } catch { return false; }
3764
+ };
3765
+ const autoDisabled = () => ({ ok: false, disabled: true, error: '自动创作处于关闭状态(实验功能):请先在画布设置里打开「多智能体自动创作(实验)」' });
3766
+
3767
+ // ---- 自动创作 runner(免费段·编剧室):进程内执行器 ----
3768
+ // 角色分工 = 独立系统提示词的轮次(调研 → 编剧A/B 独立提案 → 互评 → 监制决策 → 落盘)。
3769
+ // 全程零付费(不触发生成接口);讨论记录落盘为画布文本节点;剧情走向只来自用户 brief。
3770
+ const AUTO_RUNS = new Map(); // runKey(pid::cid) → { status:'running'|'done'|'failed'|'aborted', phase, log:[{at,role,summary}], error, brief, startedAt, meetingNodeId }
3771
+ const runKeyOf = (pid, cid) => String(pid) + '::' + (cid || 'default');
3772
+ /** 测试注入口:默认走插件内 LLM 通道;测试注入假通道以覆盖全流水线。 */
3773
+ let roomLlm = async ({ system, user }) => {
3774
+ const r = await complete({ system, user });
3775
+ return (r && r.text) || '';
3776
+ };
3777
+ /** 从模型输出提取第一个平衡的 JSON 对象(容忍 ```json 围栏与前后闲话)。 */
3778
+ function roomJson(text) {
3779
+ const s = String(text || '');
3780
+ 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; } } }
3791
+ }
3792
+ return null;
3793
+ }
3794
+ async function autoRoomStep(run, role, system, user, needJson) {
3795
+ if (run.status !== 'running') throw new Error('aborted');
3796
+ const raw = await roomLlm({ system, user });
3797
+ const parsed = needJson ? (roomJson(raw) || {}) : null;
3798
+ if (needJson && !Object.keys(parsed).length) throw new Error(role + ' 输出不是可用 JSON');
3799
+ run.log.push({ at: Date.now(), role, summary: String(raw || '').slice(0, 160) });
3800
+ return parsed || raw;
3801
+ }
3802
+ /** 画布执行适配器:自动打开画布 → 触发节点 → 轮询终态。测试可注入桩(__auto.setCanvasRunner)。 */
3803
+ const sleepMs = (ms) => new Promise((r) => setTimeout(r, ms));
3804
+ let canvasExec = async (pid, cid, nodeId, opts) => {
3805
+ await canvasOpen({ projectId: pid, canvasId: cid }); // 自动打开画布(用户不用点面板)
3806
+ await sleepMs(600); // 给客户端一个同步周期消费 openRequest
3807
+ const r = await canvasRunNode({ projectId: pid, canvasId: cid, nodeId });
3808
+ if (r && r.ok === false) throw new Error('[' + (r.gate || 'GATE') + '] ' + (r.error || '闸门拒绝'));
3809
+ const deadline = Date.now() + (Number(opts && opts.timeoutMs) || 8 * 60 * 1000);
3810
+ while (Date.now() < deadline) {
3811
+ await sleepMs(2000);
3812
+ let st = null;
3813
+ try { st = await canvasNodeStatus({ projectId: pid, canvasId: cid, nodeId }); } catch { continue; }
3814
+ const ai = String(st.aiStatus || '');
3815
+ const s = String(st.status || '');
3816
+ if (ai === 'error' || s === 'error') throw new Error(st.error || st.aiError || '生成失败');
3817
+ if (st.type === 'script' || st.type === 'storyboard') {
3818
+ if (ai !== 'running' && (String(st.output || '').trim() || (Array.isArray(st.shots) && st.shots.length))) return st;
3819
+ } else if (s === 'done') return st;
3820
+ }
3821
+ throw new Error('等待生成超时(画布需保持打开)');
3822
+ };
3823
+ /** 按【场N】拆分剧本成稿;没有标记就整段当一场。 */
3824
+ function splitScenes(text) {
3825
+ const src = String(text || '');
3826
+ const lines = src.split(/\r?\n/);
3827
+ const out = [];
3828
+ let cur = null;
3829
+ for (const line of lines) {
3830
+ const m = /^\s*【场\s*(\d+)\s*】/.exec(line);
3831
+ if (m) {
3832
+ if (cur && cur.lines.join('').trim()) out.push(cur);
3833
+ cur = { no: Number(m[1]) || out.length + 1, head: line.trim(), lines: [] };
3834
+ } else if (cur) cur.lines.push(line);
3835
+ }
3836
+ if (cur && cur.lines.join('').trim()) out.push(cur);
3837
+ if (!out.length) return [{ no: 1, head: '【场1】', lines: [src] }];
3838
+ return out.map((s, i) => ({ no: s.no || i + 1, text: (s.head + '\n' + s.lines.join('\n')).trim() }));
3839
+ }
3840
+ async function autoRoom(pid, cid, brief) {
3841
+ const runKey = runKeyOf(pid, cid);
3842
+ const run = AUTO_RUNS.get(runKey);
3843
+ const BASE = '你是短剧创作团队的一员。流程与格式是硬要求;剧情创意只来自用户 brief,绝不套模板。输出只给 JSON。';
3844
+ try {
3845
+ // ① 调研(离线知识;联网调研随会话执行器上线)
3846
+ run.phase = 'research';
3847
+ const research = await autoRoomStep(run, '调研', BASE + '\n你是题材调研员(当前离线:基于既有知识,标注「离线调研」)。给出 3 个与 brief 相关的热门题材方向与 3 种视觉风格建议。',
3848
+ '用户 brief:' + brief, true);
3849
+ // ② 编剧 A / B 独立提案(互不可见)
3850
+ run.phase = 'pitch';
3851
+ 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);
3856
+ // ③ 互评
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);
3860
+ // ④ 监制决策
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
3876
+ run.phase = 'writeback';
3877
+ const transcript = [
3878
+ '用户 brief:' + brief,
3879
+ '调研(离线):' + JSON.stringify(research),
3880
+ '编剧A提案:' + JSON.stringify(pitchA),
3881
+ '编剧B提案:' + JSON.stringify(pitchB),
3882
+ '互评:' + JSON.stringify(crit),
3883
+ '监制决策:' + dec.decision + '——' + (dec.rationale || ''),
3884
+ '定稿 logline:' + (dec.logline || ''),
3885
+ ].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 });
3893
+ // ⑥ 剧本自动生成 → 按场拆分 → 逐场分镜表(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);
3897
+ const boards = [];
3898
+ let prevBoard = null;
3899
+ for (let i = 0; i < scenes.length; i++) {
3900
+ run.phase = 'boards ' + (i + 1) + '/' + scenes.length;
3901
+ const txt = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'text', name: '场' + scenes[i].no + '文本' });
3902
+ canvasWriteNode({ projectId: pid, canvasId: cid, nodeId: txt.nodeId, target: 'output', text: scenes[i].text, overwrite: true });
3903
+ const sb = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'storyboard', name: '场' + scenes[i].no + '分镜表', connectFrom: txt.nodeId });
3904
+ if (prevBoard) { try { canvasConnect({ projectId: pid, canvasId: cid, fromNode: prevBoard, toNode: sb.nodeId, fromPort: 'tail', toPort: 'prev' }); } catch { /* 端口异常不阻塞 */ } }
3905
+ prevBoard = sb.nodeId;
3906
+ let sbSt = await canvasExec(pid, cid, sb.nodeId, { timeoutMs: 10 * 60 * 1000 });
3907
+ 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);
3912
+ }
3913
+ boards.push({ no: scenes[i].no, storyboardId: sb.nodeId, gate: gate.ok, fails: gate.fails });
3914
+ run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' 分镜:' + (gate.ok ? '过闸' : '仍有 ' + gate.fails.length + ' 项') });
3915
+ }
3916
+ // ⑦ 预算单(免费段终点)
3917
+ const cfg = readIcConfig();
3918
+ const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
3919
+ run.budget = PROD.quote(pid, cid, price);
3920
+ run.boards = boards;
3921
+ run.meetingNodeId = meet.nodeId;
3922
+ run.scriptNodeId = sc.nodeId;
3923
+ run.status = 'done';
3924
+ run.phase = 'budget';
3925
+ run.log.push({ at: Date.now(), role: 'runner', summary: '免费段完成:' + scenes.length + ' 场分镜 + 预算单(' + run.budget.videoCalls + ' 次视频调用 / ' + run.budget.totalSeconds + ' 秒)' });
3926
+ } catch (e) {
3927
+ run.status = String((e && e.message) || e) === 'aborted' ? 'aborted' : 'failed';
3928
+ run.error = String((e && e.message) || e);
3929
+ run.log.push({ at: Date.now(), role: 'runner', summary: '失败:' + run.error });
3930
+ }
3931
+ }
3932
+ /** 付费段 v1:批准后逐分镜表建视频节点 → 生成 → 轮询(失败重试 2 次)→ 成片节点。 */
3933
+ async function autoPaid(pid, cid) {
3934
+ const cfg = readIcConfig();
3935
+ const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
3936
+ const ap = PROD.approvalOf(pid, cid, price);
3937
+ if (!ap || !ap.valid) return { ok: false, error: '没有有效的付费批准:先用 canvas_auto_budget 生成预算单,用户批准后重试' };
3938
+ const run = AUTO_RUNS.get(runKeyOf(pid, cid));
3939
+ if (!run || run.status !== 'done') return { ok: false, error: '免费段尚未完成(没有分镜与预算)' };
3940
+ if (run.paid === 'running') return { ok: false, error: '付费段已在运行' };
3941
+ run.paid = 'running';
3942
+ run.paidAbort = false;
3943
+ run.paidLog = [{ at: Date.now(), text: '付费段启动(已批准预算 ' + ap.quoteId + ')' }];
3944
+ (async () => {
3945
+ try {
3946
+ const doc = readToolDoc({ projectId: pid, canvasId: cid });
3947
+ const boards = Object.values(doc.nodes || {}).filter((n) => n.type === 'storyboard' && Array.isArray(n.data && n.data.shots) && n.data.shots.length);
3948
+ let lastVideo = null;
3949
+ 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; }
3951
+ const sb = boards[i];
3952
+ 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) }); }
3963
+ }
3964
+ if (!done) throw err;
3965
+ lastVideo = v.nodeId;
3966
+ run.paidLog.push({ at: Date.now(), text: label + ' 完成' });
3967
+ }
3968
+ if (lastVideo) {
3969
+ const fc = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'finalcut', name: '成片', connectFrom: lastVideo });
3970
+ if (fc && fc.nodeId) run.finalcutNodeId = fc.nodeId;
3971
+ }
3972
+ run.paid = 'done'; run.paidPhase = 'done';
3973
+ run.paidLog.push({ at: Date.now(), text: lastVideo ? '全部视频完成,已建成片节点' : '没有待生成的视频' });
3974
+ } catch (e) {
3975
+ run.paid = 'failed'; run.paidError = String((e && e.message) || e);
3976
+ }
3977
+ })();
3978
+ return { ok: true, status: 'running', quoteId: ap.quoteId };
3979
+ }
3980
+ __autoApi.runs = AUTO_RUNS;
3981
+ __autoApi.setRoomLlm = (fn) => { roomLlm = fn; };
3982
+ __autoApi.setCanvasRunner = (fn) => { canvasExec = fn; };
3500
3983
 
3501
3984
  const methods = {
3502
3985
  async ping() { return { ok: true, version: VERSION }; },
@@ -3803,6 +4286,131 @@ export function apply(ctx) {
3803
4286
  async bindingCapabilities() {
3804
4287
  return { ok: true, rev: 2, anyProject: true };
3805
4288
  },
4289
+ // ---- 制作阶段机 RPC(0.20.0):阶段/闸门/汇报语义的数据面 ----
4290
+ /** 制作能力探针(M0):stageMachine/qualityGate 恒真;multiAgent = 宿主是否暴露会话服务
4291
+ * (sessionController/agents,懒探测不加 inject——与 workspaceRegistry 同一安全模式)。
4292
+ * multiAgent:false 时客户端隐藏「自动创作」入口,auto* RPC 一律拒绝。 */
4293
+ async productionCapabilities() {
4294
+ const svc = (name) => { try { return !!(ctx.get && ctx.get(name)); } catch { return false; } };
4295
+ const multiAgent = svc('sessionController') || svc('agents');
4296
+ return { ok: true, rev: 1, stageMachine: true, qualityGate: true, multiAgent, autoMode: multiAgent, version: VERSION, stages: PRODUCTION_STAGES };
4297
+ },
4298
+ /** 制作状态汇报:模型宣称"完成/可交付"前必须以 ready:true 为据;next 给当前阶段的下一步。 */
4299
+ async productionStatus(args) {
4300
+ const pid = String((args && args.projectId) || '');
4301
+ if (!pid) return { ok: false, error: '缺少 projectId' };
4302
+ try { projectFile(pid); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
4303
+ return PROD.status(pid, toolCanvasId(args));
4304
+ },
4305
+ /** 显式推进/回退(返工):必须带 reason(审计);回退会下调 floor,随后按工具事件重新抬升。 */
4306
+ async productionAdvance(args) {
4307
+ const pid = String((args && args.projectId) || '');
4308
+ if (!pid) return { ok: false, error: '缺少 projectId' };
4309
+ try { projectFile(pid); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
4310
+ return PROD.advance(pid, toolCanvasId(args), String((args && args.to) || ''), String((args && args.reason) || ''), 'user');
4311
+ },
4312
+ // ---- 自动创作(实验,A1 两段式):开关默认关;关闭时所有 auto* 一律拒绝 ----
4313
+ /** 开关状态 + 能力(multiAgent 取决于宿主是否暴露会话服务,M0 探针)。 */
4314
+ async autoModeGet() {
4315
+ const cfg = readIcConfig();
4316
+ const enabled = !!(cfg.ui && cfg.ui.autoMode);
4317
+ return { ok: true, enabled, caps: await methods.productionCapabilities() };
4318
+ },
4319
+ /** 打开/关闭自动创作。默认关闭;打开只是"允许入口",不启动任何创作、不花钱。 */
4320
+ async autoModeSet(args) {
4321
+ const enabled = !!(args && args.enabled);
4322
+ const cfg = readIcConfig();
4323
+ cfg.ui = { ...(cfg.ui || {}), autoMode: enabled };
4324
+ writeIcConfig(cfg);
4325
+ return { ok: true, enabled };
4326
+ },
4327
+ /** 预算单(免费段终点):场/镜/秒数/视频调用次数(+配置了单价时的估算金额)。 */
4328
+ async autoQuote(args) {
4329
+ if (!autoEnabled()) return autoDisabled();
4330
+ const pid = String((args && args.projectId) || '');
4331
+ if (!pid) return { ok: false, error: '缺少 projectId' };
4332
+ const cfg = readIcConfig();
4333
+ const price = Number(args && args.unitPricePerSecond);
4334
+ const configured = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
4335
+ return PROD.quote(pid, toolCanvasId(args), Number.isFinite(price) && price > 0 ? price : configured);
4336
+ },
4337
+ /** 批准付费段:一次性令牌,绑定预算指纹;镜头/时长一变即失效(须重新复核)。 */
4338
+ async autoApprove(args) {
4339
+ if (!autoEnabled()) return autoDisabled();
4340
+ const pid = String((args && args.projectId) || '');
4341
+ if (!pid) return { ok: false, error: '缺少 projectId' };
4342
+ const cfg = readIcConfig();
4343
+ const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
4344
+ return PROD.approve(pid, toolCanvasId(args), String((args && args.quoteId) || ''), String((args && args.confirm) || ''), price);
4345
+ },
4346
+ /** 付费段:批准后逐分镜表生成视频(真实计费);失败重试,全部完成建成片节点。 */
4347
+ async autoGenerate(args) {
4348
+ if (!autoEnabled()) return autoDisabled();
4349
+ const pid = String((args && args.projectId) || '');
4350
+ if (!pid) return { ok: false, error: '缺少 projectId' };
4351
+ return autoPaid(pid, toolCanvasId(args));
4352
+ },
4353
+ /** 自动创作总状态:开关 / 阶段 / 当前批准是否仍有效 / 编剧室运行状态 / 下一步。 */
4354
+ async autoStatus(args) {
4355
+ const cfg = readIcConfig();
4356
+ const enabled = !!(cfg.ui && cfg.ui.autoMode);
4357
+ const caps = await methods.productionCapabilities();
4358
+ const pid = String((args && args.projectId) || '');
4359
+ const run = pid ? AUTO_RUNS.get(runKeyOf(pid, toolCanvasId(args))) : null;
4360
+ const runView = run ? { status: run.status, phase: run.phase, error: run.error || null,
4361
+ log: run.log.slice(-6), meetingNodeId: run.meetingNodeId || null, scriptNodeId: run.scriptNodeId || null, startedAt: run.startedAt,
4362
+ budget: run.budget || null, boards: run.boards || [], paid: run.paid || null, paidPhase: run.paidPhase || null, paidError: run.paidError || null,
4363
+ paidLog: (run.paidLog || []).slice(-6), finalcutNodeId: run.finalcutNodeId || null } : null;
4364
+ if (!enabled || !pid) return { ok: true, enabled, caps, stage: null, approval: null, run: runView };
4365
+ const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
4366
+ const st = PROD.status(pid, toolCanvasId(args));
4367
+ return {
4368
+ ok: true, enabled, caps,
4369
+ stage: st.stage, ready: st.ready, blockers: st.blockers,
4370
+ approval: PROD.approvalOf(pid, toolCanvasId(args), price),
4371
+ quote: PROD.quote(pid, toolCanvasId(args), price),
4372
+ run: runView,
4373
+ };
4374
+ },
4375
+ /** 启动免费段(编剧室):调研 → 编剧A/B 独立提案 → 互评 → 监制决策 → 设定集+剧本 idea 落盘。
4376
+ * 全程零付费;讨论记录写进「编剧室会议」文本节点;剧情走向只来自 brief。 */
4377
+ async autoStart(args) {
4378
+ if (!autoEnabled()) return autoDisabled();
4379
+ const pid = String((args && args.projectId) || '');
4380
+ 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
+ const cid = toolCanvasId(args);
4384
+ const runKey = runKeyOf(pid, cid);
4385
+ const prev = AUTO_RUNS.get(runKey);
4386
+ 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 };
4388
+ AUTO_RUNS.set(runKey, run);
4389
+ // brief 记进制作状态(status 可见;重启后仍能查到这一集的创意源头)
4390
+ try {
4391
+ 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;
4393
+ ps.updatedAt = Date.now();
4394
+ PROD.writeState(pid, cid, ps);
4395
+ } catch { /* 状态写入失败不阻塞启动 */ }
4396
+ autoRoom(pid, cid, brief).catch(() => { /* 兜底:autoRoom 内部已捕获并落状态 */ });
4397
+ return { ok: true, runId: runKey, status: 'running', note: '免费段已启动(调研→提案→互评→决策→落盘);用 autoStatus 查看进度' };
4398
+ },
4399
+ /** 中止运行中的自动创作(免费段或付费段):保留已产出内容(讨论节点/设定集/节点/已完成视频)。 */
4400
+ async autoAbort(args) {
4401
+ if (!autoEnabled()) return autoDisabled();
4402
+ const pid = String((args && args.projectId) || '');
4403
+ if (!pid) return { ok: false, error: '缺少 projectId' };
4404
+ const run = AUTO_RUNS.get(runKeyOf(pid, toolCanvasId(args)));
4405
+ if (!run) return { ok: false, error: '该画布没有正在运行的自动创作' };
4406
+ let stopped = false;
4407
+ if (run.status === 'running') { run.status = 'aborted'; stopped = true; }
4408
+ if (run.paid === 'running') { run.paidAbort = true; run.paid = 'aborting'; stopped = true; }
4409
+ if (!stopped) return { ok: false, error: '该画布没有正在运行的自动创作' };
4410
+ run.error = null;
4411
+ run.log.push({ at: Date.now(), role: 'runner', summary: '已中止(保留已产出内容)' });
4412
+ return { ok: true, status: run.status, paid: run.paid };
4413
+ },
3806
4414
  async sessionBindingGet(args) {
3807
4415
  const sid = String((args && args.sessionId) || '');
3808
4416
  if (!sid) return { ok: false, error: '缺少 sessionId' };
@@ -3907,6 +4515,18 @@ export function apply(ctx) {
3907
4515
  rec = wsRecOf(sc.ws);
3908
4516
  }
3909
4517
  if (!rec) { rec = wsProjectCreateAt(sc.ws); createdNow = true; }
4518
+ // 存量修正:机器生成的项目名(= 目录名 / 项目 id / ws* 随机串)→ 改用工作区显示名。
4519
+ // 用户手动改过名的项目(既不等于目录名也不像 id)绝不覆盖。
4520
+ const wsTitle = String((sc.ws && sc.ws.title) || '').replace(/\s+/g, ' ').trim().slice(0, 80);
4521
+ if (rec && wsTitle) {
4522
+ try {
4523
+ const doc = readDoc(rec.pid);
4524
+ const cur = String(doc.name || '').trim();
4525
+ const folder = (path.basename(String((sc.ws && sc.ws.path) || '')) || '').trim();
4526
+ const machineNamed = !cur || cur === folder || cur === rec.pid || /^ws[a-z0-9]{8,}$/i.test(cur);
4527
+ if (machineNamed && cur !== wsTitle) patchProjectDoc(rec.pid, { name: wsTitle });
4528
+ } catch { /* 修正失败不阻塞创建/绑定 */ }
4529
+ }
3910
4530
  const name = String((args && args.name) || '').trim();
3911
4531
  if (createdNow && name) {
3912
4532
  try { patchProjectDoc(rec.pid, { name: name.slice(0, 80) }); } catch { /* 改名失败不阻塞 */ }
@@ -3916,6 +4536,7 @@ export function apply(ctx) {
3916
4536
  if (createdNow) bound = await bindingSet(rec.pid, sid, null, sc.isAlive);
3917
4537
  return {
3918
4538
  ok: true, projectId: rec.pid, created: createdNow,
4539
+ name: (() => { try { return String(readDoc(rec.pid).name || '').trim() || undefined; } catch { return undefined; } })(),
3919
4540
  bound: !!(bound && bound.ok), occupied: !!(bound && bound.occupied),
3920
4541
  bindError: bound && !bound.ok ? (bound.error || null) : null,
3921
4542
  };
@@ -4028,10 +4649,18 @@ export function apply(ctx) {
4028
4649
  render: (args, value) => [{ type: 'text', text: String(value.text || '') }],
4029
4650
  },
4030
4651
  timeoutMs: 30000,
4031
- async execute(args) {
4652
+ async execute(args, exec) {
4032
4653
  const kw = String((args && args.keyword) || '').toLowerCase();
4033
- const list = projectsList().filter((p) => !kw || String(p.name).toLowerCase().includes(kw));
4654
+ // 绑定会话:只允许看到自己绑定的项目(读取也必须锁死,否则模型能"围观"全部画布)
4655
+ const sid = toolExecSessionId(exec);
4656
+ const bound = sid ? toolBindingForSession(sid) : null;
4657
+ let full = projectsList();
4658
+ if (full && typeof full.then === 'function') full = await full;
4659
+ let list = Array.isArray(full) ? full : [];
4660
+ if (bound) list = list.filter((p) => p.id === bound.projectId);
4661
+ list = list.filter((p) => !kw || String(p.name).toLowerCase().includes(kw));
4034
4662
  const lines = [];
4663
+ if (bound) lines.push('本会话已绑定画布工作台:只显示绑定项目「' + ((list[0] && list[0].name) || bound.projectId) + '」;其他项目已隐藏(要操作其他项目请先解绑)。');
4035
4664
  for (const p of list) {
4036
4665
  const canvases = Array.isArray(p.canvases) ? p.canvases : [];
4037
4666
  const defTxt = p.defaultCanvasDeleted
@@ -4061,7 +4690,13 @@ export function apply(ctx) {
4061
4690
  },
4062
4691
  output: textOutput,
4063
4692
  timeoutMs: 30000,
4064
- async execute(args) {
4693
+ async execute(args, exec) {
4694
+ // 绑定会话:禁止新建项目(跨项目动作;要新建先解绑)
4695
+ const sid = toolExecSessionId(exec);
4696
+ const bound = sid ? toolBindingForSession(sid) : null;
4697
+ if (bound) {
4698
+ return { ok: false, locked: true, text: '本会话已绑定画布工作台「' + (bound.canvasId ? bound.canvasId : '默认画布') + '」,代码级限制:禁止新建项目(一个会话只允许操作自己绑定的那一张画布)。要新建项目请先在对话输入行的画布选择器里解绑。' };
4699
+ }
4065
4700
  const r = canvasCreateProject(args);
4066
4701
  if (r.reused) {
4067
4702
  return { ok: true, projectId: r.projectId, name: r.name, text: '♻️ 项目「' + r.name + '」已存在(id=' + r.projectId + '),已复用,未重复创建。往其中加内容请用 canvas_write_node({ projectId: "' + r.projectId + '", ... })。' };
@@ -4113,6 +4748,10 @@ export function apply(ctx) {
4113
4748
  timeoutMs: 30000,
4114
4749
  async execute(args) {
4115
4750
  const r = await canvasRunNode(args);
4751
+ if (r && r.ok === false) {
4752
+ const det = r.fails ? '\n· ' + r.fails.join('\n· ') : '';
4753
+ return { ok: false, gate: r.gate, projectId: r.projectId, nodeId: r.nodeId, missing: r.missing || undefined, fails: r.fails || undefined, warns: r.warns || undefined, fix: r.fix || undefined, text: '⛔ [' + r.gate + '] ' + (r.error || '流程闸门未通过') + det + (r.fix ? '\n出路:' + r.fix : '') };
4754
+ }
4116
4755
  return { ok: true, projectId: r.projectId, nodeId: r.nodeId, text: '🚀 已触发执行[' + r.type + ']「' + (r.label || r.nodeId) + '」。画布将在数秒内开始,可用 canvas_node_status 查询进度与结果。' };
4117
4756
  },
4118
4757
  });
@@ -4261,6 +4900,10 @@ export function apply(ctx) {
4261
4900
  timeoutMs: 660000,
4262
4901
  async execute(args) {
4263
4902
  const r = await canvasGenerateNode(args);
4903
+ if (r && r.ok === false && r.gate) {
4904
+ const det = r.fails ? '\n· ' + r.fails.join('\n· ') : '';
4905
+ return { ok: false, gate: r.gate, projectId: r.projectId, nodeId: r.nodeId, text: '⛔ [' + r.gate + '] ' + (r.error || '流程闸门未通过') + det + (r.fix ? '\n出路:' + r.fix : '') };
4906
+ }
4264
4907
  const head = '🚀 已触发[' + r.type + ']「' + (r.label || r.nodeId) + '」';
4265
4908
  const tail = r.finished
4266
4909
  ? (r.ok ? '✅ 已完成(状态 ' + r.status + (r.assetId ? ',产物资产 ' + r.assetId : '') + ')' : '❌ 失败:' + (r.error || r.status))
@@ -4281,12 +4924,13 @@ export function apply(ctx) {
4281
4924
  timeoutMs: 30000,
4282
4925
  async execute(args) {
4283
4926
  const r = await canvasDeleteNode(args);
4927
+ if (r && r.ok === false) return { ok: false, gate: r.gate, projectId: r.projectId, nodeId: r.nodeId, text: '⛔ [' + r.gate + '] ' + (r.error || '') + (r.fix ? '\n出路:' + r.fix : '') };
4284
4928
  return { ok: true, projectId: r.projectId, nodeId: r.nodeId, text: '🗑 已删除节点 ' + r.nodeId + '。' };
4285
4929
  },
4286
4930
  });
4287
4931
  reg({
4288
4932
  name: 'canvas_relayout',
4289
- description: '一键重排画布节点布局(消除重叠):按「行」排列——横向数据流决定列(文本→分镜表→视频→资产),竖向关系(衔接 prev / 首帧 frame)不参与分列;每行 = 一个横向连通组(如「场N文本 ↔ 场N分镜表」同行对齐),行高取行内最高节点、行间保留间距。节点重叠、或批量建点后布局混乱时调用。',
4933
+ description: '一键粗排画布节点(兜底用,不是精确摆放):按「行」排列——横向数据流决定列,竖向关系(prev/frame)不参与分列;每行 = 一个横向连通组,行间保留间距,多行按带宽分带左右铺开。**pinned(被 canvas_layout_node 钉住的节点)不会被移动**。需要精确到像素的摆放请用 canvas_layout_get + canvas_layout_node,不要用本工具。',
4290
4934
  parameters: {
4291
4935
  type: 'object',
4292
4936
  properties: { projectId: { type: 'string', description: '项目 id' }, canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' } },
@@ -4297,7 +4941,61 @@ export function apply(ctx) {
4297
4941
  timeoutMs: 30000,
4298
4942
  async execute(args) {
4299
4943
  const r = canvasRelayout(args);
4300
- return { ok: true, projectId: r.projectId, text: '✅ 已重排 ' + r.moved + ' 个节点(' + r.rows + ' 行,无重叠)。' };
4944
+ return { ok: true, projectId: r.projectId, text: '✅ 已重排 ' + r.moved + ' 个节点(' + r.rows + ' 行,无重叠)。' + (r.skippedPinned ? '钉住的 ' + r.skippedPinned + ' 个节点保持原位。' : '') };
4945
+ },
4946
+ });
4947
+ reg({
4948
+ name: 'canvas_layout_get',
4949
+ description: '读取整画布几何视图:返回每个节点的 nodeId/名字/类型/x/y/w/h/pinned 与画布包围盒。精确摆放前先调它拿全图坐标(不要靠猜)。',
4950
+ parameters: {
4951
+ type: 'object',
4952
+ properties: { projectId: { type: 'string', description: '项目 id' }, canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' } },
4953
+ required: ['projectId'],
4954
+ additionalProperties: false,
4955
+ },
4956
+ output: textOutput,
4957
+ timeoutMs: 15000,
4958
+ async execute(args) {
4959
+ const r = canvasLayoutGet(args);
4960
+ const lines = r.nodes.map((n) => n.nodeId + ' [' + n.type + '] ' + n.name + ' x=' + n.x + ' y=' + n.y + ' w=' + n.w + ' h=' + n.h + (n.pinned ? ' 📌' : ''));
4961
+ return { ok: true, projectId: r.projectId, count: r.count, bounds: r.bounds || undefined, nodes: r.nodes, text: '几何视图(' + r.count + ' 个节点' + (r.bounds ? ',范围 x ' + r.bounds.minX + '..' + r.bounds.maxX + ' / y ' + r.bounds.minY + '..' + r.bounds.maxY : '') + '):\n' + lines.join('\n') };
4962
+ },
4963
+ });
4964
+ reg({
4965
+ name: 'canvas_layout_node',
4966
+ description: '精准摆放节点(0.20.0):批量设置坐标,媒体节点可同时改尺寸;pinned=true 钉住后 canvas_relayout 不会再动它。允许重叠(这是精确摆放,不是自动整理)。先 canvas_layout_get 读全图,再算好坐标一次传入。',
4967
+ parameters: {
4968
+ type: 'object',
4969
+ properties: {
4970
+ projectId: { type: 'string', description: '项目 id' },
4971
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
4972
+ nodes: {
4973
+ type: 'array',
4974
+ description: '要摆放的节点数组(一次可传多个)',
4975
+ items: {
4976
+ type: 'object',
4977
+ properties: {
4978
+ nodeId: { type: 'string' },
4979
+ x: { type: 'number', description: '目标 x(可为负)' },
4980
+ y: { type: 'number', description: '目标 y(可为负)' },
4981
+ w: { type: 'number', description: '可选:宽度(仅 image/video,≥160)' },
4982
+ h: { type: 'number', description: '可选:高度(仅 image/video,≥120)' },
4983
+ pinned: { type: 'boolean', description: '可选:钉住,canvas_relayout 不再移动它' },
4984
+ },
4985
+ required: ['nodeId', 'x', 'y'],
4986
+ additionalProperties: false,
4987
+ },
4988
+ },
4989
+ },
4990
+ required: ['projectId', 'nodes'],
4991
+ additionalProperties: false,
4992
+ },
4993
+ output: textOutput,
4994
+ timeoutMs: 30000,
4995
+ async execute(args) {
4996
+ const r = canvasLayoutNode(args);
4997
+ const lines = r.applied.map((a) => a.nodeId + ' → x=' + a.x + ' y=' + a.y + (a.w !== undefined ? ' w=' + a.w + ' h=' + a.h : '') + (a.pinned !== undefined ? (a.pinned ? ' 📌钉住' : ' 取消钉住') : ''));
4998
+ return { ok: true, projectId: r.projectId, moved: r.moved, applied: r.applied, text: '✅ 已精准摆放 ' + r.moved + ' 个节点:\n' + lines.join('\n') };
4301
4999
  },
4302
5000
  });
4303
5001
  reg({
@@ -4378,6 +5076,7 @@ export function apply(ctx) {
4378
5076
  timeoutMs: 30000,
4379
5077
  async execute(args) {
4380
5078
  const r = await canvasDeleteProject(args);
5079
+ if (r && r.ok === false && r.gate) return { ok: false, gate: r.gate, projectId: r.projectId, text: '⛔ [' + r.gate + '] ' + (r.error || '') + (r.fix ? '\n出路:' + r.fix : '') };
4381
5080
  // 磁盘清理失败必须可见:rmrf 部分失败(文件锁)时目录残留,同名重建会继承旧文件
4382
5081
  const diskErrs = r.disk && Array.isArray(r.disk.errors) ? r.disk.errors : [];
4383
5082
  const warn = diskErrs.length ? '⚠ 磁盘清理有 ' + diskErrs.length + ' 项失败:' + diskErrs.join(';') : '';
@@ -4530,6 +5229,156 @@ export function apply(ctx) {
4530
5229
  return { ok: true, projectId: b.projectId, canvasId: cid, name, text: lines.join('\n') };
4531
5230
  },
4532
5231
  });
5232
+ reg({
5233
+ name: 'canvas_production_status',
5234
+ description: '制作状态汇报(阶段机):返回本集画布当前所处阶段(brief/bible/assets/script/storyboard/shots_ready/generating/qc/post/delivered)、各闸门(设定集 G1 / 分镜质量 G2)的通过情况与缺失清单、证据计数(剧本/镜头/资产/视频完成数)、以及当前阶段的下一步建议。【铁律】宣称"完成/可以交付"之前必须先调它:只有 ready:true 或用户明确验收才允许说完成;blockers 非空时逐条修复后再继续。开工、卡住、汇报前都应调用。',
5235
+ parameters: {
5236
+ type: 'object',
5237
+ properties: {
5238
+ projectId: { type: 'string', description: '项目 id' },
5239
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5240
+ },
5241
+ required: ['projectId'],
5242
+ additionalProperties: false,
5243
+ },
5244
+ output: textOutput,
5245
+ timeoutMs: 15000,
5246
+ async execute(args) {
5247
+ const r = await productionStatus(args);
5248
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '状态读取失败') };
5249
+ let capsLine = '';
5250
+ try {
5251
+ const caps = await productionCapabilities();
5252
+ capsLine = '\n多智能体能力:' + (caps.multiAgent ? '可用(宿主已暴露会话服务)' : '不可用(宿主未暴露会话服务——自动创作保持休眠)');
5253
+ } catch { /* 探针失败不影响状态输出 */ }
5254
+ const lines = [
5255
+ '阶段:' + r.stageZh + '(' + r.stage + ')' + (r.explicit ? ' · 显式设定' : ' · 自动推进') + ' 推断基线:' + r.inferred,
5256
+ '闸门:G1 设定集 ' + (r.gates.bible.ok ? '✅' : '❌ 缺 ' + r.gates.bible.missing.join('、')) + ';G2 分镜 ' + (r.gates.storyboard.ok ? '✅' : '❌ ' + r.gates.storyboard.fails.length + ' 项'),
5257
+ ];
5258
+ if ((r.gates.storyboard.warns || []).length) lines.push('G2 建议:' + r.gates.storyboard.warns.slice(0, 4).join(';'));
5259
+ if (r.blockers.length) lines.push('阻塞:' + r.blockers.map((b) => b.gate).join('、') + '——逐条修复后再继续');
5260
+ const e = r.evidence;
5261
+ lines.push('证据:角色 ' + e.characters + ' · 场景 ' + e.scenes + ' · 剧本 ' + e.scriptsDone + '/' + e.scripts + ' · 分镜表 ' + e.storyboardsWithShots + '/' + e.storyboards + '(镜头 ' + e.shotsTotal + ')· 图 ' + e.imagesDone + '/' + e.images + ' · 视频 ' + e.videosDone + '/' + e.videos);
5262
+ lines.push('下一步:' + r.next);
5263
+ lines.push('ready=' + (r.ready ? 'true(可宣称完成/进入下一步)' : 'false(不得宣称完成)'));
5264
+ 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') };
5266
+ },
5267
+ });
5268
+ reg({
5269
+ name: 'canvas_production_advance',
5270
+ description: '显式推进/回退制作阶段(阶段机):仅在两种情况使用——① 用户明确要求跳过某一步(如实说明后果后);② 返工(如"这集分镜推倒重来"回退到 storyboard)。日常推进是自动的,不需要调它。必须携带 reason(写进审计),回退会同时下调阶段基线,后续按工具事件重新抬升。',
5271
+ parameters: {
5272
+ type: 'object',
5273
+ properties: {
5274
+ projectId: { type: 'string', description: '项目 id' },
5275
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5276
+ to: { type: 'string', enum: ['brief', 'bible', 'assets', 'script', 'storyboard', 'shots_ready', 'generating', 'qc', 'post', 'delivered'], description: '目标阶段' },
5277
+ reason: { type: 'string', description: '原因(必填,进审计日志)' },
5278
+ },
5279
+ required: ['projectId', 'to', 'reason'],
5280
+ additionalProperties: false,
5281
+ },
5282
+ output: textOutput,
5283
+ timeoutMs: 15000,
5284
+ async execute(args) {
5285
+ const r = await productionAdvance(args);
5286
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '推进失败') };
5287
+ return { ok: true, projectId: args.projectId, stage: r.to, text: '✅ 阶段 ' + r.from + ' → ' + r.to + '(已记入审计)。' };
5288
+ },
5289
+ });
5290
+ reg({
5291
+ name: 'canvas_auto_status',
5292
+ description: '自动创作总状态:开关是否开启、宿主多智能体能力、编剧室运行进度(阶段/日志)、免费段预算单(场/镜/秒/待调用次数/估算金额)、付费段进度与成片节点。【自动模式开场先调它】它决定你走全自动分支还是引导式工作坊。',
5293
+ parameters: { type: 'object', properties: {
5294
+ projectId: { type: 'string', description: '项目 id' },
5295
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5296
+ }, required: ['projectId'], additionalProperties: false },
5297
+ output: textOutput,
5298
+ timeoutMs: 15000,
5299
+ async execute(args) {
5300
+ const r = await methods.autoStatus(args);
5301
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '状态读取失败') };
5302
+ const lines = ['自动创作:' + (r.enabled ? '已开启' : '已关闭') + ' · 多智能体:' + (r.caps && r.caps.multiAgent ? '可用' : '不可用')];
5303
+ if (r.enabled) lines.push('【自动模式·硬规则】禁止调用 ask_user_question(任何理由);本轮必须 canvas_auto_start 启动编剧室,brief 不足由编剧室代拟 3 个方向并选定。');
5304
+ if (r.stage) lines.push('制作阶段:' + r.stage);
5305
+ if (r.run) {
5306
+ lines.push('编剧室:' + r.run.status + (r.run.phase ? '(' + r.run.phase + ')' : '') + (r.run.error ? ' · 错误:' + r.run.error : ''));
5307
+ if (r.run.budget) lines.push('预算单:' + r.run.budget.sceneCount + ' 场 / ' + r.run.budget.shotCount + ' 镜 / ' + r.run.budget.totalSeconds + ' 秒 / 待调用 ' + r.run.budget.videoCalls + ' 次' + (r.run.budget.estimatedCost != null ? ' / 估算 ' + r.run.budget.estimatedCost : ''));
5308
+ if (r.run.boards && r.run.boards.length) lines.push('分镜:' + r.run.boards.map((b) => '场' + b.no + (b.gate ? '✅' : '⚠' + b.fails.length)).join(' '));
5309
+ if (r.run.paid) lines.push('付费段:' + r.run.paid + (r.run.paidPhase ? '(' + r.run.paidPhase + ')' : '') + (r.run.paidError ? ' · ' + r.run.paidError : ''));
5310
+ if (r.run.log && r.run.log.length) lines.push('最近:' + r.run.log[r.run.log.length - 1].summary);
5311
+ }
5312
+ if (r.approval) lines.push('批准:' + (r.approval.valid ? '有效(' + r.approval.quoteId + ')' : '无/已过期'));
5313
+ return { ok: true, enabled: r.enabled, caps: r.caps, run: r.run, budget: r.run && r.run.budget || null, approval: r.approval, text: lines.join('\n') };
5314
+ },
5315
+ });
5316
+ reg({
5317
+ name: 'canvas_auto_start',
5318
+ description: '启动全自动创作免费段(零付费):自动打开画布 → 调研 → 编剧A/B 独立提案 → 互评 → 监制决策 → 设定集 → 剧本生成 → 按场拆分 → 逐场分镜表 → G2 校验 → 预算单。仅当自动创作开关已开启时可用。**自动模式下用户给出创意后直接调用它,不要逐步提问。**',
5319
+ parameters: { type: 'object', properties: {
5320
+ projectId: { type: 'string', description: '项目 id' },
5321
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5322
+ brief: { type: 'string', description: '一句话创意(拍什么/给谁看/什么情绪)——剧情走向的唯一源头' },
5323
+ }, required: ['projectId', 'brief'], additionalProperties: false },
5324
+ output: textOutput,
5325
+ timeoutMs: 30000,
5326
+ async execute(args) {
5327
+ try { await canvasOpen({ projectId: args.projectId, canvasId: args.canvasId }); } catch { /* 打开失败不阻塞启动 */ }
5328
+ const r = await methods.autoStart(args);
5329
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '启动失败') };
5330
+ return { ok: true, projectId: args.projectId, status: r.status, text: '🚀 免费段已启动(自动打开画布 + 调研/提案/互评/决策/剧本/分镜/预算单)。用 canvas_auto_status 查看进度。' };
5331
+ },
5332
+ });
5333
+ reg({
5334
+ name: 'canvas_auto_budget',
5335
+ description: '生成/查看免费段的预算单:场数、镜数、总秒数、待调用视频次数、配置单价时的估算金额。批准付费前必须先用它出单。',
5336
+ parameters: { type: 'object', properties: {
5337
+ projectId: { type: 'string', description: '项目 id' },
5338
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5339
+ unitPricePerSecond: { type: 'number', description: '可选:每秒单价(不传则用画布设置里的单价)' },
5340
+ }, required: ['projectId'], additionalProperties: false },
5341
+ output: textOutput,
5342
+ timeoutMs: 15000,
5343
+ async execute(args) {
5344
+ const r = await methods.autoQuote(args);
5345
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '预算单生成失败') };
5346
+ const lines = ['预算单 ' + r.quoteId, '场 ' + r.sceneCount + ' / 镜 ' + r.shotCount + ' / ' + r.totalSeconds + ' 秒 / 待调用 ' + r.videoCalls + ' 次'];
5347
+ if (r.estimatedCost != null) lines.push('估算金额:' + r.estimatedCost + '(单价 ' + r.unitPricePerSecond + '/秒)');
5348
+ lines.push('批准:调用 autoApprove 或在设置卡点「批准付费段」(必须带用户原话)');
5349
+ return { ok: true, quoteId: r.quoteId, budget: r, text: lines.join('\n') };
5350
+ },
5351
+ });
5352
+ reg({
5353
+ name: 'canvas_auto_generate',
5354
+ description: '付费段:仅在有有效批准后可用——逐分镜表创建视频节点并真实生成(按秒计费),失败重试 2 次,全部完成后创建「成片」节点。没有批准会被拒绝。',
5355
+ parameters: { type: 'object', properties: {
5356
+ projectId: { type: 'string', description: '项目 id' },
5357
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5358
+ }, required: ['projectId'], additionalProperties: false },
5359
+ output: textOutput,
5360
+ timeoutMs: 30000,
5361
+ async execute(args) {
5362
+ const r = await methods.autoGenerate(args);
5363
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '付费段启动失败') };
5364
+ return { ok: true, projectId: args.projectId, status: r.status, text: '🎬 付费段已启动(逐场建视频节点并生成,失败重试 2 次)。用 canvas_auto_status 查看进度。' };
5365
+ },
5366
+ });
5367
+ reg({
5368
+ name: 'canvas_auto_abort',
5369
+ description: '中止正在运行的自动创作(免费段或付费段),保留已产出内容(会议记录/设定集/节点)。',
5370
+ parameters: { type: 'object', properties: {
5371
+ projectId: { type: 'string', description: '项目 id' },
5372
+ canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
5373
+ }, required: ['projectId'], additionalProperties: false },
5374
+ output: textOutput,
5375
+ timeoutMs: 15000,
5376
+ async execute(args) {
5377
+ const r = await methods.autoAbort(args);
5378
+ if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '中止失败') };
5379
+ return { ok: true, projectId: args.projectId, text: '⏹ 已中止(保留已产出内容)。' };
5380
+ },
5381
+ });
4533
5382
  reg({
4534
5383
  name: 'canvas_create_node',
4535
5384
  description: '在项目画布上新建指定类型的节点(image 图片节点 / video 视频节点 / storyboard 分镜表 / finalcut 成片 / script 剧本 / text 文本)。图片与视频是**合并节点**:有 assetId 就是已有素材(资产),空节点在画布上点开生成面板填写提示词后生成;旧类型名 image-gen / image-asset / video-gen / video-asset 仍可用,会被自动映射为 image / video。【分镜必须用 type:"storyboard" 的分镜表节点,绝不要用剧本节点装分镜】。【工作流铁律】实际生成由节点完成:你只负责写提示词、连线(connectFrom)、canvas_run_node 触发,不要把成稿直接填进 output。分镜表用 connectFrom 连到上游剧本节点(内容来自连线,不要复制剧本全文);image/video 没有上游提示词时才在 prompt 里写内容,有上游时靠连线取。',
@@ -4558,6 +5407,10 @@ export function apply(ctx) {
4558
5407
  timeoutMs: 30000,
4559
5408
  async execute(args) {
4560
5409
  const r = canvasCreateNode(args);
5410
+ if (r && r.ok === false && r.gate) {
5411
+ const det = r.fails ? '\n· ' + r.fails.join('\n· ') : '';
5412
+ return { ok: false, gate: r.gate, projectId: r.projectId, existingVideoId: r.existingVideoId || undefined, fails: r.fails || undefined, warns: r.warns || undefined, text: '⛔ [' + r.gate + '] ' + (r.error || '流程闸门未通过') + det + (r.fix ? '\n出路:' + r.fix : '') };
5413
+ }
4561
5414
  const kindHint = r.type === 'image'
4562
5415
  ? '(图片节点:有 assetId 即资产;空节点在画布上点开生成面板写提示词后生成)'
4563
5416
  : r.type === 'video'