@wwp9298/canvas-agent 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +121 -2
- package/codex.mjs +91 -0
- package/index.mjs +479 -0
- package/package.json +33 -5
- package/remote.mjs +1133 -0
package/remote.mjs
ADDED
|
@@ -0,0 +1,1133 @@
|
|
|
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
|
+
this.storageCache = null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
async request(path, { method = "GET", body, timeout } = {}) {
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
const timer = setTimeout(() => controller.abort(), timeout ?? this.timeout);
|
|
86
|
+
let response;
|
|
87
|
+
try {
|
|
88
|
+
response = await this.fetchImpl(this.baseUrl + path, {
|
|
89
|
+
method,
|
|
90
|
+
headers: {
|
|
91
|
+
authorization: "Bearer " + this.key,
|
|
92
|
+
"content-type": "application/json",
|
|
93
|
+
accept: "application/json",
|
|
94
|
+
},
|
|
95
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
96
|
+
signal: controller.signal,
|
|
97
|
+
});
|
|
98
|
+
} catch (error) {
|
|
99
|
+
const reason = error?.name === "AbortError" ? "请求超时" : error?.message || "网络异常";
|
|
100
|
+
throw new Error("访问 " + this.baseUrl + " 失败:" + reason);
|
|
101
|
+
} finally {
|
|
102
|
+
clearTimeout(timer);
|
|
103
|
+
}
|
|
104
|
+
const text = await response.text();
|
|
105
|
+
let payload;
|
|
106
|
+
try {
|
|
107
|
+
payload = text ? JSON.parse(text) : {};
|
|
108
|
+
} catch {
|
|
109
|
+
throw new Error("服务端返回非 JSON(HTTP " + response.status + "):" + text.slice(0, 200));
|
|
110
|
+
}
|
|
111
|
+
if (!response.ok) throw new Error(payload?.msg || "HTTP " + response.status);
|
|
112
|
+
// 业务错误也是 HTTP 200,用 code 判定。
|
|
113
|
+
if (payload && typeof payload.code === "number" && payload.code !== 0) throw new Error(payload.msg || "操作失败");
|
|
114
|
+
return payload?.data;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
// ---------- 画布 ----------
|
|
118
|
+
|
|
119
|
+
async listCanvases() {
|
|
120
|
+
const projects = (await this.request("/api/v1/canvas/projects")) || [];
|
|
121
|
+
return projects.map((project) => ({
|
|
122
|
+
id: project.id,
|
|
123
|
+
title: project.title || "未命名画布",
|
|
124
|
+
updatedAt: project.updatedAt,
|
|
125
|
+
nodeCount: Array.isArray(project.nodes) ? project.nodes.length : 0,
|
|
126
|
+
connectionCount: Array.isArray(project.connections) ? project.connections.length : 0,
|
|
127
|
+
}));
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
async getCanvas(projectId) {
|
|
131
|
+
const detail = await this.request("/api/v1/canvas/projects/" + encodeURIComponent(projectId));
|
|
132
|
+
const project = detail?.project || {};
|
|
133
|
+
return {
|
|
134
|
+
project: {
|
|
135
|
+
...project,
|
|
136
|
+
nodes: Array.isArray(project.nodes) ? project.nodes : [],
|
|
137
|
+
connections: Array.isArray(project.connections) ? project.connections : [],
|
|
138
|
+
},
|
|
139
|
+
revision: detail?.revision || 0,
|
|
140
|
+
visibility: detail?.visibility || "",
|
|
141
|
+
access: detail?.access || "",
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
async createCanvas(title) {
|
|
146
|
+
const now = nowISO();
|
|
147
|
+
const project = {
|
|
148
|
+
id: shortId("canvas-"),
|
|
149
|
+
title: title || "未命名画布",
|
|
150
|
+
createdAt: now,
|
|
151
|
+
updatedAt: now,
|
|
152
|
+
nodes: [],
|
|
153
|
+
connections: [],
|
|
154
|
+
chatSessions: [],
|
|
155
|
+
activeChatId: null,
|
|
156
|
+
agentConfig: null,
|
|
157
|
+
autoTitlePending: false,
|
|
158
|
+
backgroundMode: "lines",
|
|
159
|
+
showImageInfo: false,
|
|
160
|
+
viewport: { x: 0, y: 0, k: 1 },
|
|
161
|
+
sidePanel: { open: false, width: 280 },
|
|
162
|
+
agentPanel: { open: false, width: 464 },
|
|
163
|
+
};
|
|
164
|
+
await this.request("/api/v1/canvas/projects", { method: "POST", body: { data: project } });
|
|
165
|
+
return project;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async submitOps(projectId, ops) {
|
|
169
|
+
if (!ops.length) return { revision: null, opCount: 0 };
|
|
170
|
+
const result = await this.request("/api/v1/canvas/projects/" + encodeURIComponent(projectId) + "/ops", {
|
|
171
|
+
method: "POST",
|
|
172
|
+
body: { ops },
|
|
173
|
+
});
|
|
174
|
+
return { revision: result?.revision ?? null, opCount: ops.length };
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// ---------- 模型 / 生成 ----------
|
|
178
|
+
|
|
179
|
+
async loadModelCatalog() {
|
|
180
|
+
if (this.modelsCache) return this.modelsCache;
|
|
181
|
+
const response = await this.fetchImpl(this.baseUrl + "/api/settings");
|
|
182
|
+
const payload = await response.json();
|
|
183
|
+
const modelChannel = payload?.data?.modelChannel || payload?.data?.model_channel || {};
|
|
184
|
+
const channels = (modelChannel.channels || []).filter((channel) => channel.enabled !== false);
|
|
185
|
+
this.modelsCache = {
|
|
186
|
+
availableModels: modelChannel.availableModels || [],
|
|
187
|
+
defaults: {
|
|
188
|
+
image: modelChannel.defaultImageModel || modelChannel.defaultModel || "",
|
|
189
|
+
video: modelChannel.defaultVideoModel || modelChannel.defaultModel || "",
|
|
190
|
+
text: modelChannel.defaultTextModel || modelChannel.defaultModel || "",
|
|
191
|
+
},
|
|
192
|
+
channels: channels.map((channel) => ({ id: channel.id, name: channel.name, models: channel.models || [] })),
|
|
193
|
+
};
|
|
194
|
+
return this.modelsCache;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// server_* 才能由 Agent 直传;local_indexeddb 只有浏览器本地库。
|
|
198
|
+
async loadStorageConfig() {
|
|
199
|
+
if (this.storageCache) return this.storageCache;
|
|
200
|
+
try {
|
|
201
|
+
const response = await this.fetchImpl(this.baseUrl + "/api/storage/config");
|
|
202
|
+
const payload = await response.json();
|
|
203
|
+
this.storageCache = payload?.data || { mode: "" };
|
|
204
|
+
} catch {
|
|
205
|
+
this.storageCache = { mode: "" };
|
|
206
|
+
}
|
|
207
|
+
return this.storageCache;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
async resolveModel(kind, model, channelId) {
|
|
211
|
+
const catalog = await this.loadModelCatalog();
|
|
212
|
+
const picked = model || catalog.defaults[kind] || "";
|
|
213
|
+
if (!picked) throw new Error("站点没有配置默认模型,请在生成时显式传 model");
|
|
214
|
+
if (channelId) return { model: picked, channelId };
|
|
215
|
+
const owners = catalog.channels.filter((channel) => channel.models.includes(picked));
|
|
216
|
+
if (!owners.length) throw new Error("模型 " + picked + " 不在任何已启用渠道里,请检查渠道配置");
|
|
217
|
+
return { model: picked, channelId: owners[0].id };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async createMediaTask(kind, { nodeId, prompt, model, channelId, extra, projectId }) {
|
|
221
|
+
const resolved = await this.resolveModel(kind, model, channelId);
|
|
222
|
+
if (kind === "image") {
|
|
223
|
+
return this.request("/api/v1/canvas/image-tasks", {
|
|
224
|
+
method: "POST",
|
|
225
|
+
body: {
|
|
226
|
+
endpoint: "/images/generations",
|
|
227
|
+
nodeId,
|
|
228
|
+
prompt,
|
|
229
|
+
channelId: resolved.channelId,
|
|
230
|
+
requestBody: { model: resolved.model, prompt, n: 1, ...extra },
|
|
231
|
+
},
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
if (kind === "audio") {
|
|
235
|
+
return this.request("/api/v1/canvas/audio-tasks", {
|
|
236
|
+
method: "POST",
|
|
237
|
+
body: {
|
|
238
|
+
endpoint: "/audio/speech",
|
|
239
|
+
nodeId,
|
|
240
|
+
prompt,
|
|
241
|
+
channelId: resolved.channelId,
|
|
242
|
+
requestBody: { model: resolved.model, input: prompt, ...extra },
|
|
243
|
+
},
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return this.request("/api/v1/videos", {
|
|
247
|
+
method: "POST",
|
|
248
|
+
body: {
|
|
249
|
+
model: resolved.model,
|
|
250
|
+
prompt,
|
|
251
|
+
channelId: resolved.channelId,
|
|
252
|
+
// 让视频任务能回溯到画布:列表接口只认 source/source_id。
|
|
253
|
+
...(projectId ? { source: "canvas", sourceId: projectId } : {}),
|
|
254
|
+
...extra,
|
|
255
|
+
},
|
|
256
|
+
});
|
|
257
|
+
}
|
|
258
|
+
async getMediaTask(kind, taskId) {
|
|
259
|
+
if (kind === "audio") return this.request("/api/v1/canvas/audio-tasks/" + encodeURIComponent(taskId));
|
|
260
|
+
if (kind === "video") return this.request("/api/v1/videos/" + encodeURIComponent(taskId));
|
|
261
|
+
return this.request("/api/v1/canvas/image-tasks/" + encodeURIComponent(taskId));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// ---------- 素材上传 ----------
|
|
265
|
+
|
|
266
|
+
// multipart 走独立通道:不能带 content-type,boundary 由 fetch 生成。
|
|
267
|
+
async requestMultipart(path, formData) {
|
|
268
|
+
const controller = new AbortController();
|
|
269
|
+
const timer = setTimeout(() => controller.abort(), Math.max(this.timeout, 180_000));
|
|
270
|
+
let response;
|
|
271
|
+
try {
|
|
272
|
+
response = await this.fetchImpl(this.baseUrl + path, {
|
|
273
|
+
method: "POST",
|
|
274
|
+
headers: { authorization: "Bearer " + this.key, accept: "application/json" },
|
|
275
|
+
body: formData,
|
|
276
|
+
signal: controller.signal,
|
|
277
|
+
});
|
|
278
|
+
} catch (error) {
|
|
279
|
+
const reason = error?.name === "AbortError" ? "上传超时" : error?.message || "网络异常";
|
|
280
|
+
throw new Error("上传到 " + this.baseUrl + " 失败:" + reason);
|
|
281
|
+
} finally {
|
|
282
|
+
clearTimeout(timer);
|
|
283
|
+
}
|
|
284
|
+
const text = await response.text();
|
|
285
|
+
let payload;
|
|
286
|
+
try {
|
|
287
|
+
payload = text ? JSON.parse(text) : {};
|
|
288
|
+
} catch {
|
|
289
|
+
throw new Error("服务端返回非 JSON(HTTP " + response.status + "):" + text.slice(0, 200));
|
|
290
|
+
}
|
|
291
|
+
if (!response.ok) throw new Error(payload?.msg || "HTTP " + response.status);
|
|
292
|
+
if (payload && typeof payload.code === "number" && payload.code !== 0) throw new Error(payload.msg || "上传失败");
|
|
293
|
+
return payload?.data;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// 三种来源:本地文件路径、远程 URL、显式 base64。
|
|
297
|
+
async uploadMedia({ filePath, url, base64, filename, canvasId, mimeType } = {}) {
|
|
298
|
+
// 存储模式决定能不能直传:local_indexeddb 只有浏览器侧 IndexedDB,服务端没有对象存储。
|
|
299
|
+
const storage = await this.loadStorageConfig();
|
|
300
|
+
if (storage.mode && storage.mode !== "server_sqlite_s3" && !String(storage.mode).startsWith("server")) {
|
|
301
|
+
throw new Error(
|
|
302
|
+
"该站点存储模式为 " + storage.mode + "(浏览器本地),Agent 无法直接上传素材。请让管理员在后台配置服务端对象存储后再试。",
|
|
303
|
+
);
|
|
304
|
+
}
|
|
305
|
+
const { readFile } = await import("node:fs/promises");
|
|
306
|
+
const { basename } = await import("node:path");
|
|
307
|
+
let bytes;
|
|
308
|
+
let name = filename || "";
|
|
309
|
+
let type = mimeType || "";
|
|
310
|
+
|
|
311
|
+
if (filePath) {
|
|
312
|
+
bytes = await readFile(filePath);
|
|
313
|
+
if (!name) name = basename(filePath);
|
|
314
|
+
} else if (base64) {
|
|
315
|
+
const raw = String(base64).replace(/^data:[^;]+;base64,/, "");
|
|
316
|
+
bytes = Buffer.from(raw, "base64");
|
|
317
|
+
if (!name) name = "upload.bin";
|
|
318
|
+
const match = /^data:([^;]+);base64,/.exec(String(base64));
|
|
319
|
+
if (!type && match) type = match[1];
|
|
320
|
+
} else if (url) {
|
|
321
|
+
const response = await this.fetchImpl(url);
|
|
322
|
+
if (!response.ok) throw new Error("下载素材失败:HTTP " + response.status);
|
|
323
|
+
bytes = Buffer.from(await response.arrayBuffer());
|
|
324
|
+
if (!type) type = response.headers.get("content-type") || "";
|
|
325
|
+
if (!name) {
|
|
326
|
+
const pathname = (() => { try { return new URL(url).pathname; } catch { return ""; } })();
|
|
327
|
+
name = basename(pathname) || "download.bin";
|
|
328
|
+
}
|
|
329
|
+
} else {
|
|
330
|
+
throw new Error("请提供 filePath、url 或 base64 之一");
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
if (!bytes?.length) throw new Error("素材为空,未上传");
|
|
334
|
+
const blob = new Blob([bytes], type ? { type } : undefined);
|
|
335
|
+
const form = new FormData();
|
|
336
|
+
form.append("file", blob, name);
|
|
337
|
+
if (canvasId) form.append("canvasId", canvasId);
|
|
338
|
+
const object = await this.requestMultipart("/api/v1/files", form);
|
|
339
|
+
if (!object?.id) throw new Error("上传成功但服务端没有返回文件 ID");
|
|
340
|
+
return {
|
|
341
|
+
fileId: object.id,
|
|
342
|
+
ref: "server:" + object.id,
|
|
343
|
+
url: object.publicUrl || "",
|
|
344
|
+
contentUrl: "/api/files/" + object.id + "/content",
|
|
345
|
+
mimeType: object.mimeType || type || "",
|
|
346
|
+
bytes: object.bytes ?? bytes.length,
|
|
347
|
+
width: object.width || 0,
|
|
348
|
+
height: object.height || 0,
|
|
349
|
+
filename: name,
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// ---------- 任务总览 / 重试 / 取消 ----------
|
|
354
|
+
|
|
355
|
+
// audio 没有列表接口,只能按 taskId 单查;这里只覆盖 image / video。
|
|
356
|
+
async listTasks(kind) {
|
|
357
|
+
if (kind === "video") return (await this.request("/api/v1/video-tasks")) || [];
|
|
358
|
+
if (kind === "audio") return [];
|
|
359
|
+
return (await this.request("/api/v1/canvas/image-tasks")) || [];
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
async deleteTask(kind, taskId) {
|
|
363
|
+
// 音频任务没有删除接口,服务端只提供查询。
|
|
364
|
+
if (kind === "audio") throw new Error("音频任务暂不支持取消,服务端未开放删除接口");
|
|
365
|
+
const path = kind === "video" ? "/api/v1/video-tasks/" : "/api/v1/canvas/image-tasks/";
|
|
366
|
+
return this.request(path + encodeURIComponent(taskId), { method: "DELETE" });
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// ---------- 运行时自检 ----------
|
|
370
|
+
|
|
371
|
+
async health() {
|
|
372
|
+
const response = await this.fetchImpl(this.baseUrl + "/api/health");
|
|
373
|
+
return { ok: response.ok, status: response.status };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
async currentUser() {
|
|
377
|
+
const response = await this.fetchImpl(this.baseUrl + "/api/auth/me", {
|
|
378
|
+
headers: { authorization: "Bearer " + this.key, accept: "application/json" },
|
|
379
|
+
});
|
|
380
|
+
const payload = await response.json();
|
|
381
|
+
return payload?.data || null;
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// ---------- 工具定义 ----------
|
|
386
|
+
|
|
387
|
+
const PROJECT_ID = { type: "string", description: "画布 ID;省略时使用本次会话最近操作的画布" };
|
|
388
|
+
const NODE_ID = { type: "string", description: "节点 ID" };
|
|
389
|
+
|
|
390
|
+
function schema(properties, required = []) {
|
|
391
|
+
return { type: "object", properties, required, additionalProperties: false };
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
export function createRemoteTools(client) {
|
|
395
|
+
// 会话内最近操作的画布:Agent 建完画布后不必每次带 projectId。
|
|
396
|
+
let activeProjectId = "";
|
|
397
|
+
|
|
398
|
+
async function canvas(projectId) {
|
|
399
|
+
const id = projectId || activeProjectId;
|
|
400
|
+
if (!id) throw new Error("请先创建画布(create_canvas)或传入 projectId(list_canvases 可取)");
|
|
401
|
+
activeProjectId = id;
|
|
402
|
+
return { id, detail: await client.getCanvas(id) };
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
const tools = [
|
|
406
|
+
{
|
|
407
|
+
name: "list_canvases",
|
|
408
|
+
description: "列出账号下的全部画布(id/标题/节点数/更新时间)。用于找到要操作的目标画布。",
|
|
409
|
+
inputSchema: schema({}),
|
|
410
|
+
handler: async () => ({ ok: true, canvases: await client.listCanvases() }),
|
|
411
|
+
},
|
|
412
|
+
{
|
|
413
|
+
name: "create_canvas",
|
|
414
|
+
description: "新建一个空白画布,返回画布 ID。之后可直接用 create_text_node 等工具往里放内容,不需要打开浏览器。",
|
|
415
|
+
inputSchema: schema({ title: { type: "string", description: "画布标题,省略为「未命名画布」" } }),
|
|
416
|
+
handler: async (args) => {
|
|
417
|
+
const project = await client.createCanvas(args.title);
|
|
418
|
+
activeProjectId = project.id;
|
|
419
|
+
return { ok: true, projectId: project.id, title: project.title, url: "/canvas/" + project.id };
|
|
420
|
+
},
|
|
421
|
+
},
|
|
422
|
+
{
|
|
423
|
+
name: "get_canvas_summary",
|
|
424
|
+
description: "读取画布概览:标题、节点清单、连线清单。写内容前先看它确认现状。",
|
|
425
|
+
inputSchema: schema({ projectId: PROJECT_ID }),
|
|
426
|
+
handler: async (args) => {
|
|
427
|
+
const { id, detail } = await canvas(args.projectId);
|
|
428
|
+
const project = detail.project;
|
|
429
|
+
return {
|
|
430
|
+
ok: true,
|
|
431
|
+
project: { id, title: project.title || "未命名画布", revision: detail.revision, access: detail.access },
|
|
432
|
+
nodes: project.nodes.map(nodeSummary),
|
|
433
|
+
connections: project.connections.slice(0, 240),
|
|
434
|
+
};
|
|
435
|
+
},
|
|
436
|
+
},
|
|
437
|
+
{
|
|
438
|
+
name: "query_canvas_nodes",
|
|
439
|
+
description: "按类型/关键词分页筛选节点。",
|
|
440
|
+
inputSchema: schema({
|
|
441
|
+
projectId: PROJECT_ID,
|
|
442
|
+
type: { type: "string", description: "节点类型:text/image/video/audio/group/config/director/panorama" },
|
|
443
|
+
keyword: { type: "string" },
|
|
444
|
+
page: { type: "number" },
|
|
445
|
+
pageSize: { type: "number" },
|
|
446
|
+
}),
|
|
447
|
+
handler: async (args) => {
|
|
448
|
+
const { detail } = await canvas(args.projectId);
|
|
449
|
+
const keyword = String(args.keyword || "").toLowerCase();
|
|
450
|
+
const page = Math.max(1, Math.floor(Number(args.page) || 1));
|
|
451
|
+
const pageSize = Math.max(1, Math.min(50, Math.floor(Number(args.pageSize) || 20)));
|
|
452
|
+
const filtered = detail.project.nodes.filter((node) => {
|
|
453
|
+
if (args.type && node.type !== args.type) return false;
|
|
454
|
+
if (!keyword) return true;
|
|
455
|
+
return (node.title + " " + (node.metadata?.content || "") + " " + (node.metadata?.prompt || "")).toLowerCase().includes(keyword);
|
|
456
|
+
});
|
|
457
|
+
return {
|
|
458
|
+
ok: true,
|
|
459
|
+
total: filtered.length,
|
|
460
|
+
page,
|
|
461
|
+
pageSize,
|
|
462
|
+
items: filtered.slice((page - 1) * pageSize, page * pageSize).map(nodeSummary),
|
|
463
|
+
};
|
|
464
|
+
},
|
|
465
|
+
},
|
|
466
|
+
{
|
|
467
|
+
name: "get_node",
|
|
468
|
+
description: "读取单个节点的完整信息。",
|
|
469
|
+
inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
|
|
470
|
+
handler: async (args) => {
|
|
471
|
+
const { detail } = await canvas(args.projectId);
|
|
472
|
+
const node = detail.project.nodes.find((item) => item.id === args.nodeId);
|
|
473
|
+
if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
|
|
474
|
+
return { ok: true, node };
|
|
475
|
+
},
|
|
476
|
+
},
|
|
477
|
+
{
|
|
478
|
+
name: "get_upstream_nodes",
|
|
479
|
+
description: "读取某节点的全部上游节点(谁连到它)。",
|
|
480
|
+
inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
|
|
481
|
+
handler: async (args) => {
|
|
482
|
+
const { detail } = await canvas(args.projectId);
|
|
483
|
+
const ids = detail.project.connections.filter((conn) => conn.toNodeId === args.nodeId).map((conn) => conn.fromNodeId);
|
|
484
|
+
return { ok: true, nodes: detail.project.nodes.filter((node) => ids.includes(node.id)).map(nodeSummary) };
|
|
485
|
+
},
|
|
486
|
+
},
|
|
487
|
+
{
|
|
488
|
+
name: "get_downstream_nodes",
|
|
489
|
+
description: "读取某节点的全部下游节点(它连到谁)。",
|
|
490
|
+
inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
|
|
491
|
+
handler: async (args) => {
|
|
492
|
+
const { detail } = await canvas(args.projectId);
|
|
493
|
+
const ids = detail.project.connections.filter((conn) => conn.fromNodeId === args.nodeId).map((conn) => conn.toNodeId);
|
|
494
|
+
return { ok: true, nodes: detail.project.nodes.filter((node) => ids.includes(node.id)).map(nodeSummary) };
|
|
495
|
+
},
|
|
496
|
+
},
|
|
497
|
+
{
|
|
498
|
+
name: "create_text_node",
|
|
499
|
+
description: "创建文本节点(剧本、镜头、角色、提示词、备注等)。sourceNodeIds 会同时连线:上游 → 新节点。",
|
|
500
|
+
inputSchema: schema({
|
|
501
|
+
projectId: PROJECT_ID,
|
|
502
|
+
title: { type: "string" },
|
|
503
|
+
content: { type: "string", description: "正文内容" },
|
|
504
|
+
sourceNodeIds: { type: "array", items: { type: "string" }, description: "上游节点 ID 列表" },
|
|
505
|
+
width: { type: "number" },
|
|
506
|
+
height: { type: "number" },
|
|
507
|
+
}, ["content"]),
|
|
508
|
+
handler: async (args) => {
|
|
509
|
+
const { id, detail } = await canvas(args.projectId);
|
|
510
|
+
const nodes = detail.project.nodes;
|
|
511
|
+
const sources = nodes.filter((node) => (args.sourceNodeIds || []).includes(node.id));
|
|
512
|
+
const size = { width: args.width || NODE_SPECS.text.width, height: args.height || NODE_SPECS.text.height };
|
|
513
|
+
const node = makeNode("text", {
|
|
514
|
+
title: args.title || String(args.content).slice(0, 24),
|
|
515
|
+
content: args.content,
|
|
516
|
+
prompt: args.content,
|
|
517
|
+
position: nextPosition(nodes, sources, size),
|
|
518
|
+
width: size.width,
|
|
519
|
+
height: size.height,
|
|
520
|
+
metadata: { status: "success" },
|
|
521
|
+
});
|
|
522
|
+
const connections = sources.map((source) => ({ id: shortId("conn-"), fromNodeId: source.id, toNodeId: node.id }));
|
|
523
|
+
const ops = [{ type: "upsertNode", node }, ...connections.map((connection) => ({ type: "upsertConnection", connection }))];
|
|
524
|
+
const result = await client.submitOps(id, ops);
|
|
525
|
+
return { ok: true, projectId: id, nodeId: node.id, connectionIds: connections.map((item) => item.id), revision: result.revision };
|
|
526
|
+
},
|
|
527
|
+
},
|
|
528
|
+
{
|
|
529
|
+
name: "update_text_node",
|
|
530
|
+
description: "修改文本节点的标题/正文。",
|
|
531
|
+
inputSchema: schema({
|
|
532
|
+
projectId: PROJECT_ID,
|
|
533
|
+
nodeId: NODE_ID,
|
|
534
|
+
title: { type: "string" },
|
|
535
|
+
content: { type: "string" },
|
|
536
|
+
}, ["nodeId"]),
|
|
537
|
+
handler: async (args) => {
|
|
538
|
+
const { id, detail } = await canvas(args.projectId);
|
|
539
|
+
const node = detail.project.nodes.find((item) => item.id === args.nodeId);
|
|
540
|
+
if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
|
|
541
|
+
if (node.type !== "text") return { ok: false, code: "invalid_node_type", message: "只能用 update_text_node 修改文本节点" };
|
|
542
|
+
const next = {
|
|
543
|
+
...node,
|
|
544
|
+
title: args.title || node.title,
|
|
545
|
+
metadata: {
|
|
546
|
+
...node.metadata,
|
|
547
|
+
...(args.content !== undefined ? { content: args.content, prompt: args.content, status: "success" } : {}),
|
|
548
|
+
},
|
|
549
|
+
};
|
|
550
|
+
const result = await client.submitOps(id, [{ type: "upsertNode", node: next }]);
|
|
551
|
+
return { ok: true, nodeId: next.id, revision: result.revision };
|
|
552
|
+
},
|
|
553
|
+
},
|
|
554
|
+
{
|
|
555
|
+
name: "update_node",
|
|
556
|
+
description: "通用节点更新:改标题、写 metadata(content/prompt/status 等)。生成任务完成后用它把结果 URL 写回节点。",
|
|
557
|
+
inputSchema: schema({
|
|
558
|
+
projectId: PROJECT_ID,
|
|
559
|
+
nodeId: NODE_ID,
|
|
560
|
+
title: { type: "string" },
|
|
561
|
+
metadata: { type: "object", description: "要合并进节点 metadata 的字段", additionalProperties: true },
|
|
562
|
+
position: { type: "object", description: "{x,y}", additionalProperties: true },
|
|
563
|
+
width: { type: "number" },
|
|
564
|
+
height: { type: "number" },
|
|
565
|
+
}, ["nodeId"]),
|
|
566
|
+
handler: async (args) => {
|
|
567
|
+
const { id, detail } = await canvas(args.projectId);
|
|
568
|
+
const node = detail.project.nodes.find((item) => item.id === args.nodeId);
|
|
569
|
+
if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
|
|
570
|
+
const next = {
|
|
571
|
+
...node,
|
|
572
|
+
title: args.title || node.title,
|
|
573
|
+
position: args.position || node.position,
|
|
574
|
+
width: args.width || node.width,
|
|
575
|
+
height: args.height || node.height,
|
|
576
|
+
metadata: { ...node.metadata, ...(args.metadata || {}) },
|
|
577
|
+
};
|
|
578
|
+
const result = await client.submitOps(id, [{ type: "upsertNode", node: next }]);
|
|
579
|
+
return { ok: true, nodeId: next.id, revision: result.revision };
|
|
580
|
+
},
|
|
581
|
+
},
|
|
582
|
+
{
|
|
583
|
+
name: "delete_node",
|
|
584
|
+
description: "删除节点(连同它的连线)。",
|
|
585
|
+
inputSchema: schema({ projectId: PROJECT_ID, nodeId: NODE_ID }, ["nodeId"]),
|
|
586
|
+
handler: async (args) => {
|
|
587
|
+
const { id, detail } = await canvas(args.projectId);
|
|
588
|
+
if (!detail.project.nodes.some((node) => node.id === args.nodeId)) {
|
|
589
|
+
return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
|
|
590
|
+
}
|
|
591
|
+
const result = await client.submitOps(id, [{ type: "removeNode", nodeId: args.nodeId }]);
|
|
592
|
+
return { ok: true, deletedNodeIds: [args.nodeId], revision: result.revision };
|
|
593
|
+
},
|
|
594
|
+
},
|
|
595
|
+
{
|
|
596
|
+
name: "create_connection",
|
|
597
|
+
description: "连接两个节点(from → to)。",
|
|
598
|
+
inputSchema: schema({ projectId: PROJECT_ID, fromNodeId: NODE_ID, toNodeId: NODE_ID }, ["fromNodeId", "toNodeId"]),
|
|
599
|
+
handler: async (args) => {
|
|
600
|
+
const { id, detail } = await canvas(args.projectId);
|
|
601
|
+
const has = (nodeId) => detail.project.nodes.some((node) => node.id === nodeId);
|
|
602
|
+
if (!has(args.fromNodeId)) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.fromNodeId };
|
|
603
|
+
if (!has(args.toNodeId)) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.toNodeId };
|
|
604
|
+
if (args.fromNodeId === args.toNodeId) return { ok: false, code: "self_connection", message: "节点不能连接到自身" };
|
|
605
|
+
const existing = detail.project.connections.find((conn) => conn.fromNodeId === args.fromNodeId && conn.toNodeId === args.toNodeId);
|
|
606
|
+
if (existing) return { ok: true, connectionId: existing.id, alreadyExists: true };
|
|
607
|
+
const connection = { id: shortId("conn-"), fromNodeId: args.fromNodeId, toNodeId: args.toNodeId };
|
|
608
|
+
const result = await client.submitOps(id, [{ type: "upsertConnection", connection }]);
|
|
609
|
+
return { ok: true, connectionId: connection.id, revision: result.revision };
|
|
610
|
+
},
|
|
611
|
+
},
|
|
612
|
+
{
|
|
613
|
+
name: "delete_connection",
|
|
614
|
+
description: "删除一条连线。",
|
|
615
|
+
inputSchema: schema({ projectId: PROJECT_ID, connectionId: { type: "string" } }, ["connectionId"]),
|
|
616
|
+
handler: async (args) => {
|
|
617
|
+
const { id, detail } = await canvas(args.projectId);
|
|
618
|
+
if (!detail.project.connections.some((conn) => conn.id === args.connectionId)) {
|
|
619
|
+
return { ok: false, code: "connection_not_found", message: "找不到连线 " + args.connectionId };
|
|
620
|
+
}
|
|
621
|
+
const result = await client.submitOps(id, [{ type: "removeConnection", connectionId: args.connectionId }]);
|
|
622
|
+
return { ok: true, deletedConnectionId: args.connectionId, revision: result.revision };
|
|
623
|
+
},
|
|
624
|
+
},
|
|
625
|
+
{
|
|
626
|
+
name: "create_group",
|
|
627
|
+
description: "把若干节点框进一个分组(至少两个节点)。",
|
|
628
|
+
inputSchema: schema({
|
|
629
|
+
projectId: PROJECT_ID,
|
|
630
|
+
nodeIds: { type: "array", items: { type: "string" } },
|
|
631
|
+
title: { type: "string" },
|
|
632
|
+
}, ["nodeIds"]),
|
|
633
|
+
handler: async (args) => {
|
|
634
|
+
const { id, detail } = await canvas(args.projectId);
|
|
635
|
+
const members = detail.project.nodes.filter((node) => (args.nodeIds || []).includes(node.id));
|
|
636
|
+
if (members.length < 2) return { ok: false, code: "invalid_group", message: "分组至少需要两个节点" };
|
|
637
|
+
const padding = 80;
|
|
638
|
+
const minX = Math.min(...members.map((node) => node.position.x)) - padding;
|
|
639
|
+
const minY = Math.min(...members.map((node) => node.position.y)) - padding;
|
|
640
|
+
const maxX = Math.max(...members.map((node) => node.position.x + node.width)) + padding;
|
|
641
|
+
const maxY = Math.max(...members.map((node) => node.position.y + node.height)) + padding;
|
|
642
|
+
const group = makeNode("group", {
|
|
643
|
+
title: args.title || "分组",
|
|
644
|
+
position: { x: minX, y: minY },
|
|
645
|
+
width: maxX - minX,
|
|
646
|
+
height: maxY - minY,
|
|
647
|
+
});
|
|
648
|
+
const ops = [
|
|
649
|
+
{ type: "upsertNode", node: group },
|
|
650
|
+
...members.map((node) => ({ type: "upsertNode", node: { ...node, metadata: { ...node.metadata, groupId: group.id } } })),
|
|
651
|
+
];
|
|
652
|
+
const result = await client.submitOps(id, ops);
|
|
653
|
+
return { ok: true, groupId: group.id, nodeIds: members.map((node) => node.id), revision: result.revision };
|
|
654
|
+
},
|
|
655
|
+
},
|
|
656
|
+
{
|
|
657
|
+
name: "arrange_nodes",
|
|
658
|
+
description: "把指定节点(省略则全部未分组节点)按网格重新排布。",
|
|
659
|
+
inputSchema: schema({
|
|
660
|
+
projectId: PROJECT_ID,
|
|
661
|
+
nodeIds: { type: "array", items: { type: "string" } },
|
|
662
|
+
columns: { type: "number" },
|
|
663
|
+
}),
|
|
664
|
+
handler: async (args) => {
|
|
665
|
+
const { id, detail } = await canvas(args.projectId);
|
|
666
|
+
const nodes = detail.project.nodes;
|
|
667
|
+
const targets = (args.nodeIds && args.nodeIds.length)
|
|
668
|
+
? nodes.filter((node) => args.nodeIds.includes(node.id))
|
|
669
|
+
: nodes.filter((node) => !node.metadata?.groupId);
|
|
670
|
+
if (!targets.length) return { ok: true, arrangedNodeIds: [] };
|
|
671
|
+
const columns = Math.max(1, Math.min(8, Math.floor(Number(args.columns) || 4)));
|
|
672
|
+
const startX = Math.min(...targets.map((node) => node.position.x));
|
|
673
|
+
const startY = Math.min(...targets.map((node) => node.position.y));
|
|
674
|
+
let x = startX;
|
|
675
|
+
let y = startY;
|
|
676
|
+
let rowHeight = 0;
|
|
677
|
+
const ops = [];
|
|
678
|
+
targets.forEach((node, index) => {
|
|
679
|
+
if (index > 0 && index % columns === 0) {
|
|
680
|
+
x = startX;
|
|
681
|
+
y += rowHeight + LAYOUT_GAP;
|
|
682
|
+
rowHeight = 0;
|
|
683
|
+
}
|
|
684
|
+
ops.push({ type: "upsertNode", node: { ...node, position: { x, y } } });
|
|
685
|
+
x += node.width + LAYOUT_GAP;
|
|
686
|
+
rowHeight = Math.max(rowHeight, node.height);
|
|
687
|
+
});
|
|
688
|
+
const result = await client.submitOps(id, ops);
|
|
689
|
+
return { ok: true, arrangedNodeIds: targets.map((node) => node.id), revision: result.revision };
|
|
690
|
+
},
|
|
691
|
+
},
|
|
692
|
+
{
|
|
693
|
+
name: "list_generation_models",
|
|
694
|
+
description: "列出站点已配置的生成模型与默认值(图片/视频/文本)。生成前用它确认可用模型。",
|
|
695
|
+
inputSchema: schema({}),
|
|
696
|
+
handler: async () => ({ ok: true, ...(await client.loadModelCatalog()) }),
|
|
697
|
+
},
|
|
698
|
+
{
|
|
699
|
+
name: "generate_image",
|
|
700
|
+
description: "生成图片:先在画布上建一个 image 节点(状态 loading),再提交生成任务。用 get_media_task_status 查进度,完成后用 update_node 把 URL 写回 content/status。",
|
|
701
|
+
inputSchema: schema({
|
|
702
|
+
projectId: PROJECT_ID,
|
|
703
|
+
prompt: { type: "string" },
|
|
704
|
+
title: { type: "string" },
|
|
705
|
+
model: { type: "string" },
|
|
706
|
+
channelId: { type: "string" },
|
|
707
|
+
size: { type: "string", description: "如 1024x1024" },
|
|
708
|
+
sourceNodeIds: { type: "array", items: { type: "string" }, description: "参考图节点" },
|
|
709
|
+
}, ["prompt"]),
|
|
710
|
+
handler: async (args) => createMedia("image", args),
|
|
711
|
+
},
|
|
712
|
+
{
|
|
713
|
+
name: "generate_video",
|
|
714
|
+
description: "生成视频:建 video 节点 + 提交视频任务,其余同 generate_image。",
|
|
715
|
+
inputSchema: schema({
|
|
716
|
+
projectId: PROJECT_ID,
|
|
717
|
+
prompt: { type: "string" },
|
|
718
|
+
title: { type: "string" },
|
|
719
|
+
model: { type: "string" },
|
|
720
|
+
channelId: { type: "string" },
|
|
721
|
+
seconds: { type: "number" },
|
|
722
|
+
size: { type: "string" },
|
|
723
|
+
sourceNodeIds: { type: "array", items: { type: "string" } },
|
|
724
|
+
}, ["prompt"]),
|
|
725
|
+
handler: async (args) => createMedia("video", args),
|
|
726
|
+
},
|
|
727
|
+
{
|
|
728
|
+
name: "generate_audio",
|
|
729
|
+
description: "生成音频(TTS):建 audio 节点 + 提交音频任务,其余同 generate_image。",
|
|
730
|
+
inputSchema: schema({
|
|
731
|
+
projectId: PROJECT_ID,
|
|
732
|
+
prompt: { type: "string", description: "要朗读的文本" },
|
|
733
|
+
title: { type: "string" },
|
|
734
|
+
model: { type: "string" },
|
|
735
|
+
channelId: { type: "string" },
|
|
736
|
+
voice: { type: "string" },
|
|
737
|
+
format: { type: "string" },
|
|
738
|
+
}, ["prompt"]),
|
|
739
|
+
handler: async (args) => createMedia("audio", args),
|
|
740
|
+
},
|
|
741
|
+
{
|
|
742
|
+
name: "get_media_task_status",
|
|
743
|
+
description: "查询生成任务状态与结果 URL。kind 取 image/video/audio。",
|
|
744
|
+
inputSchema: schema({
|
|
745
|
+
taskId: { type: "string" },
|
|
746
|
+
kind: { type: "string", description: "image(默认)| video | audio" },
|
|
747
|
+
}, ["taskId"]),
|
|
748
|
+
handler: async (args) => {
|
|
749
|
+
const kind = ["video", "audio"].includes(args.kind) ? args.kind : "image";
|
|
750
|
+
const task = await client.getMediaTask(kind, args.taskId);
|
|
751
|
+
return { ok: true, kind, task };
|
|
752
|
+
},
|
|
753
|
+
},
|
|
754
|
+
{
|
|
755
|
+
name: "upload_media",
|
|
756
|
+
description: "上传素材到站点,返回 server:<id> 引用,可直接写进节点 content 或作为生成参考。三种来源选一种:filePath(本机绝对路径)、url(远程地址)、base64。",
|
|
757
|
+
inputSchema: schema({
|
|
758
|
+
projectId: PROJECT_ID,
|
|
759
|
+
filePath: { type: "string", description: "本机文件绝对路径" },
|
|
760
|
+
url: { type: "string", description: "远程素材地址,由客户端下载后上传" },
|
|
761
|
+
base64: { type: "string", description: "data URL 或纯 base64" },
|
|
762
|
+
filename: { type: "string", description: "覆盖文件名" },
|
|
763
|
+
mimeType: { type: "string", description: "覆盖 MIME 类型" },
|
|
764
|
+
}),
|
|
765
|
+
handler: async (args) => {
|
|
766
|
+
const projectId = args.projectId || activeProjectId || "";
|
|
767
|
+
const asset = await client.uploadMedia({
|
|
768
|
+
filePath: args.filePath,
|
|
769
|
+
url: args.url,
|
|
770
|
+
base64: args.base64,
|
|
771
|
+
filename: args.filename,
|
|
772
|
+
mimeType: args.mimeType,
|
|
773
|
+
canvasId: projectId,
|
|
774
|
+
});
|
|
775
|
+
return { ok: true, projectId, ...asset };
|
|
776
|
+
},
|
|
777
|
+
},
|
|
778
|
+
{
|
|
779
|
+
name: "create_media_node",
|
|
780
|
+
description: "在画布上放一个已有素材节点(图片/视频/音频),不触发生成。content 可传 server:<id>、上传返回的 ref,或完整 URL。",
|
|
781
|
+
inputSchema: schema({
|
|
782
|
+
projectId: PROJECT_ID,
|
|
783
|
+
type: { type: "string", description: "image | video | audio | text" },
|
|
784
|
+
title: { type: "string" },
|
|
785
|
+
content: { type: "string", description: "素材引用:server:<id> 或 https URL" },
|
|
786
|
+
prompt: { type: "string", description: "可选,记录提示词" },
|
|
787
|
+
sourceNodeIds: { type: "array", items: { type: "string" }, description: "上游节点,会同时连线" },
|
|
788
|
+
width: { type: "number" },
|
|
789
|
+
height: { type: "number" },
|
|
790
|
+
}, ["type", "content"]),
|
|
791
|
+
handler: async (args) => {
|
|
792
|
+
const type = ["image", "video", "audio", "text"].includes(args.type) ? args.type : "image";
|
|
793
|
+
const { id, detail } = await canvas(args.projectId);
|
|
794
|
+
const nodes = detail.project.nodes;
|
|
795
|
+
const sources = nodes.filter((node) => (args.sourceNodeIds || []).includes(node.id));
|
|
796
|
+
const size = { width: args.width || NODE_SPECS[type].width, height: args.height || NODE_SPECS[type].height };
|
|
797
|
+
const node = makeNode(type, {
|
|
798
|
+
title: args.title || type,
|
|
799
|
+
content: args.content,
|
|
800
|
+
prompt: args.prompt,
|
|
801
|
+
position: nextPosition(nodes, sources, size),
|
|
802
|
+
width: size.width,
|
|
803
|
+
height: size.height,
|
|
804
|
+
metadata: { status: "success" },
|
|
805
|
+
});
|
|
806
|
+
const connections = sources.map((source) => ({ id: shortId("conn-"), fromNodeId: source.id, toNodeId: node.id }));
|
|
807
|
+
const result = await client.submitOps(id, [
|
|
808
|
+
{ type: "upsertNode", node },
|
|
809
|
+
...connections.map((connection) => ({ type: "upsertConnection", connection })),
|
|
810
|
+
]);
|
|
811
|
+
return { ok: true, projectId: id, nodeId: node.id, connectionIds: connections.map((item) => item.id), revision: result.revision };
|
|
812
|
+
},
|
|
813
|
+
},
|
|
814
|
+
{
|
|
815
|
+
name: "list_media_tasks",
|
|
816
|
+
description: "汇总画布内的生成任务并定位失败项:以画布节点为准(读节点上的 taskId 与状态),再合并服务端进行中的任务。返回状态、进度、错误原因与对应节点。排查「哪个节点卡住/失败」先调它。",
|
|
817
|
+
inputSchema: schema({
|
|
818
|
+
projectId: PROJECT_ID,
|
|
819
|
+
kind: { type: "string", description: "image | video | audio | all(默认 all)" },
|
|
820
|
+
status: { type: "string", description: "只看某个状态:queued/running/success/error 等" },
|
|
821
|
+
limit: { type: "number", description: "最多返回多少条,默认 50" },
|
|
822
|
+
}),
|
|
823
|
+
handler: async (args) => {
|
|
824
|
+
const { id, detail } = await canvas(args.projectId);
|
|
825
|
+
const nodes = detail.project.nodes;
|
|
826
|
+
const kindArg = String(args.kind || "all").toLowerCase();
|
|
827
|
+
const wantKind = (type) => kindArg === "all" || kindArg === type;
|
|
828
|
+
const limit = Math.max(1, Math.min(200, Math.floor(Number(args.limit) || 50)));
|
|
829
|
+
const pick = (obj, ...keys) => {
|
|
830
|
+
for (const key of keys) {
|
|
831
|
+
if (obj && obj[key] !== undefined && obj[key] !== null && obj[key] !== "") return obj[key];
|
|
832
|
+
}
|
|
833
|
+
return "";
|
|
834
|
+
};
|
|
835
|
+
|
|
836
|
+
const collected = new Map();
|
|
837
|
+
const push = (item) => {
|
|
838
|
+
const key = item.taskId || "node:" + item.nodeId;
|
|
839
|
+
const existing = collected.get(key);
|
|
840
|
+
// 同一任务以线上状态为准,节点侧信息补齐标题
|
|
841
|
+
if (!existing || (existing.status !== item.status && item.fromTask)) collected.set(key, item);
|
|
842
|
+
};
|
|
843
|
+
|
|
844
|
+
// 1) 节点侧:画布上所有待跟踪的媒体节点
|
|
845
|
+
const tracked = nodes
|
|
846
|
+
.filter((node) => ["image", "video", "audio"].includes(node.type) && wantKind(node.type))
|
|
847
|
+
.filter((node) => node.metadata?.taskId || (node.metadata?.status && !["success", "idle"].includes(node.metadata.status)))
|
|
848
|
+
.slice(0, limit);
|
|
849
|
+
|
|
850
|
+
for (let i = 0; i < tracked.length; i += 8) {
|
|
851
|
+
const chunk = tracked.slice(i, i + 8);
|
|
852
|
+
await Promise.all(chunk.map(async (node) => {
|
|
853
|
+
const taskId = String(node.metadata?.taskId || "");
|
|
854
|
+
let task = null;
|
|
855
|
+
if (taskId) {
|
|
856
|
+
try {
|
|
857
|
+
task = await client.getMediaTask(node.type, taskId);
|
|
858
|
+
} catch {
|
|
859
|
+
task = null;
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
push({
|
|
863
|
+
kind: node.type,
|
|
864
|
+
taskId,
|
|
865
|
+
nodeId: node.id,
|
|
866
|
+
nodeTitle: node.title || "",
|
|
867
|
+
status: String(pick(task, "status") || node.metadata?.status || "unknown"),
|
|
868
|
+
progress: Number(pick(task, "progress") ?? 0),
|
|
869
|
+
model: String(pick(task, "model") || node.metadata?.model || ""),
|
|
870
|
+
prompt: String(pick(task, "prompt") || node.metadata?.prompt || "").slice(0, 160),
|
|
871
|
+
error: String(pick(task, "error", "errorDetail", "error_detail") || node.metadata?.errorDetails || ""),
|
|
872
|
+
errorKind: String(pick(task, "errorKind", "error_kind") || ""),
|
|
873
|
+
errorHint: String(pick(task, "errorHint", "error_hint") || ""),
|
|
874
|
+
resultUrl: String(pick(task, "url", "image_url", "videoUrl", "video_url") || ""),
|
|
875
|
+
createdAt: pick(task, "createdAt", "created_at"),
|
|
876
|
+
fromTask: Boolean(task),
|
|
877
|
+
});
|
|
878
|
+
}));
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
// 2) 服务端侧:进行中任务(接口只返回未完成项),用于发现节点没记 taskId 的孤儿任务
|
|
882
|
+
const nodeIds = new Set(nodes.map((node) => node.id));
|
|
883
|
+
const [imageTasks, videoTasks] = await Promise.all([
|
|
884
|
+
kindArg === "all" || kindArg === "image" ? client.listTasks("image").catch(() => []) : [],
|
|
885
|
+
kindArg === "all" || kindArg === "video" ? client.listTasks("video").catch(() => []) : [],
|
|
886
|
+
]);
|
|
887
|
+
const adopt = (kind, task) => {
|
|
888
|
+
const nodeId = String(pick(task, "node_id", "nodeId") || "");
|
|
889
|
+
const sourceId = String(pick(task, "source_id", "sourceId") || "");
|
|
890
|
+
if (!nodeIds.has(nodeId) && sourceId !== id) return;
|
|
891
|
+
const node = nodes.find((item) => item.id === nodeId);
|
|
892
|
+
push({
|
|
893
|
+
kind,
|
|
894
|
+
taskId: String(pick(task, "id") || ""),
|
|
895
|
+
nodeId,
|
|
896
|
+
nodeTitle: node?.title || "",
|
|
897
|
+
status: String(pick(task, "status") || "unknown"),
|
|
898
|
+
progress: Number(pick(task, "progress") ?? 0),
|
|
899
|
+
model: String(pick(task, "model") || ""),
|
|
900
|
+
prompt: String(pick(task, "prompt") || "").slice(0, 160),
|
|
901
|
+
error: String(pick(task, "error", "errorDetail", "error_detail") || ""),
|
|
902
|
+
errorKind: String(pick(task, "errorKind", "error_kind") || ""),
|
|
903
|
+
errorHint: String(pick(task, "errorHint", "error_hint") || ""),
|
|
904
|
+
resultUrl: String(pick(task, "url", "image_url", "videoUrl", "video_url") || ""),
|
|
905
|
+
createdAt: pick(task, "createdAt", "created_at"),
|
|
906
|
+
fromTask: true,
|
|
907
|
+
});
|
|
908
|
+
};
|
|
909
|
+
imageTasks.forEach((task) => adopt("image", task));
|
|
910
|
+
videoTasks.forEach((task) => adopt("video", task));
|
|
911
|
+
|
|
912
|
+
let items = Array.from(collected.values());
|
|
913
|
+
if (args.status) items = items.filter((item) => item.status === args.status);
|
|
914
|
+
items.sort((a, b) => String(b.createdAt || "").localeCompare(String(a.createdAt || "")));
|
|
915
|
+
|
|
916
|
+
const failed = items.filter((item) => ["error", "failed", "failure"].includes(item.status));
|
|
917
|
+
const running = items.filter((item) => ["queued", "pending", "processing", "running", "in_progress", "loading"].includes(item.status));
|
|
918
|
+
return {
|
|
919
|
+
ok: true,
|
|
920
|
+
projectId: id,
|
|
921
|
+
total: items.length,
|
|
922
|
+
failedCount: failed.length,
|
|
923
|
+
runningCount: running.length,
|
|
924
|
+
failed,
|
|
925
|
+
running,
|
|
926
|
+
items: items.slice(0, limit),
|
|
927
|
+
};
|
|
928
|
+
},
|
|
929
|
+
},
|
|
930
|
+
{
|
|
931
|
+
name: "retry_media_task",
|
|
932
|
+
description: "重跑某个节点上的生成任务(复用节点已有 prompt/model,可覆盖)。不新建节点,直接刷新它的状态与任务 ID。",
|
|
933
|
+
inputSchema: schema({
|
|
934
|
+
projectId: PROJECT_ID,
|
|
935
|
+
nodeId: NODE_ID,
|
|
936
|
+
prompt: { type: "string", description: "覆盖原提示词" },
|
|
937
|
+
model: { type: "string", description: "覆盖原模型" },
|
|
938
|
+
channelId: { type: "string" },
|
|
939
|
+
}, ["nodeId"]),
|
|
940
|
+
handler: async (args) => {
|
|
941
|
+
const { id, detail } = await canvas(args.projectId);
|
|
942
|
+
const node = detail.project.nodes.find((item) => item.id === args.nodeId);
|
|
943
|
+
if (!node) return { ok: false, code: "node_not_found", message: "找不到节点 " + args.nodeId };
|
|
944
|
+
const kind = node.type === "video" ? "video" : node.type === "audio" ? "audio" : "image";
|
|
945
|
+
if (!["image", "video", "audio"].includes(node.type)) {
|
|
946
|
+
return { ok: false, code: "invalid_node_type", message: "只有 image/video/audio 节点可以重跑" };
|
|
947
|
+
}
|
|
948
|
+
const prompt = args.prompt || node.metadata?.prompt || node.metadata?.content || "";
|
|
949
|
+
if (!prompt) return { ok: false, code: "missing_prompt", message: "节点没有提示词,请显式传 prompt" };
|
|
950
|
+
const upstreamIds = detail.project.connections
|
|
951
|
+
.filter((conn) => conn.toNodeId === node.id)
|
|
952
|
+
.map((conn) => conn.fromNodeId);
|
|
953
|
+
const extra = {};
|
|
954
|
+
if (node.metadata?.size) extra.size = node.metadata.size;
|
|
955
|
+
if (node.metadata?.seconds) extra.seconds = node.metadata.seconds;
|
|
956
|
+
if (node.metadata?.voice) extra.voice = node.metadata.voice;
|
|
957
|
+
|
|
958
|
+
await client.submitOps(id, [{
|
|
959
|
+
type: "upsertNode",
|
|
960
|
+
node: { ...node, metadata: { ...node.metadata, status: "loading", errorDetails: "", errorDetail: "" } },
|
|
961
|
+
}]);
|
|
962
|
+
let task;
|
|
963
|
+
try {
|
|
964
|
+
task = await client.createMediaTask(kind, {
|
|
965
|
+
nodeId: node.id,
|
|
966
|
+
prompt,
|
|
967
|
+
model: args.model || node.metadata?.model,
|
|
968
|
+
channelId: args.channelId,
|
|
969
|
+
extra,
|
|
970
|
+
projectId: id,
|
|
971
|
+
});
|
|
972
|
+
} catch (error) {
|
|
973
|
+
await client.submitOps(id, [{
|
|
974
|
+
type: "upsertNode",
|
|
975
|
+
node: { ...node, metadata: { ...node.metadata, status: "error", errorDetails: String(error.message || error) } },
|
|
976
|
+
}]).catch(() => {});
|
|
977
|
+
throw error;
|
|
978
|
+
}
|
|
979
|
+
const taskId = task?.id || task?.task_id || "";
|
|
980
|
+
await client.submitOps(id, [{
|
|
981
|
+
type: "upsertNode",
|
|
982
|
+
node: { ...node, metadata: { ...node.metadata, status: task?.status || "loading", taskId, model: task?.model || node.metadata?.model } },
|
|
983
|
+
}]).catch(() => {});
|
|
984
|
+
return { ok: true, projectId: id, nodeId: node.id, taskId, status: task?.status || "queued", kind, reuseSources: upstreamIds };
|
|
985
|
+
},
|
|
986
|
+
},
|
|
987
|
+
{
|
|
988
|
+
name: "cancel_media_task",
|
|
989
|
+
description: "取消/删除一个生成任务(图片、视频)。可同时传 nodeId 把节点状态标记为 cancelled。音频任务服务端未开放删除。",
|
|
990
|
+
inputSchema: schema({
|
|
991
|
+
projectId: PROJECT_ID,
|
|
992
|
+
taskId: { type: "string" },
|
|
993
|
+
kind: { type: "string", description: "image(默认)| video" },
|
|
994
|
+
nodeId: { type: "string", description: "可选,同步更新该节点状态" },
|
|
995
|
+
}, ["taskId"]),
|
|
996
|
+
handler: async (args) => {
|
|
997
|
+
const kind = args.kind === "video" ? "video" : "image";
|
|
998
|
+
const result = await client.deleteTask(kind, args.taskId);
|
|
999
|
+
let nodeUpdated = false;
|
|
1000
|
+
if (args.nodeId) {
|
|
1001
|
+
try {
|
|
1002
|
+
const { id, detail } = await canvas(args.projectId);
|
|
1003
|
+
const node = detail.project.nodes.find((item) => item.id === args.nodeId);
|
|
1004
|
+
if (node) {
|
|
1005
|
+
await client.submitOps(id, [{
|
|
1006
|
+
type: "upsertNode",
|
|
1007
|
+
node: { ...node, metadata: { ...node.metadata, status: "cancelled", taskId: "" } },
|
|
1008
|
+
}]);
|
|
1009
|
+
nodeUpdated = true;
|
|
1010
|
+
}
|
|
1011
|
+
} catch {
|
|
1012
|
+
nodeUpdated = false;
|
|
1013
|
+
}
|
|
1014
|
+
}
|
|
1015
|
+
return { ok: true, kind, taskId: args.taskId, deleted: true, nodeUpdated, result };
|
|
1016
|
+
},
|
|
1017
|
+
},
|
|
1018
|
+
{
|
|
1019
|
+
name: "get_capabilities",
|
|
1020
|
+
description: "运行时自检:站点连通性、当前账号、可用模型、画布数量、支持的节点类型与工具清单。开新会话或怀疑配置不对时先跑它。",
|
|
1021
|
+
inputSchema: schema({}),
|
|
1022
|
+
handler: async () => {
|
|
1023
|
+
const checks = {};
|
|
1024
|
+
try {
|
|
1025
|
+
checks.health = await client.health();
|
|
1026
|
+
} catch (error) {
|
|
1027
|
+
checks.health = { ok: false, error: String(error.message || error) };
|
|
1028
|
+
}
|
|
1029
|
+
try {
|
|
1030
|
+
const user = await client.currentUser();
|
|
1031
|
+
checks.account = user ? { id: user.id, username: user.username, displayName: user.displayName, role: user.role, credits: user.credits } : null;
|
|
1032
|
+
} catch (error) {
|
|
1033
|
+
checks.account = { error: String(error.message || error) };
|
|
1034
|
+
}
|
|
1035
|
+
let catalog = null;
|
|
1036
|
+
try {
|
|
1037
|
+
catalog = await client.loadModelCatalog();
|
|
1038
|
+
} catch (error) {
|
|
1039
|
+
checks.models = { error: String(error.message || error) };
|
|
1040
|
+
}
|
|
1041
|
+
let canvases = [];
|
|
1042
|
+
try {
|
|
1043
|
+
canvases = await client.listCanvases();
|
|
1044
|
+
} catch (error) {
|
|
1045
|
+
checks.canvases = { error: String(error.message || error) };
|
|
1046
|
+
}
|
|
1047
|
+
const storage = await client.loadStorageConfig();
|
|
1048
|
+
const canUpload = Boolean(storage.mode) && (storage.mode === "server_sqlite_s3" || String(storage.mode).startsWith("server"));
|
|
1049
|
+
return {
|
|
1050
|
+
ok: Boolean(checks.health?.ok),
|
|
1051
|
+
baseUrl: client.baseUrl,
|
|
1052
|
+
checks,
|
|
1053
|
+
storage: { mode: storage.mode || "", canUpload },
|
|
1054
|
+
defaults: catalog?.defaults || {},
|
|
1055
|
+
modelCount: catalog?.availableModels?.length || 0,
|
|
1056
|
+
channelCount: catalog?.channels?.length || 0,
|
|
1057
|
+
canvasCount: canvases.length,
|
|
1058
|
+
nodeTypes: Object.keys(NODE_SPECS),
|
|
1059
|
+
tools: tools.map((tool) => tool.name),
|
|
1060
|
+
activeProjectId,
|
|
1061
|
+
};
|
|
1062
|
+
},
|
|
1063
|
+
},
|
|
1064
|
+
{
|
|
1065
|
+
name: "open_canvas",
|
|
1066
|
+
description: "返回画布的可直接打开链接(浏览器里可继续编辑),用于交付给用户。",
|
|
1067
|
+
inputSchema: schema({ projectId: PROJECT_ID }),
|
|
1068
|
+
handler: async (args) => {
|
|
1069
|
+
const { id, detail } = await canvas(args.projectId);
|
|
1070
|
+
return {
|
|
1071
|
+
ok: true,
|
|
1072
|
+
projectId: id,
|
|
1073
|
+
title: detail.project.title || "未命名画布",
|
|
1074
|
+
url: client.baseUrl + "/canvas/" + encodeURIComponent(id),
|
|
1075
|
+
path: "/canvas/" + encodeURIComponent(id),
|
|
1076
|
+
nodeCount: detail.project.nodes.length,
|
|
1077
|
+
connectionCount: detail.project.connections.length,
|
|
1078
|
+
};
|
|
1079
|
+
},
|
|
1080
|
+
},
|
|
1081
|
+
];
|
|
1082
|
+
|
|
1083
|
+
async function createMedia(kind, args) {
|
|
1084
|
+
const { id, detail } = await canvas(args.projectId);
|
|
1085
|
+
const nodes = detail.project.nodes;
|
|
1086
|
+
const sources = nodes.filter((node) => (args.sourceNodeIds || []).includes(node.id));
|
|
1087
|
+
const type = kind === "video" ? "video" : kind === "audio" ? "audio" : "image";
|
|
1088
|
+
const size = { width: NODE_SPECS[type].width, height: NODE_SPECS[type].height };
|
|
1089
|
+
const node = makeNode(type, {
|
|
1090
|
+
title: args.title || String(args.prompt).slice(0, 24),
|
|
1091
|
+
prompt: args.prompt,
|
|
1092
|
+
content: "",
|
|
1093
|
+
position: nextPosition(nodes, sources, size),
|
|
1094
|
+
metadata: { status: "loading" },
|
|
1095
|
+
});
|
|
1096
|
+
const extra = {};
|
|
1097
|
+
if (args.size) extra.size = args.size;
|
|
1098
|
+
if (args.seconds) extra.seconds = args.seconds;
|
|
1099
|
+
if (args.voice) extra.voice = args.voice;
|
|
1100
|
+
if (args.format) extra.format = args.format;
|
|
1101
|
+
const connections = sources.map((source) => ({ id: shortId("conn-"), fromNodeId: source.id, toNodeId: node.id }));
|
|
1102
|
+
await client.submitOps(id, [
|
|
1103
|
+
{ type: "upsertNode", node },
|
|
1104
|
+
...connections.map((connection) => ({ type: "upsertConnection", connection })),
|
|
1105
|
+
]);
|
|
1106
|
+
let task;
|
|
1107
|
+
try {
|
|
1108
|
+
task = await client.createMediaTask(kind, {
|
|
1109
|
+
nodeId: node.id,
|
|
1110
|
+
prompt: args.prompt,
|
|
1111
|
+
model: args.model,
|
|
1112
|
+
channelId: args.channelId,
|
|
1113
|
+
extra,
|
|
1114
|
+
projectId: id,
|
|
1115
|
+
});
|
|
1116
|
+
} catch (error) {
|
|
1117
|
+
// 提交失败:把节点标成 error,避免画布上永远转圈。
|
|
1118
|
+
await client.submitOps(id, [{
|
|
1119
|
+
type: "upsertNode",
|
|
1120
|
+
node: { ...node, metadata: { ...node.metadata, status: "error", errorDetails: String(error.message || error) } },
|
|
1121
|
+
}]).catch(() => {});
|
|
1122
|
+
throw error;
|
|
1123
|
+
}
|
|
1124
|
+
const taskId = task?.id || task?.task_id || "";
|
|
1125
|
+
await client.submitOps(id, [{
|
|
1126
|
+
type: "upsertNode",
|
|
1127
|
+
node: { ...node, metadata: { ...node.metadata, taskId, model: task?.model, status: task?.status || "loading" } },
|
|
1128
|
+
}]).catch(() => {});
|
|
1129
|
+
return { ok: true, projectId: id, nodeId: node.id, taskId, status: task?.status || "queued", kind };
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
return { tools, get activeProjectId() { return activeProjectId; } };
|
|
1133
|
+
}
|