@magpie-community/opencode-opendesign-auth 0.1.15 → 0.1.17

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.
Files changed (4) hide show
  1. package/README.md +287 -2
  2. package/index.mjs +776 -16
  3. package/package.json +7 -2
  4. package/video.mjs +545 -0
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-opendesign-auth",
3
- "version": "0.1.15",
4
- "description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in, its models, and the plan's 5-hour and 7-day allowance",
3
+ "version": "0.1.17",
4
+ "description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in, chat and native video models, the plan's 5-hour and 7-day allowance, and its reset cards",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",
7
7
  "files": [
@@ -9,6 +9,7 @@
9
9
  "opencode.mjs",
10
10
  "opencode2.mjs",
11
11
  "models.mjs",
12
+ "video.mjs",
12
13
  "rates.mjs",
13
14
  "refresh-models.mjs",
14
15
  "README.md"
@@ -26,7 +27,11 @@
26
27
  "directory": "packages/opendesign"
27
28
  },
28
29
  "magpie": {
30
+ "name": "Open Design",
29
31
  "icon": "https://open-design.ai/favicon.svg"
30
32
  },
33
+ "scripts": {
34
+ "test": "bun test"
35
+ },
31
36
  "exports": { ".": "./opencode2.mjs" }
32
37
  }
package/video.mjs ADDED
@@ -0,0 +1,545 @@
1
+ import { randomUUID } from "node:crypto"
2
+
3
+ const ORIGIN = "https://amr-link.open-design.ai"
4
+ const MEDIA = `${ORIGIN}/api/v1/media`
5
+ const CHAT = `${ORIGIN}/v1`
6
+ const MAX_UPLOAD = 50 * 1024 * 1024
7
+ const MAX_IMAGES = 5
8
+ const IMAGE_MIMES = new Set(["image/jpeg", "image/png", "image/webp"])
9
+ const ROLES = new Set(["first_frame", "reference"])
10
+ const COST = { input: 0, output: 0, cache: { read: 0, write: 0 } }
11
+ const SUBMIT_ATTEMPTS = 3
12
+ const RETRY_STATUSES = new Set([502, 503, 504])
13
+ const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308])
14
+ const MAX_REDIRECTS = 5
15
+ const NOT_AN_IMAGE = "reference image must be a data: URL, an uploaded file or an asset_id"
16
+
17
+ export const VIDEO_MODELS = Object.freeze({
18
+ "doubao-seedance-2-5-260628": { name: "Seedance 2.5", min: 4, max: 30, seconds: 5, resolutions: ["480p", "720p", "1080p"], ratios: ["adaptive", "16:9", "4:3", "1:1", "3:4", "9:16", "21:9"], images: 1 },
19
+ "doubao-seedance-2-5-flash-261115": { name: "Seedance 2.5 Flash", min: 4, max: 30, seconds: 5, resolutions: ["480p", "720p"], ratios: ["adaptive", "16:9", "4:3", "1:1", "3:4", "9:16", "21:9"], images: 1 },
20
+ "doubao-seedance-2-0-260128": { name: "Seedance 2.0", min: 4, max: 30, seconds: 5, resolutions: ["480p", "720p", "1080p", "4k"], ratios: ["16:9", "9:16", "1:1"], images: 1 },
21
+ "wan-2.7": { name: "Wan 2.7", min: 2, max: 15, seconds: 5, resolutions: ["720p", "1080p"], ratios: ["adaptive", "16:9", "9:16", "1:1", "4:3", "3:4"], images: 1 },
22
+ "magi-2": { name: "MAGI-2", min: 4, max: 5, seconds: 5, resolutions: ["1080p"], ratios: ["16:9", "4:3", "1:1", "3:4", "9:16", "21:9"], images: 5 },
23
+ })
24
+
25
+ const text = (value) => typeof value === "string" && value.trim() ? value.trim() : ""
26
+ const record = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {}
27
+ const given = (value) => value !== undefined && value !== null && value !== ""
28
+ const fail = (status, message, extra = {}) => Object.assign(new Error(message), { status, ...extra })
29
+ const abortReason = (signal) => signal.reason ?? new Error("The operation was aborted")
30
+
31
+ function json(body, status = 200, headers = {}) {
32
+ return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", ...headers } })
33
+ }
34
+
35
+ function errorJSON(status, message, signIn) {
36
+ const type = status === 401 ? "authentication_error"
37
+ : status === 403 ? "permission_error"
38
+ : status === 429 ? "rate_limit_error"
39
+ : status < 500 ? "invalid_request_error" : "upstream_error"
40
+ return json({ error: { message, type } }, status, signIn ? { "X-Magpie-Sign-In": signIn } : {})
41
+ }
42
+
43
+ function sleep(ms, signal) {
44
+ return new Promise((resolve, reject) => {
45
+ if (signal?.aborted) return reject(abortReason(signal))
46
+ const onAbort = () => {
47
+ clearTimeout(timer)
48
+ reject(abortReason(signal))
49
+ }
50
+ const timer = setTimeout(() => {
51
+ signal?.removeEventListener("abort", onAbort)
52
+ resolve()
53
+ }, ms)
54
+ signal?.addEventListener("abort", onAbort, { once: true })
55
+ })
56
+ }
57
+
58
+ export function videoPath(input) {
59
+ let path
60
+ try { path = new URL(String(input), "https://local").pathname } catch { return null }
61
+ if (/\/v1\/videos\/?$/.test(path)) return { kind: "create" }
62
+ const found = /\/v1\/videos\/([^/]+)(?:\/(content))?\/?$/.exec(path)
63
+ if (!found) return null
64
+ let id
65
+ try { id = decodeURIComponent(found[1]) } catch { id = found[1] }
66
+ return { kind: found[2] === "content" ? "content" : "get", id }
67
+ }
68
+
69
+ export function videoConfigModels() {
70
+ return Object.fromEntries(Object.entries(VIDEO_MODELS).map(([id, spec]) => [id, {
71
+ id,
72
+ name: spec.name,
73
+ attachment: true,
74
+ tool_call: false,
75
+ reasoning: false,
76
+ limit: { context: 0, output: 0 },
77
+ cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
78
+ modalities: { input: ["text", "image"], output: ["video"] },
79
+ variants: {},
80
+ }]))
81
+ }
82
+
83
+ function videoServed(id, name) {
84
+ return {
85
+ id,
86
+ name: text(name) || VIDEO_MODELS[id]?.name || id,
87
+ api: { id, url: CHAT, npm: "@ai-sdk/openai-compatible" },
88
+ status: "active",
89
+ headers: {},
90
+ options: {},
91
+ cost: COST,
92
+ limit: { context: 0, output: 0 },
93
+ capabilities: {
94
+ temperature: false,
95
+ reasoning: false,
96
+ attachment: true,
97
+ toolcall: false,
98
+ input: { text: true, image: true, audio: false, video: false, pdf: false },
99
+ output: { text: false, image: false, audio: false, video: true, pdf: false },
100
+ interleaved: false,
101
+ },
102
+ release_date: "",
103
+ variants: {},
104
+ }
105
+ }
106
+
107
+ function catalogRows(body) {
108
+ if (Array.isArray(body)) return body
109
+ for (const key of ["data", "models"]) if (Array.isArray(body?.[key])) return body[key]
110
+ return []
111
+ }
112
+
113
+ function isVideo(row) {
114
+ const kind = text(row?.kind ?? row?.type ?? row?.output_modality).toLowerCase()
115
+ if (["video", "videos", "video_generation", "video_generations"].includes(kind)) return true
116
+ const outputs = row?.output_modalities ?? row?.architecture?.output_modalities ?? row?.modalities?.output ?? row?.capabilities?.output
117
+ return Array.isArray(outputs) ? outputs.includes("video") && !outputs.includes("text") : outputs?.video === true && outputs?.text !== true
118
+ }
119
+
120
+ export function videoModels(body) {
121
+ const out = {}
122
+ for (const row of catalogRows(body)) {
123
+ const id = text(row?.id ?? row?.model ?? row?.model_id)
124
+ if (id && isVideo(row)) out[id] = videoServed(id, row.name ?? row.display_name ?? row.displayName)
125
+ }
126
+ return out
127
+ }
128
+
129
+ export function withFallbackVideos(models) {
130
+ return { ...Object.fromEntries(Object.keys(VIDEO_MODELS).map((id) => [id, videoServed(id)])), ...models }
131
+ }
132
+
133
+ // ---- request fields ------------------------------------------------------------
134
+
135
+ const gcd = (a, b) => b ? gcd(b, a % b) : a
136
+
137
+ function sizeOf(size) {
138
+ const value = text(size).toLowerCase()
139
+ if (!value) return {}
140
+ if (value === "auto" || value === "adaptive") return { ratio: "adaptive" }
141
+ if (/^(?:\d{3,4}p|4k)$/.test(value)) return { resolution: value }
142
+ const found = /^(\d{1,5})\s*[x×*:]\s*(\d{1,5})$/.exec(value)
143
+ const width = Number(found?.[1])
144
+ const height = Number(found?.[2])
145
+ if (!width || !height) throw fail(400, "size must be WIDTHxHEIGHT, a ratio such as 16:9, or a resolution such as 720p")
146
+ const divisor = gcd(width, height)
147
+ return { ratio: `${width / divisor}:${height / divisor}`, shape: width / height }
148
+ }
149
+
150
+ function nearestRatio({ ratio, shape }, options) {
151
+ if (ratio === "adaptive") return options.includes("adaptive") ? "adaptive" : ""
152
+ if (options.includes(ratio)) return ratio
153
+ const distance = (option) => {
154
+ const [width, height] = option.split(":").map(Number)
155
+ return Math.abs(Math.log(width / height) - Math.log(shape))
156
+ }
157
+ return options.filter((option) => option !== "adaptive").sort((a, b) => distance(a) - distance(b))[0] ?? ""
158
+ }
159
+
160
+ function ratioOf(value) {
161
+ const ratio = text(value)
162
+ return ratio.toLowerCase() === "auto" ? "adaptive" : ratio
163
+ }
164
+
165
+ function choice(value, options, label) {
166
+ const selected = text(value)
167
+ if (!selected || !options) return selected
168
+ const found = options.find((option) => option.toLowerCase() === selected.toLowerCase())
169
+ if (!found) throw fail(400, `${label} must be one of ${options.join(", ")}`)
170
+ return found
171
+ }
172
+
173
+ function duration(body, model, spec) {
174
+ const raw = body.seconds ?? body.duration
175
+ if (!given(raw)) return spec?.seconds
176
+ const value = Number(raw)
177
+ if (!Number.isInteger(value) || value <= 0) throw fail(400, "video duration must be a whole number of seconds")
178
+ if (spec && (value < spec.min || value > spec.max)) throw fail(400, `${model} duration must be ${spec.min}–${spec.max} seconds`)
179
+ return value
180
+ }
181
+
182
+ function flag(value, label) {
183
+ if (value === true || value === false) return value
184
+ const word = String(value).trim().toLowerCase()
185
+ if (word === "true") return true
186
+ if (word === "false") return false
187
+ throw fail(400, `${label} must be true or false`)
188
+ }
189
+
190
+ // ---- reference images ------------------------------------------------------------
191
+
192
+ function sniff(bytes) {
193
+ if (bytes.length >= 4 && bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47) return "image/png"
194
+ if (bytes.length >= 3 && bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) return "image/jpeg"
195
+ if (bytes.length >= 12 && bytes.toString("latin1", 0, 4) === "RIFF" && bytes.toString("latin1", 8, 12) === "WEBP") return "image/webp"
196
+ return ""
197
+ }
198
+
199
+ function imageBytes(bytes, declared) {
200
+ let mime = String(declared ?? "").split(";")[0].trim().toLowerCase()
201
+ if (mime === "image/jpg") mime = "image/jpeg"
202
+ if (!mime || mime === "application/octet-stream" || mime === "binary/octet-stream") mime = sniff(bytes)
203
+ if (!IMAGE_MIMES.has(mime)) throw fail(400, "reference image must be JPEG, PNG or WebP")
204
+ if (!bytes.length || bytes.length > MAX_UPLOAD) throw fail(400, "reference image must be between 1 byte and 50 MiB")
205
+ return { bytes, mime }
206
+ }
207
+
208
+ function dataImage(url) {
209
+ const found = /^data:([^,]*),(.*)$/is.exec(url)
210
+ if (!found) throw fail(400, "reference image data: URL is malformed")
211
+ let bytes
212
+ try {
213
+ bytes = /;base64(?:;|$)/i.test(found[1]) ? Buffer.from(found[2], "base64") : Buffer.from(decodeURIComponent(found[2]))
214
+ } catch { throw fail(400, "reference image data: URL is malformed") }
215
+ return imageBytes(bytes, found[1])
216
+ }
217
+
218
+ function referenceOf(value, role) {
219
+ if (Buffer.isBuffer(value?.bytes)) return { bytes: value.bytes, mime: value.mime, role }
220
+ if (typeof value === "string") return { source: value.trim(), role }
221
+ const item = record(value)
222
+ const url = typeof item.image_url === "string" ? item.image_url : item.image_url?.url
223
+ return { source: text(item.asset_id ?? item.assetId ?? item.url ?? url), role: text(item.role) || role }
224
+ }
225
+
226
+ function allReferences(body) {
227
+ const out = []
228
+ const first = body.input_reference ?? body.input_image
229
+ if (given(first)) out.push(referenceOf(first, "first_frame"))
230
+ const refs = body.reference_images ?? body.images
231
+ if (given(refs) && !Array.isArray(refs)) throw fail(400, "reference_images must be an array")
232
+ for (const value of Array.isArray(refs) ? refs : []) out.push(referenceOf(value, "reference"))
233
+ for (const key of ["last_frame", "last_frame_image"]) if (given(body[key])) out.push(referenceOf(body[key], "last_frame"))
234
+ return out
235
+ }
236
+
237
+ function checkRole(ref) {
238
+ if (ref.role === "last_frame") throw fail(400, "Open Design video generation does not support a last_frame image")
239
+ if (!ROLES.has(ref.role)) throw fail(400, "reference image role must be first_frame or reference")
240
+ }
241
+
242
+ function checkCounts(model, spec, refs) {
243
+ if (refs.filter((ref) => ref.role === "first_frame").length > 1) throw fail(400, "a video takes at most one first_frame image")
244
+ const max = spec?.images ?? MAX_IMAGES
245
+ if (refs.length > max) throw fail(400, `${model} accepts at most ${max} reference image${max === 1 ? "" : "s"}`)
246
+ if (spec?.images === 1 && refs.some((ref) => ref.role !== "first_frame")) throw fail(400, `${model} accepts only a first_frame image (input_reference)`)
247
+ }
248
+
249
+ // checkSource never fetches an image URL: a request could name an address on
250
+ // this computer's own network, and its answer would be uploaded to Open Design.
251
+ function checkSource(ref) {
252
+ if (ref.bytes) return { role: ref.role, ...imageBytes(ref.bytes, ref.mime) }
253
+ const source = ref.source
254
+ if (/^https?:\/\//i.test(source)) throw fail(400, "reference image URLs are not downloaded; send the image as a data: URL or an uploaded file")
255
+ if (/^data:/i.test(source)) return { role: ref.role, ...dataImage(source) }
256
+ if (!source || /^[a-z][a-z0-9+.-]*:/i.test(source) || /[\\/\s]/.test(source) || /^\.+$/.test(source)) throw fail(400, NOT_AN_IMAGE)
257
+ return { role: ref.role, asset: source }
258
+ }
259
+
260
+ async function assetOf(ref, send) {
261
+ if (ref.asset) return ref.asset
262
+ return uploadBytes(ref.bytes, ref.mime, send)
263
+ }
264
+
265
+ async function uploadBytes(bytes, mime, send) {
266
+ const created = await send("POST", "/uploads", { body: { mime_type: mime, size_bytes: bytes.length }, label: "reference image upload" })
267
+ if (!created.ok) throw await upstreamError(created, "reference image upload")
268
+ const body = await responseJSON(created)
269
+ const id = text(body?.asset_id ?? body?.assetId ?? body?.id ?? body?.data?.asset_id)
270
+ const target = text(body?.upload_url ?? body?.uploadUrl ?? body?.data?.upload_url)
271
+ if (!id || !/^https:\/\//i.test(target)) throw fail(502, "Open Design upload returned no HTTPS upload_url and asset_id")
272
+ const put = await send("PUT", target, { body: bytes, contentType: mime, label: "reference image bytes upload", accept: "*/*" })
273
+ if (!put.ok) throw fail(502, `Open Design reference image bytes upload: HTTP ${put.status}`)
274
+ const committed = await send("POST", `/uploads/${encodeURIComponent(id)}/commit`, { body: {}, label: "reference image commit" })
275
+ if (!committed.ok) throw await upstreamError(committed, "reference image commit")
276
+ return id
277
+ }
278
+
279
+ // ---- request bodies ----------------------------------------------------------------
280
+
281
+ async function formInput(form) {
282
+ const out = {}
283
+ for (const [name, value] of form.entries()) {
284
+ const field = name.replace(/\[\]$/, "")
285
+ const item = typeof value === "string" ? value : { bytes: Buffer.from(await value.arrayBuffer()), mime: value.type }
286
+ if (field === "reference_images" || field === "images") (out[field] ??= []).push(item)
287
+ else out[field] ??= item
288
+ }
289
+ return out
290
+ }
291
+
292
+ async function videoInput(body, headers) {
293
+ if (typeof FormData !== "undefined" && body instanceof FormData) return formInput(body)
294
+ const type = new Headers(headers ?? undefined).get("content-type") ?? ""
295
+ if (/^multipart\/form-data/i.test(type)) {
296
+ let form
297
+ try { form = await new Response(body, { headers: { "content-type": type } }).formData() }
298
+ catch { throw fail(400, "request body must be multipart form data") }
299
+ return formInput(form)
300
+ }
301
+ const raw = given(body) && typeof body !== "string" ? await new Response(body).text() : body
302
+ let parsed = null
303
+ try { parsed = JSON.parse(given(raw) ? raw : "{}") } catch {}
304
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw fail(400, "request body must be a JSON object")
305
+ return parsed
306
+ }
307
+
308
+ // ---- upstream ------------------------------------------------------------------------
309
+
310
+ // transport sends the account's key to amr-link alone: a presigned upload URL
311
+ // and a redirected download never see it.
312
+ function transport({ key, fetch, signal }) {
313
+ return async (verb, target, { body, contentType, label, idempotencyKey, accept = "application/json", redirect = "follow" } = {}) => {
314
+ const url = /^https:\/\//i.test(target) ? target : MEDIA + target
315
+ const headers = { accept }
316
+ if (new URL(url).origin === ORIGIN) headers.authorization = `Bearer ${key}`
317
+ let data = body
318
+ if (body !== undefined && !(body instanceof Uint8Array)) {
319
+ headers["content-type"] = "application/json"
320
+ data = JSON.stringify(body)
321
+ } else if (contentType) headers["content-type"] = contentType
322
+ if (idempotencyKey) headers["Idempotency-Key"] = idempotencyKey
323
+ try {
324
+ return await fetch(url, { method: verb, headers, body: data, signal, redirect })
325
+ } catch (error) {
326
+ if (signal?.aborted) throw error
327
+ throw fail(502, `Open Design ${label}: ${error?.message ?? error}`, { network: true })
328
+ }
329
+ }
330
+ }
331
+
332
+ async function responseJSON(res) {
333
+ try { return await res.json() } catch { return null }
334
+ }
335
+
336
+ async function discard(res) {
337
+ try { await res.body?.cancel() } catch {}
338
+ }
339
+
340
+ // issuesOf is what Open Design's validation names, field by field:
341
+ // {"error":"invalid_request","issues":[{"path":"model","message":"unknown or unavailable model"}]}
342
+ function issuesOf(body) {
343
+ const list = Array.isArray(body?.issues) ? body.issues : Array.isArray(body?.error?.issues) ? body.error.issues : []
344
+ return list.map((issue) => {
345
+ const path = Array.isArray(issue?.path) ? issue.path.join(".") : text(issue?.path)
346
+ const message = text(issue?.message)
347
+ return message && path ? `${path}: ${message}` : message
348
+ }).filter(Boolean)
349
+ }
350
+
351
+ async function upstreamError(res, label) {
352
+ const raw = await res.text().catch(() => "")
353
+ let body = null
354
+ try { body = raw ? JSON.parse(raw) : null } catch {}
355
+ const said = body
356
+ ? [body.error?.message, body.message, body.error, body.error?.code, body.code].find((value) => typeof value === "string" && value.trim())
357
+ : raw
358
+ const plain = typeof said === "string" && !said.trim().startsWith("<") ? said.trim() : ""
359
+ const issues = issuesOf(body)
360
+ const words = [plain, issues.length ? `(${issues.join("; ")})` : ""].filter(Boolean).join(" ").slice(0, 300)
361
+ const status = res.status >= 400 && res.status < 500 ? res.status : 502
362
+ return fail(status, `Open Design ${label}: HTTP ${res.status}${words ? `: ${words}` : ""}`, res.status === 401 ? { signIn: "expired" } : {})
363
+ }
364
+
365
+ // A submission that fails on the network or at a gateway is sent again with
366
+ // the same key and body, so Open Design starts at most one paid task for it.
367
+ async function submitTask(payload, send, idempotencyKey, { retryDelay, signal }) {
368
+ for (let attempt = 1; ; attempt++) {
369
+ let res
370
+ try {
371
+ res = await send("POST", "/videos/tasks", { body: payload, label: "video task submission", idempotencyKey })
372
+ } catch (error) {
373
+ if (!error?.network || attempt >= SUBMIT_ATTEMPTS) throw error
374
+ await sleep(retryDelay * attempt, signal)
375
+ continue
376
+ }
377
+ if (!RETRY_STATUSES.has(res.status) || attempt >= SUBMIT_ATTEMPTS) return res
378
+ await discard(res)
379
+ await sleep(retryDelay * attempt, signal)
380
+ }
381
+ }
382
+
383
+ // The content route answers with the MP4 or a redirect to storage; each hop
384
+ // is followed here so the key stays on amr-link.
385
+ async function downloadVideo(path, send) {
386
+ let target = MEDIA + path
387
+ for (let hop = 0; ; hop++) {
388
+ const res = await send("GET", target, { label: "video content download", accept: "video/mp4, */*", redirect: "manual" })
389
+ const location = REDIRECT_STATUSES.has(res.status) ? res.headers.get("location") : null
390
+ if (!location) return { res, target }
391
+ await discard(res)
392
+ if (hop >= MAX_REDIRECTS) throw fail(502, "Open Design video content download redirected too many times")
393
+ const next = new URL(location, target)
394
+ if (next.protocol !== "https:") throw fail(502, "Open Design video content download redirected away from HTTPS")
395
+ target = next.href
396
+ }
397
+ }
398
+
399
+ // ---- tasks -----------------------------------------------------------------------------
400
+
401
+ function taskId(body) {
402
+ return text(body?.task_id ?? body?.taskId ?? body?.id ?? body?.data?.task_id ?? body?.data?.id)
403
+ }
404
+
405
+ function statusOf(body) {
406
+ const upstream = text(body.status ?? body.task_status ?? body.state).toLowerCase()
407
+ const progress = Math.max(0, Math.min(100, Number(body.progress) || 0))
408
+ if (["succeeded", "success", "completed", "done"].includes(upstream)) return { status: "completed", progress: 100, upstream }
409
+ if (["failed", "error", "cancelled", "canceled", "expired"].includes(upstream)) return { status: "failed", progress, upstream }
410
+ if (["running", "processing", "in_progress", "generating"].includes(upstream)) return { status: "in_progress", progress, upstream }
411
+ return { status: "queued", progress, upstream }
412
+ }
413
+
414
+ function failure(body, current) {
415
+ const error = body.error
416
+ const plain = typeof error === "string" ? text(error) : ""
417
+ return {
418
+ code: text(error?.code ?? body.error_code ?? body.code) || plain || current.upstream || "failed",
419
+ message: text(error?.message ?? body.message ?? body.error_message ?? body.failure_reason) || plain || `Open Design video generation ${current.upstream || "failed"}`,
420
+ }
421
+ }
422
+
423
+ function timestamp(value) {
424
+ const number = Number(value)
425
+ if (given(value) && Number.isFinite(number) && number > 0) return Math.floor(number > 1e12 ? number / 1000 : number)
426
+ const parsed = Date.parse(String(value ?? ""))
427
+ return Number.isFinite(parsed) ? Math.floor(parsed / 1000) : Math.floor(Date.now() / 1000)
428
+ }
429
+
430
+ function encodeId(model, task) {
431
+ return `${model}::${task}`
432
+ }
433
+
434
+ function decodeId(id) {
435
+ const value = String(id)
436
+ const at = value.indexOf("::")
437
+ const model = at > 0 ? value.slice(0, at) : ""
438
+ const task = at > 0 ? value.slice(at + 2) : ""
439
+ if (!model || !task || /^\.+$/.test(task)) throw fail(404, "not an Open Design video id")
440
+ return { model, task }
441
+ }
442
+
443
+ // planVideo checks everything a request says before anything is uploaded or
444
+ // paid for, and gives the task body without its images.
445
+ function planVideo(body) {
446
+ const model = text(body.model)
447
+ if (!model) throw fail(400, "model is required")
448
+ const prompt = text(body.prompt)
449
+ if (!prompt) throw fail(400, "prompt is required")
450
+ const spec = VIDEO_MODELS[model]
451
+ const payload = { model, prompt }
452
+ const seconds = duration(body, model, spec)
453
+ if (seconds !== undefined) payload.duration = seconds
454
+ const sized = sizeOf(body.size)
455
+ const ratio = text(body.ratio)
456
+ ? choice(ratioOf(body.ratio), spec?.ratios, "video ratio")
457
+ : sized.ratio && spec ? nearestRatio(sized, spec.ratios) : sized.ratio
458
+ if (ratio) payload.ratio = ratio
459
+ const resolution = choice(text(body.resolution) || sized.resolution, spec?.resolutions, "video resolution")
460
+ if (resolution) payload.resolution = resolution
461
+ if (given(body.generate_audio)) {
462
+ const audio = flag(body.generate_audio, "generate_audio")
463
+ if (model === "magi-2" && !audio) throw fail(400, "MAGI-2 always generates native synchronized audio; generate_audio:false is not supported")
464
+ if (model !== "magi-2") payload.generate_audio = audio
465
+ }
466
+ const refs = allReferences(body)
467
+ for (const ref of refs) checkRole(ref)
468
+ checkCounts(model, spec, refs)
469
+ return { model, payload, references: refs.map(checkSource) }
470
+ }
471
+
472
+ async function createVideo(body, send, idempotencyKey, options) {
473
+ const { model, payload, references } = planVideo(body)
474
+ if (references.length) {
475
+ payload.images = []
476
+ for (const ref of references) payload.images.push({ asset_id: await assetOf(ref, send), role: ref.role })
477
+ }
478
+ const res = await submitTask(payload, send, idempotencyKey, options)
479
+ if (!res.ok) throw await upstreamError(res, "video task submission")
480
+ const task = taskId(await responseJSON(res))
481
+ if (!task) throw fail(502, "Open Design video task submission returned no task_id")
482
+ return json({
483
+ id: encodeId(model, task),
484
+ object: "video",
485
+ created_at: Math.floor(Date.now() / 1000),
486
+ status: "queued",
487
+ progress: 0,
488
+ model,
489
+ ...(payload.duration !== undefined ? { seconds: String(payload.duration) } : {}),
490
+ })
491
+ }
492
+
493
+ async function readVideo(id, send, content) {
494
+ const { model, task } = decodeId(id)
495
+ const path = `/videos/tasks/${encodeURIComponent(task)}`
496
+ const res = await send("GET", path, { label: "video task query" })
497
+ if (!res.ok) throw await upstreamError(res, "video task query")
498
+ let body = record(await responseJSON(res))
499
+ if (!given(body.status) && record(body.data).status) body = record(body.data)
500
+ const current = statusOf(body)
501
+ if (!content) {
502
+ const out = { id, object: "video", created_at: timestamp(body.created_at ?? body.createdAt), status: current.status, progress: current.progress, model: text(body.model) || model }
503
+ const seconds = body.duration ?? body.seconds
504
+ if (given(seconds)) out.seconds = String(seconds)
505
+ if (current.status === "failed") out.error = failure(body, current)
506
+ return json(out)
507
+ }
508
+ if (current.status === "failed") throw fail(502, failure(body, current).message)
509
+ if (current.status !== "completed") throw fail(409, `Open Design video is ${current.status}; its content is not ready yet`)
510
+ const { res: download, target } = await downloadVideo(`${path}/content`, send)
511
+ if (!download.ok) {
512
+ if (new URL(target).origin === ORIGIN) throw await upstreamError(download, "video content download")
513
+ throw fail(502, `Open Design video content download: HTTP ${download.status}`)
514
+ }
515
+ const headers = new Headers({ "content-type": download.headers.get("content-type") || "video/mp4" })
516
+ const length = download.headers.get("content-length")
517
+ if (length && !download.headers.has("content-encoding")) headers.set("content-length", length)
518
+ const disposition = download.headers.get("content-disposition")
519
+ if (disposition) headers.set("content-disposition", disposition)
520
+ return new Response(download.body, { status: 200, headers })
521
+ }
522
+
523
+ // handleVideoFetch answers magpie's OpenAI-shaped videos API (POST /videos,
524
+ // GET /videos/{id}, GET /videos/{id}/content) from Open Design's media task
525
+ // API, or returns null for any other request.
526
+ export async function handleVideoFetch(url, { method = "GET", body, headers, signal } = {}, { key, fetch = globalThis.fetch, idempotencyKey = randomUUID(), retryDelay = 1000 } = {}) {
527
+ const route = videoPath(url)
528
+ if (!route) return null
529
+ if (signal?.aborted) throw abortReason(signal)
530
+ const send = transport({ key, fetch, signal })
531
+ const verb = String(method).toUpperCase()
532
+ try {
533
+ if (route.kind === "create") {
534
+ if (verb !== "POST") return errorJSON(405, "use POST to start a video")
535
+ return await createVideo(await videoInput(body, headers), send, idempotencyKey, { retryDelay, signal })
536
+ }
537
+ if (verb !== "GET") return errorJSON(405, "use GET to read a video")
538
+ return await readVideo(route.id, send, route.kind === "content")
539
+ } catch (error) {
540
+ if (signal?.aborted) throw error
541
+ return errorJSON(Number.isInteger(error?.status) ? error.status : 502, String(error?.message ?? error), error?.signIn)
542
+ }
543
+ }
544
+
545
+ export const _videoInternal = { allReferences, dataImage, decodeId, duration, encodeId, nearestRatio, planVideo, sizeOf, statusOf }