feat(xai): add native image and video endpoints

Expose the xAI Imagine image and video surfaces on top of the `xai`
provider, and make the shared OpenAI video-task layer survive the
production configuration they need.

Native video requests live under /v1 (generations, edits, extensions,
with /v1/videos as a creation alias that only selects xAI candidates);
the OpenAI-compatible adapter stays under /openai/v1/videos and maps
`seconds` / `size` onto numeric duration, aspect ratio and resolution.
Clients receive an opaque Aether task ID scoped to the owning user;
polling uses the upstream task ID and the original credential, and
completed downloads fetch the returned media URL without forwarding
provider authorization to the media host.

Three fixes to the shared video layer are required for this to work
outside tests:

- OpenAI/xAI task persistence now supplies a stable 16-character
  short_id, which the PostgreSQL schema requires. Existing rows keep
  their original value across reconstruction, so no schema change or
  historical rewrite is needed.
- Task retrieval and content downloads are admitted by the production
  GET execution gate, and reconstructed tasks resolve proxy nodes,
  system proxy defaults, tunnel affinity and transport profiles through
  the same deployment resolver used for creation. A configured proxy
  route no longer silently becomes a direct request after restart.
- When the gateway also serves the frontend, /openai/v1/videos and its
  subpaths bypass the static SPA handler. Otherwise a video query
  returns HTTP 200 with text/html instead of the task JSON.

