dsh-game-material-master 0.1.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/lib/tools.js ADDED
@@ -0,0 +1,1365 @@
1
+ /**
2
+ * 游戏素材大师 —— 对话调用面(模型工具)。
3
+ *
4
+ * 目标:**插件里的每个功能都能通过对话调用**,多步流程(八方向图这种)
5
+ * 让 agent 自己推进 / 等待 / 审查,也可以每一步停下来交给人验收。
6
+ *
7
+ * 工具分工:
8
+ *
9
+ * | 工具 | 作用 |
10
+ * |---|---|
11
+ * | `game_material_call` | 万能通道:45 个远程方法逐个可调,覆盖全部功能 |
12
+ * | `game_material_status` | 读一眼当前进度(项目 / 任务 / 阶段 / 是否有任务在跑) |
13
+ * | `game_material_wait` | 阻塞等待到「没有任务在跑」或超时,回来就是可审查状态 |
14
+ * | `game_material_review` | 出一个**验收包**:每个产物的绝对 URL、状态、通过标记、深链接 |
15
+ * | `game_material_approve` | 打「通过 / 取消通过」(八方向图按阶段+方位,图片按张,序列帧按步骤) |
16
+ *
17
+ * 几个刻意的设计:
18
+ *
19
+ * - **不新增业务逻辑**:工具只是 `GameStudioGateway` 上已有方法的编排层,
20
+ * 避免同一件事有两份实现(界面走远程服务,模型走工具,底层同一份代码)。
21
+ * - **结果里永远带 `openUrl`**:模型把这条链接贴给用户,用户点一下就把
22
+ * Web GUI 切到插件对应页面验收。见 src/links.ts。
23
+ * - **不重复提交**:生成类调用照旧由宿主半区拦重复提交,工具层不再拦一次
24
+ * (两层拦截会让报错信息变得莫名其妙)。
25
+ */
26
+ import { readFile, stat } from "node:fs/promises";
27
+ import { basename, resolve } from "node:path";
28
+ import { DIRECTION_KEYS, directionOf } from "./directions.js";
29
+ import { listJobs } from "./pipeline.js";
30
+ import { listProjects, readProject } from "./store.js";
31
+ import { listImageJobs, readImageJob, sniffImage } from "./imagegen.js";
32
+ import { listSequenceJobs, readSequenceJob, listSequenceTasks } from "./seqgen.js";
33
+ import { listRigJobs, readRigJob, rigSnapshot } from "./riggen.js";
34
+ import { TOOL_METHODS } from "./wire.js";
35
+ import { PANEL_KEY, buildOpenLink, originForLinks } from "./links.js";
36
+ /** 三个模块的 key 与界面里的模块 key 完全一致。 */
37
+ const MODULES = ["sprite", "image", "sequence", "rig"];
38
+ /** 工具名统一前缀,避免和别家插件撞名。 */
39
+ const PREFIX = "game_material_";
40
+ /** 远程资源路由前缀,与 index.ts 的 ROUTE_PREFIX 一致。 */
41
+ const ROUTE_PREFIX = "/dsh-game-material-master";
42
+ /** 输出 schema:工具返回值是不定形的 JSON,这里只约束到「对象」。 */
43
+ const OBJECT_SCHEMA = { type: "object", additionalProperties: true };
44
+ const textBlocks = (text) => [{ type: "text", text }];
45
+ const asRecord = (value) => value !== null && typeof value === "object" ? value : {};
46
+ const asString = (value, fallback = "") => (typeof value === "string" ? value : fallback);
47
+ const clampInt = (value, fallback, min, max) => {
48
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
49
+ if (!Number.isFinite(n))
50
+ return fallback;
51
+ return Math.min(max, Math.max(min, Math.round(n)));
52
+ };
53
+ function moduleOf(value) {
54
+ return typeof value === "string" && MODULES.includes(value) ? value : undefined;
55
+ }
56
+ /** 任务 id 前缀决定它属于哪个模块(p… / i… / s… / r…)。 */
57
+ export function moduleForId(id) {
58
+ if (/^p[a-z0-9]+$/.test(id))
59
+ return "sprite";
60
+ if (/^i[a-z0-9]+$/.test(id))
61
+ return "image";
62
+ if (/^s[a-z0-9]+$/.test(id))
63
+ return "sequence";
64
+ if (/^r[a-z0-9]+$/.test(id))
65
+ return "rig";
66
+ return undefined;
67
+ }
68
+ /** 产物相对路径 → 浏览器可直接打开的绝对 URL。 */
69
+ function assetUrl(assetBase, relative) {
70
+ if (typeof relative !== "string" || relative === "")
71
+ return undefined;
72
+ return `${originForLinks()}${assetBase}${relative}`;
73
+ }
74
+ function cellsOf(nodes, assetBase, pick) {
75
+ return DIRECTION_KEYS.map((key) => {
76
+ const node = nodes?.[key] ?? {};
77
+ const picked = pick(node);
78
+ return {
79
+ direction: key,
80
+ label: directionOf(key)?.label ?? key,
81
+ status: String(node.status ?? "empty"),
82
+ approved: node.approved === true,
83
+ stale: node.stale === true,
84
+ file: picked.file,
85
+ url: picked.url ?? assetUrl(assetBase, picked.file),
86
+ ...(picked.extra ?? {}),
87
+ ...(typeof node.error === "string" && node.error !== "" ? { error: node.error } : {})
88
+ };
89
+ });
90
+ }
91
+ function spriteSnapshot(project) {
92
+ const assetBase = `${ROUTE_PREFIX}/assets/${project.id}/`;
93
+ // 「还有没有活在跑」= 节点状态 + 宿主的后台任务表。只看节点不行:批量任务是
94
+ // 一个方向一个方向开工的(抽帧并发只有 2),任务刚登记时八个方向可能都还不是
95
+ // running,只看节点会让 game_material_wait 立刻返回 settled=true,
96
+ // 而那时候一个产物都没出来。
97
+ const busy = DIRECTION_KEYS.some((key) => project.images?.[key]?.status === "running" ||
98
+ project.videos?.[key]?.status === "running" ||
99
+ project.frames?.[key]?.status === "running") || project.sheet?.status === "running" || listJobs(project.id).length > 0;
100
+ const count = (cells, status) => cells.filter((cell) => cell.status === status).length;
101
+ const approved = (cells) => cells.filter((cell) => cell.approved).length;
102
+ const images = cellsOf(project.images, assetBase, (node) => ({ file: node.file }));
103
+ const videos = cellsOf(project.videos, assetBase, (node) => ({ file: node.file }));
104
+ const frames = cellsOf(project.frames, assetBase, (node) => ({ file: node.strip, extra: { frameCount: node.frames?.length ?? 0 } }));
105
+ const sheetCell = [
106
+ {
107
+ direction: "sheet",
108
+ label: "整图",
109
+ status: String(project.sheet?.status ?? "empty"),
110
+ approved: project.sheet?.approved === true,
111
+ stale: false,
112
+ file: project.sheet?.file,
113
+ url: assetUrl(assetBase, project.sheet?.file),
114
+ ...(typeof project.sheet?.error === "string" && project.sheet.error !== "" ? { error: project.sheet.error } : {})
115
+ }
116
+ ];
117
+ return {
118
+ module: "sprite",
119
+ id: project.id,
120
+ name: project.name,
121
+ sourceFile: project.source?.file ?? null,
122
+ reviewMode: project.reviewMode ?? null,
123
+ busy,
124
+ stages: [
125
+ { stage: "images", title: "① 八方向绿幕图", ready: count(images, "ready"), running: count(images, "running"), error: count(images, "error"), approved: approved(images), total: 8, cells: images },
126
+ { stage: "videos", title: "② 行走动作视频", ready: count(videos, "ready"), running: count(videos, "running"), error: count(videos, "error"), approved: approved(videos), total: 8, cells: videos },
127
+ { stage: "frames", title: "③ 提取序列帧", ready: count(frames, "ready"), running: count(frames, "running"), error: count(frames, "error"), approved: approved(frames), total: 8, cells: frames },
128
+ { stage: "sheet", title: "④ 抠绿幕合成整图", ready: sheetCell[0].status === "ready" ? 1 : 0, running: sheetCell[0].status === "running" ? 1 : 0, error: sheetCell[0].status === "error" ? 1 : 0, approved: sheetCell[0].approved ? 1 : 0, total: 1, cells: sheetCell }
129
+ ],
130
+ settings: {
131
+ cellWidth: project.settings?.cellWidth,
132
+ cellHeight: project.settings?.cellHeight,
133
+ frameCount: project.settings?.frameCount,
134
+ pixelSize: project.settings?.pixelSize,
135
+ rowOrder: project.settings?.rowOrder
136
+ },
137
+ prompts: {
138
+ video: project.prompts?.video,
139
+ suffix: project.prompts?.suffix ?? "",
140
+ images: project.prompts?.images
141
+ },
142
+ runningTasks: listJobs(project.id),
143
+ logTail: Array.isArray(project.log) ? project.log.slice(-6).map((entry) => `${entry.level}: ${entry.message}`) : []
144
+ };
145
+ }
146
+ function imageSnapshot(job) {
147
+ const assetBase = `${ROUTE_PREFIX}/image-assets/${job.id}/`;
148
+ const items = (job.items ?? []).map((item) => ({
149
+ index: item.index,
150
+ status: item.status,
151
+ approved: item.approved === true,
152
+ source: item.source,
153
+ file: item.file,
154
+ url: assetUrl(assetBase, item.file),
155
+ keyedFile: item.keyedFile,
156
+ keyedUrl: assetUrl(assetBase, item.keyedFile),
157
+ backgroundFraction: item.backgroundFraction,
158
+ ...(typeof item.error === "string" && item.error !== "" ? { error: item.error } : {})
159
+ }));
160
+ return {
161
+ module: "image",
162
+ id: job.id,
163
+ name: job.name,
164
+ reviewMode: job.reviewMode ?? null,
165
+ busy: items.some((item) => item.status === "running"),
166
+ prompt: job.prompt,
167
+ suffix: job.suffix,
168
+ refs: (job.refs ?? []).map((ref) => ref.file),
169
+ settings: job.settings,
170
+ keying: job.keying,
171
+ items,
172
+ review: {
173
+ ready: items.filter((item) => item.status === "ready").length,
174
+ approved: items.filter((item) => item.approved).length,
175
+ error: items.filter((item) => item.status === "error").length
176
+ }
177
+ };
178
+ }
179
+ function sequenceSnapshot(job) {
180
+ const assetBase = `${ROUTE_PREFIX}/sequence-assets/${job.id}/`;
181
+ const steps = [
182
+ { step: "video", title: "① 生成视频", status: job.video?.status, approved: job.video?.approved === true, url: assetUrl(assetBase, job.video?.file), error: job.video?.error },
183
+ { step: "frames", title: "② 抽帧 + 抠像", status: job.frames?.status, approved: job.frames?.approved === true, files: (job.frames?.files ?? []).map((file) => assetUrl(assetBase, file)), keyed: (job.frames?.keyed ?? []).map((file) => assetUrl(assetBase, file)), stale: job.frames?.stale === true, error: job.frames?.error },
184
+ { step: "sheet", title: "③ 横向合成条图", status: job.sheet?.status, approved: job.sheet?.approved === true, url: assetUrl(assetBase, job.sheet?.file), error: job.sheet?.error }
185
+ ];
186
+ return {
187
+ module: "sequence",
188
+ id: job.id,
189
+ name: job.name,
190
+ mode: job.mode,
191
+ reviewMode: job.reviewMode ?? null,
192
+ prompt: job.prompt,
193
+ suffix: job.suffix,
194
+ refs: {
195
+ firstFrame: job.refs?.firstFrame?.file ?? null,
196
+ lastFrame: job.refs?.lastFrame?.file ?? null,
197
+ referenceImages: (job.refs?.referenceImages ?? []).length,
198
+ referenceVideos: (job.refs?.referenceVideos ?? []).length
199
+ },
200
+ busy: steps.some((step) => step.status === "running"),
201
+ settings: job.settings,
202
+ keying: job.keying,
203
+ steps,
204
+ runningTasks: listSequenceTasks(job.id)
205
+ };
206
+ }
207
+ /** 读一个目标(项目 / 图片任务 / 序列帧任务 / 骨骼动画任务)的快照。 */
208
+ async function snapshotOf(module, id) {
209
+ if (module === "sprite") {
210
+ const project = await readProject(id);
211
+ if (project === undefined)
212
+ throw new Error(`找不到八方向图项目:${id}`);
213
+ return spriteSnapshot(project);
214
+ }
215
+ if (module === "image") {
216
+ const job = await readImageJob(id);
217
+ if (job === undefined)
218
+ throw new Error(`找不到图片任务:${id}`);
219
+ return imageSnapshot(job);
220
+ }
221
+ if (module === "sequence") {
222
+ const job = await readSequenceJob(id);
223
+ if (job === undefined)
224
+ throw new Error(`找不到序列帧任务:${id}`);
225
+ return sequenceSnapshot(job);
226
+ }
227
+ const job = await readRigJob(id);
228
+ if (job === undefined)
229
+ throw new Error(`找不到骨骼动画任务:${id}`);
230
+ // 工具侧要的是**绝对** URL(会直接贴给用户点),所以带上已上报的 origin。
231
+ return rigSnapshot(job, originForLinks());
232
+ }
233
+ /** 猜一个目标属于哪个模块:显式声明优先,其次按 id 前缀。 */
234
+ function resolveTarget(module, id) {
235
+ const declared = moduleOf(module);
236
+ if (declared !== undefined)
237
+ return declared;
238
+ const guessed = moduleForId(id);
239
+ if (guessed === undefined)
240
+ throw new Error(`无法判断 "${id}" 属于哪个模块,请显式给 module`);
241
+ return guessed;
242
+ }
243
+ /** 目标 → 深链接意图。 */
244
+ function intentOf(module, id, extra = {}) {
245
+ if (module === "sprite")
246
+ return { module, projectId: id, ...extra };
247
+ return { module, jobId: id, ...extra };
248
+ }
249
+ /** 结果里统一带上的「打开界面」信息。 */
250
+ function openInfo(intent, hint) {
251
+ return { panel: PANEL_KEY, openUrl: buildOpenLink(intent), openHint: hint };
252
+ }
253
+ /**
254
+ * 从一次远程调用的入参里推断该打开哪个界面。
255
+ * 推断不出来(例如 listProjects)就不给链接,免得把用户带到一个空页面上。
256
+ */
257
+ function intentFromCall(method, payload) {
258
+ const projectId = asString(payload.projectId);
259
+ const jobId = asString(payload.jobId);
260
+ const stage = typeof payload.stage === "string" ? payload.stage : undefined;
261
+ if (projectId !== "")
262
+ return { module: "sprite", projectId, stage };
263
+ if (jobId !== "") {
264
+ const module = moduleForId(jobId);
265
+ return module === undefined ? undefined : { module, jobId };
266
+ }
267
+ if (method.startsWith("listRigJob") || method.startsWith("createRigJob"))
268
+ return { module: "rig" };
269
+ if (method.startsWith("listImageJob") || method.startsWith("createImageJob"))
270
+ return { module: "image" };
271
+ if (method.startsWith("listSequenceJob") || method.startsWith("createSequenceJob"))
272
+ return { module: "sequence" };
273
+ if (method.startsWith("listProject") || method.startsWith("createProject"))
274
+ return { module: "sprite" };
275
+ return undefined;
276
+ }
277
+ // ── 工具注册 ────────────────────────────────────────────────────────────
278
+ /** `game_material_call` 的描述:把 45 个方法的用途与入参写清楚。 */
279
+ const CALL_DESCRIPTION = [
280
+ "调用「游戏素材大师」插件的任意远程方法——插件界面上的每个功能都能在这里调用。",
281
+ "配置:getConfig() / saveConfig(payload: 任意配置字段,如 arkApiKey、arkModel、minimaxModel、cellWidth…) / testArk() / testMinimax()",
282
+ "八方向图:listProjects() / createProject({name}) / getProject({projectId}) / deleteProject({projectId}) / renameProject({projectId,name}) /",
283
+ " uploadSource({projectId,name,data:base64}) / savePrompts({projectId,images?,video?,videoPerDirection?,suffix?,resetImagesToDefault?,resetVideoToDefault?}) /",
284
+ " saveSettings({projectId,settings}) / setApproved({projectId,stage:images|videos|frames|sheet,key?,approved}) / revealProject({projectId}) /",
285
+ " runImage({projectId,key,prompt?}) / runImages({projectId,force?}) / runVideos({projectId,keys?,regenerate?}) / pollVideos({projectId}) /",
286
+ " clearVideos({projectId,keys?}) / runFrames({projectId,keys?}) / rekey({projectId}) / compose({projectId})",
287
+ "图片生成:listImageJobs() / createImageJob({name}) / getImageJob({jobId}) / deleteImageJob({jobId}) /",
288
+ " saveImageJob({jobId,name?,prompt?,suffix?,settings?,keying?,approved?,index?}) / uploadImageRef({jobId,name,data}) / removeImageRef({jobId,file}) /",
289
+ " addImageItem({jobId,name,data}) / removeImageItem({jobId,index}) / runImageJob({jobId,count?}) / keyImageJob({jobId})",
290
+ "序列帧:listSequenceJobs() / createSequenceJob({name}) / getSequenceJob({jobId}) / deleteSequenceJob({jobId}) /",
291
+ " saveSequenceJob({jobId,name?,mode?,prompt?,suffix?,settings?,keying?,approved?,step?}) / uploadSequenceRef({jobId,kind:firstFrame|lastFrame|referenceImage|referenceVideo,name,data}) /",
292
+ " removeSequenceRef({jobId,kind,file?}) / runSequenceVideo({jobId}) / pollSequenceVideo({jobId}) / clearSequenceVideo({jobId}) /",
293
+ " runSequenceFrames({jobId,count?}) / keySequenceFrames({jobId}) / composeSequence({jobId})",
294
+ "骨骼动画生成:listRigJobs() / createRigJob({name}) / getRigJob({jobId}) / deleteRigJob({jobId}) /",
295
+ " saveRigJob({jobId,name?,sheetPrompt?,suffix?,resetSheetPrompt?,settings?,approved?,stage?parts|layout|rig|atlas,part?}) /",
296
+ " uploadRigSource({jobId,name,data:角色整图}) / uploadRigPart({jobId,name:部件名,data:部件PNG}) / removeRigPart({jobId,name}) /",
297
+ " setRigPartVisibility({jobId,name,hidden}) / saveRigLayoutItem({jobId,name,x?,y?,width?,height?,rotation?,z?}) /",
298
+ " setRigSemantics({jobId,parts:[{name,role?,parent?,proximal?,distal?,tags?}]})【语义:这块是什么、挂在谁身上、骨骼从哪端伸到哪端】/",
299
+ " setRigBoneOffsets({jobId,bones:[{name,x?,y?,rotation?}]}) / resetRigBoneOffsets({jobId,names?})【手工骨骼偏移,重跑骨骼不会覆盖它】/",
300
+ " setRigAnimationSettings({jobId,animations:[{id,duration?,amplitude?}]}) / resetRigAnimationSettings({jobId,ids?})【动画参数】/",
301
+ " tintRigParts({jobId,names?|tag?,tint:{hue?,saturation?,lightness?,brightness?,contrast?,rgb?},note?})【换色,落成新版本】/",
302
+ " uploadRigTexture({jobId,name,data}) / setRigTextureVersion({jobId,name,version}) / removeRigTextureVersion({jobId,name,version})【贴图版本】/",
303
+ " runRigRedraw({jobId,name,prompt,erode?})【★花钱:一次 Seedream 调用,用生图模型重绘单个部件】/",
304
+ " runRigSheet({jobId})【花钱:一次 Seedream 调用,把角色拆成部件摊平图】/ runRigSegment({jobId})【本地分割,免费】/",
305
+ " runRigLayout({jobId,names?})【本地装配定位,免费;只给 names 就只重跑那几个部件】/",
306
+ " runRigBones({jobId})【本地生成骨架与动画,同时产出 Spine 4.2 skeleton.json 与 DragonBones 5.5 skeleton_ske.json】/",
307
+ " runRigAtlas({jobId})【本地打包图集,同时产出 Spine .atlas 与 DragonBones _tex.json】",
308
+ " ★ 自动摆位不准时用 setRigLayoutHints:先 read_image 看 getRigJob 返回的 partsMontagePath(部件按 partsOrder 顺序排列)",
309
+ "说明:key 是方向英文字面量(front/back/downLeft/downRight/upLeft/upRight/left/right);data 是原始文件字节的 base64(不带 data: 前缀);",
310
+ "生成类方法立刻返回 {started:true},接着用 game_material_wait 等它跑完,再用 game_material_review 拿验收包。",
311
+ "调用结果里若带 openUrl,请把它作为 Markdown 链接贴给用户,用户点击即切换到插件对应页面。"
312
+ ].join("\n");
313
+ /**
314
+ * 注册对话调用面。
315
+ *
316
+ * @param host - 可选服务(tools / systemPrompt)
317
+ * @param gateway - 已经注册成 typert 远程服务的网关实例,工具直接复用它的方法
318
+ * @returns 每个贡献的 disposer 列表(按注册顺序)
319
+ */
320
+ export function registerStudioTools(host, gateway) {
321
+ const disposers = [];
322
+ const tools = host.tools;
323
+ /** 统一的注册包装:把 output schema 与 render 固定下来。 */
324
+ const register = (definition) => {
325
+ if (tools === undefined)
326
+ return;
327
+ disposers.push(tools.register(definition));
328
+ };
329
+ if (tools !== undefined) {
330
+ register({
331
+ name: `${PREFIX}call`,
332
+ description: CALL_DESCRIPTION,
333
+ parameters: {
334
+ type: "object",
335
+ additionalProperties: false,
336
+ properties: {
337
+ method: { type: "string", enum: TOOL_METHODS.map((entry) => entry.method), description: "要调用的远程方法名。" },
338
+ payload: { type: "object", additionalProperties: true, description: "方法入参对象;无参方法可省略。" }
339
+ },
340
+ required: ["method"]
341
+ },
342
+ output: {
343
+ schema: OBJECT_SCHEMA,
344
+ render: (_args, value) => textBlocks(renderCallResult(value))
345
+ },
346
+ async execute(args) {
347
+ const method = asString(args?.method);
348
+ const spec = TOOL_METHODS.find((entry) => entry.method === method);
349
+ if (spec === undefined)
350
+ throw new Error(`未知方法:${method}`);
351
+ const payload = args?.payload === undefined ? undefined : asRecord(args.payload);
352
+ if (spec.payload && payload === undefined)
353
+ throw new Error(`${method} 需要一个 payload 对象`);
354
+ if (!spec.payload && payload !== undefined && Object.keys(payload).length > 0) {
355
+ throw new Error(`${method} 不接受 payload`);
356
+ }
357
+ const fn = gateway[method];
358
+ if (typeof fn !== "function")
359
+ throw new Error(`方法未实现:${method}`);
360
+ let value;
361
+ try {
362
+ value = payload === undefined ? await fn.call(gateway) : await fn.call(gateway, payload);
363
+ }
364
+ catch (error) {
365
+ throw new Error(`${method} 调用失败:${error instanceof Error ? error.message : String(error)}`);
366
+ }
367
+ const result = { method, ok: true, value: value ?? null };
368
+ const intent = intentFromCall(method, payload ?? {});
369
+ if (intent !== undefined)
370
+ Object.assign(result, openInfo(intent, "点开可以看到这一步的实际产物并打「通过」"));
371
+ return result;
372
+ }
373
+ });
374
+ register({
375
+ name: `${PREFIX}status`,
376
+ description: [
377
+ "看一眼「游戏素材大师」的当前进度。",
378
+ "不给 id 时列出全部项目 / 图片任务 / 序列帧任务;给了 id 就返回该目标的阶段进度、每个产物的状态与绝对 URL、是否有任务在跑。",
379
+ "任何时候想确认「现在该做哪一步」都先调它。返回值里的 openUrl 请以 Markdown 链接贴给用户。"
380
+ ].join("\n"),
381
+ parameters: {
382
+ type: "object",
383
+ additionalProperties: false,
384
+ properties: {
385
+ module: { type: "string", enum: [...MODULES], description: "目标所属模块;给了 id 时可省略,宿主按 id 前缀判断。" },
386
+ id: { type: "string", description: "项目 id(p…)/ 图片任务 id(i…)/ 序列帧任务 id(s…)。" }
387
+ }
388
+ },
389
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderStatus(value)) },
390
+ async execute(args) {
391
+ const id = asString(args?.id);
392
+ if (id === "") {
393
+ const [projects, images, sequences, rigs] = await Promise.all([listProjects(), listImageJobs(), listSequenceJobs(), listRigJobs()]);
394
+ return {
395
+ module: moduleOf(args?.module) ?? null,
396
+ projects,
397
+ imageJobs: images,
398
+ sequenceJobs: sequences,
399
+ rigJobs: rigs,
400
+ links: {
401
+ sprite: buildOpenLink({ module: "sprite" }),
402
+ image: buildOpenLink({ module: "image" }),
403
+ sequence: buildOpenLink({ module: "sequence" }),
404
+ rig: buildOpenLink({ module: "rig" })
405
+ },
406
+ hint: "用 game_material_status({module,id}) 看某个目标的细节;八方向图的四步是 images → videos → frames → sheet。"
407
+ };
408
+ }
409
+ const module = resolveTarget(args?.module, id);
410
+ const snapshot = await snapshotOf(module, id);
411
+ const stage = typeof args?.stage === "string" ? args.stage : undefined;
412
+ return { ...snapshot, ...openInfo(intentOf(module, id, { stage }), "点开可以看到产物并打「通过」") };
413
+ }
414
+ });
415
+ register({
416
+ name: `${PREFIX}intake`,
417
+ description: [
418
+ "【固定流程第 0 步】用户一说要用「游戏素材大师」的某个功能,先调它,再动手。",
419
+ "返回三样东西:① `blockers` —— 必须先解决的阻塞(例如还没配 API Key);② `questions` —— 用户还没告知的关键参数,逐条问;",
420
+ "③ `reviewModeQuestion` —— 必须问清楚「自动审核结果」还是「每一步人工审核」。",
421
+ "在 `questions` 与 `reviewModeQuestion` 都得到用户答复之前,**不要**调用任何生成类 / 删除类方法。",
422
+ "用户答复后:用 `game_material_reviewMode` 把审核模式记下来,用 `game_material_call` 把参数写进目标,再开始生成。",
423
+ "已经明确告知过的参数不用重复问——只问这个工具列出来的、且用户确实没说的。"
424
+ ].join("\n"),
425
+ parameters: {
426
+ type: "object",
427
+ additionalProperties: false,
428
+ properties: {
429
+ module: { type: "string", enum: [...MODULES], description: "用户想用的是哪个模块。" },
430
+ id: { type: "string", description: "已有目标的 id(想在它基础上继续时给)。" },
431
+ told: {
432
+ type: "array",
433
+ items: { type: "string" },
434
+ description: "用户已经明确告知过的参数名(如 prompt、count、mode、direction),这些不再重复问。"
435
+ }
436
+ },
437
+ required: ["module"]
438
+ },
439
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderIntake(value)) },
440
+ async execute(args) {
441
+ const module = moduleOf(args?.module);
442
+ if (module === undefined)
443
+ throw new Error(`未知模块:${String(args?.module)}`);
444
+ const id = asString(args?.id);
445
+ const told = new Set(Array.isArray(args?.told) ? args.told.map((entry) => String(entry)) : []);
446
+ const config = await gateway.getConfig();
447
+ // 已有目标时先读它的真实状态:源图 / 提示词 / 素材已经在的项目里就不再问一遍。
448
+ const target = id === "" ? undefined : await snapshotOf(module, id);
449
+ return intakeFor(module, id, told, config, target);
450
+ }
451
+ });
452
+ register({
453
+ name: `${PREFIX}upload`,
454
+ description: [
455
+ "把本机文件上传进「游戏素材大师」——界面上那些「上传」框的对话等价物。",
456
+ "参数 `path` 是文件的绝对路径或相对当前工作目录的路径,宿主自己读盘,**不要把 base64 贴进来**。",
457
+ "kind 取值:sprite=source(源设定图);image=ref(参考图,最多 10 张)| item(直接加一张图,只做抠像用);",
458
+ "sequence=firstFrame | lastFrame | referenceImage | referenceVideo;rig=source(角色整图)| part(单个部件 PNG,文件名即部件名)。",
459
+ "限制:图片 ≤30MB,参考视频 ≤40MB(平台请求体上限 64MB),图片类型按文件头嗅探。"
460
+ ].join("\n"),
461
+ parameters: {
462
+ type: "object",
463
+ additionalProperties: false,
464
+ properties: {
465
+ module: { type: "string", enum: [...MODULES], description: "目标所属模块。" },
466
+ id: { type: "string", description: "项目 id(p…)或任务 id(i… / s…)。" },
467
+ kind: { type: "string", enum: ["source", "ref", "item", "firstFrame", "lastFrame", "referenceImage", "referenceVideo", "part"], description: "上传到哪个槽位。" },
468
+ path: { type: "string", description: "本机文件路径。" },
469
+ name: { type: "string", description: "可选:展示用的文件名。" }
470
+ },
471
+ required: ["module", "id", "kind", "path"]
472
+ },
473
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderUpload(value)) },
474
+ async execute(args) {
475
+ const module = moduleOf(args?.module);
476
+ if (module === undefined)
477
+ throw new Error(`未知模块:${String(args?.module)}`);
478
+ const id = asString(args?.id);
479
+ const kind = asString(args?.kind);
480
+ const path = asString(args?.path);
481
+ if (path === "")
482
+ throw new Error("path 不能为空");
483
+ return uploadFromPath(gateway, module, id, kind, path, asString(args?.name) || undefined);
484
+ }
485
+ });
486
+ register({
487
+ name: `${PREFIX}reviewMode`,
488
+ description: [
489
+ "记录用户选的审核模式(固定流程必问项之一):`auto` = agent 自己审完结果就往下走;`manual` = 每一步产出后停下来等用户打「通过」。",
490
+ "记在目标自己身上,之后每一轮都按它走,不必再问。重复调用即改选。",
491
+ "用户明确说「自动跑完就行」→ auto;说「每步我看一下 / 我要审核」→ manual。用户没表态就不要猜,先问。"
492
+ ].join("\n"),
493
+ parameters: {
494
+ type: "object",
495
+ additionalProperties: false,
496
+ properties: {
497
+ module: { type: "string", enum: [...MODULES], description: "目标所属模块。" },
498
+ id: { type: "string", description: "项目 id(p…)或任务 id(i… / s…)。" },
499
+ reviewMode: { type: "string", enum: ["auto", "manual"], description: "审核模式。" }
500
+ },
501
+ required: ["module", "id", "reviewMode"]
502
+ },
503
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderReviewMode(value)) },
504
+ async execute(args) {
505
+ const module = moduleOf(args?.module);
506
+ if (module === undefined)
507
+ throw new Error(`未知模块:${String(args?.module)}`);
508
+ const result = await gateway.setReviewMode({
509
+ module,
510
+ id: asString(args?.id),
511
+ reviewMode: asString(args?.reviewMode)
512
+ });
513
+ return { ...result, ...openInfo(intentOf(module, asString(args?.id)), "点开看验收结果") };
514
+ }
515
+ });
516
+ register({
517
+ name: `${PREFIX}wait`,
518
+ description: [
519
+ "等待某个目标跑完当前这一步。",
520
+ "每 1.5 秒读一次状态,直到「没有任务在跑」或超时;返回等待结束时的完整状态(含 openUrl 与验收信息)。",
521
+ "生成类调用(runImages / runVideos / runFrames / compose / runImageJob / runSequenceVideo …)之后紧接着调它,",
522
+ "拿到 settled=true 再判断下一步。超时不算失败——超时后可以再调一次,或先把 openUrl 贴给用户。",
523
+ "注意:等待期间不要同时提交同一个目标的新任务,重复提交会被宿主拒绝。"
524
+ ].join("\n"),
525
+ parameters: {
526
+ type: "object",
527
+ additionalProperties: false,
528
+ properties: {
529
+ module: { type: "string", enum: [...MODULES], description: "目标所属模块;可省略,按 id 前缀判断。" },
530
+ id: { type: "string", description: "项目 id(p…)/ 图片任务 id(i…)/ 序列帧任务 id(s…)。" },
531
+ timeoutSeconds: { type: "integer", description: "最长等待秒数,默认 120,上限 900。超时后返回当前状态。" }
532
+ },
533
+ required: ["id"]
534
+ },
535
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderWait(value)) },
536
+ async execute(args, exec) {
537
+ const id = asString(args?.id);
538
+ if (id === "")
539
+ throw new Error("id 不能为空");
540
+ const module = resolveTarget(args?.module, id);
541
+ const timeoutMs = clampInt(args?.timeoutSeconds, 120, 1, 900) * 1000;
542
+ const startedAt = Date.now();
543
+ let snapshot = await snapshotOf(module, id);
544
+ while (snapshot.busy === true && Date.now() - startedAt < timeoutMs) {
545
+ exec?.signal?.throwIfAborted?.();
546
+ await sleep(1500, exec?.signal);
547
+ snapshot = await snapshotOf(module, id);
548
+ }
549
+ const settled = snapshot.busy !== true;
550
+ return {
551
+ settled,
552
+ timedOut: !settled,
553
+ elapsedMs: Date.now() - startedAt,
554
+ ...snapshot,
555
+ ...openInfo(intentOf(module, id), "点开可以看到产物并打「通过」")
556
+ };
557
+ }
558
+ });
559
+ register({
560
+ name: `${PREFIX}review`,
561
+ description: [
562
+ "出验收包:把某一步的每个产物连成可直接打开的绝对 URL,附状态、通过标记与报错,再给出建议的下一步。",
563
+ "用户说「我看看」「验收一下」时用它,然后把 openUrl 以 Markdown 链接贴给用户,用户点击即切到插件对应页面。",
564
+ "用自己的判断验收时:逐项看 status 与 error,全部 ready 才继续下一步;有 error 就按 hint 里的方法重跑那一步。",
565
+ "阶段约定:八方向图 stage=images|videos|frames|sheet;骨骼动画 stage=parts|layout|rig|atlas;图片/序列帧任务只看某一个产物时用 index / step 过滤。"
566
+ ].join("\n"),
567
+ parameters: {
568
+ type: "object",
569
+ additionalProperties: false,
570
+ properties: {
571
+ module: { type: "string", enum: [...MODULES], description: "目标所属模块;可省略,按 id 前缀判断。" },
572
+ id: { type: "string", description: "项目 id(p…)/ 图片任务 id(i…)/ 序列帧任务 id(s…)。" },
573
+ stage: { type: "string", enum: ["images", "videos", "frames", "sheet", "parts", "layout", "rig", "atlas"], description: "八方向图 / 骨骼动画专用:只看某一个阶段。" },
574
+ direction: { type: "string", description: "八方向图专用:只看某一个方位(front/back/…)。" },
575
+ index: { type: "integer", description: "图片任务专用:只看第几张(从 0 开始)。" },
576
+ step: { type: "string", enum: ["video", "frames", "sheet"], description: "序列帧任务专用:只看某一步。" }
577
+ },
578
+ required: ["id"]
579
+ },
580
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderReview(value)) },
581
+ async execute(args) {
582
+ const id = asString(args?.id);
583
+ if (id === "")
584
+ throw new Error("id 不能为空");
585
+ const module = resolveTarget(args?.module, id);
586
+ const snapshot = await snapshotOf(module, id);
587
+ const stage = typeof args?.stage === "string" ? args.stage : undefined;
588
+ const direction = typeof args?.direction === "string" ? args.direction : undefined;
589
+ const index = args?.index === undefined ? undefined : clampInt(args.index, 0, 0, 99);
590
+ const step = typeof args?.step === "string" ? args.step : undefined;
591
+ const packet = {
592
+ module,
593
+ id,
594
+ name: snapshot.name,
595
+ busy: snapshot.busy === true,
596
+ ...openInfo(intentOf(module, id, { stage, direction }), "点开直接看产物并打「通过」")
597
+ };
598
+ if (module === "sprite") {
599
+ const stages = snapshot.stages.filter((entry) => stage === undefined || entry.stage === stage);
600
+ if (stages.length === 0)
601
+ throw new Error(`未知阶段:${stage}`);
602
+ packet.stages = stages.map((entry) => ({
603
+ ...entry,
604
+ cells: entry.cells.filter((cell) => direction === undefined || cell.direction === direction)
605
+ }));
606
+ packet.nextActions = spriteNextActions(snapshot, stage, direction);
607
+ }
608
+ else if (module === "image") {
609
+ const items = snapshot.items.filter((item) => index === undefined || item.index === index);
610
+ if (items.length === 0)
611
+ throw new Error(index === undefined ? "这个任务还没有产物" : `没有第 ${index} 张`);
612
+ packet.items = items;
613
+ packet.nextActions = imageNextActions(snapshot);
614
+ }
615
+ else if (module === "sequence") {
616
+ const steps = snapshot.steps.filter((entry) => step === undefined || entry.step === step);
617
+ if (steps.length === 0)
618
+ throw new Error(`未知步骤:${step}`);
619
+ packet.steps = steps;
620
+ packet.nextActions = sequenceNextActions(snapshot);
621
+ }
622
+ else {
623
+ const stages = snapshot.stages.filter((entry) => stage === undefined || entry.stage === stage);
624
+ if (stages.length === 0)
625
+ throw new Error(`未知阶段:${stage}`);
626
+ packet.stages = stages;
627
+ packet.parts = snapshot.parts.filter((part) => stage !== "layout" || part.status === "ready");
628
+ packet.review = snapshot.review;
629
+ packet.nextActions = rigNextActions(snapshot, stage);
630
+ }
631
+ return packet;
632
+ }
633
+ });
634
+ register({
635
+ name: `${PREFIX}approve`,
636
+ description: [
637
+ "给某一步的产物打「通过」或取消通过(等价于界面上的验收按钮)。",
638
+ "只有在用户明确说「这步可以」「通过」时才自动调用;用户要求逐步确认时,先贴 openUrl 停下来等回复。",
639
+ "八方向图:module=sprite,id=项目 id,stage=images|videos|frames|sheet,key 可只对某个方位生效(省略即整阶段)。",
640
+ "图片任务:module=image,id=任务 id,index 可只对某一张生效(省略即全任务)。",
641
+ "序列帧:module=sequence,id=任务 id,step=video|frames|sheet(省略即全部三步)。",
642
+ "骨骼动画:module=rig,id=任务 id,stage=parts|layout|rig|atlas(省略即四个阶段全打);stage=parts 时可再带 part 只对某个部件生效。"
643
+ ].join("\n"),
644
+ parameters: {
645
+ type: "object",
646
+ additionalProperties: false,
647
+ properties: {
648
+ module: { type: "string", enum: [...MODULES], description: "目标所属模块;可省略,按 id 前缀判断。" },
649
+ id: { type: "string", description: "项目 / 任务 id。" },
650
+ stage: { type: "string", enum: ["images", "videos", "frames", "sheet"], description: "八方向图:阶段。" },
651
+ key: { type: "string", description: "八方向图:只对某个方位生效(front/back/…)。" },
652
+ index: { type: "integer", description: "图片任务:只对某一张生效。" },
653
+ step: { type: "string", enum: ["video", "frames", "sheet"], description: "序列帧:只对某一步生效。" },
654
+ part: { type: "string", description: "骨骼动画:stage=parts 时只对某个部件生效。" },
655
+ approved: { type: "boolean", description: "true = 通过,false = 取消通过。" }
656
+ },
657
+ required: ["id", "approved"]
658
+ },
659
+ output: { schema: OBJECT_SCHEMA, render: (_args, value) => textBlocks(renderApprove(value)) },
660
+ async execute(args) {
661
+ const id = asString(args?.id);
662
+ if (id === "")
663
+ throw new Error("id 不能为空");
664
+ if (typeof args?.approved !== "boolean")
665
+ throw new Error("approved 必须是布尔值");
666
+ const module = resolveTarget(args?.module, id);
667
+ const approved = args.approved === true;
668
+ if (module === "sprite") {
669
+ const stage = asString(args?.stage, "images");
670
+ if (!["images", "videos", "frames", "sheet"].includes(stage))
671
+ throw new Error(`未知阶段:${stage}`);
672
+ const key = asString(args?.key) || undefined;
673
+ if (key !== undefined && directionOf(key) === undefined)
674
+ throw new Error(`未知方位:${key}`);
675
+ await gateway.setApproved({ projectId: id, stage, key, approved });
676
+ return { module, id, stage, key: key ?? null, approved, ...openInfo({ module, projectId: id, stage }, "点开看验收结果") };
677
+ }
678
+ if (module === "image") {
679
+ const job = await readImageJob(id);
680
+ if (job === undefined)
681
+ throw new Error(`找不到图片任务:${id}`);
682
+ const index = args?.index === undefined ? undefined : clampInt(args.index, 0, 0, 99);
683
+ const targets = (job.items ?? []).filter((item) => index === undefined || item.index === index);
684
+ if (targets.length === 0)
685
+ throw new Error(index === undefined ? "这个任务还没有产物" : `没有第 ${index} 张`);
686
+ // 走 saveImageJob 而不是直接写文件:生图模型是全局设置,保存时由宿主对齐当前模型。
687
+ await gateway.saveImageJob(index === undefined ? { jobId: id, approved } : { jobId: id, approved, index });
688
+ return { module, id, index: index ?? null, approved, count: targets.length, ...openInfo({ module: "image", jobId: id }, "点开看验收结果") };
689
+ }
690
+ if (module === "sequence") {
691
+ const job = await readSequenceJob(id);
692
+ if (job === undefined)
693
+ throw new Error(`找不到序列帧任务:${id}`);
694
+ const step = asString(args?.step) || undefined;
695
+ if (step !== undefined && !["video", "frames", "sheet"].includes(step))
696
+ throw new Error(`未知步骤:${step}`);
697
+ await gateway.saveSequenceJob(step === undefined ? { jobId: id, approved } : { jobId: id, approved, step });
698
+ return { module, id, step: step ?? null, approved, ...openInfo({ module: "sequence", jobId: id }, "点开看验收结果") };
699
+ }
700
+ const rigJob = await readRigJob(id);
701
+ if (rigJob === undefined)
702
+ throw new Error(`找不到骨骼动画任务:${id}`);
703
+ const rigStage = asString(args?.stage) || undefined;
704
+ if (rigStage !== undefined && !["parts", "layout", "rig", "atlas"].includes(rigStage))
705
+ throw new Error(`未知阶段:${rigStage}`);
706
+ const part = asString(args?.part) || undefined;
707
+ await gateway.saveRigJob(rigStage === "parts" && part !== undefined ? { jobId: id, approved, stage: "parts", part } : rigStage === undefined ? { jobId: id, approved } : { jobId: id, approved, stage: rigStage });
708
+ return { module, id, stage: rigStage ?? null, part: part ?? null, approved, ...openInfo({ module: "rig", jobId: id, stage: rigStage }, "点开看验收结果") };
709
+ }
710
+ });
711
+ }
712
+ const systemPrompt = host.systemPrompt;
713
+ if (systemPrompt !== undefined) {
714
+ disposers.push(systemPrompt.section({
715
+ name: "game-material-master",
716
+ order: 8600,
717
+ text: PROMPT_SECTION
718
+ }));
719
+ }
720
+ return disposers;
721
+ }
722
+ const PROMPT_SECTION = [
723
+ "## 游戏素材大师(game-material-master)",
724
+ "本机已挂载「游戏素材大师」插件:八方向图生成 / 图片生成 / 序列帧生成 / 骨骼动画生成四个模块,界面在侧栏「游戏素材大师」面板。",
725
+ "工具:`game_material_intake`(固定流程第 0 步)、`game_material_call`(万能通道,插件全部方法)、`game_material_upload`(按路径上传素材)、",
726
+ "`game_material_reviewMode`、`game_material_status`、`game_material_wait`、`game_material_review`、`game_material_approve`。",
727
+ "一律走这些工具,不要用 bash/shell 直接改 `<DSH_HOME>/game-material-master/` 下的 JSON——那会绕过宿主的复用与校验。",
728
+ "",
729
+ "### 固定流程(必须按这个顺序走)",
730
+ "第 0 步 · 先问,再动手:用户一说要用某个功能,**先调用 `game_material_intake`**,把它返回的 `questions` 逐条问清楚,",
731
+ "并且**必须问同一个问题**:「结果要自动审核,还是每一步人工审核?」——两者合并成一次提问,不要挤牙膏式地一问一停。",
732
+ "在关键参数与审核模式都拿到答复之前,**不要调用任何生成类 / 删除类方法**。",
733
+ "用户已经明确告知过的参数不必重复问;答复用 `game_material_call` 写进目标,审核模式用 `game_material_reviewMode` 记下来。",
734
+ "第 1 步 · 逐阶段推进:八方向图是 images → videos → frames → sheet;图片生成是 prompt → runImageJob → keyImageJob;",
735
+ "序列帧是 video → frames → sheet;骨骼动画是 parts → layout → rig → atlas。每次提交类调用之后**立刻** `game_material_wait`。",
736
+ "骨骼动画只有第 ① 步(runRigSheet)花钱,②③④ 都是本地计算,重跑不额外计费;装配失败时用 runRigLayout({jobId, names:[…]}) 只重跑那几个部件。",
737
+ "",
738
+ "### 骨骼动画的自动摆位不准时:给「视觉先验」(重要)",
739
+ "第 ② 步的自动定位是**纯几何匹配**,对「模型重画过的部件」(裙摆、袖子这类服装裁片)会失手:",
740
+ "它在错误位置也可能拿到不低的分数。这时**你(agent)就是那个视觉模型**,去做一次语义对应:",
741
+ " 1. read_image 看 `getRigJob` 返回的 `sourcePath`(角色参考图)与 `partsMontagePath`(全部部件的蒙太奇图,",
742
+ " 按 `partsOrder` 的先后从左上到右下排列,每格一个部件,带格线可以数格子);",
743
+ " 2. 逐个判断「这块部件在参考图的哪个位置」,给出**大致**的像素框(不需要精确,区域对就行);",
744
+ " 3. game_material_call({method:'setRigLayoutHints', payload:{jobId, hints:{部件名:{x,y,width,height}}}})",
745
+ " 然后 runRigLayout({jobId}) 重新装配。",
746
+ "实测效果:一张真实立绘从「头被摆到脚下面、16 个部件只有 3 个落在正确区域」变成「结构正确、13/16 落在指定区域」。",
747
+ "先验框给大一点没关系(搜索区域会自动向外放宽 35%),但**别给错区域**——给错了它就会老老实实往错的地方搜。",
748
+ "",
749
+ "### 骨骼动画的三层修改:语义 / 骨骼偏移 / 动画参数(都是本地免费,且互不覆盖)",
750
+ "这三层是**分开存的**,所以你重跑任何一步都不会抹掉另一层的人工改动。优先用它们,",
751
+ "而不是让用户重新生成整条链路:", " 1. **语义** `setRigSemantics({jobId, parts:[{name, role?, parent?, proximal?, distal?, tags?}]})`",
752
+ " —— 决定「这块是什么、挂在谁身上、骨骼从部件的哪一端伸到哪一端」。",
753
+ " `getRigJob` 返回的 `parts[].role/parent/proximal/distal` 是当前值,顶层 `semantics` 是校验结果",
754
+ " (`errors` 非空时写入会被拒绝并原样返回原因,据此修正后重试即可)。",
755
+ " **改语义只作废③骨骼与④图集,②里已经摆好的位置不受影响。**",
756
+ " 2. **骨骼偏移** `setRigBoneOffsets({jobId, bones:[{name, x?, y?, rotation?}]})`",
757
+ " —— 手工微调某根骨头(位移单位是参考图像素,旋转是度)。它与「重新推骨骼」互不覆盖,",
758
+ " 是「AI 重新想一遍、人调过的不丢」的保证;`resetRigBoneOffsets({jobId, names?})` 回到自动推的姿势。",
759
+ " 3. **动画参数** `setRigAnimationSettings({jobId, animations:[{id, duration?, amplitude?}]})`",
760
+ " —— `amplitude` 统一缩放旋转与位移(动作太大/再夸张一点),`duration` 改循环秒数。",
761
+ " 改完要 `runRigBones({jobId})` 重算。哪些动作会生成由 `saveRigJob` 的 `settings.animations` 决定。",
762
+ " 4. **贴图变体** `tintRigParts({jobId, names?|tag?, tint, note?})` 换色、`setRigTextureVersion({jobId, name, version})` 切版本。",
763
+ " 每一次换色 / 上传替换都**新增一个版本,永不覆盖原图**——所以「这张 AI 头发不行,换回原版」",
764
+ " 只是切一下 `version`,成本为零。`getRigJob` 的 `parts[].versions` 是版本表(带 `note` 说明每版怎么来的),",
765
+ " `parts[].activeTexture` 是当前生效的版本号。换色是**本地计算、免费**,随时可以试。",
766
+ " `tag` 参数可以按语义标签批量(例如所有 `cloth` 一起换色),适合「这套衣服整体换个色调」。",
767
+ " ★ 判断依据:先 `getRigJob` 看 `rig.warnings`(几何推导的告警)、`semantics.errors/warnings`(结构问题)、",
768
+ " `atlas.warnings`。**构建失败时先读 `stage.error`**——导出前校验(Spine 4.2 四条地雷、DragonBones 的",
769
+ " `tweenEasing` 缺省即阶跃与 `curve` 编码规则、循环接缝、图集越界/缺区域)不通过会直接让那一步失败,",
770
+ " 并把具体原因写在 error 里。",
771
+ " ★ ④ 图集现在同时产出**两种描述**:Spine 的 `skeleton.atlas` 与 DragonBones 的 `_tex.json`(`atlas.dragonBones[]`),",
772
+ " 两者是同一次装箱出来的,不要只导一个就以为齐了。③ 也同时产出 `rig.skeleton`(Spine 4.2)与",
773
+ " `rig.dragonBones.skeleton`(DragonBones 5.5)——同一个骨架的两种写法,给不同的引擎用。",
774
+ "第 2 步 · 每步都要审:`game_material_review` 拿验收包,逐项看 status / error / 绝对 URL。",
775
+ "第 3 步 · 按审核模式分岔:`auto` → 自己判断没问题就 `game_material_approve` 打通过并进入下一步;",
776
+ "`manual` → 贴出 openUrl 并**停下等用户回复**,只有用户明确说「通过 / 可以」才 `game_material_approve` 并继续。",
777
+ "失败只重跑失败的那一项(`runImage` / `runVideos({regenerate:true, keys:[…]})` / `runFrames({keys:[…]})`),不要整批重来。",
778
+ "",
779
+ "### 验收链接",
780
+ "`game_material_intake` / `status` / `wait` / `review` / `upload` 等返回的 `openUrl` 是给用户点的深链接。",
781
+ "输出时必须原样写成 Markdown 链接(例如 `[查看第 2 步验收](http://…/?dsh-gmm=1&module=sprite&project=…&stage=videos)`);",
782
+ "用户点击后界面会原地切到插件对应页面。不要改写成裸文本,也不要自己编 URL。",
783
+ "`manual` 模式下每完成一步都要贴一次;`auto` 模式下至少在全部完成或需要用户决策时贴。",
784
+ "",
785
+ "### 计费与重复提交",
786
+ "生图与生视频都真实计费:不要为了确认状态而重复提交同一个目标;提交类调用返回后一律先 `game_material_wait`。"
787
+ ].join("\n");
788
+ function sleep(ms, signal) {
789
+ return new Promise((resolve, reject) => {
790
+ if (signal?.aborted === true) {
791
+ reject(new Error("已取消"));
792
+ return;
793
+ }
794
+ const timer = setTimeout(() => {
795
+ signal?.removeEventListener?.("abort", onAbort);
796
+ resolve();
797
+ }, ms);
798
+ const onAbort = () => {
799
+ clearTimeout(timer);
800
+ reject(new Error("已取消"));
801
+ };
802
+ signal?.addEventListener?.("abort", onAbort, { once: true });
803
+ });
804
+ }
805
+ // ── 固定流程第 0 步:问清楚再动手 ────────────────────────────────────────
806
+ //
807
+ // 用户只说「用八方向图做个角色」的时候,缺的信息其实很多:源图、统一附加
808
+ // 提示词、要不要改默认参数、以及最关键的一条——**结果谁来审核**。
809
+ // 这些一律由 `game_material_intake` 按真实状态算出来,而不是让模型凭感觉问:
810
+ // 已经配好的 / 有默认值的进 `known`,真正缺的进 `questions`,
811
+ // 必须先解决的进 `blockers`。这样「问了什么」是可复现、可测的。
812
+ const REVIEW_MODE_QUESTION = {
813
+ id: "reviewMode",
814
+ question: "结果要「自动审核」还是「每一步人工审核」?",
815
+ options: [
816
+ { value: "auto", label: "自动审核", detail: "agent 自己检查每步产出与报错,直接往下推进;只在失败或全部完成时才找你" },
817
+ { value: "manual", label: "每一步人工审核", detail: "每步产出后 agent 把验收链接贴给你,你说「通过」它才进入下一步" }
818
+ ],
819
+ how: "用户答复后用 game_material_reviewMode 记下来(module + id + reviewMode)。"
820
+ };
821
+ function intakeFor(module, id, told, config, target) {
822
+ const reviewModeQuestion = REVIEW_MODE_QUESTION;
823
+ const blockers = [];
824
+ const questions = [];
825
+ const known = {};
826
+ /** 已经存在的事实(源图 / 提示词 / 素材)就不再问,直接列进 known。 */
827
+ const hasSource = target !== undefined && target.sourceFile !== null && target.sourceFile !== undefined;
828
+ const hasPrompt = target !== undefined && typeof target.prompt === "string" && target.prompt.trim() !== "";
829
+ const ask = (key, question, why, how) => {
830
+ if (told.has(key))
831
+ return;
832
+ questions.push({ key, question, why, how });
833
+ };
834
+ if (module === "sprite" || module === "image" || module === "rig") {
835
+ if (config?.arkApiKeySet !== true) {
836
+ blockers.push("还没配置火山方舟 API Key(生图必需):设置 → 游戏素材大师 → 火山方舟 API Key,配好点「测试连接」。");
837
+ }
838
+ known.生图模型 = config?.arkModel;
839
+ known.出图尺寸 = config?.arkSize;
840
+ }
841
+ if (module === "sequence") {
842
+ if (config?.minimaxApiKeySet !== true) {
843
+ blockers.push("还没配置 MiniMax API Key(生视频必需):设置 → 游戏素材大师 → MiniMax API Key,配好点「测试连接」。");
844
+ }
845
+ known.视频模型 = config?.minimaxModel;
846
+ known.BaseURL = config?.minimaxBaseUrl;
847
+ }
848
+ if (module === "sprite") {
849
+ known.默认单格尺寸 = `${config?.cellWidth ?? "?"}×${config?.cellHeight ?? "?"}`;
850
+ known.默认每段抽帧数 = config?.frameCount;
851
+ known.默认像素块 = config?.pixelSize;
852
+ known.默认行序 = config?.rowOrder;
853
+ known.四个阶段 = "① 八方向绿幕图 → ② 行走动作视频 → ③ 提取序列帧 → ④ 抠绿幕合成整图";
854
+ }
855
+ if (module === "image") {
856
+ known.默认张数范围 = "1~8(Seedream 约 0.2 元/张)";
857
+ known.参考图上限 = "10 张,可在提示词里写「图一」「图二」";
858
+ }
859
+ if (module === "sequence") {
860
+ known.两种输入模式 = "首尾帧模式(必须给首帧图)/ 多模态参考模式(参考图 ≤9 张 + 参考视频 ≤3 段),平台规定互斥";
861
+ known.分辨率与时长档位 = config?.minimaxCapabilities;
862
+ }
863
+ if (module === "rig") {
864
+ known.四个阶段 = "① 拆件 → ② 装配定位 → ③ 骨骼与动画 → ④ 图集";
865
+ known.只有第一步花钱 = "① 拆件是一次 Seedream 生图(约 0.2 元);②③④ 都是本地计算,重跑不额外花钱";
866
+ known.默认拆件网格 = `${config ? "" : ""}4 列 × 4 行 = 16 个标准人形部件(头/脖子/躯干/胯/上臂/小臂/手/大腿/小腿/脚),格子位置即部件身份`;
867
+ known.默认动画 = "idle 待机 / walk 行走 / run 奔跑 / wave 挥手 / jump 跳跃 / attack 攻击";
868
+ }
869
+ if (id === "") {
870
+ questions.push({
871
+ key: "target",
872
+ question: module === "sprite"
873
+ ? "新建一个项目,还是在已有项目上继续?"
874
+ : module === "image"
875
+ ? "新建一个图片任务,还是在已有任务上继续?"
876
+ : module === "sequence"
877
+ ? "新建一个序列帧任务,还是在已有任务上继续?"
878
+ : "新建一个骨骼动画任务,还是在已有任务上继续?",
879
+ why: "后面的参数都挂在项目 / 任务上。",
880
+ how: "新建:game_material_call({method:'createProject'|'createImageJob'|'createSequenceJob'|'createRigJob', payload:{name}}),返回的 id 就是后续 payload 里的 projectId / jobId。"
881
+ });
882
+ }
883
+ if (module === "sprite") {
884
+ if (hasSource)
885
+ known.源图 = target.sourceFile;
886
+ else {
887
+ ask("source", "用哪张角色设定图作为源图?(PNG / JPG,≤30MB)", "八方向图从这一张出发派生其余七个方位,没有它无法开始。", "给我文件路径后我用 game_material_upload({module:'sprite', id, kind:'source', path}) 上传。");
888
+ }
889
+ if (target?.reviewMode)
890
+ known.审核模式 = target.reviewMode;
891
+ ask("suffix", "有没有跨方向都要遵守的统一要求?(例如「必须穿同一双靴子」「不要出现文字」;可留空)", "会追加到每一张生图提示词末尾,改一次八个方向全生效。", "用 game_material_call 的 savePrompts({projectId, suffix}) 保存。");
892
+ ask("scope", "八个方向全做,还是只做指定方向?", "只做部分方向能明显省钱省时间。", "开始生成时 runImage({projectId,key}) 做单个方向,runImages({projectId}) 做全部。");
893
+ ask("tuning", "默认参数要改吗?(单格尺寸 / 每段抽帧数 / 像素块大小 / 行序 / 并发数;不改就用默认)", "这些决定了最终精灵图的规格。", "要改就用 saveSettings({projectId, settings})。");
894
+ ask("prompts", "每个方向的生图/视频提示词要用默认模板,还是你自己写?(默认模板已经把方位与可见部位写对了,建议先用默认)", "方位写错会导致八个方向看起来是抬头 / 低头而不是转身。", "要改就用 savePrompts。");
895
+ }
896
+ if (module === "image") {
897
+ if (hasPrompt)
898
+ known.提示词 = target.prompt;
899
+ else
900
+ ask("prompt", "想要什么画面?请给一句具体的中文提示词。", "生图的唯一必填项。", "saveImageJob({jobId, prompt}) 后 runImageJob({jobId, count})。");
901
+ ask("count", "生成几张?(1~8,默认 1)", "按张计费。", "runImageJob({jobId, count})。");
902
+ ask("refs", "要不要参考图?需要的话给我文件路径(最多 10 张)。", "带参考图时可以在提示词里写「图一」「图二」。", "game_material_upload({module:'image', id, kind:'ref', path})。");
903
+ ask("keying", "生成后要不要自动抠绿幕导出透明 PNG?", "抠像是本地做的、不额外收费。", "saveImageJob({jobId, keying:{enabled:true}}) 再 keyImageJob({jobId})。");
904
+ }
905
+ if (module === "rig") {
906
+ if (hasSource)
907
+ known.角色参考图 = target.sourceFile;
908
+ else {
909
+ ask("source", "用哪张**角色整图**作为参考?(PNG / JPG,≤30MB;要能看清全身)", "拆件、装配、骨骼全都以它为基准。", "给我文件路径后我用 game_material_upload({module:'rig', id, kind:'source', path}) 上传。");
910
+ }
911
+ ask("partsSource", "部件从哪来:让生图模型自动拆件(默认,一次约 0.2 元),还是你自己已经有分好的部件 PNG?", "已经有部件图的话可以跳过生图,直接用 uploadRigPart 逐张传(部件名就是文件名,例如 head.png / torso.png / left-upper-leg.png)。", "自动拆件:runRigSheet({jobId});手工上传:game_material_upload({module:'rig', id, kind:'part', path})。");
912
+ ask("animations", "要生成哪些动画?(默认全做:待机/行走/奔跑/挥手/跳跃/攻击)", "动画是本地查表生成的,多做几个不额外花钱。", "saveRigJob({jobId, settings:{animations:[...]}})。");
913
+ if (target?.reviewMode)
914
+ known.审核模式 = target.reviewMode;
915
+ }
916
+ if (module === "sequence") {
917
+ ask("mode", "用「首尾帧模式」还是「多模态参考模式」?(平台规定只能二选一)", "两种模式的素材要求完全不同。", "saveSequenceJob({jobId, mode:'frames'|'reference'})。");
918
+ if (target !== undefined && (target.refs?.firstFrame !== null || target.refs?.referenceImages > 0 || target.refs?.referenceVideos > 0)) {
919
+ known.已上传素材 = target.refs;
920
+ }
921
+ else {
922
+ ask("material", "对应模式要用的素材:首尾帧模式给首帧图(尾帧可选);参考模式给参考图(≤9 张)和/或参考视频(≤3 段,每段 2~15 秒)。", "没有素材无法提交。", "game_material_upload({module:'sequence', id, kind:'firstFrame'|'lastFrame'|'referenceImage'|'referenceVideo', path})。");
923
+ }
924
+ if (hasPrompt)
925
+ known.提示词 = target.prompt;
926
+ else
927
+ ask("prompt", "希望这段动作是什么样的?请给一句提示词。", "视频生成的必填项。", "saveSequenceJob({jobId, prompt})。");
928
+ ask("duration", "时长和分辨率用当前模型档位里的哪个?(不改就用默认)", "不同模型支持的档位不同。", "saveSequenceJob({jobId, settings:{duration, resolution}})。");
929
+ ask("frames", "抽几帧、单格多大?(默认按全局配置)", "决定最终横向条图的规模。", "saveSequenceJob({jobId, settings:{frameCount, cellWidth, cellHeight}})。");
930
+ }
931
+ return {
932
+ module,
933
+ id: id === "" ? null : id,
934
+ blockers,
935
+ questions,
936
+ reviewModeQuestion,
937
+ known,
938
+ nextStep: blockers.length > 0
939
+ ? "先把 blockers 告诉用户并等它处理;同时把 questions 与 reviewModeQuestion 一起问掉,别分多轮挤牙膏。"
940
+ : "把 questions 与 reviewModeQuestion 合并成一次提问(能一次问完就别拆开),等用户答复后再动手。",
941
+ afterAnswered: "用户答复后:game_material_reviewMode 记审核模式 → game_material_call 写参数 → 开始生成 → game_material_wait。"
942
+ };
943
+ }
944
+ // ── 上传:宿主自己读盘,模型只给路径 ────────────────────────────────────
945
+ const IMAGE_MAX_BYTES = 30 * 1024 * 1024;
946
+ const VIDEO_MAX_BYTES = 40 * 1024 * 1024;
947
+ /** 各模块允许的 kind,避免把「源图」传到「参考视频」这类错位。 */
948
+ const UPLOAD_KINDS = {
949
+ sprite: ["source"],
950
+ image: ["ref", "item"],
951
+ sequence: ["firstFrame", "lastFrame", "referenceImage", "referenceVideo"],
952
+ rig: ["source", "part"]
953
+ };
954
+ async function uploadFromPath(gateway, module, id, kind, path, name) {
955
+ if (id === "")
956
+ throw new Error("id 不能为空");
957
+ if (!UPLOAD_KINDS[module].includes(kind)) {
958
+ throw new Error(`${module} 不支持 kind=${kind}(可用:${UPLOAD_KINDS[module].join(" / ")})`);
959
+ }
960
+ const absolute = resolve(path);
961
+ let info;
962
+ try {
963
+ info = await stat(absolute);
964
+ }
965
+ catch {
966
+ throw new Error(`读不到文件:${absolute}`);
967
+ }
968
+ if (!info.isFile())
969
+ throw new Error(`不是文件:${absolute}`);
970
+ const isVideo = kind === "referenceVideo";
971
+ const limit = isVideo ? VIDEO_MAX_BYTES : IMAGE_MAX_BYTES;
972
+ if (info.size > limit) {
973
+ throw new Error(`文件 ${(info.size / 1024 / 1024).toFixed(1)}MB 超过上限 ${(limit / 1024 / 1024).toFixed(0)}MB:${absolute}`);
974
+ }
975
+ const bytes = await readFile(absolute);
976
+ const base64 = bytes.toString("base64");
977
+ const fileName = name ?? basename(absolute);
978
+ if (!isVideo && sniffImage(base64) === undefined) {
979
+ throw new Error(`无法识别的图片格式(支持 PNG / JPEG / WebP / GIF / BMP):${absolute}`);
980
+ }
981
+ const call = gateway;
982
+ if (module === "sprite") {
983
+ await call.uploadSource({ projectId: id, name: fileName, data: base64 });
984
+ }
985
+ else if (module === "image") {
986
+ if (kind === "ref")
987
+ await call.uploadImageRef({ jobId: id, name: fileName, data: base64 });
988
+ else
989
+ await call.addImageItem({ jobId: id, name: fileName, data: base64 });
990
+ }
991
+ else if (module === "rig") {
992
+ if (kind === "part")
993
+ await call.uploadRigPart({ jobId: id, name: fileName, data: base64 });
994
+ else
995
+ await call.uploadRigSource({ jobId: id, name: fileName, data: base64 });
996
+ }
997
+ else {
998
+ await call.uploadSequenceRef({ jobId: id, kind, name: fileName, data: base64 });
999
+ }
1000
+ return {
1001
+ module,
1002
+ id,
1003
+ kind,
1004
+ name: fileName,
1005
+ path: absolute,
1006
+ bytes: info.size,
1007
+ ...openInfo(module === "sprite" ? { module, projectId: id } : { module, jobId: id }, "点开确认素材已就位")
1008
+ };
1009
+ }
1010
+ function renderIntake(value) {
1011
+ const lines = [`【固定流程第 0 步】${value.module}${value.id === null ? "(新目标)" : ` · ${value.id}`}`];
1012
+ if (value.blockers.length > 0) {
1013
+ lines.push("必须先解决:");
1014
+ for (const blocker of value.blockers)
1015
+ lines.push(` ✗ ${blocker}`);
1016
+ }
1017
+ lines.push("要问用户的参数:");
1018
+ if (value.questions.length === 0)
1019
+ lines.push(" (没有遗漏——用户已经说清了,可以直接动手)");
1020
+ for (const question of value.questions) {
1021
+ lines.push(` ? [${question.key}] ${question.question}`);
1022
+ lines.push(` ${question.why}`);
1023
+ }
1024
+ lines.push(`必须问:${value.reviewModeQuestion.question}`);
1025
+ for (const option of value.reviewModeQuestion.options)
1026
+ lines.push(` - ${option.label}:${option.detail}`);
1027
+ const knownKeys = Object.keys(value.known ?? {});
1028
+ if (knownKeys.length > 0) {
1029
+ lines.push("已知 / 有默认值(不必问,除非用户主动要改):");
1030
+ for (const key of knownKeys) {
1031
+ const entry = value.known[key];
1032
+ lines.push(` · ${key}:${typeof entry === "object" ? JSON.stringify(entry) : entry}`);
1033
+ }
1034
+ }
1035
+ lines.push(value.nextStep);
1036
+ lines.push(value.afterAnswered);
1037
+ return lines.join("\n");
1038
+ }
1039
+ function renderUpload(value) {
1040
+ const tail = typeof value.openUrl === "string" ? `\n打开界面:[${value.openHint}](${value.openUrl})` : "";
1041
+ return `已上传 ${value.name}(${(value.bytes / 1024).toFixed(0)} KB)→ ${value.module} · ${value.id} · ${value.kind}${tail}`;
1042
+ }
1043
+ function renderReviewMode(value) {
1044
+ const tail = typeof value.openUrl === "string" ? `\n打开界面:[${value.openHint}](${value.openUrl})` : "";
1045
+ return `${value.id} 的审核模式已记为「${value.reviewMode === "manual" ? "每一步人工审核" : "自动审核"}」。${value.reviewMode === "manual" ? "之后每一步产出后都要贴验收链接并停下等用户说通过。" : "之后 agent 自己审完即可继续。"}${tail}`;
1046
+ }
1047
+ // ── 工具结果的文字渲染 ──────────────────────────────────────────────────
1048
+ // 模型看到的是这段文本;链接与关键计数必须一眼可见。
1049
+ function renderCallResult(value) {
1050
+ const head = `${value.method} → ok`;
1051
+ const body = JSON.stringify(value.value, null, 2);
1052
+ const clipped = body.length > 4000 ? `${body.slice(0, 4000)}\n…(已截断)` : body;
1053
+ const link = typeof value.openUrl === "string" ? `\n打开界面:[${value.openHint}](${value.openUrl})` : "";
1054
+ return `${head}\n${clipped}${link}`;
1055
+ }
1056
+ /**
1057
+ * 阶段一行文字。八方向图 / 图片 / 序列帧的阶段带 ready/total/running,
1058
+ * 骨骼动画的阶段只有 status——按同一套字段渲染,骨骼动画会印出一串 undefined。
1059
+ */
1060
+ function renderStageLine(stage) {
1061
+ const tail = `${stage.approved === true ? " · 已通过" : ""}${stage.stale ? " · 需重做" : ""}${stage.error ? ` · ${stage.error}` : ""}`;
1062
+ if (typeof stage.ready === "number" || typeof stage.total === "number") {
1063
+ return `${stage.title}:ready ${stage.ready ?? 0}/${stage.total ?? 0},running ${stage.running ?? 0},error ${stage.error ?? "-"},已通过 ${stage.approved === true}`;
1064
+ }
1065
+ return `${stage.title}:${stage.status ?? "-"}${tail}`;
1066
+ }
1067
+ /** 骨骼动画阶段没有「格子」,产物是每阶段固定的几个 URL。 */
1068
+ function renderRigStageDetail(stage) {
1069
+ const lines = [];
1070
+ const push = (label, value) => {
1071
+ if (typeof value === "string" && value.length > 0)
1072
+ lines.push(` ${label}:${value}`);
1073
+ };
1074
+ if (stage.stage === "parts") {
1075
+ push("拆件图", stage.url);
1076
+ if (typeof stage.partReady === "number")
1077
+ lines.push(` 可用部件:${stage.partReady}`);
1078
+ }
1079
+ else if (stage.stage === "layout") {
1080
+ push("合成图", stage.composite);
1081
+ push("并排对比图", stage.comparison);
1082
+ if (Array.isArray(stage.unmatched) && stage.unmatched.length > 0) {
1083
+ lines.push(` 没匹配上(要手工摆或给先验):${stage.unmatched.join("、")}`);
1084
+ }
1085
+ }
1086
+ else if (stage.stage === "rig") {
1087
+ push("骨架 JSON(Spine 4.2)", stage.skeleton);
1088
+ push("骨架 JSON(DragonBones 5.5)", stage.dragonBones?.skeleton);
1089
+ push("预览页(双击可播动画)", stage.preview);
1090
+ if (Array.isArray(stage.animations) && stage.animations.length > 0)
1091
+ lines.push(` 动画:${stage.animations.join("、")}`);
1092
+ for (const warning of stage.warnings ?? [])
1093
+ lines.push(` ⚠ ${warning}`);
1094
+ }
1095
+ else if (stage.stage === "atlas") {
1096
+ push("图集 PNG", stage.image);
1097
+ push("图集文本(Spine)", stage.text);
1098
+ for (const entry of stage.dragonBones ?? [])
1099
+ push("贴图描述(DragonBones)", entry.url);
1100
+ if (typeof stage.width === "number" && typeof stage.height === "number")
1101
+ lines.push(` 尺寸:${stage.width}×${stage.height}`);
1102
+ }
1103
+ return lines;
1104
+ }
1105
+ function renderStatus(value) {
1106
+ if (Array.isArray(value.projects)) {
1107
+ const lines = [
1108
+ `项目(${value.projects.length}):`,
1109
+ ...value.projects.map((p) => ` - ${p.id} ${p.name} — 图 ${p.imageReady}/8 · 视频 ${p.videoReady}/8 · 帧 ${p.framesReady}/8${p.sheetReady ? " · 整图✓" : ""}`),
1110
+ `图片任务(${value.imageJobs.length}):`,
1111
+ ...value.imageJobs.map((j) => ` - ${j.id} ${j.name} — ${j.ready}/${j.total} 张(抠像 ${j.keyed})`),
1112
+ `序列帧任务(${value.sequenceJobs.length}):`,
1113
+ ...value.sequenceJobs.map((j) => ` - ${j.id} ${j.name} — 视频${j.videoReady ? "✓" : "✗"} 帧${j.frameReady ? "✓" : "✗"} 条图${j.sheetReady ? "✓" : "✗"}`),
1114
+ value.hint
1115
+ ];
1116
+ return lines.join("\n");
1117
+ }
1118
+ const lines = [`${value.name}(${value.id})${value.busy ? " — ⏳ 有任务在跑" : ""}`];
1119
+ // 拆件质检放在最前面:它管的是「这批拆件能不能信」,直接决定后面几步值不值得做。
1120
+ if (value.qa !== null && value.qa !== undefined) {
1121
+ lines.push(` ${renderRigQa(value.qa)}`);
1122
+ }
1123
+ if (Array.isArray(value.stages)) {
1124
+ for (const stage of value.stages) {
1125
+ lines.push(` ${renderStageLine(stage)}`);
1126
+ // 骨骼动画:阶段名之后直接把产物 URL 贴上,否则用户点不到东西。
1127
+ for (const detail of renderRigStageDetail(stage))
1128
+ lines.push(detail);
1129
+ }
1130
+ }
1131
+ if (Array.isArray(value.parts)) {
1132
+ const ready = value.parts.filter((part) => part.status === "ready").length;
1133
+ const placed = value.parts.filter((part) => part.placed).length;
1134
+ lines.push(` 部件 ${ready} 件可用,已放置 ${placed}`);
1135
+ const unmatched = value.parts.filter((part) => part.status === "ready" && !part.placed).map((part) => part.name);
1136
+ if (unmatched.length > 0)
1137
+ lines.push(` 没定位到的:${unmatched.join("、")}`);
1138
+ }
1139
+ if (Array.isArray(value.items))
1140
+ lines.push(` 图片 ${value.review?.ready ?? "?"} 张就绪,已通过 ${value.review?.approved ?? "?"},失败 ${value.review?.error ?? "?"}`);
1141
+ if (Array.isArray(value.steps)) {
1142
+ for (const step of value.steps)
1143
+ lines.push(` ${step.title}:${step.status}${step.approved ? " · 已通过" : ""}${step.error ? ` · ${step.error}` : ""}`);
1144
+ }
1145
+ if (typeof value.openUrl === "string")
1146
+ lines.push(`打开界面:[${value.openHint}](${value.openUrl})`);
1147
+ return lines.join("\n");
1148
+ }
1149
+ /** 拆件质检:把结论、重复件和建议都摆出来,agent 才能据此决定下一步。 */
1150
+ function renderRigQa(qa) {
1151
+ const head = `拆件质检:${qa.ok ? "通过" : "**不通过**"}(可信度 ${Math.round((qa.score ?? 0) * 100)}%)— ${qa.summary ?? ""}`;
1152
+ const lines = [head];
1153
+ for (const issue of qa.issues ?? []) {
1154
+ const mark = issue.level === "error" ? "✗" : "⚠";
1155
+ lines.push(` ${mark} [${issue.code}] ${issue.message}`);
1156
+ if (typeof issue.suggestion === "string" && issue.suggestion !== "")
1157
+ lines.push(` → ${issue.suggestion}`);
1158
+ }
1159
+ if (qa.expectedParts !== undefined)
1160
+ lines.push(` (参考图目测约 ${qa.expectedParts} 个独立部位)`);
1161
+ return lines.join("\n");
1162
+ }
1163
+ function renderWait(value) {
1164
+ const head = value.settled ? `已跑完(${(value.elapsedMs / 1000).toFixed(1)}s)` : `仍在跑(等待 ${(value.elapsedMs / 1000).toFixed(1)}s 后超时)`;
1165
+ return `${head}\n${renderStatus(value)}`;
1166
+ }
1167
+ function renderReview(value) {
1168
+ const lines = [`${value.name}(${value.id})验收包${value.busy ? " — ⏳ 仍有任务在跑" : ""}`];
1169
+ if (value.qa !== null && value.qa !== undefined)
1170
+ lines.push(renderRigQa(value.qa));
1171
+ if (Array.isArray(value.stages)) {
1172
+ for (const stage of value.stages) {
1173
+ lines.push(`${stage.title}${stage.stale ? " · 需重做" : ""}`);
1174
+ // 骨骼动画的阶段**没有 cells**(产物是每阶段固定的几个 URL),
1175
+ // 一律按 cells 迭代会直接把整个工具调用炸掉(stage.cells is not iterable)。
1176
+ for (const detail of renderRigStageDetail(stage))
1177
+ lines.push(detail);
1178
+ for (const cell of stage.cells ?? []) {
1179
+ lines.push(` - ${cell.label}:${cell.status}${cell.approved ? " · 已通过" : ""}${cell.stale ? " · 需重做" : ""}${cell.error ? ` · ${cell.error}` : ""}`);
1180
+ if (typeof cell.url === "string")
1181
+ lines.push(` ${cell.url}`);
1182
+ }
1183
+ }
1184
+ }
1185
+ if (Array.isArray(value.items)) {
1186
+ for (const item of value.items) {
1187
+ lines.push(` - 第 ${item.index} 张:${item.status}${item.approved ? " · 已通过" : ""}${item.error ? ` · ${item.error}` : ""}`);
1188
+ if (typeof item.url === "string")
1189
+ lines.push(` ${item.url}`);
1190
+ if (typeof item.keyedUrl === "string")
1191
+ lines.push(` ${item.keyedUrl}(透明 PNG)`);
1192
+ }
1193
+ }
1194
+ if (Array.isArray(value.steps)) {
1195
+ for (const step of value.steps) {
1196
+ lines.push(` - ${step.title}:${step.status}${step.approved ? " · 已通过" : ""}${step.stale ? " · 需重做" : ""}${step.error ? ` · ${step.error}` : ""}`);
1197
+ if (typeof step.url === "string")
1198
+ lines.push(` ${step.url}`);
1199
+ for (const url of step.keyed ?? [])
1200
+ lines.push(` ${url}`);
1201
+ }
1202
+ }
1203
+ if (Array.isArray(value.parts)) {
1204
+ for (const part of value.parts) {
1205
+ lines.push(` - ${part.label ?? part.name}:${part.status}${part.approved ? " · 已通过" : ""}${part.placed ? " · 已定位" : " · 未定位"}${part.hidden ? " · 已隐藏" : ""}${typeof part.score === "number" ? ` · 相似度 ${part.score}` : ""}${part.error ? ` · ${part.error}` : ""}`);
1206
+ if (typeof part.url === "string")
1207
+ lines.push(` ${part.url}`);
1208
+ }
1209
+ }
1210
+ for (const action of value.nextActions ?? [])
1211
+ lines.push(`建议:${action}`);
1212
+ if (typeof value.openUrl === "string")
1213
+ lines.push(`打开界面验收:[${value.openHint}](${value.openUrl})`);
1214
+ return lines.join("\n");
1215
+ }
1216
+ function renderApprove(value) {
1217
+ const where = [value.stage, value.step, value.key, value.index === null || value.index === undefined ? undefined : `第 ${value.index} 张`]
1218
+ .filter((part) => part !== undefined && part !== null)
1219
+ .join(" / ");
1220
+ const tail = typeof value.openUrl === "string" ? `\n打开界面:[${value.openHint}](${value.openUrl})` : "";
1221
+ return `${value.id}${where === "" ? "" : ` · ${where}`} → ${value.approved ? "已标记通过" : "已取消通过"}${tail}`;
1222
+ }
1223
+ // ── 「下一步该做什么」的推荐 ────────────────────────────────────────────
1224
+ function spriteNextActions(snapshot, stage, direction) {
1225
+ const byStage = Object.fromEntries(snapshot.stages.map((entry) => [entry.stage, entry]));
1226
+ const actions = [];
1227
+ const pick = (key) => (stage === undefined || stage === key ? byStage[key] : undefined);
1228
+ const images = pick("images");
1229
+ if (images !== undefined && images.ready < images.total) {
1230
+ actions.push(snapshot.sourceFile === null
1231
+ ? "还没有源图:先用 game_material_call({method:'uploadSource', payload:{projectId,name,data}}) 上传一张设定图"
1232
+ : `绿幕图还差 ${images.total - images.ready} 张:game_material_call({method:'runImages', payload:{projectId}}) 然后 game_material_wait`);
1233
+ }
1234
+ const videos = pick("videos");
1235
+ if (videos !== undefined && videos.ready < videos.total && (images === undefined || images.ready === images.total)) {
1236
+ actions.push(`视频还差 ${videos.total - videos.ready} 段:game_material_call({method:'runVideos', payload:{projectId}}) 然后 game_material_wait(这一步最贵,约几分钟)`);
1237
+ }
1238
+ const frames = pick("frames");
1239
+ if (frames !== undefined && frames.ready < frames.total && (videos === undefined || videos.ready === videos.total)) {
1240
+ actions.push("序列帧还没抽完:game_material_call({method:'runFrames', payload:{projectId}}) 然后 game_material_wait");
1241
+ }
1242
+ const sheet = pick("sheet");
1243
+ if (sheet !== undefined && sheet.ready < sheet.total && (frames === undefined || frames.ready === frames.total)) {
1244
+ actions.push("整图还没合成:game_material_call({method:'compose', payload:{projectId}}) 然后 game_material_wait");
1245
+ }
1246
+ const stageEntry = byStage[stage ?? ""];
1247
+ if (stageEntry !== undefined && stageEntry.error > 0) {
1248
+ actions.push(`有 ${stageEntry.error} 个产物失败:先看返回里的 error,再对失败项用 runImage / runVideos({regenerate:true, keys:[…]}) / runFrames({keys:[…]}) 重跑`);
1249
+ }
1250
+ if (direction !== undefined)
1251
+ actions.push(`只看方位 ${direction} 的重跑:game_material_call({method:'runVideos', payload:{projectId, keys:['${direction}'], regenerate:true}})`);
1252
+ if (actions.length === 0)
1253
+ actions.push("这一步已全部就绪:可以 game_material_approve 打通过,或进入下一阶段");
1254
+ return actions;
1255
+ }
1256
+ function imageNextActions(snapshot) {
1257
+ const actions = [];
1258
+ if (snapshot.review.ready === 0 && snapshot.review.error === 0) {
1259
+ actions.push("还没有产物:确认 prompt 非空后 game_material_call({method:'runImageJob', payload:{jobId,count}}) 然后 game_material_wait");
1260
+ }
1261
+ if (snapshot.review.error > 0)
1262
+ actions.push(`有 ${snapshot.review.error} 张失败:看 error 后调整提示词或参考图再重跑`);
1263
+ if (snapshot.keying?.enabled !== true)
1264
+ actions.push("还没开抠像:saveImageJob({jobId, keying:{enabled:true}}) 再 keyImageJob({jobId})");
1265
+ if (snapshot.review.approved === snapshot.review.ready && snapshot.review.ready > 0)
1266
+ actions.push("全部已通过:可以 game_material_call({method:'revealProject'|'getImageJob'}) 取用产物");
1267
+ return actions;
1268
+ }
1269
+ function rigNextActions(snapshot, stage) {
1270
+ const byStage = Object.fromEntries(snapshot.stages.map((entry) => [entry.stage, entry]));
1271
+ const actions = [];
1272
+ // 拆件质检的结论优先于一切阶段建议:它不通过时,后面每一步都在错误素材上做功。
1273
+ const qa = snapshot.qa;
1274
+ if (qa !== null && qa !== undefined && qa.ok !== true) {
1275
+ const duplicate = (qa.issues ?? []).find((issue) => issue.code === "duplicate-parts");
1276
+ const lowConfidence = (qa.issues ?? []).find((issue) => issue.code === "layout-low-confidence");
1277
+ if (duplicate !== undefined) {
1278
+ actions.push("**拆件质检不通过:有部件被重复画了多遍**。先用 read_image 看 partsMontagePath 确认哪几块是同一部位," +
1279
+ "用 setRigPartVisibility({jobId,name,hidden:true}) 隐藏多余的(每组留 1 块),再重跑 runRigQa 与 runRigLayout");
1280
+ }
1281
+ if (lowConfidence !== undefined) {
1282
+ actions.push("**装配相似度整体偏低**:模板匹配对「重新绘制过、与参考图不像」的部件失手。" +
1283
+ "用 read_image 看 sourcePath 与 partsMontagePath,判断每块在参考图的位置," +
1284
+ "setRigLayoutHints 写大致框后 runRigLayout;被遮挡的部位(例如裙下的整段大腿)直接给最终位置");
1285
+ }
1286
+ }
1287
+ else if (qa !== null && qa !== undefined && qa.ok === true && qa.issues?.length > 0) {
1288
+ actions.push("拆件质检有提示项(见上面的 ⚠):值得看一眼,但不阻塞");
1289
+ }
1290
+ const pick = (key) => (stage === undefined || stage === key ? byStage[key] : undefined);
1291
+ const parts = pick("parts");
1292
+ if (parts !== undefined && parts.status !== "ready") {
1293
+ actions.push(snapshot.sourceFile === null
1294
+ ? "还没有角色参考图:先用 game_material_upload({module:'rig', id, kind:'source', path}) 上传一张全身整图"
1295
+ : "拆件还没做:game_material_call({method:'runRigSheet', payload:{jobId}}),随后立刻 game_material_wait(这一步花钱,只跑一次)");
1296
+ }
1297
+ const layout = pick("layout");
1298
+ if (layout !== undefined && parts?.status === "ready" && layout.status !== "ready") {
1299
+ actions.push("部件已就绪但还没装配:game_material_call({method:'runRigLayout', payload:{jobId}}),随后 game_material_wait(本地计算,免费)");
1300
+ }
1301
+ if (layout !== undefined && layout.status === "ready" && Object.keys(layout.hints ?? {}).length === 0) {
1302
+ actions.push("如果自动摆位的结果不对(合成图上明显错位),先 read_image 看 getRigJob 返回的 sourcePath 与 partsMontagePath," +
1303
+ "给每个部件一个大致像素框,用 setRigLayoutHints 写回去,再 runRigLayout 重跑一遍——实测这是把真实立绘摆对的关键一步");
1304
+ }
1305
+ if (layout !== undefined && Array.isArray(layout.unmatched) && layout.unmatched.length > 0) {
1306
+ actions.push(`这些部件没匹配上:${layout.unmatched.join("、")}。可以让用户点开 openUrl 手工拖到正确位置,` +
1307
+ "也可以只重跑它们:runRigLayout({jobId, names:[…]})");
1308
+ }
1309
+ const rig = pick("rig");
1310
+ if (rig !== undefined && layout?.status === "ready" && rig.status !== "ready") {
1311
+ actions.push("装配没问题了:game_material_call({method:'runRigBones', payload:{jobId}}) 生成 skeleton.json 与动画预览(免费)");
1312
+ }
1313
+ if (rig !== undefined && Array.isArray(rig.warnings) && rig.warnings.length > 0) {
1314
+ actions.push(`骨骼构建有告警:${rig.warnings.join(";")}`);
1315
+ }
1316
+ if (rig !== undefined && rig.status === "ready") {
1317
+ // 这三层是「AI 与手工共存」的实际落地:任何一层重跑都不会抹掉另外两层的人工改动。
1318
+ const semantics = snapshot.semantics;
1319
+ if (semantics !== undefined && semantics.ok !== false && semantics.confirmed !== true && semantics.count > 0) {
1320
+ actions.push("语义还没被确认过:`getRigJob` 的 `parts[].role/parent/proximal/distal` 是按名字推断的默认值。" +
1321
+ "看一眼 partsMontagePath(蒙太奇图)就能判断有没有推断错的,用 setRigSemantics 改掉那几条——" +
1322
+ "改语义只作废骨骼与图集,②里已经摆好的位置不受影响");
1323
+ }
1324
+ const presets = Array.isArray(rig.animationPresets) ? rig.animationPresets : [];
1325
+ const untouched = presets.filter((preset) => preset.duration === preset.defaultDuration && preset.amplitude === 1);
1326
+ if (presets.length > 0 && untouched.length === presets.length) {
1327
+ actions.push("六个动作目前都是预设原值。如果角色的体型/节奏与预设不合(动作太大、循环太快)," +
1328
+ "用 setRigAnimationSettings({jobId, animations:[{id, amplitude, duration}]}) 调,再 runRigBones 重算——" +
1329
+ "幅度作用在缩放前的简写上,所以缓动不会被打乱");
1330
+ }
1331
+ // 导出前校验不通过会让那一步直接失败,原因写在 error 里。
1332
+ const broken = [pick("rig"), pick("atlas")].filter((entry) => entry !== undefined && entry.status === "error");
1333
+ if (broken.length > 0) {
1334
+ actions.push("构建失败多半是**导出前校验**拦下的(Spine 4.2 wire format / DragonBones 的 tweenEasing 与 curve 编码 / 循环接缝 / 图集越界与缺区域)。先读 error 里的具体位置再改,不要盲目重跑");
1335
+ }
1336
+ }
1337
+ const atlas = pick("atlas");
1338
+ if (atlas !== undefined && rig?.status === "ready" && atlas.status !== "ready") {
1339
+ actions.push("骨骼就绪:game_material_call({method:'runRigAtlas', payload:{jobId}}) 打包纹理图集(免费)");
1340
+ }
1341
+ const failed = Object.values(byStage).filter((entry) => entry.status === "error");
1342
+ if (failed.length > 0)
1343
+ actions.push(`有阶段失败(${failed.map((entry) => entry.stage).join("、")}):看返回里的 error 后只重跑那一步`);
1344
+ if (actions.length === 0)
1345
+ actions.push("四个阶段都已就绪:可以 game_material_approve 打通过,或把 openUrl 贴给用户验收动画预览");
1346
+ return actions;
1347
+ }
1348
+ function sequenceNextActions(snapshot) {
1349
+ const byStep = Object.fromEntries(snapshot.steps.map((entry) => [entry.step, entry]));
1350
+ const actions = [];
1351
+ if (byStep.video?.status !== "ready") {
1352
+ actions.push("视频还没好:game_material_call({method:'runSequenceVideo', payload:{jobId}}) 然后 game_material_wait(先确认首帧图或参考素材已上传)");
1353
+ }
1354
+ if (byStep.video?.status === "ready" && byStep.frames?.status !== "ready") {
1355
+ actions.push("视频已就绪但还没抽帧:game_material_call({method:'runSequenceFrames', payload:{jobId,count}})");
1356
+ }
1357
+ if (byStep.frames?.status === "ready" && byStep.sheet?.status !== "ready") {
1358
+ actions.push("帧已就绪但条图还没合成:game_material_call({method:'composeSequence', payload:{jobId}})");
1359
+ }
1360
+ if (byStep.frames?.stale === true)
1361
+ actions.push("抽帧参数改过,需要重抽:saveSequenceJob 保存参数后 runSequenceFrames");
1362
+ if (actions.length === 0)
1363
+ actions.push("三步都已就绪:可以 game_material_approve 打通过,或把 openUrl 贴给用户验收");
1364
+ return actions;
1365
+ }