@ninkch/dsh-infinite-canvas 0.19.19 → 0.19.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +9 -0
  2. package/README.zh-CN.md +9 -0
  3. package/assets/canvas-director/genres/absurd-parable.md +33 -35
  4. package/assets/canvas-director/genres/action-mission.md +36 -24
  5. package/assets/canvas-director/genres/adventure.md +34 -35
  6. package/assets/canvas-director/genres/broken-mirror-reunion.md +35 -77
  7. package/assets/canvas-director/genres/class-vertical.md +36 -36
  8. package/assets/canvas-director/genres/counterattack.md +35 -24
  9. package/assets/canvas-director/genres/county-drift.md +35 -35
  10. package/assets/canvas-director/genres/crime-police.md +36 -35
  11. package/assets/canvas-director/genres/family-melodrama.md +35 -35
  12. package/assets/canvas-director/genres/family-relation.md +38 -24
  13. package/assets/canvas-director/genres/fantasy.md +36 -38
  14. package/assets/canvas-director/genres/gambling-den.md +35 -35
  15. package/assets/canvas-director/genres/gunstandoff.md +35 -35
  16. package/assets/canvas-director/genres/hk-retro.md +35 -35
  17. package/assets/canvas-director/genres/identity-swap.md +37 -24
  18. package/assets/canvas-director/genres/institutional-eccentric.md +35 -35
  19. package/assets/canvas-director/genres/mo-lei-tau.md +36 -37
  20. package/assets/canvas-director/genres/modern-urban.md +34 -35
  21. package/assets/canvas-director/genres/multi-thread-caper.md +35 -35
  22. package/assets/canvas-director/genres/neon-dystopia.md +36 -35
  23. package/assets/canvas-director/genres/parent-child-secret.md +40 -75
  24. package/assets/canvas-director/genres/period-power-struggle.md +38 -24
  25. package/assets/canvas-director/genres/rebirth-transmigration.md +37 -24
  26. package/assets/canvas-director/genres/revenge-face-slap.md +38 -24
  27. package/assets/canvas-director/genres/shanhaijing-myth.md +85 -40
  28. package/assets/canvas-director/genres/slice-of-life.md +36 -24
  29. package/assets/canvas-director/genres/smalltown-uncanny.md +34 -35
  30. package/assets/canvas-director/genres/social-traverse.md +34 -35
  31. package/assets/canvas-director/genres/survival-fate.md +35 -35
  32. package/assets/canvas-director/genres/suspense-rule.md +38 -24
  33. package/assets/canvas-director/genres/system-flow.md +38 -24
  34. package/assets/canvas-director/genres/wasteland-chase.md +35 -35
  35. package/assets/canvas-director/genres/wealthy-romance.md +38 -24
  36. package/assets/canvas-director/genres/workplace-comedy.md +37 -24
  37. package/assets/canvas-director/genres/wuxia.md +35 -35
  38. package/assets/canvas-director/genres/xianxia-cultivation.md +38 -24
  39. package/assets/canvas-director/genres/youth-distance.md +35 -35
  40. package/assets/canvas-director/pack.js +3 -2
  41. package/assets/canvas-studio/SKILL.md +14 -0
  42. package/client.js +648 -41
  43. package/docs/UI-RULES.md +4 -0
  44. package/index.js +692 -18
  45. package/package.json +1 -1
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';
@@ -539,6 +539,11 @@ function dbAssetUpdate(id, patch) {
539
539
  * 引用计数回收(gcObjectIfUnreferenced)兜住,不需要独立的定期扫描入口。 */
540
540
 
541
541
  function readDocOrNull(id) {
542
+ // 工作区内嵌项目优先:文档在 <ws>/.infinite-canvas/,与数据根/SQLite 无关
543
+ const wsf = wsDocFile(id);
544
+ if (wsf) {
545
+ try { return JSON.parse(readFileSync(wsf, 'utf8')); } catch { return null; }
546
+ }
542
547
  if (sqlActive()) {
543
548
  const db = getDb();
544
549
  const row = db.prepare('SELECT doc FROM projects WHERE id = ?').get(id);
@@ -548,6 +553,8 @@ function readDocOrNull(id) {
548
553
  try { return JSON.parse(readFileSync(projectFile(id), 'utf8')); } catch { return null; }
549
554
  }
550
555
  function docExists(id) {
556
+ if (wsDocFile(id)) return !!readDocOrNull(id);
557
+ try { projectFile(id); } catch { return false; } // 非法 id(含路径逃逸段):一律视为不存在,不抛
551
558
  if (sqlActive()) {
552
559
  const db = getDb();
553
560
  return !!db.prepare('SELECT id FROM projects WHERE id = ?').get(id);
@@ -1116,6 +1123,363 @@ function sanitizeCanvases(list) {
1116
1123
  }
1117
1124
  return out.slice(0, 200);
1118
1125
  }
1126
+ // ---- 工作区内嵌项目(0.20.x):<工作区目录>/.infinite-canvas/ 即项目家目录 ----
1127
+ // 项目随工作区目录走(宿主侧 workspaceRegistry 发现):project.json / canvases/ / memory/ / bindings.json
1128
+ // 全部内嵌目录自包含。文档读写与数据根/SQLite 完全解耦(wsDocFile 分发);媒体仍走数据根管线
1129
+ //(ensureProjectFolder 统一登记媒体文件夹),拷工作区目录 = 带走全部设定/记忆/画布文档。
1130
+ const WS_APP_DIR = '.infinite-canvas';
1131
+ /** 工作区项目缓存:pid -> { pid, wsId, wsPath, home, doc };wsProjectsScan 负责刷新。 */
1132
+ const wsProjects = new Map();
1133
+ /** 扫描工作区注册表 list([{id,path,title,sessionIds}]),发现带 `.infinite-canvas/project.json` 标记的项目。
1134
+ * 每次全量重扫(代价 = 每工作区读一个小 JSON),标记消失/目录消失自然落榜。 */
1135
+ function wsProjectsScan(list) {
1136
+ const seen = Array.isArray(list) ? list : [];
1137
+ wsProjects.clear();
1138
+ for (const w of seen) {
1139
+ if (!w || typeof w.path !== 'string' || !w.path) continue;
1140
+ let doc = null;
1141
+ try {
1142
+ doc = JSON.parse(readFileSync(path.join(w.path, WS_APP_DIR, 'project.json'), 'utf8'));
1143
+ } catch { /* 无标记/损坏 → 不算项目 */ }
1144
+ if (!doc || typeof doc !== 'object' || !doc.id) continue;
1145
+ const pid = String(doc.id);
1146
+ wsProjects.set(pid, { pid, wsId: String(w.id || ''), wsPath: w.path, home: path.join(w.path, WS_APP_DIR), doc });
1147
+ }
1148
+ return [...wsProjects.values()];
1149
+ }
1150
+ /** 该 pid 是否工作区内嵌项目(按最近一次扫描缓存)。 */
1151
+ function isWsProject(pid) { return wsProjects.has(String(pid || '')); }
1152
+ /** 工作区项目家目录(<工作区>/.infinite-canvas);非工作区项目返回 null。 */
1153
+ function wsProjectHome(pid) {
1154
+ const r = wsProjects.get(String(pid || ''));
1155
+ return r ? r.home : null;
1156
+ }
1157
+ /** 工作区文档 id → 物理文件:项目文档 = project.json;子画布文档 = canvases/<cid>.json;非工作区项目返回 null。 */
1158
+ function wsDocFile(id) {
1159
+ const s = String(id || '');
1160
+ try { projectFile(s); } catch { return null; } // id 段合法性复用 projectFile 校验:封死 canvases/<cid> 路径逃逸(评审 I4)
1161
+ const ref = isCanvasDocId(s) ? splitCanvasDocId(s) : { projectId: s, canvasId: null };
1162
+ const home = wsProjectHome(ref.projectId);
1163
+ if (!home) return null;
1164
+ return ref.canvasId ? path.join(home, 'canvases', ref.canvasId + '.json') : path.join(home, 'project.json');
1165
+ }
1166
+ /** 工作区项目 → projectsList 条目(与数据根条目同形,另带 origin:'workspace' + wsId/wsPath)。 */
1167
+ function wsProjectListEntry(rec) {
1168
+ const d = rec.doc || {};
1169
+ const nodes = Object.values(d.nodes || {}).map((n) => ({
1170
+ id: n.id, type: normalizeNodeType(n.type), label: (n.data && n.data.label) || '',
1171
+ status: (n.data && n.data.status) || 'idle',
1172
+ x: Number(n.x) || 0, y: Number(n.y) || 0, w: Number(n.w) || 0, h: Number(n.h) || 0,
1173
+ }));
1174
+ return {
1175
+ id: d.id, name: d.name || rec.pid, createdAt: d.createdAt || 0, updatedAt: d.updatedAt || 0,
1176
+ source: d.source || 'agent', nodeIds: Object.keys(d.nodes || {}), nodes,
1177
+ tombstones: Array.isArray(d.tombstones) ? d.tombstones : [], bibleUpdatedAt: d.bibleUpdatedAt || 0,
1178
+ canvases: canvasRegistry(d), defaultCanvasName: defaultCanvasNameForApi(d),
1179
+ defaultCanvasDeleted: !defaultCanvasExists(d),
1180
+ origin: 'workspace', wsId: rec.wsId, wsPath: rec.wsPath,
1181
+ };
1182
+ }
1183
+ /** 删除工作区项目目录(.infinite-canvas 整目录);工作区目录本身不动。
1184
+ * watcher 只发现不创建 → 删除后不会复活,无需墓碑。 */
1185
+ function wsProjectRemove(pid) {
1186
+ const home = wsProjectHome(pid);
1187
+ if (!home) return false;
1188
+ try { rmSync(home, { recursive: true, force: true }); } catch { /* 目录被占用:标记已无效,后续扫描自然落榜 */ }
1189
+ wsProjects.delete(String(pid));
1190
+ return true;
1191
+ }
1192
+ /** 在工作区目录创建内嵌项目(RPC「建画布项目」/ 测试共用):默认画布「第1集」。仅显式路径调用。 */
1193
+ function wsProjectCreateAt(w) {
1194
+ const dir = path.join(String(w.path), WS_APP_DIR);
1195
+ try { mkdirSync(dir, { recursive: true }); } catch { /* 已存在 */ }
1196
+ const pid = 'ws' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
1197
+ const name = (path.basename(w.path) || '画布项目').replace(/\s+/g, ' ').trim().slice(0, 80) || '画布项目';
1198
+ const doc = {
1199
+ id: pid, name, createdAt: Date.now(), updatedAt: Date.now(), source: 'agent',
1200
+ nodes: {}, edges: [], view: { x: 60, y: 40, scale: 1 },
1201
+ defaultCanvasName: '第1集',
1202
+ };
1203
+ const rec = { pid, wsId: String(w.id || ''), wsPath: String(w.path), home: dir, doc };
1204
+ wsProjects.set(pid, rec); // 先登记再写:writeIcDoc 的 ws 分发靠 wsProjectHome 命中
1205
+ try {
1206
+ writeIcDoc(pid, doc); // ws 分发 → <dir>/project.json
1207
+ } catch (e) {
1208
+ wsProjects.delete(pid); // 写失败不留幽灵缓存
1209
+ throw e;
1210
+ }
1211
+ return rec;
1212
+ }
1213
+ /** 工作区注册表条目 → 已登记项目缓存记录(wsId/wsPath 双口径匹配)。 */
1214
+ function wsRecOf(w) {
1215
+ if (!w) return null;
1216
+ return [...wsProjects.values()].find((r) => r.wsId === String(w.id || '') || r.wsPath === w.path) || null;
1217
+ }
1218
+ /** watcher 单次 tick:**纯发现**——只扫描已带 `.infinite-canvas/project.json` 标记的工作区项目进缓存/列表。
1219
+ * 不自动建项目、不自动绑会话(0.20.x 口径修正):绑定必须是用户在 composer chip 里的显式动作,
1220
+ * 编码等普通任务的工作区零打扰。目录消失的标记自然读不到 → 自动落榜,无需特殊处理。 */
1221
+ function wsWatchTick(list) {
1222
+ if (!Array.isArray(list)) return { skipped: true };
1223
+ const scan = wsProjectsScan(list);
1224
+ return { skipped: false, discovered: scan.map((r) => r.pid) };
1225
+ }
1226
+ // ---- 项目记忆(0.20.x):每集画布一份记忆正文 + 项目级调度索引 ----
1227
+ // 落位:<项目家目录>/memory/index.json(索引:canvasId/标题/摘要/关键词/状态)+ memory/episodes/<canvasId>.md(正文)。
1228
+ // 项目家目录:工作区项目 = <ws>/.infinite-canvas;数据根项目 = <数据根>/projects/<项目文件夹>。
1229
+ // 世界观/风格在 bible(project.json),记忆只记「动态」:剧情决策/人物状态变化/伏笔账本。
1230
+ /** 项目家目录:记忆/绑定等派生文件的落点。
1231
+ * 工作区项目 = <ws>/.infinite-canvas;有数据根 = <数据根>/projects/<项目文件夹>;
1232
+ * 无数据根(IndexedDB 模式)= PROJECTS_DIR/<pid>/(记忆功能不因数据根缺席而缺席)。 */
1233
+ function projectHomeDir(pid) {
1234
+ const id = String(pid || '');
1235
+ const ws = wsProjectHome(id);
1236
+ if (ws) return ws;
1237
+ const root = dataRoot();
1238
+ if (root) {
1239
+ let entry = readDataRootMeta().projects.find((p) => p.id === id);
1240
+ if (!entry) {
1241
+ // 从未登记过媒体文件夹的老项目:按需登记(目录随之创建)
1242
+ try {
1243
+ const doc = readDocOrNull(id);
1244
+ const folder = ensureProjectFolder(id, (doc && doc.name) || id);
1245
+ if (folder) entry = { folder };
1246
+ } catch { /* 项目不存在等 → 走统一落点 */ }
1247
+ }
1248
+ return entry && entry.folder ? path.join(root, 'projects', entry.folder) : null;
1249
+ }
1250
+ try { projectFile(id); } catch { return null; } // 非法 id 拒绝(防路径逃逸)
1251
+ return path.join(PROJECTS_DIR, id);
1252
+ }
1253
+ const MEMORY_CAP = { title: 80, summary: 120, keywords: 10, keyword: 24 };
1254
+ /** 同项目写串行链:并发 memoryWrite 顺序落盘,互不覆盖。 */
1255
+ const memoryWriteChains = new Map();
1256
+ function memoryDirOf(pid) {
1257
+ const home = projectHomeDir(pid);
1258
+ return home ? path.join(home, 'memory') : null;
1259
+ }
1260
+ /** 读调度索引;缺失/损坏一律容错为空索引(写路径会重建)。 */
1261
+ function readMemoryIndex(pid) {
1262
+ const dir = memoryDirOf(pid);
1263
+ if (dir) {
1264
+ try {
1265
+ const m = JSON.parse(readFileSync(path.join(dir, 'index.json'), 'utf8'));
1266
+ if (m && typeof m === 'object' && Array.isArray(m.episodes)) return m;
1267
+ } catch { /* 缺失/损坏 → 重建 */ }
1268
+ }
1269
+ return { version: 1, updatedAt: 0, episodes: [] };
1270
+ }
1271
+ /** 原子写索引;覆盖前留一份 index.backup.json(上次良好状态)。 */
1272
+ function writeMemoryIndexAtomic(pid, index) {
1273
+ const dir = memoryDirOf(pid);
1274
+ if (!dir) return;
1275
+ mkdirSync(dir, { recursive: true });
1276
+ const f = path.join(dir, 'index.json');
1277
+ try { if (existsSync(f)) copyFileSync(f, path.join(dir, 'index.backup.json')); } catch { /* 备份失败不阻塞 */ }
1278
+ const tmp = f + '.' + process.pid + '.tmp';
1279
+ writeFileSync(tmp, JSON.stringify(index, null, 1), 'utf8');
1280
+ renameSync(tmp, f);
1281
+ }
1282
+ /** 写一集记忆:正文落 episodes/<canvasId>.md(有内容才写),索引条目 upsert(保序)。 */
1283
+ async function memoryWrite(pid, canvasId, patch) {
1284
+ const id = String(pid || '');
1285
+ const cid = normalizeCanvasId(canvasId);
1286
+ if (!id || !cid) return { ok: false, error: '缺少 projectId 或 canvasId' };
1287
+ try { projectFile(id); } catch { return { ok: false, error: '非法项目 id' }; }
1288
+ const p = patch || {};
1289
+ const rec = {
1290
+ canvasId: cid,
1291
+ title: String(p.title || '').trim().slice(0, MEMORY_CAP.title) || ('画布 ' + cid),
1292
+ summary: String(p.summary || '').trim().slice(0, MEMORY_CAP.summary),
1293
+ keywords: (Array.isArray(p.keywords) ? p.keywords : [])
1294
+ .map((k) => String(k || '').trim().slice(0, MEMORY_CAP.keyword)).filter(Boolean).slice(0, MEMORY_CAP.keywords),
1295
+ status: p.status === 'done' ? 'done' : 'drafting',
1296
+ updatedAt: Date.now(),
1297
+ };
1298
+ const body = String(p.body == null ? '' : p.body);
1299
+ const job = (memoryWriteChains.get(id) || Promise.resolve()).catch(() => {}).then(() => {
1300
+ const dir = memoryDirOf(id);
1301
+ if (!dir) return { ok: false, error: '项目家目录不可用(未设置数据根且非工作区项目)' };
1302
+ if (body.trim()) {
1303
+ const epDir = path.join(dir, 'episodes');
1304
+ try { mkdirSync(epDir, { recursive: true }); } catch { /* 已存在 */ }
1305
+ const f = path.join(epDir, cid + '.md');
1306
+ const tmp = f + '.' + process.pid + '.tmp';
1307
+ writeFileSync(tmp, body, 'utf8');
1308
+ renameSync(tmp, f);
1309
+ }
1310
+ const idx = readMemoryIndex(id);
1311
+ const i = idx.episodes.findIndex((e) => e && e.canvasId === cid);
1312
+ if (i >= 0) idx.episodes[i] = { ...idx.episodes[i], ...rec };
1313
+ else idx.episodes.push(rec);
1314
+ idx.version = 1;
1315
+ idx.updatedAt = Date.now();
1316
+ writeMemoryIndexAtomic(id, idx);
1317
+ return { ok: true, projectId: id, canvasId: cid, index: idx };
1318
+ });
1319
+ memoryWriteChains.set(id, job);
1320
+ return job;
1321
+ }
1322
+ /** 读记忆:无 canvasId 只回索引;有 canvasId 附该集正文(正文文件可独立于索引存在)。 */
1323
+ async function memoryRead(pid, canvasId) {
1324
+ const id = String(pid || '');
1325
+ const idx = readMemoryIndex(id);
1326
+ const cid = normalizeCanvasId(canvasId);
1327
+ let episode = null;
1328
+ if (cid) {
1329
+ const dir = memoryDirOf(id);
1330
+ let body = null;
1331
+ if (dir) {
1332
+ try { body = readFileSync(path.join(dir, 'episodes', cid + '.md'), 'utf8'); } catch { /* 无正文 */ }
1333
+ }
1334
+ const meta = idx.episodes.find((e) => e && e.canvasId === cid) || null;
1335
+ if (meta || body != null) {
1336
+ episode = {
1337
+ canvasId: cid,
1338
+ title: meta ? meta.title : '', summary: meta ? meta.summary : '',
1339
+ keywords: meta ? meta.keywords || [] : [], status: meta ? meta.status || 'drafting' : 'drafting',
1340
+ updatedAt: meta ? meta.updatedAt || 0 : 0,
1341
+ body: body == null ? '' : body,
1342
+ };
1343
+ }
1344
+ }
1345
+ return { ok: true, projectId: id, index: idx, episode };
1346
+ }
1347
+ /** 会话 → 绑定 {projectId, canvasId}:扫**全部项目**(工作区内嵌 + 数据根)的绑定表。 */
1348
+ function toolBindingForSession(sid) {
1349
+ const s = String(sid || '');
1350
+ if (!s) return null;
1351
+ for (const pid of allBoundProjectIds()) {
1352
+ let data = null;
1353
+ try { data = bindingsRead(pid); } catch { continue; }
1354
+ const hit = data.bindings.find((b) => b && b.sessionId === s);
1355
+ if (hit) return { projectId: pid, canvasId: hit.canvasId == null ? null : hit.canvasId };
1356
+ }
1357
+ return null;
1358
+ }
1359
+ /** 可承载绑定的项目 id 全集:工作区内嵌项目 + 数据根项目(绑定可跨来源,菜单列表同口径)。 */
1360
+ function allBoundProjectIds() {
1361
+ const ids = new Set(wsProjects.keys());
1362
+ try { for (const p of projectsListDataRoot()) ids.add(String(p.id)); } catch { /* 无数据根:只留工作区项目 */ }
1363
+ return [...ids];
1364
+ }
1365
+ /** 文档 → 画布清单(默认画布 id=null 在前)。 */
1366
+ function canvasesOfDoc(doc) {
1367
+ const list = defaultCanvasExists(doc) ? [{ id: null, name: defaultCanvasNameOf(doc) }] : [];
1368
+ for (const c of canvasRegistry(doc)) list.push({ id: c.id, name: c.name });
1369
+ return list;
1370
+ }
1371
+ /** 绑定的人类可读标签「项目名·画布名」(拒绝文案用)。 */
1372
+ function bindingLabelOf(b) {
1373
+ try {
1374
+ const doc = readDocOrNull(b.projectId) || {};
1375
+ const cid = b.canvasId == null ? null : b.canvasId;
1376
+ let cname = '默认画布';
1377
+ if (cid != null) {
1378
+ const hit = canvasRegistry(doc).find((c) => c.id === cid);
1379
+ cname = (hit && hit.name) || String(cid);
1380
+ } else if (defaultCanvasExists(doc)) {
1381
+ cname = defaultCanvasNameOf(doc);
1382
+ }
1383
+ return (doc.name || String(b.projectId || '')) + '·' + cname;
1384
+ } catch { return String(b.projectId || ''); }
1385
+ }
1386
+ /** 防御式嗅探工具执行身份:不同宿主版本 exec.agent 携带的会话字段可能不同
1387
+ * (sessionId / session / id;cordis branded id 可能包一层 {value})。拿不到 → null(走显式参数路径)。 */
1388
+ function toolExecSessionId(exec) {
1389
+ try {
1390
+ const a = exec && exec.agent;
1391
+ if (!a || typeof a !== 'object') return null;
1392
+ const candidates = [a.sessionId, a.session, a.id];
1393
+ if (a.ctx && typeof a.ctx === 'object') candidates.push(a.ctx.sessionId, a.ctx.session);
1394
+ for (const v of candidates) {
1395
+ if (typeof v === 'string' && v) return v;
1396
+ if (v && typeof v === 'object' && typeof v.value === 'string' && v.value) return v.value;
1397
+ }
1398
+ } catch { /* 嗅探失败 → null */ }
1399
+ return null;
1400
+ }
1401
+ // ---- 会话↔画布绑定(0.20.x):一会话一画布、一画布一会话 ----
1402
+ // 落位:<项目家目录>/bindings.json:{ version:1, updatedAt, bindings:[{ sessionId, canvasId, boundAt }] }
1403
+ // 占用判定:目标画布已被其他会话绑定时,aliveFn(占用者) 为真 → 拒绝(occupied);为假(会话已删的孤儿)→ 覆盖。
1404
+ /** 读绑定文件;缺失/损坏容错为空。 */
1405
+ function bindingsRead(pid) {
1406
+ const id = String(pid || '');
1407
+ try { projectFile(id); } catch { return { version: 1, updatedAt: 0, bindings: [] }; }
1408
+ const home = projectHomeDir(id);
1409
+ if (!home) return { version: 1, updatedAt: 0, bindings: [] };
1410
+ try {
1411
+ const b = JSON.parse(readFileSync(path.join(home, 'bindings.json'), 'utf8'));
1412
+ if (b && typeof b === 'object' && Array.isArray(b.bindings)) return b;
1413
+ } catch { /* 缺失/损坏 → 空 */ }
1414
+ return { version: 1, updatedAt: 0, bindings: [] };
1415
+ }
1416
+ function writeBindingsAtomic(pid, data) {
1417
+ const home = projectHomeDir(pid);
1418
+ if (!home) return false;
1419
+ try { mkdirSync(home, { recursive: true }); } catch { /* 已存在 */ }
1420
+ const f = path.join(home, 'bindings.json');
1421
+ const tmp = f + '.' + process.pid + '.tmp';
1422
+ writeFileSync(tmp, JSON.stringify(data, null, 1), 'utf8');
1423
+ renameSync(tmp, f);
1424
+ return true;
1425
+ }
1426
+ /** 绑定会话到画布(canvasId=null = 默认画布)。一会话一画布(换绑移除旧条目);一画布一会话。 */
1427
+ function bindingSetSync(pid, sessionId, canvasId, aliveFn) {
1428
+ const id = String(pid || '');
1429
+ const sid = String(sessionId || '').trim();
1430
+ let cid = null;
1431
+ try { cid = normalizeCanvasId(canvasId); } catch { return { ok: false, error: '非法画布 id' }; }
1432
+ if (!id || !sid) return { ok: false, error: '缺少 projectId 或 sessionId' };
1433
+ try { projectFile(id); } catch { return { ok: false, error: '非法项目 id' }; }
1434
+ const projectDoc = readDocOrNull(id);
1435
+ if (!projectDoc) return { ok: false, error: '项目不存在:' + id };
1436
+ if (cid) {
1437
+ if (!canvasRegistry(projectDoc).some((c) => c.id === cid)) return { ok: false, error: '画布不存在:' + cid };
1438
+ } else if (!defaultCanvasExists(projectDoc)) {
1439
+ return { ok: false, error: '默认画布已删除:请指定 canvasId' };
1440
+ }
1441
+ const alive = typeof aliveFn === 'function' ? aliveFn : () => true;
1442
+ const data = bindingsRead(id);
1443
+ const others = data.bindings.filter((b) => b && b.sessionId !== sid);
1444
+ const mine = data.bindings.find((b) => b && b.sessionId === sid);
1445
+ const occupant = others.find((b) => (b.canvasId || null) === cid);
1446
+ if (occupant && alive(occupant.sessionId)) {
1447
+ return { ok: false, occupied: true, by: occupant.sessionId, error: '该画布已绑定其他会话' };
1448
+ }
1449
+ // 会话全局唯一绑定(评审 I3):会话改绑本项目时,清掉它在**其他任何项目**(含数据根)里的绑定——
1450
+ // 「一会话一画布」是全局约束,否则会话感知默认值可能落到错误项目且 agent 无感知。
1451
+ for (const otherPid of allBoundProjectIds()) {
1452
+ if (otherPid === id) continue;
1453
+ let ob = null;
1454
+ try { ob = bindingsRead(otherPid); } catch { continue; }
1455
+ const kept = ob.bindings.filter((b) => b && b.sessionId !== sid);
1456
+ if (kept.length !== ob.bindings.length) {
1457
+ writeBindingsAtomic(otherPid, { ...ob, updatedAt: Date.now(), bindings: kept });
1458
+ }
1459
+ }
1460
+ const next = {
1461
+ version: 1,
1462
+ updatedAt: Date.now(),
1463
+ bindings: others.filter((b) => b !== occupant).concat([{ sessionId: sid, canvasId: cid, boundAt: Date.now() }]),
1464
+ };
1465
+ writeBindingsAtomic(id, next);
1466
+ return { ok: true, projectId: id, sessionId: sid, canvasId: cid, replaced: !!(mine || occupant) };
1467
+ }
1468
+ /** 异步包装(watcher 用同步核心以准确回报;RPC 走此包装)。 */
1469
+ async function bindingSet(pid, sessionId, canvasId, aliveFn) {
1470
+ return bindingSetSync(pid, sessionId, canvasId, aliveFn);
1471
+ }
1472
+ /** 解绑会话(幂等:无绑定返回 removed=false)。显式解绑即持久——watcher 只发现不绑定,不会绑回。 */
1473
+ async function bindingClear(pid, sessionId) {
1474
+ const id = String(pid || '');
1475
+ const sid = String(sessionId || '').trim();
1476
+ if (!id || !sid) return { ok: false, error: '缺少 projectId 或 sessionId' };
1477
+ const data = bindingsRead(id);
1478
+ const kept = data.bindings.filter((b) => b && b.sessionId !== sid);
1479
+ const removed = kept.length < data.bindings.length;
1480
+ if (removed) writeBindingsAtomic(id, { version: 1, updatedAt: Date.now(), bindings: kept });
1481
+ return { ok: true, removed };
1482
+ }
1119
1483
  // ---- 默认画布(canvasId=null):名字存项目文档 defaultCanvasName;删除后 defaultCanvasDeleted=true ----
1120
1484
  const DEFAULT_CANVAS_NAME = '默认画布';
1121
1485
  /** 默认画布名:缺省 '默认画布'(旧项目无该字段 → 零迁移)。 */
@@ -1134,7 +1498,7 @@ function allCanvasNames(projectDoc) {
1134
1498
  const names = defaultCanvasExists(projectDoc) ? [defaultCanvasNameOf(projectDoc)] : [];
1135
1499
  return names.concat(canvasRegistry(projectDoc).map((c) => c.name));
1136
1500
  }
1137
- function projectsList() {
1501
+ function projectsListDataRoot() {
1138
1502
  if (sqlActive()) {
1139
1503
  const db = getDb();
1140
1504
  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 +1545,11 @@ function projectsList() {
1181
1545
  }
1182
1546
  return list.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
1183
1547
  }
1548
+ /** 项目总列表 = 工作区内嵌项目 + 数据根项目,按更新时间合并排序(工作区缓存由 wsProjectsScan 刷新)。 */
1549
+ function projectsList() {
1550
+ const ws = [...wsProjects.values()].map(wsProjectListEntry);
1551
+ return ws.concat(projectsListDataRoot()).sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
1552
+ }
1184
1553
  async function projectsPut(args) {
1185
1554
  const id = String((args && args.id) || '');
1186
1555
  // 项目删除墓碑(长效):删除后迟到的全量推送(450ms 防抖竞速 / 启动 pushAllProjectsToHost 快照)
@@ -1462,7 +1831,11 @@ function setDataRoot(raw) {
1462
1831
  async function projectsDelete(args) {
1463
1832
  const id = String((args && args.id) || '');
1464
1833
  let cleanup = null;
1465
- if (sqlActive()) {
1834
+ if (isWsProject(id)) {
1835
+ // 工作区内嵌项目:删 .infinite-canvas 整目录(工作区目录本身不动),并清数据根媒体文件夹
1836
+ cleanup = { ws: wsProjectRemove(id) };
1837
+ try { removeDataRootProject(id); } catch { /* 媒体清理失败不影响删除 */ }
1838
+ } else if (sqlActive()) {
1466
1839
  // BLK-01:行 + FTS + 资产文件 + 镜像目录,一处收口(与 canvasDeleteProject 共用同一实现)
1467
1840
  cleanup = sqlDeleteProjectRows(getDb(), id, dataRoot());
1468
1841
  } else {
@@ -1839,30 +2212,35 @@ function canvasWriteNode(args) {
1839
2212
  }
1840
2213
  /** 读取项目文档:把"文件不存在/内容损坏"变成用户和模型都读得懂的报错(不泄漏绝对路径)。 */
1841
2214
  function readDoc(id) {
1842
- if (sqlActive()) {
1843
- const doc = readDocOrNull(id);
1844
- if (!doc) throw new Error('项目不存在:' + id + '(先用 canvas_list_projects 查看可用项目 id)');
2215
+ const doc = readDocOrNull(id);
2216
+ if (doc) {
1845
2217
  // 旧项目兼容:读入即归一旧节点类型(image-gen/image-asset → image,video-gen/video-asset → video)
1846
2218
  return normalizeDocNodes(doc);
1847
2219
  }
1848
- const f = projectFile(id);
1849
- let raw;
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 {
2220
+ // 文件模式区分「不存在」与「损坏」(损坏给重建提示);SQL/工作区侧统一按不存在处理
2221
+ if (!sqlActive() && !wsDocFile(id) && existsSync(projectFile(id))) {
1858
2222
  throw new Error('项目文件损坏,无法解析:' + id + '(可考虑重建该项目)');
1859
2223
  }
2224
+ throw new Error('项目不存在:' + id + '(先用 canvas_list_projects 查看可用项目 id)');
1860
2225
  }
1861
2226
  /** 原子写项目/画布文档:SQL 模式走单行事务;文件模式先写临时文件再改名,避免半写导致项目"消失"。
1862
2227
  * 子画布文档(id 含 __cv__)不重复登记项目文件夹、不镜像 project.json——项目级 meta 只属于默认画布行。 */
1863
2228
  function writeIcDoc(id, doc) {
1864
2229
  const canvasRef = splitCanvasDocId(id);
1865
2230
  const isCanvas = isCanvasDocId(id);
2231
+ // 工作区内嵌项目:文档直接落 <ws>/.infinite-canvas/(原子写);不进 SQLite、不镜像数据根。
2232
+ // 项目级文档顺带在数据根登记媒体文件夹(媒体仍走数据根管线),失败不阻塞。
2233
+ const wsf = wsDocFile(id);
2234
+ if (wsf) {
2235
+ try { mkdirSync(path.dirname(wsf), { recursive: true }); } catch { /* 目录已存在 */ }
2236
+ const tmp = wsf + '.' + process.pid + '.tmp';
2237
+ writeFileSync(tmp, JSON.stringify(doc, null, 1), 'utf8');
2238
+ renameSync(tmp, wsf);
2239
+ if (!isCanvas) {
2240
+ try { ensureProjectFolder(canvasRef.projectId, (doc && doc.name) || canvasRef.projectId); } catch { /* 媒体文件夹登记失败不阻塞文档 */ }
2241
+ }
2242
+ return;
2243
+ }
1866
2244
  if (sqlActive()) {
1867
2245
  const db = getDb();
1868
2246
  db.prepare(`INSERT INTO projects (id, name, created_at, updated_at, bible_updated_at, summary, tombstones, doc)
@@ -1961,6 +2339,18 @@ function deleteCanvasDocsForProject(projectId) {
1961
2339
  const pid = String(projectId || '');
1962
2340
  if (!pid) return 0;
1963
2341
  let removed = 0;
2342
+ // 工作区内嵌项目:清 <home>/canvases/ 目录
2343
+ const home = wsProjectHome(pid);
2344
+ if (home) {
2345
+ const dir = path.join(home, 'canvases');
2346
+ let files = [];
2347
+ try { files = readdirSync(dir); } catch { return 0; }
2348
+ for (const f of files) {
2349
+ if (!f.endsWith('.json')) continue;
2350
+ try { unlinkSync(path.join(dir, f)); removed++; } catch { /* 文件占用/已删 */ }
2351
+ }
2352
+ return removed;
2353
+ }
1964
2354
  if (sqlActive()) {
1965
2355
  try {
1966
2356
  const db = getDb();
@@ -2932,7 +3322,7 @@ async function updateInstall() {
2932
3322
  export const inject = ['webServer', 'tools'];
2933
3323
 
2934
3324
  // 仅供诊断 / 自动化测试(不属于 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 };
3325
+ export const _internals = { THUMB_MAX_SIDE, thumbRelOf, isDerivedMedia, updateCheck, updateInstall, npmLatestVersion, cmpVer, findPnpm, NPM_REGISTRIES, pickUpdateRegistry, registryCacheValid, pnpmAddArgs, getProfileDir: () => PROFILE_DIR, getVersion: () => VERSION, dataRoot, setDataRoot, dataRootMigrate, dataRootImport, ensureProjectFolder, physicalRel, mirrorProjectToDataRoot, writeAssetIndex, removeAssetIndexEntry, readDataRootMeta, removeDataRootProject, sqlDeleteProjectRows, deletedProjectIds, addDeletedProjectId, clearDeletedProjectId, fetchProxyForward, storyboardConsistencyWarnings, readAssetIndexNames, safeJoin, mimeOf, pipeFile, getIcConfigPath: () => CONFIG_PATH, canvasCreateProject, canvasWriteNode, canvasConnect, canvasDeleteProject, canvasDeleteNode, canvasRunNode, canvasNodeStatus, canvasGetBible, canvasUpdateBible, canvasCreateNode, canvasOpen, canvasesList, canvasCreate, canvasRename, canvasDelete, canvasDocId, isCanvasDocId, splitCanvasDocId, normalizeCanvasId, canvasRegistry, sanitizeCanvases, wsProjectsScan, isWsProject, wsProjectHome, wsWatchTick, wsProjectCreateAt, projectHomeDir, memoryRead, memoryWrite, bindingsRead, bindingSet, bindingClear, readCanvasDoc, writeCanvasDoc, deleteCanvasDocsForProject, projectsList, projectsPut, projectsGet, projectsDelete, projectsSync, sqliteAvailable: () => !!SQLITE, getDb, closeDb, dbAssetsList, dbAssetsGet, dbAssetNames, dbAssetCreate, dbAssetUpdate, dbAssetDelete, objectAbsFor, ftsReconcile, readDocOrNull, docExists, sqlActive, rpcMethods: () => _rpcMethods, canvasUpdateNode, canvasGenerateNode };
2936
3326
 
2937
3327
  function resolveModel(providers, want) {
2938
3328
  const byProvider = want && want.provider
@@ -3093,6 +3483,21 @@ export function apply(ctx) {
3093
3483
  return _directorEngine;
3094
3484
  };
3095
3485
 
3486
+ // ---- 会话↔画布绑定:会话所在工作区解析(ctx 闭包内:需要 workspaceRegistry 服务)----
3487
+ /** 解析 sessionId 所在工作区与活会话判定;老宿主无 workspaceRegistry → supported:false(全链降级)。 */
3488
+ const wsSessionContext = (sessionId) => {
3489
+ let reg = null;
3490
+ try { reg = ctx.get && ctx.get('workspaceRegistry'); } catch { reg = null; }
3491
+ const list = reg && typeof reg.list === 'function' ? reg.list() : null;
3492
+ if (!Array.isArray(list)) return { supported: false, list: null, ws: null, isAlive: () => true };
3493
+ const sid = String(sessionId || '');
3494
+ const ws = list.find((w) => w && Array.isArray(w.sessionIds) && w.sessionIds.map(String).includes(sid)) || null;
3495
+ const isAlive = (t) => list.some((w) => w && Array.isArray(w.sessionIds) && w.sessionIds.map(String).includes(String(t)));
3496
+ return { supported: true, list, ws, isAlive };
3497
+ };
3498
+ /** 工作区注册表条目的对外视图(不泄漏内部字段)。 */
3499
+ const wsView = (w) => ({ id: w && w.id, path: w && w.path, title: (w && w.title) || '' });
3500
+
3096
3501
  const methods = {
3097
3502
  async ping() { return { ok: true, version: VERSION }; },
3098
3503
  async llmOptions() { return listLlmOptions(); },
@@ -3393,10 +3798,154 @@ export function apply(ctx) {
3393
3798
  text: String(text ?? ((def && typeof def === 'object') ? JSON.stringify(def) : '')).slice(0, 80000),
3394
3799
  };
3395
3800
  },
3801
+ // ---- 会话↔画布绑定 RPC(0.20.x):composer 画布选择器与画布面板跟随的数据面 ----
3802
+ /** 绑定能力探针:客户端用它识别「宿主进程仍是旧版」(旧宿主无此方法 → 返回 400 → 客户端提示重启)。 */
3803
+ async bindingCapabilities() {
3804
+ return { ok: true, rev: 2, anyProject: true };
3805
+ },
3806
+ async sessionBindingGet(args) {
3807
+ const sid = String((args && args.sessionId) || '');
3808
+ if (!sid) return { ok: false, error: '缺少 sessionId' };
3809
+ const sc = wsSessionContext(sid);
3810
+ if (!sc.supported) return { ok: true, supported: false };
3811
+ // 绑定查找是**全局**的(工作区内嵌 + 数据根项目都可被绑定):先找会话现绑的项目;
3812
+ // 未绑定时再退回会话所在工作区项目(仅供上下文/画布清单,不产生绑定)。
3813
+ const boundHit = toolBindingForSession(sid);
3814
+ let pid = boundHit ? boundHit.projectId : null;
3815
+ if (!pid && sc.ws) {
3816
+ let rec = wsRecOf(sc.ws);
3817
+ if (!rec && sc.list) {
3818
+ // watcher 可能还没轮到:按**完整** registry 补扫一次(单工作区补扫会清掉其他工作区缓存)
3819
+ wsProjectsScan(sc.list);
3820
+ rec = wsRecOf(sc.ws);
3821
+ }
3822
+ if (rec) pid = rec.pid;
3823
+ }
3824
+ if (!pid) return { ok: true, supported: true, workspace: sc.ws ? wsView(sc.ws) : null, project: null, binding: null, canvasId: null, canvases: [], occupied: {} };
3825
+ const data = bindingsRead(pid);
3826
+ const binding = boundHit ? (data.bindings.find((b) => b && b.sessionId === sid) || null) : null;
3827
+ const pdoc = readDocOrNull(pid) || {};
3828
+ const canvases = canvasesOfDoc(pdoc);
3829
+ const occupied = {};
3830
+ for (const b of data.bindings) if (b && b.sessionId !== sid && b.canvasId) occupied[b.canvasId] = b.sessionId;
3831
+ return {
3832
+ ok: true, supported: true,
3833
+ workspace: sc.ws ? wsView(sc.ws) : null,
3834
+ project: { id: pid, name: pdoc.name || pid },
3835
+ binding: binding ? { canvasId: binding.canvasId, boundAt: binding.boundAt || 0 } : null,
3836
+ canvasId: binding ? binding.canvasId : null,
3837
+ defaultCanvasName: defaultCanvasNameForApi(pdoc),
3838
+ canvases, occupied,
3839
+ };
3840
+ },
3841
+ async sessionBindingSet(args) {
3842
+ const sid = String((args && args.sessionId) || '');
3843
+ if (!sid) return { ok: false, error: '缺少 sessionId' };
3844
+ const sc = wsSessionContext(sid);
3845
+ if (!sc.supported) return { ok: false, unsupported: true, error: '当前宿主无工作区能力,无法绑定画布' };
3846
+ let pid = String((args && args.projectId) || '');
3847
+ if (!pid) {
3848
+ if (!sc.ws) return { ok: false, error: '会话不在任何工作区,无法解析项目' };
3849
+ const rec = wsRecOf(sc.ws);
3850
+ if (!rec) return { ok: false, error: '该工作区还没有画布项目' };
3851
+ pid = rec.pid;
3852
+ }
3853
+ // 项目必须是真实存在的画布项目(工作区内嵌或数据根均可);存在性由 bindingSet 校验
3854
+ const alive = (t) => sc.isAlive(t);
3855
+ return bindingSet(pid, sid, (args && args.canvasId) ?? null, alive);
3856
+ },
3857
+ async sessionBindingClear(args) {
3858
+ const sid = String((args && args.sessionId) || '');
3859
+ if (!sid) return { ok: false, error: '缺少 sessionId' };
3860
+ const sc = wsSessionContext(sid);
3861
+ if (!sc.supported) return { ok: false, unsupported: true, error: '当前宿主无工作区能力' };
3862
+ let pid = String((args && args.projectId) || '');
3863
+ if (!pid) {
3864
+ // 绑定查找是全局的:先找会话**实际绑定**的项目(绑定可指向数据根老项目)
3865
+ const hit = toolBindingForSession(sid);
3866
+ if (hit) pid = hit.projectId;
3867
+ }
3868
+ if (!pid && sc.ws) {
3869
+ const rec = wsRecOf(sc.ws);
3870
+ if (rec) pid = rec.pid;
3871
+ }
3872
+ if (!pid) return { ok: true, removed: false };
3873
+ return bindingClear(pid, sid);
3874
+ },
3875
+ /** 可绑定的项目清单(画布选择器未绑定态用):工作区内嵌 + 数据根混排,按更新时间倒序,每项带画布清单。 */
3876
+ async bindableProjects() {
3877
+ const out = [];
3878
+ try {
3879
+ for (const rec of wsProjects.values()) {
3880
+ const doc = readDocOrNull(rec.pid) || {};
3881
+ out.push({
3882
+ id: rec.pid, name: doc.name || rec.pid, origin: 'workspace',
3883
+ updatedAt: doc.updatedAt || 0, canvases: canvasesOfDoc(doc),
3884
+ });
3885
+ }
3886
+ } catch { /* 单个项目读取失败跳过 */ }
3887
+ try {
3888
+ for (const p of projectsListDataRoot()) {
3889
+ if (wsProjects.has(p.id)) continue;
3890
+ const canvases = (p.defaultCanvasDeleted ? [] : [{ id: null, name: p.defaultCanvasName || '默认画布' }])
3891
+ .concat((p.canvases || []).map((c) => ({ id: c.id, name: c.name })));
3892
+ out.push({ id: p.id, name: p.name, origin: 'dataRoot', updatedAt: p.updatedAt || 0, canvases });
3893
+ }
3894
+ } catch { /* 无数据根:仅工作区项目 */ }
3895
+ out.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0));
3896
+ return { ok: true, projects: out.slice(0, 100) };
3897
+ },
3898
+ async workspaceProjectCreate(args) { const sid = String((args && args.sessionId) || '');
3899
+ if (!sid) return { ok: false, error: '缺少 sessionId' };
3900
+ const sc = wsSessionContext(sid);
3901
+ if (!sc.supported) return { ok: false, unsupported: true, error: '当前宿主无工作区能力' };
3902
+ if (!sc.ws) return { ok: false, error: '会话不在任何工作区(仅会话无法挂画布项目)' };
3903
+ let rec = wsRecOf(sc.ws);
3904
+ let createdNow = false;
3905
+ if (!rec && sc.list) {
3906
+ wsProjectsScan(sc.list); // 完整补扫(语义同上:不清其他工作区的账)
3907
+ rec = wsRecOf(sc.ws);
3908
+ }
3909
+ if (!rec) { rec = wsProjectCreateAt(sc.ws); createdNow = true; }
3910
+ const name = String((args && args.name) || '').trim();
3911
+ if (createdNow && name) {
3912
+ try { patchProjectDoc(rec.pid, { name: name.slice(0, 80) }); } catch { /* 改名失败不阻塞 */ }
3913
+ }
3914
+ // 只在**新建**时自动绑默认画布(复用既有项目时不强行绑定:绑定走选择器,避免占用冲突)
3915
+ let bound = null;
3916
+ if (createdNow) bound = await bindingSet(rec.pid, sid, null, sc.isAlive);
3917
+ return {
3918
+ ok: true, projectId: rec.pid, created: createdNow,
3919
+ bound: !!(bound && bound.ok), occupied: !!(bound && bound.occupied),
3920
+ bindError: bound && !bound.ok ? (bound.error || null) : null,
3921
+ };
3922
+ },
3923
+ async memoryGet(args) {
3924
+ return memoryRead(args && args.projectId, args && args.canvasId);
3925
+ },
3926
+ async memoryPut(args) {
3927
+ return memoryWrite(args && args.projectId, args && args.canvasId, args || {});
3928
+ },
3396
3929
 
3397
3930
  };
3398
3931
 
3399
3932
  const toolDisposers = [];
3933
+ // 工作区 watcher:5s 轮询 workspaceRegistry(老宿主无该服务 → list 不可得 → tick 直接跳过)。
3934
+ // 不把 workspaceRegistry 放进 export const inject:cordis 的 inject 语义是「服务不存在则插件挂起等待」,
3935
+ // 老宿主会让我们整个插件起不来——防御式 get + 轮询才是可降级的接法。
3936
+ ctx.effect(() => {
3937
+ const tick = () => {
3938
+ try {
3939
+ const reg = ctx.get && ctx.get('workspaceRegistry');
3940
+ const list = reg && typeof reg.list === 'function' ? reg.list() : null;
3941
+ wsWatchTick(list);
3942
+ } catch { /* registry 漂移/服务缺失 → 下轮再试 */ }
3943
+ };
3944
+ tick(); // 启动即扫一次(工作区项目立即可见,不等首个 5s)
3945
+ const timer = setInterval(tick, 5000);
3946
+ if (timer && typeof timer.unref === 'function') timer.unref(); // 不阻塞进程退出
3947
+ return () => clearInterval(timer);
3948
+ }, 'infinite-canvas: workspace watcher');
3400
3949
  try {
3401
3950
  if (ctx.tools && typeof ctx.tools.register === 'function') {
3402
3951
  /** 深度剥掉 undefined 值:DSH 对工具结果做"无损 JSON"校验(snapshotJsonValue),
@@ -3417,7 +3966,43 @@ export function apply(ctx) {
3417
3966
  const reg = (def) => {
3418
3967
  try {
3419
3968
  const inner = def.execute;
3420
- def.execute = async (args, exec) => stripUndefined(await inner(args, exec));
3969
+ // 会话绑定(0.20.x):绑定会话的 agent 被**代码级锁死**在本集画布——
3970
+ // ① projectId/canvasId 缺省 → 自动注入绑定值;
3971
+ // ② 显式传其他项目/画布(含同项目其他画布与默认画布)→ 直接拒绝(locked),文案指引先解绑;
3972
+ // ③ 未绑定会话不受任何限制(编码等普通任务零打扰)。
3973
+ // 只对 schema 声明了该参数的工具生效(additionalProperties:false 的工具不能多塞键);
3974
+ // 嗅探失败(宿主不带会话身份)静默回退旧行为。
3975
+ const propDefs = (def.parameters && def.parameters.properties) || null;
3976
+ const allowProject = !!(propDefs && Object.prototype.hasOwnProperty.call(propDefs, 'projectId'));
3977
+ const allowCanvas = !!(propDefs && Object.prototype.hasOwnProperty.call(propDefs, 'canvasId'));
3978
+ def.execute = async (args, exec) => {
3979
+ let a = args;
3980
+ try {
3981
+ const sid = toolExecSessionId(exec);
3982
+ if (sid && (allowProject || allowCanvas)) {
3983
+ const b = toolBindingForSession(sid);
3984
+ if (b) {
3985
+ a = (args && typeof args === 'object' && !Array.isArray(args)) ? args : {};
3986
+ const wantPid = b.projectId == null ? null : String(b.projectId);
3987
+ const wantCid = b.canvasId == null ? null : String(b.canvasId);
3988
+ const deny = (what) => {
3989
+ const label = bindingLabelOf(b);
3990
+ return stripUndefined({
3991
+ ok: false,
3992
+ locked: true,
3993
+ text: '本会话已绑定画布工作台「' + label + '」,代码级限制:' + what
3994
+ + '。一个会话只允许操作自己绑定的那一张画布;如需操作其他画布/项目,请先在对话输入行的画布选择器里解绑。',
3995
+ });
3996
+ };
3997
+ if (allowProject && a.projectId != null && String(a.projectId) !== wantPid) return deny('禁止跨项目操作');
3998
+ if (allowCanvas && a.canvasId != null && String(a.canvasId) !== wantCid) return deny('禁止跨画布操作(含同项目其他画布与默认画布)');
3999
+ if (allowProject && a.projectId == null && wantPid != null) a.projectId = b.projectId;
4000
+ if (allowCanvas && a.canvasId == null && wantCid != null) a.canvasId = b.canvasId;
4001
+ }
4002
+ }
4003
+ } catch { /* 默认解析失败 → 原参数路径 */ }
4004
+ return stripUndefined(await inner(a, exec));
4005
+ };
3421
4006
  toolDisposers.push(ctx.tools.register(def));
3422
4007
  } catch { /* 单个工具失败不阻塞其余 */ }
3423
4008
  };
@@ -3856,6 +4441,95 @@ export function apply(ctx) {
3856
4441
  return { ok: true, projectId: r.projectId, text };
3857
4442
  },
3858
4443
  });
4444
+ reg({
4445
+ name: 'canvas_read_memory',
4446
+ description: '读取项目记忆:不带 canvasId 返回**调度索引**(每集画布的标题/摘要/关键词/状态,一眼看到全项目各集记忆脉络);带 canvasId 额外返回该集**完整记忆正文**(剧情决策/人物状态变化/伏笔账本)。【记忆先行】写第 N 集剧本或分镜之前必须先读本集记忆(canvasId 从画布清单或索引对上号);跨集要伏笔/人物状态连续性时先读索引再读相关集正文。世界观/风格/角色场景设定不在记忆里——那些用 canvas_get_bible。',
4447
+ parameters: {
4448
+ type: 'object',
4449
+ properties: {
4450
+ projectId: { type: 'string', description: '项目 id' },
4451
+ canvasId: { type: 'string', description: '画布 id(集);缺省只回索引' },
4452
+ },
4453
+ required: ['projectId'],
4454
+ additionalProperties: false,
4455
+ },
4456
+ output: textOutput,
4457
+ timeoutMs: 30000,
4458
+ async execute(args) {
4459
+ const r = await memoryRead(args && args.projectId, args && args.canvasId);
4460
+ const idx = r.index || { episodes: [] };
4461
+ const lines = [];
4462
+ if (!idx.episodes.length) lines.push('(项目记忆为空:本集是第一集或尚未回写过记忆。写完记得 canvas_write_memory。)');
4463
+ else {
4464
+ lines.push('记忆索引(' + idx.episodes.length + ' 集)——跨集连续性的总账:');
4465
+ for (const e of idx.episodes) {
4466
+ lines.push(' · [' + (e.canvasId || '-') + '] ' + (e.title || '未命名') + '(' + (e.status === 'done' ? '已完结' : ' drafting/进行中') + ')' + (e.summary ? ':' + e.summary : '') + (Array.isArray(e.keywords) && e.keywords.length ? ' 关键词:' + e.keywords.join('/') : ''));
4467
+ }
4468
+ }
4469
+ if (r.episode) {
4470
+ lines.push('—— [' + r.episode.canvasId + '] ' + (r.episode.title || '未命名') + ' 的完整记忆 ——');
4471
+ lines.push(r.episode.body || '(该集还没有记忆正文)');
4472
+ }
4473
+ return { ok: true, projectId: r.projectId, text: lines.join('\n') };
4474
+ },
4475
+ });
4476
+ reg({
4477
+ name: 'canvas_write_memory',
4478
+ description: '写入某集(画布)的项目记忆并自动更新调度索引:title 集标题、summary 一句话摘要(≤120 字,进索引供其他集快速检索)、keywords 关键词、body 完整记忆正文(剧情决策/人物状态变化/伏笔账本/未回收的钩子)、status 进度。【会话收尾铁律】一集创作告一段落(每场定稿/全集完成)必须回写本集记忆——记忆是跨集连续性的唯一载体,不回写 = 下一集会重复创作、重复设定、丢伏笔。',
4479
+ parameters: {
4480
+ type: 'object',
4481
+ properties: {
4482
+ projectId: { type: 'string', description: '项目 id' },
4483
+ canvasId: { type: 'string', description: '画布 id(集)——记忆按画布隔离' },
4484
+ title: { type: 'string', description: '集标题(如「第3集 雨夜追踪」)' },
4485
+ summary: { type: 'string', description: '一句话摘要(≤120 字,写入索引供跨集检索)' },
4486
+ keywords: { type: 'array', items: { type: 'string' }, description: '关键词(人物/地点/伏笔标记,≤10 个)' },
4487
+ body: { type: 'string', description: '完整记忆正文(markdown):剧情决策、人物状态变化、伏笔登记与回收、生成要点' },
4488
+ status: { type: 'string', enum: ['drafting', 'done'], description: '进度:进行中/已完结' },
4489
+ },
4490
+ required: ['projectId', 'canvasId', 'title', 'summary', 'body'],
4491
+ additionalProperties: false,
4492
+ },
4493
+ output: textOutput,
4494
+ timeoutMs: 30000,
4495
+ async execute(args) {
4496
+ if (!args || !String(args.canvasId || '').trim()) return { ok: false, text: '缺少 canvasId:记忆按画布(集)隔离,必须指定。' };
4497
+ const r = await memoryWrite(args.projectId, args.canvasId, args);
4498
+ if (!r.ok) return { ok: false, text: r.error || '记忆写入失败' };
4499
+ return { ok: true, projectId: r.projectId, canvasId: r.canvasId, text: '✅ 记忆已写入索引(' + ((r.index && r.index.episodes.length) || 0) + ' 集)。' };
4500
+ },
4501
+ });
4502
+ reg({
4503
+ name: 'canvas_my_canvas',
4504
+ description: '自证身份:返回当前会话绑定的画布项目与画布(第几集),以及本集记忆状态。【会话=画布工作台】开始任何创作前先调用它确认「我是哪一集」;此后所有 canvas_* 工具不传 projectId/canvasId 即默认作用于本集画布。**代码级禁令**:绑定会话只能操作本集画布——显式传其他项目/画布(含同项目其他画布)会被工具直接拒绝,确需操作先请用户解绑;未绑定会话可自由操作任意项目/画布。返回的记忆提示告知是否需要先读/写本集记忆。',
4505
+ parameters: { type: 'object', properties: {}, additionalProperties: false },
4506
+ output: textOutput,
4507
+ timeoutMs: 15000,
4508
+ async execute(args, exec) {
4509
+ const sid = toolExecSessionId(exec);
4510
+ if (!sid) return { ok: false, text: '无法识别当前会话(宿主未提供会话身份):请显式指定 projectId/canvasId 操作画布。' };
4511
+ const b = toolBindingForSession(sid);
4512
+ if (!b) return { ok: false, text: '当前会话未绑定画布:在对话输入行的「绑画布」选择器里选择或新建画布后再试;或显式传 projectId/canvasId 直接操作。' };
4513
+ const doc = readDocOrNull(b.projectId) || {};
4514
+ const regList = canvasRegistry(doc);
4515
+ const cid = b.canvasId == null ? null : b.canvasId;
4516
+ const canvases = (defaultCanvasExists(doc) && !cid ? [{ id: null, name: defaultCanvasNameOf(doc) }] : regList.map((c) => ({ id: c.id, name: c.name })));
4517
+ const idx = canvases.findIndex((c) => (c.id || null) === cid);
4518
+ const ep = idx >= 0 ? idx + 1 : null;
4519
+ const name = idx >= 0 ? canvases[idx].name : String(cid || '默认画布');
4520
+ const mem = await memoryRead(b.projectId, cid);
4521
+ const hasMem = !!(mem.episode && ((mem.episode.body || '').trim() || (mem.episode.summary || '').trim()));
4522
+ let nodeCount = 0;
4523
+ try { nodeCount = Object.keys((readCanvasDoc(b.projectId, cid) || {}).nodes || {}).length; } catch { /* 画布读取失败不阻塞自证 */ }
4524
+ const lines = [
4525
+ '本会话绑定:项目「' + (doc.name || b.projectId) + '」· 画布「' + name + '」' + (ep ? '(第' + ep + ' 集 / 共 ' + canvases.length + ' 集)' : ''),
4526
+ '记忆状态:' + (hasMem ? '已有本集记忆——开写前先 canvas_read_memory 读索引与本集正文' : '本集还没有记忆——创作告一段落必须 canvas_write_memory 回写'),
4527
+ '本集画布节点:' + nodeCount + ' 个(可读写:canvas_write_node / canvas_create_node / canvas_connect / canvas_run_node / canvas_delete_node / canvas_get_bible / canvas_update_bible)',
4528
+ '代码级禁令:绑定会话禁止跨画布/跨项目操作(显式传其他 id 会被工具拒绝);如需操作其他画布,请用户先在对话输入行解绑。',
4529
+ ];
4530
+ return { ok: true, projectId: b.projectId, canvasId: cid, name, text: lines.join('\n') };
4531
+ },
4532
+ });
3859
4533
  reg({
3860
4534
  name: 'canvas_create_node',
3861
4535
  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 里写内容,有上游时靠连线取。',