@wwp9298/canvas-agent 0.0.0-stage → 0.3.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/remote.mjs ADDED
@@ -0,0 +1,665 @@
1
+ // 远程模式:不依赖浏览器标签页,凭 Agent 密钥直接调用站点 HTTP 接口。
2
+ // 与浏览器桥接(index.mjs 的 3210 服务 + 网页端工具执行器)相比:
3
+ // - 可以凭空新建画布(不需要先有画布页面);
4
+ // - 可以读写任意一个自己有权访问的画布(不需要页面在线);
5
+ // - 节点/连线变更走服务端 ops 合并,浏览器打开同一画布时能实时看到增量。
6
+ import { randomUUID } from "node:crypto";
7
+
8
+ const REQUEST_TIMEOUT_MS = 60_000;
9
+
10
+ // 与 web/src/app/(user)/canvas/constants.ts 的 NODE_SPECS 保持一致。
11
+ const NODE_SPECS = {
12
+ text: { width: 340, height: 240, metadata: { content: "", status: "idle", fontSize: 14 } },
13
+ image: { width: 340, height: 240, metadata: { content: "", status: "idle" } },
14
+ video: { width: 420, height: 236, metadata: { content: "", status: "idle" } },
15
+ audio: { width: 340, height: 160, metadata: { content: "", status: "idle" } },
16
+ group: { width: 760, height: 480, metadata: { status: "idle" } },
17
+ };
18
+
19
+ const LAYOUT_GAP = 72;
20
+
21
+ function shortId(prefix) {
22
+ return prefix + randomUUID().replace(/-/g, "").slice(0, 20);
23
+ }
24
+
25
+ function nowISO() {
26
+ return new Date().toISOString();
27
+ }
28
+
29
+ function nodeSummary(node) {
30
+ return {
31
+ id: node.id,
32
+ type: node.type,
33
+ title: node.title,
34
+ status: node.metadata?.status,
35
+ groupId: node.metadata?.groupId,
36
+ prompt: node.metadata?.prompt,
37
+ content: typeof node.metadata?.content === "string" ? node.metadata.content.slice(0, 600) : undefined,
38
+ };
39
+ }
40
+
41
+ function makeNode(type, { title, content, prompt, position, width, height, metadata } = {}) {
42
+ const spec = NODE_SPECS[type] || NODE_SPECS.text;
43
+ const node = {
44
+ id: shortId(type + "-"),
45
+ type,
46
+ title: title || (type === "text" ? "文本" : type === "group" ? "分组" : type),
47
+ position: position || { x: 0, y: 0 },
48
+ width: width || spec.width,
49
+ height: height || spec.height,
50
+ metadata: { ...spec.metadata, ...metadata },
51
+ };
52
+ if (content !== undefined) {
53
+ node.metadata.content = content;
54
+ if (node.metadata.prompt === undefined || prompt === undefined) node.metadata.prompt = content;
55
+ }
56
+ if (prompt !== undefined) node.metadata.prompt = prompt;
57
+ return node;
58
+ }
59
+
60
+ // 新节点落位:有上游就在上游右侧、纵向居中;否则在画布最右侧另起一列。
61
+ function nextPosition(nodes, sources, size) {
62
+ if (sources.length) {
63
+ const right = Math.max(...sources.map((node) => node.position.x + (node.width || size.width)));
64
+ const centerY = sources.reduce((sum, node) => sum + node.position.y + (node.height || 0) / 2, 0) / sources.length;
65
+ return { x: right + 160, y: centerY - size.height / 2 };
66
+ }
67
+ const right = nodes.reduce((max, node) => Math.max(max, node.position.x + (node.width || 0)), 0);
68
+ return { x: nodes.length ? right + 160 : 0, y: 0 };
69
+ }
70
+
71
+ export class CanvasRemoteClient {
72
+ constructor({ baseUrl, key, fetchImpl, timeout = REQUEST_TIMEOUT_MS } = {}) {
73
+ if (!baseUrl) throw new Error("缺少站点地址(--base-url 或 CANVAS_AGENT_BASE_URL)");
74
+ if (!key) throw new Error("缺少 Agent 密钥(--key 或 CANVAS_AGENT_KEY)");
75
+ this.baseUrl = String(baseUrl).replace(/\/+$/, "");
76
+ this.key = String(key);
77
+ this.fetchImpl = fetchImpl || globalThis.fetch;
78
+ this.timeout = timeout;
79
+ this.modelsCache = null;
80
+ }
81
+
82
+ async request(path, { method = "GET", body, timeout } = {}) {
83
+ const controller = new AbortController();
84
+ const timer = setTimeout(() => controller.abort(), timeout ?? this.timeout);
85
+ let response;
86
+ try {
87
+ response = await this.fetchImpl(this.baseUrl + path, {
88
+ method,
89
+ headers: {
90
+ authorization: "Bearer " + this.key,
91
+ "content-type": "application/json",
92
+ accept: "application/json",
93
+ },
94
+ body: body === undefined ? undefined : JSON.stringify(body),
95
+ signal: controller.signal,
96
+ });
97
+ } catch (error) {
98
+ const reason = error?.name === "AbortError" ? "请求超时" : error?.message || "网络异常";
99
+ throw new Error("访问 " + this.baseUrl + " 失败:" + reason);
100
+ } finally {
101
+ clearTimeout(timer);
102
+ }
103
+ const text = await response.text();
104
+ let payload;
105
+ try {
106
+ payload = text ? JSON.parse(text) : {};
107
+ } catch {
108
+ throw new Error("服务端返回非 JSON(HTTP " + response.status + "):" + text.slice(0, 200));
109
+ }
110
+ if (!response.ok) throw new Error(payload?.msg || "HTTP " + response.status);
111
+ // 业务错误也是 HTTP 200,用 code 判定。
112
+ if (payload && typeof payload.code === "number" && payload.code !== 0) throw new Error(payload.msg || "操作失败");
113
+ return payload?.data;
114
+ }
115
+
116
+ // ---------- 画布 ----------
117
+
118
+ async listCanvases() {
119
+ const projects = (await this.request("/api/v1/canvas/projects")) || [];
120
+ return projects.map((project) => ({
121
+ id: project.id,
122
+ title: project.title || "未命名画布",
123
+ updatedAt: project.updatedAt,
124
+ nodeCount: Array.isArray(project.nodes) ? project.nodes.length : 0,
125
+ connectionCount: Array.isArray(project.connections) ? project.connections.length : 0,
126
+ }));
127
+ }
128
+
129
+ async getCanvas(projectId) {
130
+ const detail = await this.request("/api/v1/canvas/projects/" + encodeURIComponent(projectId));
131
+ const project = detail?.project || {};
132
+ return {
133
+ project: {
134
+ ...project,
135
+ nodes: Array.isArray(project.nodes) ? project.nodes : [],
136
+ connections: Array.isArray(project.connections) ? project.connections : [],
137
+ },
138
+ revision: detail?.revision || 0,
139
+ visibility: detail?.visibility || "",
140
+ access: detail?.access || "",
141
+ };
142
+ }
143
+
144
+ async createCanvas(title) {
145
+ const now = nowISO();
146
+ const project = {
147
+ id: shortId("canvas-"),
148
+ title: title || "未命名画布",
149
+ createdAt: now,
150
+ updatedAt: now,
151
+ nodes: [],
152
+ connections: [],
153
+ chatSessions: [],
154
+ activeChatId: null,
155
+ agentConfig: null,
156
+ autoTitlePending: false,
157
+ backgroundMode: "lines",
158
+ showImageInfo: false,
159
+ viewport: { x: 0, y: 0, k: 1 },
160
+ sidePanel: { open: false, width: 280 },
161
+ agentPanel: { open: false, width: 464 },
162
+ };
163
+ await this.request("/api/v1/canvas/projects", { method: "POST", body: { data: project } });
164
+ return project;
165
+ }
166
+
167
+ async submitOps(projectId, ops) {
168
+ if (!ops.length) return { revision: null, opCount: 0 };
169
+ const result = await this.request("/api/v1/canvas/projects/" + encodeURIComponent(projectId) + "/ops", {
170
+ method: "POST",
171
+ body: { ops },
172
+ });
173
+ return { revision: result?.revision ?? null, opCount: ops.length };
174
+ }
175
+
176
+ // ---------- 模型 / 生成 ----------
177
+
178
+ async loadModelCatalog() {
179
+ if (this.modelsCache) return this.modelsCache;
180
+ const response = await this.fetchImpl(this.baseUrl + "/api/settings");
181
+ const payload = await response.json();
182
+ const modelChannel = payload?.data?.modelChannel || payload?.data?.model_channel || {};
183
+ const channels = (modelChannel.channels || []).filter((channel) => channel.enabled !== false);
184
+ this.modelsCache = {
185
+ availableModels: modelChannel.availableModels || [],
186
+ defaults: {
187
+ image: modelChannel.defaultImageModel || modelChannel.defaultModel || "",
188
+ video: modelChannel.defaultVideoModel || modelChannel.defaultModel || "",
189
+ text: modelChannel.defaultTextModel || modelChannel.defaultModel || "",
190
+ },
191
+ channels: channels.map((channel) => ({ id: channel.id, name: channel.name, models: channel.models || [] })),
192
+ };
193
+ return this.modelsCache;
194
+ }
195
+
196
+ async resolveModel(kind, model, channelId) {
197
+ const catalog = await this.loadModelCatalog();
198
+ const picked = model || catalog.defaults[kind] || "";
199
+ if (!picked) throw new Error("站点没有配置默认模型,请在生成时显式传 model");
200
+ if (channelId) return { model: picked, channelId };
201
+ const owners = catalog.channels.filter((channel) => channel.models.includes(picked));
202
+ if (!owners.length) throw new Error("模型 " + picked + " 不在任何已启用渠道里,请检查渠道配置");
203
+ return { model: picked, channelId: owners[0].id };
204
+ }
205
+
206
+ async createMediaTask(kind, { nodeId, prompt, model, channelId, extra }) {
207
+ const resolved = await this.resolveModel(kind, model, channelId);
208
+ if (kind === "image") {
209
+ return this.request("/api/v1/canvas/image-tasks", {
210
+ method: "POST",
211
+ body: {
212
+ endpoint: "/images/generations",
213
+ nodeId,
214
+ prompt,
215
+ channelId: resolved.channelId,
216
+ requestBody: { model: resolved.model, prompt, n: 1, ...extra },
217
+ },
218
+ });
219
+ }
220
+ if (kind === "audio") {
221
+ return this.request("/api/v1/canvas/audio-tasks", {
222
+ method: "POST",
223
+ body: {
224
+ endpoint: "/audio/speech",
225
+ nodeId,
226
+ prompt,
227
+ channelId: resolved.channelId,
228
+ requestBody: { model: resolved.model, input: prompt, ...extra },
229
+ },
230
+ });
231
+ }
232
+ return this.request("/api/v1/videos", {
233
+ method: "POST",
234
+ body: { model: resolved.model, prompt, channelId: resolved.channelId, ...extra },
235
+ });
236
+ }
237
+
238
+ async getMediaTask(kind, taskId) {
239
+ if (kind === "audio") return this.request("/api/v1/canvas/audio-tasks/" + encodeURIComponent(taskId));
240
+ if (kind === "video") return this.request("/api/v1/videos/" + encodeURIComponent(taskId));
241
+ return this.request("/api/v1/canvas/image-tasks/" + encodeURIComponent(taskId));
242
+ }
243
+ }
244
+
245
+ // ---------- 工具定义 ----------
246
+
247
+ const PROJECT_ID = { type: "string", description: "画布 ID;省略时使用本次会话最近操作的画布" };
248
+ const NODE_ID = { type: "string", description: "节点 ID" };
249
+
250
+ function schema(properties, required = []) {
251
+ return { type: "object", properties, required, additionalProperties: false };
252
+ }
253
+
254
+ export function createRemoteTools(client) {
255
+ // 会话内最近操作的画布:Agent 建完画布后不必每次带 projectId。
256
+ let activeProjectId = "";
257
+
258
+ async function canvas(projectId) {
259
+ const id = projectId || activeProjectId;
260
+ if (!id) throw new Error("请先创建画布(create_canvas)或传入 projectId(list_canvases 可取)");
261
+ activeProjectId = id;
262
+ return { id, detail: await client.getCanvas(id) };
263
+ }
264
+
265
+ const tools = [
266
+ {
267
+ name: "list_canvases",
268
+ description: "列出账号下的全部画布(id/标题/节点数/更新时间)。用于找到要操作的目标画布。",
269
+ inputSchema: schema({}),
270
+ handler: async () => ({ ok: true, canvases: await client.listCanvases() }),
271
+ },
272
+ {
273
+ name: "create_canvas",
274
+ description: "新建一个空白画布,返回画布 ID。之后可直接用 create_text_node 等工具往里放内容,不需要打开浏览器。",
275
+ inputSchema: schema({ title: { type: "string", description: "画布标题,省略为「未命名画布」" } }),
276
+ handler: async (args) => {
277
+ const project = await client.createCanvas(args.title);
278
+ activeProjectId = project.id;
279
+ return { ok: true, projectId: project.id, title: project.title, url: "/canvas/" + project.id };
280
+ },
281
+ },
282
+ {
283
+ name: "get_canvas_summary",
284
+ description: "读取画布概览:标题、节点清单、连线清单。写内容前先看它确认现状。",
285
+ inputSchema: schema({ projectId: PROJECT_ID }),
286
+ handler: async (args) => {
287
+ const { id, detail } = await canvas(args.projectId);
288
+ const project = detail.project;
289
+ return {
290
+ ok: true,
291
+ project: { id, title: project.title || "未命名画布", revision: detail.revision, access: detail.access },
292
+ nodes: project.nodes.map(nodeSummary),
293
+ connections: project.connections.slice(0, 240),
294
+ };
295
+ },
296
+ },
297
+ {
298
+ name: "query_canvas_nodes",
299
+ description: "按类型/关键词分页筛选节点。",
300
+ inputSchema: schema({
301
+ projectId: PROJECT_ID,
302
+ type: { type: "string", description: "节点类型:text/image/video/audio/group/config/director/panorama" },
303
+ keyword: { type: "string" },
304
+ page: { type: "number" },
305
+ pageSize: { type: "number" },
306
+ }),
307
+ handler: async (args) => {
308
+ const { detail } = await canvas(args.projectId);
309
+ const keyword = String(args.keyword || "").toLowerCase();
310
+ const page = Math.max(1, Math.floor(Number(args.page) || 1));
311
+ const pageSize = Math.max(1, Math.min(50, Math.floor(Number(args.pageSize) || 20)));
312
+ const filtered = detail.project.nodes.filter((node) => {
313
+ if (args.type && node.type !== args.type) return false;
314
+ if (!keyword) return true;
315
+ return (node.title + " " + (node.metadata?.content || "") + " " + (node.metadata?.prompt || "")).toLowerCase().includes(keyword);
316
+ });
317
+ return {
318
+ ok: true,
319
+ total: filtered.length,
320
+ page,
321
+ pageSize,
322
+ items: filtered.slice((page - 1) * pageSize, page * pageSize).map(nodeSummary),
323
+ };
324
+ },
325
+ },
326
+ {
327
+ name: "get_node",
328
+ description: "读取单个节点的完整信息。",
329
+ inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
330
+ handler: async (args) => {
331
+ const { detail } = await canvas(args.projectId);
332
+ const node = detail.project.nodes.find((item) => item.id === args.nodeId);
333
+ if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
334
+ return { ok: true, node };
335
+ },
336
+ },
337
+ {
338
+ name: "get_upstream_nodes",
339
+ description: "读取某节点的全部上游节点(谁连到它)。",
340
+ inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
341
+ handler: async (args) => {
342
+ const { detail } = await canvas(args.projectId);
343
+ const ids = detail.project.connections.filter((conn) => conn.toNodeId === args.nodeId).map((conn) => conn.fromNodeId);
344
+ return { ok: true, nodes: detail.project.nodes.filter((node) => ids.includes(node.id)).map(nodeSummary) };
345
+ },
346
+ },
347
+ {
348
+ name: "get_downstream_nodes",
349
+ description: "读取某节点的全部下游节点(它连到谁)。",
350
+ inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
351
+ handler: async (args) => {
352
+ const { detail } = await canvas(args.projectId);
353
+ const ids = detail.project.connections.filter((conn) => conn.fromNodeId === args.nodeId).map((conn) => conn.toNodeId);
354
+ return { ok: true, nodes: detail.project.nodes.filter((node) => ids.includes(node.id)).map(nodeSummary) };
355
+ },
356
+ },
357
+ {
358
+ name: "create_text_node",
359
+ description: "创建文本节点(剧本、镜头、角色、提示词、备注等)。sourceNodeIds 会同时连线:上游 → 新节点。",
360
+ inputSchema: schema({
361
+ projectId: PROJECT_ID,
362
+ title: { type: "string" },
363
+ content: { type: "string", description: "正文内容" },
364
+ sourceNodeIds: { type: "array", items: { type: "string" }, description: "上游节点 ID 列表" },
365
+ width: { type: "number" },
366
+ height: { type: "number" },
367
+ }, ["content"]),
368
+ handler: async (args) => {
369
+ const { id, detail } = await canvas(args.projectId);
370
+ const nodes = detail.project.nodes;
371
+ const sources = nodes.filter((node) => (args.sourceNodeIds || []).includes(node.id));
372
+ const size = { width: args.width || NODE_SPECS.text.width, height: args.height || NODE_SPECS.text.height };
373
+ const node = makeNode("text", {
374
+ title: args.title || String(args.content).slice(0, 24),
375
+ content: args.content,
376
+ prompt: args.content,
377
+ position: nextPosition(nodes, sources, size),
378
+ width: size.width,
379
+ height: size.height,
380
+ metadata: { status: "success" },
381
+ });
382
+ const connections = sources.map((source) => ({ id: shortId("conn-"), fromNodeId: source.id, toNodeId: node.id }));
383
+ const ops = [{ type: "upsertNode", node }, ...connections.map((connection) => ({ type: "upsertConnection", connection }))];
384
+ const result = await client.submitOps(id, ops);
385
+ return { ok: true, projectId: id, nodeId: node.id, connectionIds: connections.map((item) => item.id), revision: result.revision };
386
+ },
387
+ },
388
+ {
389
+ name: "update_text_node",
390
+ description: "修改文本节点的标题/正文。",
391
+ inputSchema: schema({
392
+ projectId: PROJECT_ID,
393
+ nodeId: NODE_ID,
394
+ title: { type: "string" },
395
+ content: { type: "string" },
396
+ }, ["nodeId"]),
397
+ handler: async (args) => {
398
+ const { id, detail } = await canvas(args.projectId);
399
+ const node = detail.project.nodes.find((item) => item.id === args.nodeId);
400
+ if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
401
+ if (node.type !== "text") return { ok: false, code: "invalid_node_type", message: "只能用 update_text_node 修改文本节点" };
402
+ const next = {
403
+ ...node,
404
+ title: args.title || node.title,
405
+ metadata: {
406
+ ...node.metadata,
407
+ ...(args.content !== undefined ? { content: args.content, prompt: args.content, status: "success" } : {}),
408
+ },
409
+ };
410
+ const result = await client.submitOps(id, [{ type: "upsertNode", node: next }]);
411
+ return { ok: true, nodeId: next.id, revision: result.revision };
412
+ },
413
+ },
414
+ {
415
+ name: "update_node",
416
+ description: "通用节点更新:改标题、写 metadata(content/prompt/status 等)。生成任务完成后用它把结果 URL 写回节点。",
417
+ inputSchema: schema({
418
+ projectId: PROJECT_ID,
419
+ nodeId: NODE_ID,
420
+ title: { type: "string" },
421
+ metadata: { type: "object", description: "要合并进节点 metadata 的字段", additionalProperties: true },
422
+ position: { type: "object", description: "{x,y}", additionalProperties: true },
423
+ width: { type: "number" },
424
+ height: { type: "number" },
425
+ }, ["nodeId"]),
426
+ handler: async (args) => {
427
+ const { id, detail } = await canvas(args.projectId);
428
+ const node = detail.project.nodes.find((item) => item.id === args.nodeId);
429
+ if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
430
+ const next = {
431
+ ...node,
432
+ title: args.title || node.title,
433
+ position: args.position || node.position,
434
+ width: args.width || node.width,
435
+ height: args.height || node.height,
436
+ metadata: { ...node.metadata, ...(args.metadata || {}) },
437
+ };
438
+ const result = await client.submitOps(id, [{ type: "upsertNode", node: next }]);
439
+ return { ok: true, nodeId: next.id, revision: result.revision };
440
+ },
441
+ },
442
+ {
443
+ name: "delete_node",
444
+ description: "删除节点(连同它的连线)。",
445
+ inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
446
+ handler: async (args) => {
447
+ const { id, detail } = await canvas(args.projectId);
448
+ if (!detail.project.nodes.some((node) => node.id === args.nodeId)) {
449
+ return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
450
+ }
451
+ const result = await client.submitOps(id, [{ type: "removeNode", nodeId: args.nodeId }]);
452
+ return { ok: true, deletedNodeIds: [args.nodeId], revision: result.revision };
453
+ },
454
+ },
455
+ {
456
+ name: "create_connection",
457
+ description: "连接两个节点(from → to)。",
458
+ inputSchema: schema({ projectId: PROJECT_ID, fromNodeId: NODE_ID, toNodeId: NODE_ID }, ["fromNodeId", "toNodeId"]),
459
+ handler: async (args) => {
460
+ const { id, detail } = await canvas(args.projectId);
461
+ const has = (nodeId) => detail.project.nodes.some((node) => node.id === nodeId);
462
+ if (!has(args.fromNodeId)) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.fromNodeId };
463
+ if (!has(args.toNodeId)) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.toNodeId };
464
+ if (args.fromNodeId === args.toNodeId) return { ok: false, code: "self_connection", message: "节点不能连接到自身" };
465
+ const existing = detail.project.connections.find((conn) => conn.fromNodeId === args.fromNodeId && conn.toNodeId === args.toNodeId);
466
+ if (existing) return { ok: true, connectionId: existing.id, alreadyExists: true };
467
+ const connection = { id: shortId("conn-"), fromNodeId: args.fromNodeId, toNodeId: args.toNodeId };
468
+ const result = await client.submitOps(id, [{ type: "upsertConnection", connection }]);
469
+ return { ok: true, connectionId: connection.id, revision: result.revision };
470
+ },
471
+ },
472
+ {
473
+ name: "delete_connection",
474
+ description: "删除一条连线。",
475
+ inputSchema: schema({ projectId: PROJECT_ID, connectionId: { type: "string" } }, ["connectionId"]),
476
+ handler: async (args) => {
477
+ const { id, detail } = await canvas(args.projectId);
478
+ if (!detail.project.connections.some((conn) => conn.id === args.connectionId)) {
479
+ return { ok: false, code: "connection_not_found", message: "找不到连线 " + args.connectionId };
480
+ }
481
+ const result = await client.submitOps(id, [{ type: "removeConnection", connectionId: args.connectionId }]);
482
+ return { ok: true, deletedConnectionId: args.connectionId, revision: result.revision };
483
+ },
484
+ },
485
+ {
486
+ name: "create_group",
487
+ description: "把若干节点框进一个分组(至少两个节点)。",
488
+ inputSchema: schema({
489
+ projectId: PROJECT_ID,
490
+ nodeIds: { type: "array", items: { type: "string" } },
491
+ title: { type: "string" },
492
+ }, ["nodeIds"]),
493
+ handler: async (args) => {
494
+ const { id, detail } = await canvas(args.projectId);
495
+ const members = detail.project.nodes.filter((node) => (args.nodeIds || []).includes(node.id));
496
+ if (members.length < 2) return { ok: false, code: "invalid_group", message: "分组至少需要两个节点" };
497
+ const padding = 80;
498
+ const minX = Math.min(...members.map((node) => node.position.x)) - padding;
499
+ const minY = Math.min(...members.map((node) => node.position.y)) - padding;
500
+ const maxX = Math.max(...members.map((node) => node.position.x + node.width)) + padding;
501
+ const maxY = Math.max(...members.map((node) => node.position.y + node.height)) + padding;
502
+ const group = makeNode("group", {
503
+ title: args.title || "分组",
504
+ position: { x: minX, y: minY },
505
+ width: maxX - minX,
506
+ height: maxY - minY,
507
+ });
508
+ const ops = [
509
+ { type: "upsertNode", node: group },
510
+ ...members.map((node) => ({ type: "upsertNode", node: { ...node, metadata: { ...node.metadata, groupId: group.id } } })),
511
+ ];
512
+ const result = await client.submitOps(id, ops);
513
+ return { ok: true, groupId: group.id, nodeIds: members.map((node) => node.id), revision: result.revision };
514
+ },
515
+ },
516
+ {
517
+ name: "arrange_nodes",
518
+ description: "把指定节点(省略则全部未分组节点)按网格重新排布。",
519
+ inputSchema: schema({
520
+ projectId: PROJECT_ID,
521
+ nodeIds: { type: "array", items: { type: "string" } },
522
+ columns: { type: "number" },
523
+ }),
524
+ handler: async (args) => {
525
+ const { id, detail } = await canvas(args.projectId);
526
+ const nodes = detail.project.nodes;
527
+ const targets = (args.nodeIds && args.nodeIds.length)
528
+ ? nodes.filter((node) => args.nodeIds.includes(node.id))
529
+ : nodes.filter((node) => !node.metadata?.groupId);
530
+ if (!targets.length) return { ok: true, arrangedNodeIds: [] };
531
+ const columns = Math.max(1, Math.min(8, Math.floor(Number(args.columns) || 4)));
532
+ const startX = Math.min(...targets.map((node) => node.position.x));
533
+ const startY = Math.min(...targets.map((node) => node.position.y));
534
+ let x = startX;
535
+ let y = startY;
536
+ let rowHeight = 0;
537
+ const ops = [];
538
+ targets.forEach((node, index) => {
539
+ if (index > 0 && index % columns === 0) {
540
+ x = startX;
541
+ y += rowHeight + LAYOUT_GAP;
542
+ rowHeight = 0;
543
+ }
544
+ ops.push({ type: "upsertNode", node: { ...node, position: { x, y } } });
545
+ x += node.width + LAYOUT_GAP;
546
+ rowHeight = Math.max(rowHeight, node.height);
547
+ });
548
+ const result = await client.submitOps(id, ops);
549
+ return { ok: true, arrangedNodeIds: targets.map((node) => node.id), revision: result.revision };
550
+ },
551
+ },
552
+ {
553
+ name: "list_generation_models",
554
+ description: "列出站点已配置的生成模型与默认值(图片/视频/文本)。生成前用它确认可用模型。",
555
+ inputSchema: schema({}),
556
+ handler: async () => ({ ok: true, ...(await client.loadModelCatalog()) }),
557
+ },
558
+ {
559
+ name: "generate_image",
560
+ description: "生成图片:先在画布上建一个 image 节点(状态 loading),再提交生成任务。用 get_media_task_status 查进度,完成后用 update_node 把 URL 写回 content/status。",
561
+ inputSchema: schema({
562
+ projectId: PROJECT_ID,
563
+ prompt: { type: "string" },
564
+ title: { type: "string" },
565
+ model: { type: "string" },
566
+ channelId: { type: "string" },
567
+ size: { type: "string", description: "如 1024x1024" },
568
+ sourceNodeIds: { type: "array", items: { type: "string" }, description: "参考图节点" },
569
+ }, ["prompt"]),
570
+ handler: async (args) => createMedia("image", args),
571
+ },
572
+ {
573
+ name: "generate_video",
574
+ description: "生成视频:建 video 节点 + 提交视频任务,其余同 generate_image。",
575
+ inputSchema: schema({
576
+ projectId: PROJECT_ID,
577
+ prompt: { type: "string" },
578
+ title: { type: "string" },
579
+ model: { type: "string" },
580
+ channelId: { type: "string" },
581
+ seconds: { type: "number" },
582
+ size: { type: "string" },
583
+ sourceNodeIds: { type: "array", items: { type: "string" } },
584
+ }, ["prompt"]),
585
+ handler: async (args) => createMedia("video", args),
586
+ },
587
+ {
588
+ name: "generate_audio",
589
+ description: "生成音频(TTS):建 audio 节点 + 提交音频任务,其余同 generate_image。",
590
+ inputSchema: schema({
591
+ projectId: PROJECT_ID,
592
+ prompt: { type: "string", description: "要朗读的文本" },
593
+ title: { type: "string" },
594
+ model: { type: "string" },
595
+ channelId: { type: "string" },
596
+ voice: { type: "string" },
597
+ format: { type: "string" },
598
+ }, ["prompt"]),
599
+ handler: async (args) => createMedia("audio", args),
600
+ },
601
+ {
602
+ name: "get_media_task_status",
603
+ description: "查询生成任务状态与结果 URL。kind 取 image/video/audio。",
604
+ inputSchema: schema({
605
+ taskId: { type: "string" },
606
+ kind: { type: "string", description: "image(默认)| video | audio" },
607
+ }, ["taskId"]),
608
+ handler: async (args) => {
609
+ const kind = ["video", "audio"].includes(args.kind) ? args.kind : "image";
610
+ const task = await client.getMediaTask(kind, args.taskId);
611
+ return { ok: true, kind, task };
612
+ },
613
+ },
614
+ ];
615
+
616
+ async function createMedia(kind, args) {
617
+ const { id, detail } = await canvas(args.projectId);
618
+ const nodes = detail.project.nodes;
619
+ const sources = nodes.filter((node) => (args.sourceNodeIds || []).includes(node.id));
620
+ const type = kind === "video" ? "video" : kind === "audio" ? "audio" : "image";
621
+ const size = { width: NODE_SPECS[type].width, height: NODE_SPECS[type].height };
622
+ const node = makeNode(type, {
623
+ title: args.title || String(args.prompt).slice(0, 24),
624
+ prompt: args.prompt,
625
+ content: "",
626
+ position: nextPosition(nodes, sources, size),
627
+ metadata: { status: "loading" },
628
+ });
629
+ const extra = {};
630
+ if (args.size) extra.size = args.size;
631
+ if (args.seconds) extra.seconds = args.seconds;
632
+ if (args.voice) extra.voice = args.voice;
633
+ if (args.format) extra.format = args.format;
634
+ const connections = sources.map((source) => ({ id: shortId("conn-"), fromNodeId: source.id, toNodeId: node.id }));
635
+ await client.submitOps(id, [
636
+ { type: "upsertNode", node },
637
+ ...connections.map((connection) => ({ type: "upsertConnection", connection })),
638
+ ]);
639
+ let task;
640
+ try {
641
+ task = await client.createMediaTask(kind, {
642
+ nodeId: node.id,
643
+ prompt: args.prompt,
644
+ model: args.model,
645
+ channelId: args.channelId,
646
+ extra,
647
+ });
648
+ } catch (error) {
649
+ // 提交失败:把节点标成 error,避免画布上永远转圈。
650
+ await client.submitOps(id, [{
651
+ type: "upsertNode",
652
+ node: { ...node, metadata: { ...node.metadata, status: "error", errorDetails: String(error.message || error) } },
653
+ }]).catch(() => {});
654
+ throw error;
655
+ }
656
+ const taskId = task?.id || task?.task_id || "";
657
+ await client.submitOps(id, [{
658
+ type: "upsertNode",
659
+ node: { ...node, metadata: { ...node.metadata, taskId, model: task?.model, status: task?.status || "loading" } },
660
+ }]).catch(() => {});
661
+ return { ok: true, projectId: id, nodeId: node.id, taskId, status: task?.status || "queued", kind };
662
+ }
663
+
664
+ return { tools, get activeProjectId() { return activeProjectId; } };
665
+ }