@magpie-community/opencode-opendesign-auth 0.1.15 → 0.1.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +67 -2
- package/index.mjs +36 -6
- package/package.json +4 -2
- package/video.mjs +545 -0
package/README.md
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
Open Design (open-design.ai) Cloud as a magpie / OpenCode provider: sign in
|
|
4
4
|
with the Open Design account, use the models its **Design Plan** entitles the
|
|
5
|
-
account to,
|
|
5
|
+
account to, generate videos with **Seedance 2.5 / 2.5 Flash / 2.0, Wan 2.7
|
|
6
|
+
and MAGI-2**, and watch the plan's **5-hour and 7-day allowance** and wallet
|
|
6
7
|
balance where every other subscription's usage shows.
|
|
7
8
|
|
|
8
9
|
Works in [magpie](https://usemagpie.ai) (which runs OpenCode provider plugins)
|
|
@@ -29,6 +30,7 @@ Open Design's cloud is two planes:
|
|
|
29
30
|
| --- | --- | --- | --- |
|
|
30
31
|
| Control | `amr-api.open-design.ai` | `vela_ctrl_…` | plan, wallet balance, the Design Plan's allowance windows, the workspace |
|
|
31
32
|
| Model | `amr-link.open-design.ai/v1` | `sk-amr-…` | `/models`, `/chat/completions`, `/responses`, `/messages` |
|
|
33
|
+
| Media | `amr-link.open-design.ai/api/v1/media` | `sk-amr-…` | `/models`, `/videos/tasks`, reference-image uploads |
|
|
32
34
|
|
|
33
35
|
A sign-in is the same device authorization the Open Design CLI
|
|
34
36
|
(`vela login`) runs:
|
|
@@ -100,6 +102,69 @@ doesn't name yet; they disagree with the plan for most models (Claude Haiku
|
|
|
100
102
|
Flash's 0.25× "限时谷价" row is a time-limited promotional price, not a
|
|
101
103
|
second model id, so the model keeps 0.5×.
|
|
102
104
|
|
|
105
|
+
### Video generation
|
|
106
|
+
|
|
107
|
+
The five video models appear in magpie's video settings and use its native
|
|
108
|
+
video API. They are video-only models, not additional chat models. Before
|
|
109
|
+
sign-in, or if the media catalog is temporarily unavailable, these models
|
|
110
|
+
are available:
|
|
111
|
+
|
|
112
|
+
| Model | ID | Duration | Resolution |
|
|
113
|
+
| --- | --- | --- | --- |
|
|
114
|
+
| Seedance 2.5 | `doubao-seedance-2-5-260628` | 4–30 s | 480p / 720p / 1080p |
|
|
115
|
+
| Seedance 2.5 Flash | `doubao-seedance-2-5-flash-261115` | 4–30 s | 480p / 720p |
|
|
116
|
+
| Seedance 2.0 | `doubao-seedance-2-0-260128` | 4–30 s | 480p / 720p / 1080p / 4K |
|
|
117
|
+
| Wan 2.7 | `wan-2.7` | 2–15 s | 720p / 1080p |
|
|
118
|
+
| MAGI-2 | `magi-2` | 4–5 s | 1080p, with native synchronized audio |
|
|
119
|
+
|
|
120
|
+
After sign-in, `GET /api/v1/media/models` selects the video models the
|
|
121
|
+
account's workspace offers; image and audio rows are not added. The task API
|
|
122
|
+
takes only the models that catalog lists: it answers any other with
|
|
123
|
+
`unknown or unavailable model`, so a model the public models page shows but
|
|
124
|
+
the account's catalog leaves out is not offered, and it appears once the
|
|
125
|
+
catalog lists it. The ordinary
|
|
126
|
+
chat catalog remains independent: a media catalog that refuses the key
|
|
127
|
+
(401/403) leaves the account no video models, one that can't be read keeps
|
|
128
|
+
the five above, and neither changes the chat models. `refresh-models.mjs`
|
|
129
|
+
still refreshes only the chat seed in `models.mjs`.
|
|
130
|
+
|
|
131
|
+
amr-link's chat catalog (`/v1/models`) also lists video models, with
|
|
132
|
+
`output_modalities: ["video"]`. Those are served as video models only, never
|
|
133
|
+
as chat models that take tools.
|
|
134
|
+
|
|
135
|
+
Magpie's OpenAI-shaped `POST /v1/videos`, `GET /v1/videos/{id}` and
|
|
136
|
+
`GET /v1/videos/{id}/content` are translated to Open Design's unified media
|
|
137
|
+
task API, from a JSON or multipart body. `seconds`/`duration`, `size`,
|
|
138
|
+
`ratio` and `resolution` are mapped to its task fields. For the five models
|
|
139
|
+
above, an explicit `ratio`, `resolution` or duration must be one the model
|
|
140
|
+
offers, while a `size` such as `1024x1792` picks the closest ratio it
|
|
141
|
+
offers. `input_reference` supplies a first frame; `reference_images`
|
|
142
|
+
supplies additional references. An image uploaded in magpie arrives as a
|
|
143
|
+
data URL, and a multipart body can carry one as a file. The plugin uploads
|
|
144
|
+
the image with `POST /uploads`, a PUT of the bytes and `/commit` before the
|
|
145
|
+
task is submitted. An image URL (`http://` or `https://`) gets a 400 and is
|
|
146
|
+
never downloaded, so a request can't have this computer fetch an address
|
|
147
|
+
on its network and upload what it answers. That includes a URL a client
|
|
148
|
+
sends through magpie: upload the image instead. A caller that uses the
|
|
149
|
+
plugin directly, not through magpie, can also pass the id of an asset it
|
|
150
|
+
has already committed. Seedance and Wan accept one first frame; MAGI-2
|
|
151
|
+
accepts up to five references. MAGI-2 always produces audio, so
|
|
152
|
+
`generate_audio:false` is refused. Every check runs before an image is
|
|
153
|
+
uploaded or a paid task is created.
|
|
154
|
+
|
|
155
|
+
Every new task gets its own idempotency key, or the `Idempotency-Key` the
|
|
156
|
+
request carries. A submission that fails on the network or with 502, 503
|
|
157
|
+
or 504 is sent at most three times, with the same key and body, so Open
|
|
158
|
+
Design starts one task for it; polling and downloading never submit
|
|
159
|
+
another. Open Design's 4xx answers reach magpie as they are (a 401 also
|
|
160
|
+
marks the sign-in expired), with the fields its validation rejected; its
|
|
161
|
+
5xx answers become 502. The returned video
|
|
162
|
+
id keeps both the model and task id, so status and MP4 content can be read
|
|
163
|
+
later without maintaining local state.
|
|
164
|
+
|
|
165
|
+
The account's key goes to `amr-link.open-design.ai` only: the presigned
|
|
166
|
+
upload URL and a download redirected to storage never receive it.
|
|
167
|
+
|
|
103
168
|
`models.mjs` is the seed the provider has *before* anyone signs in. Refresh
|
|
104
169
|
it from the live catalog with:
|
|
105
170
|
|
|
@@ -157,7 +222,7 @@ renew and `refresh` is empty.
|
|
|
157
222
|
## Use
|
|
158
223
|
|
|
159
224
|
```
|
|
160
|
-
magpie plugin # opendesign (Open Design,
|
|
225
|
+
magpie plugin # opendesign (Open Design, chat + video) signed in
|
|
161
226
|
magpie provider test opendesign
|
|
162
227
|
magpie quota # opendesign · Design Plan Go · 5h 32% ↻3h
|
|
163
228
|
```
|
package/index.mjs
CHANGED
|
@@ -19,10 +19,12 @@ import pkg from "./package.json" with { type: "json" }
|
|
|
19
19
|
|
|
20
20
|
import { MODELS } from "./models.mjs"
|
|
21
21
|
import { RATES } from "./rates.mjs"
|
|
22
|
+
import { handleVideoFetch, videoConfigModels, videoModels, videoPath, withFallbackVideos } from "./video.mjs"
|
|
22
23
|
|
|
23
24
|
const ID = "opendesign"
|
|
24
25
|
const CONTROL = "https://amr-api.open-design.ai"
|
|
25
26
|
const LINK = "https://amr-link.open-design.ai/v1"
|
|
27
|
+
const MEDIA = "https://amr-link.open-design.ai/api/v1/media"
|
|
26
28
|
// WHICH API each model is asked on: magpie reads the protocol off the AI SDK
|
|
27
29
|
// package a model declares (its api.npm) — "@ai-sdk/openai" is the Responses
|
|
28
30
|
// API, "@ai-sdk/anthropic" Anthropic's messages, the compatible package chat
|
|
@@ -60,7 +62,21 @@ const alsoOf = (id) => Object.values(WIRE).filter((w) => w !== wireOf(id))
|
|
|
60
62
|
// with an x-api-key. signFor reads the API off the request's path.
|
|
61
63
|
const MESSAGES = /\/messages(\/count_tokens)?\/?$/
|
|
62
64
|
const signFor = (key) => async (input, init = {}) => {
|
|
63
|
-
const
|
|
65
|
+
const req = input instanceof Request ? input : null
|
|
66
|
+
const url = req ? req.url : String(input)
|
|
67
|
+
if (videoPath(url)) {
|
|
68
|
+
const signal = init.signal ?? req?.signal
|
|
69
|
+
if (signal?.aborted) throw signal.reason ?? new Error("The operation was aborted")
|
|
70
|
+
let body = init.body
|
|
71
|
+
if (body === undefined && req && req.method !== "GET" && req.method !== "HEAD") body = Buffer.from(await req.clone().arrayBuffer())
|
|
72
|
+
const media = await handleVideoFetch(url, {
|
|
73
|
+
method: init.method ?? req?.method ?? "GET",
|
|
74
|
+
body,
|
|
75
|
+
headers: init.headers ?? req?.headers,
|
|
76
|
+
signal,
|
|
77
|
+
}, { key, idempotencyKey: new Headers(init.headers ?? req?.headers).get("idempotency-key") ?? undefined })
|
|
78
|
+
if (media) return media
|
|
79
|
+
}
|
|
64
80
|
const h = new Headers(init.headers ?? (input instanceof Request ? input.headers : undefined))
|
|
65
81
|
let path = ""
|
|
66
82
|
try {
|
|
@@ -603,8 +619,14 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
603
619
|
// a kept copy's: magpie hands back what the hook last wrote, and a model
|
|
604
620
|
// kept from an earlier version would otherwise stay on the Responses API
|
|
605
621
|
// it chose for every model, or on a rate the plan no longer charges
|
|
606
|
-
const
|
|
622
|
+
const videos = videoConfigModels()
|
|
623
|
+
const models = { ...seed(), ...videos, ...(was.models ?? {}) }
|
|
607
624
|
for (const [id, m] of Object.entries(models)) {
|
|
625
|
+
if (videos[id]) {
|
|
626
|
+
models[id] = { ...videos[id], ...m, id, tool_call: false, reasoning: false, variants: {}, modalities: { input: ["text", "image"], output: ["video"] }, limit: { context: 0, output: 0 } }
|
|
627
|
+
delete models[id].also
|
|
628
|
+
continue
|
|
629
|
+
}
|
|
608
630
|
const rate = RATES[id] === undefined ? undefined : "x" + RATES[id]
|
|
609
631
|
// a kept copy's limit is capped too: an earlier version wrote the
|
|
610
632
|
// catalog's 232000 for glm-5.3-flash, which amr-link refuses (CAP)
|
|
@@ -627,13 +649,21 @@ export const OpenDesignAuthPlugin = async () => {
|
|
|
627
649
|
async models(provider, { auth } = {}) {
|
|
628
650
|
const key = runtimeKeyOf(auth)
|
|
629
651
|
if (!key) return provider.models
|
|
630
|
-
const r = await
|
|
652
|
+
const [r, media] = await Promise.all([
|
|
653
|
+
api(LINK, "/models", { key }),
|
|
654
|
+
api(MEDIA, "/models", { key }).catch(() => ({ ok: false, status: 0, body: null })),
|
|
655
|
+
])
|
|
631
656
|
if (r.status === 401 || r.status === 403) {
|
|
632
657
|
throw Object.assign(new Error(`Open Design refused the account's key (${said(r.body, "unauthorized")}) — sign in again`), { signIn: "expired" })
|
|
633
658
|
}
|
|
634
|
-
|
|
635
|
-
const
|
|
636
|
-
|
|
659
|
+
const listed = r.ok ? videoModels(r.body) : {}
|
|
660
|
+
const videos = media.ok ? videoModels(media.body)
|
|
661
|
+
: media.status === 401 || media.status === 403 ? {}
|
|
662
|
+
: withFallbackVideos(listed)
|
|
663
|
+
const previous = Object.fromEntries(Object.entries(provider.models ?? {}).filter(([, model]) => !model.capabilities?.output?.video && !model.modalities?.output?.includes("video")))
|
|
664
|
+
if (!r.ok) return { ...previous, ...videos } // magpie keeps the chat list it had
|
|
665
|
+
const models = Object.fromEntries(Object.entries(modelsOf(r.body)).filter(([id]) => !listed[id]))
|
|
666
|
+
return Object.keys(models).length ? { ...models, ...videos } : { ...previous, ...videos }
|
|
637
667
|
},
|
|
638
668
|
},
|
|
639
669
|
auth: {
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@magpie-community/opencode-opendesign-auth",
|
|
3
|
-
"version": "0.1.
|
|
4
|
-
"description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in,
|
|
3
|
+
"version": "0.1.16",
|
|
4
|
+
"description": "Open Design Cloud (Design Plan) in OpenCode and magpie: the account's device sign-in, chat and native video models, and the plan's 5-hour and 7-day allowance",
|
|
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,6 +27,7 @@
|
|
|
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
|
},
|
|
31
33
|
"exports": { ".": "./opencode2.mjs" }
|
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 }
|