@ninkch/dsh-infinite-canvas 0.19.20 → 0.20.0
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/README.md +23 -0
- package/README.zh-CN.md +23 -0
- package/assets/canvas-layout/SKILL.md +19 -2
- package/assets/canvas-studio/SKILL.md +156 -378
- package/client.js +847 -61
- package/cordis.patch.yml +13 -0
- package/docs/UI-RULES.md +4 -0
- package/docs/auto-creation-design.md +68 -0
- package/docs/guide.en.md +13 -1
- package/docs/guide.zh-CN.md +14 -0
- package/index.js +1547 -30
- package/package.json +2 -1
- package/production.js +427 -0
package/index.js
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { spawn } from 'node:child_process';
|
|
10
10
|
import fs from 'node:fs/promises';
|
|
11
|
-
import { createReadStream, createWriteStream, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { createReadStream, createWriteStream, copyFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
12
12
|
import os from 'node:os';
|
|
13
13
|
import path from 'node:path';
|
|
14
14
|
import { fileURLToPath } from 'node:url';
|
|
@@ -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';
|
|
@@ -539,6 +550,11 @@ function dbAssetUpdate(id, patch) {
|
|
|
539
550
|
* 引用计数回收(gcObjectIfUnreferenced)兜住,不需要独立的定期扫描入口。 */
|
|
540
551
|
|
|
541
552
|
function readDocOrNull(id) {
|
|
553
|
+
// 工作区内嵌项目优先:文档在 <ws>/.infinite-canvas/,与数据根/SQLite 无关
|
|
554
|
+
const wsf = wsDocFile(id);
|
|
555
|
+
if (wsf) {
|
|
556
|
+
try { return JSON.parse(readFileSync(wsf, 'utf8')); } catch { return null; }
|
|
557
|
+
}
|
|
542
558
|
if (sqlActive()) {
|
|
543
559
|
const db = getDb();
|
|
544
560
|
const row = db.prepare('SELECT doc FROM projects WHERE id = ?').get(id);
|
|
@@ -548,6 +564,8 @@ function readDocOrNull(id) {
|
|
|
548
564
|
try { return JSON.parse(readFileSync(projectFile(id), 'utf8')); } catch { return null; }
|
|
549
565
|
}
|
|
550
566
|
function docExists(id) {
|
|
567
|
+
if (wsDocFile(id)) return !!readDocOrNull(id);
|
|
568
|
+
try { projectFile(id); } catch { return false; } // 非法 id(含路径逃逸段):一律视为不存在,不抛
|
|
551
569
|
if (sqlActive()) {
|
|
552
570
|
const db = getDb();
|
|
553
571
|
return !!db.prepare('SELECT id FROM projects WHERE id = ?').get(id);
|
|
@@ -1116,6 +1134,367 @@ function sanitizeCanvases(list) {
|
|
|
1116
1134
|
}
|
|
1117
1135
|
return out.slice(0, 200);
|
|
1118
1136
|
}
|
|
1137
|
+
// ---- 工作区内嵌项目(0.20.x):<工作区目录>/.infinite-canvas/ 即项目家目录 ----
|
|
1138
|
+
// 项目随工作区目录走(宿主侧 workspaceRegistry 发现):project.json / canvases/ / memory/ / bindings.json
|
|
1139
|
+
// 全部内嵌目录自包含。文档读写与数据根/SQLite 完全解耦(wsDocFile 分发);媒体仍走数据根管线
|
|
1140
|
+
//(ensureProjectFolder 统一登记媒体文件夹),拷工作区目录 = 带走全部设定/记忆/画布文档。
|
|
1141
|
+
const WS_APP_DIR = '.infinite-canvas';
|
|
1142
|
+
/** 工作区项目缓存:pid -> { pid, wsId, wsPath, home, doc };wsProjectsScan 负责刷新。 */
|
|
1143
|
+
const wsProjects = new Map();
|
|
1144
|
+
/** 扫描工作区注册表 list([{id,path,title,sessionIds}]),发现带 `.infinite-canvas/project.json` 标记的项目。
|
|
1145
|
+
* 每次全量重扫(代价 = 每工作区读一个小 JSON),标记消失/目录消失自然落榜。 */
|
|
1146
|
+
function wsProjectsScan(list) {
|
|
1147
|
+
const seen = Array.isArray(list) ? list : [];
|
|
1148
|
+
wsProjects.clear();
|
|
1149
|
+
for (const w of seen) {
|
|
1150
|
+
if (!w || typeof w.path !== 'string' || !w.path) continue;
|
|
1151
|
+
let doc = null;
|
|
1152
|
+
try {
|
|
1153
|
+
doc = JSON.parse(readFileSync(path.join(w.path, WS_APP_DIR, 'project.json'), 'utf8'));
|
|
1154
|
+
} catch { /* 无标记/损坏 → 不算项目 */ }
|
|
1155
|
+
if (!doc || typeof doc !== 'object' || !doc.id) continue;
|
|
1156
|
+
const pid = String(doc.id);
|
|
1157
|
+
wsProjects.set(pid, { pid, wsId: String(w.id || ''), wsPath: w.path, home: path.join(w.path, WS_APP_DIR), doc });
|
|
1158
|
+
}
|
|
1159
|
+
return [...wsProjects.values()];
|
|
1160
|
+
}
|
|
1161
|
+
/** 该 pid 是否工作区内嵌项目(按最近一次扫描缓存)。 */
|
|
1162
|
+
function isWsProject(pid) { return wsProjects.has(String(pid || '')); }
|
|
1163
|
+
/** 工作区项目家目录(<工作区>/.infinite-canvas);非工作区项目返回 null。 */
|
|
1164
|
+
function wsProjectHome(pid) {
|
|
1165
|
+
const r = wsProjects.get(String(pid || ''));
|
|
1166
|
+
return r ? r.home : null;
|
|
1167
|
+
}
|
|
1168
|
+
/** 工作区文档 id → 物理文件:项目文档 = project.json;子画布文档 = canvases/<cid>.json;非工作区项目返回 null。 */
|
|
1169
|
+
function wsDocFile(id) {
|
|
1170
|
+
const s = String(id || '');
|
|
1171
|
+
try { projectFile(s); } catch { return null; } // id 段合法性复用 projectFile 校验:封死 canvases/<cid> 路径逃逸(评审 I4)
|
|
1172
|
+
const ref = isCanvasDocId(s) ? splitCanvasDocId(s) : { projectId: s, canvasId: null };
|
|
1173
|
+
const home = wsProjectHome(ref.projectId);
|
|
1174
|
+
if (!home) return null;
|
|
1175
|
+
return ref.canvasId ? path.join(home, 'canvases', ref.canvasId + '.json') : path.join(home, 'project.json');
|
|
1176
|
+
}
|
|
1177
|
+
/** 工作区项目 → projectsList 条目(与数据根条目同形,另带 origin:'workspace' + wsId/wsPath)。 */
|
|
1178
|
+
function wsProjectListEntry(rec) {
|
|
1179
|
+
const d = rec.doc || {};
|
|
1180
|
+
const nodes = Object.values(d.nodes || {}).map((n) => ({
|
|
1181
|
+
id: n.id, type: normalizeNodeType(n.type), label: (n.data && n.data.label) || '',
|
|
1182
|
+
status: (n.data && n.data.status) || 'idle',
|
|
1183
|
+
x: Number(n.x) || 0, y: Number(n.y) || 0, w: Number(n.w) || 0, h: Number(n.h) || 0,
|
|
1184
|
+
}));
|
|
1185
|
+
return {
|
|
1186
|
+
id: d.id, name: d.name || rec.pid, createdAt: d.createdAt || 0, updatedAt: d.updatedAt || 0,
|
|
1187
|
+
source: d.source || 'agent', nodeIds: Object.keys(d.nodes || {}), nodes,
|
|
1188
|
+
tombstones: Array.isArray(d.tombstones) ? d.tombstones : [], bibleUpdatedAt: d.bibleUpdatedAt || 0,
|
|
1189
|
+
canvases: canvasRegistry(d), defaultCanvasName: defaultCanvasNameForApi(d),
|
|
1190
|
+
defaultCanvasDeleted: !defaultCanvasExists(d),
|
|
1191
|
+
origin: 'workspace', wsId: rec.wsId, wsPath: rec.wsPath,
|
|
1192
|
+
};
|
|
1193
|
+
}
|
|
1194
|
+
/** 删除工作区项目目录(.infinite-canvas 整目录);工作区目录本身不动。
|
|
1195
|
+
* watcher 只发现不创建 → 删除后不会复活,无需墓碑。 */
|
|
1196
|
+
function wsProjectRemove(pid) {
|
|
1197
|
+
const home = wsProjectHome(pid);
|
|
1198
|
+
if (!home) return false;
|
|
1199
|
+
try { rmSync(home, { recursive: true, force: true }); } catch { /* 目录被占用:标记已无效,后续扫描自然落榜 */ }
|
|
1200
|
+
wsProjects.delete(String(pid));
|
|
1201
|
+
return true;
|
|
1202
|
+
}
|
|
1203
|
+
/** 在工作区目录创建内嵌项目(RPC「建画布项目」/ 测试共用):默认画布「第1集」。仅显式路径调用。 */
|
|
1204
|
+
function wsProjectCreateAt(w) {
|
|
1205
|
+
const dir = path.join(String(w.path), WS_APP_DIR);
|
|
1206
|
+
try { mkdirSync(dir, { recursive: true }); } catch { /* 已存在 */ }
|
|
1207
|
+
const pid = 'ws' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
|
|
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 || '画布项目';
|
|
1213
|
+
const doc = {
|
|
1214
|
+
id: pid, name, createdAt: Date.now(), updatedAt: Date.now(), source: 'agent',
|
|
1215
|
+
nodes: {}, edges: [], view: { x: 60, y: 40, scale: 1 },
|
|
1216
|
+
defaultCanvasName: '第1集',
|
|
1217
|
+
};
|
|
1218
|
+
const rec = { pid, wsId: String(w.id || ''), wsPath: String(w.path), home: dir, doc };
|
|
1219
|
+
wsProjects.set(pid, rec); // 先登记再写:writeIcDoc 的 ws 分发靠 wsProjectHome 命中
|
|
1220
|
+
try {
|
|
1221
|
+
writeIcDoc(pid, doc); // ws 分发 → <dir>/project.json
|
|
1222
|
+
} catch (e) {
|
|
1223
|
+
wsProjects.delete(pid); // 写失败不留幽灵缓存
|
|
1224
|
+
throw e;
|
|
1225
|
+
}
|
|
1226
|
+
return rec;
|
|
1227
|
+
}
|
|
1228
|
+
/** 工作区注册表条目 → 已登记项目缓存记录(wsId/wsPath 双口径匹配)。 */
|
|
1229
|
+
function wsRecOf(w) {
|
|
1230
|
+
if (!w) return null;
|
|
1231
|
+
return [...wsProjects.values()].find((r) => r.wsId === String(w.id || '') || r.wsPath === w.path) || null;
|
|
1232
|
+
}
|
|
1233
|
+
/** watcher 单次 tick:**纯发现**——只扫描已带 `.infinite-canvas/project.json` 标记的工作区项目进缓存/列表。
|
|
1234
|
+
* 不自动建项目、不自动绑会话(0.20.x 口径修正):绑定必须是用户在 composer chip 里的显式动作,
|
|
1235
|
+
* 编码等普通任务的工作区零打扰。目录消失的标记自然读不到 → 自动落榜,无需特殊处理。 */
|
|
1236
|
+
function wsWatchTick(list) {
|
|
1237
|
+
if (!Array.isArray(list)) return { skipped: true };
|
|
1238
|
+
const scan = wsProjectsScan(list);
|
|
1239
|
+
return { skipped: false, discovered: scan.map((r) => r.pid) };
|
|
1240
|
+
}
|
|
1241
|
+
// ---- 项目记忆(0.20.x):每集画布一份记忆正文 + 项目级调度索引 ----
|
|
1242
|
+
// 落位:<项目家目录>/memory/index.json(索引:canvasId/标题/摘要/关键词/状态)+ memory/episodes/<canvasId>.md(正文)。
|
|
1243
|
+
// 项目家目录:工作区项目 = <ws>/.infinite-canvas;数据根项目 = <数据根>/projects/<项目文件夹>。
|
|
1244
|
+
// 世界观/风格在 bible(project.json),记忆只记「动态」:剧情决策/人物状态变化/伏笔账本。
|
|
1245
|
+
/** 项目家目录:记忆/绑定等派生文件的落点。
|
|
1246
|
+
* 工作区项目 = <ws>/.infinite-canvas;有数据根 = <数据根>/projects/<项目文件夹>;
|
|
1247
|
+
* 无数据根(IndexedDB 模式)= PROJECTS_DIR/<pid>/(记忆功能不因数据根缺席而缺席)。 */
|
|
1248
|
+
function projectHomeDir(pid) {
|
|
1249
|
+
const id = String(pid || '');
|
|
1250
|
+
const ws = wsProjectHome(id);
|
|
1251
|
+
if (ws) return ws;
|
|
1252
|
+
const root = dataRoot();
|
|
1253
|
+
if (root) {
|
|
1254
|
+
let entry = readDataRootMeta().projects.find((p) => p.id === id);
|
|
1255
|
+
if (!entry) {
|
|
1256
|
+
// 从未登记过媒体文件夹的老项目:按需登记(目录随之创建)
|
|
1257
|
+
try {
|
|
1258
|
+
const doc = readDocOrNull(id);
|
|
1259
|
+
const folder = ensureProjectFolder(id, (doc && doc.name) || id);
|
|
1260
|
+
if (folder) entry = { folder };
|
|
1261
|
+
} catch { /* 项目不存在等 → 走统一落点 */ }
|
|
1262
|
+
}
|
|
1263
|
+
return entry && entry.folder ? path.join(root, 'projects', entry.folder) : null;
|
|
1264
|
+
}
|
|
1265
|
+
try { projectFile(id); } catch { return null; } // 非法 id 拒绝(防路径逃逸)
|
|
1266
|
+
return path.join(PROJECTS_DIR, id);
|
|
1267
|
+
}
|
|
1268
|
+
const MEMORY_CAP = { title: 80, summary: 120, keywords: 10, keyword: 24 };
|
|
1269
|
+
/** 同项目写串行链:并发 memoryWrite 顺序落盘,互不覆盖。 */
|
|
1270
|
+
const memoryWriteChains = new Map();
|
|
1271
|
+
function memoryDirOf(pid) {
|
|
1272
|
+
const home = projectHomeDir(pid);
|
|
1273
|
+
return home ? path.join(home, 'memory') : null;
|
|
1274
|
+
}
|
|
1275
|
+
/** 读调度索引;缺失/损坏一律容错为空索引(写路径会重建)。 */
|
|
1276
|
+
function readMemoryIndex(pid) {
|
|
1277
|
+
const dir = memoryDirOf(pid);
|
|
1278
|
+
if (dir) {
|
|
1279
|
+
try {
|
|
1280
|
+
const m = JSON.parse(readFileSync(path.join(dir, 'index.json'), 'utf8'));
|
|
1281
|
+
if (m && typeof m === 'object' && Array.isArray(m.episodes)) return m;
|
|
1282
|
+
} catch { /* 缺失/损坏 → 重建 */ }
|
|
1283
|
+
}
|
|
1284
|
+
return { version: 1, updatedAt: 0, episodes: [] };
|
|
1285
|
+
}
|
|
1286
|
+
/** 原子写索引;覆盖前留一份 index.backup.json(上次良好状态)。 */
|
|
1287
|
+
function writeMemoryIndexAtomic(pid, index) {
|
|
1288
|
+
const dir = memoryDirOf(pid);
|
|
1289
|
+
if (!dir) return;
|
|
1290
|
+
mkdirSync(dir, { recursive: true });
|
|
1291
|
+
const f = path.join(dir, 'index.json');
|
|
1292
|
+
try { if (existsSync(f)) copyFileSync(f, path.join(dir, 'index.backup.json')); } catch { /* 备份失败不阻塞 */ }
|
|
1293
|
+
const tmp = f + '.' + process.pid + '.tmp';
|
|
1294
|
+
writeFileSync(tmp, JSON.stringify(index, null, 1), 'utf8');
|
|
1295
|
+
renameSync(tmp, f);
|
|
1296
|
+
}
|
|
1297
|
+
/** 写一集记忆:正文落 episodes/<canvasId>.md(有内容才写),索引条目 upsert(保序)。 */
|
|
1298
|
+
async function memoryWrite(pid, canvasId, patch) {
|
|
1299
|
+
const id = String(pid || '');
|
|
1300
|
+
const cid = normalizeCanvasId(canvasId);
|
|
1301
|
+
if (!id || !cid) return { ok: false, error: '缺少 projectId 或 canvasId' };
|
|
1302
|
+
try { projectFile(id); } catch { return { ok: false, error: '非法项目 id' }; }
|
|
1303
|
+
const p = patch || {};
|
|
1304
|
+
const rec = {
|
|
1305
|
+
canvasId: cid,
|
|
1306
|
+
title: String(p.title || '').trim().slice(0, MEMORY_CAP.title) || ('画布 ' + cid),
|
|
1307
|
+
summary: String(p.summary || '').trim().slice(0, MEMORY_CAP.summary),
|
|
1308
|
+
keywords: (Array.isArray(p.keywords) ? p.keywords : [])
|
|
1309
|
+
.map((k) => String(k || '').trim().slice(0, MEMORY_CAP.keyword)).filter(Boolean).slice(0, MEMORY_CAP.keywords),
|
|
1310
|
+
status: p.status === 'done' ? 'done' : 'drafting',
|
|
1311
|
+
updatedAt: Date.now(),
|
|
1312
|
+
};
|
|
1313
|
+
const body = String(p.body == null ? '' : p.body);
|
|
1314
|
+
const job = (memoryWriteChains.get(id) || Promise.resolve()).catch(() => {}).then(() => {
|
|
1315
|
+
const dir = memoryDirOf(id);
|
|
1316
|
+
if (!dir) return { ok: false, error: '项目家目录不可用(未设置数据根且非工作区项目)' };
|
|
1317
|
+
if (body.trim()) {
|
|
1318
|
+
const epDir = path.join(dir, 'episodes');
|
|
1319
|
+
try { mkdirSync(epDir, { recursive: true }); } catch { /* 已存在 */ }
|
|
1320
|
+
const f = path.join(epDir, cid + '.md');
|
|
1321
|
+
const tmp = f + '.' + process.pid + '.tmp';
|
|
1322
|
+
writeFileSync(tmp, body, 'utf8');
|
|
1323
|
+
renameSync(tmp, f);
|
|
1324
|
+
}
|
|
1325
|
+
const idx = readMemoryIndex(id);
|
|
1326
|
+
const i = idx.episodes.findIndex((e) => e && e.canvasId === cid);
|
|
1327
|
+
if (i >= 0) idx.episodes[i] = { ...idx.episodes[i], ...rec };
|
|
1328
|
+
else idx.episodes.push(rec);
|
|
1329
|
+
idx.version = 1;
|
|
1330
|
+
idx.updatedAt = Date.now();
|
|
1331
|
+
writeMemoryIndexAtomic(id, idx);
|
|
1332
|
+
return { ok: true, projectId: id, canvasId: cid, index: idx };
|
|
1333
|
+
});
|
|
1334
|
+
memoryWriteChains.set(id, job);
|
|
1335
|
+
return job;
|
|
1336
|
+
}
|
|
1337
|
+
/** 读记忆:无 canvasId 只回索引;有 canvasId 附该集正文(正文文件可独立于索引存在)。 */
|
|
1338
|
+
async function memoryRead(pid, canvasId) {
|
|
1339
|
+
const id = String(pid || '');
|
|
1340
|
+
const idx = readMemoryIndex(id);
|
|
1341
|
+
const cid = normalizeCanvasId(canvasId);
|
|
1342
|
+
let episode = null;
|
|
1343
|
+
if (cid) {
|
|
1344
|
+
const dir = memoryDirOf(id);
|
|
1345
|
+
let body = null;
|
|
1346
|
+
if (dir) {
|
|
1347
|
+
try { body = readFileSync(path.join(dir, 'episodes', cid + '.md'), 'utf8'); } catch { /* 无正文 */ }
|
|
1348
|
+
}
|
|
1349
|
+
const meta = idx.episodes.find((e) => e && e.canvasId === cid) || null;
|
|
1350
|
+
if (meta || body != null) {
|
|
1351
|
+
episode = {
|
|
1352
|
+
canvasId: cid,
|
|
1353
|
+
title: meta ? meta.title : '', summary: meta ? meta.summary : '',
|
|
1354
|
+
keywords: meta ? meta.keywords || [] : [], status: meta ? meta.status || 'drafting' : 'drafting',
|
|
1355
|
+
updatedAt: meta ? meta.updatedAt || 0 : 0,
|
|
1356
|
+
body: body == null ? '' : body,
|
|
1357
|
+
};
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
return { ok: true, projectId: id, index: idx, episode };
|
|
1361
|
+
}
|
|
1362
|
+
/** 会话 → 绑定 {projectId, canvasId}:扫**全部项目**(工作区内嵌 + 数据根)的绑定表。 */
|
|
1363
|
+
function toolBindingForSession(sid) {
|
|
1364
|
+
const s = String(sid || '');
|
|
1365
|
+
if (!s) return null;
|
|
1366
|
+
for (const pid of allBoundProjectIds()) {
|
|
1367
|
+
let data = null;
|
|
1368
|
+
try { data = bindingsRead(pid); } catch { continue; }
|
|
1369
|
+
const hit = data.bindings.find((b) => b && b.sessionId === s);
|
|
1370
|
+
if (hit) return { projectId: pid, canvasId: hit.canvasId == null ? null : hit.canvasId };
|
|
1371
|
+
}
|
|
1372
|
+
return null;
|
|
1373
|
+
}
|
|
1374
|
+
/** 可承载绑定的项目 id 全集:工作区内嵌项目 + 数据根项目(绑定可跨来源,菜单列表同口径)。 */
|
|
1375
|
+
function allBoundProjectIds() {
|
|
1376
|
+
const ids = new Set(wsProjects.keys());
|
|
1377
|
+
try { for (const p of projectsListDataRoot()) ids.add(String(p.id)); } catch { /* 无数据根:只留工作区项目 */ }
|
|
1378
|
+
return [...ids];
|
|
1379
|
+
}
|
|
1380
|
+
/** 文档 → 画布清单(默认画布 id=null 在前)。 */
|
|
1381
|
+
function canvasesOfDoc(doc) {
|
|
1382
|
+
const list = defaultCanvasExists(doc) ? [{ id: null, name: defaultCanvasNameOf(doc) }] : [];
|
|
1383
|
+
for (const c of canvasRegistry(doc)) list.push({ id: c.id, name: c.name });
|
|
1384
|
+
return list;
|
|
1385
|
+
}
|
|
1386
|
+
/** 绑定的人类可读标签「项目名·画布名」(拒绝文案用)。 */
|
|
1387
|
+
function bindingLabelOf(b) {
|
|
1388
|
+
try {
|
|
1389
|
+
const doc = readDocOrNull(b.projectId) || {};
|
|
1390
|
+
const cid = b.canvasId == null ? null : b.canvasId;
|
|
1391
|
+
let cname = '默认画布';
|
|
1392
|
+
if (cid != null) {
|
|
1393
|
+
const hit = canvasRegistry(doc).find((c) => c.id === cid);
|
|
1394
|
+
cname = (hit && hit.name) || String(cid);
|
|
1395
|
+
} else if (defaultCanvasExists(doc)) {
|
|
1396
|
+
cname = defaultCanvasNameOf(doc);
|
|
1397
|
+
}
|
|
1398
|
+
return (doc.name || String(b.projectId || '')) + '·' + cname;
|
|
1399
|
+
} catch { return String(b.projectId || ''); }
|
|
1400
|
+
}
|
|
1401
|
+
/** 防御式嗅探工具执行身份:不同宿主版本 exec.agent 携带的会话字段可能不同
|
|
1402
|
+
* (sessionId / session / id;cordis branded id 可能包一层 {value})。拿不到 → null(走显式参数路径)。 */
|
|
1403
|
+
function toolExecSessionId(exec) {
|
|
1404
|
+
try {
|
|
1405
|
+
const a = exec && exec.agent;
|
|
1406
|
+
if (!a || typeof a !== 'object') return null;
|
|
1407
|
+
const candidates = [a.sessionId, a.session, a.id];
|
|
1408
|
+
if (a.ctx && typeof a.ctx === 'object') candidates.push(a.ctx.sessionId, a.ctx.session);
|
|
1409
|
+
for (const v of candidates) {
|
|
1410
|
+
if (typeof v === 'string' && v) return v;
|
|
1411
|
+
if (v && typeof v === 'object' && typeof v.value === 'string' && v.value) return v.value;
|
|
1412
|
+
}
|
|
1413
|
+
} catch { /* 嗅探失败 → null */ }
|
|
1414
|
+
return null;
|
|
1415
|
+
}
|
|
1416
|
+
// ---- 会话↔画布绑定(0.20.x):一会话一画布、一画布一会话 ----
|
|
1417
|
+
// 落位:<项目家目录>/bindings.json:{ version:1, updatedAt, bindings:[{ sessionId, canvasId, boundAt }] }
|
|
1418
|
+
// 占用判定:目标画布已被其他会话绑定时,aliveFn(占用者) 为真 → 拒绝(occupied);为假(会话已删的孤儿)→ 覆盖。
|
|
1419
|
+
/** 读绑定文件;缺失/损坏容错为空。 */
|
|
1420
|
+
function bindingsRead(pid) {
|
|
1421
|
+
const id = String(pid || '');
|
|
1422
|
+
try { projectFile(id); } catch { return { version: 1, updatedAt: 0, bindings: [] }; }
|
|
1423
|
+
const home = projectHomeDir(id);
|
|
1424
|
+
if (!home) return { version: 1, updatedAt: 0, bindings: [] };
|
|
1425
|
+
try {
|
|
1426
|
+
const b = JSON.parse(readFileSync(path.join(home, 'bindings.json'), 'utf8'));
|
|
1427
|
+
if (b && typeof b === 'object' && Array.isArray(b.bindings)) return b;
|
|
1428
|
+
} catch { /* 缺失/损坏 → 空 */ }
|
|
1429
|
+
return { version: 1, updatedAt: 0, bindings: [] };
|
|
1430
|
+
}
|
|
1431
|
+
function writeBindingsAtomic(pid, data) {
|
|
1432
|
+
const home = projectHomeDir(pid);
|
|
1433
|
+
if (!home) return false;
|
|
1434
|
+
try { mkdirSync(home, { recursive: true }); } catch { /* 已存在 */ }
|
|
1435
|
+
const f = path.join(home, 'bindings.json');
|
|
1436
|
+
const tmp = f + '.' + process.pid + '.tmp';
|
|
1437
|
+
writeFileSync(tmp, JSON.stringify(data, null, 1), 'utf8');
|
|
1438
|
+
renameSync(tmp, f);
|
|
1439
|
+
return true;
|
|
1440
|
+
}
|
|
1441
|
+
/** 绑定会话到画布(canvasId=null = 默认画布)。一会话一画布(换绑移除旧条目);一画布一会话。 */
|
|
1442
|
+
function bindingSetSync(pid, sessionId, canvasId, aliveFn) {
|
|
1443
|
+
const id = String(pid || '');
|
|
1444
|
+
const sid = String(sessionId || '').trim();
|
|
1445
|
+
let cid = null;
|
|
1446
|
+
try { cid = normalizeCanvasId(canvasId); } catch { return { ok: false, error: '非法画布 id' }; }
|
|
1447
|
+
if (!id || !sid) return { ok: false, error: '缺少 projectId 或 sessionId' };
|
|
1448
|
+
try { projectFile(id); } catch { return { ok: false, error: '非法项目 id' }; }
|
|
1449
|
+
const projectDoc = readDocOrNull(id);
|
|
1450
|
+
if (!projectDoc) return { ok: false, error: '项目不存在:' + id };
|
|
1451
|
+
if (cid) {
|
|
1452
|
+
if (!canvasRegistry(projectDoc).some((c) => c.id === cid)) return { ok: false, error: '画布不存在:' + cid };
|
|
1453
|
+
} else if (!defaultCanvasExists(projectDoc)) {
|
|
1454
|
+
return { ok: false, error: '默认画布已删除:请指定 canvasId' };
|
|
1455
|
+
}
|
|
1456
|
+
const alive = typeof aliveFn === 'function' ? aliveFn : () => true;
|
|
1457
|
+
const data = bindingsRead(id);
|
|
1458
|
+
const others = data.bindings.filter((b) => b && b.sessionId !== sid);
|
|
1459
|
+
const mine = data.bindings.find((b) => b && b.sessionId === sid);
|
|
1460
|
+
const occupant = others.find((b) => (b.canvasId || null) === cid);
|
|
1461
|
+
if (occupant && alive(occupant.sessionId)) {
|
|
1462
|
+
return { ok: false, occupied: true, by: occupant.sessionId, error: '该画布已绑定其他会话' };
|
|
1463
|
+
}
|
|
1464
|
+
// 会话全局唯一绑定(评审 I3):会话改绑本项目时,清掉它在**其他任何项目**(含数据根)里的绑定——
|
|
1465
|
+
// 「一会话一画布」是全局约束,否则会话感知默认值可能落到错误项目且 agent 无感知。
|
|
1466
|
+
for (const otherPid of allBoundProjectIds()) {
|
|
1467
|
+
if (otherPid === id) continue;
|
|
1468
|
+
let ob = null;
|
|
1469
|
+
try { ob = bindingsRead(otherPid); } catch { continue; }
|
|
1470
|
+
const kept = ob.bindings.filter((b) => b && b.sessionId !== sid);
|
|
1471
|
+
if (kept.length !== ob.bindings.length) {
|
|
1472
|
+
writeBindingsAtomic(otherPid, { ...ob, updatedAt: Date.now(), bindings: kept });
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
const next = {
|
|
1476
|
+
version: 1,
|
|
1477
|
+
updatedAt: Date.now(),
|
|
1478
|
+
bindings: others.filter((b) => b !== occupant).concat([{ sessionId: sid, canvasId: cid, boundAt: Date.now() }]),
|
|
1479
|
+
};
|
|
1480
|
+
writeBindingsAtomic(id, next);
|
|
1481
|
+
return { ok: true, projectId: id, sessionId: sid, canvasId: cid, replaced: !!(mine || occupant) };
|
|
1482
|
+
}
|
|
1483
|
+
/** 异步包装(watcher 用同步核心以准确回报;RPC 走此包装)。 */
|
|
1484
|
+
async function bindingSet(pid, sessionId, canvasId, aliveFn) {
|
|
1485
|
+
return bindingSetSync(pid, sessionId, canvasId, aliveFn);
|
|
1486
|
+
}
|
|
1487
|
+
/** 解绑会话(幂等:无绑定返回 removed=false)。显式解绑即持久——watcher 只发现不绑定,不会绑回。 */
|
|
1488
|
+
async function bindingClear(pid, sessionId) {
|
|
1489
|
+
const id = String(pid || '');
|
|
1490
|
+
const sid = String(sessionId || '').trim();
|
|
1491
|
+
if (!id || !sid) return { ok: false, error: '缺少 projectId 或 sessionId' };
|
|
1492
|
+
const data = bindingsRead(id);
|
|
1493
|
+
const kept = data.bindings.filter((b) => b && b.sessionId !== sid);
|
|
1494
|
+
const removed = kept.length < data.bindings.length;
|
|
1495
|
+
if (removed) writeBindingsAtomic(id, { version: 1, updatedAt: Date.now(), bindings: kept });
|
|
1496
|
+
return { ok: true, removed };
|
|
1497
|
+
}
|
|
1119
1498
|
// ---- 默认画布(canvasId=null):名字存项目文档 defaultCanvasName;删除后 defaultCanvasDeleted=true ----
|
|
1120
1499
|
const DEFAULT_CANVAS_NAME = '默认画布';
|
|
1121
1500
|
/** 默认画布名:缺省 '默认画布'(旧项目无该字段 → 零迁移)。 */
|
|
@@ -1134,7 +1513,7 @@ function allCanvasNames(projectDoc) {
|
|
|
1134
1513
|
const names = defaultCanvasExists(projectDoc) ? [defaultCanvasNameOf(projectDoc)] : [];
|
|
1135
1514
|
return names.concat(canvasRegistry(projectDoc).map((c) => c.name));
|
|
1136
1515
|
}
|
|
1137
|
-
function
|
|
1516
|
+
function projectsListDataRoot() {
|
|
1138
1517
|
if (sqlActive()) {
|
|
1139
1518
|
const db = getDb();
|
|
1140
1519
|
const rows = db.prepare('SELECT id, name, created_at, updated_at, bible_updated_at, summary, tombstones FROM projects ORDER BY updated_at DESC').all()
|
|
@@ -1181,6 +1560,11 @@ function projectsList() {
|
|
|
1181
1560
|
}
|
|
1182
1561
|
return list.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
|
1183
1562
|
}
|
|
1563
|
+
/** 项目总列表 = 工作区内嵌项目 + 数据根项目,按更新时间合并排序(工作区缓存由 wsProjectsScan 刷新)。 */
|
|
1564
|
+
function projectsList() {
|
|
1565
|
+
const ws = [...wsProjects.values()].map(wsProjectListEntry);
|
|
1566
|
+
return ws.concat(projectsListDataRoot()).sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
|
1567
|
+
}
|
|
1184
1568
|
async function projectsPut(args) {
|
|
1185
1569
|
const id = String((args && args.id) || '');
|
|
1186
1570
|
// 项目删除墓碑(长效):删除后迟到的全量推送(450ms 防抖竞速 / 启动 pushAllProjectsToHost 快照)
|
|
@@ -1462,7 +1846,11 @@ function setDataRoot(raw) {
|
|
|
1462
1846
|
async function projectsDelete(args) {
|
|
1463
1847
|
const id = String((args && args.id) || '');
|
|
1464
1848
|
let cleanup = null;
|
|
1465
|
-
if (
|
|
1849
|
+
if (isWsProject(id)) {
|
|
1850
|
+
// 工作区内嵌项目:删 .infinite-canvas 整目录(工作区目录本身不动),并清数据根媒体文件夹
|
|
1851
|
+
cleanup = { ws: wsProjectRemove(id) };
|
|
1852
|
+
try { removeDataRootProject(id); } catch { /* 媒体清理失败不影响删除 */ }
|
|
1853
|
+
} else if (sqlActive()) {
|
|
1466
1854
|
// BLK-01:行 + FTS + 资产文件 + 镜像目录,一处收口(与 canvasDeleteProject 共用同一实现)
|
|
1467
1855
|
cleanup = sqlDeleteProjectRows(getDb(), id, dataRoot());
|
|
1468
1856
|
} else {
|
|
@@ -1839,30 +2227,35 @@ function canvasWriteNode(args) {
|
|
|
1839
2227
|
}
|
|
1840
2228
|
/** 读取项目文档:把"文件不存在/内容损坏"变成用户和模型都读得懂的报错(不泄漏绝对路径)。 */
|
|
1841
2229
|
function readDoc(id) {
|
|
1842
|
-
|
|
1843
|
-
|
|
1844
|
-
if (!doc) throw new Error('项目不存在:' + id + '(先用 canvas_list_projects 查看可用项目 id)');
|
|
2230
|
+
const doc = readDocOrNull(id);
|
|
2231
|
+
if (doc) {
|
|
1845
2232
|
// 旧项目兼容:读入即归一旧节点类型(image-gen/image-asset → image,video-gen/video-asset → video)
|
|
1846
2233
|
return normalizeDocNodes(doc);
|
|
1847
2234
|
}
|
|
1848
|
-
|
|
1849
|
-
|
|
1850
|
-
try {
|
|
1851
|
-
raw = readFileSync(f, 'utf8');
|
|
1852
|
-
} catch {
|
|
1853
|
-
throw new Error('项目不存在:' + id + '(先用 canvas_list_projects 查看可用项目 id)');
|
|
1854
|
-
}
|
|
1855
|
-
try {
|
|
1856
|
-
return normalizeDocNodes(JSON.parse(raw));
|
|
1857
|
-
} catch {
|
|
2235
|
+
// 文件模式区分「不存在」与「损坏」(损坏给重建提示);SQL/工作区侧统一按不存在处理
|
|
2236
|
+
if (!sqlActive() && !wsDocFile(id) && existsSync(projectFile(id))) {
|
|
1858
2237
|
throw new Error('项目文件损坏,无法解析:' + id + '(可考虑重建该项目)');
|
|
1859
2238
|
}
|
|
2239
|
+
throw new Error('项目不存在:' + id + '(先用 canvas_list_projects 查看可用项目 id)');
|
|
1860
2240
|
}
|
|
1861
2241
|
/** 原子写项目/画布文档:SQL 模式走单行事务;文件模式先写临时文件再改名,避免半写导致项目"消失"。
|
|
1862
2242
|
* 子画布文档(id 含 __cv__)不重复登记项目文件夹、不镜像 project.json——项目级 meta 只属于默认画布行。 */
|
|
1863
2243
|
function writeIcDoc(id, doc) {
|
|
1864
2244
|
const canvasRef = splitCanvasDocId(id);
|
|
1865
2245
|
const isCanvas = isCanvasDocId(id);
|
|
2246
|
+
// 工作区内嵌项目:文档直接落 <ws>/.infinite-canvas/(原子写);不进 SQLite、不镜像数据根。
|
|
2247
|
+
// 项目级文档顺带在数据根登记媒体文件夹(媒体仍走数据根管线),失败不阻塞。
|
|
2248
|
+
const wsf = wsDocFile(id);
|
|
2249
|
+
if (wsf) {
|
|
2250
|
+
try { mkdirSync(path.dirname(wsf), { recursive: true }); } catch { /* 目录已存在 */ }
|
|
2251
|
+
const tmp = wsf + '.' + process.pid + '.tmp';
|
|
2252
|
+
writeFileSync(tmp, JSON.stringify(doc, null, 1), 'utf8');
|
|
2253
|
+
renameSync(tmp, wsf);
|
|
2254
|
+
if (!isCanvas) {
|
|
2255
|
+
try { ensureProjectFolder(canvasRef.projectId, (doc && doc.name) || canvasRef.projectId); } catch { /* 媒体文件夹登记失败不阻塞文档 */ }
|
|
2256
|
+
}
|
|
2257
|
+
return;
|
|
2258
|
+
}
|
|
1866
2259
|
if (sqlActive()) {
|
|
1867
2260
|
const db = getDb();
|
|
1868
2261
|
db.prepare(`INSERT INTO projects (id, name, created_at, updated_at, bible_updated_at, summary, tombstones, doc)
|
|
@@ -1961,6 +2354,18 @@ function deleteCanvasDocsForProject(projectId) {
|
|
|
1961
2354
|
const pid = String(projectId || '');
|
|
1962
2355
|
if (!pid) return 0;
|
|
1963
2356
|
let removed = 0;
|
|
2357
|
+
// 工作区内嵌项目:清 <home>/canvases/ 目录
|
|
2358
|
+
const home = wsProjectHome(pid);
|
|
2359
|
+
if (home) {
|
|
2360
|
+
const dir = path.join(home, 'canvases');
|
|
2361
|
+
let files = [];
|
|
2362
|
+
try { files = readdirSync(dir); } catch { return 0; }
|
|
2363
|
+
for (const f of files) {
|
|
2364
|
+
if (!f.endsWith('.json')) continue;
|
|
2365
|
+
try { unlinkSync(path.join(dir, f)); removed++; } catch { /* 文件占用/已删 */ }
|
|
2366
|
+
}
|
|
2367
|
+
return removed;
|
|
2368
|
+
}
|
|
1964
2369
|
if (sqlActive()) {
|
|
1965
2370
|
try {
|
|
1966
2371
|
const db = getDb();
|
|
@@ -2040,6 +2445,8 @@ async function canvasUpdateBible(args) {
|
|
|
2040
2445
|
} catch { /* 重算失败不影响设定集写入 */ }
|
|
2041
2446
|
writeIcDoc(id, doc);
|
|
2042
2447
|
markDocChanged(id);
|
|
2448
|
+
// 阶段机:设定集落盘 → 本画布阶段 ≥ bible(只抬高,不回退)
|
|
2449
|
+
try { PROD.noteStage(id, toolCanvasId(args), 'bible', 'update_bible'); } catch { /* 阶段机故障不阻塞主流程 */ }
|
|
2043
2450
|
return { projectId: id, bible: doc.bible, bibleUpdatedAt: doc.bibleUpdatedAt };
|
|
2044
2451
|
}
|
|
2045
2452
|
/** 通用建节点(供对话建角色/场景/道具参考图等);支持 script/text/image/video/storyboard/finalcut。
|
|
@@ -2056,6 +2463,11 @@ function canvasCreateNode(args) {
|
|
|
2056
2463
|
const label = args && args.name ? String(args.name).slice(0, 40) : '';
|
|
2057
2464
|
const prompt = String((args && args.prompt) || '');
|
|
2058
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
|
+
}
|
|
2059
2471
|
// 媒体节点:空态按「预览区比例 + 标题栏」给外框(没有操作栏就不加 NODE_FOOT_H),
|
|
2060
2472
|
// 布点时用真实外框做碰撞检测,避免按 360×360 估小后与同列邻居重叠。
|
|
2061
2473
|
const mediaSize = (type === 'image' || type === 'video')
|
|
@@ -2064,6 +2476,7 @@ function canvasCreateNode(args) {
|
|
|
2064
2476
|
const pos = nextNodePos(doc, type, connectFrom, mediaSize);
|
|
2065
2477
|
let connected = null;
|
|
2066
2478
|
let autoConnected = null;
|
|
2479
|
+
let shotsGatePass = false; // 目标分镜表 shots 已过质量闸门(建点成功后据此抬升 shots_ready)
|
|
2067
2480
|
let node;
|
|
2068
2481
|
if (type === 'image') {
|
|
2069
2482
|
node = agentNode('text', '', pos.x, pos.y, label || '图片节点');
|
|
@@ -2088,6 +2501,30 @@ function canvasCreateNode(args) {
|
|
|
2088
2501
|
} else if (!hasPrompt && sbEmpty) {
|
|
2089
2502
|
autoConnectId = sbEmpty.id; // 分镜表存在但 shots 为空:先连线占位(生成前需先拆解镜头)
|
|
2090
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
|
+
}
|
|
2091
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' };
|
|
2092
2529
|
autoConnected = autoConnectId ? { from: autoConnectId, ignoredPrompt: forced && hasPrompt, emptyShots: !sbWithShots && !!sbEmpty } : null;
|
|
2093
2530
|
} else if (type === 'storyboard') {
|
|
@@ -2129,6 +2566,13 @@ function canvasCreateNode(args) {
|
|
|
2129
2566
|
}
|
|
2130
2567
|
doc.updatedAt = Date.now();
|
|
2131
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 { /* 阶段机故障不阻塞建点 */ }
|
|
2132
2576
|
const note = autoConnected && autoConnected.ignoredPrompt
|
|
2133
2577
|
? (type === 'video'
|
|
2134
2578
|
? '⚠️ 已强制连线到分镜表(多镜头工作流:一个分镜表 = 一个完整视频,镜头清单从分镜表读取),传入的 prompt 已忽略——不要手写视频提示词绕过分镜表。'
|
|
@@ -2151,8 +2595,11 @@ function canvasRelayout(args) {
|
|
|
2151
2595
|
const id = String((args && args.projectId) || '');
|
|
2152
2596
|
const canvasId = toolCanvasId(args);
|
|
2153
2597
|
const doc = readToolDoc(args);
|
|
2154
|
-
const
|
|
2155
|
-
|
|
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 };
|
|
2156
2603
|
const VERT = new Set(['prev', 'frame']);
|
|
2157
2604
|
const byId = new Map(nodes.map((n) => [n.id, n]));
|
|
2158
2605
|
const depth = new Map(nodes.map((n) => [n.id, 0]));
|
|
@@ -2189,19 +2636,160 @@ function canvasRelayout(args) {
|
|
|
2189
2636
|
const colX = new Map();
|
|
2190
2637
|
let cx = 80;
|
|
2191
2638
|
for (const d of [...colW.keys()].sort((a, b) => a - b)) { colX.set(d, cx); cx += (colW.get(d) || 280) + 60; }
|
|
2192
|
-
|
|
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;
|
|
2193
2648
|
let moved = 0;
|
|
2194
2649
|
for (const row of rowList) {
|
|
2195
|
-
const
|
|
2196
|
-
|
|
2197
|
-
|
|
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);
|
|
2696
|
+
}
|
|
2697
|
+
doc.updatedAt = Date.now();
|
|
2698
|
+
writeToolDoc(args, doc);
|
|
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);
|
|
2198
2780
|
}
|
|
2199
2781
|
doc.updatedAt = Date.now();
|
|
2200
2782
|
writeToolDoc(args, doc);
|
|
2201
|
-
return { ok: true, projectId:
|
|
2783
|
+
return { ok: true, projectId: pid, ...(canvasId ? { canvasId } : {}), applied, moved: applied.length };
|
|
2202
2784
|
}
|
|
2203
2785
|
async function canvasDeleteProject(args) {
|
|
2204
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 { /* 审计失败不阻塞 */ }
|
|
2205
2793
|
let name = id;
|
|
2206
2794
|
const prevDoc = readDocOrNull(id);
|
|
2207
2795
|
if (prevDoc && prevDoc.name) name = prevDoc.name;
|
|
@@ -2231,6 +2819,12 @@ async function canvasDeleteNode(args) {
|
|
|
2231
2819
|
const id = String((args && args.projectId) || '');
|
|
2232
2820
|
const nodeId = String((args && args.nodeId) || '');
|
|
2233
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 { /* 审计失败不阻塞 */ }
|
|
2234
2828
|
const doc = readToolDoc(args);
|
|
2235
2829
|
if (!doc.nodes[nodeId]) throw new Error('节点不存在: ' + nodeId);
|
|
2236
2830
|
delete doc.nodes[nodeId];
|
|
@@ -2249,9 +2843,43 @@ async function canvasRunNode(args) {
|
|
|
2249
2843
|
const doc = readToolDoc(args);
|
|
2250
2844
|
const node = doc.nodes[nodeId];
|
|
2251
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
|
+
}
|
|
2252
2878
|
const cfg = readIcConfig();
|
|
2253
2879
|
cfg.ui = { ...(cfg.ui || {}), runRequest: { projectId: pid, canvasId, nodeId, at: Date.now() } };
|
|
2254
2880
|
writeIcConfig(cfg);
|
|
2881
|
+
// 阶段机:视频触发 → ≥ generating
|
|
2882
|
+
try { if (node.type === 'video') PROD.noteStage(pid, canvasId, 'generating', 'video_run'); } catch { /* 忽略 */ }
|
|
2255
2883
|
return { ok: true, projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, type: node.type, label: (node.data && node.data.label) || '' };
|
|
2256
2884
|
}
|
|
2257
2885
|
/** 读取节点运行状态与产物(画布执行完成后会把结果推回 Host 文档)。 */
|
|
@@ -2354,10 +2982,29 @@ async function canvasNodeStatus(args) {
|
|
|
2354
2982
|
}))
|
|
2355
2983
|
: undefined;
|
|
2356
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 { /* 阶段机故障不影响状态读取 */ }
|
|
2357
3001
|
return {
|
|
2358
3002
|
projectId: pid, ...(canvasId ? { canvasId } : {}), nodeId, type: n.type, label: d.label || '',
|
|
2359
3003
|
status: d.status || 'idle',
|
|
2360
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,
|
|
2361
3008
|
// 布局事实:坐标与外框尺寸只读透出(改布局走 canvas_relayout;canvas_update_node 仍禁改结构字段)
|
|
2362
3009
|
x: Number(n.x) || 0,
|
|
2363
3010
|
y: Number(n.y) || 0,
|
|
@@ -2486,6 +3133,8 @@ async function canvasGenerateNode(args) {
|
|
|
2486
3133
|
const baseline = await canvasNodeStatus({ projectId: pid, canvasId, nodeId }).catch(() => null);
|
|
2487
3134
|
const baseUpdatedAt = Number(baseline && baseline.docUpdatedAt) || 0;
|
|
2488
3135
|
const run = await canvasRunNode({ projectId: pid, canvasId, nodeId });
|
|
3136
|
+
// 闸门拒绝(G1/G2/G6)原样透传:调用方拿到 gate/fails/fix 结构化字段
|
|
3137
|
+
if (run && run.ok === false) return run;
|
|
2489
3138
|
if (!waitSec) {
|
|
2490
3139
|
return { ok: true, triggered: true, finished: false, projectId: pid, nodeId, type: run.type, label: run.label, status: 'running', note: '已触发执行;画布需处于打开状态才会真正执行,可用 canvas_node_status 查询进度' };
|
|
2491
3140
|
}
|
|
@@ -2932,7 +3581,9 @@ async function updateInstall() {
|
|
|
2932
3581
|
export const inject = ['webServer', 'tools'];
|
|
2933
3582
|
|
|
2934
3583
|
// 仅供诊断 / 自动化测试(不属于 RPC 面,运行时行为不受影响)
|
|
2935
|
-
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, 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 };
|
|
2936
3587
|
|
|
2937
3588
|
function resolveModel(providers, want) {
|
|
2938
3589
|
const byProvider = want && want.provider
|
|
@@ -3093,6 +3744,233 @@ export function apply(ctx) {
|
|
|
3093
3744
|
return _directorEngine;
|
|
3094
3745
|
};
|
|
3095
3746
|
|
|
3747
|
+
// ---- 会话↔画布绑定:会话所在工作区解析(ctx 闭包内:需要 workspaceRegistry 服务)----
|
|
3748
|
+
/** 解析 sessionId 所在工作区与活会话判定;老宿主无 workspaceRegistry → supported:false(全链降级)。 */
|
|
3749
|
+
const wsSessionContext = (sessionId) => {
|
|
3750
|
+
let reg = null;
|
|
3751
|
+
try { reg = ctx.get && ctx.get('workspaceRegistry'); } catch { reg = null; }
|
|
3752
|
+
const list = reg && typeof reg.list === 'function' ? reg.list() : null;
|
|
3753
|
+
if (!Array.isArray(list)) return { supported: false, list: null, ws: null, isAlive: () => true };
|
|
3754
|
+
const sid = String(sessionId || '');
|
|
3755
|
+
const ws = list.find((w) => w && Array.isArray(w.sessionIds) && w.sessionIds.map(String).includes(sid)) || null;
|
|
3756
|
+
const isAlive = (t) => list.some((w) => w && Array.isArray(w.sessionIds) && w.sessionIds.map(String).includes(String(t)));
|
|
3757
|
+
return { supported: true, list, ws, isAlive };
|
|
3758
|
+
};
|
|
3759
|
+
/** 工作区注册表条目的对外视图(不泄漏内部字段)。 */
|
|
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
|
+
const dec = await autoRoomStep(run, '监制', BASE + '\n你是监制。择一或融合,给出决策与理由,并把世界观/风格/角色/场景/道具写成设定集草案(描述要可生成:年龄/发型/服装/材质/光线)。',
|
|
3863
|
+
ctxUser + '\nA案:' + JSON.stringify(pitchA).slice(0, 800) + '\nB案:' + JSON.stringify(pitchB).slice(0, 800) + '\n互评:' + JSON.stringify(crit).slice(0, 800) +
|
|
3864
|
+
'\n输出 {"decision":"A|B|merge","rationale":"…","logline":"…","beats":["…"],"scriptIdea":"(写给剧本节点的创作提示词,含两条叙事硬约束:每场结尾因果钩子、每场至少一个冲突点)","bible":{"worldview":"…","style":"…","characters":[{"name":"…","desc":"…"}],"scenes":[{"name":"…","desc":"…"}],"props":[{"name":"…","desc":"…"}]}}', true);
|
|
3865
|
+
// ⑤ 落盘:讨论记录节点 + 设定集 + 剧本 idea
|
|
3866
|
+
run.phase = 'writeback';
|
|
3867
|
+
const transcript = [
|
|
3868
|
+
'用户 brief:' + brief,
|
|
3869
|
+
'调研(离线):' + JSON.stringify(research),
|
|
3870
|
+
'编剧A提案:' + JSON.stringify(pitchA),
|
|
3871
|
+
'编剧B提案:' + JSON.stringify(pitchB),
|
|
3872
|
+
'互评:' + JSON.stringify(crit),
|
|
3873
|
+
'监制决策:' + dec.decision + '——' + (dec.rationale || ''),
|
|
3874
|
+
'定稿 logline:' + (dec.logline || ''),
|
|
3875
|
+
].join('\n\n');
|
|
3876
|
+
const meet = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'text', name: '编剧室会议' });
|
|
3877
|
+
canvasWriteNode({ projectId: pid, canvasId: cid, nodeId: meet.nodeId, target: 'output', text: transcript.slice(0, 60000), overwrite: true });
|
|
3878
|
+
const bi = dec.bible || {};
|
|
3879
|
+
await canvasUpdateBible({ projectId: pid, bible: bi });
|
|
3880
|
+
// scriptIdea 兼容两处:监制按指示写在根级,写歪时落到 bible 里(模型照抄示例的结构错误要容忍)
|
|
3881
|
+
const idea = String(dec.scriptIdea || bi.scriptIdea || dec.logline || brief).slice(0, 4000);
|
|
3882
|
+
const sc = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'script', name: '第1节剧本', prompt: idea });
|
|
3883
|
+
// ⑥ 剧本自动生成 → 按场拆分 → 逐场分镜表(tail→prev 串联)→ 生成 → G2 校验
|
|
3884
|
+
run.phase = 'script';
|
|
3885
|
+
const st = await canvasExec(pid, cid, sc.nodeId, { timeoutMs: 10 * 60 * 1000 });
|
|
3886
|
+
const scenes = splitScenes(st.output);
|
|
3887
|
+
const boards = [];
|
|
3888
|
+
let prevBoard = null;
|
|
3889
|
+
for (let i = 0; i < scenes.length; i++) {
|
|
3890
|
+
run.phase = 'boards ' + (i + 1) + '/' + scenes.length;
|
|
3891
|
+
const txt = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'text', name: '场' + scenes[i].no + '文本' });
|
|
3892
|
+
canvasWriteNode({ projectId: pid, canvasId: cid, nodeId: txt.nodeId, target: 'output', text: scenes[i].text, overwrite: true });
|
|
3893
|
+
const sb = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'storyboard', name: '场' + scenes[i].no + '分镜表', connectFrom: txt.nodeId });
|
|
3894
|
+
if (prevBoard) { try { canvasConnect({ projectId: pid, canvasId: cid, fromNode: prevBoard, toNode: sb.nodeId, fromPort: 'tail', toPort: 'prev' }); } catch { /* 端口异常不阻塞 */ } }
|
|
3895
|
+
prevBoard = sb.nodeId;
|
|
3896
|
+
let sbSt = await canvasExec(pid, cid, sb.nodeId, { timeoutMs: 10 * 60 * 1000 });
|
|
3897
|
+
let gate = PROD.gateStoryboard(sbSt.shots);
|
|
3898
|
+
if (!gate.ok) { // 不过闸自动重生成一次(分镜重生成不花钱)
|
|
3899
|
+
run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' G2 未过,自动重生成:' + gate.fails.slice(0, 2).join(';') });
|
|
3900
|
+
sbSt = await canvasExec(pid, cid, sb.nodeId, { timeoutMs: 10 * 60 * 1000 });
|
|
3901
|
+
gate = PROD.gateStoryboard(sbSt.shots);
|
|
3902
|
+
}
|
|
3903
|
+
boards.push({ no: scenes[i].no, storyboardId: sb.nodeId, gate: gate.ok, fails: gate.fails });
|
|
3904
|
+
run.log.push({ at: Date.now(), role: 'runner', summary: '场' + scenes[i].no + ' 分镜:' + (gate.ok ? '过闸' : '仍有 ' + gate.fails.length + ' 项') });
|
|
3905
|
+
}
|
|
3906
|
+
// ⑦ 预算单(免费段终点)
|
|
3907
|
+
const cfg = readIcConfig();
|
|
3908
|
+
const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
|
|
3909
|
+
run.budget = PROD.quote(pid, cid, price);
|
|
3910
|
+
run.boards = boards;
|
|
3911
|
+
run.meetingNodeId = meet.nodeId;
|
|
3912
|
+
run.scriptNodeId = sc.nodeId;
|
|
3913
|
+
run.status = 'done';
|
|
3914
|
+
run.phase = 'budget';
|
|
3915
|
+
run.log.push({ at: Date.now(), role: 'runner', summary: '免费段完成:' + scenes.length + ' 场分镜 + 预算单(' + run.budget.videoCalls + ' 次视频调用 / ' + run.budget.totalSeconds + ' 秒)' });
|
|
3916
|
+
} catch (e) {
|
|
3917
|
+
run.status = String((e && e.message) || e) === 'aborted' ? 'aborted' : 'failed';
|
|
3918
|
+
run.error = String((e && e.message) || e);
|
|
3919
|
+
run.log.push({ at: Date.now(), role: 'runner', summary: '失败:' + run.error });
|
|
3920
|
+
}
|
|
3921
|
+
}
|
|
3922
|
+
/** 付费段 v1:批准后逐分镜表建视频节点 → 生成 → 轮询(失败重试 2 次)→ 成片节点。 */
|
|
3923
|
+
async function autoPaid(pid, cid) {
|
|
3924
|
+
const cfg = readIcConfig();
|
|
3925
|
+
const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
|
|
3926
|
+
const ap = PROD.approvalOf(pid, cid, price);
|
|
3927
|
+
if (!ap || !ap.valid) return { ok: false, error: '没有有效的付费批准:先用 canvas_auto_budget 生成预算单,用户批准后重试' };
|
|
3928
|
+
const run = AUTO_RUNS.get(runKeyOf(pid, cid));
|
|
3929
|
+
if (!run || run.status !== 'done') return { ok: false, error: '免费段尚未完成(没有分镜与预算)' };
|
|
3930
|
+
if (run.paid === 'running') return { ok: false, error: '付费段已在运行' };
|
|
3931
|
+
run.paid = 'running';
|
|
3932
|
+
run.paidAbort = false;
|
|
3933
|
+
run.paidLog = [{ at: Date.now(), text: '付费段启动(已批准预算 ' + ap.quoteId + ')' }];
|
|
3934
|
+
(async () => {
|
|
3935
|
+
try {
|
|
3936
|
+
const doc = readToolDoc({ projectId: pid, canvasId: cid });
|
|
3937
|
+
const boards = Object.values(doc.nodes || {}).filter((n) => n.type === 'storyboard' && Array.isArray(n.data && n.data.shots) && n.data.shots.length);
|
|
3938
|
+
let lastVideo = null;
|
|
3939
|
+
for (let i = 0; i < boards.length; i++) {
|
|
3940
|
+
if (run.paidAbort) { run.paid = 'aborted'; run.paidPhase = 'aborted'; run.paidLog.push({ at: Date.now(), text: '已中止(保留已完成视频)' }); return; }
|
|
3941
|
+
const sb = boards[i];
|
|
3942
|
+
run.paidPhase = 'video ' + (i + 1) + '/' + boards.length;
|
|
3943
|
+
const hasVideo = (doc.edges || []).some((e) => e.fromNode === sb.id && doc.nodes[e.toNode] && doc.nodes[e.toNode].type === 'video');
|
|
3944
|
+
if (hasVideo) continue;
|
|
3945
|
+
const label = String((sb.data && sb.data.label) || ('场' + (i + 1))).replace(/分镜表$/, '') + '视频';
|
|
3946
|
+
const v = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'video', name: label.slice(0, 40), connectFrom: sb.id });
|
|
3947
|
+
if (v && v.ok === false) throw new Error('[' + v.gate + '] ' + v.error);
|
|
3948
|
+
let done = false; let err = null;
|
|
3949
|
+
for (let attempt = 0; attempt < 2 && !done; attempt++) {
|
|
3950
|
+
if (attempt > 0 && run.paidAbort) { run.paid = 'aborted'; run.paidPhase = 'aborted'; run.paidLog.push({ at: Date.now(), text: '已中止(保留已完成视频)' }); return; }
|
|
3951
|
+
try { await canvasExec(pid, cid, v.nodeId, { timeoutMs: 15 * 60 * 1000 }); done = true; }
|
|
3952
|
+
catch (e) { err = e; run.paidLog.push({ at: Date.now(), text: label + ' 第 ' + (attempt + 1) + ' 次失败:' + String((e && e.message) || e) }); }
|
|
3953
|
+
}
|
|
3954
|
+
if (!done) throw err;
|
|
3955
|
+
lastVideo = v.nodeId;
|
|
3956
|
+
run.paidLog.push({ at: Date.now(), text: label + ' 完成' });
|
|
3957
|
+
}
|
|
3958
|
+
if (lastVideo) {
|
|
3959
|
+
const fc = canvasCreateNode({ projectId: pid, canvasId: cid, type: 'finalcut', name: '成片', connectFrom: lastVideo });
|
|
3960
|
+
if (fc && fc.nodeId) run.finalcutNodeId = fc.nodeId;
|
|
3961
|
+
}
|
|
3962
|
+
run.paid = 'done'; run.paidPhase = 'done';
|
|
3963
|
+
run.paidLog.push({ at: Date.now(), text: lastVideo ? '全部视频完成,已建成片节点' : '没有待生成的视频' });
|
|
3964
|
+
} catch (e) {
|
|
3965
|
+
run.paid = 'failed'; run.paidError = String((e && e.message) || e);
|
|
3966
|
+
}
|
|
3967
|
+
})();
|
|
3968
|
+
return { ok: true, status: 'running', quoteId: ap.quoteId };
|
|
3969
|
+
}
|
|
3970
|
+
__autoApi.runs = AUTO_RUNS;
|
|
3971
|
+
__autoApi.setRoomLlm = (fn) => { roomLlm = fn; };
|
|
3972
|
+
__autoApi.setCanvasRunner = (fn) => { canvasExec = fn; };
|
|
3973
|
+
|
|
3096
3974
|
const methods = {
|
|
3097
3975
|
async ping() { return { ok: true, version: VERSION }; },
|
|
3098
3976
|
async llmOptions() { return listLlmOptions(); },
|
|
@@ -3393,10 +4271,292 @@ export function apply(ctx) {
|
|
|
3393
4271
|
text: String(text ?? ((def && typeof def === 'object') ? JSON.stringify(def) : '')).slice(0, 80000),
|
|
3394
4272
|
};
|
|
3395
4273
|
},
|
|
4274
|
+
// ---- 会话↔画布绑定 RPC(0.20.x):composer 画布选择器与画布面板跟随的数据面 ----
|
|
4275
|
+
/** 绑定能力探针:客户端用它识别「宿主进程仍是旧版」(旧宿主无此方法 → 返回 400 → 客户端提示重启)。 */
|
|
4276
|
+
async bindingCapabilities() {
|
|
4277
|
+
return { ok: true, rev: 2, anyProject: true };
|
|
4278
|
+
},
|
|
4279
|
+
// ---- 制作阶段机 RPC(0.20.0):阶段/闸门/汇报语义的数据面 ----
|
|
4280
|
+
/** 制作能力探针(M0):stageMachine/qualityGate 恒真;multiAgent = 宿主是否暴露会话服务
|
|
4281
|
+
* (sessionController/agents,懒探测不加 inject——与 workspaceRegistry 同一安全模式)。
|
|
4282
|
+
* multiAgent:false 时客户端隐藏「自动创作」入口,auto* RPC 一律拒绝。 */
|
|
4283
|
+
async productionCapabilities() {
|
|
4284
|
+
const svc = (name) => { try { return !!(ctx.get && ctx.get(name)); } catch { return false; } };
|
|
4285
|
+
const multiAgent = svc('sessionController') || svc('agents');
|
|
4286
|
+
return { ok: true, rev: 1, stageMachine: true, qualityGate: true, multiAgent, autoMode: multiAgent, version: VERSION, stages: PRODUCTION_STAGES };
|
|
4287
|
+
},
|
|
4288
|
+
/** 制作状态汇报:模型宣称"完成/可交付"前必须以 ready:true 为据;next 给当前阶段的下一步。 */
|
|
4289
|
+
async productionStatus(args) {
|
|
4290
|
+
const pid = String((args && args.projectId) || '');
|
|
4291
|
+
if (!pid) return { ok: false, error: '缺少 projectId' };
|
|
4292
|
+
try { projectFile(pid); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
|
|
4293
|
+
return PROD.status(pid, toolCanvasId(args));
|
|
4294
|
+
},
|
|
4295
|
+
/** 显式推进/回退(返工):必须带 reason(审计);回退会下调 floor,随后按工具事件重新抬升。 */
|
|
4296
|
+
async productionAdvance(args) {
|
|
4297
|
+
const pid = String((args && args.projectId) || '');
|
|
4298
|
+
if (!pid) return { ok: false, error: '缺少 projectId' };
|
|
4299
|
+
try { projectFile(pid); } catch (e) { return { ok: false, error: String((e && e.message) || e) }; }
|
|
4300
|
+
return PROD.advance(pid, toolCanvasId(args), String((args && args.to) || ''), String((args && args.reason) || ''), 'user');
|
|
4301
|
+
},
|
|
4302
|
+
// ---- 自动创作(实验,A1 两段式):开关默认关;关闭时所有 auto* 一律拒绝 ----
|
|
4303
|
+
/** 开关状态 + 能力(multiAgent 取决于宿主是否暴露会话服务,M0 探针)。 */
|
|
4304
|
+
async autoModeGet() {
|
|
4305
|
+
const cfg = readIcConfig();
|
|
4306
|
+
const enabled = !!(cfg.ui && cfg.ui.autoMode);
|
|
4307
|
+
return { ok: true, enabled, caps: await methods.productionCapabilities() };
|
|
4308
|
+
},
|
|
4309
|
+
/** 打开/关闭自动创作。默认关闭;打开只是"允许入口",不启动任何创作、不花钱。 */
|
|
4310
|
+
async autoModeSet(args) {
|
|
4311
|
+
const enabled = !!(args && args.enabled);
|
|
4312
|
+
const cfg = readIcConfig();
|
|
4313
|
+
cfg.ui = { ...(cfg.ui || {}), autoMode: enabled };
|
|
4314
|
+
writeIcConfig(cfg);
|
|
4315
|
+
return { ok: true, enabled };
|
|
4316
|
+
},
|
|
4317
|
+
/** 预算单(免费段终点):场/镜/秒数/视频调用次数(+配置了单价时的估算金额)。 */
|
|
4318
|
+
async autoQuote(args) {
|
|
4319
|
+
if (!autoEnabled()) return autoDisabled();
|
|
4320
|
+
const pid = String((args && args.projectId) || '');
|
|
4321
|
+
if (!pid) return { ok: false, error: '缺少 projectId' };
|
|
4322
|
+
const cfg = readIcConfig();
|
|
4323
|
+
const price = Number(args && args.unitPricePerSecond);
|
|
4324
|
+
const configured = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
|
|
4325
|
+
return PROD.quote(pid, toolCanvasId(args), Number.isFinite(price) && price > 0 ? price : configured);
|
|
4326
|
+
},
|
|
4327
|
+
/** 批准付费段:一次性令牌,绑定预算指纹;镜头/时长一变即失效(须重新复核)。 */
|
|
4328
|
+
async autoApprove(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(cfg.production && cfg.production.videoUnitPricePerSecond);
|
|
4334
|
+
return PROD.approve(pid, toolCanvasId(args), String((args && args.quoteId) || ''), String((args && args.confirm) || ''), price);
|
|
4335
|
+
},
|
|
4336
|
+
/** 付费段:批准后逐分镜表生成视频(真实计费);失败重试,全部完成建成片节点。 */
|
|
4337
|
+
async autoGenerate(args) {
|
|
4338
|
+
if (!autoEnabled()) return autoDisabled();
|
|
4339
|
+
const pid = String((args && args.projectId) || '');
|
|
4340
|
+
if (!pid) return { ok: false, error: '缺少 projectId' };
|
|
4341
|
+
return autoPaid(pid, toolCanvasId(args));
|
|
4342
|
+
},
|
|
4343
|
+
/** 自动创作总状态:开关 / 阶段 / 当前批准是否仍有效 / 编剧室运行状态 / 下一步。 */
|
|
4344
|
+
async autoStatus(args) {
|
|
4345
|
+
const cfg = readIcConfig();
|
|
4346
|
+
const enabled = !!(cfg.ui && cfg.ui.autoMode);
|
|
4347
|
+
const caps = await methods.productionCapabilities();
|
|
4348
|
+
const pid = String((args && args.projectId) || '');
|
|
4349
|
+
const run = pid ? AUTO_RUNS.get(runKeyOf(pid, toolCanvasId(args))) : null;
|
|
4350
|
+
const runView = run ? { status: run.status, phase: run.phase, error: run.error || null,
|
|
4351
|
+
log: run.log.slice(-6), meetingNodeId: run.meetingNodeId || null, scriptNodeId: run.scriptNodeId || null, startedAt: run.startedAt,
|
|
4352
|
+
budget: run.budget || null, boards: run.boards || [], paid: run.paid || null, paidPhase: run.paidPhase || null, paidError: run.paidError || null,
|
|
4353
|
+
paidLog: (run.paidLog || []).slice(-6), finalcutNodeId: run.finalcutNodeId || null } : null;
|
|
4354
|
+
if (!enabled || !pid) return { ok: true, enabled, caps, stage: null, approval: null, run: runView };
|
|
4355
|
+
const price = Number(cfg.production && cfg.production.videoUnitPricePerSecond);
|
|
4356
|
+
const st = PROD.status(pid, toolCanvasId(args));
|
|
4357
|
+
return {
|
|
4358
|
+
ok: true, enabled, caps,
|
|
4359
|
+
stage: st.stage, ready: st.ready, blockers: st.blockers,
|
|
4360
|
+
approval: PROD.approvalOf(pid, toolCanvasId(args), price),
|
|
4361
|
+
quote: PROD.quote(pid, toolCanvasId(args), price),
|
|
4362
|
+
run: runView,
|
|
4363
|
+
};
|
|
4364
|
+
},
|
|
4365
|
+
/** 启动免费段(编剧室):调研 → 编剧A/B 独立提案 → 互评 → 监制决策 → 设定集+剧本 idea 落盘。
|
|
4366
|
+
* 全程零付费;讨论记录写进「编剧室会议」文本节点;剧情走向只来自 brief。 */
|
|
4367
|
+
async autoStart(args) {
|
|
4368
|
+
if (!autoEnabled()) return autoDisabled();
|
|
4369
|
+
const pid = String((args && args.projectId) || '');
|
|
4370
|
+
if (!pid) return { ok: false, error: '缺少 projectId' };
|
|
4371
|
+
const brief = String((args && args.brief) || '').trim();
|
|
4372
|
+
if (brief.length < 4) return { ok: false, error: '缺少 brief:请给一句话创意(至少 4 个字),它是剧情走向的唯一源头' };
|
|
4373
|
+
const cid = toolCanvasId(args);
|
|
4374
|
+
const runKey = runKeyOf(pid, cid);
|
|
4375
|
+
const prev = AUTO_RUNS.get(runKey);
|
|
4376
|
+
if (prev && prev.status === 'running') return { ok: false, error: '该画布已有自动创作在跑(阶段 ' + prev.phase + '):先 autoAbort 或等待完成' };
|
|
4377
|
+
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 };
|
|
4378
|
+
AUTO_RUNS.set(runKey, run);
|
|
4379
|
+
// brief 记进制作状态(status 可见;重启后仍能查到这一集的创意源头)
|
|
4380
|
+
try {
|
|
4381
|
+
const ps = PROD.readState(pid, cid) || { version: 1, projectId: pid, canvasKey: (cid || 'default'), floor: 0, explicit: null, createdAt: Date.now(), updatedAt: 0, history: [], overrides: [] };
|
|
4382
|
+
ps.brief = brief;
|
|
4383
|
+
ps.updatedAt = Date.now();
|
|
4384
|
+
PROD.writeState(pid, cid, ps);
|
|
4385
|
+
} catch { /* 状态写入失败不阻塞启动 */ }
|
|
4386
|
+
autoRoom(pid, cid, brief).catch(() => { /* 兜底:autoRoom 内部已捕获并落状态 */ });
|
|
4387
|
+
return { ok: true, runId: runKey, status: 'running', note: '免费段已启动(调研→提案→互评→决策→落盘);用 autoStatus 查看进度' };
|
|
4388
|
+
},
|
|
4389
|
+
/** 中止运行中的自动创作(免费段或付费段):保留已产出内容(讨论节点/设定集/节点/已完成视频)。 */
|
|
4390
|
+
async autoAbort(args) {
|
|
4391
|
+
if (!autoEnabled()) return autoDisabled();
|
|
4392
|
+
const pid = String((args && args.projectId) || '');
|
|
4393
|
+
if (!pid) return { ok: false, error: '缺少 projectId' };
|
|
4394
|
+
const run = AUTO_RUNS.get(runKeyOf(pid, toolCanvasId(args)));
|
|
4395
|
+
if (!run) return { ok: false, error: '该画布没有正在运行的自动创作' };
|
|
4396
|
+
let stopped = false;
|
|
4397
|
+
if (run.status === 'running') { run.status = 'aborted'; stopped = true; }
|
|
4398
|
+
if (run.paid === 'running') { run.paidAbort = true; run.paid = 'aborting'; stopped = true; }
|
|
4399
|
+
if (!stopped) return { ok: false, error: '该画布没有正在运行的自动创作' };
|
|
4400
|
+
run.error = null;
|
|
4401
|
+
run.log.push({ at: Date.now(), role: 'runner', summary: '已中止(保留已产出内容)' });
|
|
4402
|
+
return { ok: true, status: run.status, paid: run.paid };
|
|
4403
|
+
},
|
|
4404
|
+
async sessionBindingGet(args) {
|
|
4405
|
+
const sid = String((args && args.sessionId) || '');
|
|
4406
|
+
if (!sid) return { ok: false, error: '缺少 sessionId' };
|
|
4407
|
+
const sc = wsSessionContext(sid);
|
|
4408
|
+
if (!sc.supported) return { ok: true, supported: false };
|
|
4409
|
+
// 绑定查找是**全局**的(工作区内嵌 + 数据根项目都可被绑定):先找会话现绑的项目;
|
|
4410
|
+
// 未绑定时再退回会话所在工作区项目(仅供上下文/画布清单,不产生绑定)。
|
|
4411
|
+
const boundHit = toolBindingForSession(sid);
|
|
4412
|
+
let pid = boundHit ? boundHit.projectId : null;
|
|
4413
|
+
if (!pid && sc.ws) {
|
|
4414
|
+
let rec = wsRecOf(sc.ws);
|
|
4415
|
+
if (!rec && sc.list) {
|
|
4416
|
+
// watcher 可能还没轮到:按**完整** registry 补扫一次(单工作区补扫会清掉其他工作区缓存)
|
|
4417
|
+
wsProjectsScan(sc.list);
|
|
4418
|
+
rec = wsRecOf(sc.ws);
|
|
4419
|
+
}
|
|
4420
|
+
if (rec) pid = rec.pid;
|
|
4421
|
+
}
|
|
4422
|
+
if (!pid) return { ok: true, supported: true, workspace: sc.ws ? wsView(sc.ws) : null, project: null, binding: null, canvasId: null, canvases: [], occupied: {} };
|
|
4423
|
+
const data = bindingsRead(pid);
|
|
4424
|
+
const binding = boundHit ? (data.bindings.find((b) => b && b.sessionId === sid) || null) : null;
|
|
4425
|
+
const pdoc = readDocOrNull(pid) || {};
|
|
4426
|
+
const canvases = canvasesOfDoc(pdoc);
|
|
4427
|
+
const occupied = {};
|
|
4428
|
+
for (const b of data.bindings) if (b && b.sessionId !== sid && b.canvasId) occupied[b.canvasId] = b.sessionId;
|
|
4429
|
+
return {
|
|
4430
|
+
ok: true, supported: true,
|
|
4431
|
+
workspace: sc.ws ? wsView(sc.ws) : null,
|
|
4432
|
+
project: { id: pid, name: pdoc.name || pid },
|
|
4433
|
+
binding: binding ? { canvasId: binding.canvasId, boundAt: binding.boundAt || 0 } : null,
|
|
4434
|
+
canvasId: binding ? binding.canvasId : null,
|
|
4435
|
+
defaultCanvasName: defaultCanvasNameForApi(pdoc),
|
|
4436
|
+
canvases, occupied,
|
|
4437
|
+
};
|
|
4438
|
+
},
|
|
4439
|
+
async sessionBindingSet(args) {
|
|
4440
|
+
const sid = String((args && args.sessionId) || '');
|
|
4441
|
+
if (!sid) return { ok: false, error: '缺少 sessionId' };
|
|
4442
|
+
const sc = wsSessionContext(sid);
|
|
4443
|
+
if (!sc.supported) return { ok: false, unsupported: true, error: '当前宿主无工作区能力,无法绑定画布' };
|
|
4444
|
+
let pid = String((args && args.projectId) || '');
|
|
4445
|
+
if (!pid) {
|
|
4446
|
+
if (!sc.ws) return { ok: false, error: '会话不在任何工作区,无法解析项目' };
|
|
4447
|
+
const rec = wsRecOf(sc.ws);
|
|
4448
|
+
if (!rec) return { ok: false, error: '该工作区还没有画布项目' };
|
|
4449
|
+
pid = rec.pid;
|
|
4450
|
+
}
|
|
4451
|
+
// 项目必须是真实存在的画布项目(工作区内嵌或数据根均可);存在性由 bindingSet 校验
|
|
4452
|
+
const alive = (t) => sc.isAlive(t);
|
|
4453
|
+
return bindingSet(pid, sid, (args && args.canvasId) ?? null, alive);
|
|
4454
|
+
},
|
|
4455
|
+
async sessionBindingClear(args) {
|
|
4456
|
+
const sid = String((args && args.sessionId) || '');
|
|
4457
|
+
if (!sid) return { ok: false, error: '缺少 sessionId' };
|
|
4458
|
+
const sc = wsSessionContext(sid);
|
|
4459
|
+
if (!sc.supported) return { ok: false, unsupported: true, error: '当前宿主无工作区能力' };
|
|
4460
|
+
let pid = String((args && args.projectId) || '');
|
|
4461
|
+
if (!pid) {
|
|
4462
|
+
// 绑定查找是全局的:先找会话**实际绑定**的项目(绑定可指向数据根老项目)
|
|
4463
|
+
const hit = toolBindingForSession(sid);
|
|
4464
|
+
if (hit) pid = hit.projectId;
|
|
4465
|
+
}
|
|
4466
|
+
if (!pid && sc.ws) {
|
|
4467
|
+
const rec = wsRecOf(sc.ws);
|
|
4468
|
+
if (rec) pid = rec.pid;
|
|
4469
|
+
}
|
|
4470
|
+
if (!pid) return { ok: true, removed: false };
|
|
4471
|
+
return bindingClear(pid, sid);
|
|
4472
|
+
},
|
|
4473
|
+
/** 可绑定的项目清单(画布选择器未绑定态用):工作区内嵌 + 数据根混排,按更新时间倒序,每项带画布清单。 */
|
|
4474
|
+
async bindableProjects() {
|
|
4475
|
+
const out = [];
|
|
4476
|
+
try {
|
|
4477
|
+
for (const rec of wsProjects.values()) {
|
|
4478
|
+
const doc = readDocOrNull(rec.pid) || {};
|
|
4479
|
+
out.push({
|
|
4480
|
+
id: rec.pid, name: doc.name || rec.pid, origin: 'workspace',
|
|
4481
|
+
updatedAt: doc.updatedAt || 0, canvases: canvasesOfDoc(doc),
|
|
4482
|
+
});
|
|
4483
|
+
}
|
|
4484
|
+
} catch { /* 单个项目读取失败跳过 */ }
|
|
4485
|
+
try {
|
|
4486
|
+
for (const p of projectsListDataRoot()) {
|
|
4487
|
+
if (wsProjects.has(p.id)) continue;
|
|
4488
|
+
const canvases = (p.defaultCanvasDeleted ? [] : [{ id: null, name: p.defaultCanvasName || '默认画布' }])
|
|
4489
|
+
.concat((p.canvases || []).map((c) => ({ id: c.id, name: c.name })));
|
|
4490
|
+
out.push({ id: p.id, name: p.name, origin: 'dataRoot', updatedAt: p.updatedAt || 0, canvases });
|
|
4491
|
+
}
|
|
4492
|
+
} catch { /* 无数据根:仅工作区项目 */ }
|
|
4493
|
+
out.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
|
|
4494
|
+
return { ok: true, projects: out.slice(0, 100) };
|
|
4495
|
+
},
|
|
4496
|
+
async workspaceProjectCreate(args) { const sid = String((args && args.sessionId) || '');
|
|
4497
|
+
if (!sid) return { ok: false, error: '缺少 sessionId' };
|
|
4498
|
+
const sc = wsSessionContext(sid);
|
|
4499
|
+
if (!sc.supported) return { ok: false, unsupported: true, error: '当前宿主无工作区能力' };
|
|
4500
|
+
if (!sc.ws) return { ok: false, error: '会话不在任何工作区(仅会话无法挂画布项目)' };
|
|
4501
|
+
let rec = wsRecOf(sc.ws);
|
|
4502
|
+
let createdNow = false;
|
|
4503
|
+
if (!rec && sc.list) {
|
|
4504
|
+
wsProjectsScan(sc.list); // 完整补扫(语义同上:不清其他工作区的账)
|
|
4505
|
+
rec = wsRecOf(sc.ws);
|
|
4506
|
+
}
|
|
4507
|
+
if (!rec) { rec = wsProjectCreateAt(sc.ws); createdNow = true; }
|
|
4508
|
+
// 存量修正:机器生成的项目名(= 目录名 / 项目 id / ws* 随机串)→ 改用工作区显示名。
|
|
4509
|
+
// 用户手动改过名的项目(既不等于目录名也不像 id)绝不覆盖。
|
|
4510
|
+
const wsTitle = String((sc.ws && sc.ws.title) || '').replace(/\s+/g, ' ').trim().slice(0, 80);
|
|
4511
|
+
if (rec && wsTitle) {
|
|
4512
|
+
try {
|
|
4513
|
+
const doc = readDoc(rec.pid);
|
|
4514
|
+
const cur = String(doc.name || '').trim();
|
|
4515
|
+
const folder = (path.basename(String((sc.ws && sc.ws.path) || '')) || '').trim();
|
|
4516
|
+
const machineNamed = !cur || cur === folder || cur === rec.pid || /^ws[a-z0-9]{8,}$/i.test(cur);
|
|
4517
|
+
if (machineNamed && cur !== wsTitle) patchProjectDoc(rec.pid, { name: wsTitle });
|
|
4518
|
+
} catch { /* 修正失败不阻塞创建/绑定 */ }
|
|
4519
|
+
}
|
|
4520
|
+
const name = String((args && args.name) || '').trim();
|
|
4521
|
+
if (createdNow && name) {
|
|
4522
|
+
try { patchProjectDoc(rec.pid, { name: name.slice(0, 80) }); } catch { /* 改名失败不阻塞 */ }
|
|
4523
|
+
}
|
|
4524
|
+
// 只在**新建**时自动绑默认画布(复用既有项目时不强行绑定:绑定走选择器,避免占用冲突)
|
|
4525
|
+
let bound = null;
|
|
4526
|
+
if (createdNow) bound = await bindingSet(rec.pid, sid, null, sc.isAlive);
|
|
4527
|
+
return {
|
|
4528
|
+
ok: true, projectId: rec.pid, created: createdNow,
|
|
4529
|
+
name: (() => { try { return String(readDoc(rec.pid).name || '').trim() || undefined; } catch { return undefined; } })(),
|
|
4530
|
+
bound: !!(bound && bound.ok), occupied: !!(bound && bound.occupied),
|
|
4531
|
+
bindError: bound && !bound.ok ? (bound.error || null) : null,
|
|
4532
|
+
};
|
|
4533
|
+
},
|
|
4534
|
+
async memoryGet(args) {
|
|
4535
|
+
return memoryRead(args && args.projectId, args && args.canvasId);
|
|
4536
|
+
},
|
|
4537
|
+
async memoryPut(args) {
|
|
4538
|
+
return memoryWrite(args && args.projectId, args && args.canvasId, args || {});
|
|
4539
|
+
},
|
|
3396
4540
|
|
|
3397
4541
|
};
|
|
3398
4542
|
|
|
3399
4543
|
const toolDisposers = [];
|
|
4544
|
+
// 工作区 watcher:5s 轮询 workspaceRegistry(老宿主无该服务 → list 不可得 → tick 直接跳过)。
|
|
4545
|
+
// 不把 workspaceRegistry 放进 export const inject:cordis 的 inject 语义是「服务不存在则插件挂起等待」,
|
|
4546
|
+
// 老宿主会让我们整个插件起不来——防御式 get + 轮询才是可降级的接法。
|
|
4547
|
+
ctx.effect(() => {
|
|
4548
|
+
const tick = () => {
|
|
4549
|
+
try {
|
|
4550
|
+
const reg = ctx.get && ctx.get('workspaceRegistry');
|
|
4551
|
+
const list = reg && typeof reg.list === 'function' ? reg.list() : null;
|
|
4552
|
+
wsWatchTick(list);
|
|
4553
|
+
} catch { /* registry 漂移/服务缺失 → 下轮再试 */ }
|
|
4554
|
+
};
|
|
4555
|
+
tick(); // 启动即扫一次(工作区项目立即可见,不等首个 5s)
|
|
4556
|
+
const timer = setInterval(tick, 5000);
|
|
4557
|
+
if (timer && typeof timer.unref === 'function') timer.unref(); // 不阻塞进程退出
|
|
4558
|
+
return () => clearInterval(timer);
|
|
4559
|
+
}, 'infinite-canvas: workspace watcher');
|
|
3400
4560
|
try {
|
|
3401
4561
|
if (ctx.tools && typeof ctx.tools.register === 'function') {
|
|
3402
4562
|
/** 深度剥掉 undefined 值:DSH 对工具结果做"无损 JSON"校验(snapshotJsonValue),
|
|
@@ -3417,7 +4577,43 @@ export function apply(ctx) {
|
|
|
3417
4577
|
const reg = (def) => {
|
|
3418
4578
|
try {
|
|
3419
4579
|
const inner = def.execute;
|
|
3420
|
-
|
|
4580
|
+
// 会话绑定(0.20.x):绑定会话的 agent 被**代码级锁死**在本集画布——
|
|
4581
|
+
// ① projectId/canvasId 缺省 → 自动注入绑定值;
|
|
4582
|
+
// ② 显式传其他项目/画布(含同项目其他画布与默认画布)→ 直接拒绝(locked),文案指引先解绑;
|
|
4583
|
+
// ③ 未绑定会话不受任何限制(编码等普通任务零打扰)。
|
|
4584
|
+
// 只对 schema 声明了该参数的工具生效(additionalProperties:false 的工具不能多塞键);
|
|
4585
|
+
// 嗅探失败(宿主不带会话身份)静默回退旧行为。
|
|
4586
|
+
const propDefs = (def.parameters && def.parameters.properties) || null;
|
|
4587
|
+
const allowProject = !!(propDefs && Object.prototype.hasOwnProperty.call(propDefs, 'projectId'));
|
|
4588
|
+
const allowCanvas = !!(propDefs && Object.prototype.hasOwnProperty.call(propDefs, 'canvasId'));
|
|
4589
|
+
def.execute = async (args, exec) => {
|
|
4590
|
+
let a = args;
|
|
4591
|
+
try {
|
|
4592
|
+
const sid = toolExecSessionId(exec);
|
|
4593
|
+
if (sid && (allowProject || allowCanvas)) {
|
|
4594
|
+
const b = toolBindingForSession(sid);
|
|
4595
|
+
if (b) {
|
|
4596
|
+
a = (args && typeof args === 'object' && !Array.isArray(args)) ? args : {};
|
|
4597
|
+
const wantPid = b.projectId == null ? null : String(b.projectId);
|
|
4598
|
+
const wantCid = b.canvasId == null ? null : String(b.canvasId);
|
|
4599
|
+
const deny = (what) => {
|
|
4600
|
+
const label = bindingLabelOf(b);
|
|
4601
|
+
return stripUndefined({
|
|
4602
|
+
ok: false,
|
|
4603
|
+
locked: true,
|
|
4604
|
+
text: '本会话已绑定画布工作台「' + label + '」,代码级限制:' + what
|
|
4605
|
+
+ '。一个会话只允许操作自己绑定的那一张画布;如需操作其他画布/项目,请先在对话输入行的画布选择器里解绑。',
|
|
4606
|
+
});
|
|
4607
|
+
};
|
|
4608
|
+
if (allowProject && a.projectId != null && String(a.projectId) !== wantPid) return deny('禁止跨项目操作');
|
|
4609
|
+
if (allowCanvas && a.canvasId != null && String(a.canvasId) !== wantCid) return deny('禁止跨画布操作(含同项目其他画布与默认画布)');
|
|
4610
|
+
if (allowProject && a.projectId == null && wantPid != null) a.projectId = b.projectId;
|
|
4611
|
+
if (allowCanvas && a.canvasId == null && wantCid != null) a.canvasId = b.canvasId;
|
|
4612
|
+
}
|
|
4613
|
+
}
|
|
4614
|
+
} catch { /* 默认解析失败 → 原参数路径 */ }
|
|
4615
|
+
return stripUndefined(await inner(a, exec));
|
|
4616
|
+
};
|
|
3421
4617
|
toolDisposers.push(ctx.tools.register(def));
|
|
3422
4618
|
} catch { /* 单个工具失败不阻塞其余 */ }
|
|
3423
4619
|
};
|
|
@@ -3443,10 +4639,18 @@ export function apply(ctx) {
|
|
|
3443
4639
|
render: (args, value) => [{ type: 'text', text: String(value.text || '') }],
|
|
3444
4640
|
},
|
|
3445
4641
|
timeoutMs: 30000,
|
|
3446
|
-
async execute(args) {
|
|
4642
|
+
async execute(args, exec) {
|
|
3447
4643
|
const kw = String((args && args.keyword) || '').toLowerCase();
|
|
3448
|
-
|
|
4644
|
+
// 绑定会话:只允许看到自己绑定的项目(读取也必须锁死,否则模型能"围观"全部画布)
|
|
4645
|
+
const sid = toolExecSessionId(exec);
|
|
4646
|
+
const bound = sid ? toolBindingForSession(sid) : null;
|
|
4647
|
+
let full = projectsList();
|
|
4648
|
+
if (full && typeof full.then === 'function') full = await full;
|
|
4649
|
+
let list = Array.isArray(full) ? full : [];
|
|
4650
|
+
if (bound) list = list.filter((p) => p.id === bound.projectId);
|
|
4651
|
+
list = list.filter((p) => !kw || String(p.name).toLowerCase().includes(kw));
|
|
3449
4652
|
const lines = [];
|
|
4653
|
+
if (bound) lines.push('本会话已绑定画布工作台:只显示绑定项目「' + ((list[0] && list[0].name) || bound.projectId) + '」;其他项目已隐藏(要操作其他项目请先解绑)。');
|
|
3450
4654
|
for (const p of list) {
|
|
3451
4655
|
const canvases = Array.isArray(p.canvases) ? p.canvases : [];
|
|
3452
4656
|
const defTxt = p.defaultCanvasDeleted
|
|
@@ -3476,7 +4680,13 @@ export function apply(ctx) {
|
|
|
3476
4680
|
},
|
|
3477
4681
|
output: textOutput,
|
|
3478
4682
|
timeoutMs: 30000,
|
|
3479
|
-
async execute(args) {
|
|
4683
|
+
async execute(args, exec) {
|
|
4684
|
+
// 绑定会话:禁止新建项目(跨项目动作;要新建先解绑)
|
|
4685
|
+
const sid = toolExecSessionId(exec);
|
|
4686
|
+
const bound = sid ? toolBindingForSession(sid) : null;
|
|
4687
|
+
if (bound) {
|
|
4688
|
+
return { ok: false, locked: true, text: '本会话已绑定画布工作台「' + (bound.canvasId ? bound.canvasId : '默认画布') + '」,代码级限制:禁止新建项目(一个会话只允许操作自己绑定的那一张画布)。要新建项目请先在对话输入行的画布选择器里解绑。' };
|
|
4689
|
+
}
|
|
3480
4690
|
const r = canvasCreateProject(args);
|
|
3481
4691
|
if (r.reused) {
|
|
3482
4692
|
return { ok: true, projectId: r.projectId, name: r.name, text: '♻️ 项目「' + r.name + '」已存在(id=' + r.projectId + '),已复用,未重复创建。往其中加内容请用 canvas_write_node({ projectId: "' + r.projectId + '", ... })。' };
|
|
@@ -3528,6 +4738,10 @@ export function apply(ctx) {
|
|
|
3528
4738
|
timeoutMs: 30000,
|
|
3529
4739
|
async execute(args) {
|
|
3530
4740
|
const r = await canvasRunNode(args);
|
|
4741
|
+
if (r && r.ok === false) {
|
|
4742
|
+
const det = r.fails ? '\n· ' + r.fails.join('\n· ') : '';
|
|
4743
|
+
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 : '') };
|
|
4744
|
+
}
|
|
3531
4745
|
return { ok: true, projectId: r.projectId, nodeId: r.nodeId, text: '🚀 已触发执行[' + r.type + ']「' + (r.label || r.nodeId) + '」。画布将在数秒内开始,可用 canvas_node_status 查询进度与结果。' };
|
|
3532
4746
|
},
|
|
3533
4747
|
});
|
|
@@ -3676,6 +4890,10 @@ export function apply(ctx) {
|
|
|
3676
4890
|
timeoutMs: 660000,
|
|
3677
4891
|
async execute(args) {
|
|
3678
4892
|
const r = await canvasGenerateNode(args);
|
|
4893
|
+
if (r && r.ok === false && r.gate) {
|
|
4894
|
+
const det = r.fails ? '\n· ' + r.fails.join('\n· ') : '';
|
|
4895
|
+
return { ok: false, gate: r.gate, projectId: r.projectId, nodeId: r.nodeId, text: '⛔ [' + r.gate + '] ' + (r.error || '流程闸门未通过') + det + (r.fix ? '\n出路:' + r.fix : '') };
|
|
4896
|
+
}
|
|
3679
4897
|
const head = '🚀 已触发[' + r.type + ']「' + (r.label || r.nodeId) + '」';
|
|
3680
4898
|
const tail = r.finished
|
|
3681
4899
|
? (r.ok ? '✅ 已完成(状态 ' + r.status + (r.assetId ? ',产物资产 ' + r.assetId : '') + ')' : '❌ 失败:' + (r.error || r.status))
|
|
@@ -3696,12 +4914,13 @@ export function apply(ctx) {
|
|
|
3696
4914
|
timeoutMs: 30000,
|
|
3697
4915
|
async execute(args) {
|
|
3698
4916
|
const r = await canvasDeleteNode(args);
|
|
4917
|
+
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 : '') };
|
|
3699
4918
|
return { ok: true, projectId: r.projectId, nodeId: r.nodeId, text: '🗑 已删除节点 ' + r.nodeId + '。' };
|
|
3700
4919
|
},
|
|
3701
4920
|
});
|
|
3702
4921
|
reg({
|
|
3703
4922
|
name: 'canvas_relayout',
|
|
3704
|
-
description: '
|
|
4923
|
+
description: '一键粗排画布节点(兜底用,不是精确摆放):按「行」排列——横向数据流决定列,竖向关系(prev/frame)不参与分列;每行 = 一个横向连通组,行间保留间距,多行按带宽分带左右铺开。**pinned(被 canvas_layout_node 钉住的节点)不会被移动**。需要精确到像素的摆放请用 canvas_layout_get + canvas_layout_node,不要用本工具。',
|
|
3705
4924
|
parameters: {
|
|
3706
4925
|
type: 'object',
|
|
3707
4926
|
properties: { projectId: { type: 'string', description: '项目 id' }, canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' } },
|
|
@@ -3712,7 +4931,61 @@ export function apply(ctx) {
|
|
|
3712
4931
|
timeoutMs: 30000,
|
|
3713
4932
|
async execute(args) {
|
|
3714
4933
|
const r = canvasRelayout(args);
|
|
3715
|
-
return { ok: true, projectId: r.projectId, text: '✅ 已重排 ' + r.moved + ' 个节点(' + r.rows + ' 行,无重叠)。' };
|
|
4934
|
+
return { ok: true, projectId: r.projectId, text: '✅ 已重排 ' + r.moved + ' 个节点(' + r.rows + ' 行,无重叠)。' + (r.skippedPinned ? '钉住的 ' + r.skippedPinned + ' 个节点保持原位。' : '') };
|
|
4935
|
+
},
|
|
4936
|
+
});
|
|
4937
|
+
reg({
|
|
4938
|
+
name: 'canvas_layout_get',
|
|
4939
|
+
description: '读取整画布几何视图:返回每个节点的 nodeId/名字/类型/x/y/w/h/pinned 与画布包围盒。精确摆放前先调它拿全图坐标(不要靠猜)。',
|
|
4940
|
+
parameters: {
|
|
4941
|
+
type: 'object',
|
|
4942
|
+
properties: { projectId: { type: 'string', description: '项目 id' }, canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' } },
|
|
4943
|
+
required: ['projectId'],
|
|
4944
|
+
additionalProperties: false,
|
|
4945
|
+
},
|
|
4946
|
+
output: textOutput,
|
|
4947
|
+
timeoutMs: 15000,
|
|
4948
|
+
async execute(args) {
|
|
4949
|
+
const r = canvasLayoutGet(args);
|
|
4950
|
+
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 ? ' 📌' : ''));
|
|
4951
|
+
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') };
|
|
4952
|
+
},
|
|
4953
|
+
});
|
|
4954
|
+
reg({
|
|
4955
|
+
name: 'canvas_layout_node',
|
|
4956
|
+
description: '精准摆放节点(0.20.0):批量设置坐标,媒体节点可同时改尺寸;pinned=true 钉住后 canvas_relayout 不会再动它。允许重叠(这是精确摆放,不是自动整理)。先 canvas_layout_get 读全图,再算好坐标一次传入。',
|
|
4957
|
+
parameters: {
|
|
4958
|
+
type: 'object',
|
|
4959
|
+
properties: {
|
|
4960
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
4961
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
4962
|
+
nodes: {
|
|
4963
|
+
type: 'array',
|
|
4964
|
+
description: '要摆放的节点数组(一次可传多个)',
|
|
4965
|
+
items: {
|
|
4966
|
+
type: 'object',
|
|
4967
|
+
properties: {
|
|
4968
|
+
nodeId: { type: 'string' },
|
|
4969
|
+
x: { type: 'number', description: '目标 x(可为负)' },
|
|
4970
|
+
y: { type: 'number', description: '目标 y(可为负)' },
|
|
4971
|
+
w: { type: 'number', description: '可选:宽度(仅 image/video,≥160)' },
|
|
4972
|
+
h: { type: 'number', description: '可选:高度(仅 image/video,≥120)' },
|
|
4973
|
+
pinned: { type: 'boolean', description: '可选:钉住,canvas_relayout 不再移动它' },
|
|
4974
|
+
},
|
|
4975
|
+
required: ['nodeId', 'x', 'y'],
|
|
4976
|
+
additionalProperties: false,
|
|
4977
|
+
},
|
|
4978
|
+
},
|
|
4979
|
+
},
|
|
4980
|
+
required: ['projectId', 'nodes'],
|
|
4981
|
+
additionalProperties: false,
|
|
4982
|
+
},
|
|
4983
|
+
output: textOutput,
|
|
4984
|
+
timeoutMs: 30000,
|
|
4985
|
+
async execute(args) {
|
|
4986
|
+
const r = canvasLayoutNode(args);
|
|
4987
|
+
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 ? ' 📌钉住' : ' 取消钉住') : ''));
|
|
4988
|
+
return { ok: true, projectId: r.projectId, moved: r.moved, applied: r.applied, text: '✅ 已精准摆放 ' + r.moved + ' 个节点:\n' + lines.join('\n') };
|
|
3716
4989
|
},
|
|
3717
4990
|
});
|
|
3718
4991
|
reg({
|
|
@@ -3793,6 +5066,7 @@ export function apply(ctx) {
|
|
|
3793
5066
|
timeoutMs: 30000,
|
|
3794
5067
|
async execute(args) {
|
|
3795
5068
|
const r = await canvasDeleteProject(args);
|
|
5069
|
+
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 : '') };
|
|
3796
5070
|
// 磁盘清理失败必须可见:rmrf 部分失败(文件锁)时目录残留,同名重建会继承旧文件
|
|
3797
5071
|
const diskErrs = r.disk && Array.isArray(r.disk.errors) ? r.disk.errors : [];
|
|
3798
5072
|
const warn = diskErrs.length ? '⚠ 磁盘清理有 ' + diskErrs.length + ' 项失败:' + diskErrs.join(';') : '';
|
|
@@ -3856,6 +5130,245 @@ export function apply(ctx) {
|
|
|
3856
5130
|
return { ok: true, projectId: r.projectId, text };
|
|
3857
5131
|
},
|
|
3858
5132
|
});
|
|
5133
|
+
reg({
|
|
5134
|
+
name: 'canvas_read_memory',
|
|
5135
|
+
description: '读取项目记忆:不带 canvasId 返回**调度索引**(每集画布的标题/摘要/关键词/状态,一眼看到全项目各集记忆脉络);带 canvasId 额外返回该集**完整记忆正文**(剧情决策/人物状态变化/伏笔账本)。【记忆先行】写第 N 集剧本或分镜之前必须先读本集记忆(canvasId 从画布清单或索引对上号);跨集要伏笔/人物状态连续性时先读索引再读相关集正文。世界观/风格/角色场景设定不在记忆里——那些用 canvas_get_bible。',
|
|
5136
|
+
parameters: {
|
|
5137
|
+
type: 'object',
|
|
5138
|
+
properties: {
|
|
5139
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5140
|
+
canvasId: { type: 'string', description: '画布 id(集);缺省只回索引' },
|
|
5141
|
+
},
|
|
5142
|
+
required: ['projectId'],
|
|
5143
|
+
additionalProperties: false,
|
|
5144
|
+
},
|
|
5145
|
+
output: textOutput,
|
|
5146
|
+
timeoutMs: 30000,
|
|
5147
|
+
async execute(args) {
|
|
5148
|
+
const r = await memoryRead(args && args.projectId, args && args.canvasId);
|
|
5149
|
+
const idx = r.index || { episodes: [] };
|
|
5150
|
+
const lines = [];
|
|
5151
|
+
if (!idx.episodes.length) lines.push('(项目记忆为空:本集是第一集或尚未回写过记忆。写完记得 canvas_write_memory。)');
|
|
5152
|
+
else {
|
|
5153
|
+
lines.push('记忆索引(' + idx.episodes.length + ' 集)——跨集连续性的总账:');
|
|
5154
|
+
for (const e of idx.episodes) {
|
|
5155
|
+
lines.push(' · [' + (e.canvasId || '-') + '] ' + (e.title || '未命名') + '(' + (e.status === 'done' ? '已完结' : ' drafting/进行中') + ')' + (e.summary ? ':' + e.summary : '') + (Array.isArray(e.keywords) && e.keywords.length ? ' 关键词:' + e.keywords.join('/') : ''));
|
|
5156
|
+
}
|
|
5157
|
+
}
|
|
5158
|
+
if (r.episode) {
|
|
5159
|
+
lines.push('—— [' + r.episode.canvasId + '] ' + (r.episode.title || '未命名') + ' 的完整记忆 ——');
|
|
5160
|
+
lines.push(r.episode.body || '(该集还没有记忆正文)');
|
|
5161
|
+
}
|
|
5162
|
+
return { ok: true, projectId: r.projectId, text: lines.join('\n') };
|
|
5163
|
+
},
|
|
5164
|
+
});
|
|
5165
|
+
reg({
|
|
5166
|
+
name: 'canvas_write_memory',
|
|
5167
|
+
description: '写入某集(画布)的项目记忆并自动更新调度索引:title 集标题、summary 一句话摘要(≤120 字,进索引供其他集快速检索)、keywords 关键词、body 完整记忆正文(剧情决策/人物状态变化/伏笔账本/未回收的钩子)、status 进度。【会话收尾铁律】一集创作告一段落(每场定稿/全集完成)必须回写本集记忆——记忆是跨集连续性的唯一载体,不回写 = 下一集会重复创作、重复设定、丢伏笔。',
|
|
5168
|
+
parameters: {
|
|
5169
|
+
type: 'object',
|
|
5170
|
+
properties: {
|
|
5171
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5172
|
+
canvasId: { type: 'string', description: '画布 id(集)——记忆按画布隔离' },
|
|
5173
|
+
title: { type: 'string', description: '集标题(如「第3集 雨夜追踪」)' },
|
|
5174
|
+
summary: { type: 'string', description: '一句话摘要(≤120 字,写入索引供跨集检索)' },
|
|
5175
|
+
keywords: { type: 'array', items: { type: 'string' }, description: '关键词(人物/地点/伏笔标记,≤10 个)' },
|
|
5176
|
+
body: { type: 'string', description: '完整记忆正文(markdown):剧情决策、人物状态变化、伏笔登记与回收、生成要点' },
|
|
5177
|
+
status: { type: 'string', enum: ['drafting', 'done'], description: '进度:进行中/已完结' },
|
|
5178
|
+
},
|
|
5179
|
+
required: ['projectId', 'canvasId', 'title', 'summary', 'body'],
|
|
5180
|
+
additionalProperties: false,
|
|
5181
|
+
},
|
|
5182
|
+
output: textOutput,
|
|
5183
|
+
timeoutMs: 30000,
|
|
5184
|
+
async execute(args) {
|
|
5185
|
+
if (!args || !String(args.canvasId || '').trim()) return { ok: false, text: '缺少 canvasId:记忆按画布(集)隔离,必须指定。' };
|
|
5186
|
+
const r = await memoryWrite(args.projectId, args.canvasId, args);
|
|
5187
|
+
if (!r.ok) return { ok: false, text: r.error || '记忆写入失败' };
|
|
5188
|
+
return { ok: true, projectId: r.projectId, canvasId: r.canvasId, text: '✅ 记忆已写入索引(' + ((r.index && r.index.episodes.length) || 0) + ' 集)。' };
|
|
5189
|
+
},
|
|
5190
|
+
});
|
|
5191
|
+
reg({
|
|
5192
|
+
name: 'canvas_my_canvas',
|
|
5193
|
+
description: '自证身份:返回当前会话绑定的画布项目与画布(第几集),以及本集记忆状态。【会话=画布工作台】开始任何创作前先调用它确认「我是哪一集」;此后所有 canvas_* 工具不传 projectId/canvasId 即默认作用于本集画布。**代码级禁令**:绑定会话只能操作本集画布——显式传其他项目/画布(含同项目其他画布)会被工具直接拒绝,确需操作先请用户解绑;未绑定会话可自由操作任意项目/画布。返回的记忆提示告知是否需要先读/写本集记忆。',
|
|
5194
|
+
parameters: { type: 'object', properties: {}, additionalProperties: false },
|
|
5195
|
+
output: textOutput,
|
|
5196
|
+
timeoutMs: 15000,
|
|
5197
|
+
async execute(args, exec) {
|
|
5198
|
+
const sid = toolExecSessionId(exec);
|
|
5199
|
+
if (!sid) return { ok: false, text: '无法识别当前会话(宿主未提供会话身份):请显式指定 projectId/canvasId 操作画布。' };
|
|
5200
|
+
const b = toolBindingForSession(sid);
|
|
5201
|
+
if (!b) return { ok: false, text: '当前会话未绑定画布:在对话输入行的「绑画布」选择器里选择或新建画布后再试;或显式传 projectId/canvasId 直接操作。' };
|
|
5202
|
+
const doc = readDocOrNull(b.projectId) || {};
|
|
5203
|
+
const regList = canvasRegistry(doc);
|
|
5204
|
+
const cid = b.canvasId == null ? null : b.canvasId;
|
|
5205
|
+
const canvases = (defaultCanvasExists(doc) && !cid ? [{ id: null, name: defaultCanvasNameOf(doc) }] : regList.map((c) => ({ id: c.id, name: c.name })));
|
|
5206
|
+
const idx = canvases.findIndex((c) => (c.id || null) === cid);
|
|
5207
|
+
const ep = idx >= 0 ? idx + 1 : null;
|
|
5208
|
+
const name = idx >= 0 ? canvases[idx].name : String(cid || '默认画布');
|
|
5209
|
+
const mem = await memoryRead(b.projectId, cid);
|
|
5210
|
+
const hasMem = !!(mem.episode && ((mem.episode.body || '').trim() || (mem.episode.summary || '').trim()));
|
|
5211
|
+
let nodeCount = 0;
|
|
5212
|
+
try { nodeCount = Object.keys((readCanvasDoc(b.projectId, cid) || {}).nodes || {}).length; } catch { /* 画布读取失败不阻塞自证 */ }
|
|
5213
|
+
const lines = [
|
|
5214
|
+
'本会话绑定:项目「' + (doc.name || b.projectId) + '」· 画布「' + name + '」' + (ep ? '(第' + ep + ' 集 / 共 ' + canvases.length + ' 集)' : ''),
|
|
5215
|
+
'记忆状态:' + (hasMem ? '已有本集记忆——开写前先 canvas_read_memory 读索引与本集正文' : '本集还没有记忆——创作告一段落必须 canvas_write_memory 回写'),
|
|
5216
|
+
'本集画布节点:' + nodeCount + ' 个(可读写:canvas_write_node / canvas_create_node / canvas_connect / canvas_run_node / canvas_delete_node / canvas_get_bible / canvas_update_bible)',
|
|
5217
|
+
'代码级禁令:绑定会话禁止跨画布/跨项目操作(显式传其他 id 会被工具拒绝);如需操作其他画布,请用户先在对话输入行解绑。',
|
|
5218
|
+
];
|
|
5219
|
+
return { ok: true, projectId: b.projectId, canvasId: cid, name, text: lines.join('\n') };
|
|
5220
|
+
},
|
|
5221
|
+
});
|
|
5222
|
+
reg({
|
|
5223
|
+
name: 'canvas_production_status',
|
|
5224
|
+
description: '制作状态汇报(阶段机):返回本集画布当前所处阶段(brief/bible/assets/script/storyboard/shots_ready/generating/qc/post/delivered)、各闸门(设定集 G1 / 分镜质量 G2)的通过情况与缺失清单、证据计数(剧本/镜头/资产/视频完成数)、以及当前阶段的下一步建议。【铁律】宣称"完成/可以交付"之前必须先调它:只有 ready:true 或用户明确验收才允许说完成;blockers 非空时逐条修复后再继续。开工、卡住、汇报前都应调用。',
|
|
5225
|
+
parameters: {
|
|
5226
|
+
type: 'object',
|
|
5227
|
+
properties: {
|
|
5228
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5229
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5230
|
+
},
|
|
5231
|
+
required: ['projectId'],
|
|
5232
|
+
additionalProperties: false,
|
|
5233
|
+
},
|
|
5234
|
+
output: textOutput,
|
|
5235
|
+
timeoutMs: 15000,
|
|
5236
|
+
async execute(args) {
|
|
5237
|
+
const r = await productionStatus(args);
|
|
5238
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '状态读取失败') };
|
|
5239
|
+
let capsLine = '';
|
|
5240
|
+
try {
|
|
5241
|
+
const caps = await productionCapabilities();
|
|
5242
|
+
capsLine = '\n多智能体能力:' + (caps.multiAgent ? '可用(宿主已暴露会话服务)' : '不可用(宿主未暴露会话服务——自动创作保持休眠)');
|
|
5243
|
+
} catch { /* 探针失败不影响状态输出 */ }
|
|
5244
|
+
const lines = [
|
|
5245
|
+
'阶段:' + r.stageZh + '(' + r.stage + ')' + (r.explicit ? ' · 显式设定' : ' · 自动推进') + ' 推断基线:' + r.inferred,
|
|
5246
|
+
'闸门:G1 设定集 ' + (r.gates.bible.ok ? '✅' : '❌ 缺 ' + r.gates.bible.missing.join('、')) + ';G2 分镜 ' + (r.gates.storyboard.ok ? '✅' : '❌ ' + r.gates.storyboard.fails.length + ' 项'),
|
|
5247
|
+
];
|
|
5248
|
+
if ((r.gates.storyboard.warns || []).length) lines.push('G2 建议:' + r.gates.storyboard.warns.slice(0, 4).join(';'));
|
|
5249
|
+
if (r.blockers.length) lines.push('阻塞:' + r.blockers.map((b) => b.gate).join('、') + '——逐条修复后再继续');
|
|
5250
|
+
const e = r.evidence;
|
|
5251
|
+
lines.push('证据:角色 ' + e.characters + ' · 场景 ' + e.scenes + ' · 剧本 ' + e.scriptsDone + '/' + e.scripts + ' · 分镜表 ' + e.storyboardsWithShots + '/' + e.storyboards + '(镜头 ' + e.shotsTotal + ')· 图 ' + e.imagesDone + '/' + e.images + ' · 视频 ' + e.videosDone + '/' + e.videos);
|
|
5252
|
+
lines.push('下一步:' + r.next);
|
|
5253
|
+
lines.push('ready=' + (r.ready ? 'true(可宣称完成/进入下一步)' : 'false(不得宣称完成)'));
|
|
5254
|
+
if (capsLine) lines.push(capsLine.trim());
|
|
5255
|
+
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') };
|
|
5256
|
+
},
|
|
5257
|
+
});
|
|
5258
|
+
reg({
|
|
5259
|
+
name: 'canvas_production_advance',
|
|
5260
|
+
description: '显式推进/回退制作阶段(阶段机):仅在两种情况使用——① 用户明确要求跳过某一步(如实说明后果后);② 返工(如"这集分镜推倒重来"回退到 storyboard)。日常推进是自动的,不需要调它。必须携带 reason(写进审计),回退会同时下调阶段基线,后续按工具事件重新抬升。',
|
|
5261
|
+
parameters: {
|
|
5262
|
+
type: 'object',
|
|
5263
|
+
properties: {
|
|
5264
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5265
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5266
|
+
to: { type: 'string', enum: ['brief', 'bible', 'assets', 'script', 'storyboard', 'shots_ready', 'generating', 'qc', 'post', 'delivered'], description: '目标阶段' },
|
|
5267
|
+
reason: { type: 'string', description: '原因(必填,进审计日志)' },
|
|
5268
|
+
},
|
|
5269
|
+
required: ['projectId', 'to', 'reason'],
|
|
5270
|
+
additionalProperties: false,
|
|
5271
|
+
},
|
|
5272
|
+
output: textOutput,
|
|
5273
|
+
timeoutMs: 15000,
|
|
5274
|
+
async execute(args) {
|
|
5275
|
+
const r = await productionAdvance(args);
|
|
5276
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '推进失败') };
|
|
5277
|
+
return { ok: true, projectId: args.projectId, stage: r.to, text: '✅ 阶段 ' + r.from + ' → ' + r.to + '(已记入审计)。' };
|
|
5278
|
+
},
|
|
5279
|
+
});
|
|
5280
|
+
reg({
|
|
5281
|
+
name: 'canvas_auto_status',
|
|
5282
|
+
description: '自动创作总状态:开关是否开启、宿主多智能体能力、编剧室运行进度(阶段/日志)、免费段预算单(场/镜/秒/待调用次数/估算金额)、付费段进度与成片节点。【自动模式开场先调它】它决定你走全自动分支还是引导式工作坊。',
|
|
5283
|
+
parameters: { type: 'object', properties: {
|
|
5284
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5285
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5286
|
+
}, required: ['projectId'], additionalProperties: false },
|
|
5287
|
+
output: textOutput,
|
|
5288
|
+
timeoutMs: 15000,
|
|
5289
|
+
async execute(args) {
|
|
5290
|
+
const r = await methods.autoStatus(args);
|
|
5291
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '状态读取失败') };
|
|
5292
|
+
const lines = ['自动创作:' + (r.enabled ? '已开启' : '已关闭') + ' · 多智能体:' + (r.caps && r.caps.multiAgent ? '可用' : '不可用')];
|
|
5293
|
+
if (r.enabled) lines.push('【自动模式·硬规则】禁止调用 ask_user_question(任何理由);本轮必须 canvas_auto_start 启动编剧室,brief 不足由编剧室代拟 3 个方向并选定。');
|
|
5294
|
+
if (r.stage) lines.push('制作阶段:' + r.stage);
|
|
5295
|
+
if (r.run) {
|
|
5296
|
+
lines.push('编剧室:' + r.run.status + (r.run.phase ? '(' + r.run.phase + ')' : '') + (r.run.error ? ' · 错误:' + r.run.error : ''));
|
|
5297
|
+
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 : ''));
|
|
5298
|
+
if (r.run.boards && r.run.boards.length) lines.push('分镜:' + r.run.boards.map((b) => '场' + b.no + (b.gate ? '✅' : '⚠' + b.fails.length)).join(' '));
|
|
5299
|
+
if (r.run.paid) lines.push('付费段:' + r.run.paid + (r.run.paidPhase ? '(' + r.run.paidPhase + ')' : '') + (r.run.paidError ? ' · ' + r.run.paidError : ''));
|
|
5300
|
+
if (r.run.log && r.run.log.length) lines.push('最近:' + r.run.log[r.run.log.length - 1].summary);
|
|
5301
|
+
}
|
|
5302
|
+
if (r.approval) lines.push('批准:' + (r.approval.valid ? '有效(' + r.approval.quoteId + ')' : '无/已过期'));
|
|
5303
|
+
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') };
|
|
5304
|
+
},
|
|
5305
|
+
});
|
|
5306
|
+
reg({
|
|
5307
|
+
name: 'canvas_auto_start',
|
|
5308
|
+
description: '启动全自动创作免费段(零付费):自动打开画布 → 调研 → 编剧A/B 独立提案 → 互评 → 监制决策 → 设定集 → 剧本生成 → 按场拆分 → 逐场分镜表 → G2 校验 → 预算单。仅当自动创作开关已开启时可用。**自动模式下用户给出创意后直接调用它,不要逐步提问。**',
|
|
5309
|
+
parameters: { type: 'object', properties: {
|
|
5310
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5311
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5312
|
+
brief: { type: 'string', description: '一句话创意(拍什么/给谁看/什么情绪)——剧情走向的唯一源头' },
|
|
5313
|
+
}, required: ['projectId', 'brief'], additionalProperties: false },
|
|
5314
|
+
output: textOutput,
|
|
5315
|
+
timeoutMs: 30000,
|
|
5316
|
+
async execute(args) {
|
|
5317
|
+
try { await canvasOpen({ projectId: args.projectId, canvasId: args.canvasId }); } catch { /* 打开失败不阻塞启动 */ }
|
|
5318
|
+
const r = await methods.autoStart(args);
|
|
5319
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '启动失败') };
|
|
5320
|
+
return { ok: true, projectId: args.projectId, status: r.status, text: '🚀 免费段已启动(自动打开画布 + 调研/提案/互评/决策/剧本/分镜/预算单)。用 canvas_auto_status 查看进度。' };
|
|
5321
|
+
},
|
|
5322
|
+
});
|
|
5323
|
+
reg({
|
|
5324
|
+
name: 'canvas_auto_budget',
|
|
5325
|
+
description: '生成/查看免费段的预算单:场数、镜数、总秒数、待调用视频次数、配置单价时的估算金额。批准付费前必须先用它出单。',
|
|
5326
|
+
parameters: { type: 'object', properties: {
|
|
5327
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5328
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5329
|
+
unitPricePerSecond: { type: 'number', description: '可选:每秒单价(不传则用画布设置里的单价)' },
|
|
5330
|
+
}, required: ['projectId'], additionalProperties: false },
|
|
5331
|
+
output: textOutput,
|
|
5332
|
+
timeoutMs: 15000,
|
|
5333
|
+
async execute(args) {
|
|
5334
|
+
const r = await methods.autoQuote(args);
|
|
5335
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '预算单生成失败') };
|
|
5336
|
+
const lines = ['预算单 ' + r.quoteId, '场 ' + r.sceneCount + ' / 镜 ' + r.shotCount + ' / ' + r.totalSeconds + ' 秒 / 待调用 ' + r.videoCalls + ' 次'];
|
|
5337
|
+
if (r.estimatedCost != null) lines.push('估算金额:' + r.estimatedCost + '(单价 ' + r.unitPricePerSecond + '/秒)');
|
|
5338
|
+
lines.push('批准:调用 autoApprove 或在设置卡点「批准付费段」(必须带用户原话)');
|
|
5339
|
+
return { ok: true, quoteId: r.quoteId, budget: r, text: lines.join('\n') };
|
|
5340
|
+
},
|
|
5341
|
+
});
|
|
5342
|
+
reg({
|
|
5343
|
+
name: 'canvas_auto_generate',
|
|
5344
|
+
description: '付费段:仅在有有效批准后可用——逐分镜表创建视频节点并真实生成(按秒计费),失败重试 2 次,全部完成后创建「成片」节点。没有批准会被拒绝。',
|
|
5345
|
+
parameters: { type: 'object', properties: {
|
|
5346
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5347
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5348
|
+
}, required: ['projectId'], additionalProperties: false },
|
|
5349
|
+
output: textOutput,
|
|
5350
|
+
timeoutMs: 30000,
|
|
5351
|
+
async execute(args) {
|
|
5352
|
+
const r = await methods.autoGenerate(args);
|
|
5353
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '付费段启动失败') };
|
|
5354
|
+
return { ok: true, projectId: args.projectId, status: r.status, text: '🎬 付费段已启动(逐场建视频节点并生成,失败重试 2 次)。用 canvas_auto_status 查看进度。' };
|
|
5355
|
+
},
|
|
5356
|
+
});
|
|
5357
|
+
reg({
|
|
5358
|
+
name: 'canvas_auto_abort',
|
|
5359
|
+
description: '中止正在运行的自动创作(免费段或付费段),保留已产出内容(会议记录/设定集/节点)。',
|
|
5360
|
+
parameters: { type: 'object', properties: {
|
|
5361
|
+
projectId: { type: 'string', description: '项目 id' },
|
|
5362
|
+
canvasId: { type: 'string', description: '可选:画布 id(缺省 = 项目默认画布)' },
|
|
5363
|
+
}, required: ['projectId'], additionalProperties: false },
|
|
5364
|
+
output: textOutput,
|
|
5365
|
+
timeoutMs: 15000,
|
|
5366
|
+
async execute(args) {
|
|
5367
|
+
const r = await methods.autoAbort(args);
|
|
5368
|
+
if (!r.ok) return { ok: false, text: '❌ ' + (r.error || '中止失败') };
|
|
5369
|
+
return { ok: true, projectId: args.projectId, text: '⏹ 已中止(保留已产出内容)。' };
|
|
5370
|
+
},
|
|
5371
|
+
});
|
|
3859
5372
|
reg({
|
|
3860
5373
|
name: 'canvas_create_node',
|
|
3861
5374
|
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 里写内容,有上游时靠连线取。',
|
|
@@ -3884,6 +5397,10 @@ export function apply(ctx) {
|
|
|
3884
5397
|
timeoutMs: 30000,
|
|
3885
5398
|
async execute(args) {
|
|
3886
5399
|
const r = canvasCreateNode(args);
|
|
5400
|
+
if (r && r.ok === false && r.gate) {
|
|
5401
|
+
const det = r.fails ? '\n· ' + r.fails.join('\n· ') : '';
|
|
5402
|
+
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 : '') };
|
|
5403
|
+
}
|
|
3887
5404
|
const kindHint = r.type === 'image'
|
|
3888
5405
|
? '(图片节点:有 assetId 即资产;空节点在画布上点开生成面板写提示词后生成)'
|
|
3889
5406
|
: r.type === 'video'
|