1pub mod comfy_serve;
7pub mod openrouter;
8
9use agentai_core::HttpError;
10use agentai_core::message::Media;
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14use thiserror::Error;
15
16#[derive(Debug, Clone, PartialEq)]
21#[non_exhaustive]
22pub struct VideoRequest {
23 pub prompt: String,
25 pub duration: Option<u32>,
27 pub resolution: Option<String>,
29 pub aspect_ratio: Option<String>,
31 pub seed: Option<u32>,
33 pub inputs: VideoInputs,
35}
36
37impl VideoRequest {
38 pub fn new(prompt: impl Into<String>) -> Self {
40 Self {
41 prompt: prompt.into(),
42 duration: None,
43 resolution: None,
44 aspect_ratio: None,
45 seed: None,
46 inputs: VideoInputs::None,
47 }
48 }
49
50 pub fn with_duration(mut self, seconds: u32) -> Self {
52 self.duration = Some(seconds);
53 self
54 }
55
56 pub fn with_resolution(mut self, resolution: impl Into<String>) -> Self {
58 self.resolution = Some(resolution.into());
59 self
60 }
61
62 pub fn with_aspect_ratio(mut self, aspect_ratio: impl Into<String>) -> Self {
64 self.aspect_ratio = Some(aspect_ratio.into());
65 self
66 }
67
68 pub fn with_seed(mut self, seed: u32) -> Self {
70 self.seed = Some(seed);
71 self
72 }
73
74 pub fn with_inputs(mut self, inputs: VideoInputs) -> Self {
76 self.inputs = inputs;
77 self
78 }
79}
80
81#[derive(Debug, Clone, PartialEq)]
83#[non_exhaustive]
84pub enum VideoInputs {
85 None,
87 Frames {
89 first: Option<Media>,
91 last: Option<Media>,
93 },
94 References(VideoReferences),
96}
97
98#[derive(Debug, Clone, PartialEq, Default)]
102#[non_exhaustive]
103pub struct VideoReferences {
104 pub images: Vec<Media>,
106 pub videos: Vec<Media>,
108 pub audio: Vec<Media>,
110 pub video_sound: Vec<u32>,
112}
113
114impl VideoReferences {
115 pub fn new() -> Self {
117 Self::default()
118 }
119
120 pub fn with_image(mut self, image: Media) -> Self {
122 self.images.push(image);
123 self
124 }
125
126 pub fn with_video(mut self, video: Media) -> Self {
128 self.videos.push(video);
129 self
130 }
131
132 pub fn with_audio(mut self, audio: Media) -> Self {
134 self.audio.push(audio);
135 self
136 }
137
138 pub fn with_video_sound(mut self, index: u32) -> Self {
140 self.video_sound.push(index);
141 self
142 }
143}
144
145#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
149#[non_exhaustive]
150pub struct VideoJob {
151 pub id: String,
153 pub data: Value,
156}
157
158impl VideoJob {
159 pub fn new(id: impl Into<String>) -> Self {
161 Self {
162 id: id.into(),
163 data: Value::Null,
164 }
165 }
166
167 pub fn with_data(mut self, data: Value) -> Self {
169 self.data = data;
170 self
171 }
172}
173
174#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
176#[serde(rename_all = "snake_case")]
177#[non_exhaustive]
178pub enum JobStatus {
179 Queued,
181 Running,
183 Completed,
185 Failed(String),
187 Gone,
189}
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(rename_all = "snake_case")]
194#[non_exhaustive]
195pub enum VideoInputKind {
196 FirstFrame,
198 LastFrame,
200 Image,
202 Video,
204 Audio,
206}
207
208#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
213#[non_exhaustive]
214pub struct VideoModel {
215 pub model: String,
217 pub id: String,
219 pub name: Option<String>,
221 pub durations: Option<Vec<u32>>,
223 pub resolutions: Option<Vec<String>>,
225 pub aspect_ratios: Option<Vec<String>>,
227 pub inputs: Option<Vec<VideoInputKind>>,
229}
230
231impl VideoModel {
232 pub fn new(model: impl Into<String>, id: impl Into<String>) -> Self {
234 Self {
235 model: model.into(),
236 id: id.into(),
237 name: None,
238 durations: None,
239 resolutions: None,
240 aspect_ratios: None,
241 inputs: None,
242 }
243 }
244}
245
246#[derive(Debug, Error)]
248#[non_exhaustive]
249pub enum VideoError {
250 #[error(transparent)]
252 Http(HttpError),
253 #[error("video API error (status {status}): {message}")]
255 Api {
256 status: u16,
258 message: String,
260 },
261 #[error("invalid video API response: {0}")]
263 InvalidResponse(String),
264 #[error("not supported by the video provider: {0}")]
266 Unsupported(&'static str),
267 #[error("no video provider for model '{0}'")]
269 UnknownProvider(String),
270 #[error("the API key is missing, set {0}")]
272 MissingApiKey(&'static str),
273 #[error("the base URL is missing, set {0}")]
275 MissingBaseUrl(&'static str),
276}
277
278impl From<HttpError> for VideoError {
279 fn from(err: HttpError) -> Self {
280 match err {
281 HttpError::Status { status, message } => Self::Api { status, message },
282 err => Self::Http(err),
283 }
284 }
285}
286
287impl VideoError {
288 pub fn is_auth(&self) -> bool {
290 matches!(
291 self,
292 Self::Api {
293 status: 401 | 403,
294 ..
295 }
296 )
297 }
298}
299
300#[async_trait]
305pub trait VideoProvider: Send + Sync + 'static {
306 fn model(&self) -> Option<&str> {
308 None
309 }
310
311 async fn submit(&self, request: VideoRequest) -> Result<VideoJob, VideoError>;
313
314 async fn status(&self, job: &VideoJob) -> Result<JobStatus, VideoError>;
316
317 async fn download(&self, job: &VideoJob) -> Result<Media, VideoError>;
319
320 fn supports_cancel(&self) -> bool {
322 false
323 }
324
325 async fn cancel(&self, _job: &VideoJob) -> Result<(), VideoError> {
329 Err(VideoError::Unsupported("cancelling a job"))
330 }
331
332 async fn list_models(&self) -> Result<Vec<VideoModel>, VideoError> {
334 Err(VideoError::Unsupported("listing models"))
335 }
336}
337
338#[derive(Debug, Clone, Copy, PartialEq, Eq)]
340enum ProviderKind {
341 ComfyServe,
342 OpenRouter,
343}
344
345impl ProviderKind {
346 fn from_name(name: &str) -> Option<Self> {
347 match name {
348 "comfy-serve" => Some(Self::ComfyServe),
349 "openrouter" => Some(Self::OpenRouter),
350 _ => None,
351 }
352 }
353
354 fn build(self, model: &str) -> Result<Box<dyn VideoProvider>, VideoError> {
355 Ok(match self {
356 Self::ComfyServe => Box::new(comfy_serve::ComfyServeVideoProvider::from_env(model)?),
357 Self::OpenRouter => Box::new(openrouter::OpenRouterVideoProvider::from_env(model)?),
358 })
359 }
360}
361
362fn resolve(model: &str) -> Result<(ProviderKind, &str), VideoError> {
364 model
365 .split_once("::")
366 .and_then(|(provider, name)| Some((ProviderKind::from_name(provider)?, name)))
367 .ok_or_else(|| VideoError::UnknownProvider(model.to_string()))
368}
369
370pub fn from_model(model: &str) -> Result<Box<dyn VideoProvider>, VideoError> {
374 let (kind, name) = resolve(model)?;
375 kind.build(name)
376}
377
378pub async fn list_models(provider: &str) -> Result<Vec<VideoModel>, VideoError> {
390 let kind = ProviderKind::from_name(provider)
391 .ok_or_else(|| VideoError::UnknownProvider(provider.to_string()))?;
392 kind.build("")?.list_models().await
393}
394
395#[cfg(test)]
396mod tests {
397 use serde_json::json;
398
399 use super::*;
400
401 #[test]
402 fn a_prefix_selects_the_provider_and_is_required() {
403 assert_eq!(
404 resolve("comfy-serve::wan/2.2").unwrap(),
405 (ProviderKind::ComfyServe, "wan/2.2")
406 );
407 assert_eq!(
408 resolve("openrouter::google/veo-3.1").unwrap(),
409 (ProviderKind::OpenRouter, "google/veo-3.1")
410 );
411 for model in ["wan", "comfy::wan", "other::wan"] {
412 assert!(matches!(resolve(model), Err(VideoError::UnknownProvider(m)) if m == model));
413 }
414 }
415
416 #[test]
417 fn jobs_and_statuses_keep_dreamers_stored_format() {
418 assert_eq!(
419 serde_json::to_value(JobStatus::Failed("x".into())).unwrap(),
420 json!({"failed": "x"})
421 );
422 assert_eq!(
423 serde_json::to_value(JobStatus::Queued).unwrap(),
424 json!("queued")
425 );
426 assert_eq!(
427 serde_json::to_value(VideoJob::new("j").with_data(json!({"polling_url": null})))
428 .unwrap(),
429 json!({"id": "j", "data": {"polling_url": null}})
430 );
431 }
432}