Skip to content

armgit / fuobe

Public Imported from GitHub
0

The open creative studio on ComfyUI: images, video, 3D and audio on open weights, on your own GPU or the cloud. Camera motions, effects, apps, Cinema, Layers, Image to 3D and an AI agent.

Catalog: Kling 4.0 in the cloud, with shots, elements and edits billed in and out

Claude27da40b0518b
diff --git a/scripts/gen-cloud-models.py b/scripts/gen-cloud-models.py
index b1839042..5d76eee7 100644
--- a/scripts/gen-cloud-models.py
+++ b/scripts/gen-cloud-models.py
@@ -68,6 +68,8 @@ IMAGE_SIZE_MAP = {
"5:4": "landscape_4_3", "4:5": "portrait_4_3",
}
RATIO = re.compile(r"^\d+(\.\d+)?:\d+(\.\d+)?$")
+# Models whose @mentioned Elements go as the API's own elements (FieldMap.elements, ModelOptions.elements).
+ELEMENT_MODELS = {"kling-4"}
# Duration picks for APIs that take any whole number of seconds in a range.
NICE_DURATIONS = [3, 4, 5, 6, 8, 10, 12, 15, 20, 30]
@@ -396,6 +398,27 @@ model("seedance-2-5", "Seedance 2.5", "ByteDance", "seedance", "video",
badges=["top", "audio", "new"], pricing=("second", 0.473, "720p"), defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "720p"},
# fal's schema gives no count for 2.5's reference clips; Replicate's 2.5 schema says up to 10 (30 s in all), as the research found.
options={"multiShot": {"mode": "prompt", "maxShots": 6}, "maxVideos": 10, "maxAudios": 10})
+# Kling 4.0 (research part 4, re-read 2026-11-01 when fal opened its API; build package nm10-kling-4): 3-30 s at 720p or
+# 1080p, per-shot prompts (multi_prompt) and @Element1.. elements on fal; Replicate's official model takes the text and
+# start/end-frame runs as a second provider (its @image_1 numbering, and no shots or elements, keep references and edits
+# on fal). The reference route's start_image_url is left out: Fuobe's references are references, not a first frame.
+# Edits keep the clip's length (duration defaults to the source's), so their routes send none. An edit, reference clips
+# and video elements bill per second of input plus output, at least twice the output (Pricing.clipInput). fal's
+# middle_image_urls (8 ordered keyframes, no times) and voice_ids aren't mapped: Frames mode stays on FLUX 3 Max, and
+# Fuobe can't make fal voice ids yet.
+_K4_EDIT = "kling/v4/video-to-video/edit"
+model("kling-4", "Kling 4.0", "Kuaishou", "kling", "video",
+ "Kuaishou's newest flagship — 3–30 s takes, multi-shot, @Elements and video edits up to 1080p",
+ [("t2v", "kling/v4/text-to-video"), ("i2v", "kling/v4/image-to-video", "fal", "+flf2v"),
+ ("ref2v", "kling/v4/reference-to-video", "fal", {"drop": ["image"]}),
+ ("v2v", _K4_EDIT, "fal", {"drop": ["duration"]}),
+ ("video-swap", _K4_EDIT, "fal", {"drop": ["duration"]}), ("video-insert", _K4_EDIT, "fal", {"drop": ["duration"]}),
+ ("t2v", "kwaivgi/kling-v4.0", "replicate", {"drop": ["image", "endImage", "images", "video"]}),
+ ("i2v", "kwaivgi/kling-v4.0", "replicate", {"drop": ["images", "video", "aspectRatio"], "flf2v": True})],
+ badges=["top", "30s", "new"], ranged_durations=True,
+ pricing=("second", 0.235, "1080p; 720p $0.157. An edit, reference clips or video elements bill $0.141/s at 1080p ($0.094 at 720p) on the seconds in plus the seconds out, at least twice the output",
+ {"byResolution": {"720p": 0.157, "1080p": 0.235}, "clipInput": {"usd": 0.141, "byResolution": {"720p": 0.094, "1080p": 0.141}}}),
+ defaults={"aspectRatio": "16:9", "duration": 5, "resolution": "1080p"})
model("seedance-2-0", "Seedance 2.0", "ByteDance", "seedance", "video",
"Smooth multi-shot motion with audio",
[("t2v", "bytedance/seedance-2.0/text-to-video"), ("i2v", "bytedance/seedance-2.0/image-to-video", "fal", "+flf2v"),
@@ -1019,11 +1042,7 @@ model("meshy-7-1", "Meshy 7.1", "Meshy", "meshy", "model3d", "Textured models wi
# ---------------------------------------------------------------------------
# Round 4 (research part 4): video erase / swap / insert, FPS boost, SDR to HDR, FFmpeg-style tools, OCR, 3D
# and the models released between 2026-09-15 and 2026-10-22.
-#
-# TODO(kling-4): Kling 4.0 (kling/v4/text-to-video, image-to-video, reference-to-video, video-to-video/edit) has
-# schemas in paid-model-apis-4.json but status "playground-only": fal's pages say "Kling 4.0 is available in the
-# playground and fal Agent. API access is coming soon." (re-checked 2026-10-22). Add a "kling-4" model here
-# (t2v / i2v + keyframes / ref2v / v2v + remove-object / video-swap / video-insert) once the API opens.
+
# What VOID and VACE regenerate in the masked area when Fuobe's prompt names the thing to remove.
SCENE_AFTER_REMOVAL = "The same shot with nothing there: the background continues naturally, matching the light, texture and motion around it"
@@ -1735,6 +1754,13 @@ def build_route(op, ep, provider, m, opts, ropts=None):
# Part 3 names for clip lists (merge-videos' video_urls, Seed Audio's reference audio_urls).
for k in ("videos", "audios"):
if k in kf and (inputs.get(kf[k]) or {}).get("type") == "array":
+ # An edit that takes its source clip and reference clips apart (Kling 4.0: video_url as @Video1, video_urls
+ # as @Video2..): the list is the reference clips (FieldMap.videos), the source stays the clip edited.
+ if k == "videos" and "video" in kf and (inputs.get(kf["video"]) or {}).get("type") != "array":
+ fmap["videos"] = kf.pop(k)
+ spec = inputs.get(fmap["videos"]) or {}
+ opts["maxVideos"] = max(opts.get("maxVideos", 0), num(spec.get("maxItems")) or 3)
+ continue
kf.setdefault(k[:-1], kf.pop(k))
for k in ["negativePrompt", "image", "images", "endImage", "mask", "video", "audio", "numOutputs", "seed", "generateAudio"]:
if k in kf:
@@ -1759,12 +1785,43 @@ def build_route(op, ep, provider, m, opts, ropts=None):
item = (inputs.get(kf["multiShot"]) or {}).get("itemSchema") or {}
dtype = "string" if (item.get("duration") or {}).get("valueType") == "string" else "number"
ms = {"key": kf["multiShot"], "durationType": dtype}
+ # Kling 4.0's shots: a prompt of up to 512 characters each, whole seconds (FieldMap.multiShot.maxPrompt / integer).
+ if num((item.get("prompt") or {}).get("maxLength")):
+ ms["maxPrompt"] = int(num(item["prompt"]["maxLength"]))
+ if (item.get("duration") or {}).get("type") == "integer":
+ ms["integer"] = True
if (inputs.get(kf["multiShot"]) or {}).get("type") == "string":
ms["json"] = True
if "shotType" in kf:
ms["shotType"] = kf["shotType"]
fmap["multiShot"] = ms
opts["multiShot"] = {"mode": "native", "maxShots": 6}
+ # Kling 4.0's elements (@Element1..): objects of a frontal image and more angles, or a clip (FieldMap.elements), with the
+ # limits the schema states: how many, how many angles, how many may be clips ("up to 3 may be video elements").
+ # Only for the models in ELEMENT_MODELS: Kling O1 / O3 record elements too, but their runs keep sending @mentions as
+ # reference images as before (moving them is its own change, with its own checks).
+ if "elements" in kf and m["id"] in ELEMENT_MODELS and (inputs.get(kf["elements"]) or {}).get("type") == "array":
+ spec = inputs.get(kf["elements"]) or {}
+ item = spec.get("itemSchema") or {}
+ frontal = next((k for k in item if "frontal" in k), None)
+ views = next((k for k, v in item.items() if (v or {}).get("type") == "array" and "image" in k), None)
+ clip = next((k for k, v in item.items() if (v or {}).get("type") == "string" and "video" in k), None)
+ if frontal and views:
+ most = int(num(spec.get("maxItems")) or 4)
+ angles = int(num((item[views] or {}).get("maxItems")) or 3)
+ clips = re.search(r"up to (\d+) may be video elements", spec.get("desc") or "")
+ el = {"key": kf["elements"], "frontal": frontal, "views": views, "max": most, "maxViews": angles}
+ if clip:
+ el["video"] = clip
+ el["maxVideos"] = int(clips[1]) if clips else most
+ fmap["elements"] = el
+ prev = opts.get("elements") or {}
+ # Voices need the provider's voice ids (fal's Kling create-voice), which Fuobe can't make yet: never sent.
+ opts["elements"] = {"max": max(prev.get("max", 0), most), "views": max(prev.get("views", 0), angles),
+ "videos": max(prev.get("videos", 0), el.get("maxVideos", 0)), "voices": False,
+ "ops": union(prev.get("ops", []), [op])}
+ else:
+ warn(f"{m['id']}: {ep} elements have no frontal image and angle list")
if "draft" in kf and op in ("t2v", "i2v", "ref2v"):
fmap["draft"] = kf["draft"]
opts["draft"] = True
diff --git a/src/components/studio/composer.tsx b/src/components/studio/composer.tsx
index e9252146..fe3f205f 100644
--- a/src/components/studio/composer.tsx
+++ b/src/components/studio/composer.tsx
@@ -19,7 +19,7 @@ import { DEFAULT_LOOK, lookCard } from "@/lib/catalog/soul-cards";
import { formatsOf } from "@/lib/av/formats";
import { CONNECT_GPU_EVENT, enhance, useClipFacts, useCreateGeneration, useElements, useEngine, useHydrated, useStatus } from "@/lib/api";
import { usePagePlace } from "@/components/gpu/use-page-place";
-import { applyMentions, type StudioElement } from "@/lib/catalog/elements";
+import { applyMentions, elementsNote, type StudioElement } from "@/lib/catalog/elements";
import { applySketch, stripMotionPaths } from "@/lib/catalog/sketch";
import {
chainGapProblem,
@@ -740,7 +740,7 @@ export function Composer({ docked }: { docked: boolean }) {
// Enhance writes a scene; a tool's optional words (FLUX.3 Upscale's details) stay as typed.
const baseShape = settingsShape(model, effectiveOp, config.kind, showPrompt && !config.hidePrompt, p, config.ops, studioFormats);
const shape = framesCtx ? framesShape(baseShape, framesCtx.chained) : baseShape;
- const outcome = config.clipFacts && draft.slots.video?.ref ? clipOutcome(effectiveOp, facts, p, model) : null;
+ const outcome = config.clipFacts && draft.slots.video?.ref ? clipOutcome(effectiveOp, facts, p, model, today) : null;
const video = draft.slots.video?.ref;
const alternative = config.comfyOnly?.alternative;
const alternativeHref = alternative && `${alternative.href}${video?.startsWith("/api/files/") ? `&video=${encodeURIComponent(video)}` : ""}`;
@@ -1080,6 +1080,7 @@ export function Composer({ docked }: { docked: boolean }) {
placeholder={preset?.promptPlaceholder ?? (config.hidePrompt && config.modelPrompt ? config.modelPrompt : config.placeholder)}
elements={elements}
collapsed={collapsed}
+ elementsNote={elementsNote(model)}
/>
)}
diff --git a/src/components/studio/model-picker.tsx b/src/components/studio/model-picker.tsx
index fd4964d8..535ec824 100644
--- a/src/components/studio/model-picker.tsx
+++ b/src/components/studio/model-picker.tsx
@@ -35,6 +35,7 @@ const BADGE_LABEL: Record<string, string> = {
open: "Open",
uncensored: "Uncensored",
beta: "Beta",
+ "30s": "30 s",
};
export function ModelBadges({ model, max }: { model: ModelDef; max?: number }) {
@@ -85,6 +86,7 @@ function ModelRow({
gpuName,
needs,
made,
+ edits,
}: {
m: ModelDef;
selected: boolean;
@@ -100,6 +102,8 @@ function ModelRow({
needs?: CloudProvider[] | null;
/** The active preset's live preview was made with this model. */
made?: boolean;
+ /** The studio edits clips (Edit video): the price is an edit's, on the seconds in and out (Kling 4.0). */
+ edits?: boolean;
}) {
return (
<>
@@ -149,7 +153,7 @@ function ModelRow({
<span className="max-sm:hidden">{addKeyLabel(needs[0])}</span>
</span>
) : (
- <span className="shrink-0 text-right text-[11px] text-muted-foreground tabular-nums">{pickerPrice(m, today)}</span>
+ <span className="shrink-0 text-right text-[11px] text-muted-foreground tabular-nums">{pickerPrice(m, today, edits)}</span>
)}
{/* Pointer only: inside an option it would be a nested control. Keyboard: Alt+S on the highlighted row (starKey). */}
<button
@@ -289,6 +293,8 @@ function PickerList({
const [recent] = useStoredList(RECENT_MODELS);
const [starred, setStarred] = useStoredList(STARRED_MODELS);
const today = useToday();
+ // A studio for clip edits (Edit video: its first operation edits a clip) prices models as an edit bills.
+ const editsClips = ops?.[0] === "v2v" || ops?.[0] === "video-swap" || ops?.[0] === "video-insert";
const engines = useMemo<Engine[]>(() => (mode === "both" ? ["cloud", "open"] : [mode]), [mode]);
// "Best" ranks models that do what the studio is for, not single-purpose tools.
// A preset's recipe leads, when it runs on this engine.
@@ -397,6 +403,7 @@ function PickerList({
gpuName={badges?.gpu}
needs={needsKey(m, status)}
made={m.id === madeWith}
+ edits={editsClips}
/>
</CommandItem>
))}
diff --git a/src/components/studio/prompt-input.tsx b/src/components/studio/prompt-input.tsx
index 309e940e..fce60f8d 100644
--- a/src/components/studio/prompt-input.tsx
+++ b/src/components/studio/prompt-input.tsx
@@ -58,8 +58,10 @@ export const PromptInput = forwardRef<
className?: string;
/** Docked and not focused: keep the prompt to one line. */
collapsed?: boolean;
+ /** What the model does with an @mention, under the menu's heading (Kling 4.0: "Up to 7 as Kling elements · voices: not yet"). */
+ elementsNote?: string;
}
->(function PromptInput({ value, onChange, onSubmit, placeholder, elements, className, collapsed }, ref) {
+>(function PromptInput({ value, onChange, onSubmit, placeholder, elements, className, collapsed, elementsNote }, ref) {
const ta = useRef<HTMLTextAreaElement>(null);
const mirror = useRef<HTMLDivElement>(null);
const [caret, setCaret] = useState<number | null>(null);
@@ -220,6 +222,7 @@ export const PromptInput = forwardRef<
<p className="flex items-center gap-1.5 px-2 pt-1.5 pb-1 text-[11px] font-medium tracking-wide text-muted-foreground uppercase">
<AtSign className="size-3" /> Elements
</p>
+ {elementsNote && <p className="px-2 pb-1.5 text-[11px] leading-snug text-muted-foreground">{elementsNote}</p>}
{matches.map((el, i) => {
const Icon = ELEMENT_ICONS[el.kind];
return (
diff --git a/src/lib/catalog/clip-windows.ts b/src/lib/catalog/clip-windows.ts
index 74504aec..d81814be 100644
--- a/src/lib/catalog/clip-windows.ts
+++ b/src/lib/catalog/clip-windows.ts
@@ -6,6 +6,8 @@
*/
const SOURCE_SECONDS: Record<string, { min?: number; max?: number }> = {
"kling-o3-4k-edit": { min: 3, max: 15 },
+ // fal: "3-30 s" (up to 30.05 s), 300 MB, 700-4553 px a side (research part 4, re-read 2026-11-01).
+ "kling-4": { min: 3, max: 30 },
// It reads 3–60 s but returns at most the first 15 s.
"happy-horse-video-edit": { min: 3, max: 15 },
"runway-aleph-2": { min: 2, max: 30 },
@@ -18,6 +20,19 @@ export function sourceSeconds(modelId: string): { min?: number; max?: number } {
return SOURCE_SECONDS[modelId] ?? {};
}
+/**
+ * The most seconds of clips a run takes in all, where the model says (Kling 4.0: "the source, reference and element
+ * videos must total at most 30s").
+ */
+const CLIP_TOTAL_SECONDS: Record<string, number> = { "kling-4": 30 };
+
+/** Why clips `seconds` long in all are too long for the model ("Kling 4.0 takes 30 s of clips in all…"), or null. */
+export function clipTotalProblem(model: { id: string; name: string }, seconds: number): string | null {
+ const max = CLIP_TOTAL_SECONDS[model.id];
+ if (max === undefined || seconds <= max + 0.05) return null;
+ return `${model.name} takes ${max} s of clips in all (the clip you edit, reference clips and clip elements together), and these add up to ${secs(seconds)}: trim them first`;
+}
+
const secs = (n: number) => `${Math.round(n * 10) / 10} s`;
/**
diff --git a/src/lib/catalog/cloud-models.generated.ts b/src/lib/catalog/cloud-models.generated.ts
index 0c085ea4..33fee1c3 100644
--- a/src/lib/catalog/cloud-models.generated.ts
+++ b/src/lib/catalog/cloud-models.generated.ts
@@ -4106,6 +4106,277 @@ export const CLOUD_MODELS: ModelDef[] = [
"note": "720p"
}
},
+ {
+ "id": "kling-4",
+ "name": "Kling 4.0",
+ "vendor": "Kuaishou",
+ "family": "kling",
+ "engine": "cloud",
+ "kind": "video",
+ "tagline": "Kuaishou's newest flagship \u2014 3\u201330 s takes, multi-shot, @Elements and video edits up to 1080p",
+ "routes": [
+ {
+ "op": "t2v",
+ "provider": "fal",
+ "endpoint": "kling/v4/text-to-video",
+ "map": {
+ "multiShot": {
+ "key": "multi_prompt",
+ "durationType": "number",
+ "maxPrompt": 512,
+ "integer": true
+ },
+ "aspectRatio": "aspect_ratio",
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ },
+ {
+ "op": "i2v",
+ "provider": "fal",
+ "endpoint": "kling/v4/image-to-video",
+ "map": {
+ "image": "start_image_url",
+ "endImage": "end_image_url",
+ "multiShot": {
+ "key": "multi_prompt",
+ "durationType": "number",
+ "maxPrompt": 512,
+ "integer": true
+ },
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ },
+ {
+ "op": "flf2v",
+ "provider": "fal",
+ "endpoint": "kling/v4/image-to-video",
+ "map": {
+ "image": "start_image_url",
+ "endImage": "end_image_url",
+ "multiShot": {
+ "key": "multi_prompt",
+ "durationType": "number",
+ "maxPrompt": 512,
+ "integer": true
+ },
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ },
+ {
+ "op": "ref2v",
+ "provider": "fal",
+ "endpoint": "kling/v4/reference-to-video",
+ "map": {
+ "images": "image_urls",
+ "videos": "video_urls",
+ "multiShot": {
+ "key": "multi_prompt",
+ "durationType": "number",
+ "maxPrompt": 512,
+ "integer": true
+ },
+ "elements": {
+ "key": "elements",
+ "frontal": "frontal_image_url",
+ "views": "reference_image_urls",
+ "max": 7,
+ "maxViews": 3,
+ "video": "video_url",
+ "maxVideos": 3
+ },
+ "aspectRatio": "aspect_ratio",
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ },
+ {
+ "op": "v2v",
+ "provider": "fal",
+ "endpoint": "kling/v4/video-to-video/edit",
+ "map": {
+ "videos": "video_urls",
+ "images": "image_urls",
+ "video": "video_url",
+ "elements": {
+ "key": "elements",
+ "frontal": "frontal_image_url",
+ "views": "reference_image_urls",
+ "max": 7,
+ "maxViews": 3,
+ "video": "video_url",
+ "maxVideos": 3
+ },
+ "resolution": "resolution"
+ }
+ },
+ {
+ "op": "video-swap",
+ "provider": "fal",
+ "endpoint": "kling/v4/video-to-video/edit",
+ "map": {
+ "videos": "video_urls",
+ "images": "image_urls",
+ "video": "video_url",
+ "elements": {
+ "key": "elements",
+ "frontal": "frontal_image_url",
+ "views": "reference_image_urls",
+ "max": 7,
+ "maxViews": 3,
+ "video": "video_url",
+ "maxVideos": 3
+ },
+ "resolution": "resolution"
+ }
+ },
+ {
+ "op": "video-insert",
+ "provider": "fal",
+ "endpoint": "kling/v4/video-to-video/edit",
+ "map": {
+ "videos": "video_urls",
+ "images": "image_urls",
+ "video": "video_url",
+ "elements": {
+ "key": "elements",
+ "frontal": "frontal_image_url",
+ "views": "reference_image_urls",
+ "max": 7,
+ "maxViews": 3,
+ "video": "video_url",
+ "maxVideos": 3
+ },
+ "resolution": "resolution"
+ }
+ },
+ {
+ "op": "t2v",
+ "provider": "replicate",
+ "endpoint": "kwaivgi/kling-v4.0",
+ "map": {
+ "aspectRatio": "aspect_ratio",
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ },
+ {
+ "op": "i2v",
+ "provider": "replicate",
+ "endpoint": "kwaivgi/kling-v4.0",
+ "map": {
+ "image": "start_image",
+ "endImage": "end_image",
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ },
+ {
+ "op": "flf2v",
+ "provider": "replicate",
+ "endpoint": "kwaivgi/kling-v4.0",
+ "map": {
+ "image": "start_image",
+ "endImage": "end_image",
+ "resolution": "resolution",
+ "duration": {
+ "key": "duration",
+ "type": "number"
+ }
+ }
+ }
+ ],
+ "options": {
+ "multiShot": {
+ "mode": "native",
+ "maxShots": 6
+ },
+ "aspectRatios": [
+ "16:9",
+ "9:16",
+ "1:1",
+ "21:9",
+ "auto"
+ ],
+ "resolutions": [
+ "720p",
+ "1080p"
+ ],
+ "durations": [
+ 3,
+ 4,
+ 5,
+ 6,
+ 8,
+ 10,
+ 12,
+ 15,
+ 20,
+ 30
+ ],
+ "endFrame": true,
+ "maxImages": 10,
+ "maxVideos": 5,
+ "elements": {
+ "max": 7,
+ "views": 3,
+ "videos": 3,
+ "voices": false,
+ "ops": [
+ "ref2v",
+ "v2v",
+ "video-swap",
+ "video-insert"
+ ]
+ }
+ },
+ "badges": [
+ "top",
+ "30s",
+ "new"
+ ],
+ "defaults": {
+ "aspectRatio": "16:9",
+ "duration": 5,
+ "resolution": "1080p"
+ },
+ "pricing": {
+ "unit": "second",
+ "usd": 0.235,
+ "note": "1080p; 720p $0.157. An edit, reference clips or video elements bill $0.141/s at 1080p ($0.094 at 720p) on the seconds in plus the seconds out, at least twice the output",
+ "byResolution": {
+ "720p": 0.157,
+ "1080p": 0.235
+ },
+ "clipInput": {
+ "usd": 0.141,
+ "byResolution": {
+ "720p": 0.094,
+ "1080p": 0.141
+ }
+ }
+ }
+ },
{
"id": "seedance-2-0",
"name": "Seedance 2.0",
diff --git a/src/lib/catalog/elements.ts b/src/lib/catalog/elements.ts
index 998ae052..a497780d 100644
--- a/src/lib/catalog/elements.ts
+++ b/src/lib/catalog/elements.ts
@@ -4,7 +4,8 @@
* server (authoritative), the composer (live preview + cost) and the agent share it.
*/
import { identityFor, type TrainingFamily } from "./training";
-import type { Engine, GenerationRequest, LoraRef, ModelDef, Operation } from "./types";
+import { imageLimit } from "./plan";
+import type { Engine, GenParams, GenerationRequest, LoraRef, ModelDef, Operation } from "./types";
export type ElementKind = "character" | "location" | "prop" | "style" | "voice";
@@ -61,6 +62,16 @@ export interface StudioElement {
createdAt: number;
}
+/**
+ * What a model does with @mentioned Elements, for the mention menu, when it has elements of its own (Kling 4.0): how many,
+ * which kinds, and that voices aren't sent yet (they need the provider's voice ids, which Fuobe can't make).
+ */
+export function elementsNote(model: Pick<ModelDef, "name" | "options"> | undefined): string | undefined {
+ const e = model?.options.elements;
+ if (!e) return undefined;
+ return `${model!.name}: characters and props go as its elements, up to ${e.max} (a photo and ${e.views} more angles, or a clip) · voices: not yet`;
+}
+
/** `Maya Lopez` → `Maya_Lopez`. Letters, digits, `_` and `-` only. */
export function handleFor(name: string): string {
return (
@@ -103,6 +114,30 @@ export interface MentionResolution {
const ops = (m: ModelDef) => new Set(m.routes.map((r) => r.op));
+/** A reference that is a clip (a video element), by its file's extension. */
+const isClipRef = (ref: string) => /\.(mp4|mov|m4v|webm)(\?|#|$)/i.test(ref);
+
+/** Element kinds a model's own elements stand for (Kling 4.0: "characters/objects"). */
+const ELEMENT_KINDS_AS_ELEMENTS = new Set<ElementKind>(["character", "prop"]);
+
+/**
+ * Which mentioned Elements go as the model's own elements (ModelOptions.elements), and on which route: the run's own
+ * operation when it takes elements (an edit), else reference-to-video for a clip from words alone (as references do,
+ * never in place of a start or end frame). Null when the model has none, or nothing mentioned fits.
+ */
+function elementPlan(req: GenerationRequest, model: ModelDef, mentioned: StudioElement[], op: Operation | undefined) {
+ const spec = model.options.elements;
+ if (!spec) return null;
+ const takes = new Set(spec.ops);
+ const existing = req.inputs?.images?.length ?? 0;
+ const target: Operation | undefined =
+ op && takes.has(op) ? op : takes.has("ref2v") && model.kind === "video" && (!op || op === "t2v") && !existing && !req.inputs?.endImage ? "ref2v" : undefined;
+ if (!target) return null;
+ const fit = mentioned.filter((e) => ELEMENT_KINDS_AS_ELEMENTS.has(e.kind) && e.references.length);
+ if (!fit.length) return null;
+ return { op: target, elements: fit.slice(0, spec.max), left: fit.slice(spec.max) };
+}
+
/**
* Turn `@handle` mentions into reference images (or a trained LoRA + trigger word) and a
* prompt that tells the model which image is which. Leaves the request alone when nothing
@@ -142,8 +177,15 @@ export function applyMentions(req: GenerationRequest, model: ModelDef, elements:
viaLora.add(el.id);
}
+ // Kling 4.0 takes characters and props as its own elements (@Element1..: a frontal photo and up to 3 more angles, or a
+ // short clip), on the routes that have them; locations and styles stay reference images.
+ const asElement = elementPlan(req, model, mentioned.filter((e) => !viaLora.has(e.id)), op);
+ if (asElement) op = asElement.op;
+ const elementNo = new Map<string, number>((asElement?.elements ?? []).map((e, i) => [e.id, i + 1]));
+ if (asElement) budget = Math.max(0, (imageLimit(model, asElement.op) ?? model.options.maxImages ?? 4) - existing.length);
+
// Share the reference budget: one image each first, then fill up to each kind's ideal count.
- const wanted = mentioned.filter((e) => !viaLora.has(e.id) && e.references.length);
+ const wanted = mentioned.filter((e) => !viaLora.has(e.id) && !elementNo.has(e.id) && e.references.length);
const take = new Map<string, number>(wanted.map((e) => [e.id, 0]));
let left = budget;
for (let round = 0; left > 0; round++) {
@@ -170,13 +212,29 @@ export function applyMentions(req: GenerationRequest, model: ModelDef, elements:
}
positions.set(e.id, pos);
}
- if (model.kind === "video" && images.length > existing.length) op = "ref2v";
+ if (model.kind === "video" && images.length > existing.length && !asElement) op = "ref2v";
+ // The elements' files go after every reference image, so the references keep the numbers the legend gives them.
+ const groups: NonNullable<GenParams["elements"]> = [];
+ const videos = [...(req.inputs?.videos ?? [])];
+ for (const el of asElement?.elements ?? []) {
+ const clip = el.references.find(isClipRef);
+ if (clip && groups.filter((g) => g.video !== undefined).length < (model.options.elements?.videos ?? 0)) {
+ videos.push(clip);
+ groups.push({ video: videos.length - 1 });
+ continue;
+ }
+ const photos = el.references.filter((r) => !isClipRef(r)).slice(0, 1 + (model.options.elements?.views ?? 3));
+ const at = photos.map((r) => images.push(r) - 1);
+ groups.push({ images: at });
+ }
// Rewrite the prompt: "@Maya" → "Maya", plus who/what each image is.
const seen = new Set<string>();
const rewrite = (text: string) => text.replace(MENTION, (whole, h: string) => {
const el = mentioned.find((e) => e.handle.toLowerCase() === h.toLowerCase());
if (!el) return whole;
+ // An element is named as the model names it.
+ if (elementNo.has(el.id)) return `@Element${elementNo.get(el.id)}`;
const first = !seen.has(el.id);
seen.add(el.id);
const lora = loras.find((l) => viaLora.has(el.id) && el.loras.some((x) => x.file === l.file));
@@ -202,8 +260,9 @@ export function applyMentions(req: GenerationRequest, model: ModelDef, elements:
.filter(Boolean);
if (legend.length) prompt = `${prompt.trim().replace(/[.\s]+$/, "")}${prompt.trim() ? ". " : ""}${legend.join(". ")}.`;
+ for (const e of asElement?.left ?? []) notes.push(`${e.name} is described in words — ${model.name} takes up to ${model.options.elements?.max} elements`);
for (const e of mentioned) {
- if (viaLora.has(e.id)) continue;
+ if (viaLora.has(e.id) || elementNo.has(e.id)) continue;
if (!positions.get(e.id)?.length) {
notes.push(
budget === 0
@@ -218,9 +277,9 @@ export function applyMentions(req: GenerationRequest, model: ModelDef, elements:
...req,
op,
prompt,
- inputs: { ...req.inputs, images: images.length ? images : undefined },
+ inputs: { ...req.inputs, images: images.length ? images : undefined, ...(videos.length > (req.inputs?.videos?.length ?? 0) && { videos }) },
loras: loras.length ? loras : undefined,
- params: newShots ? { ...req.params, shots: newShots } : req.params,
+ params: { ...req.params, ...(newShots && { shots: newShots }), ...(groups.length && { elements: groups }) },
},
mentioned,
notes,
diff --git a/src/lib/catalog/payload.ts b/src/lib/catalog/payload.ts
index 8726545d..9b56819d 100644
--- a/src/lib/catalog/payload.ts
+++ b/src/lib/catalog/payload.ts
@@ -315,6 +315,39 @@ function zoomValue(z: NonNullable<FieldMap["zoom"]>, input: GenInput): Record<st
return out;
}
+/** `text` cut to `max` characters, at a word where one is near the end (a shot's prompt: Kling 4.0 takes 512). */
+function clipWords(text: string, max: number): string {
+ if (text.length <= max) return text;
+ const cut = text.slice(0, max);
+ const space = cut.lastIndexOf(" ");
+ return (space > max * 0.8 ? cut.slice(0, space) : cut).replace(/[\s,;:.]+$/, "");
+}
+
+/**
+ * Kling 4.0's elements (@Element1..) from params.elements: each group's images (its first the frontal view, the next
+ * ones more angles) or its clip, up to the API's limits (7 elements, 3 angles, 3 clips); the rest are left out. Returns
+ * the list and the images and clips it took, which leave the image and clip lists so the rest keep their numbers.
+ */
+function elementList(e: NonNullable<FieldMap["elements"]>, images: string[], videos: string[], groups: NonNullable<GenInput["elements"]>) {
+ const usedImages = new Set<number>();
+ const usedVideos = new Set<number>();
+ const list: Record<string, unknown>[] = [];
+ for (const g of groups) {
+ if (list.length >= e.max) break;
+ if (g.video !== undefined && e.video && videos[g.video] !== undefined && !usedVideos.has(g.video) && usedVideos.size < (e.maxVideos ?? e.max)) {
+ list.push({ [e.video]: videos[g.video] });
+ usedVideos.add(g.video);
+ continue;
+ }
+ const own = (g.images ?? []).filter((i) => images[i] !== undefined && !usedImages.has(i));
+ if (!own.length) continue;
+ const views = own.slice(1, 1 + e.maxViews);
+ list.push({ [e.frontal]: images[own[0]], ...(views.length && { [e.views]: views.map((i) => images[i]) }) });
+ for (const i of [own[0], ...views]) usedImages.add(i);
+ }
+ return { list, usedImages, usedVideos };
+}
+
/** Build a provider payload from canonical input using a route's {@link FieldMap}. Pure + unit-tested. */
export function buildPayload(map: FieldMap, input: GenInput): Record<string, unknown> {
const out: Record<string, unknown> = {};
@@ -366,8 +399,13 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk
if (map.multiShot && (input.shots?.length || input.multiShot === "auto")) {
const ms = map.multiShot;
if (input.shots?.length) {
- const shots = input.shots.map((s) => ({ prompt: s.prompt, duration: ms.durationType === "string" ? String(s.duration) : s.duration }));
+ const shots = input.shots.map((s) => {
+ // Whole seconds where the API takes them (Kling 4.0): the take is as long as its shots, so the duration follows.
+ const seconds = ms.integer ? Math.max(1, Math.round(s.duration)) : s.duration;
+ return { prompt: ms.maxPrompt ? clipWords(s.prompt, ms.maxPrompt) : s.prompt, duration: ms.durationType === "string" ? String(seconds) : seconds };
+ });
out[ms.key] = ms.json ? JSON.stringify(shots) : shots;
+ if (ms.integer && map.duration) out[map.duration.key] = timeValue(map.duration, shots.reduce((n, s) => n + Number(s.duration), 0));
if (map.prompt !== false) delete out[map.prompt ?? "prompt"];
if (ms.shotType) out[ms.shotType] = "customize";
} else if (ms.shotType) {
@@ -376,6 +414,20 @@ export function buildPayload(map: FieldMap, input: GenInput): Record<string, unk
if (ms.flag) out[ms.flag] = true;
}
if (map.draft && input.draft) out[map.draft] = true;
+ if (map.elements && input.elements?.length) {
+ const { list, usedImages, usedVideos } = elementList(map.elements, images, input.videos ?? [], input.elements);
+ if (list.length) {
+ out[map.elements.key] = list;
+ const rest = (key: string | undefined, all: string[], used: Set<number>) => {
+ if (!key || !used.size) return;
+ const left = all.filter((_, i) => !used.has(i));
+ if (left.length) out[key] = left;
+ else delete out[key];
+ };
+ rest(map.images, images, usedImages);
+ rest(map.videos, input.videos ?? [], usedVideos);
+ }
+ }
// Voices, dialogue and dubbing.
if (map.voice && input.voice) setPath(out, map.voice, input.voice);
if (map.voiceAudio && input.voiceAudio) out[map.voiceAudio] = input.voiceAudio;
diff --git a/src/lib/catalog/plan.ts b/src/lib/catalog/plan.ts
index 3e6f67d3..0f879748 100644
--- a/src/lib/catalog/plan.ts
+++ b/src/lib/catalog/plan.ts
@@ -387,6 +387,9 @@ export function planGeneration(
prompt = `${prompt.replace(/[.\s]+$/, "")}. Multi-shot sequence: tell it in several distinct shots with clean cuts between them.`;
}
op = op ?? inferOperation(model, req);
+ // Reference clips and video elements on a model that bills them with the output (Kling 4.0, Pricing.clipInput): priced
+ // at the least they bill (twice the output) until the server reads their length (params.clipSeconds).
+ if (model.pricing?.clipInput && req.inputs?.videos?.length && params.clipSeconds === undefined) params = { ...params, clipSeconds: 0 };
if (!routesFor(model, op).length) {
throw new Error(`${model.name} can't do ${op} — try another model`);
}
@@ -713,6 +716,43 @@ export function clipEditSeconds(model: Pick<ModelDef, "id" | "options" | "routes
return max !== undefined ? Math.min(seconds, max) : seconds;
}
+/** The edits of a clip that keep its length: the clip goes in whole, and the result is as long (Kling 4.0's edit). */
+const CLIP_EDIT_OPS = new Set<Operation>(["v2v", "video-swap", "video-insert", "remove-object"]);
+
+export interface ClipBilling {
+ /** Seconds of clips going in: the edited clip's and the reference clips'. */
+ input: number;
+ output: number;
+ /** What's billed: input plus output, at least twice the output. */
+ billed: number;
+ /** Per billed second. */
+ rate: number;
+ /** The input's length isn't known yet (no clip header read): priced at the least it bills, twice the output. */
+ guessed: boolean;
+}
+
+/**
+ * How a run with a clip going in is billed, on a model that bills those runs on input plus output (Pricing.clipInput,
+ * Kling 4.0): an edit of a clip (its length, params.sourceDuration, in and out: the edit keeps it), or a run with
+ * reference clips or video elements (params.clipSeconds: their seconds; 0 while they aren't read yet). Undefined for
+ * a run with no clip, or a model that bills them as any other.
+ */
+export function clipBilling(model: Pick<ModelDef, "pricing" | "defaults">, params: GenParams, op?: Operation, now?: PriceClock): ClipBilling | undefined {
+ const p = model.pricing && pricingOn(model.pricing, now);
+ const c = p?.clipInput;
+ if (!c || p.unit !== "second") return undefined;
+ const edit = !!op && CLIP_EDIT_OPS.has(op);
+ if (!edit && params.clipSeconds === undefined) return undefined;
+ const res = params.resolution ?? model.defaults?.resolution;
+ const rate = (res && (c.byResolution?.[res] ?? c.byResolution?.[res.toLowerCase()])) || c.usd;
+ const source = params.sourceDuration && params.sourceDuration > 0 ? params.sourceDuration : undefined;
+ const output = edit ? (source ?? params.duration ?? model.defaults?.duration ?? 5) : (params.duration ?? model.defaults?.duration ?? 5);
+ const refs = Math.max(0, params.clipSeconds ?? 0);
+ const guessed = edit ? !source : !refs;
+ const input = (edit ? (source ?? output) : 0) + refs;
+ return { input, output, billed: Math.max(input + output, 2 * output), rate, guessed };
+}
+
/**
* The seconds a talking avatar is made (and billed) for a voice `seconds` long: as long as the voice, or what a
* frame-count route's limits make of it, in the seconds it bills (fal's InfiniteTalk: 41–721 frames, 25 a second; Wan 2.2
@@ -823,7 +863,9 @@ export function estimateCost(model: ModelDef, params: GenParams, jobs = 1, op?:
: (routeMegapixels(model, params, op) ?? sentMegapixels(params) ?? 1);
per = usd * (p.roundUp ? Math.ceil(mp - 1e-9) : mp) * n;
}
- if (p.unit === "second") {
+ const clipped = p.unit === "second" ? clipBilling(model, params, op, now) : undefined;
+ if (clipped) per = clipped.rate * clipped.billed;
+ else if (p.unit === "second") {
// A length the caller set wins (Shorts, Mixed Media and Genjutsu say the seconds they bill); then a clip edit's clip.
const seconds = clip ?? voice ?? params.duration ?? clipEditSeconds(model, params, op) ?? model.defaults?.duration ?? 5;
const mp = p.videoMegapixel ? videoMegapixels(model, params, seconds) : undefined;
diff --git a/src/lib/catalog/types.ts b/src/lib/catalog/types.ts
index a804346a..bb99af38 100644
--- a/src/lib/catalog/types.ts
+++ b/src/lib/catalog/types.ts
@@ -318,7 +318,23 @@ export interface FieldMap {
/** Language to translate into (dubbing). */
targetLanguage?: string;
/** Native multi-shot: an array of {prompt, duration} (Kling's `multi_prompt`). */
- multiShot?: { key: string; durationType: "string" | "number"; json?: boolean; shotType?: string; flag?: string };
+ multiShot?: {
+ key: string;
+ durationType: "string" | "number";
+ json?: boolean;
+ shotType?: string;
+ flag?: string;
+ /** The most characters a shot's prompt takes (Kling 4.0: 512); a longer one is cut at a word. */
+ maxPrompt?: number;
+ /** Shot lengths in whole seconds (rounded, at least 1). */
+ integer?: true;
+ };
+ /**
+ * Kling 4.0's elements (@Element1..): a list of objects, each a frontal image with up to `views` more angles, or a
+ * clip (`video`). Filled from params.elements, which groups some of inputs.images / inputs.videos into elements: those
+ * leave the image and clip lists, so the rest keep their @Image / @Video numbers.
+ */
+ elements?: { key: string; frontal: string; views: string; video?: string; max: number; maxViews: number; maxVideos?: number };
/** Boolean draft switch (Seedance 2.5 renders a cheap 480p take and returns a draft id). */
draft?: string;
/** Field that takes the draft id to finish. */
@@ -529,7 +545,8 @@ export interface ModelRoute {
maxImages?: number;
}
-export type Badge = "new" | "top" | "fast" | "audio" | "4k" | "hd" | "pro" | "open" | "uncensored" | "beta";
+/** "30s": takes of up to 30 s in one call (Kling 4.0). */
+export type Badge = "new" | "top" | "fast" | "audio" | "4k" | "hd" | "pro" | "open" | "uncensored" | "beta" | "30s";
export interface ModelOptions {
aspectRatios?: string[];
@@ -546,6 +563,12 @@ export interface ModelOptions {
endFrame?: boolean;
/** Multi-shot support: "native" sends per-shot prompts, "prompt" writes the shots into one prompt. */
multiShot?: { mode: "native" | "prompt" | "concat"; maxShots: number };
+ /**
+ * @mentioned Elements go as the model's own elements (Kling 4.0's @Element1..): up to `max`, each a frontal image and up
+ * to `views` more angles, or a clip (up to `videos` of them). `voices`: a voice can be bound to one (false: Fuobe has no
+ * way to make the provider's voice ids yet, so voices aren't sent).
+ */
+ elements?: { max: number; views: number; videos: number; voices: false; ops: Operation[] };
/** Draft mode (cheap preview, then a full render of the take you like). */
draft?: boolean;
/**
@@ -673,6 +696,12 @@ export interface Pricing {
roundUp?: true;
/** What an animation preset adds to a run (params.animation: Meshy rigging +$0.12). */
animationUsd?: number;
+ /**
+ * A run with a clip going in (an edit's source, reference clips, video elements: Kling 4.0) bills this rate per second
+ * of input plus output, at least twice the output (fal and Replicate: "2x output if input is shorter than output,
+ * otherwise input + output"), in place of `usd` / `byResolution`.
+ */
+ clipInput?: { usd: number; byResolution?: Record<string, number> };
}
/** A model's weights licence, as read in the research: information, never a gate (the owner's decision of 2026-10-27). */
@@ -747,6 +776,13 @@ export interface GenParams {
targetLanguage?: string;
/** Multi-shot: shots in order (empty/undefined = one shot). "auto" lets the model cut by itself. */
shots?: { prompt: string; duration: number }[];
+ /**
+ * @mentioned Elements as the model's elements (ModelOptions.elements, FieldMap.elements): each groups inputs.images by
+ * index (0-based; the first is its frontal view), or names one of inputs.videos (a video element).
+ */
+ elements?: { images?: number[]; video?: number }[];
+ /** Seconds of the reference clips that go in (Kling 4.0 bills them with the output: Pricing.clipInput). */
+ clipSeconds?: number;
multiShot?: "auto";
/** Render a cheap draft first (Seedance 2.5 draft mode). */
draft?: boolean;
diff --git a/src/lib/composer.ts b/src/lib/composer.ts
index 22490cdf..6392098f 100644
--- a/src/lib/composer.ts
+++ b/src/lib/composer.ts
@@ -8,12 +8,14 @@ import { fpsPlan, fpsSummary } from "./av/fps";
import { targetShortEdge, upscaledSize, upscaleFactorFor, upscaleTier } from "./av/upscale";
import { wholeClipProblem, wholeClipTool } from "./av/video-finish";
import { clipWindowProblem } from "./catalog/clip-windows";
+import { clipBilling } from "./catalog/plan";
import { addFrameAt, frameTimes, framesInputs, removeFrameAt, spread, type FrameSupport } from "./catalog/keyframes";
import { FACE_MOSAIC_MODELS } from "./catalog/open-tools";
import { pricingOn, type PriceClock } from "./catalog/promo";
import { soulPostStep } from "./catalog/soul";
import { appModels, ownRoute, presetRoutes, type HasModel, type RecipePreset } from "./catalog/preset-recipe-routes";
import { COLORMAPS, type Engine, type GenParams, type InputSlot, type MatteOutput, type MediaKind, type ModelDef, type Operation, type Preset, type PresetRoute, type VideoFormat } from "./catalog/types";
+import { formatCost } from "./format";
import { spokenLanguageName } from "./speech-languages";
// ---------------------------------------------------------------------------
@@ -203,7 +205,8 @@ export function clipOutcome(
op: Operation | undefined,
facts: { width?: number; height?: number; fps?: number; duration?: number } | undefined,
params: GenParams,
- model: (Pick<ModelDef, "engine" | "options" | "defaults"> & Partial<Pick<ModelDef, "name" | "routes">>) | undefined,
+ model: (Pick<ModelDef, "engine" | "options" | "defaults"> & Partial<Pick<ModelDef, "name" | "routes" | "pricing">>) | undefined,
+ now?: PriceClock,
): string | null {
if (!facts || !model) return null;
const { width, height, fps, duration } = facts;
@@ -267,6 +270,12 @@ export function clipOutcome(
} else if (f === "exr" && duration && fps) frames = ` (${Math.round(duration * fps)} frames)`;
return info ? `${head} → ${info.short}${frames}, .${info.ext}` : head;
}
+ // An edit billed on the seconds in and out (Kling 4.0): what's billed, before the total.
+ const billing = duration && model.engine === "cloud" ? clipBilling(model, { ...params, sourceDuration: duration }, op, now) : undefined;
+ if (billing) {
+ const twice = billing.input < billing.output ? " (at least twice the output)" : "";
+ return `${clipSeconds(billing.input)} in + ${clipSeconds(billing.output)} out: billed on ${clipSeconds(billing.billed)}${twice} at ${formatCost(billing.rate)}/s`;
+ }
return null;
}
diff --git a/src/lib/model-rows.ts b/src/lib/model-rows.ts
index 4fe91436..72b3b4d7 100644
--- a/src/lib/model-rows.ts
+++ b/src/lib/model-rows.ts
@@ -98,9 +98,11 @@ const PICKER_UNIT = { image: "/image", second: "/sec", video: "/video", request:
* The model picker's short price ("$0.05/sec", "Free"), at `now` (./catalog/promo): the launch price while it holds,
* nothing for a launch-priced model while no clock may be read (null).
*/
-export function pickerPrice(m: ModelDef, now: PriceClock): string {
+export function pickerPrice(m: ModelDef, now: PriceClock, edits = false): string {
if (m.engine === "open") return "Free";
const p = m.pricing && pricingOn(m.pricing, now);
+ // A studio that edits clips (Edit video) shows the rate an edit bills, on the seconds in and out (Kling 4.0).
+ if (edits && p?.clipInput) return `${formatCost(p.clipInput.usd)}/sec in+out`;
return p ? `${formatCost(p.usd)}${PICKER_UNIT[p.unit]}` : "";
}
diff --git a/src/server/generations.ts b/src/server/generations.ts
index 8669cf96..9d156099 100644
--- a/src/server/generations.ts
+++ b/src/server/generations.ts
@@ -12,7 +12,7 @@ import { cueText, type Cue } from "@/lib/cues";
import { HELPER_FEATURES, HELPER_SUFFIX, isReviewStatus, type AssetUse, type ReviewFilter } from "@/lib/library";
import { upscaleTier } from "@/lib/av/upscale";
import { chainedWaitMessage, framesWait, keyframeChain } from "@/lib/catalog/keyframes";
-import { clipWindowProblem } from "@/lib/catalog/clip-windows";
+import { clipTotalProblem, clipWindowProblem } from "@/lib/catalog/clip-windows";
import { avatarSeconds, clipEditSeconds, estimateCost, inferOperation, movedAppRequest, planGeneration, presetRoute, routeLoras, routesFor, withoutTriggers } from "@/lib/catalog/plan";
import { framedLength, keepMatte } from "@/lib/catalog/payload";
import { fitLoras, loraName, lorasFit } from "@/lib/catalog/loras";
@@ -1499,6 +1499,18 @@ async function submitNow(
return adapter.prepareFile(f.data, f.contentType, f.name, route);
});
};
+ // Reference clips and clip elements a model bills with the output (Kling 4.0, Pricing.clipInput): their headers' lengths.
+ const clipLengths: number[] = [];
+ const billsClips = !!plan.model.pricing?.clipInput;
+ const prepClip = async (ref?: string) => {
+ if (!ref || !billsClips) return prep(ref);
+ return gate(async () => {
+ const f = await readRef(ref);
+ const facts = mediaFacts(f.data);
+ if (facts.duration) clipLengths.push(facts.duration);
+ return adapter.prepareFile(f.data, f.contentType, f.name, route);
+ });
+ };
const prepMask = async (ref?: string) => {
if (!ref) return undefined;
return gate(async () => {
@@ -1553,7 +1565,7 @@ async function submitNow(
audio2: await prep(req.inputs?.audio2),
voiceAudio: await prep(req.inputs?.voiceAudio),
voiceAudio2: await prep(req.inputs?.voiceAudio2),
- videos: (await Promise.all((req.inputs?.videos ?? []).map(prep))).filter(Boolean) as string[],
+ videos: (await Promise.all((req.inputs?.videos ?? []).map(prepClip))).filter(Boolean) as string[],
audios: (await Promise.all((req.inputs?.audios ?? []).map(prep))).filter(Boolean) as string[],
model3d: await prep(req.inputs?.model3d),
loras: plan.loras,
@@ -1576,6 +1588,19 @@ async function submitNow(
update(id, { cost_usd: estimateCost(plan.model, { ...plan.params, sourceDuration: input.sourceDuration }, 1, plan.op, plan.loras.length > 0 && !!route.loraEndpoint) });
}
}
+ // Reference clips (and clip elements) billed with the output: refused past the most the model takes in all (with the
+ // clip edited), before it's paid for, and priced on their seconds once read (the plan priced the least they bill).
+ // An edit of a clip whose length the caller didn't say is priced on it (in and out) once its header is read.
+ const edits = plan.op === "v2v" || plan.op === "video-swap" || plan.op === "video-insert";
+ const unpricedEdit = edits && !!input.sourceDuration && plan.params.sourceDuration === undefined;
+ if (billsClips && (clipLengths.length || unpricedEdit) && providerId !== "mock" && plan.model.engine !== "open") {
+ const seconds = clipLengths.reduce((a, b) => a + b, 0);
+ const problem = clipTotalProblem(plan.model, (edits ? (input.sourceDuration ?? 0) : 0) + seconds);
+ if (problem) throw new Error(problem);
+ if (clipLengths.length) input.clipSeconds = seconds;
+ const priced = { ...plan.params, ...(input.sourceDuration !== undefined && { sourceDuration: input.sourceDuration }), ...(clipLengths.length && { clipSeconds: seconds }) };
+ update(id, { cost_usd: estimateCost(plan.model, priced, 1, plan.op) });
+ }
// An upscale that wouldn't enlarge the clip (a 1080p clip at a default 1080p; a 4K clip would even shrink):
// a tier the model only defaulted to moves up to the next one it offers, one the caller picked is refused.
if (plan.op === "upscale-video" && input.sourceSize) {
diff --git a/src/server/request-schema.ts b/src/server/request-schema.ts
index 87016c5f..6352c28a 100644
--- a/src/server/request-schema.ts
+++ b/src/server/request-schema.ts
@@ -65,6 +65,11 @@ export const GenerationRequestSchema = z.object({
enhancePrompt: z.boolean().optional(),
shots: z.array(z.object({ prompt: z.string().max(2000), duration: z.number().positive().max(60) })).max(12).optional(),
multiShot: z.literal("auto").optional(),
+ // Kling 4.0's elements: groups of inputs.images (by index, the frontal view first) or one of inputs.videos.
+ elements: z
+ .array(z.object({ images: z.array(z.number().int().min(0).max(63)).max(4).optional(), video: z.number().int().min(0).max(23).optional() }))
+ .max(7)
+ .optional(),
draft: z.boolean().optional(),
draftId: z.string().max(8192).optional(),
voice: z.string().max(200).optional(),
diff --git a/tests/cloud-catalog-4.test.ts b/tests/cloud-catalog-4.test.ts
index e7d96083..1143d267 100644
--- a/tests/cloud-catalog-4.test.ts
+++ b/tests/cloud-catalog-4.test.ts
@@ -112,11 +112,14 @@ describe("round-4 cloud models", () => {
}
});
- it("leaves Kling 4.0 out until its API opens", () => {
- const routes = MODELS.flatMap((m) => m.routes);
- expect(routes.filter((r) => r.endpoint.startsWith("kling/v4/"))).toEqual([]);
- expect(research4.filter((e) => e.endpoint.startsWith("kling/v4/")).every((e) => e.status === "playground-only")).toBe(true);
- expect(fs.readFileSync("scripts/gen-cloud-models.py", "utf8")).toMatch(/TODO\(kling-4\)/);
+ it("routes Kling 4.0 only on endpoints whose API is open (checked 2026-11-01, nm10-kling-4)", () => {
+ const routes = MODELS.flatMap((m) => m.routes).filter((r) => r.endpoint.startsWith("kling/v4/"));
+ expect(new Set(routes.map((r) => r.endpoint)).size).toBe(4);
+ for (const r of routes) {
+ const e = research4.find((x) => x.endpoint === r.endpoint)!;
+ expect(e.status, r.endpoint).toBe("active");
+ }
+ expect(fs.readFileSync("scripts/gen-cloud-models.py", "utf8")).not.toMatch(/TODO\(kling-4\)/);
});
it("hides chain helpers and shows the new models in their studios' pickers", () => {