Co-Authored-By: Claude Opus 5 <[email protected]>
This commit is contained in:
stabey
2026-09-14 21:17:21 +08:00
co-authored by Claude Opus 5
parent e83399db2f
commit 04c4a97766
42 changed files with 1880 additions and 164 deletions
+181 -17
View File
@@ -43,6 +43,27 @@ pub fn map_openai_stored_task_to_read_response(
}
fn build_openai_stored_task_body(task: StoredVideoTask, status: VideoTaskStatus) -> Value {
if task.client_api_format.as_deref() == Some("xai:video") {
let mut body = json!({"status":match status {
VideoTaskStatus::Completed => "done",
VideoTaskStatus::Expired => "expired",
VideoTaskStatus::Failed | VideoTaskStatus::Cancelled | VideoTaskStatus::Deleted => "failed",
_ => "pending",
}});
if let Some(model) = task.model {
body["model"] = json!(model);
}
if let Some(url) = task.video_url {
body["video"] = json!({"url":url});
if let Some(duration) = task.duration_seconds {
body["video"]["duration"] = json!(duration);
}
}
if status == VideoTaskStatus::Failed {
body["error"] = json!({"code":sanitize_video_task_error_code(task.error_code).unwrap_or_else(|| "unknown".into()),"message":"Video generation failed"});
}
return body;
}
let mut body = json!({
"id": task.id,
"object": "video",
@@ -57,6 +78,9 @@ fn build_openai_stored_task_body(task: StoredVideoTask, status: VideoTaskStatus)
if let Some(prompt) = task.prompt {
body["prompt"] = Value::String(prompt);
}
if let Some(seconds) = task.duration_seconds {
body["seconds"] = json!(seconds.to_string());
}
if let Some(size) = task.size {
body["size"] = Value::String(size);
}
@@ -91,21 +115,97 @@ fn map_openai_stored_task_status(status: VideoTaskStatus) -> &'static str {
}
impl OpenAiVideoTaskSeed {
pub fn uses_xai_provider(&self) -> bool {
self.xai_provider || self.is_xai_native()
}
pub fn is_xai_native(&self) -> bool {
self.persistence.client_api_format == "xai:video"
}
pub fn native_create_body_json(&self) -> Value {
let mut body = self.native_response.clone().unwrap_or_else(|| json!({}));
body["request_id"] = json!(self.local_task_id);
if body.get("id").is_some() {
body["id"] = json!(self.local_task_id);
}
body
}
fn native_read_body_json(&self) -> Value {
if let Some(mut body) = self.native_response.clone().filter(|body| {
body.get("status").is_some()
|| body.get("error").is_some()
|| body.get("code").is_some()
}) {
if body.get("request_id").is_some() {
body["request_id"] = json!(self.local_task_id);
}
if body.get("id").is_some() {
body["id"] = json!(self.local_task_id);
}
return body;
}
let mut body = json!({"status":match self.status {
LocalVideoTaskStatus::Completed => "done",
LocalVideoTaskStatus::Expired => "expired",
LocalVideoTaskStatus::Failed | LocalVideoTaskStatus::Cancelled | LocalVideoTaskStatus::Deleted => "failed",
_ => "pending",
}});
if let Some(model) = &self.model {
body["model"] = json!(model);
}
if let Some(url) = &self.video_url {
body["video"] = json!({"url":url});
if let Some(duration) = self.seconds.as_deref().and_then(|v| v.parse::<u64>().ok()) {
body["video"]["duration"] = json!(duration);
}
}
if self.error_code.is_some() {
body["error"] = json!({"code":self.error_code,"message":"Video generation failed"});
}
body
}
pub fn apply_provider_body(&mut self, provider_body: &Map<String, Value>) {
if self.uses_xai_provider() {
self.native_response = Some(Value::Object(provider_body.clone()));
}
let raw_status = provider_body
.get("status")
.and_then(Value::as_str)
.map(str::trim)
.unwrap_or_default();
self.status = match raw_status {
"queued" => LocalVideoTaskStatus::Queued,
"processing" => LocalVideoTaskStatus::Processing,
"completed" => LocalVideoTaskStatus::Completed,
"failed" => LocalVideoTaskStatus::Failed,
"cancelled" => LocalVideoTaskStatus::Cancelled,
// Accept xAI's native lifecycle vocabulary alongside OpenAI's fields.
self.status = match raw_status.to_ascii_lowercase().as_str() {
"queued" | "pending" => LocalVideoTaskStatus::Queued,
"processing" | "in_progress" | "running" => LocalVideoTaskStatus::Processing,
"completed" | "done" | "succeeded" | "success" => LocalVideoTaskStatus::Completed,
"failed" | "error" => LocalVideoTaskStatus::Failed,
"cancelled" | "canceled" => LocalVideoTaskStatus::Cancelled,
"expired" => LocalVideoTaskStatus::Expired,
_ => LocalVideoTaskStatus::Submitted,
};
let error = provider_body.get("error").filter(|value| !value.is_null());
let error_code = provider_body
.get("code")
.and_then(Value::as_str)
.filter(|value| !value.trim().is_empty())
.or_else(|| {
error
.and_then(|value| value.get("code"))
.and_then(Value::as_str)
});
// xAI may report a failed job as a 200 response with code/error only.
if (error.is_some() || error_code.is_some())
&& !matches!(
self.status,
LocalVideoTaskStatus::Cancelled | LocalVideoTaskStatus::Expired
)
{
self.status = LocalVideoTaskStatus::Failed;
}
self.progress_percent = provider_body
.get("progress")
.and_then(Value::as_u64)
@@ -117,20 +217,35 @@ impl OpenAiVideoTaskSeed {
});
self.completed_at_unix_secs = provider_body.get("completed_at").and_then(Value::as_u64);
self.expires_at_unix_secs = provider_body.get("expires_at").and_then(Value::as_u64);
let error = provider_body.get("error").and_then(Value::as_object);
self.error_code = sanitize_video_task_error_code(
error
.and_then(|value| value.get("code"))
.and_then(Value::as_str)
.map(str::to_string),
);
self.error_code = sanitize_video_task_error_code(error_code.map(str::to_string));
self.error_message = None;
self.video_url = provider_body
.get("video_url")
.or_else(|| provider_body.get("url"))
.or_else(|| provider_body.get("result_url"))
.or_else(|| {
provider_body
.get("video")
.and_then(|video| video.get("url"))
})
.and_then(Value::as_str)
.map(str::to_string);
if let Some(seconds) = provider_body
.get("seconds")
.or_else(|| {
provider_body
.get("video")
.and_then(|video| video.get("duration"))
})
.filter(|value| value.is_string() || value.is_number())
{
self.seconds = Some(
seconds
.as_str()
.map(str::to_string)
.unwrap_or_else(|| seconds.to_string()),
);
}
}
pub fn build_content_stream_action(
@@ -239,6 +354,9 @@ impl OpenAiVideoTaskSeed {
}
pub fn client_body_json(&self) -> Value {
if self.is_xai_native() {
return self.native_read_body_json();
}
let mut body = json!({
"id": self.local_task_id,
"object": "video",
@@ -259,6 +377,9 @@ impl OpenAiVideoTaskSeed {
if let Some(seconds) = &self.seconds {
body["seconds"] = Value::String(seconds.clone());
}
if let Some(video_url) = &self.video_url {
body["video_url"] = Value::String(video_url.clone());
}
if let Some(remixed_from_video_id) = &self.remixed_from_video_id {
body["remixed_from_video_id"] = Value::String(remixed_from_video_id.clone());
}
@@ -357,12 +478,20 @@ impl OpenAiVideoTaskSeed {
}
pub fn build_get_follow_up_plan(&self, trace_id: &str) -> Option<ExecutionPlan> {
if !matches!(
let refreshable = matches!(
self.status,
LocalVideoTaskStatus::Submitted
| LocalVideoTaskStatus::Queued
| LocalVideoTaskStatus::Processing
) {
) || (self.uses_xai_provider()
&& self.native_response.is_none()
&& matches!(
self.status,
LocalVideoTaskStatus::Completed
| LocalVideoTaskStatus::Failed
| LocalVideoTaskStatus::Expired
));
if !refreshable {
return None;
}
@@ -573,7 +702,12 @@ impl OpenAiVideoTaskSeed {
};
let mut record = UpsertVideoTask {
id: self.local_task_id.clone(),
short_id: None,
// The production schema requires a unique, non-null short_id (at most 16 chars).
// Derive it deterministically so repeated capture and legacy snapshot reloads agree.
short_id: Some(self.local_short_id.clone().unwrap_or_else(|| {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(self.local_task_id.as_bytes()))[..16].to_string()
})),
request_id: self.persistence.request_id.clone(),
user_id: self.user_id.clone(),
api_key_id: self.api_key_id.clone(),
@@ -589,7 +723,11 @@ impl OpenAiVideoTaskSeed {
model: self.model.clone().or_else(|| Some(String::new())),
prompt: self.prompt.clone().or_else(|| Some(String::new())),
original_request_body: None,
duration_seconds: request_body_u32(&self.persistence.original_request_body, "seconds"),
duration_seconds: self
.seconds
.as_deref()
.and_then(|value| value.parse().ok())
.or_else(|| request_body_u32(&self.persistence.original_request_body, "seconds")),
resolution: request_body_string(&self.persistence.original_request_body, "resolution"),
aspect_ratio: request_body_string(
&self.persistence.original_request_body,
@@ -697,6 +835,9 @@ mod tests {
#[test]
fn builds_minimal_openai_persistence_record_without_sensitive_snapshot() {
let seed = OpenAiVideoTaskSeed {
local_short_id: None,
native_response: None,
xai_provider: false,
local_task_id: "task-openai-sensitive".to_string(),
upstream_task_id: "upstream-openai-sensitive".to_string(),
created_at_unix_ms: 1_712_345_678,
@@ -747,6 +888,12 @@ mod tests {
let record = seed.to_upsert_record();
let short_id = record
.short_id
.as_deref()
.expect("database short_id is required");
assert_eq!(short_id.len(), 16);
assert_eq!(seed.to_upsert_record().short_id, record.short_id);
assert_eq!(record.error_code.as_deref(), Some("provider_error"));
assert!(record.original_request_body.is_none());
assert!(record.progress_message.is_none());
@@ -759,6 +906,8 @@ mod tests {
let mut stored = record.into_stored();
stored.status = VideoTaskStatus::Completed;
// Migrated tasks can already have a short ID unrelated to the derived ID.
stored.short_id = Some("legacy-short-id".to_string());
let snapshot =
LocalVideoTaskSnapshot::from_stored_task_with_transport(&stored, seed.transport)
.expect("stored task should reconstruct with current transport");
@@ -766,6 +915,21 @@ mod tests {
panic!("expected OpenAI snapshot");
};
assert_eq!(restored.prompt, stored.prompt);
assert_eq!(restored.to_upsert_record().short_id, stored.short_id);
let mut embedded = stored.clone();
let mut legacy_snapshot =
serde_json::to_value(LocalVideoTaskSnapshot::OpenAi(restored.clone())).unwrap();
legacy_snapshot["OpenAi"]
.as_object_mut()
.unwrap()
.remove("local_short_id");
embedded.request_metadata = Some(json!({"rust_local_snapshot": legacy_snapshot}));
let embedded_snapshot = LocalVideoTaskSnapshot::from_stored_task(&embedded)
.expect("legacy embedded snapshot should hydrate");
assert_eq!(
embedded_snapshot.to_upsert_record().short_id,
stored.short_id
);
assert_eq!(restored.to_upsert_record().video_url, stored.video_url);
let Some(LocalVideoTaskContentAction::StreamPlan(plan)) =
restored.build_content_stream_action(None, "trace-download")