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/index.js ADDED
@@ -0,0 +1,1602 @@
1
+ /**
2
+ * dsh-8dir-sprites —— 宿主半区。
3
+ *
4
+ * 一个 Typert 远程服务("spriteStudio")承担整条流水线的控制面:
5
+ * 配置读写、项目 CRUD、生图 / 视频 / 抽帧 / 合成四个阶段的启动与状态查询、
6
+ * 以及每一步的验收打标。
7
+ *
8
+ * 另外用 `ctx.webServer` 注册一条 prefix 路由,把项目目录里的图片和视频
9
+ * 直接发给浏览器——否则界面每帧都要靠 RPC 传 base64,又慢又费内存。
10
+ */
11
+ import { createReadStream, readdirSync, statSync } from "node:fs";
12
+ import { mkdir, stat, writeFile } from "node:fs/promises";
13
+ import { basename, dirname, extname, join } from "node:path";
14
+ import { fileURLToPath } from "node:url";
15
+ import { spawn } from "node:child_process";
16
+ import { TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
17
+ import { ARK_MODEL_PRESETS, DEFAULT_CONFIG, ROW_ORDER_VERSION, MINIMAX_HOST_PRESETS, MINIMAX_MODEL_PRESETS, loadConfig, maskConfig, migrateLegacyDataRoot, projectsRoot, saveConfig } from "./config.js";
18
+ import { DEFAULT_ROW_ORDER, DEFAULT_VIDEO_PROMPT, DIRECTION_KEYS, defaultImagePrompts, directionOf } from "./directions.js";
19
+ import { checkFfmpeg } from "./media.js";
20
+ import { testArk } from "./ark.js";
21
+ import { COMP_SHARE_BASE_URL, COMP_SHARE_MODEL_ID, capabilityOf, isCompshareModel, normalizeDuration, normalizeResolution, pathPrefixOf, testMiniMax } from "./minimax.js";
22
+ import { disposePipeline, ensurePoller, listJobs, pollVideosOnce, startAllImages, startCompose, startExtract, startImage, startRekey, startVideos, clearVideos } from "./pipeline.js";
23
+ import { assetPath, createProject, deleteProject, listProjects, log, patchProject, projectDir, projectExists, readProject, } from "./store.js";
24
+ import * as imagegen from "./imagegen.js";
25
+ import * as seqgen from "./seqgen.js";
26
+ import * as riggen from "./riggen.js";
27
+ import { MANIFEST, METHODS, SERVICE_NAME } from "./wire.js";
28
+ import { rememberClientOrigin } from "./links.js";
29
+ import { registerStudioTools } from "./tools.js";
30
+ /**
31
+ * 游戏素材大师 —— 宿主半区。
32
+ *
33
+ * 一个 Typert 远程服务("gameStudio")承载三个功能模块的控制面:
34
+ * ① 八方向图生成 ② 图片生成 ③ 序列帧生成
35
+ * 三者共用同一套配置(API Key / 模型 / 抠像默认值),但各自独立存项目。
36
+ *
37
+ * 另外用 `ctx.webServer` 注册一条 prefix 路由,把三个模块的产物直接发给浏览器。
38
+ */
39
+ export const name = "dsh-game-material-master";
40
+ /**
41
+ * `webServer` 必须声明成硬依赖:它要等真正 listen 成功之后才可用,
42
+ * 而本插件的 `apply` 与它几乎同时发生——只用 `ctx.get()` 探测的话,
43
+ * 大概率拿到 undefined,路由就永远不会注册(表现是资源请求一路 404)。
44
+ * 声明 inject 后 cordis 会把本插件挂起,直到 webServer 就绪再 apply。
45
+ */
46
+ export const inject = ["typert", "webServer"];
47
+ const ROUTE_PREFIX = "/dsh-game-material-master";
48
+ /**
49
+ * 本模块**被 import 时**捕获的自身信息,用于 `/_health`。
50
+ *
51
+ * 关键在「被 import 时」:宿主半区是进程启动时冻结的模块图,改了 `lib/*.js` 之后
52
+ * 如果没有真正重新 import,这里的数值就还是旧的。于是 `GET
53
+ * /dsh-game-material-master/_health` 变成一条**廉价且确定**的探针——
54
+ * 用来回答「运行中的宿主到底吃到了哪一版代码」,而不用去猜。
55
+ *
56
+ * ⚠️ 别只看 `moduleMtimeMs`:`tsc` 对**内容没变**的输出文件不重写,所以只改
57
+ * `riggen.js` 时 `index.js` 的 mtime 纹丝不动——曾经拿它当探针,结果误判成
58
+ * 「宿主没重载」而多花了一次付费调用。`builtAtMs` 取的是**整个产物目录里最新的
59
+ * 那个 mtime**,任何一次 build 都会让它前进。
60
+ */
61
+ const BOOT_INFO = (() => {
62
+ const info = { bootedAt: Date.now() };
63
+ try {
64
+ const self = fileURLToPath(import.meta.url);
65
+ info.module = basename(self);
66
+ info.moduleMtimeMs = statSync(self).mtimeMs;
67
+ // 同目录下所有构建产物的最新 mtime。
68
+ let newest = info.moduleMtimeMs;
69
+ for (const entry of readdirSync(dirname(self))) {
70
+ if (!entry.endsWith(".js"))
71
+ continue;
72
+ try {
73
+ const stamp = statSync(join(dirname(self), entry)).mtimeMs;
74
+ if (stamp > newest)
75
+ newest = stamp;
76
+ }
77
+ catch {
78
+ /* 单个文件读不到就跳过 */
79
+ }
80
+ }
81
+ info.builtAtMs = newest;
82
+ }
83
+ catch {
84
+ /* 取不到就只报 bootedAt,探针退化成「进程内不变」仍可用 */
85
+ }
86
+ return info;
87
+ })();
88
+ /**
89
+ * 改动这些设置会让已经生成的整图失效,必须重新合成。
90
+ * `workingLongEdge` / `cropInset` 不在其中——它们属于抽帧参数,另走 stale 标记。
91
+ */
92
+ const COMPOSE_SETTINGS = [
93
+ "cellWidth",
94
+ "cellHeight",
95
+ "frameCount",
96
+ "pixelSize",
97
+ "autoCrop",
98
+ "fillRatio",
99
+ "bottomMargin",
100
+ "fitMode",
101
+ "rowOrder",
102
+ "keyLow",
103
+ "keyHigh",
104
+ "despill",
105
+ "bgTolerance",
106
+ "edgeShrink"
107
+ ];
108
+ const PROJECT_ID_PATTERN = /^p[a-z0-9]{4,40}$/;
109
+ const MIME_TYPES = {
110
+ ".png": "image/png",
111
+ ".jpg": "image/jpeg",
112
+ ".jpeg": "image/jpeg",
113
+ ".webp": "image/webp",
114
+ ".gif": "image/gif",
115
+ ".bmp": "image/bmp",
116
+ ".mp4": "video/mp4",
117
+ ".webm": "video/webm",
118
+ ".json": "application/json; charset=utf-8",
119
+ // 骨骼动画的自包含预览是一整个 HTML 文件,必须用 text/html 才能被 iframe 渲染。
120
+ ".html": "text/html; charset=utf-8",
121
+ ".atlas": "text/plain; charset=utf-8"
122
+ };
123
+ function asString(value, fallback = "") {
124
+ return typeof value === "string" ? value : fallback;
125
+ }
126
+ function asRecord(value) {
127
+ return value !== null && typeof value === "object" ? value : {};
128
+ }
129
+ function clampInt(value, fallback, min, max) {
130
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
131
+ if (!Number.isFinite(n))
132
+ return fallback;
133
+ return Math.min(max, Math.max(min, Math.round(n)));
134
+ }
135
+ function clampFloat(value, fallback, min, max) {
136
+ const n = typeof value === "number" ? value : Number.parseFloat(String(value ?? ""));
137
+ if (!Number.isFinite(n))
138
+ return fallback;
139
+ return Math.min(max, Math.max(min, n));
140
+ }
141
+ /** 从 base64 头部嗅探图片类型,避免用户上传一个改了后缀的任意文件。 */
142
+ function sniffImage(base64) {
143
+ let head;
144
+ try {
145
+ head = Buffer.from(base64.slice(0, 64), "base64");
146
+ }
147
+ catch {
148
+ return undefined;
149
+ }
150
+ if (head.length >= 8 && head[0] === 0x89 && head[1] === 0x50 && head[2] === 0x4e && head[3] === 0x47) {
151
+ return { ext: "png", mime: "image/png" };
152
+ }
153
+ if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) {
154
+ return { ext: "jpg", mime: "image/jpeg" };
155
+ }
156
+ if (head.length >= 12 && head.toString("ascii", 0, 4) === "RIFF" && head.toString("ascii", 8, 12) === "WEBP") {
157
+ return { ext: "webp", mime: "image/webp" };
158
+ }
159
+ if (head.length >= 6 && head.toString("ascii", 0, 3) === "GIF") {
160
+ return { ext: "gif", mime: "image/gif" };
161
+ }
162
+ if (head.length >= 2 && head.toString("ascii", 0, 2) === "BM") {
163
+ return { ext: "bmp", mime: "image/bmp" };
164
+ }
165
+ return undefined;
166
+ }
167
+ function safeFileName(input) {
168
+ const base = basename(input).replace(/[^\w.\-()\u4e00-\u9fa5]+/g, "_");
169
+ return base === "" ? "source" : base.slice(0, 120);
170
+ }
171
+ export class GameStudioGateway extends TypertRemoteService {
172
+ ffmpegCache;
173
+ constructor(ctx) {
174
+ super(ctx, SERVICE_NAME);
175
+ }
176
+ // ── 配置 ────────────────────────────────────────────────────────────────
177
+ async configView() {
178
+ const config = await loadConfig();
179
+ return this.decorateConfig(config);
180
+ }
181
+ async decorateConfig(config) {
182
+ if (this.ffmpegCache === undefined)
183
+ this.ffmpegCache = await checkFfmpeg();
184
+ return {
185
+ ...maskConfig(config),
186
+ rowOrder: [...config.rowOrder],
187
+ defaults: { ...DEFAULT_CONFIG },
188
+ arkModels: ARK_MODEL_PRESETS,
189
+ minimaxModels: MINIMAX_MODEL_PRESETS,
190
+ minimaxHosts: MINIMAX_HOST_PRESETS,
191
+ // 「优云智算版 H3」由用户在模型下拉里显式选择,选中后网关地址/路径/档位全部跟着它走。
192
+ minimaxCompshareModelId: COMP_SHARE_MODEL_ID,
193
+ minimaxCompshareBaseUrl: COMP_SHARE_BASE_URL,
194
+ // 选中优云智算版时,界面显示的 Base URL 就是插件真正会用的那个地址。
195
+ minimaxBaseUrl: isCompshareModel(config.minimaxModel) ? COMP_SHARE_BASE_URL : config.minimaxBaseUrl,
196
+ // 优云智算网关的请求路径多一层 /minimax,界面据此展示真实端点。
197
+ minimaxPathPrefix: pathPrefixOf(config.minimaxModel),
198
+ // 分辨率档位与时长区间都跟着模型走,界面据此渲染控件;优云智算版更宽。
199
+ minimaxCapabilities: capabilityOf(config.minimaxModel),
200
+ minimaxCapabilitiesByModel: Object.fromEntries(MINIMAX_MODEL_PRESETS.map((preset) => [preset.id, capabilityOf(preset.id)])),
201
+ directions: DIRECTION_KEYS.map((key) => {
202
+ const direction = directionOf(key);
203
+ return { key, label: direction?.label ?? key, refs: direction?.refs ?? [] };
204
+ }),
205
+ ffmpeg: this.ffmpegCache,
206
+ dataRoot: projectsRoot()
207
+ };
208
+ }
209
+ async getConfig() {
210
+ return this.configView();
211
+ }
212
+ /**
213
+ * 保存配置。
214
+ * 约定:`arkApiKey` / `minimaxApiKey` **只有用户确实改了才带**——不带就是保持原值,
215
+ * 带空串才是清除。这样界面就不必把明文 key 回填到输入框里。
216
+ */
217
+ async saveConfig(payload) {
218
+ const input = asRecord(payload);
219
+ const patch = {};
220
+ const directKeys = [
221
+ "arkBaseUrl",
222
+ "arkModel",
223
+ "arkSize",
224
+ "arkWatermark",
225
+ "arkTimeoutMs",
226
+ "minimaxBaseUrl",
227
+ "minimaxModel",
228
+ "minimaxDuration",
229
+ "minimaxResolution",
230
+ "minimaxPromptOptimizer",
231
+ "minimaxTimeoutMs",
232
+ "cellWidth",
233
+ "cellHeight",
234
+ "frameCount",
235
+ "fitMode",
236
+ "workingLongEdge",
237
+ "pixelSize",
238
+ "autoCrop",
239
+ "fillRatio",
240
+ "bottomMargin",
241
+ "cropInset",
242
+ "keyLow",
243
+ "keyHigh",
244
+ "despill",
245
+ "bgTolerance",
246
+ "edgeShrink",
247
+ "rowOrder",
248
+ "concurrency"
249
+ ];
250
+ for (const key of directKeys) {
251
+ if (input[key] !== undefined)
252
+ patch[key] = input[key];
253
+ }
254
+ if (typeof input.arkApiKey === "string")
255
+ patch.arkApiKey = input.arkApiKey.trim();
256
+ if (typeof input.minimaxApiKey === "string")
257
+ patch.minimaxApiKey = input.minimaxApiKey.trim();
258
+ if (input.clearArkApiKey === true)
259
+ patch.arkApiKey = "";
260
+ if (input.clearMinimaxApiKey === true)
261
+ patch.minimaxApiKey = "";
262
+ const saved = await saveConfig(patch);
263
+ this.ffmpegCache = undefined;
264
+ return this.decorateConfig(saved);
265
+ }
266
+ async testArk() {
267
+ const config = await loadConfig();
268
+ if (config.arkApiKey.trim() === "")
269
+ throw new Error("尚未配置火山方舟 API Key");
270
+ return testArk({
271
+ baseUrl: config.arkBaseUrl,
272
+ apiKey: config.arkApiKey,
273
+ model: config.arkModel,
274
+ timeoutMs: config.arkTimeoutMs
275
+ });
276
+ }
277
+ async testMinimax() {
278
+ const config = await loadConfig();
279
+ return testMiniMax({
280
+ baseUrl: config.minimaxBaseUrl,
281
+ apiKey: config.minimaxApiKey,
282
+ model: config.minimaxModel,
283
+ timeoutMs: config.minimaxTimeoutMs
284
+ });
285
+ }
286
+ /**
287
+ * 浏览器半区上报自己的 `location.origin`。
288
+ *
289
+ * 宿主不知道对外 origin(可能被反代改写),而模型要在回复里贴可点链接,
290
+ * 只能由页面自己报一次。返回体里回带上「认没认」,方便界面自检。
291
+ */
292
+ async reportClientOrigin(payload) {
293
+ const origin = asString(asRecord(payload).origin);
294
+ const accepted = rememberClientOrigin(origin);
295
+ return accepted ? { ok: true, origin } : { ok: false, message: `拒绝非 http(s) origin:${origin}` };
296
+ }
297
+ // ── 项目 ────────────────────────────────────────────────────────────────
298
+ async listProjects() {
299
+ return { projects: await listProjects() };
300
+ }
301
+ async createProject(payload) {
302
+ const project = await createProject(asString(asRecord(payload).name, ""));
303
+ return { projectId: project.id };
304
+ }
305
+ async getProject(payload) {
306
+ const projectId = asString(asRecord(payload).projectId);
307
+ const project = await readProject(projectId);
308
+ if (project === undefined)
309
+ throw new Error(`项目不存在:${projectId}`);
310
+ return {
311
+ ...project,
312
+ jobs: listJobs(projectId),
313
+ assetBase: `${ROUTE_PREFIX}/assets/${projectId}/`
314
+ };
315
+ }
316
+ async deleteProject(payload) {
317
+ const projectId = asString(asRecord(payload).projectId);
318
+ await deleteProject(projectId);
319
+ return { ok: true };
320
+ }
321
+ async renameProject(payload) {
322
+ const input = asRecord(payload);
323
+ const projectId = asString(input.projectId);
324
+ const nextName = asString(input.name).trim();
325
+ if (nextName === "")
326
+ throw new Error("项目名不能为空");
327
+ await patchProject(projectId, (project) => {
328
+ project.name = nextName.slice(0, 80);
329
+ });
330
+ return { ok: true };
331
+ }
332
+ async uploadSource(payload) {
333
+ const input = asRecord(payload);
334
+ const projectId = asString(input.projectId);
335
+ if (!(await projectExists(projectId)))
336
+ throw new Error(`项目不存在:${projectId}`);
337
+ const base64 = asString(input.data).replace(/^data:[^;]+;base64,/, "");
338
+ if (base64 === "")
339
+ throw new Error("没有收到图片数据");
340
+ const bytes = Buffer.from(base64, "base64");
341
+ if (bytes.length === 0)
342
+ throw new Error("图片数据为空");
343
+ if (bytes.length > 30 * 1024 * 1024)
344
+ throw new Error("源图超过 30 MB,请先压缩后再上传");
345
+ const sniffed = sniffImage(base64);
346
+ if (sniffed === undefined)
347
+ throw new Error("无法识别的图片格式(支持 PNG / JPEG / WebP / GIF / BMP)");
348
+ const originalName = safeFileName(asString(input.name, `source.${sniffed.ext}`));
349
+ const stem = originalName.replace(/\.[^.]+$/, "") || "source";
350
+ const relative = `source/${stem}.${sniffed.ext}`;
351
+ await mkdir(join(projectDir(projectId), "source"), { recursive: true });
352
+ await writeFile(assetPath(projectId, relative), bytes);
353
+ await patchProject(projectId, (project) => {
354
+ project.source = { file: relative, name: originalName };
355
+ log(project, "info", `已上传源图:${originalName}(${(bytes.length / 1024).toFixed(0)} KB)`);
356
+ });
357
+ return { ok: true, file: relative, name: originalName };
358
+ }
359
+ async savePrompts(payload) {
360
+ const input = asRecord(payload);
361
+ const projectId = asString(input.projectId);
362
+ const images = input.images === undefined ? undefined : asRecord(input.images);
363
+ const video = typeof input.video === "string" ? input.video : undefined;
364
+ const perDirection = input.videoPerDirection === undefined ? undefined : asRecord(input.videoPerDirection);
365
+ const resetImages = input.resetImagesToDefault === true;
366
+ const resetVideo = input.resetVideoToDefault === true;
367
+ await patchProject(projectId, (project) => {
368
+ // 提示词模板升级后(例如这次把方位语义改对),老项目要能一键重新套用默认值。
369
+ if (resetImages)
370
+ project.prompts.images = defaultImagePrompts();
371
+ if (resetVideo) {
372
+ project.prompts.video = DEFAULT_VIDEO_PROMPT;
373
+ project.prompts.videoPerDirection = {};
374
+ }
375
+ if (images !== undefined) {
376
+ for (const key of DIRECTION_KEYS) {
377
+ if (typeof images[key] === "string" && images[key].trim() !== "") {
378
+ project.prompts.images[key] = images[key];
379
+ }
380
+ }
381
+ }
382
+ if (video !== undefined && video.trim() !== "")
383
+ project.prompts.video = video;
384
+ if (perDirection !== undefined) {
385
+ for (const key of DIRECTION_KEYS) {
386
+ const value = perDirection[key];
387
+ if (typeof value === "string" && value.trim() !== "")
388
+ project.prompts.videoPerDirection[key] = value;
389
+ else
390
+ delete project.prompts.videoPerDirection[key];
391
+ }
392
+ }
393
+ });
394
+ return { ok: true };
395
+ }
396
+ async saveSettings(payload) {
397
+ const input = asRecord(payload);
398
+ const projectId = asString(input.projectId);
399
+ const raw = asRecord(input.settings);
400
+ const changed = await patchProject(projectId, (project) => {
401
+ const before = { ...project.settings };
402
+ const current = project.settings;
403
+ project.settings = {
404
+ cellWidth: clampInt(raw.cellWidth, current.cellWidth, 16, 2048),
405
+ cellHeight: clampInt(raw.cellHeight, current.cellHeight, 16, 2048),
406
+ frameCount: clampInt(raw.frameCount, current.frameCount, 1, 64),
407
+ fitMode: raw.fitMode === "stretch" ? "stretch" : raw.fitMode === "contain" ? "contain" : current.fitMode,
408
+ workingLongEdge: clampInt(raw.workingLongEdge, current.workingLongEdge, 128, 2048),
409
+ pixelSize: clampInt(raw.pixelSize, current.pixelSize, 0, 32),
410
+ autoCrop: typeof raw.autoCrop === "boolean" ? raw.autoCrop : current.autoCrop,
411
+ fillRatio: clampFloat(raw.fillRatio, current.fillRatio, 0.5, 1),
412
+ bottomMargin: clampInt(raw.bottomMargin, current.bottomMargin, 0, 64),
413
+ cropInset: clampFloat(raw.cropInset, current.cropInset, 0, 0.2),
414
+ keyLow: clampInt(raw.keyLow, current.keyLow, 0, 255),
415
+ keyHigh: clampInt(raw.keyHigh, current.keyHigh, 1, 255),
416
+ despill: clampFloat(raw.despill, current.despill, 0, 1),
417
+ bgTolerance: clampInt(raw.bgTolerance, current.bgTolerance, 0, 160),
418
+ edgeShrink: clampInt(raw.edgeShrink, current.edgeShrink, 0, 8),
419
+ rowOrder: Array.isArray(raw.rowOrder) && raw.rowOrder.length > 0
420
+ ? raw.rowOrder.filter((key) => typeof key === "string" && directionOf(key) !== undefined)
421
+ : current.rowOrder.length > 0
422
+ ? current.rowOrder
423
+ : [...DEFAULT_ROW_ORDER],
424
+ rowOrderVersion: ROW_ORDER_VERSION,
425
+ concurrency: clampInt(raw.concurrency, current.concurrency, 1, 8)
426
+ };
427
+ if (project.settings.rowOrder.length === 0)
428
+ project.settings.rowOrder = [...DEFAULT_ROW_ORDER];
429
+ if (project.settings.keyHigh <= project.settings.keyLow)
430
+ project.settings.keyHigh = Math.min(255, project.settings.keyLow + 1);
431
+ const differs = (fields) => fields.some((field) => JSON.stringify(before[field]) !== JSON.stringify(project.settings[field]));
432
+ if (differs(["workingLongEdge", "cropInset"])) {
433
+ // 抽帧参数变了:raw.bin 已经作废,必须重抽,不能只重新合成。
434
+ for (const key of DIRECTION_KEYS) {
435
+ const node = project.frames[key];
436
+ if (node?.raw !== undefined)
437
+ node.stale = true;
438
+ }
439
+ }
440
+ return { compose: differs(COMPOSE_SETTINGS) };
441
+ });
442
+ // 改行序、格子尺寸、抠像参数……都会让已经生成的整图失效。这里自动重跑一次
443
+ // 合成,否则整图/预览会和设置对不上(按新行号去切旧图 → 取到错误的方向)。
444
+ if (changed.compose === true) {
445
+ const fresh = await readProject(projectId);
446
+ const hasFrames = fresh !== undefined && DIRECTION_KEYS.some((key) => fresh.frames[key]?.raw !== undefined);
447
+ if (hasFrames)
448
+ startCompose(projectId);
449
+ }
450
+ return { ok: true };
451
+ }
452
+ async setApproved(payload) {
453
+ const input = asRecord(payload);
454
+ const projectId = asString(input.projectId);
455
+ const stage = asString(input.stage);
456
+ const key = typeof input.key === "string" ? input.key : undefined;
457
+ const approved = input.approved === true;
458
+ await patchProject(projectId, (project) => {
459
+ if (stage === "images" && key !== undefined && project.images[key] !== undefined) {
460
+ project.images[key].approved = approved;
461
+ }
462
+ else if (stage === "images") {
463
+ for (const k of DIRECTION_KEYS)
464
+ project.images[k].approved = approved;
465
+ }
466
+ else if (stage === "videos" && key !== undefined && project.videos[key] !== undefined) {
467
+ project.videos[key].approved = approved;
468
+ }
469
+ else if (stage === "videos") {
470
+ for (const k of DIRECTION_KEYS)
471
+ if (project.videos[k].status === "ready")
472
+ project.videos[k].approved = approved;
473
+ }
474
+ else if (stage === "frames" && key !== undefined && project.frames[key] !== undefined) {
475
+ project.frames[key].approved = approved;
476
+ }
477
+ else if (stage === "frames") {
478
+ for (const k of DIRECTION_KEYS)
479
+ if (project.frames[k].status === "ready")
480
+ project.frames[k].approved = approved;
481
+ }
482
+ else if (stage === "sheet") {
483
+ project.sheet.approved = approved;
484
+ }
485
+ });
486
+ return { ok: true };
487
+ }
488
+ async revealProject(payload) {
489
+ const projectId = asString(asRecord(payload).projectId);
490
+ if (!(await projectExists(projectId)))
491
+ throw new Error(`项目不存在:${projectId}`);
492
+ const dir = projectDir(projectId);
493
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
494
+ try {
495
+ spawn(command, [dir], { detached: true, stdio: "ignore" }).unref();
496
+ }
497
+ catch (error) {
498
+ throw new Error(`无法打开目录:${error instanceof Error ? error.message : String(error)}`);
499
+ }
500
+ return { ok: true, dir };
501
+ }
502
+ /**
503
+ * 记录审核模式(`auto` = agent 自己审完继续;`manual` = 每步停下等用户确认)。
504
+ *
505
+ * 固定流程要求:动手之前先问用户选哪个。选完存在目标自己身上,
506
+ * 之后每一轮都由它决定「agent 继续」还是「停下来等回复」——不靠模型记性。
507
+ */
508
+ async setReviewMode(payload) {
509
+ const input = asRecord(payload);
510
+ const id = asString(input.id);
511
+ const module = asString(input.module);
512
+ const reviewMode = asString(input.reviewMode);
513
+ if (reviewMode !== "auto" && reviewMode !== "manual")
514
+ throw new Error(`未知审核模式:${reviewMode}`);
515
+ if (module === "sprite") {
516
+ await patchProject(id, (project) => {
517
+ project.reviewMode = reviewMode;
518
+ log(project, "info", `审核模式:${reviewMode === "manual" ? "每一步人工审核" : "agent 自动审核"}`);
519
+ });
520
+ return { ok: true, id, module, reviewMode };
521
+ }
522
+ if (module === "image") {
523
+ const job = await imagegen.readImageJob(id);
524
+ if (job === undefined)
525
+ throw new Error(`任务不存在:${id}`);
526
+ job.reviewMode = reviewMode;
527
+ await imagegen.writeImageJob(job);
528
+ return { ok: true, id, module, reviewMode };
529
+ }
530
+ if (module === "sequence") {
531
+ const job = await seqgen.readSequenceJob(id);
532
+ if (job === undefined)
533
+ throw new Error(`任务不存在:${id}`);
534
+ job.reviewMode = reviewMode;
535
+ await seqgen.writeSequenceJob(job);
536
+ return { ok: true, id, module, reviewMode };
537
+ }
538
+ // 骨骼动画:模块四的 RigJob 也有 reviewMode 字段,但早期版本的这里与 wire 的
539
+ // module 枚举都漏了 rig —— 于是「固定流程第 0 步必须问清审核模式」这条规则对
540
+ // 骨骼动画根本落不了地(走到这里会抛「未知模块:rig」)。
541
+ if (module === "rig") {
542
+ const job = await riggen.readRigJob(id);
543
+ if (job === undefined)
544
+ throw new Error(`任务不存在:${id}`);
545
+ job.reviewMode = reviewMode;
546
+ await riggen.writeRigJob(job);
547
+ return { ok: true, id, module, reviewMode };
548
+ }
549
+ throw new Error(`未知模块:${module}`);
550
+ }
551
+ // ── 流水线控制 ──────────────────────────────────────────────────────────
552
+ async runImage(payload) {
553
+ const input = asRecord(payload);
554
+ const projectId = asString(input.projectId);
555
+ const key = asString(input.key);
556
+ if (directionOf(key) === undefined)
557
+ throw new Error(`未知方向:${key}`);
558
+ return startImage(projectId, key, {
559
+ prompt: typeof input.prompt === "string" ? input.prompt : undefined
560
+ });
561
+ }
562
+ async runImages(payload) {
563
+ const input = asRecord(payload);
564
+ return startAllImages(asString(input.projectId), input.force === true);
565
+ }
566
+ async runVideos(payload) {
567
+ const input = asRecord(payload);
568
+ const projectId = asString(input.projectId);
569
+ const project = await readProject(projectId);
570
+ if (project === undefined)
571
+ throw new Error(`项目不存在:${projectId}`);
572
+ const keys = Array.isArray(input.keys) ? input.keys.filter((k) => directionOf(k) !== undefined) : undefined;
573
+ // 「重新生成」只允许点名方向:批量提交带这个标记会把八段视频全部重跑一遍,
574
+ // 用户点一下「生成全部视频」就白花八段视频的钱。
575
+ const regenerate = input.regenerate === true;
576
+ if (regenerate && keys === undefined) {
577
+ throw new Error("「重新生成」必须指定方向:请点对应方向的「重新生成」,或先「清空视频重来」");
578
+ }
579
+ const candidates = keys ?? DIRECTION_KEYS;
580
+ if (!candidates.some((key) => project.images[key]?.file !== undefined)) {
581
+ throw new Error("还没有可用的绿幕图,请先在第 1 步生成绿幕图");
582
+ }
583
+ // 重复提交会把正在跑的任务覆盖成孤儿(钱照花、结果拿不到),
584
+ // 所以这里同步拦掉,并且让界面能直接看到原因而不是只在日志里。
585
+ const running = candidates.filter((key) => {
586
+ const node = project.videos[key];
587
+ return node?.status === "running" && typeof node.taskId === "string";
588
+ });
589
+ const pending = candidates.filter((key) => !running.includes(key));
590
+ if (pending.length === 0) {
591
+ throw new Error(`这些方向已经在生成中,请等它们跑完:${running.join("、")}`);
592
+ }
593
+ // 「重新生成」:先把旧视频与它抽出来的帧作废,否则 startVideos 会把 ready 的方向
594
+ // 当成「已完成」跳过——界面表现为转一圈就结束,失败信息只留在日志里
595
+ // (实测报错:「没有可提交的方向:请先生成绿幕图,或先清掉已完成的视频」)。
596
+ const obsolete = regenerate
597
+ ? pending.filter((key) => project.videos[key]?.status === "ready" || project.videos[key]?.file !== undefined)
598
+ : [];
599
+ if (obsolete.length > 0) {
600
+ await clearVideos(projectId, obsolete);
601
+ const labels = obsolete.map((key) => directionOf(key)?.label ?? key).join("、");
602
+ await patchProject(projectId, (current) => {
603
+ log(current, "info", `重新生成:已作废「${labels}」的旧视频与序列帧,需要重新抽帧与合成整图`);
604
+ });
605
+ }
606
+ // 已经完成的方向默认不重复提交;只有点名「重新生成」的才重跑。
607
+ const submittable = pending.filter((key) => regenerate || project.videos[key]?.status !== "ready");
608
+ if (submittable.length === 0) {
609
+ throw new Error("这些方向的视频都已经生成完成;要重做请点该方向的「重新生成」");
610
+ }
611
+ return startVideos(projectId, submittable);
612
+ }
613
+ async pollVideos(payload) {
614
+ const projectId = asString(asRecord(payload).projectId);
615
+ await pollVideosOnce(projectId);
616
+ return { ok: true, jobs: listJobs(projectId) };
617
+ }
618
+ async clearVideos(payload) {
619
+ const input = asRecord(payload);
620
+ const keys = Array.isArray(input.keys) ? input.keys.filter((k) => directionOf(k) !== undefined) : undefined;
621
+ await clearVideos(asString(input.projectId), keys);
622
+ return { ok: true };
623
+ }
624
+ async runFrames(payload) {
625
+ const input = asRecord(payload);
626
+ const projectId = asString(input.projectId);
627
+ const project = await readProject(projectId);
628
+ if (project === undefined)
629
+ throw new Error(`项目不存在:${projectId}`);
630
+ const keys = Array.isArray(input.keys) ? input.keys.filter((k) => directionOf(k) !== undefined) : undefined;
631
+ const candidates = keys ?? DIRECTION_KEYS;
632
+ // 这里就把「到底要抽哪几个方向」定死再交给流水线:宿主要把它写进任务的覆盖面
633
+ // (界面靠它盖住还没轮到的方向),而没视频的方向永远抽不出东西,留在里面
634
+ // 会让那个格子一直转圈。
635
+ const targets = candidates.filter((key) => project.videos[key]?.file !== undefined);
636
+ if (targets.length === 0) {
637
+ throw new Error("还没有可抽帧的视频,请先在第 2 步生成视频");
638
+ }
639
+ return startExtract(projectId, targets);
640
+ }
641
+ async rekey(payload) {
642
+ const projectId = asString(asRecord(payload).projectId);
643
+ const project = await readProject(projectId);
644
+ if (project === undefined)
645
+ throw new Error(`项目不存在:${projectId}`);
646
+ if (!DIRECTION_KEYS.some((key) => project.frames[key]?.raw !== undefined)) {
647
+ throw new Error("还没有抽过帧,请先在第 3 步抽取序列帧");
648
+ }
649
+ return startRekey(projectId);
650
+ }
651
+ async compose(payload) {
652
+ const projectId = asString(asRecord(payload).projectId);
653
+ const project = await readProject(projectId);
654
+ if (project === undefined)
655
+ throw new Error(`项目不存在:${projectId}`);
656
+ if (!DIRECTION_KEYS.some((key) => project.frames[key]?.raw !== undefined)) {
657
+ throw new Error("还没有抽过帧,请先在第 3 步抽取序列帧");
658
+ }
659
+ return startCompose(projectId);
660
+ }
661
+ /** 方法表里声明的名字都要真实存在,这里做一次自检(仅开发期会失败)。 */
662
+ // ── 图片生成模块 ──────────────────────────────────────────────────────
663
+ async listImageJobs() {
664
+ return { jobs: await imagegen.listImageJobs() };
665
+ }
666
+ async createImageJob(payload) {
667
+ const job = await imagegen.createImageJob(asString(asRecord(payload).name, ""));
668
+ return { jobId: job.id };
669
+ }
670
+ async getImageJob(payload) {
671
+ const jobId = asString(asRecord(payload).jobId);
672
+ const job = await imagegen.readImageJob(jobId);
673
+ if (job === undefined)
674
+ throw new Error(`任务不存在:${jobId}`);
675
+ return { ...job, assetBase: `${ROUTE_PREFIX}/image-assets/${jobId}/` };
676
+ }
677
+ async deleteImageJob(payload) {
678
+ await imagegen.deleteImageJob(asString(asRecord(payload).jobId));
679
+ return { ok: true };
680
+ }
681
+ async saveImageJob(payload) {
682
+ const input = asRecord(payload);
683
+ const jobId = asString(input.jobId);
684
+ const job = await imagegen.readImageJob(jobId);
685
+ if (job === undefined)
686
+ throw new Error(`任务不存在:${jobId}`);
687
+ if (typeof input.name === "string" && input.name.trim() !== "")
688
+ job.name = input.name.trim().slice(0, 80);
689
+ if (typeof input.prompt === "string")
690
+ job.prompt = input.prompt;
691
+ if (typeof input.suffix === "string")
692
+ job.suffix = input.suffix;
693
+ if (input.settings !== undefined) {
694
+ const raw = asRecord(input.settings);
695
+ // 生图模型是全局设置(设置 → 游戏素材大师 → 生图模型),任务里不保留可覆盖的副本。
696
+ job.settings.model = (await loadConfig()).arkModel;
697
+ job.settings.size = asString(raw.size, job.settings.size);
698
+ job.settings.count = clampInt(raw.count, job.settings.count, 1, 8);
699
+ job.settings.watermark = raw.watermark === true;
700
+ }
701
+ if (input.keying !== undefined)
702
+ applyKeying(job.keying, asRecord(input.keying));
703
+ // 验收打标:不带 index 就是整个任务,带 index 只改那一张。和界面上的「通过」是同一份数据。
704
+ if (typeof input.approved === "boolean") {
705
+ const index = input.index === undefined || input.index === null ? undefined : clampInt(input.index, -1, 0, 9999);
706
+ let touched = 0;
707
+ for (const item of job.items) {
708
+ if (index === undefined || item.index === index) {
709
+ item.approved = input.approved;
710
+ touched++;
711
+ }
712
+ }
713
+ if (index !== undefined && touched === 0)
714
+ throw new Error(`没有第 ${index} 张产物`);
715
+ }
716
+ await imagegen.writeImageJob(job);
717
+ return { ok: true };
718
+ }
719
+ async uploadImageRef(payload) {
720
+ const input = asRecord(payload);
721
+ await imagegen.addImageRef(asString(input.jobId), asString(input.name, "ref.png"), asString(input.data));
722
+ return { ok: true };
723
+ }
724
+ async removeImageRef(payload) {
725
+ const input = asRecord(payload);
726
+ await imagegen.removeImageRef(asString(input.jobId), asString(input.file));
727
+ return { ok: true };
728
+ }
729
+ async addImageItem(payload) {
730
+ const input = asRecord(payload);
731
+ await imagegen.addImageToJob(asString(input.jobId), asString(input.name, "image.png"), asString(input.data));
732
+ return { ok: true };
733
+ }
734
+ async removeImageItem(payload) {
735
+ const input = asRecord(payload);
736
+ await imagegen.removeImageItem(asString(input.jobId), clampInt(input.index, 0, 0, 9999));
737
+ return { ok: true };
738
+ }
739
+ async runImageJob(payload) {
740
+ const input = asRecord(payload);
741
+ const jobId = asString(input.jobId);
742
+ const job = await imagegen.readImageJob(jobId);
743
+ if (job === undefined)
744
+ throw new Error(`任务不存在:${jobId}`);
745
+ if (job.prompt.trim() === "")
746
+ throw new Error("提示词为空,请先填写");
747
+ const count = clampInt(input.count, job.settings.count, 1, 8);
748
+ if (count !== job.settings.count) {
749
+ job.settings.count = count;
750
+ await imagegen.writeImageJob(job);
751
+ }
752
+ let started = 0;
753
+ for (let i = 0; i < count; i++) {
754
+ if (kickImageItem(jobId, i))
755
+ started++;
756
+ }
757
+ if (started === 0)
758
+ throw new Error("这些图片已经在生成中,请等它们跑完");
759
+ return { started: true, count: started };
760
+ }
761
+ async keyImageJob(payload) {
762
+ const jobId = asString(asRecord(payload).jobId);
763
+ const ok = kickImageKey(jobId);
764
+ return ok ? { started: true } : { started: false, reason: "抠像已在进行中" };
765
+ }
766
+ // ── 序列帧生成模块 ────────────────────────────────────────────────────
767
+ async listSequenceJobs() {
768
+ return { jobs: await seqgen.listSequenceJobs() };
769
+ }
770
+ async createSequenceJob(payload) {
771
+ const job = await seqgen.createSequenceJob(asString(asRecord(payload).name, ""));
772
+ return { jobId: job.id };
773
+ }
774
+ async getSequenceJob(payload) {
775
+ const jobId = asString(asRecord(payload).jobId);
776
+ const job = await seqgen.readSequenceJob(jobId);
777
+ if (job === undefined)
778
+ throw new Error(`任务不存在:${jobId}`);
779
+ return { ...job, tasks: seqgen.listSequenceTasks(jobId), assetBase: `${ROUTE_PREFIX}/sequence-assets/${jobId}/` };
780
+ }
781
+ async deleteSequenceJob(payload) {
782
+ await seqgen.deleteSequenceJob(asString(asRecord(payload).jobId));
783
+ return { ok: true };
784
+ }
785
+ async saveSequenceJob(payload) {
786
+ const input = asRecord(payload);
787
+ const jobId = asString(input.jobId);
788
+ const job = await seqgen.readSequenceJob(jobId);
789
+ if (job === undefined)
790
+ throw new Error(`任务不存在:${jobId}`);
791
+ if (typeof input.name === "string" && input.name.trim() !== "")
792
+ job.name = input.name.trim().slice(0, 80);
793
+ if (input.mode === "frames" || input.mode === "reference")
794
+ job.mode = input.mode;
795
+ if (typeof input.prompt === "string")
796
+ job.prompt = input.prompt;
797
+ if (typeof input.suffix === "string")
798
+ job.suffix = input.suffix;
799
+ if (input.settings !== undefined) {
800
+ const raw = asRecord(input.settings);
801
+ const before = { ...job.settings };
802
+ // 视频模型是全局设置(含优云智算版),任务里不保留可覆盖的副本;
803
+ // 时长/分辨率也跟着当前模型收敛,避免存下当前模型不支持的档位。
804
+ const model = (await loadConfig()).minimaxModel;
805
+ job.settings.model = model;
806
+ job.settings.duration = normalizeDuration(model, clampInt(raw.duration, job.settings.duration, 1, 30));
807
+ job.settings.resolution = normalizeResolution(model, asString(raw.resolution, job.settings.resolution));
808
+ job.settings.promptOptimizer = raw.promptOptimizer !== false;
809
+ job.settings.frameCount = clampInt(raw.frameCount, job.settings.frameCount, 1, 64);
810
+ job.settings.cellWidth = clampInt(raw.cellWidth, job.settings.cellWidth, 16, 2048);
811
+ job.settings.cellHeight = clampInt(raw.cellHeight, job.settings.cellHeight, 16, 2048);
812
+ job.settings.longEdge = clampInt(raw.longEdge, job.settings.longEdge, 128, 2048);
813
+ job.settings.cropInset = clampFloat(raw.cropInset, job.settings.cropInset, 0, 0.2);
814
+ job.settings.pixelSize = clampInt(raw.pixelSize, job.settings.pixelSize, 0, 32);
815
+ // 抽帧参数变了,raw.bin 作废,必须重抽。
816
+ if (before.longEdge !== job.settings.longEdge || before.cropInset !== job.settings.cropInset) {
817
+ if (job.frames.raw !== undefined)
818
+ job.frames.stale = true;
819
+ }
820
+ }
821
+ if (input.keying !== undefined)
822
+ applyKeying(job.keying, asRecord(input.keying));
823
+ // 验收打标:不带 step 就是三步全打,带 step 只改那一步。与界面的「通过」共用同一份数据。
824
+ if (typeof input.approved === "boolean") {
825
+ const step = typeof input.step === "string" ? input.step : undefined;
826
+ if (step === undefined) {
827
+ job.video.approved = input.approved;
828
+ job.frames.approved = input.approved;
829
+ job.sheet.approved = input.approved;
830
+ }
831
+ else {
832
+ if (step !== "video" && step !== "frames" && step !== "sheet")
833
+ throw new Error(`未知步骤:${step}`);
834
+ job[step].approved = input.approved;
835
+ }
836
+ }
837
+ await seqgen.writeSequenceJob(job);
838
+ return { ok: true };
839
+ }
840
+ async uploadSequenceRef(payload) {
841
+ const input = asRecord(payload);
842
+ await seqgen.uploadSequenceRef(asString(input.jobId), asString(input.kind, "referenceImage"), asString(input.name, "file"), asString(input.data));
843
+ return { ok: true };
844
+ }
845
+ async removeSequenceRef(payload) {
846
+ const input = asRecord(payload);
847
+ await seqgen.removeSequenceRef(asString(input.jobId), asString(input.kind, "referenceImage"), typeof input.file === "string" ? input.file : undefined);
848
+ return { ok: true };
849
+ }
850
+ async runSequenceVideo(payload) {
851
+ const jobId = asString(asRecord(payload).jobId);
852
+ const job = await seqgen.readSequenceJob(jobId);
853
+ if (job === undefined)
854
+ throw new Error(`任务不存在:${jobId}`);
855
+ if (job.video.status === "running" && typeof job.video.taskId === "string") {
856
+ throw new Error("视频已经在生成中,请等它跑完(重复提交会白花一次生成的钱)");
857
+ }
858
+ // 素材缺失同步报错,否则只会落进日志、界面上看着像「点了没反应」。
859
+ if (job.mode === "frames" && job.refs.firstFrame === undefined) {
860
+ throw new Error("首尾帧模式必须上传一张首帧图");
861
+ }
862
+ if (job.mode === "reference" && job.refs.referenceImages.length === 0 && job.refs.referenceVideos.length === 0) {
863
+ throw new Error("参考模式至少要上传一张参考图或一段参考视频");
864
+ }
865
+ if (job.frames.raw !== undefined && job.video.status === "empty") {
866
+ throw new Error("清空视频后才能重新生成");
867
+ }
868
+ return seqgen.startSequenceVideo(jobId);
869
+ }
870
+ async pollSequenceVideo(payload) {
871
+ await seqgen.pollSequenceOnce(asString(asRecord(payload).jobId));
872
+ return { ok: true };
873
+ }
874
+ async clearSequenceVideo(payload) {
875
+ const jobId = asString(asRecord(payload).jobId);
876
+ const job = await seqgen.readSequenceJob(jobId);
877
+ if (job === undefined)
878
+ throw new Error(`任务不存在:${jobId}`);
879
+ job.video = { status: "empty" };
880
+ job.frames = { status: "empty", count: job.settings.frameCount, files: [], keyed: [] };
881
+ job.sheet = { status: "empty" };
882
+ await seqgen.writeSequenceJob(job);
883
+ return { ok: true };
884
+ }
885
+ async runSequenceFrames(payload) {
886
+ const input = asRecord(payload);
887
+ const jobId = asString(input.jobId);
888
+ const job = await seqgen.readSequenceJob(jobId);
889
+ if (job === undefined)
890
+ throw new Error(`任务不存在:${jobId}`);
891
+ if (job.video.file === undefined)
892
+ throw new Error("还没有可用视频,请先生成视频");
893
+ const count = input.count === undefined ? undefined : clampInt(input.count, job.settings.frameCount, 1, 64);
894
+ return seqgen.startSequenceFrames(jobId, count);
895
+ }
896
+ async keySequenceFrames(payload) {
897
+ const jobId = asString(asRecord(payload).jobId);
898
+ const job = await seqgen.readSequenceJob(jobId);
899
+ if (job === undefined)
900
+ throw new Error(`任务不存在:${jobId}`);
901
+ if (job.frames.raw === undefined)
902
+ throw new Error("还没有抽过帧,请先抽帧");
903
+ return seqgen.startSequenceKey(jobId);
904
+ }
905
+ async composeSequence(payload) {
906
+ const jobId = asString(asRecord(payload).jobId);
907
+ const job = await seqgen.readSequenceJob(jobId);
908
+ if (job === undefined)
909
+ throw new Error(`任务不存在:${jobId}`);
910
+ if (job.frames.raw === undefined)
911
+ throw new Error("还没有抽过帧,请先抽帧");
912
+ await seqgen.composeSequenceSheet(jobId);
913
+ return { started: true };
914
+ }
915
+ // ── 骨骼动画生成模块 ──────────────────────────────────────────────────
916
+ async listRigJobs() {
917
+ return { jobs: await riggen.listRigJobs() };
918
+ }
919
+ async createRigJob(payload) {
920
+ const job = await riggen.createRigJob(asString(asRecord(payload).name, ""));
921
+ return { jobId: job.id };
922
+ }
923
+ async getRigJob(payload) {
924
+ const jobId = asString(asRecord(payload).jobId);
925
+ const job = await riggen.readRigJob(jobId);
926
+ if (job === undefined)
927
+ throw new Error(`任务不存在:${jobId}`);
928
+ // 界面拿的是**与对话工具同一份**任务视图(相对 URL),字段不会再各拼一份。
929
+ return {
930
+ ...riggen.rigSnapshot(job),
931
+ stageList: riggen.RIG_STAGES,
932
+ animationPresets: riggen.RIG_ANIMATIONS
933
+ };
934
+ }
935
+ async deleteRigJob(payload) {
936
+ await riggen.deleteRigJob(asString(asRecord(payload).jobId));
937
+ return { ok: true };
938
+ }
939
+ async saveRigJob(payload) {
940
+ const input = asRecord(payload);
941
+ const jobId = asString(input.jobId);
942
+ const job = await riggen.readRigJob(jobId);
943
+ if (job === undefined)
944
+ throw new Error(`任务不存在:${jobId}`);
945
+ if (typeof input.name === "string" && input.name.trim() !== "") {
946
+ await riggen.writeRigJob({ ...job, name: input.name.trim().slice(0, 80) });
947
+ }
948
+ if (typeof input.sheetPrompt === "string" || typeof input.suffix === "string" || input.resetSheetPrompt === true) {
949
+ await riggen.saveRigPrompts(jobId, {
950
+ sheet: typeof input.sheetPrompt === "string" ? input.sheetPrompt : undefined,
951
+ suffix: typeof input.suffix === "string" ? input.suffix : undefined,
952
+ resetSheet: input.resetSheetPrompt === true
953
+ });
954
+ }
955
+ if (input.settings !== undefined)
956
+ await riggen.saveRigSettings(jobId, asRecord(input.settings));
957
+ if (typeof input.approved === "boolean") {
958
+ const stage = typeof input.stage === "string" ? input.stage : undefined;
959
+ if (stage === undefined) {
960
+ await riggen.setRigStageApproved(jobId, "parts", input.approved);
961
+ await riggen.setRigStageApproved(jobId, "layout", input.approved);
962
+ await riggen.setRigStageApproved(jobId, "rig", input.approved);
963
+ await riggen.setRigStageApproved(jobId, "atlas", input.approved);
964
+ }
965
+ else if (stage === "parts" && typeof input.part === "string") {
966
+ await riggen.setRigPartApproved(jobId, input.part, input.approved);
967
+ }
968
+ else {
969
+ await riggen.setRigStageApproved(jobId, stage, input.approved);
970
+ }
971
+ }
972
+ return { ok: true };
973
+ }
974
+ async uploadRigSource(payload) {
975
+ const input = asRecord(payload);
976
+ const size = await riggen.setRigSource(asString(input.jobId), asString(input.name, "character.png"), asString(input.data));
977
+ return { ok: true, ...size };
978
+ }
979
+ async uploadRigPart(payload) {
980
+ const input = asRecord(payload);
981
+ const result = await riggen.uploadRigPart(asString(input.jobId), asString(input.name, "part.png"), asString(input.data));
982
+ return { ok: true, ...result };
983
+ }
984
+ async removeRigPart(payload) {
985
+ const input = asRecord(payload);
986
+ await riggen.removeRigPart(asString(input.jobId), asString(input.name));
987
+ return { ok: true };
988
+ }
989
+ async renameRigPart(payload) {
990
+ const input = asRecord(payload);
991
+ await riggen.renameRigPart(asString(input.jobId), asString(input.from), asString(input.to));
992
+ return { ok: true };
993
+ }
994
+ async setRigPartVisibility(payload) {
995
+ const input = asRecord(payload);
996
+ await riggen.setRigPartVisibility(asString(input.jobId), asString(input.name), input.hidden === true);
997
+ return { ok: true };
998
+ }
999
+ async saveRigLayoutItem(payload) {
1000
+ const input = asRecord(payload);
1001
+ const num = (value) => (typeof value === "number" && Number.isFinite(value) ? value : undefined);
1002
+ await riggen.saveLayoutItem(asString(input.jobId), asString(input.name), {
1003
+ x: num(input.x),
1004
+ y: num(input.y),
1005
+ width: num(input.width),
1006
+ height: num(input.height),
1007
+ rotation: num(input.rotation),
1008
+ z: num(input.z)
1009
+ });
1010
+ return { ok: true };
1011
+ }
1012
+ async saveRigLayoutItems(payload) {
1013
+ const input = asRecord(payload);
1014
+ const items = Array.isArray(input.items) ? input.items : [];
1015
+ const result = await riggen.saveRigLayoutItems(asString(input.jobId), items.map((entry) => ({
1016
+ name: asString(entry?.name),
1017
+ x: typeof entry?.x === "number" ? entry.x : undefined,
1018
+ y: typeof entry?.y === "number" ? entry.y : undefined,
1019
+ width: typeof entry?.width === "number" ? entry.width : undefined,
1020
+ height: typeof entry?.height === "number" ? entry.height : undefined,
1021
+ rotation: typeof entry?.rotation === "number" ? entry.rotation : undefined,
1022
+ z: typeof entry?.z === "number" ? entry.z : undefined,
1023
+ placed: typeof entry?.placed === "boolean" ? entry.placed : undefined
1024
+ })));
1025
+ return { ok: true, ...result };
1026
+ }
1027
+ async setRigLayoutHints(payload) {
1028
+ const input = asRecord(payload);
1029
+ const raw = asRecord(input.hints);
1030
+ const hints = {};
1031
+ for (const [name, value] of Object.entries(raw))
1032
+ hints[name] = value === null ? null : value;
1033
+ const result = await riggen.setRigLayoutHints(asString(input.jobId), hints);
1034
+ return { ok: true, ...result };
1035
+ }
1036
+ async runRigSheet(payload) {
1037
+ return riggen.startSheetGeneration(asString(asRecord(payload).jobId));
1038
+ }
1039
+ /**
1040
+ * 手工骨骼偏移(三通道的中间那一层)。
1041
+ *
1042
+ * 它与 `setRigSemantics` 一样只作废「骨骼与图集」:偏置只影响骨骼推导,
1043
+ * 部件摆在画布上的位置与它无关。
1044
+ */
1045
+ async setRigBoneOffsets(payload) {
1046
+ const input = asRecord(payload);
1047
+ const rawBones = Array.isArray(input.bones) ? input.bones : [];
1048
+ const bones = rawBones.map((item) => {
1049
+ const record = asRecord(item);
1050
+ const patch = { name: asString(record.name) };
1051
+ if (typeof record.x === "number")
1052
+ patch.x = record.x;
1053
+ if (typeof record.y === "number")
1054
+ patch.y = record.y;
1055
+ if (typeof record.rotation === "number")
1056
+ patch.rotation = record.rotation;
1057
+ return patch;
1058
+ });
1059
+ const touched = await riggen.setRigBoneOffsets(asString(input.jobId), bones, {
1060
+ by: input.by === "ai" ? "ai" : "human",
1061
+ label: typeof input.label === "string" ? input.label : undefined
1062
+ });
1063
+ return { ok: true, ...touched };
1064
+ }
1065
+ async resetRigBoneOffsets(payload) {
1066
+ const input = asRecord(payload);
1067
+ const names = Array.isArray(input.names) ? input.names.filter((name) => typeof name === "string") : undefined;
1068
+ return { ok: true, ...(await riggen.resetRigBoneOffsets(asString(input.jobId), names)) };
1069
+ }
1070
+ /** 动画参数:`amplitude`(统一缩放幅度)与 `duration`(循环时长)。 */
1071
+ async setRigAnimationSettings(payload) {
1072
+ const input = asRecord(payload);
1073
+ const raw = Array.isArray(input.animations) ? input.animations : [];
1074
+ const patches = raw.map((item) => {
1075
+ const record = asRecord(item);
1076
+ const patch = { id: asString(record.id) };
1077
+ if (typeof record.duration === "number")
1078
+ patch.duration = record.duration;
1079
+ if (typeof record.amplitude === "number")
1080
+ patch.amplitude = record.amplitude;
1081
+ return patch;
1082
+ });
1083
+ const result = await riggen.setRigAnimationSettings(asString(input.jobId), patches, {
1084
+ by: input.by === "ai" ? "ai" : "human"
1085
+ });
1086
+ return { ok: true, ...result };
1087
+ }
1088
+ async resetRigAnimationSettings(payload) {
1089
+ const input = asRecord(payload);
1090
+ const ids = Array.isArray(input.ids) ? input.ids.filter((id) => typeof id === "string") : undefined;
1091
+ return { ok: true, ...(await riggen.resetRigAnimationSettings(asString(input.jobId), ids)) };
1092
+ }
1093
+ /** 取一台动画的可编辑关键帧数据(时间轴编辑器用)。 */
1094
+ async getRigAnimation(payload) {
1095
+ const input = asRecord(payload);
1096
+ return { ok: true, ...(await riggen.getRigAnimation(asString(input.jobId), asString(input.id))) };
1097
+ }
1098
+ /**
1099
+ * 整份写回一台动画。
1100
+ *
1101
+ * `animation` 缺省时是**实例化**:用当前参数把预设烘成显式关键帧,
1102
+ * 之后这台动画就以数据为准——参数旋钮不再影响它(刻意如此,否则
1103
+ * 手调过的帧会被下一次调参悄悄改掉)。
1104
+ */
1105
+ async saveRigAnimation(payload) {
1106
+ const input = asRecord(payload);
1107
+ return {
1108
+ ok: true,
1109
+ ...(await riggen.saveRigAnimation(asString(input.jobId), {
1110
+ id: asString(input.id),
1111
+ animation: input.animation
1112
+ }))
1113
+ };
1114
+ }
1115
+ /** 还原一台动画到预设。 */
1116
+ async resetRigAnimation(payload) {
1117
+ const input = asRecord(payload);
1118
+ return { ok: true, ...(await riggen.resetRigAnimation(asString(input.jobId), asString(input.id))) };
1119
+ }
1120
+ /**
1121
+ * 重跑拆件质检。
1122
+ *
1123
+ * 分割后会自动跑一次(那一次要解码全部部件 PNG,只在拆完时做);这里是手动入口,
1124
+ * 用于「改了语义/隐藏了部件之后重新评估」,以及让 agent 把看图得到的
1125
+ * `expectedParts`(参考图里大致有几个独立部位)写进去。
1126
+ */
1127
+ async runRigQa(payload) {
1128
+ const input = asRecord(payload);
1129
+ const expected = typeof input.expectedParts === "number" ? input.expectedParts : undefined;
1130
+ return { ok: true, ...(await riggen.runRigQa(asString(input.jobId), expected)) };
1131
+ }
1132
+ /**
1133
+ * 写入 / 覆盖 IK 约束(M5)。
1134
+ *
1135
+ * 目标骨不存在时宿主会自动补一根可拖的点,所以这里只要求 `bone` 与 `name`。
1136
+ */
1137
+ async setRigConstraints(payload) {
1138
+ const input = asRecord(payload);
1139
+ const raw = Array.isArray(input.constraints) ? input.constraints : [];
1140
+ const patches = raw.map((item) => {
1141
+ const record = asRecord(item);
1142
+ const patch = { name: asString(record.name), bone: asString(record.bone) };
1143
+ if (typeof record.target === "string")
1144
+ patch.target = record.target;
1145
+ if (typeof record.chain === "number")
1146
+ patch.chain = record.chain;
1147
+ if (typeof record.bendPositive === "boolean")
1148
+ patch.bendPositive = record.bendPositive;
1149
+ if (typeof record.weight === "number")
1150
+ patch.weight = record.weight;
1151
+ return patch;
1152
+ });
1153
+ const result = await riggen.setRigConstraints(asString(input.jobId), patches, {
1154
+ by: input.by === "ai" ? "ai" : "human"
1155
+ });
1156
+ return { ok: true, ...result };
1157
+ }
1158
+ async resetRigConstraints(payload) {
1159
+ const input = asRecord(payload);
1160
+ const names = Array.isArray(input.names) ? input.names.filter((name) => typeof name === "string") : undefined;
1161
+ return { ok: true, ...(await riggen.resetRigConstraints(asString(input.jobId), names)) };
1162
+ }
1163
+ /**
1164
+ * 蒙皮网格与 FFD 变形(M5)。
1165
+ *
1166
+ * 网格是**确定性重算**的(规则三角化),只传密度;`deform` 是波形参数,
1167
+ * 导出时会按每个动画的时长采样成 deform/ffd 时间轴。
1168
+ */
1169
+ async setRigMesh(payload) {
1170
+ const input = asRecord(payload);
1171
+ const raw = Array.isArray(input.meshes) ? input.meshes : [];
1172
+ const patches = raw.map((item) => {
1173
+ const record = asRecord(item);
1174
+ const patch = { name: asString(record.name) };
1175
+ if (typeof record.cols === "number")
1176
+ patch.cols = record.cols;
1177
+ if (typeof record.rows === "number")
1178
+ patch.rows = record.rows;
1179
+ if (record.deform === null)
1180
+ patch.deform = null;
1181
+ else if (record.deform !== undefined) {
1182
+ const deform = asRecord(record.deform);
1183
+ const parsed = {};
1184
+ if (typeof deform.amplitude === "number")
1185
+ parsed.amplitude = deform.amplitude;
1186
+ if (typeof deform.cycles === "number")
1187
+ parsed.cycles = deform.cycles;
1188
+ if (typeof deform.direction === "number")
1189
+ parsed.direction = deform.direction;
1190
+ if (deform.anchor === "top" || deform.anchor === "bottom" || deform.anchor === "none")
1191
+ parsed.anchor = deform.anchor;
1192
+ if (typeof deform.duration === "number")
1193
+ parsed.duration = deform.duration;
1194
+ patch.deform = parsed;
1195
+ }
1196
+ return patch;
1197
+ });
1198
+ const result = await riggen.setRigMesh(asString(input.jobId), patches, {
1199
+ by: input.by === "ai" ? "ai" : "human"
1200
+ });
1201
+ return { ok: true, ...result };
1202
+ }
1203
+ /**
1204
+ * Path 约束(M5)。`points` 是扁平的 `[x0,y0,x1,y1,…]`(参考图像素)。
1205
+ *
1206
+ * 路径点与骨链放在同一条记录里:它们**只能一起改**——换一条骨链而留着旧路径的间距,
1207
+ * 结果一定是错的。
1208
+ */
1209
+ async setRigPath(payload) {
1210
+ const input = asRecord(payload);
1211
+ const raw = Array.isArray(input.paths) ? input.paths : [];
1212
+ const patches = raw.map((item) => {
1213
+ const record = asRecord(item);
1214
+ const patch = { name: asString(record.name) };
1215
+ if (Array.isArray(record.points))
1216
+ patch.points = record.points.filter((n) => typeof n === "number");
1217
+ if (typeof record.closed === "boolean")
1218
+ patch.closed = record.closed;
1219
+ if (Array.isArray(record.bones))
1220
+ patch.bones = record.bones.filter((n) => typeof n === "string");
1221
+ if (typeof record.spacing === "number")
1222
+ patch.spacing = record.spacing;
1223
+ if (typeof record.translateMix === "number")
1224
+ patch.translateMix = record.translateMix;
1225
+ if (typeof record.rotateMix === "number")
1226
+ patch.rotateMix = record.rotateMix;
1227
+ return patch;
1228
+ });
1229
+ const result = await riggen.setRigPath(asString(input.jobId), patches, {
1230
+ by: input.by === "ai" ? "ai" : "human"
1231
+ });
1232
+ return { ok: true, ...result };
1233
+ }
1234
+ async resetRigPath(payload) {
1235
+ const input = asRecord(payload);
1236
+ const names = Array.isArray(input.names) ? input.names.filter((name) => typeof name === "string") : undefined;
1237
+ return { ok: true, ...(await riggen.resetRigPath(asString(input.jobId), names)) };
1238
+ }
1239
+ async resetRigMesh(payload) {
1240
+ const input = asRecord(payload);
1241
+ const names = Array.isArray(input.names) ? input.names.filter((name) => typeof name === "string") : undefined;
1242
+ return { ok: true, ...(await riggen.resetRigMesh(asString(input.jobId), names)) };
1243
+ }
1244
+ /**
1245
+ * 换色(本地计算,免费)。
1246
+ *
1247
+ * 目标二选一:点名 `names`,或按语义 `tag` 批量。落成一个**新版本**,
1248
+ * 所以不满意随时用 `setRigTextureVersion` 切回去。
1249
+ */
1250
+ async tintRigParts(payload) {
1251
+ const input = asRecord(payload);
1252
+ const names = Array.isArray(input.names) ? input.names.filter((name) => typeof name === "string") : undefined;
1253
+ const raw = asRecord(input.tint);
1254
+ const tint = {};
1255
+ for (const key of ["hue", "saturation", "lightness", "brightness", "contrast"]) {
1256
+ if (typeof raw[key] === "number")
1257
+ tint[key] = raw[key];
1258
+ }
1259
+ if (Array.isArray(raw.rgb) && raw.rgb.length === 3) {
1260
+ tint.rgb = raw.rgb.map((value) => Number(value));
1261
+ }
1262
+ return {
1263
+ ok: true,
1264
+ ...(await riggen.tintRigParts(asString(input.jobId), { names, tag: typeof input.tag === "string" ? input.tag : undefined }, tint, { by: input.by === "ai" ? "ai" : "human", note: typeof input.note === "string" ? input.note : undefined }))
1265
+ };
1266
+ }
1267
+ /** 手工上传一张贴图顶掉当前版本(同样是新增一版,不覆盖)。 */
1268
+ async uploadRigTexture(payload) {
1269
+ const input = asRecord(payload);
1270
+ return {
1271
+ ok: true,
1272
+ ...(await riggen.uploadRigTexture(asString(input.jobId), asString(input.name), asString(input.data), {
1273
+ note: typeof input.note === "string" ? input.note : undefined
1274
+ }))
1275
+ };
1276
+ }
1277
+ /** 切到某一版贴图(「这张 AI 头发不行,换回原版」)。 */
1278
+ async setRigTextureVersion(payload) {
1279
+ const input = asRecord(payload);
1280
+ return { ok: true, ...(await riggen.setRigTextureVersion(asString(input.jobId), asString(input.name), Number(input.version))) };
1281
+ }
1282
+ async removeRigTextureVersion(payload) {
1283
+ const input = asRecord(payload);
1284
+ return { ok: true, ...(await riggen.removeRigTextureVersion(asString(input.jobId), asString(input.name), Number(input.version))) };
1285
+ }
1286
+ /** AI 逐部件重绘(花钱)。生图要几十秒,所以走后台任务 + `game_material_wait`。 */
1287
+ async runRigRedraw(payload) {
1288
+ const input = asRecord(payload);
1289
+ return riggen.startRigRedraw(asString(input.jobId), asString(input.name), asString(input.prompt), {
1290
+ erode: typeof input.erode === "number" ? input.erode : undefined
1291
+ });
1292
+ }
1293
+ /**
1294
+ * 语义层(阶段③):AI 或人改「这块是什么、挂在谁身上、骨骼从哪伸到哪」。
1295
+ *
1296
+ * 校验不通过时**不抛异常**,而是把 errors/warnings 原样回给调用方——
1297
+ * 界面要能把「哪一条、为什么不合法」显示出来,agent 也要能据此自我修正。
1298
+ */
1299
+ async setRigSemantics(payload) {
1300
+ const input = asRecord(payload);
1301
+ const rawParts = Array.isArray(input.parts) ? input.parts : [];
1302
+ const parts = rawParts.map((item) => {
1303
+ const record = asRecord(item);
1304
+ const patch = { name: asString(record.name) };
1305
+ if (typeof record.role === "string")
1306
+ patch.role = record.role;
1307
+ if (record.parent === null)
1308
+ patch.parent = undefined;
1309
+ else if (typeof record.parent === "string")
1310
+ patch.parent = record.parent;
1311
+ if (Array.isArray(record.proximal) && record.proximal.length === 2)
1312
+ patch.proximal = [Number(record.proximal[0]), Number(record.proximal[1])];
1313
+ if (Array.isArray(record.distal) && record.distal.length === 2)
1314
+ patch.distal = [Number(record.distal[0]), Number(record.distal[1])];
1315
+ if (Array.isArray(record.tags))
1316
+ patch.tags = record.tags.filter((tag) => typeof tag === "string");
1317
+ return patch;
1318
+ });
1319
+ return riggen.setRigSemantics(asString(input.jobId), parts, {
1320
+ humanoid: typeof input.humanoid === "boolean" ? input.humanoid : undefined,
1321
+ by: input.by === "ai" ? "ai" : "human"
1322
+ });
1323
+ }
1324
+ async runRigSegment(payload) {
1325
+ return riggen.startSegmentation(asString(asRecord(payload).jobId));
1326
+ }
1327
+ async runRigLayout(payload) {
1328
+ const input = asRecord(payload);
1329
+ const names = Array.isArray(input.names) ? input.names.filter((name) => typeof name === "string") : undefined;
1330
+ return riggen.startLayout(asString(input.jobId), names);
1331
+ }
1332
+ async runRigBones(payload) {
1333
+ return riggen.startRig(asString(asRecord(payload).jobId));
1334
+ }
1335
+ async runRigAtlas(payload) {
1336
+ return riggen.startAtlas(asString(asRecord(payload).jobId));
1337
+ }
1338
+ assertSurface() {
1339
+ for (const spec of METHODS) {
1340
+ if (typeof this[spec.method] !== "function") {
1341
+ throw new Error(`gameStudio 缺少方法:${spec.method}`);
1342
+ }
1343
+ }
1344
+ }
1345
+ }
1346
+ /**
1347
+ * 把界面传来的抠像参数收敛进目标对象。
1348
+ * 三个模块共用同一套参数名,所以收敛逻辑也共用。
1349
+ */
1350
+ function applyKeying(target, raw) {
1351
+ target.keyLow = clampInt(raw.keyLow, target.keyLow, 0, 255);
1352
+ target.keyHigh = clampInt(raw.keyHigh, target.keyHigh, 1, 255);
1353
+ if (target.keyHigh <= target.keyLow)
1354
+ target.keyHigh = Math.min(255, target.keyLow + 1);
1355
+ target.despill = clampFloat(raw.despill, target.despill, 0, 1);
1356
+ target.bgTolerance = clampInt(raw.bgTolerance, target.bgTolerance, 0, 160);
1357
+ target.edgeShrink = clampInt(raw.edgeShrink, target.edgeShrink, 0, 8);
1358
+ if (typeof raw.enabled === "boolean")
1359
+ target.enabled = raw.enabled;
1360
+ }
1361
+ /**
1362
+ * 图片模块的运行表:一张图一个槽位。
1363
+ * 同一张图重复点「生成」会白花一次钱,所以这里和八方向模块一样做拒绝。
1364
+ */
1365
+ const imageTasks = new Map();
1366
+ function startedImageTask(jobId, key) {
1367
+ return imageTasks.get(jobId)?.has(key) === true;
1368
+ }
1369
+ function trackImageTask(jobId, key, run) {
1370
+ if (startedImageTask(jobId, key))
1371
+ return false;
1372
+ const set = imageTasks.get(jobId) ?? new Set();
1373
+ imageTasks.set(jobId, set);
1374
+ set.add(key);
1375
+ void run()
1376
+ .catch(() => undefined)
1377
+ .finally(() => {
1378
+ set.delete(key);
1379
+ if (set.size === 0)
1380
+ imageTasks.delete(jobId);
1381
+ });
1382
+ return true;
1383
+ }
1384
+ function kickImageItem(jobId, index) {
1385
+ return trackImageTask(jobId, `image:${index}`, () => imagegen.generateImageItem(jobId, index));
1386
+ }
1387
+ function kickImageKey(jobId) {
1388
+ return trackImageTask(jobId, "image:key", () => imagegen.rekeyImageJob(jobId));
1389
+ }
1390
+ function disposeImageTasks() {
1391
+ imageTasks.clear();
1392
+ }
1393
+ // ── 静态资源路由 ────────────────────────────────────────────────────────
1394
+ /** 各模块允许通过 HTTP 路由读取的子目录白名单。 */
1395
+ const SERVABLE_DIRS = new Set(["source", "images", "videos", "frames", "keyed", "preview", "out"]);
1396
+ const SERVABLE_IMAGE_DIRS = new Set(["refs", "out", "keyed"]);
1397
+ const SERVABLE_SEQUENCE_DIRS = new Set(["refs", "video-refs", "videos", "frames", "keyed", "out"]);
1398
+ /** 骨骼动画:源图、拆件摊平图、部件、装配结果、骨骼与图集。 */
1399
+ // `export/` 是后加的第二条导出路径(DragonBones 5.5 的 `_ske.json`)。
1400
+ // 白名单只比对**第一段**路径,所以 `export/dragonbones/xxx.json` 加一条 `export` 就够。
1401
+ const SERVABLE_RIG_DIRS = new Set(["source", "sheet", "parts", "layout", "rig", "atlas", "export"]);
1402
+ function resolveAssetTarget(scope, id, relative) {
1403
+ if (scope === "assets") {
1404
+ if (!PROJECT_ID_PATTERN.test(id))
1405
+ return undefined;
1406
+ return { file: assetPath(id, relative), dirs: SERVABLE_DIRS };
1407
+ }
1408
+ if (scope === "image-assets") {
1409
+ if (!imagegen.isValidImageJobId(id))
1410
+ return undefined;
1411
+ return { file: imagegen.imageAssetPath(id, relative), dirs: SERVABLE_IMAGE_DIRS };
1412
+ }
1413
+ if (scope === "rig-assets") {
1414
+ if (!riggen.isValidRigJobId(id))
1415
+ return undefined;
1416
+ return { file: riggen.rigAssetPath(id, relative), dirs: SERVABLE_RIG_DIRS };
1417
+ }
1418
+ if (!seqgen.isValidSequenceJobId(id))
1419
+ return undefined;
1420
+ return { file: seqgen.sequenceAssetPath(id, relative), dirs: SERVABLE_SEQUENCE_DIRS };
1421
+ }
1422
+ function sendText(res, status, text) {
1423
+ res.writeHead(status, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" });
1424
+ res.end(text);
1425
+ }
1426
+ /**
1427
+ * 把四个模块的产物路径映射到磁盘文件:
1428
+ * /dsh-game-material-master/assets/<项目 id>/<相对路径> 八方向图
1429
+ * /dsh-game-material-master/image-assets/<任务 id>/<相对路径> 图片生成
1430
+ * /dsh-game-material-master/sequence-assets/<任务 id>/<相对路径> 序列帧生成
1431
+ * /dsh-game-material-master/rig-assets/<任务 id>/<相对路径> 骨骼动画生成
1432
+ *
1433
+ * 支持 Range:没有它浏览器里的 <video> 就不能拖动进度条,验收视频时会很难受。
1434
+ */
1435
+ async function handleAsset(req, res) {
1436
+ if (req.method !== "GET" && req.method !== "HEAD") {
1437
+ sendText(res, 405, "Method Not Allowed");
1438
+ return;
1439
+ }
1440
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
1441
+ const rest = decodeURIComponent(url.pathname.slice(ROUTE_PREFIX.length)).replace(/^\/+/, "");
1442
+ /**
1443
+ * 构建探针。走 prefix 路由,所以路径是 `/dsh-game-material-master/_health`。
1444
+ *
1445
+ * 不读盘、无副作用,只回「本模块是哪次 import 进来的」——客户端 bundle 每次请求
1446
+ * 都从磁盘现读,宿主半区却只在进程启动(或 profile patch 热重载)时 import 一次,
1447
+ * 两者会不一致。有这个端点,界面与测试就能明确区分「代码没生效」和「功能坏了」,
1448
+ * 而不是像以前那样以「按钮一直是灰的 / 图片 404」的形式坏掉。
1449
+ */
1450
+ if (rest === "_health") {
1451
+ res.writeHead(200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
1452
+ res.end(`${JSON.stringify({ ok: true, pid: process.pid, ...BOOT_INFO })}\n`);
1453
+ return;
1454
+ }
1455
+ const segments = rest.split("/").filter((segment) => segment !== "");
1456
+ if (segments.length < 3) {
1457
+ sendText(res, 404, "Not Found");
1458
+ return;
1459
+ }
1460
+ const scope = segments[0];
1461
+ if (scope !== "assets" && scope !== "image-assets" && scope !== "sequence-assets" && scope !== "rig-assets") {
1462
+ sendText(res, 404, "Not Found");
1463
+ return;
1464
+ }
1465
+ const id = segments[1];
1466
+ const relative = segments.slice(2).join("/");
1467
+ if (relative.includes("..")) {
1468
+ sendText(res, 400, "Bad Request");
1469
+ return;
1470
+ }
1471
+ let target;
1472
+ try {
1473
+ target = resolveAssetTarget(scope, id, relative);
1474
+ }
1475
+ catch {
1476
+ sendText(res, 400, "Bad Request");
1477
+ return;
1478
+ }
1479
+ if (target === undefined) {
1480
+ sendText(res, 400, "Bad Request");
1481
+ return;
1482
+ }
1483
+ if (!target.dirs.has(relative.split("/")[0])) {
1484
+ sendText(res, 403, "Forbidden");
1485
+ return;
1486
+ }
1487
+ let info;
1488
+ try {
1489
+ info = await stat(target.file);
1490
+ }
1491
+ catch {
1492
+ sendText(res, 404, "Not Found");
1493
+ return;
1494
+ }
1495
+ if (!info.isFile()) {
1496
+ sendText(res, 404, "Not Found");
1497
+ return;
1498
+ }
1499
+ const type = MIME_TYPES[extname(target.file).toLowerCase()] ?? "application/octet-stream";
1500
+ const etag = `W/"${info.size.toString(16)}-${Math.floor(info.mtimeMs).toString(16)}"`;
1501
+ const baseHeaders = {
1502
+ "Content-Type": type,
1503
+ ETag: etag,
1504
+ "Last-Modified": new Date(info.mtimeMs).toUTCString(),
1505
+ // 产物是不可变的(每次重跑都会换 mtime → 换 ETag),所以可以放心长缓存。
1506
+ "Cache-Control": "private, max-age=300",
1507
+ "Accept-Ranges": "bytes"
1508
+ };
1509
+ if (req.headers["if-none-match"] === etag) {
1510
+ res.writeHead(304, baseHeaders);
1511
+ res.end();
1512
+ return;
1513
+ }
1514
+ const rangeHeader = req.headers.range;
1515
+ if (typeof rangeHeader === "string") {
1516
+ const match = /^bytes=(\d*)-(\d*)$/.exec(rangeHeader.trim());
1517
+ if (match !== null) {
1518
+ const start = match[1] === "" ? Math.max(0, info.size - Number(match[2])) : Number(match[1]);
1519
+ const end = match[1] === "" || match[2] === "" ? info.size - 1 : Math.min(info.size - 1, Number(match[2]));
1520
+ if (Number.isFinite(start) && Number.isFinite(end) && start <= end && start < info.size) {
1521
+ res.writeHead(206, {
1522
+ ...baseHeaders,
1523
+ "Content-Range": `bytes ${start}-${end}/${info.size}`,
1524
+ "Content-Length": String(end - start + 1)
1525
+ });
1526
+ if (req.method === "HEAD") {
1527
+ res.end();
1528
+ return;
1529
+ }
1530
+ const stream = createReadStream(target.file, { start, end });
1531
+ stream.on("error", () => res.destroy());
1532
+ stream.pipe(res);
1533
+ return;
1534
+ }
1535
+ }
1536
+ }
1537
+ res.writeHead(200, { ...baseHeaders, "Content-Length": String(info.size) });
1538
+ if (req.method === "HEAD") {
1539
+ res.end();
1540
+ return;
1541
+ }
1542
+ const stream = createReadStream(target.file);
1543
+ stream.on("error", () => res.destroy());
1544
+ stream.pipe(res);
1545
+ }
1546
+ // ── cordis 插件体 ────────────────────────────────────────────────────────
1547
+ export function apply(ctx) {
1548
+ // 旧版本的数据目录叫 8dir-sprites,插件改名后搬一次,已有项目无缝接上。
1549
+ void migrateLegacyDataRoot()
1550
+ .then((moved) => {
1551
+ if (moved)
1552
+ process.stderr.write("[game-material-master] 已把旧数据目录 8dir-sprites 迁移到 game-material-master\n");
1553
+ })
1554
+ .catch(() => undefined);
1555
+ const gateway = new GameStudioGateway(ctx);
1556
+ gateway.assertSurface();
1557
+ ctx.effect(() => ctx.typert.register(MANIFEST), "dsh-8dir-sprites: typert manifest");
1558
+ /**
1559
+ * 对话调用面:把网关的全部方法 + 多步流程编排注册成模型工具,
1560
+ * 并加一段系统提示词说明「怎么推进、怎么把验收链接贴给用户」。
1561
+ *
1562
+ * `tools` / `systemPrompt` 都是可选服务:最小化的测试组合里可能没有,
1563
+ * 缺了就只是没有对话调用面,插件本体照常工作。
1564
+ */
1565
+ ctx.effect(() => {
1566
+ const disposers = registerStudioTools({ tools: ctx.get("tools"), systemPrompt: ctx.get("systemPrompt") }, gateway);
1567
+ return () => {
1568
+ for (const dispose of disposers)
1569
+ dispose();
1570
+ };
1571
+ }, "dsh-game-material-master: 对话调用面");
1572
+ const webServer = ctx.get("webServer");
1573
+ if (webServer !== undefined) {
1574
+ ctx.effect(() => webServer.register({ kind: "prefix", path: ROUTE_PREFIX, handler: handleAsset }), "dsh-8dir-sprites: asset route");
1575
+ }
1576
+ else {
1577
+ // inject 已声明 webServer,正常路径下走不到这里;留一条 stderr 诊断,
1578
+ // 因为 ctx.logger 的输出不会出现在启动日志里。
1579
+ process.stderr.write("[dsh-8dir-sprites] webServer 服务不可用,图片预览路由未注册\n");
1580
+ }
1581
+ // 进程重启后,把上次没跑完的视频轮询接上。
1582
+ void (async () => {
1583
+ try {
1584
+ for (const summary of await listProjects()) {
1585
+ const project = await readProject(summary.id);
1586
+ if (project === undefined)
1587
+ continue;
1588
+ if (DIRECTION_KEYS.some((key) => project.videos[key]?.status === "running")) {
1589
+ ensurePoller(summary.id);
1590
+ }
1591
+ }
1592
+ }
1593
+ catch {
1594
+ // 恢复轮询失败不影响插件本体。
1595
+ }
1596
+ })();
1597
+ ctx.effect(() => () => {
1598
+ disposePipeline();
1599
+ seqgen.disposeSequence();
1600
+ riggen.disposeRig();
1601
+ }, "dsh-game-material-master: pipeline cleanup");
1602
+ }