mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-05 23:02:10 +03:00
* chore(release): open v3.8.38 development cycle
* fix(executors): strip client_metadata for cerebras and mistral (#4727)
Integrated into release/v3.8.38 (leva 5)
* fix(codebuddy): only send reasoning params when client requests reasoning (#5019)
Integrated into release/v3.8.38 (leva 5)
* fix(sse): keep streaming for forceStream providers when client requests JSON (#5021)
Integrated into release/v3.8.38 (leva 5)
* fix(sse): guard non-JSON SSE lines and duplicate [DONE] (#4937)
Integrated into release/v3.8.38 (leva 5)
* feat(blackbox): refresh provider model catalog (#4935)
Integrated into release/v3.8.38 (leva 5)
* fix(sse): dedupe case-variant Anthropic version/beta headers (#4846)
Integrated into release/v3.8.38 (leva 5)
* feat(sse): Kiro inline <thinking> stream splitter (#4911)
Integrated into release/v3.8.38 (leva 5)
* feat(cursor): parse Composer DeepSeek-style inline tool calls (#4912)
Integrated into release/v3.8.38 (leva 5)
* feat(proxy): auth-less host:port batch import (#4938)
Integrated into release/v3.8.38 (leva 5)
* fix(oauth): support Kiro IDC (organization) token import (#4944)
Integrated into release/v3.8.38 (leva 5)
* fix(translator): preserve cache_control for DashScope OpenAI-compat providers (port from 9router#2069) (#5013)
Integrated into release/v3.8.38 (leva 5)
* fix(tts): resolve Gemini TTS models from catalog (#4934)
Integrated into release/v3.8.38 (leva 5)
* fix(sse): don't cool down the connection on a self-inflicted upstream timeout (504) (#5064)
Integrated into release/v3.8.38 (leva 5)
* fix(sse): robust Anthropic /v1/messages streaming — real ping keepalive + client-disconnect guard (#5063)
Integrated into release/v3.8.38 (leva 5)
* feat(video): add Alibaba DashScope (wan2.7-t2v) provider (#5051)
Integrated into release/v3.8.38 (leva 5)
* fix: preserve model hidden flags (isHidden) across model sync (#5086)
Integrated into release/v3.8.38 (leva 5)
* fix(models): derive model discovery config from registry modelsUrl (#5087)
Integrated into release/v3.8.38 (leva 5)
* fix(compression): replace fileURLToPath(import.meta.url) with runtime anchors for standalone bundle (#5089)
Integrated into release/v3.8.38 (leva 5)
* feat(cc): add summarized thinking display toggle (#5055)
Integrated into release/v3.8.38 (leva 5)
* Harden selected API error responses (#5032)
Integrated into release/v3.8.38 (leva 5)
* chore(quality): rebaseline file-size for leva 5 PR batch drift
6 frozen files grew from merged leva-5 PRs (cursor #4912, kiro #4911,
videoGeneration #5051, default #4727, base #4846, chat #5064); all covered
by per-PR tests. See _rebaseline_2026_06_26_leva5 in the baseline.
* feat(compression): compression playground (Play + Compare tabs) in the studio (#5080)
Integrated into release/v3.8.38
* fix(combo): fail over on empty-content 502 instead of exhausting the provider (#5085) (#5104)
* fix(dashboard): surface detailed credential-validation error in add-connection modal (#5088) (#5106)
* feat(providers): allow local/private provider URLs by default with scoped metadata-safe guard (#5066) (#5107)
* fix(diagnostics): treat non-streaming Claude messages shape as valid output (#5108) (#5116)
* fix(db): translate pt-BR SQLite driver-fallback log lines to English (#5103) (#5115)
* fix(sse): repair release base-reds — malformed-response false positives + header casing + stale tests (#5117)
Repairs the release/v3.8.38 base-reds; unblocks #5078.
* chore(quality): rebaseline file-size for responseSanitizer (#5117) + AddApiKeyModal drift
* fix(translator): forward image tool_result blocks as image_url (#5100)
Base-reds fixed (#5117); image tool_result→image_url. Integrated into release/v3.8.38.
* fix(responses): default text.format for openai-compatible responses providers (#5101)
Base-reds fixed (#5117); default text.format + file-size rebaseline. Integrated into release/v3.8.38.
* feat(dashboard): expose Fusion judgeModel + fusionTuning in the combo editor (#5074)
Base-reds fixed (#5117); Fusion editor + file-size rebaseline. Integrated into release/v3.8.38.
* feat(quota): add opt-in Codex/Claude auto-ping keepalive (#5102)
Base-reds fixed (#5117); auto-ping keepalive + file-size rebaseline. Integrated into release/v3.8.38.
* test(release): relocate 2 orphan test files into the collected flat tests/unit dir (#5120)
Unblocks Lint (test-discovery) on #5078. Integrated into release/v3.8.38.
* fix(translator): preserve reasoning-replay reasoning_content + repair 3 release-green test reds (#5122)
Repairs 3 release-green test reds + test-masking; unblocks #5078.
* test(golden): redact live Node version from provider translate-path snapshot (#5125)
Final golden unblock for #5078.
* test(golden): redact OmniRoute app version from translate-path snapshot (#5126)
Coverage shard golden unblock for #5078.
* Ignore disconnect races during in-band stream error handling (#5007)
Integrated into release/v3.8.38
* Track final connection IDs in failover logs (#5016)
Integrated into release/v3.8.38
* fix(sse): convert Gemini body to OpenAI format in antigravity MITM handler (#4845)
Integrated into release/v3.8.38 (rebased on tip, CHANGELOG re-injected)
* feat(providers): add ZenMux Free session-cookie provider (#5105)
Integrated into release/v3.8.38 (rebased on tip, CHANGELOG re-injected)
* feat(dashboard): click-to-edit model alias in provider page (#5119)
Integrated into release/v3.8.38 (rebased on tip, i18n scope verified, CHANGELOG re-injected)
* feat(mcp): web-session robustness — cookie dedup (PR6) + browser-pool observability (PR7) (#3368) (#5121)
Integrated into release/v3.8.38 (rebased on tip; cookie-dedup branch extracted to findExistingCookieConnection helper → complexity-neutral; CHANGELOG added)
* fix(usage): dedupe request-usage logging and debounce stats (#4940)
Integrated into release/v3.8.38 (rebased on tip; DB-handle hang was stale-base artifact — resetDbInstance already closes the handle, test green 5/5; file-size drift consolidated at release; CHANGELOG re-injected)
* fix(dashboard): key model visibility toggle on canonical providerId (#5091)
Integrated into release/v3.8.38 (retargeted main→release; .tsx visibility-key test green 2/2)
* chore(deps): bump actions/cache from 5.0.5 to 6.0.0 (#5112)
Integrated into release/v3.8.38 (retargeted main→release; workflow-only actions/cache bump — unit failures were stale main base-reds)
* fix(streaming): harden long OpenAI-compatible SSE streams (#5124)
Integrated into release/v3.8.38 (rebased on tip; streamHandler conflict with #5007 disconnect-guard resolved — both coexist, stream-handler 22/22 green)
* feat: Add Grok Build (xAI) provider with OAuth import-token flow (#5020)
Integrated into release/v3.8.38 (rebased on tip; Hard Rule #11 fix — Grok public client_id now via resolvePublicCred(grok_id), 3 literals removed; grok-oauth 7/7 + check:public-creds green)
* feat(providers): add Factory (factory.ai) as a subscription gateway provider (#5065)
Integrated into release/v3.8.38 (rebased on tip; added factory registry test for PR Test Policy + fixed check:env-doc-sync phantom FACTORY_API_KEY; factory loads in PROVIDERS, no Zod issue — that flag was a false positive)
* chore(test): reconcile golden snapshot + apikey count for new providers
#5020 (grok-cli), #5065 (factory), #5105 (zenmux-free) added providers but did
not regenerate tests/snapshots/provider/translate-path.json (now +3 entries) nor
bump the APIKEY_PROVIDERS count (159->160 for the factory gateway). Test-only
reconciliation; no production change.
* fix(resilience): harden quota and model lockout edge cases (#5093)
Integrated into release/v3.8.38 (rebased on tip). TRUST-BUT-VERIFY: dropped the PR's 0dd7df641 'fix unit gates' commit which reverted #5122 reasoning-replay (preserveReasoningContent) + re-introduced #4849 O(n^2) growth, and restored 5 tests it had realigned. Kept only the 3 declared resilience fixes (quota cutoff guard, gemini MIME, model-lockout maxCooldownMs); 23/23 green.
* Hydrate quota cache and scope auto combo candidates (#5015)
Integrated into release/v3.8.38 (rebased on tip). Kept core quota-cache hydration + auto-combo candidate scoping + combos UI; dropped out-of-scope toolCloaking refactor (conflicted with #4813 stripEnumDescriptions — took tip) and the unrelated sse-auth test split. Added quota-cache-hydrate-5015 regression test (Rule #18); combo-account-allowlist 8/8 + hydration 2/2 green.
* chore(quality): reconcile complexity + file-size baselines for v3.8.38 owner-PR batch
complexity 1972->1978 (+6) and file-size providers.ts 1093->1107 / usageHistory.ts
934->983 — drift from the /review-prs merge batch (#4845/#5105/#5020/#4940/#5093/
#5015 + #5121 cookie-dedup helper extraction). check:complexity/check:file-size do
not run on the PR->release fast-path, so the branch accrued unmeasured; all legit
feature/fix growth, not regression. See per-key justifications in each baseline.
* fix(security): exact-host Anthropic baseUrl check (CodeQL js/incomplete-url-substring-sanitization #674) (#5130)
The anthropic-compatible Bearer-fallback gate decided whether a configured baseUrl
targeted the official api.anthropic.com host via a substring `.includes("api.anthropic.com")`.
A look-alike upstream such as `https://api.anthropic.com.evil.test` or
`https://evil.test/?x=api.anthropic.com` matched the substring and was wrongly treated as
official, suppressing the Bearer fallback meant for third-party gateways
(CodeQL #674, js/incomplete-url-substring-sanitization, high).
Replace the substring test with an exported `isOfficialAnthropicBaseUrl()` helper that
parses the URL and compares the hostname for exact equality. Empty baseUrl stays official;
scheme-less hosts are parsed with an assumed https://; an unparseable baseUrl falls back to
third-party (Bearer emitted) as the safer default. Behavior for legitimate official/third-party
baseUrls is unchanged.
Adds tests/unit/anthropic-official-baseurl-host.test.ts covering official, look-alike,
scheme-less, and unparseable inputs plus a static guard that the substring pattern is gone.
* fix(proxy): repair one-click Deno & Cloudflare relay deployments (#5128) (#5132)
* fix(services): embed WS proxy honours LIVE_WS_HOST; reject empty messages early (#5110) (#5133)
* fix(api): resolve /v1/models/{id} case-insensitively (#5082) (#5135)
* fix(providers): add MiniMax M3 & Nemotron 3 Ultra to Cline catalog (#3321) (#5136)
* fix(proxy): make SOCKS5 handshake timeout tunable via SOCKS_HANDSHAKE_TIMEOUT_MS (#5109) (#5137)
* feat(sidebar): add support for colored menu icons (#3812)
Integrated into release/v3.8.38 (recreated on tip — fork had unrelated history; added getSidebarIconAccent regression test, Rule #18). Clean 2-file UI feature.
* fix(providers): complete grok-cli OAuth wiring + zenmux-free web-session metadata
Base-red repair for #5020 (grok-cli) and #5105 (zenmux-free), surfaced by the
full CI on the release PR (#5078) — the PR->release fast-path does not run the
oauth-providers-config / web-session-credentials / provider-consistency gates.
- grok-cli: register in OAUTH_PROVIDERS (providers.ts canonical list, fixes
check:provider-consistency), add OAUTH_PROVIDER_IDS.GROK_CLI + GROK_CLI_CONFIG
in oauth constants (provider config now sourced there, not a local literal),
align oauth-providers-config.test.ts (EXPECTED_PROVIDER_KEYS + config map).
- zenmux-free: declare its web-session credential requirement (full Cookie header)
in WEB_SESSION_CREDENTIAL_REQUIREMENTS.
Local: oauth-providers-config 27/27, web-session-credentials 4/4, grok-cli-oauth
7/7, check:provider-consistency OK, +115 OAUTH_PROVIDERS tests green.
* Fix resilience settings page response mapping (#5139)
Integrated into release/v3.8.38. Thanks @rdself for the fix and the regression test.
* fix(kiro): retire claude-sonnet-4.5 from catalog + pin 400 model-unavailable test (#5140)
Extracted the real change from #5140 (the bot PR regenerated the entire
freeModelCatalog.data.ts + touched package-lock.json; only the targeted
edits are kept here):
- remove claude-sonnet-4.5 from the Kiro registry entry
- remove the matching kiro free-model catalog row
- pin Kiro's verbatim 400 "Invalid model..." to isModelUnavailableError
Closes #4484
* fix(sidebar): drop orphan `settings` accent color (typecheck:core red) (#5142)
SIDEBAR_ICON_ACCENTS is typed Partial<Record<HideableSidebarItemId, string>>,
but `settings` is not a hideable item id (only `settings-general`,
`settings-appearance`, … and `context-settings` exist; there is no item with
`id: "settings"`), so the accent was unreachable. It broke `typecheck:core`
on the release tip ("'settings' does not exist in type …", introduced by
#3812 colored menu icons). Removing the orphan key restores a clean
typecheck:core (rc=0).
* feat: salvage batch 2 — diagnostics null-guard (#5096) + observed quota reset windows (#5025) (#5141)
* fix(diagnostics): null-guard content blocks in detectMalformedNonStream
A null (or non-object) entry in a Claude-native `content` array made the
non-stream classifier throw `TypeError: Cannot read properties of null
(reading 'type')`, crashing the malformed-response detection path. Guard
before type-asserting each block: a null/non-object block is simply skipped.
Two regression tests added (null block among valid blocks → null; only-null
blocks → empty_choices).
Salvaged from closed PR #5096 (base-stale; only the defensive guard — the
Claude-shape recognition it also carried already landed via #5108).
Co-authored-by: herjarsa <herjarsa@users.noreply.github.com>
* feat(quota): persist observed provider quota reset windows
Adds `provider_quota_reset_events` (migration 108) + `db/quotaResetEvents.ts`
to record real upstream weekly-quota window transitions whenever a quota
refresh shows the reset rolling to a new cycle (different day, later resetAt).
`apiKeyUsageLimits` now prefers the observed window start over the inferred
`resetAt − 7d`, falling back to snapshot inference when no event is recorded
yet. `quotaCache.setQuotaCache` records the transition opportunistically.
`recordProviderQuotaResetEventIfChanged` only fires for the primary weekly
window (not daily/sonnet), is idempotent (INSERT OR IGNORE on the unique
window key), and no-ops when the reset didn't actually roll. 4 unit tests
(tests/unit/lib/quota-reset-events.test.ts).
Salvaged from closed PR #5025 (which bundled this with two unrelated
features + a colliding migration 104). Renumbered to 108; module re-exported
from localDb (Rule #2).
Co-authored-by: Witroch4 <175152067+Witroch4@users.noreply.github.com>
---------
Co-authored-by: herjarsa <herjarsa@users.noreply.github.com>
Co-authored-by: Witroch4 <175152067+Witroch4@users.noreply.github.com>
* docs(i18n): sync 3.8.38 CHANGELOG section to 41 mirrors (unblock docs-accuracy) (#5144)
The root CHANGELOG [3.8.38] section grew with this cycle's merged PRs, but the
docs/i18n/<lang>/CHANGELOG.md mirrors were not re-synced — drifting >25% in body
size and failing check:docs-sync (the "Docs accuracy" fast-gate step) for every
open PR against the release.
Ran scripts/release/sync-changelog-i18n.mjs 3.8.38 3.8.37 to copy the root
[3.8.38] section into all 41 mirrors. check:docs-all now passes (exit 0).
Sections are copied verbatim; the per-language translation pass runs at release
time via i18n:run — this only restores the size-sync the gate enforces.
* feat(compression): pure per-step fidelity checker (4 invariants, fail-open)
* feat(compression): fidelityGate config + rejected breakdown fields
* feat(compression): wire per-step fidelity gate into stacked pipeline (opt-in)
* feat(compression): preview route accepts fidelityGate flag (playground)
* feat(compression): playground fidelity-gate toggle + lane rejection display
* docs(compression): note fidelityGate advanced thresholds are intentionally API-omitted
* refactor(compression): extract fidelity-gate step helpers to shrink strategySelector (file-size gate)
bodyToText and gateAdvance moved to fidelityGateStep.ts; StackAccumulator exported.
strategySelector: 889->854 (-35). Residual +6 vs pre-Milestone-B frozen 848 is the
irreducible StackOptions.fidelityGate field + two stacked-loop dispatch reads + import.
Baseline updated to 854 with justification. No cycle introduced (import type only).
940 compression tests pass; typecheck clean.
* test(usage): wire usageHistoryDedup under unit runner brace-list (#5145)
Integrated into release/v3.8.38.
* feat: salvage batch from closed stale PRs (#5038, #5057, #5076) (#5138)
Integrated into release/v3.8.38.
* test(combo): deterministic routing-decision matrix for all 17 strategies (#5146)
Integrated into release/v3.8.38.
* feat(compression): fuzzy near-duplicate dedup (session-dedup 2nd pass + playground toggle) (#5143)
Integrated into release/v3.8.38.
* chore(quality): rebaseline file-size for sidebarVisibility.ts + chat.ts drift (#5147)
Mid-cycle drift on release/v3.8.38 from already-merged PRs that the fast-path
(PR->release skips check:file-size) let accumulate without a bump:
- src/shared/constants/sidebarVisibility.ts 1100->1198 (#3812 colored menu
icons, per-item accent map; #5142 dropped one orphan, net still above frozen)
- src/sse/handlers/chat.ts 1560->1575 (#5064 self-inflicted-timeout cooldown
skip + #5124 long OpenAI-compatible SSE hardening + #5110 embed-WS
LIVE_WS_HOST honour / early empty-message reject)
Each covered by its own PR tests; structural shrink of chat.ts tracked in #3501.
Unblocks the Fast Quality Gates for PRs targeting release/v3.8.38.
* chore(release): finalize v3.8.38 CHANGELOG + cycle reconciliation
- Reconcile [3.8.38]: +18 bullets (compression fidelity-gate/fuzzy-dedup #5143,
quota keepalive #5102, web-session robustness #5121, MiniMax/Nemotron #5136,
model-visibility #5091, failover logs #5016, disconnect races #5007, sidebar
orphan #5142, SRE playbooks salvage #5138, new Security #5130 + Maintenance roll-up)
- Credit salvaged-PR authors (@JxnLexn / @KooshaPari / @herjarsa / @Witroch4)
- Remove phantom bullet for CLOSED-not-merged #5092 (setup aggregator never landed)
- Fix isHidden bullet PR citation #4389 -> #5086 (@herjarsa)
- Back-fill forgotten v3.8.36 bullet: #5026 crypto.randomUUID ID-gen (@hamsa0x7)
- Sync 41 i18n CHANGELOG mirrors; README What's New -> v3.8.38
- Rebaseline cycle drift: eslint 3987->4002, cognitive 833->841, dead-exports
345->346, cyclomatic 1978->1980 (file-size handled by #5147)
* fix(i18n): add missing English UI labels (#5153)
Integrated into release/v3.8.38
* Preserve non-stream reasoning fields for compatible clients (#5155)
Integrated into release/v3.8.38
* feat(compression): ionizer engine — lossy JSON-array sampling reversible via CCR (#5148)
Integrated into release/v3.8.38
* test(combo): gated live smoke for combo strategies (in-process + VPS HTTP) (#5151)
Integrated into release/v3.8.38
* test: refresh release expectations to match current code (#5150)
Integrated into release/v3.8.38 (test-only base-red alignment extracted from #5150)
---------
Co-authored-by: Éder Costa <eder.almeida.costa@gmail.com>
Co-authored-by: José Victor Ferreira <root@josevictor.me>
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: fulorgnas <46461624+fulorgnas@users.noreply.github.com>
Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Jan Leon <Jan.gaschler@gmail.com>
Co-authored-by: R. Beltran <rbeltran8000@gmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: KooshaPari <42529354+KooshaPari@users.noreply.github.com>
Co-authored-by: Ramel Tecnologia - Rafa Martins <146174365+rafacpti23@users.noreply.github.com>
Co-authored-by: herjarsa <herjarsa@users.noreply.github.com>
Co-authored-by: Witroch4 <175152067+Witroch4@users.noreply.github.com>
1265 lines
38 KiB
TypeScript
1265 lines
38 KiB
TypeScript
/**
|
|
* Video Generation Handler
|
|
*
|
|
* Handles POST /v1/videos/generations requests.
|
|
* Proxies to upstream video generation providers.
|
|
*
|
|
* Supported provider formats:
|
|
* - ComfyUI: submit AnimateDiff/SVD workflow → poll → fetch video
|
|
* - SD WebUI: POST to AnimateDiff extension endpoint
|
|
*
|
|
* Response format (OpenAI-like):
|
|
* {
|
|
* "created": 1234567890,
|
|
* "data": [{ "b64_json": "...", "format": "mp4" }]
|
|
* }
|
|
*/
|
|
|
|
import { getVideoProvider, parseVideoModel } from "../config/videoRegistry.ts";
|
|
import { kieExecutor } from "../executors/kie.ts";
|
|
import { vertexGenerateVideo } from "../executors/vertexMedia.ts";
|
|
import { handleGoogleFlowVideoGeneration } from "./videoGeneration/googleFlowHandler.ts";
|
|
import { getExecutor } from "../executors/index.ts";
|
|
import { isJsonObject, parseKieResultJson } from "../utils/kieTask.ts";
|
|
import {
|
|
buildRunwayApiUrl,
|
|
buildRunwayHeaders,
|
|
RUNWAYML_IMAGE_REQUIRED_MODELS,
|
|
} from "../config/runway.ts";
|
|
import {
|
|
submitComfyWorkflow,
|
|
pollComfyResult,
|
|
fetchComfyOutput,
|
|
extractComfyOutputFiles,
|
|
} from "../utils/comfyuiClient.ts";
|
|
import { saveCallLog } from "@/lib/usageDb";
|
|
import { sanitizeErrorMessage } from "../utils/error.ts";
|
|
|
|
/**
|
|
* Handle video generation request
|
|
*/
|
|
export async function handleVideoGeneration({ body, credentials, log }) {
|
|
const { provider, model } = parseVideoModel(body.model);
|
|
|
|
if (!provider) {
|
|
return {
|
|
success: false,
|
|
status: 400,
|
|
error: `Invalid video model: ${body.model}. Use format: provider/model`,
|
|
};
|
|
}
|
|
|
|
const providerConfig = getVideoProvider(provider);
|
|
if (!providerConfig) {
|
|
return {
|
|
success: false,
|
|
status: 400,
|
|
error: `Unknown video provider: ${provider}`,
|
|
};
|
|
}
|
|
|
|
if (providerConfig.format === "vertex-veo") {
|
|
return handleVertexVeoGeneration({ model, body, credentials, log });
|
|
}
|
|
|
|
if (providerConfig.format === "google-flow") {
|
|
return handleGoogleFlowVideoGeneration({ model, providerConfig, body, credentials, log });
|
|
}
|
|
|
|
if (providerConfig.format === "comfyui") {
|
|
return handleComfyUIVideoGeneration({ model, provider, providerConfig, body, log });
|
|
}
|
|
|
|
if (providerConfig.format === "sdwebui-video") {
|
|
return handleSDWebUIVideoGeneration({ model, provider, providerConfig, body, log });
|
|
}
|
|
|
|
if (providerConfig.format === "kie-video") {
|
|
return handleKieVideoGeneration({ model, provider, providerConfig, body, credentials, log });
|
|
}
|
|
|
|
if (providerConfig.format === "runwayml") {
|
|
return handleRunwayVideoGeneration({ model, provider, providerConfig, body, credentials, log });
|
|
}
|
|
|
|
if (providerConfig.format === "haiper-video") {
|
|
return handleHaiperVideoGeneration({ model, provider, providerConfig, body, credentials, log });
|
|
}
|
|
|
|
if (providerConfig.format === "veoaifree-web") {
|
|
return handleVeoAiFreeVideoGeneration({ model, provider, body, credentials, log });
|
|
}
|
|
|
|
if (providerConfig.format === "leonardo-video") {
|
|
return handleLeonardoVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
});
|
|
}
|
|
|
|
if (providerConfig.format === "dashscope-video") {
|
|
return handleDashscopeVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
});
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
status: 400,
|
|
error: `Unsupported video format: ${providerConfig.format}`,
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Alibaba (DashScope) Wan video generation: create async task → poll → MP4.
|
|
* Targets wan2.7-t2v on the DashScope intl region. Reuses the stored alibaba
|
|
* provider Bearer apiKey — no separate credential flow.
|
|
*/
|
|
async function handleDashscopeVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
}: {
|
|
model: string;
|
|
provider: string;
|
|
providerConfig: { baseUrl: string; statusUrl?: string };
|
|
body: Record<string, unknown> & {
|
|
prompt?: unknown;
|
|
negative_prompt?: unknown;
|
|
size?: unknown;
|
|
aspect_ratio?: unknown;
|
|
duration?: unknown;
|
|
timeout_ms?: unknown;
|
|
poll_interval_ms?: unknown;
|
|
};
|
|
credentials?: { apiKey?: string; accessToken?: string } | null;
|
|
log?: {
|
|
info: (scope: string, message: string) => void;
|
|
error: (scope: string, message: string) => void;
|
|
} | null;
|
|
}) {
|
|
const startTime = Date.now();
|
|
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
|
|
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
|
|
const token = credentials?.apiKey || credentials?.accessToken;
|
|
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
|
|
const statusUrl = (providerConfig.statusUrl || `${baseUrl}/tasks`).replace(/\/$/, "");
|
|
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
|
|
|
|
if (!token) {
|
|
return { success: false, status: 401, error: "Alibaba DashScope API key is required" };
|
|
}
|
|
|
|
const sizeParam = normalizeDashscopeSize(body.size, body.aspect_ratio);
|
|
const parameters: Record<string, unknown> = {};
|
|
if (sizeParam) parameters.size = sizeParam;
|
|
if (body.duration != null) parameters.duration = Number(body.duration);
|
|
|
|
const payload = {
|
|
model,
|
|
input: {
|
|
prompt,
|
|
...(typeof body.negative_prompt === "string"
|
|
? { negative_prompt: body.negative_prompt }
|
|
: {}),
|
|
},
|
|
parameters,
|
|
};
|
|
|
|
if (log) {
|
|
log.info(
|
|
"VIDEO",
|
|
`${provider}/${model} (dashscope-video) | prompt: "${prompt.slice(0, 60)}..."`
|
|
);
|
|
}
|
|
|
|
try {
|
|
// Step 1: create async task (X-DashScope-Async: enable)
|
|
const createRes = await fetch(`${baseUrl}/services/aigc/video-generation/video-synthesis`, {
|
|
method: "POST",
|
|
headers: {
|
|
Authorization: `Bearer ${token}`,
|
|
"Content-Type": "application/json",
|
|
"X-DashScope-Async": "enable",
|
|
},
|
|
body: JSON.stringify(payload),
|
|
});
|
|
const createData = await createRes.json().catch(() => ({}));
|
|
const taskId = createData?.output?.task_id;
|
|
if (!taskId) {
|
|
const errorMessage =
|
|
createData?.message ||
|
|
createData?.errors?.[0]?.message ||
|
|
"DashScope video generation did not return task_id";
|
|
if (log) {
|
|
log.error("VIDEO", `DashScope createTask failed: ${JSON.stringify(createData)}`);
|
|
}
|
|
return { success: false, status: 502, error: String(errorMessage) };
|
|
}
|
|
|
|
// Step 2: poll statusUrl/{task_id} until terminal
|
|
const deadline = startTime + timeoutMs;
|
|
let lastStatus = "PENDING";
|
|
while (Date.now() < deadline) {
|
|
await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
|
|
const pollRes = await fetch(`${statusUrl}/${taskId}`, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
const pollData = await pollRes.json().catch(() => ({}));
|
|
lastStatus = pollData?.output?.task_status || "PENDING";
|
|
|
|
if (lastStatus === "SUCCEEDED") {
|
|
const videoUrl = pollData?.output?.video_url;
|
|
if (!videoUrl) {
|
|
return {
|
|
success: false,
|
|
status: 502,
|
|
error: "DashScope task SUCCEEDED but no video_url",
|
|
};
|
|
}
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
responseBody: { videos_count: 1 },
|
|
}).catch(() => {});
|
|
return {
|
|
success: true,
|
|
data: {
|
|
created: Math.floor(Date.now() / 1000),
|
|
data: [{ url: videoUrl, format: "mp4" }],
|
|
},
|
|
};
|
|
}
|
|
|
|
if (lastStatus === "FAILED" || lastStatus === "UNKNOWN_ERROR") {
|
|
const errorMessage =
|
|
pollData?.output?.message ||
|
|
pollData?.output?.errors?.[0]?.message ||
|
|
"DashScope video task FAILED";
|
|
return { success: false, status: 502, error: String(errorMessage) };
|
|
}
|
|
// PENDING / RUNNING → keep polling
|
|
}
|
|
|
|
return {
|
|
success: false,
|
|
status: 504,
|
|
error: `DashScope task ${taskId} timed out (status: ${lastStatus})`,
|
|
};
|
|
} catch (err: unknown) {
|
|
return {
|
|
success: false,
|
|
status: isJsonObject(err) && Number.isFinite(Number(err.status)) ? Number(err.status) : 502,
|
|
error: sanitizeErrorMessage(err) || "Video provider error",
|
|
};
|
|
}
|
|
}
|
|
|
|
// Map OmniRoute size/aspect_ratio → Alibaba DashScope "WxH" (1280*720).
|
|
// Accepts "1280*720", "1280x720", or a ratio "16:9". Returns undefined if unparseable
|
|
// (then omitted from the payload so DashScope applies its own default).
|
|
function normalizeDashscopeSize(size: unknown, aspectRatio: unknown): string | undefined {
|
|
if (typeof size === "string") {
|
|
if (/^\d+\*\d+$/.test(size)) return size;
|
|
if (/^\d+x\d+$/.test(size)) return size.replace("x", "*");
|
|
}
|
|
if (typeof aspectRatio === "string") {
|
|
const ratioMap: Record<string, string> = {
|
|
"16:9": "1280*720",
|
|
"9:16": "720*1280",
|
|
"1:1": "960*960",
|
|
};
|
|
return ratioMap[aspectRatio];
|
|
}
|
|
return undefined;
|
|
}
|
|
|
|
/**
|
|
* Veo video generation via Vertex AI (predictLongRunning → poll → MP4).
|
|
* Uses the Vertex chat credentials (Service Account JSON or Express key).
|
|
*/
|
|
async function handleVertexVeoGeneration({ model, body, credentials, log }) {
|
|
try {
|
|
const aspectRatio =
|
|
typeof body.aspect_ratio === "string"
|
|
? body.aspect_ratio
|
|
: typeof body.aspectRatio === "string"
|
|
? body.aspectRatio
|
|
: typeof body.size === "string"
|
|
? body.size
|
|
: undefined;
|
|
const durationSeconds =
|
|
typeof body.duration === "number"
|
|
? body.duration
|
|
: typeof body.durationSeconds === "number"
|
|
? body.durationSeconds
|
|
: undefined;
|
|
|
|
const result = await vertexGenerateVideo(credentials, {
|
|
model,
|
|
prompt: String(body.prompt ?? ""),
|
|
aspectRatio,
|
|
durationSeconds,
|
|
negativePrompt: typeof body.negative_prompt === "string" ? body.negative_prompt : undefined,
|
|
});
|
|
|
|
const item = result.base64
|
|
? { b64_json: result.base64, format: result.format }
|
|
: { url: result.url, format: result.format };
|
|
|
|
return {
|
|
success: true,
|
|
data: { created: Math.floor(Date.now() / 1000), data: [item] },
|
|
};
|
|
} catch (err: any) {
|
|
log?.error?.("VIDEO", `Vertex Veo generation failed: ${err?.message}`);
|
|
return {
|
|
success: false,
|
|
status: typeof err?.status === "number" ? err.status : 502,
|
|
error: sanitizeErrorMessage(err?.message || "Vertex Veo generation failed"),
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle ComfyUI video generation
|
|
* Submits an AnimateDiff or SVD workflow, polls for completion, fetches output video
|
|
*/
|
|
async function handleVeoAiFreeVideoGeneration({ model, provider, body, credentials, log }) {
|
|
const executor = getExecutor(provider);
|
|
if (!executor) {
|
|
return { success: false, status: 400, error: `Unknown video provider: ${provider}` };
|
|
}
|
|
|
|
const prompt = String(body.prompt ?? "");
|
|
const systemParts = [];
|
|
if (body.size) systemParts.push(`aspect_ratio: ${body.size}`);
|
|
if (body.aspect_ratio) systemParts.push(`aspect_ratio: ${body.aspect_ratio}`);
|
|
|
|
const response = await executor.execute({
|
|
model,
|
|
body: {
|
|
...body,
|
|
model: `${provider}/${model}`,
|
|
messages: [
|
|
...(systemParts.length > 0 ? [{ role: "system", content: systemParts.join("\n") }] : []),
|
|
{ role: "user", content: prompt },
|
|
],
|
|
},
|
|
stream: false,
|
|
credentials: credentials || { connectionId: "noauth" },
|
|
signal: null,
|
|
log,
|
|
});
|
|
|
|
const upstreamResponse = response instanceof Response ? response : response.response;
|
|
if (!upstreamResponse.ok) {
|
|
return {
|
|
success: false,
|
|
status: upstreamResponse.status || 502,
|
|
error: await upstreamResponse.text().catch(() => "Video provider error"),
|
|
};
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
data: await upstreamResponse.json(),
|
|
};
|
|
}
|
|
|
|
async function handleComfyUIVideoGeneration({ model, provider, providerConfig, body, log }) {
|
|
const startTime = Date.now();
|
|
const [width, height] = (body.size || "512x512").split("x").map(Number);
|
|
const frames = body.frames || 16;
|
|
|
|
// AnimateDiff workflow template
|
|
const workflow = {
|
|
"1": {
|
|
class_type: "CheckpointLoaderSimple",
|
|
inputs: { ckpt_name: model },
|
|
},
|
|
"2": {
|
|
class_type: "CLIPTextEncode",
|
|
inputs: { text: body.prompt, clip: ["1", 1] },
|
|
},
|
|
"3": {
|
|
class_type: "CLIPTextEncode",
|
|
inputs: { text: body.negative_prompt || "", clip: ["1", 1] },
|
|
},
|
|
"4": {
|
|
class_type: "EmptyLatentImage",
|
|
inputs: { width: width || 512, height: height || 512, batch_size: frames },
|
|
},
|
|
"5": {
|
|
class_type: "KSampler",
|
|
inputs: {
|
|
seed: Math.floor(Math.random() * 2 ** 32),
|
|
steps: body.steps || 20,
|
|
cfg: body.cfg_scale || 7,
|
|
sampler_name: "euler",
|
|
scheduler: "normal",
|
|
denoise: 1,
|
|
model: ["1", 0],
|
|
positive: ["2", 0],
|
|
negative: ["3", 0],
|
|
latent_image: ["4", 0],
|
|
},
|
|
},
|
|
"6": {
|
|
class_type: "VAEDecode",
|
|
inputs: { samples: ["5", 0], vae: ["1", 2] },
|
|
},
|
|
"7": {
|
|
class_type: "SaveAnimatedWEBP",
|
|
inputs: {
|
|
filename_prefix: "omniroute_video",
|
|
fps: body.fps || 8,
|
|
lossless: false,
|
|
quality: 80,
|
|
method: "default",
|
|
images: ["6", 0],
|
|
},
|
|
},
|
|
};
|
|
|
|
if (log) {
|
|
const promptPreview = String(body.prompt ?? "").slice(0, 60);
|
|
log.info(
|
|
"VIDEO",
|
|
`${provider}/${model} (comfyui) | prompt: "${promptPreview}..." | frames: ${frames}`
|
|
);
|
|
}
|
|
|
|
try {
|
|
const promptId = await submitComfyWorkflow(providerConfig.baseUrl, workflow);
|
|
const historyEntry = await pollComfyResult(providerConfig.baseUrl, promptId, 300_000);
|
|
const outputFiles = extractComfyOutputFiles(historyEntry);
|
|
|
|
const videos = [];
|
|
for (const file of outputFiles) {
|
|
const buffer = await fetchComfyOutput(
|
|
providerConfig.baseUrl,
|
|
file.filename,
|
|
file.subfolder,
|
|
file.type
|
|
);
|
|
const base64 = Buffer.from(buffer).toString("base64");
|
|
videos.push({ b64_json: base64, format: "webp" });
|
|
}
|
|
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
responseBody: { videos_count: videos.length },
|
|
}).catch(() => {});
|
|
|
|
return {
|
|
success: true,
|
|
data: { created: Math.floor(Date.now() / 1000), data: videos },
|
|
};
|
|
} catch (err) {
|
|
if (log) log.error("VIDEO", `${provider} comfyui error: ${err.message}`);
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: err.message,
|
|
}).catch(() => {});
|
|
return {
|
|
success: false,
|
|
status: 502,
|
|
error: sanitizeErrorMessage(err) || "Video provider error",
|
|
};
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle SD WebUI video generation via AnimateDiff extension
|
|
* POST to the AnimateDiff API endpoint
|
|
*/
|
|
async function handleSDWebUIVideoGeneration({ model, provider, providerConfig, body, log }) {
|
|
const startTime = Date.now();
|
|
const [width, height] = (body.size || "512x512").split("x").map(Number);
|
|
const url = `${providerConfig.baseUrl}/animatediff/v1/generate`;
|
|
|
|
const upstreamBody = {
|
|
prompt: body.prompt,
|
|
negative_prompt: body.negative_prompt || "",
|
|
width: width || 512,
|
|
height: height || 512,
|
|
steps: body.steps || 20,
|
|
cfg_scale: body.cfg_scale || 7,
|
|
frames: body.frames || 16,
|
|
fps: body.fps || 8,
|
|
};
|
|
|
|
if (log) {
|
|
const promptPreview = String(body.prompt ?? "").slice(0, 60);
|
|
log.info("VIDEO", `${provider}/${model} (sdwebui) | prompt: "${promptPreview}..."`);
|
|
}
|
|
|
|
try {
|
|
const response = await fetch(url, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify(upstreamBody),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
const errorText = await response.text();
|
|
if (log)
|
|
log.error("VIDEO", `${provider} error ${response.status}: ${errorText.slice(0, 200)}`);
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: response.status,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText.slice(0, 500),
|
|
}).catch(() => {});
|
|
return { success: false, status: response.status, error: errorText };
|
|
}
|
|
|
|
const data = await response.json();
|
|
// SD WebUI AnimateDiff returns { video: "base64..." } or { images: [...] }
|
|
const videos = [];
|
|
if (data.video) {
|
|
videos.push({ b64_json: data.video, format: "mp4" });
|
|
} else if (data.images) {
|
|
for (const img of data.images) {
|
|
videos.push({ b64_json: typeof img === "string" ? img : img.image, format: "mp4" });
|
|
}
|
|
}
|
|
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
responseBody: { videos_count: videos.length },
|
|
}).catch(() => {});
|
|
|
|
return {
|
|
success: true,
|
|
data: { created: Math.floor(Date.now() / 1000), data: videos },
|
|
};
|
|
} catch (err) {
|
|
if (log) log.error("VIDEO", `${provider} sdwebui error: ${err.message}`);
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: err.message,
|
|
}).catch(() => {});
|
|
return {
|
|
success: false,
|
|
status: 502,
|
|
error: sanitizeErrorMessage(err) || "Video provider error",
|
|
};
|
|
}
|
|
}
|
|
|
|
function normalizeKieVideoResult(recordData: unknown): string[] {
|
|
const record = isJsonObject(recordData) ? recordData : {};
|
|
const data = isJsonObject(record.data) ? record.data : {};
|
|
const response = isJsonObject(data.response) ? data.response : {};
|
|
const resultJson = parseKieResultJson(recordData);
|
|
|
|
const urls = Array.isArray(resultJson?.resultUrls)
|
|
? (resultJson.resultUrls as string[])
|
|
: Array.isArray(resultJson?.videoUrls)
|
|
? (resultJson.videoUrls as string[])
|
|
: Array.isArray(response.resultUrls)
|
|
? (response.resultUrls as string[])
|
|
: [];
|
|
|
|
return urls.filter((url: unknown) => typeof url === "string" && url.length > 0);
|
|
}
|
|
|
|
async function handleKieVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
}: {
|
|
model: string;
|
|
provider: string;
|
|
providerConfig: {
|
|
baseUrl: string;
|
|
statusUrl?: string;
|
|
};
|
|
body: Record<string, unknown> & {
|
|
prompt?: unknown;
|
|
duration?: unknown;
|
|
aspect_ratio?: unknown;
|
|
sound?: unknown;
|
|
timeout_ms?: unknown;
|
|
poll_interval_ms?: unknown;
|
|
};
|
|
credentials?: {
|
|
apiKey?: string;
|
|
accessToken?: string;
|
|
} | null;
|
|
log?: {
|
|
info: (scope: string, message: string) => void;
|
|
error: (scope: string, message: string) => void;
|
|
} | null;
|
|
}) {
|
|
const startTime = Date.now();
|
|
const timeoutMs = Number(body.timeout_ms) > 0 ? Number(body.timeout_ms) : 300000;
|
|
const pollIntervalMs = Number(body.poll_interval_ms) > 0 ? Number(body.poll_interval_ms) : 2500;
|
|
const token = credentials?.apiKey || credentials?.accessToken;
|
|
const baseUrl = providerConfig.baseUrl.replace(/\/$/, "");
|
|
const prompt = typeof body.prompt === "string" ? body.prompt : String(body.prompt ?? "");
|
|
|
|
if (!token) {
|
|
return { success: false, status: 401, error: "KIE API key is required" };
|
|
}
|
|
|
|
const payload = {
|
|
model,
|
|
input: {
|
|
prompt,
|
|
duration: body.duration ? String(body.duration) : "5",
|
|
aspect_ratio: typeof body.aspect_ratio === "string" ? body.aspect_ratio : "16:9",
|
|
sound: body.sound === true,
|
|
},
|
|
};
|
|
|
|
if (log) {
|
|
const promptPreview = String(body.prompt ?? "").slice(0, 60);
|
|
log.info("VIDEO", `${provider}/${model} (kie-video) | prompt: "${promptPreview}..."`);
|
|
}
|
|
|
|
try {
|
|
const createData = await kieExecutor.createTask({ baseUrl, token, payload });
|
|
const taskId = createData?.data?.taskId || createData?.taskId;
|
|
if (!taskId) {
|
|
const errorMessage =
|
|
createData?.msg ||
|
|
createData?.message ||
|
|
createData?.error ||
|
|
"KIE video generation did not return taskId";
|
|
if (log) {
|
|
log.error("VIDEO", `KIE createTask failed: ${JSON.stringify(createData)}`);
|
|
}
|
|
return { success: false, status: 502, error: errorMessage };
|
|
}
|
|
|
|
const statusUrl = providerConfig.statusUrl || `${baseUrl}/api/v1/jobs/recordInfo`;
|
|
|
|
const { data: recordData, state } = await kieExecutor.pollTask({
|
|
statusUrl,
|
|
taskId: String(taskId),
|
|
token,
|
|
timeoutMs,
|
|
pollIntervalMs,
|
|
});
|
|
|
|
if (state === "success") {
|
|
const videoUrls = normalizeKieVideoResult(recordData);
|
|
const videos = videoUrls.map((url) => ({ url, format: "mp4" }));
|
|
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
responseBody: { videos_count: videos.length },
|
|
}).catch(() => {});
|
|
|
|
return {
|
|
success: true,
|
|
data: { created: Math.floor(Date.now() / 1000), data: videos },
|
|
};
|
|
}
|
|
|
|
const record = isJsonObject(recordData) ? recordData : {};
|
|
const data = isJsonObject(record.data) ? record.data : {};
|
|
const errorMessage = data.failMsg || data.errorMessage || record.msg || "KIE video task failed";
|
|
return { success: false, status: 502, error: String(errorMessage) };
|
|
} catch (err: unknown) {
|
|
return {
|
|
success: false,
|
|
status: isJsonObject(err) && Number.isFinite(Number(err.status)) ? Number(err.status) : 502,
|
|
error: sanitizeErrorMessage(err) || "Video provider error",
|
|
};
|
|
}
|
|
}
|
|
|
|
async function handleRunwayVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
}) {
|
|
const startTime = Date.now();
|
|
const token = credentials?.apiKey || credentials?.accessToken;
|
|
if (!token) {
|
|
return { success: false, status: 400, error: "No credentials for Runway provider" };
|
|
}
|
|
|
|
const promptImage = resolveRunwayPromptImage(body);
|
|
const useImageToVideo = Boolean(promptImage);
|
|
if (!useImageToVideo && RUNWAYML_IMAGE_REQUIRED_MODELS.has(model)) {
|
|
return {
|
|
success: false,
|
|
status: 400,
|
|
error: `Runway model ${model} requires promptImage for image-to-video generation`,
|
|
};
|
|
}
|
|
|
|
const ratio = resolveRunwayRatio(body);
|
|
const duration = resolveRunwayDuration(body);
|
|
const timeoutMs = resolvePositiveInteger(body.timeout_ms, 300000);
|
|
const pollIntervalMs = resolvePositiveInteger(body.poll_interval_ms, 5000);
|
|
const submitUrl = buildRunwayApiUrl(
|
|
useImageToVideo ? "/image_to_video" : "/text_to_video",
|
|
providerConfig.baseUrl
|
|
);
|
|
const headers = buildRunwayHeaders(token);
|
|
|
|
const upstreamBody = {
|
|
model,
|
|
promptText: body.prompt,
|
|
ratio,
|
|
duration,
|
|
};
|
|
|
|
if (useImageToVideo) upstreamBody.promptImage = promptImage;
|
|
if (typeof body.seed === "number" && Number.isFinite(body.seed)) {
|
|
upstreamBody.seed = Math.max(0, Math.floor(body.seed));
|
|
}
|
|
|
|
if (log) {
|
|
const promptPreview = String(body.prompt ?? "").slice(0, 60);
|
|
log.info(
|
|
"VIDEO",
|
|
`${provider}/${model} (runway ${useImageToVideo ? "image_to_video" : "text_to_video"}) | prompt: "${promptPreview}..."`
|
|
);
|
|
}
|
|
|
|
try {
|
|
const submitResponse = await fetch(submitUrl, {
|
|
method: "POST",
|
|
headers,
|
|
body: JSON.stringify(upstreamBody),
|
|
});
|
|
|
|
if (!submitResponse.ok) {
|
|
const errorText = await submitResponse.text();
|
|
if (log) {
|
|
log.error(
|
|
"VIDEO",
|
|
`${provider} submit error ${submitResponse.status}: ${errorText.slice(0, 200)}`
|
|
);
|
|
}
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: submitResponse.status,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText.slice(0, 500),
|
|
}).catch(() => {});
|
|
return { success: false, status: submitResponse.status, error: errorText };
|
|
}
|
|
|
|
const submitData = await submitResponse.json();
|
|
const taskId = typeof submitData?.id === "string" ? submitData.id : "";
|
|
if (!taskId) {
|
|
const errorText = `Runway submit did not return task id: ${JSON.stringify(submitData).slice(0, 400)}`;
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText,
|
|
}).catch(() => {});
|
|
return { success: false, status: 502, error: errorText };
|
|
}
|
|
|
|
const deadline = Date.now() + timeoutMs;
|
|
let lastTask = null;
|
|
|
|
while (Date.now() < deadline) {
|
|
const taskResponse = await fetch(
|
|
buildRunwayApiUrl(`/tasks/${encodeURIComponent(taskId)}`, providerConfig.baseUrl),
|
|
{
|
|
method: "GET",
|
|
headers,
|
|
}
|
|
);
|
|
|
|
if (!taskResponse.ok) {
|
|
const errorText = await taskResponse.text();
|
|
if (log) {
|
|
log.error(
|
|
"VIDEO",
|
|
`${provider} poll error ${taskResponse.status}: ${errorText.slice(0, 200)}`
|
|
);
|
|
}
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: taskResponse.status,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText.slice(0, 500),
|
|
responseBody: { taskId, stage: "poll" },
|
|
}).catch(() => {});
|
|
return { success: false, status: taskResponse.status, error: errorText };
|
|
}
|
|
|
|
const task = await taskResponse.json();
|
|
lastTask = task;
|
|
const status = String(task?.status || "").toUpperCase();
|
|
|
|
if (status === "SUCCEEDED") {
|
|
const videos = await normalizeRunwayVideoResult(task, body);
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
responseBody: { videos_count: videos.length, taskId, mode: "async" },
|
|
}).catch(() => {});
|
|
return {
|
|
success: true,
|
|
data: { created: Math.floor(Date.now() / 1000), data: videos },
|
|
};
|
|
}
|
|
|
|
if (RUNWAY_TERMINAL_FAILURE_STATUSES.has(status)) {
|
|
const errorText =
|
|
extractRunwayFailureMessage(task) || `Runway task failed with status ${status}`;
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText.slice(0, 500),
|
|
responseBody: { taskId, status },
|
|
}).catch(() => {});
|
|
return { success: false, status: 502, error: errorText };
|
|
}
|
|
|
|
await sleep(pollIntervalMs);
|
|
}
|
|
|
|
const timeoutError = `Runway task timeout after ${timeoutMs}ms (taskId=${taskId}, status=${String(
|
|
lastTask?.status || "unknown"
|
|
)})`;
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 504,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: timeoutError,
|
|
responseBody: { taskId, status: lastTask?.status ?? null },
|
|
}).catch(() => {});
|
|
return { success: false, status: 504, error: timeoutError };
|
|
} catch (err) {
|
|
if (log) log.error("VIDEO", `${provider} runway error: ${err.message}`);
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: err.message,
|
|
}).catch(() => {});
|
|
return {
|
|
success: false,
|
|
status: 502,
|
|
error: sanitizeErrorMessage(err) || "Video provider error",
|
|
};
|
|
}
|
|
}
|
|
|
|
const RUNWAY_TERMINAL_FAILURE_STATUSES = new Set([
|
|
"FAILED",
|
|
"CANCELED",
|
|
"CANCELLED",
|
|
"ABORTED",
|
|
"DELETED",
|
|
]);
|
|
|
|
function resolveRunwayPromptImage(body) {
|
|
const directCandidates = [
|
|
body.promptImage,
|
|
body.prompt_image,
|
|
body.image,
|
|
body.image_url,
|
|
body.imageUrl,
|
|
body.provider_options?.promptImage,
|
|
body.provider_options?.prompt_image,
|
|
];
|
|
|
|
for (const candidate of directCandidates) {
|
|
if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
|
|
if (candidate && typeof candidate === "object") return candidate;
|
|
if (Array.isArray(candidate) && candidate.length > 0) return candidate;
|
|
}
|
|
|
|
const arrayCandidates = [
|
|
body.imageUrls,
|
|
body.image_urls,
|
|
body.provider_options?.imageUrls,
|
|
body.provider_options?.image_urls,
|
|
];
|
|
for (const candidate of arrayCandidates) {
|
|
if (Array.isArray(candidate) && candidate.length > 0) return candidate;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function resolveRunwayRatio(body) {
|
|
const aspectRatio = typeof body.aspect_ratio === "string" ? body.aspect_ratio : body.aspectRatio;
|
|
if (aspectRatio === "1280:720" || aspectRatio === "720:1280") return aspectRatio;
|
|
if (aspectRatio === "16:9") return "1280:720";
|
|
if (aspectRatio === "9:16") return "720:1280";
|
|
|
|
const size = typeof body.size === "string" ? body.size : "";
|
|
const [widthRaw, heightRaw] = size.split("x");
|
|
const width = Number(widthRaw);
|
|
const height = Number(heightRaw);
|
|
if (Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0) {
|
|
return width >= height ? "1280:720" : "720:1280";
|
|
}
|
|
|
|
return "1280:720";
|
|
}
|
|
|
|
function resolveRunwayDuration(body) {
|
|
if (Number.isFinite(body.duration)) {
|
|
return clampRunwayDuration(body.duration);
|
|
}
|
|
|
|
if (Number.isFinite(body.frames) && Number.isFinite(body.fps) && Number(body.fps) > 0) {
|
|
return clampRunwayDuration(Number(body.frames) / Number(body.fps));
|
|
}
|
|
|
|
return 5;
|
|
}
|
|
|
|
function clampRunwayDuration(value) {
|
|
const duration = Math.round(Number(value));
|
|
if (!Number.isFinite(duration)) return 5;
|
|
return Math.min(10, Math.max(2, duration));
|
|
}
|
|
|
|
function resolvePositiveInteger(value, fallback) {
|
|
const numeric = Number(value);
|
|
if (!Number.isFinite(numeric) || numeric <= 0) return fallback;
|
|
return Math.floor(numeric);
|
|
}
|
|
|
|
function extractRunwayOutputUrls(task) {
|
|
const rawOutput = Array.isArray(task?.output)
|
|
? task.output
|
|
: Array.isArray(task?.result)
|
|
? task.result
|
|
: [];
|
|
|
|
return rawOutput
|
|
.map((entry) => {
|
|
if (typeof entry === "string") return entry;
|
|
if (!entry || typeof entry !== "object") return null;
|
|
return entry.url || entry.uri || entry.videoUrl || entry.video_url || null;
|
|
})
|
|
.filter((value) => typeof value === "string" && value.length > 0);
|
|
}
|
|
|
|
function extractRunwayFailureMessage(task) {
|
|
const directCandidates = [
|
|
task?.failure,
|
|
task?.failureReason,
|
|
task?.error,
|
|
task?.errorMessage,
|
|
task?.message,
|
|
];
|
|
for (const candidate of directCandidates) {
|
|
if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
|
|
}
|
|
|
|
if (task?.failure && typeof task.failure === "object") {
|
|
const nestedCandidates = [
|
|
task.failure.message,
|
|
task.failure.reason,
|
|
task.failure.error,
|
|
task.failure.code,
|
|
];
|
|
for (const candidate of nestedCandidates) {
|
|
if (typeof candidate === "string" && candidate.trim()) return candidate.trim();
|
|
}
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
async function normalizeRunwayVideoResult(task, body) {
|
|
const urls = extractRunwayOutputUrls(task);
|
|
if (urls.length === 0) {
|
|
throw new Error(
|
|
`Runway task completed without output URLs: ${JSON.stringify(task).slice(0, 400)}`
|
|
);
|
|
}
|
|
|
|
if (body.response_format === "url") {
|
|
return urls.map((url) => ({ url, format: "mp4" }));
|
|
}
|
|
|
|
const videos = [];
|
|
for (const url of urls) {
|
|
const response = await fetch(url);
|
|
if (!response.ok) {
|
|
throw new Error(`Runway output fetch failed (${response.status})`);
|
|
}
|
|
const arrayBuffer = await response.arrayBuffer();
|
|
videos.push({
|
|
b64_json: Buffer.from(arrayBuffer).toString("base64"),
|
|
format: "mp4",
|
|
});
|
|
}
|
|
|
|
return videos;
|
|
}
|
|
|
|
async function handleHaiperVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
}) {
|
|
const startTime = Date.now();
|
|
const token = credentials?.apiKey || "";
|
|
const res = await fetch(providerConfig.baseUrl, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", HAIPER_KEY: token },
|
|
body: JSON.stringify({ prompt: body.prompt, duration: 4, aspect_ratio: "16:9" }),
|
|
});
|
|
if (!res.ok) {
|
|
const errorText = await res.text();
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: res.status,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText.slice(0, 500),
|
|
}).catch(() => {});
|
|
return { success: false, status: res.status, error: errorText };
|
|
}
|
|
const { job_id } = await res.json();
|
|
const deadline = Date.now() + 300000;
|
|
while (Date.now() < deadline) {
|
|
await sleep(5000);
|
|
const statusRes = await fetch(`${providerConfig.statusUrl}/${job_id}`, {
|
|
headers: { HAIPER_KEY: token },
|
|
});
|
|
const status = await statusRes.json();
|
|
if (status.status === "completed" || status.status === "succeeded") {
|
|
const videoUrl = status.creation_url || status.output?.video_url;
|
|
if (videoUrl) {
|
|
const videoRes = await fetch(videoUrl);
|
|
const buf = await videoRes.arrayBuffer();
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
}).catch(() => {});
|
|
return {
|
|
success: true,
|
|
data: {
|
|
created: Math.floor(Date.now() / 1000),
|
|
data: [{ b64_json: Buffer.from(buf).toString("base64"), format: "mp4" }],
|
|
},
|
|
};
|
|
}
|
|
}
|
|
if (status.status === "failed") {
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: "Haiper video generation failed",
|
|
}).catch(() => {});
|
|
return { success: false, status: 502, error: "Haiper video generation failed" };
|
|
}
|
|
}
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 504,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: "Haiper video generation timed out",
|
|
}).catch(() => {});
|
|
return { success: false, status: 504, error: "Haiper video generation timed out" };
|
|
}
|
|
|
|
async function handleLeonardoVideoGeneration({
|
|
model,
|
|
provider,
|
|
providerConfig,
|
|
body,
|
|
credentials,
|
|
log,
|
|
}) {
|
|
const startTime = Date.now();
|
|
const token = credentials?.apiKey || "";
|
|
const res = await fetch(providerConfig.baseUrl, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` },
|
|
body: JSON.stringify({
|
|
modelId: "phoenix",
|
|
prompt: body.prompt,
|
|
width: 1024,
|
|
height: 576,
|
|
num_frames: 24,
|
|
}),
|
|
});
|
|
if (!res.ok) {
|
|
const errorText = await res.text();
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: res.status,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: errorText.slice(0, 500),
|
|
}).catch(() => {});
|
|
return { success: false, status: res.status, error: errorText };
|
|
}
|
|
const { sdGenerationJob } = await res.json();
|
|
const genId = sdGenerationJob?.generationId;
|
|
if (!genId) {
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: "No generation ID returned",
|
|
}).catch(() => {});
|
|
return { success: false, status: 502, error: "No generation ID returned" };
|
|
}
|
|
const deadline = Date.now() + 300000;
|
|
while (Date.now() < deadline) {
|
|
await sleep(5000);
|
|
const statusRes = await fetch(`${providerConfig.baseUrl}/${genId}`, {
|
|
headers: { Authorization: `Bearer ${token}` },
|
|
});
|
|
const status = await statusRes.json();
|
|
const gen = status.generations_by_pk || status;
|
|
if (gen.status === "COMPLETE") {
|
|
const imgUrl = gen.generated_images?.[0]?.url;
|
|
if (imgUrl) {
|
|
const videoRes = await fetch(imgUrl);
|
|
const buf = await videoRes.arrayBuffer();
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 200,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
}).catch(() => {});
|
|
return {
|
|
success: true,
|
|
data: {
|
|
created: Math.floor(Date.now() / 1000),
|
|
data: [{ b64_json: Buffer.from(buf).toString("base64"), format: "mp4" }],
|
|
},
|
|
};
|
|
}
|
|
}
|
|
if (gen.status === "FAILED") {
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 502,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: "Leonardo video generation failed",
|
|
}).catch(() => {});
|
|
return { success: false, status: 502, error: "Leonardo video generation failed" };
|
|
}
|
|
}
|
|
saveCallLog({
|
|
method: "POST",
|
|
path: "/v1/videos/generations",
|
|
status: 504,
|
|
model: `${provider}/${model}`,
|
|
provider,
|
|
duration: Date.now() - startTime,
|
|
error: "Leonardo video generation timed out",
|
|
}).catch(() => {});
|
|
return { success: false, status: 504, error: "Leonardo video generation timed out" };
|
|
}
|
|
|
|
function sleep(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|