dsh-game-material-master 0.9.2 → 0.10.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.
@@ -42,7 +42,7 @@ const ZH = `# 游戏素材大师 · 谱曲模式指南(scoremill)
42
42
  7. 用户提意见 → 改方案/脚本的**对应段落** → 再调 \`runMusicScore\`(\`basedOn\` 指上一版)。
43
43
  8. 只有用户**明确要求**「用 Suno 生成正式版」时,才调
44
44
  \`submitMusicScoreToSuno({jobId, scoreId, confirm:true})\`。这会真实计费;先说明。
45
- 提交后 \`game_material_wait\`,再把新的 \`openUrl\` 贴回来。
45
+ 提交后 \`game_material({action:'wait', id})\`,再把新的 \`openUrl\` 贴回来。
46
46
 
47
47
  ⚠️ **永远不要自动提交 Suno。** 谱曲和试听都是本地免费;Suno 才花钱。
48
48
  ⚠️ **每版都是新版本**:不要覆盖旧 MIDI/试听;用户可能想回到上一版。
@@ -235,7 +235,7 @@ kit.bars("bdq bde sne bdq [sn hh]e hhe | bdq bde sne bdq hhe hhe |")
235
235
  \`submitMusicScoreToSuno({jobId, scoreId, confirm:true, model?, regenerate?, copyrightAudio?, audioWeight?})\`
236
236
  - 返回 \`needsCopyrightConsent:true\` 时,先把原因告诉用户,确认后再传 \`copyrightAudio:true\` 重试。
237
237
  - 已有歌曲时再提交会再计费:先问用户,并传 \`regenerate:true\`。
238
- - 提交后 \`game_material_wait\`;把新的 \`openUrl\` 贴回来,说清生成了几首。
238
+ - 提交后 \`game_material({action:'wait', id})\`;把新的 \`openUrl\` 贴回来,说清生成了几首。
239
239
  - 原曲超过 360 秒时,Suno 只能按 360 秒提交;在回答里说明。
240
240
  - 参考音频权重 \`audioWeight\` 默认 0.75;想更贴 MIDI 可以调高(0–1),想更像 Suno 的编曲可以调低。
241
241
 
@@ -271,7 +271,7 @@ const EN = `# Game Material Master · Compose Mode Guide (scoremill)
271
271
  \`runMusicScore\` again with \`basedOn\` pointing at the previous version.
272
272
  8. Only when the user **explicitly asks** for "Suno version" call
273
273
  \`submitMusicScoreToSuno({jobId, scoreId, confirm:true})\`. It costs credits; say so first.
274
- Then \`game_material_wait\` and paste the new \`openUrl\`.
274
+ Then \`game_material({action:'wait', id})\` and paste the new \`openUrl\`.
275
275
 
276
276
  ⚠️ **Never auto-submit to Suno.** Composing and auditioning are local/free; Suno is paid.
277
277
  ⚠️ **Every revision is a new version**; never overwrite old MIDI/preview.
@@ -468,7 +468,7 @@ When the user says "too loud / too slow / too many drums / theme not clear / sec
468
468
  - If it returns \`needsCopyrightConsent:true\`, explain why to the user first; retry with
469
469
  \`copyrightAudio:true\` only after confirmation.
470
470
  - If songs already exist, another batch costs credits: ask first and pass \`regenerate:true\`.
471
- - After submitting, \`game_material_wait\`; paste the new \`openUrl\` and say how many songs were produced.
471
+ - After submitting, \`game_material({action:'wait', id})\`; paste the new \`openUrl\` and say how many songs were produced.
472
472
  - If the piece is longer than 360s, Suno is submitted at 360s; state that in the answer.
473
473
  - \`audioWeight\` defaults to 0.75; raise it (0–1) to stay closer to the MIDI, lower it to let Suno
474
474
  arrange more freely.
package/lib/riggen.js CHANGED
@@ -28,7 +28,7 @@ import { mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
28
28
  import { basename, join, resolve, sep } from "node:path";
29
29
  import { randomUUID } from "node:crypto";
30
30
  import { loadConfig, rigJobsRoot } from "./config.js";
31
- import { assertImageProviderReady, generateImageWithProvider, imageModelOf, imageProviderBlocker, imageSizeOf, imageTimeoutOf, imageWatermarkOf, isCustomProvider } from "./imageprovider.js";
31
+ import { assertImageProviderReady, generateImageWithProvider, imageModelOf, imageProviderBlocker, imageSizeOf, imageTimeoutOf, imageWatermarkOf, imageUsesConfiguredSize, imageRedrawModelOf } from "./imageprovider.js";
32
32
  import { decodeToRgba, mimeOf, toDataUri } from "./media.js";
33
33
  import { encodePng } from "./png.js";
34
34
  import { appendJobLog, messageOf, readJson, writeJsonAtomic } from "./jsonio.js";
@@ -597,7 +597,7 @@ function normalizeQaState(raw) {
597
597
  *
598
598
  * 工具返回值必须是**无损 JSON**:`undefined` 一旦出现在对象里,序列化时会静默
599
599
  * 丢掉那个键,宿主据此判定「结果不是无损 JSON」并直接让整个工具调用报错
600
- * (实测表现是 `game_material_status` / `game_material_wait` / `getRigJob`
600
+ * (实测表现是 `game_material({action:'status'})` / `game_material({action:'wait'})` / `getRigJob`
601
601
  * 全部返回 `value is not lossless JSON`)。视图里有大量可选字段,逐个写
602
602
  * `?? null` 太容易漏,统一在出口处清一遍。
603
603
  */
@@ -1465,9 +1465,9 @@ export async function redrawRigPart(jobId, name, prompt, options = {}) {
1465
1465
  const square = padToSquare(original, REDRAW_PAD_COLOR);
1466
1466
  const dataUri = `data:image/png;base64,${encodePng(square.image.data, square.image.width, square.image.height).toString("base64")}`;
1467
1467
  // 部件重绘单独指定模型的开关只在火山方舟下有意义;自定义后端只有一个模型名。
1468
- const redrawModel = isCustomProvider(config) ? "" : config.arkRedrawModel.trim();
1468
+ const redrawModel = imageRedrawModelOf(config);
1469
1469
  /** 这一次真正会用的模型名(只用于报错文案)。 */
1470
- const modelUsedForRedraw = isCustomProvider(config) ? config.customModel : redrawModel || config.arkModel;
1470
+ const modelUsedForRedraw = redrawModel;
1471
1471
  const result = await generateImageWithProvider({
1472
1472
  model: redrawModel,
1473
1473
  prompt: buildRedrawPrompt(prompt, { role: part.role }),
@@ -2420,8 +2420,8 @@ export async function generateSheet(jobId) {
2420
2420
  const prompt = buildSheetRequest(job);
2421
2421
  const model = imageModelOf(config);
2422
2422
  job.settings.model = model;
2423
- if (isCustomProvider(config))
2424
- job.settings.size = config.customSize;
2423
+ if (imageUsesConfiguredSize(config))
2424
+ job.settings.size = imageSizeOf(config);
2425
2425
  job.sheet = { ...job.sheet, status: "running", error: undefined };
2426
2426
  appendJobLog(job.log, "info", `开始拆件生图(模型 ${model})`);
2427
2427
  await writeRigJob(job);
package/lib/seqgen.js CHANGED
@@ -65,9 +65,9 @@ export async function createSequenceJob(name) {
65
65
  suffix: "",
66
66
  refs: { referenceImages: [], referenceVideos: [] },
67
67
  settings: {
68
- model: config.minimaxModel,
69
- duration: config.minimaxDuration,
70
- resolution: config.minimaxResolution,
68
+ model: config.toapisVideo && !config.comfyVideo ? config.toapisVideoModel : config.minimaxModel,
69
+ duration: config.toapisVideo && !config.comfyVideo ? config.toapisVideoDuration : config.minimaxDuration,
70
+ resolution: config.toapisVideo && !config.comfyVideo ? config.toapisVideoResolution : config.minimaxResolution,
71
71
  promptOptimizer: config.minimaxPromptOptimizer,
72
72
  frameCount: config.frameCount,
73
73
  cellWidth: config.cellWidth,
@@ -187,7 +187,7 @@ function normalizeSequenceJob(raw) {
187
187
  video: {
188
188
  status: (raw?.video?.status ?? "empty"),
189
189
  taskId: typeof raw?.video?.taskId === "string" ? raw.video.taskId : undefined,
190
- backend: raw?.video?.backend === "comfy" || raw?.video?.backend === "minimax" ? raw.video.backend : undefined,
190
+ backend: raw?.video?.backend === "comfy" || raw?.video?.backend === "minimax" || raw?.video?.backend === "toapis" ? raw.video.backend : undefined,
191
191
  remoteStatus: typeof raw?.video?.remoteStatus === "string" ? raw.video.remoteStatus : undefined,
192
192
  file: typeof raw?.video?.file === "string" ? raw.video.file : undefined,
193
193
  error: typeof raw?.video?.error === "string" ? raw.video.error : undefined,
@@ -307,10 +307,10 @@ async function submitSequenceVideo(jobId) {
307
307
  // 模型是全局设置(设置 → 游戏素材大师 → 视频模型),任务只跟随、不覆盖:
308
308
  // 任务的模型快照一旦和当前网关/Key 对不上(例如官方 H3 + 优云智算网关),
309
309
  // 就会打出 cp.compshare.cn/v2/... 这种 404。这里以全局配置为准并回写任务。
310
- const model = config.minimaxModel;
310
+ const model = config.toapisVideo && !config.comfyVideo ? config.toapisVideoModel : config.minimaxModel;
311
311
  job.settings.model = model;
312
- job.settings.duration = normalizeDuration(model, job.settings.duration);
313
- job.settings.resolution = normalizeResolution(model, job.settings.resolution);
312
+ job.settings.duration = config.toapisVideo && !config.comfyVideo ? config.toapisVideoDuration : normalizeDuration(model, job.settings.duration);
313
+ job.settings.resolution = config.toapisVideo && !config.comfyVideo ? config.toapisVideoResolution : normalizeResolution(model, job.settings.resolution);
314
314
  const built = buildSequencePrompt(job);
315
315
  if ("error" in built)
316
316
  throw new Error(built.error);
package/lib/sfxgen.js CHANGED
@@ -15,7 +15,7 @@
15
15
  *
16
16
  * 火山引擎的 `seed-audio-1.0` 是**同步接口**:一次 POST 直接返回整段音频,
17
17
  * 没有 taskId、没有轮询。这里仍然用后台任务表承载,是为了不阻塞网关调用,
18
- * 也让 `game_material_wait` / 界面的「生成中」状态有统一落点。
18
+ * 也让 `game_material({action:'wait'})` / 界面的「生成中」状态有统一落点。
19
19
  *
20
20
  * 所有写 `job.json` 的地方都走 `patchSfxJob()` 的**按任务串行队列**:界面保存
21
21
  * 提示词、后台任务收尾、上传参考同时发生时,后写的不会覆盖前一次改动。
@@ -800,10 +800,10 @@ export function sfxNextActions(snapshot) {
800
800
  actions.push(snapshot.blocker);
801
801
  const takes = Array.isArray(snapshot.takes) ? snapshot.takes : [];
802
802
  if (snapshot.busy === true) {
803
- actions.push("正在生成:用 game_material_wait({module:'sfx', id}) 等它结束;不要重复提交。");
803
+ actions.push("正在生成:用 game_material({action:'wait', module:'sfx', id}) 等它结束;不要重复提交。");
804
804
  }
805
805
  else if (takes.length === 0) {
806
- actions.push("还没有生成:runSfxGeneration({jobId})(★真实计费,每次一条),然后 game_material_wait。");
806
+ actions.push("还没有生成:runSfxGeneration({jobId})(★真实计费,每次一条),然后 game_material({action:'wait', module:'sfx', id})。");
807
807
  }
808
808
  else {
809
809
  actions.push("试听 takes 里的 URL;满意就 exportSfx({jobId, takeId}),不满意改提示词再 runSfxGeneration(会再计费一次)。");
package/lib/store.js CHANGED
@@ -274,7 +274,7 @@ export function summarize(project) {
274
274
  * 一个不认识的字符串会让查询分派悄悄走到「按配置猜」那条路上。
275
275
  */
276
276
  function normalizeVideoBackend(raw) {
277
- return raw === "comfy" || raw === "minimax" ? raw : undefined;
277
+ return raw === "comfy" || raw === "minimax" || raw === "toapis" ? raw : undefined;
278
278
  }
279
279
  function normalizeProject(raw) {
280
280
  const now = Date.now();
package/lib/toapis.js ADDED
@@ -0,0 +1,338 @@
1
+ /** Optional ToAPIs asynchronous media transport. No automatic paid POST retries. */
2
+ import { createHash } from "node:crypto";
3
+ import { mkdir, readFile, open, readdir, unlink } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { writeJsonAtomic } from "./jsonio.js";
6
+ import { dataRoot } from "./config.js";
7
+ export function toapisRoot(base) {
8
+ const url = new URL(base.trim());
9
+ if (url.username ||
10
+ url.password ||
11
+ url.search ||
12
+ url.hash ||
13
+ !(url.protocol === "https:" ||
14
+ (url.protocol === "http:" &&
15
+ ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname))))
16
+ throw new Error("ToAPIs: use HTTPS (HTTP is only supported for a local proxy)");
17
+ if (!/^\/(?:v1\/?)?$/.test(url.pathname))
18
+ throw new Error("ToAPIs: Base URL must be an origin or end in /v1");
19
+ return url.origin + "/v1";
20
+ }
21
+ export function assertToapisModel(model) {
22
+ const id = model.toLowerCase().replace(/[^a-z0-9]/g, "");
23
+ if (!id || (id.includes("seedance") && id.includes("global")))
24
+ throw new Error("ToAPIs: empty model or disabled Seedance Global model");
25
+ }
26
+ export function assertToapisReady(config) {
27
+ toapisRoot(config.toapisBaseUrl);
28
+ if (!config.toapisApiKey.trim())
29
+ throw new Error("ToAPIs: configure the API Key in settings");
30
+ }
31
+ function context(config, signal) {
32
+ const timeout = AbortSignal.timeout(config.toapisTimeoutMs);
33
+ return signal ? AbortSignal.any([timeout, signal]) : timeout;
34
+ }
35
+ async function api(config, path, signal, body) {
36
+ const multipart = body instanceof FormData;
37
+ const response = await fetch(toapisRoot(config.toapisBaseUrl) + "/" + path, {
38
+ method: body === undefined ? "GET" : "POST",
39
+ redirect: "error",
40
+ signal,
41
+ headers: {
42
+ Authorization: `Bearer ${config.toapisApiKey.trim()}`,
43
+ ...(multipart || body === undefined
44
+ ? {}
45
+ : { "Content-Type": "application/json" }),
46
+ },
47
+ body: body === undefined ? undefined : multipart ? body : JSON.stringify(body),
48
+ });
49
+ if (!response.ok)
50
+ throw new Error(`ToAPIs ${path.split("/")[0]}: HTTP ${response.status}`);
51
+ return response.json();
52
+ }
53
+ const digest = (value) => createHash("sha256").update(value).digest("hex");
54
+ async function readJson(path) {
55
+ try {
56
+ return JSON.parse(await readFile(path, "utf8"));
57
+ }
58
+ catch (error) {
59
+ if (error.code === "ENOENT")
60
+ return undefined;
61
+ throw error;
62
+ }
63
+ }
64
+ const terminal = (state) => ["completed", "failed", "cancelled", "expired"].includes(state);
65
+ /** A persistent guard closes the gap between paid submission and the host storing taskId. */
66
+ async function submit(config, kind, body, signal, identity = body) {
67
+ const dir = join(dataRoot(), "toapis-receipts");
68
+ await mkdir(dir, { recursive: true });
69
+ const root = toapisRoot(config.toapisBaseUrl);
70
+ const file = join(dir, digest(JSON.stringify([root, digest(config.toapisApiKey), kind, identity])) + ".json");
71
+ const previous = await readJson(file);
72
+ if (previous?.delivered === true)
73
+ await unlink(file);
74
+ else if (previous) {
75
+ if (!previous.id)
76
+ throw new Error(`ToAPIs: previous submission uncertain; reconcile receipt ${file} before resubmitting`);
77
+ const old = await api(config, `${kind}/generations/${encodeURIComponent(previous.id)}`, signal);
78
+ if (!terminal(old.status))
79
+ return old;
80
+ // Recover completed output after restart/cancellation before allowing an explicit regeneration.
81
+ if (old.status === "completed")
82
+ return old;
83
+ throw new Error(`ToAPIs: previous task ${previous.id} is ${old.status}; reconcile receipt ${file} before an explicit regeneration`);
84
+ }
85
+ const handle = await open(file, "wx");
86
+ await handle.writeFile(JSON.stringify({ state: "submitting", kind, createdAt: Date.now() }));
87
+ await handle.close();
88
+ try {
89
+ const task = await api(config, kind + "/generations", signal, body);
90
+ if (typeof task.id !== "string" || !task.id.trim())
91
+ throw new Error("ToAPIs: no task ID; do not repeat the paid submission");
92
+ await writeJsonAtomic(file, {
93
+ id: task.id,
94
+ kind,
95
+ state: task.status,
96
+ createdAt: Date.now(),
97
+ });
98
+ return task;
99
+ }
100
+ catch (error) {
101
+ throw new Error(`ToAPIs submission may have been accepted; do not retry automatically. Reconcile ${file}. ${error instanceof Error ? error.message : "Request failed"}`);
102
+ }
103
+ }
104
+ async function updateReceipt(kind, field, value, patch) {
105
+ const dir = join(dataRoot(), "toapis-receipts");
106
+ let files;
107
+ try {
108
+ files = await readdir(dir);
109
+ }
110
+ catch (error) {
111
+ if (error.code === "ENOENT")
112
+ return;
113
+ throw error;
114
+ }
115
+ for (const name of files) {
116
+ if (!/^[a-f0-9]{64}\.json$/.test(name))
117
+ continue;
118
+ const file = join(dir, name), record = await readJson(file);
119
+ if (record?.kind === kind && record[field] === value)
120
+ await writeJsonAtomic(file, { ...record, ...patch });
121
+ }
122
+ }
123
+ function outputUrl(task) {
124
+ const url = task?.result?.data?.[0]?.url;
125
+ return typeof url === "string" && url ? url : undefined;
126
+ }
127
+ async function reference(config, image, signal) {
128
+ if (/^https:\/\//i.test(image))
129
+ return image;
130
+ const match = /^data:(image\/(?:png|jpeg|webp));base64,([a-z0-9+/=\s]+)$/i.exec(image);
131
+ if (!match)
132
+ throw new Error("ToAPIs: reference must be an HTTPS image or PNG/JPEG/WebP data URI");
133
+ const bytes = Buffer.from(match[2], "base64");
134
+ if (!bytes.length || bytes.length > 20 * 1024 * 1024)
135
+ throw new Error("ToAPIs: reference image exceeds 20 MiB or is empty");
136
+ const form = new FormData();
137
+ form.append("file", new Blob([bytes], { type: match[1] }), "reference." + match[1].split("/")[1]);
138
+ const result = await api(config, "uploads/images", signal, form);
139
+ if (typeof result?.data?.url !== "string" ||
140
+ !result.data.url.startsWith("https://"))
141
+ throw new Error("ToAPIs: upload did not return an HTTPS image URL");
142
+ return result.data.url;
143
+ }
144
+ export async function downloadToapis(config, input, kind, signal = context(config)) {
145
+ let url = new URL(input);
146
+ const local = new URL(toapisRoot(config.toapisBaseUrl));
147
+ for (let attempt = 0; attempt < 4; attempt++) {
148
+ const sameLocal = local.protocol === "http:" && url.origin === local.origin;
149
+ if (url.username ||
150
+ url.password ||
151
+ (!sameLocal &&
152
+ (url.protocol !== "https:" ||
153
+ /^(localhost|127\.|10\.|192\.168\.|169\.254\.|0\.|\[|172\.(1[6-9]|2\d|3[01])\.)/i.test(url.hostname))))
154
+ throw new Error("ToAPIs: unsafe output URL");
155
+ // No bearer header, even when a CDN redirects. Validate every redirect target.
156
+ const response = await fetch(url, { signal, redirect: "manual" });
157
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
158
+ const location = response.headers.get("location");
159
+ await response.body?.cancel();
160
+ if (!location)
161
+ throw new Error("ToAPIs: output redirect has no target");
162
+ url = new URL(location, url);
163
+ continue;
164
+ }
165
+ if (!response.ok || !response.body)
166
+ throw new Error(`ToAPIs output: HTTP ${response.status}`);
167
+ const limit = (kind === "image" ? 32 : 100) * 1024 * 1024;
168
+ const reader = response.body.getReader();
169
+ let total = 0;
170
+ const chunks = [];
171
+ try {
172
+ while (true) {
173
+ const next = await reader.read();
174
+ if (next.done)
175
+ break;
176
+ total += next.value.length;
177
+ if (total > limit)
178
+ throw new Error("ToAPIs: output exceeds size limit");
179
+ chunks.push(next.value);
180
+ }
181
+ }
182
+ finally {
183
+ await reader.cancel();
184
+ }
185
+ const bytes = Buffer.concat(chunks);
186
+ if (kind === "image"
187
+ ? imageExt(bytes) === undefined
188
+ : !(bytes.length >= 12 && bytes.toString("ascii", 4, 8) === "ftyp"))
189
+ throw new Error("ToAPIs: result is not a supported image/MP4 file");
190
+ if (kind === "video")
191
+ await updateReceipt("videos", "outputHash", digest(input), {
192
+ delivered: true,
193
+ });
194
+ return bytes;
195
+ }
196
+ throw new Error("ToAPIs: too many output redirects");
197
+ }
198
+ function imageExt(bytes) {
199
+ if (bytes.length >= 8 &&
200
+ bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
201
+ return "png";
202
+ if (bytes.length >= 3 &&
203
+ bytes[0] === 255 &&
204
+ bytes[1] === 216 &&
205
+ bytes[2] === 255)
206
+ return "jpg";
207
+ if (bytes.length >= 12 &&
208
+ bytes.toString("ascii", 0, 4) === "RIFF" &&
209
+ bytes.toString("ascii", 8, 12) === "WEBP")
210
+ return "webp";
211
+ }
212
+ function imageSize(input) {
213
+ const pixels = /^(\d+)[x×](\d+)$/i.exec(input.trim());
214
+ if (pixels) {
215
+ const w = Number(pixels[1]), h = Number(pixels[2]);
216
+ if (!(w > 0 && h > 0))
217
+ throw new Error("ToAPIs: invalid image dimensions");
218
+ const gcd = (a, b) => (b ? gcd(b, a % b) : a);
219
+ const divisor = gcd(w, h);
220
+ return {
221
+ size: `${w / divisor}:${h / divisor}`,
222
+ resolution: Math.max(w, h) > 2048 ? "4K" : Math.max(w, h) > 1024 ? "2K" : "1K",
223
+ };
224
+ }
225
+ if (/^[124]k$/i.test(input.trim()))
226
+ return { size: "1:1", resolution: input.toUpperCase() };
227
+ throw new Error("ToAPIs: use width x height or 1K/2K/4K for image size");
228
+ }
229
+ export async function generateToapisImage(config, request, signal) {
230
+ assertToapisReady(config);
231
+ const model = request.model?.trim() || config.toapisImageModel;
232
+ assertToapisModel(model);
233
+ if (!request.prompt.trim())
234
+ throw new Error("ToAPIs: empty prompt");
235
+ const combined = context({ ...config, toapisTimeoutMs: request.timeoutMs ?? config.toapisTimeoutMs }, signal);
236
+ const references = [];
237
+ for (const image of request.images)
238
+ references.push(await reference(config, image, combined));
239
+ const body = {
240
+ model,
241
+ prompt: request.prompt,
242
+ ...imageSize(request.size || config.toapisImageSize),
243
+ n: 1,
244
+ };
245
+ if (config.toapisImageQuality.trim())
246
+ body.quality = config.toapisImageQuality.trim();
247
+ if (references.length)
248
+ body.reference_images = references;
249
+ let task = await submit(config, "images", body, combined, {
250
+ ...body,
251
+ reference_images: request.images,
252
+ });
253
+ while (!terminal(task.status)) {
254
+ task = await api(config, "images/generations/" + encodeURIComponent(task.id), combined);
255
+ if (!terminal(task.status))
256
+ await new Promise((resolve, reject) => {
257
+ const abort = () => {
258
+ clearTimeout(timer);
259
+ reject(new Error("ToAPIs: image polling cancelled/timed out; resume from receipt"));
260
+ };
261
+ const timer = setTimeout(() => {
262
+ combined.removeEventListener("abort", abort);
263
+ resolve();
264
+ }, 5000);
265
+ if (combined.aborted)
266
+ abort();
267
+ else
268
+ combined.addEventListener("abort", abort, { once: true });
269
+ });
270
+ }
271
+ if (task.status !== "completed")
272
+ throw new Error(`ToAPIs image task ${task.id}: ${task.status}`);
273
+ const url = outputUrl(task);
274
+ if (!url)
275
+ throw new Error("ToAPIs: completed image task has no output URL");
276
+ const bytes = await downloadToapis(config, url, "image", combined);
277
+ await updateReceipt("images", "id", task.id, { delivered: true });
278
+ return {
279
+ bytes,
280
+ ext: imageExt(bytes),
281
+ remoteUrl: url,
282
+ usage: { taskId: task.id, billing: task.billing, usage: task.usage },
283
+ };
284
+ }
285
+ export async function submitToapisVideo(config, request) {
286
+ assertToapisReady(config);
287
+ assertToapisModel(config.toapisVideoModel);
288
+ // Initial support is deliberately first-frame-only; unsupported references never trigger a paid request.
289
+ if (request.lastFrameImage ||
290
+ request.referenceImages?.length ||
291
+ request.referenceVideos?.length)
292
+ throw new Error("ToAPIs: this adapter currently supports only text or one first-frame image, not last-frame/multimodal inputs");
293
+ const signal = context(config);
294
+ const body = {
295
+ model: config.toapisVideoModel,
296
+ prompt: request.prompt,
297
+ duration: config.toapisVideoDuration,
298
+ resolution: config.toapisVideoResolution,
299
+ aspect_ratio: "16:9",
300
+ generate_audio: false,
301
+ output_format: "mp4",
302
+ };
303
+ if (request.firstFrameImage)
304
+ body.image_with_roles = [
305
+ {
306
+ url: await reference(config, request.firstFrameImage, signal),
307
+ role: "first_frame",
308
+ },
309
+ ];
310
+ return (await submit(config, "videos", body, signal, {
311
+ ...body,
312
+ image_with_roles: undefined,
313
+ firstFrame: request.firstFrameImage,
314
+ })).id;
315
+ }
316
+ export async function queryToapisVideo(config, taskId) {
317
+ assertToapisReady(config);
318
+ const task = await api(config, "videos/generations/" + encodeURIComponent(taskId), context(config));
319
+ if (task.status === "completed") {
320
+ const url = outputUrl(task);
321
+ if (!url)
322
+ throw new Error("ToAPIs: completed video task has no output URL");
323
+ await updateReceipt("videos", "id", taskId, { outputHash: digest(url) });
324
+ return { status: "succeeded", remoteStatus: task.status, url };
325
+ }
326
+ if (["failed", "cancelled", "expired"].includes(task.status))
327
+ return {
328
+ status: "failed",
329
+ remoteStatus: task.status,
330
+ error: `ToAPIs task ${taskId}: ${task.status}`,
331
+ };
332
+ return {
333
+ status: task.status === "pending" || task.status === "queued"
334
+ ? "pending"
335
+ : "running",
336
+ remoteStatus: task.status || "unknown",
337
+ };
338
+ }