# ===== file: bin/flatkey.js ===== #!/usr/bin/env node import { main } from "../src/cli.js"; main(process.argv.slice(2)).catch((error) => { if (process.argv.includes("--json")) { process.stderr.write(`${JSON.stringify({ error: { message: error.message } })}\n`); } else { process.stderr.write(`${error.message}\n`); } process.exitCode = 1; }); # ===== file: rust/flatkey-depth/src/main.rs ===== use anyhow::{bail, Context, Result}; use clap::Parser; use image::{imageops::FilterType, DynamicImage, ImageBuffer, Rgb}; use ndarray::Array4; use ort::{session::Session, value::Tensor}; use serde::Serialize; use std::{ io::{Read, Write}, path::{Path, PathBuf}, process::{Child, Command, Stdio}, }; const MODEL_URL: &str = "https://huggingface.co/onnx-community/depth-anything-v2-small/resolve/main/onnx/model_quantized.onnx"; const MODEL_INPUT: u32 = 364; #[derive(Debug, Parser)] #[command(name = "flatkey-depth", version)] struct Args { #[arg(long)] source: PathBuf, #[arg(long)] output: PathBuf, #[arg(long, default_value_t = 100)] frame_ratio: u8, #[arg(long, default_value = "480p")] resolution: String, #[arg(long)] work_dir: PathBuf, #[arg(long)] model: Option, } #[derive(Debug, Serialize)] struct ResultJson { output: PathBuf, frame_ratio: u8, resolution: String, model: String, inference: String, } fn main() -> Result<()> { let args = Args::parse(); if !(20..=100).contains(&args.frame_ratio) { bail!("--frame-ratio must be between 20 and 100"); } if !matches!(args.resolution.as_str(), "original" | "480p" | "320p") { bail!("--resolution must be original, 480p, or 320p"); } std::fs::create_dir_all(&args.work_dir)?; let model = args .model .or_else(|| std::env::var_os("FLATKEY_DEPTH_MODEL").map(PathBuf::from)) .ok_or_else(|| anyhow::anyhow!( "Depth Anything V2 model is required; pass --model \ or set FLATKEY_DEPTH_MODEL (official model: {MODEL_URL})" ))?; if !model.is_file() { bail!("Depth Anything V2 model does not exist: {}", model.display()); } let (width, height, fps) = probe_video(&args.source)?; let (output_width, output_height) = output_size(width, height, &args.resolution); let decoder = spawn_decoder(&args.source)?; let encoder = spawn_encoder(&args.output, output_width, output_height, fps)?; let mut session = Session::builder()?.commit_from_file(&model)?; infer_frames( decoder, encoder, &mut session, output_width, output_height, args.frame_ratio, )?; println!( "{}", serde_json::to_string(&ResultJson { output: args.output, frame_ratio: args.frame_ratio, resolution: args.resolution, model: model.display().to_string(), inference: "depth-anything-v2-small-onnx".to_string(), })? ); Ok(()) } fn probe_video(path: &Path) -> Result<(u32, u32, f64)> { let out = Command::new("ffprobe") .args([ "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,avg_frame_rate", "-of", "csv=p=0", ]) .arg(path) .output() .with_context(|| "failed to start ffprobe")?; if !out.status.success() { bail!("ffprobe failed: {}", String::from_utf8_lossy(&out.stderr)); } let fields: Vec<_> = String::from_utf8_lossy(&out.stdout) .trim() .split(',') .map(str::to_owned) .collect(); if fields.len() < 3 { bail!("ffprobe returned invalid video metadata"); } Ok((fields[0].parse()?, fields[1].parse()?, parse_rate(&fields[2])?)) } fn parse_rate(value: &str) -> Result { if let Some((a, b)) = value.split_once('/') { return Ok(a.parse::()? / b.parse::()?); } Ok(value.parse()?) } fn output_size(width: u32, height: u32, resolution: &str) -> (u32, u32) { let max_height = match resolution { "320p" => Some(320), "480p" => Some(480), _ => None, }; let Some(max_height) = max_height else { return (width, height); }; if height <= max_height { return (width, height); } let scaled_width = ((width as f64 * max_height as f64 / height as f64) / 2.0).floor() as u32 * 2; (scaled_width.max(2), max_height) } fn spawn_decoder(source: &Path) -> Result { let filter = "scale=364:364:flags=lanczos,format=rgb24"; Command::new("ffmpeg") .args(["-v", "error", "-i"]) .arg(source) .args(["-an", "-vf", &filter, "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]) .stdout(Stdio::piped()) .spawn() .with_context(|| "failed to start ffmpeg decoder") } fn spawn_encoder(output: &Path, width: u32, height: u32, fps: f64) -> Result { let fps_arg = if fps.is_finite() && fps > 0.0 { format!("{fps:.6}") } else { "30".to_string() }; Command::new("ffmpeg") .args([ "-v", "error", "-y", "-f", "rawvideo", "-pix_fmt", "gray", "-s", &format!("{width}x{height}"), "-r", &fps_arg, "-i", "-", "-an", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-preset", "veryfast", "-crf", "18", "-movflags", "+faststart", ]) .arg(output) .stdin(Stdio::piped()) .spawn() .with_context(|| "failed to start ffmpeg encoder") } fn infer_frames( mut decoder: Child, mut encoder: Child, session: &mut Session, output_width: u32, output_height: u32, frame_ratio: u8, ) -> Result<()> { let mut input = decoder.stdout.take().context("decoder stdout unavailable")?; let mut encoded = encoder.stdin.take().context("encoder stdin unavailable")?; let frame_bytes = (MODEL_INPUT * MODEL_INPUT * 3) as usize; let mut frame = vec![0_u8; frame_bytes]; let mut last_frame = vec![0_u8; frame_bytes]; let mut previous_depth: Option> = None; let mut previous_index = 0_u64; let mut frame_index = 0_u64; let mut selection_accumulator = 100_u16; loop { let mut read = 0; while read < frame.len() { let count = input.read(&mut frame[read..])?; if count == 0 { break; } read += count; } if read == 0 { break; } if read != frame.len() { bail!("decoder ended with a partial RGB frame"); } last_frame.copy_from_slice(&frame); selection_accumulator += frame_ratio as u16; let selected = selection_accumulator >= 100; if selected { selection_accumulator -= 100; let depth = infer_depth(&frame, session, output_width, output_height)?; if let Some(previous) = previous_depth.replace(depth) { write_repeated(&mut encoded, &previous, frame_index - previous_index)?; } previous_index = frame_index; } frame_index += 1; } if frame_index > 0 { let last_index = frame_index - 1; if previous_index != last_index { let last_depth = infer_depth(&last_frame, session, output_width, output_height)?; if let Some(previous) = previous_depth.take() { write_repeated(&mut encoded, &previous, last_index - previous_index)?; } encoded.write_all(&last_depth)?; } else if let Some(previous) = previous_depth.take() { write_repeated(&mut encoded, &previous, 1)?; } } drop(encoded); if !decoder.wait()?.success() { bail!("ffmpeg decoder failed"); } if !encoder.wait()?.success() { bail!("ffmpeg encoder failed"); } Ok(()) } fn infer_depth( frame: &[u8], session: &mut Session, output_width: u32, output_height: u32, ) -> Result> { let plane = (MODEL_INPUT * MODEL_INPUT) as usize; let mut chw = vec![0_f32; plane * 3]; for index in 0..plane { let pixel = index * 3; chw[index] = (frame[pixel] as f32 / 255.0 - 0.485) / 0.229; chw[plane + index] = (frame[pixel + 1] as f32 / 255.0 - 0.456) / 0.224; chw[2 * plane + index] = (frame[pixel + 2] as f32 / 255.0 - 0.406) / 0.225; } let tensor = Tensor::from_array(Array4::from_shape_vec( (1, 3, MODEL_INPUT as usize, MODEL_INPUT as usize), chw, )?)?; let outputs = session.run(ort::inputs!["pixel_values" => tensor])?; let (shape, data) = outputs[0].try_extract_tensor::()?; let depth_height = shape[shape.len() - 2] as u32; let depth_width = shape[shape.len() - 1] as u32; let (mut min, mut max) = (f32::INFINITY, f32::NEG_INFINITY); for value in data.iter().copied() { min = min.min(value); max = max.max(value); } let range = (max - min).max(1e-6); let mut image = ImageBuffer::, Vec>::new(depth_width, depth_height); for (index, pixel) in image.pixels_mut().enumerate() { let value = ((data[index] - min) / range * 255.0).clamp(0.0, 255.0) as u8; *pixel = Rgb([value, value, value]); } let resized = DynamicImage::ImageRgb8(image).resize_exact( output_width, output_height, FilterType::Lanczos3, ); Ok(resized.to_luma8().into_raw()) } fn write_repeated(output: &mut impl Write, frame: &[u8], count: u64) -> Result<()> { for _ in 0..count { output.write_all(frame)?; } Ok(()) } # ===== file: src/animation.js ===== const FRAMES = [ "[FLATKEY] . ", "[FLATKEY] .. ", "[FLATKEY] ... ", "[FLATKEY] .... ", "[FLATKEY] >>>> ", ]; export function createAnimation({ json = false, stream = process.stderr, setIntervalFn = setInterval, clearIntervalFn = clearInterval, } = {}) { let timer; let active = false; let frame = 0; return { start(kind = "media") { if (json) return; if (!stream.isTTY) { stream.write(`flatkey ${kind} generation started\n`); return; } active = true; stream.write(`${FRAMES[0]}\r`); timer = setIntervalFn(() => { if (!active) return; frame = (frame + 1) % FRAMES.length; stream.write(`${FRAMES[frame]}\r`); }, 120); }, stop() { active = false; if (timer) clearIntervalFn(timer); if (!json && stream.isTTY) stream.write(" \r"); }, }; } # ===== file: src/api.js ===== import { withCliRequestHeaders } from "./requestHeaders.js"; export const DEFAULT_BASE_URL = "https://router.flatkey.ai"; export const DEFAULT_MODELS_BASE_URL = "https://console.flatkey.ai"; export const DEFAULT_CONSOLE_URL = "https://console.flatkey.ai"; export class FlatkeyError extends Error { constructor(message, { status, code } = {}) { super(message); this.name = "FlatkeyError"; this.status = status; this.code = code; } } export async function generateImage(options) { return requestJsonFromPlan(options, planImageRequest(options)); } export async function uploadTempMediaImage(options) { return uploadTempMediaByKind(options, "images"); } export async function uploadTempMediaVideo(options) { return uploadTempMediaByKind(options, "videos"); } async function uploadTempMediaByKind(options, kind) { const form = new FormData(); form.append("file", new Blob([options.file], cleanObject({ type: options.contentType, })), options.filename ?? (kind === "videos" ? "video" : "image")); return requestJsonFromPlan(options, planRequest(options, `/v1/temp-media/${kind}`, { method: "POST", headers: authHeaders(options.apiKey), body: form, })); } export function planImageRequest(options) { const model = options.model ?? "nano-banana-pro-preview"; const mediaInputs = orderedMediaInputs(options); assertReferenceLimits(mediaInputs, "image", model); if (mediaInputs.some((entry) => entry.kind === "video")) { throw new Error("Image models only accept image inputs."); } const imageUrls = mediaInputs .map((entry) => entry.url); if (model.startsWith("gpt")) { const responseFormat = options.response_format ?? options.responseFormat ?? "url"; const tempUrl = options.temp_url ?? options.tempUrl; return planJsonPost(options, "/v1/images/generations", cleanObject({ model, prompt: options.prompt, size: options.size, n: parseOptionalInteger(options.n), quality: options.quality, response_format: responseFormat, temp_url: tempUrl ?? true, images: imageUrls.length > 0 ? imageUrls : undefined, })); } const path = `/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(options.apiKey)}`; return planRequest(options, path, { method: "POST", headers: { ...jsonHeaders(options.apiKey), "x-goog-api-key": options.apiKey, }, body: { contents: [{ parts: [ { text: options.prompt }, ...imageUrls.map((url) => ({ type: "image_url", image_url: { url } })), ], }], temp_url: true, }, }); } export function generateVideo(options) { return requestJsonFromPlan(options, planVideoRequest(options)); } export function getVideo(options, taskId) { return requestJsonFromPlan(options, planVideoStatusRequest(options, taskId)); } export function planVideoRequest(options) { const model = options.model ?? "seedance-2.0-pro"; const mediaInputs = orderedMediaInputs(options); assertReferenceLimits(mediaInputs, "video", model); if (mediaInputs.some((entry) => entry.role === "first_frame" && entry.kind === "video") || mediaInputs.some((entry) => entry.role === "last_frame" && entry.kind === "video")) { throw new Error("Video first-frame and last-frame inputs must be images."); } const imageUrls = mediaInputs .filter((entry) => entry.kind !== "video") .map((entry) => entry.url); const videoUrls = mediaInputs .filter((entry) => entry.kind === "video") .map((entry) => entry.url); const ratio = validateOptionalValue( optionValue(options, "ratio", "aspect") ?? (isMiniMaxModel(model) ? "16:9" : isSeedance25Model(model) ? "adaptive" : undefined), ["16:9", "9:16", "4:3", "3:4", "21:9", "1:1", "adaptive"], "ratio", ); const resolution = validateOptionalValue( options.resolution ?? (isMiniMaxModel(model) ? "768P" : undefined), isMiniMaxModel(model) ? ["768P", "2K"] : ["480p", "720p", "1080p"], "resolution", ); const basePayload = cleanObject({ model, prompt: options.prompt, duration: options.duration === undefined && isMiniMaxModel(model) ? 5 : options.duration === undefined && isSeedance25Model(model) ? -1 : parseOptionalFloat(options.duration), aspect: ratio, ratio, resolution, quality: resolution, fps: parseOptionalInteger(options.fps), generate_audio: parseOptionalBoolean(options.generate_audio) ?? true, omni_reference_task_type: isSeedance25Model(model) && mediaInputs.some((entry) => entry.kind === "video" || entry.role === "reference_image") ? "auto" : undefined, temp_url: true, images: !isSeedanceModel(model) && imageUrls.length > 0 ? imageUrls : undefined, }); const seedanceContent = buildSeedanceContent(options, mediaInputs); if ((isSeedanceModel(model) || isMiniMaxModel(model)) && seedanceContent.length > 0) { return planJsonPost(options, videoGenerationPath(model, videoUrls), cleanObject({ ...basePayload, content: seedanceContent, })); } return planJsonPost(options, "/v1/video/generations", basePayload); } export function planVideoStatusRequest(options, taskId) { return planRequest(options, `/v1/videos/${encodeURIComponent(taskId)}`); } export function generateAudio(options) { return requestBinaryArtifactFromPlan(options, planAudioRequest(options)); } export function planAudioRequest(options) { const voiceId = optionValue(options, "voiceId", "voice_id") ?? "EXAVITQu4vr4xnSDxMaL"; return planJsonPost(options, `/v1/text-to-speech/${encodeURIComponent(voiceId)}`, cleanObject({ text: options.text ?? options.prompt, model_id: options.model ?? options.model_id ?? "eleven_multilingual_v2", voice_settings: cleanObject({ stability: parseOptionalFloat(options.stability), similarity_boost: parseOptionalFloat(optionValue(options, "similarityBoost", "similarity_boost")), style: parseOptionalFloat(options.style), }), })); } export function generateAudioSfx(options) { return requestBinaryArtifactFromPlan(options, planAudioSfxRequest(options)); } export function planAudioSfxRequest(options) { return planJsonPost(options, "/v1/sound-generation", cleanObject({ text: options.text ?? options.prompt, duration_seconds: parseOptionalFloat(optionValue(options, "durationSeconds", "duration_seconds", "duration")), })); } export function generateAudioMusic(options) { return requestBinaryArtifactFromPlan(options, planAudioMusicRequest(options)); } export function planAudioMusicRequest(options) { return planJsonPost(options, "/v1/music", cleanObject({ prompt: options.prompt, music_length_ms: parseOptionalInteger(optionValue(options, "musicLengthMs", "music_length_ms")), })); } export function getVoices(options) { return requestJson(options, "/v1/voices"); } export function planVoicesRequest(options) { return planRequest(options, "/v1/voices"); } export function generateText(options) { return requestJsonFromPlan(options, planTextRequest(options)); } export function planTextRequest(options) { return planJsonPost(options, "/v1/chat/completions", { model: options.model ?? "gpt-5.5", messages: [{ role: "user", content: options.prompt }], }); } export function getCredits(options) { return requestJson({ ...options, baseUrl: options.baseUrl ?? DEFAULT_CONSOLE_URL, }, "/v1/credits"); } export function getStatus(options) { return requestJson({ ...options, baseUrl: options.baseUrl ?? DEFAULT_CONSOLE_URL, }, "/v1/status"); } export function getModels(options) { return requestJson({ ...options, baseUrl: options.baseUrl ?? DEFAULT_MODELS_BASE_URL, }, "/v1/available_models"); } export async function createDeviceAuthorization(options) { return requestJson({ ...options, baseUrl: options.consoleUrl ?? DEFAULT_CONSOLE_URL, }, "/api/cli/device_authorizations", { method: "POST", body: JSON.stringify({ client_name: options.clientName ?? "flatkey-cli", client_version: options.clientVersion, device_id: options.deviceId, }), }); } export async function pollDeviceAuthorization(options) { return requestJson({ ...options, baseUrl: options.consoleUrl ?? DEFAULT_CONSOLE_URL, }, "/api/cli/device_authorizations/token", { method: "POST", body: JSON.stringify({ device_code: options.deviceCode, }), }); } async function postJson(options, path, payload) { return requestJsonFromPlan(options, planJsonPost(options, path, payload)); } function planJsonPost(options, path, payload) { return planRequest(options, path, { method: "POST", headers: jsonHeaders(options.apiKey), body: payload, }); } function planRequest(options, path, init = {}) { return { url: buildUrl(options.baseUrl, path), method: init.method ?? "GET", headers: withCliRequestHeaders(init.headers ?? authHeaders(options.apiKey)), body: init.body, }; } async function requestJsonFromPlan(options, plan) { const fetchImpl = options.fetch ?? fetch; const request = { method: plan.method, headers: plan.headers, body: plan.body === undefined ? undefined : isFormData(plan.body) ? plan.body : JSON.stringify(plan.body), }; logRequest(options, plan.url, request); const response = await fetchImpl(plan.url, request); logResponse(options, response); const body = await readJson(response); logResponseBody(options, body); if (!response.ok || body?.success === false) { throw new FlatkeyError(extractErrorMessage(body, response.status), { status: response.status, code: body?.code ?? body?.error?.code, }); } return body; } function isFormData(value) { return typeof FormData !== "undefined" && value instanceof FormData; } async function requestBinaryArtifactFromPlan(options, plan) { const fetchImpl = options.fetch ?? fetch; const request = { method: plan.method, headers: plan.headers, body: plan.body === undefined ? undefined : JSON.stringify(plan.body), }; logRequest(options, plan.url, request); const response = await fetchImpl(plan.url, request); logResponse(options, response); if (!response.ok) { const body = await readJson(response); logResponseBody(options, body); throw new FlatkeyError(extractErrorMessage(body, response.status), { status: response.status, code: body?.code ?? body?.error?.code, }); } return { data: [{ data: Buffer.from(await response.arrayBuffer()).toString("base64") }], }; } function logRequest(options, url, request) { if (!options?.verbose) return; const safeHeaders = redactHeaders(request.headers); const safeBody = request.body === undefined ? undefined : isFormData(request.body) ? "" : request.body; options.verboseLog?.(`-> ${request.method} ${url}`); options.verboseLog?.(`headers: ${JSON.stringify(safeHeaders)}`); if (safeBody !== undefined) { options.verboseLog?.(`body: ${safeBody}`); } } function logResponse(options, response) { if (!options?.verbose) return; options.verboseLog?.(`<- ${response.status} ${response.statusText || ""}`.trim()); } function logResponseBody(options, body) { if (!options?.verbose) return; options.verboseLog?.(`response: ${truncateLogValue(JSON.stringify(body))}`); } function redactHeaders(headers) { return Object.fromEntries(Object.entries(headers ?? {}).map(([key, value]) => [ key, key.toLowerCase() === "authorization" ? "Bearer " : `${value}`, ])); } function truncateLogValue(value) { if (value === undefined) return ""; return value.length > 1200 ? `${value.slice(0, 1200)}…` : value; } async function requestJson(options, path, init = {}) { return requestJsonFromPlan(options, planRequest(options, path, { method: init.method ?? "GET", headers: { ...authHeaders(options.apiKey), ...init.headers, }, body: init.body ? JSON.parse(init.body) : undefined, })); } function buildUrl(baseUrl = DEFAULT_BASE_URL, path) { return `${baseUrl.replace(/\/$/, "")}${path}`; } function authHeaders(apiKey) { return apiKey ? { Authorization: `Bearer ${apiKey}` } : {}; } function jsonHeaders(apiKey) { return { ...authHeaders(apiKey), "content-type": "application/json", }; } function parseOptionalInteger(value) { if (value === undefined) return undefined; return Number.parseInt(value, 10); } function parseOptionalFloat(value) { if (value === undefined) return undefined; return Number.parseFloat(value); } function parseOptionalBoolean(value) { if (value === undefined) return undefined; if (value === true || value === "true") return true; if (value === false || value === "false") return false; throw new Error(`Invalid boolean value: ${value}. Allowed values: true, false`); } function optionValue(options, ...keys) { for (const key of keys) { if (options[key] !== undefined) return options[key]; } return undefined; } function validateOptionalValue(value, allowed, name) { if (value === undefined) return undefined; if (allowed.includes(value)) return value; throw new Error(`Invalid ${name}: ${value}. Allowed values: ${allowed.join(", ")}`); } function isSeedanceModel(model) { return /seedance/i.test(model); } function isMiniMaxModel(model) { return /^minimax-h3$/i.test(model); } function videoGenerationPath(model, videoUrls = []) { // Seedance keeps text, image, and video-reference content on /v1/videos. // The legacy route does not reliably fetch video references upstream. if (isSeedanceModel(model)) return "/v1/videos"; return "/v1/video/generations"; } function buildSeedanceContent(options, mediaInputs = orderedMediaInputs(options)) { const content = []; if (options.prompt !== undefined) { content.push({ type: "text", text: options.prompt }); } for (const entry of mediaInputs) { if (entry.kind === "video") { content.push({ type: "video_url", video_url: { url: entry.url }, role: entry.role ?? "reference_video" }); continue; } content.push({ type: "image_url", image_url: { url: entry.url }, role: entry.role ?? "reference_image" }); } return content; } function arrayOption(value) { if (value === undefined) return []; return Array.isArray(value) ? value : [value]; } function cleanObject(value) { return Object.fromEntries( Object.entries(value).filter(([, entry]) => entry !== undefined), ); } function assertReferenceLimits(mediaInputs, kind, model) { const imageInputs = mediaInputs.filter((entry) => entry.kind !== "video"); const videoInputs = mediaInputs.filter((entry) => entry.kind === "video"); if (isSeedance25Model(model)) { if (imageInputs.length > 30) { throw new Error(`Too many reference images for flatkey ${kind} generate with Seedance 2.5: maximum 30.`); } if (videoInputs.length > 10) { throw new Error(`Too many reference videos for flatkey ${kind} generate with Seedance 2.5: maximum 10.`); } return; } if (imageInputs.length > 5) { throw new Error(`Too many reference images for flatkey ${kind} generate: maximum 5.`); } } function orderedMediaInputs(options) { const hidden = Array.isArray(options.__media_inputs) ? options.__media_inputs : []; if (hidden.length > 0 && hidden[0] && Object.prototype.hasOwnProperty.call(hidden[0], "url")) { return hidden; } if (hidden.length > 0) { return hidden.map((entry) => ({ ...entry, url: entry.url ?? entry.value, kind: entry.kind ?? inferMediaKindFromName(entry.name, entry.value), })); } const legacy = []; const push = (name, value, kind = "image", role) => { for (const item of arrayOption(value)) { legacy.push({ name, url: item, kind: kind === "image" ? inferMediaKindFromName(name, item) : kind, role }); } }; push("file", options.file, "image"); push("image", options.image, "image"); push("image_url", options.image_url, "image"); push("first_frame", options.first_frame, "image", "first_frame"); push("first_frame_url", options.first_frame_url, "image", "first_frame"); push("last_frame", options.last_frame, "image", "last_frame"); push("last_frame_url", options.last_frame_url, "image", "last_frame"); push("video_url", options.video_url, "video", "reference_video"); return legacy; } function inferMediaKindFromName(name, value) { const lowerName = String(name ?? "").toLowerCase(); if (lowerName.includes("video")) return "video"; if (typeof value === "string" && /\.(mp4|mov)$/i.test(value)) return "video"; return "image"; } function isSeedance25Model(model) { return String(model ?? "").toLowerCase().replaceAll(/[-_.]/g, "").includes("seedance25"); } async function readJson(response) { try { return await response.json(); } catch { return {}; } } function extractErrorMessage(body, status) { const message = typeof body?.error?.message === "string" ? body.error.message : typeof body?.message === "string" ? body.message : undefined; if (isAuthTokenError(message)) return missingApiKeyMessage(); if (message) return message; return `Flatkey API request failed with HTTP ${status}`; } function isAuthTokenError(message) { return message === "Token not provided" || /^Invalid token\b/i.test(message ?? ""); } function missingApiKeyMessage() { return "Missing or invalid Flatkey API key. Run `flatkey login`, or create a key at https://console.flatkey.ai/keys and run `flatkey onboard --api-key `."; } # ===== file: src/artifacts.js ===== import { mkdir, readdir, writeFile } from "node:fs/promises"; import { homedir } from "node:os"; import { dirname, extname, join } from "node:path"; import { CLI_REQUEST_HEADERS } from "./requestHeaders.js"; const DEFAULT_EXTENSIONS = { audio: "mp3", image: "png", video: "mp4", }; const MIME_EXTENSIONS = { "audio/aac": "aac", "audio/flac": "flac", "audio/mpeg": "mp3", "audio/mp3": "mp3", "audio/wav": "wav", "image/jpeg": "jpg", "image/png": "png", "video/mp4": "mp4", }; export async function persistArtifacts({ kind, response, outDir = "flatkey-output", output, fetch: fetchImpl = fetch, }) { output = expandHomePath(output); const items = extractItems(response); const artifacts = []; await mkdir(output ? dirname(output) : outDir, { recursive: true }); const startIndex = output ? 0 : await nextArtifactIndex({ kind, outDir }); for (const [index, item] of items.entries()) { const artifact = await persistItem({ kind, item, outDir, output, index: index + startIndex, fetchImpl }); if (artifact) artifacts.push(artifact); } return artifacts; } export async function nextArtifactPath({ kind, outDir = "flatkey-output" }) { const extension = DEFAULT_EXTENSIONS[kind] ?? "bin"; const index = await nextArtifactIndex({ kind, outDir }); const number = String(index + 1).padStart(2, "0"); return join(outDir, `${kind}-${number}.${extension}`); } function expandHomePath(path) { if (typeof path !== "string") return path; if (path === "~") return homedir(); if (path.startsWith("~/")) return join(homedir(), path.slice(2)); return path; } async function persistItem({ kind, item, outDir, output, index, fetchImpl }) { const dataUrl = getString(item, ["url", "video_url", "data_url", "dataUrl", "temp_url"]); if (dataUrl?.startsWith("data:")) { const parsed = parseDataUrl(dataUrl); const path = artifactPath({ kind, outDir, output, index, extension: parsed.extension }); await writeFile(path, parsed.buffer); return { path }; } if (dataUrl?.startsWith("http://") || dataUrl?.startsWith("https://")) { if (output) { const path = artifactPath({ kind, outDir, output, index, extension: DEFAULT_EXTENSIONS[kind] ?? "bin", }); await downloadArtifact({ url: dataUrl, path, fetchImpl }); return { path }; } return { url: dataUrl }; } const base64 = getString(item, ["b64_json", "base64", "data"]); if (base64) { const path = artifactPath({ kind, outDir, output, index, extension: DEFAULT_EXTENSIONS[kind] }); await writeFile(path, Buffer.from(base64, "base64")); return { path }; } return undefined; } async function downloadArtifact({ url, path, fetchImpl }) { const response = await fetchImpl(url, { headers: CLI_REQUEST_HEADERS }); if (!response.ok) { throw new Error(`Failed to download artifact ${url}: HTTP ${response.status}`); } await writeFile(path, Buffer.from(await response.arrayBuffer())); } function extractItems(response) { if (Array.isArray(response?.data)) return response.data; if (Array.isArray(response?.artifacts)) return response.artifacts; if (Array.isArray(response?.content)) return response.content; if (Array.isArray(response?.candidates)) { return response.candidates.flatMap((candidate) => candidate.content?.parts ?? []); } if (typeof response?.temp_url === "string") return [{ url: response.temp_url }]; if (typeof response?.metadata?.temp_url === "string") return [{ url: response.metadata.temp_url }]; if (typeof response?.metadata?.url === "string") return [{ url: response.metadata.url }]; if (typeof response?.url === "string") return [response]; if (typeof response?.video_url?.url === "string") return [{ url: response.video_url.url }]; if (typeof response?.video?.url === "string") return [{ url: response.video.url }]; if (typeof response?.video?.temp_url === "string") return [{ url: response.video.temp_url }]; return []; } function getString(item, keys) { for (const key of keys) { if (typeof item?.[key] === "string") return item[key]; if (typeof item?.[key]?.url === "string") return item[key].url; if (typeof item?.inlineData?.[key] === "string") return item.inlineData[key]; if (typeof item?.inline_data?.[key] === "string") return item.inline_data[key]; } return undefined; } function parseDataUrl(value) { const match = /^data:([^;,]+);base64,(.+)$/s.exec(value); if (!match) throw new Error("Unsupported data URL artifact."); return { extension: MIME_EXTENSIONS[match[1]] ?? "bin", buffer: Buffer.from(match[2], "base64"), }; } function artifactPath({ kind, outDir, output, index, extension }) { if (output) { if (index === 0) return output; const existingExtension = extname(output); const base = existingExtension ? output.slice(0, -existingExtension.length) : output; const suffix = String(index + 1).padStart(2, "0"); return `${base}-${suffix}${existingExtension || `.${extension}`}`; } const number = String(index + 1).padStart(2, "0"); return join(outDir, `${kind}-${number}.${extension}`); } async function nextArtifactIndex({ kind, outDir }) { const extension = DEFAULT_EXTENSIONS[kind] ?? "bin"; const pattern = new RegExp(`^${escapeRegExp(kind)}-(\\d+)\\.${escapeRegExp(extension)}$`); let max = 0; try { for (const entry of await readdir(outDir)) { const match = pattern.exec(entry); if (!match) continue; max = Math.max(max, Number.parseInt(match[1], 10)); } } catch { return 0; } return max; } function escapeRegExp(value) { return String(value).replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } # ===== file: src/cli.js ===== import { join } from "node:path"; import { DEFAULT_BASE_URL } from "./api.js"; import { nextArtifactPath, persistArtifacts } from "./artifacts.js"; const COMMANDS = new Set([ "audio", "credits", "help", "image", "login", "models", "onboard", "logout", "auth", "status", "text", "version", "video", ]); const GROUP_ACTIONS = new Set(["audio", "auth", "image", "text", "video"]); const GLOBAL_OPTIONS = new Set(["api_key", "base_url", "console_url", "dry_run", "help", "json", "output", "out", "verbose"]); const REPEATABLE_OPTIONS = new Set(["image", "image_url", "video_url"]); const MEDIA_INPUT_OPTIONS = new Set(["file", "image", "image_url", "video_url", "first_frame", "first_frame_url", "last_frame", "last_frame_url"]); const MAX_REFERENCE_IMAGES = 5; const COMMAND_OPTIONS = { "audio generate": new Set(["model", "prompt", "similarity_boost", "stability", "style", "voice_id"]), "audio music": new Set(["music_length_ms", "prompt"]), "audio sfx": new Set(["duration", "prompt"]), "audio voices": new Set([]), "auth status": new Set([]), credits: new Set([]), help: new Set(["ai", "command"]), image: new Set([]), "image generate": new Set(["file", "image", "image_url", "model", "n", "prompt", "quality", "size"]), "image upload": new Set(["file"]), login: new Set(["console_url", "no_open", "open"]), logout: new Set([]), models: new Set(["type"]), onboard: new Set(["api_key"]), status: new Set([]), text: new Set([]), "text generate": new Set(["model", "prompt"]), version: new Set([]), video: new Set([]), "video generate": new Set(["aspect", "duration", "file", "first_frame", "first_frame_url", "fps", "generate_audio", "image", "image_url", "last_frame", "last_frame_url", "model", "prompt", "ratio", "resolution", "video_url"]), "video copy": new Set(["aspect", "depth_location", "depth_model", "depth_resolution", "duration", "fps", "frame_ratio", "generate_audio", "keep_depth", "model", "prompt", "ratio", "resolution", "source"]), }; export function parseArgv(argv) { const [group, maybeAction, ...rest] = argv; if (!group) { return { group: "help", action: undefined, options: {} }; } if (group === "--help" || group === "-h") { return { group: "help", action: undefined, options: {} }; } if (group === "--version" || group === "-v") { return { group: "version", action: undefined, options: {} }; } if (!COMMANDS.has(group)) { throw new Error(`Unknown command: ${group}`); } if (group === "help" && maybeAction && !maybeAction.startsWith("--")) { return validateCommandOptions({ group: "help", action: undefined, options: { command: maybeAction, ...parseOptions(rest, repeatableOptionsFor("help")) }, }); } const hasAction = GROUP_ACTIONS.has(group); if (hasAction && isHelpToken(maybeAction)) { return { group, action: undefined, options: { help: true } }; } if (!hasAction && isHelpToken(maybeAction)) { return { group, action: undefined, options: { help: true } }; } const action = hasAction ? maybeAction : undefined; const optionTokens = hasAction ? rest : argv.slice(1); const hasHelpOption = optionTokens.some((token) => token === "--help" || token === "-h") || (optionTokens.length === 1 && optionTokens[0] === "help"); if (hasHelpOption) { return validateCommandOptions({ group, action, options: { ...parseOptions(optionTokens.filter((token) => token !== "help" && token !== "--help" && token !== "-h"), repeatableOptionsFor(group, action)), help: true, }, }); } return validateCommandOptions({ group, action, options: parseOptions(optionTokens, repeatableOptionsFor(group, action)), }); } function isHelpToken(token) { return token === "help" || token === "--help" || token === "-h"; } function parseOptions(tokens, repeatableOptions = REPEATABLE_OPTIONS) { const options = {}; const mediaInputs = []; for (let index = 0; index < tokens.length; index += 1) { const token = tokens[index]; if (token === "-o") { const output = tokens[index + 1]; if (!output || output.startsWith("-")) { throw new Error("Missing value for -o."); } options.output = output; index += 1; continue; } if (!token.startsWith("--")) { throw new Error(`Unexpected argument: ${token}`); } const name = token.slice(2).replaceAll("-", "_"); const next = tokens[index + 1]; if (!next || next.startsWith("--")) { options[name] = true; continue; } if (repeatableOptions.has(name)) { options[name] = [...asArray(options[name]), next]; } else { options[name] = next; } if (MEDIA_INPUT_OPTIONS.has(name)) { mediaInputs.push({ name, value: next }); } index += 1; } if (mediaInputs.length > 0) { Object.defineProperty(options, "__media_inputs", { value: mediaInputs, enumerable: false, writable: true, }); } return options; } function repeatableOptionsFor(group, action) { if (group === "image" && action === "generate") { return new Set([...REPEATABLE_OPTIONS, "file"]); } if (group === "video" && action === "generate") { return new Set([...REPEATABLE_OPTIONS, "file"]); } if (group === "video" && action === "copy") { return REPEATABLE_OPTIONS; } return REPEATABLE_OPTIONS; } function asArray(value) { if (value === undefined) return []; return Array.isArray(value) ? value : [value]; } function validateCommandOptions(command) { const key = command.action ? `${command.group} ${command.action}` : command.group; const allowed = COMMAND_OPTIONS[key] ?? new Set(); for (const option of Object.keys(command.options)) { if (option.startsWith("_")) continue; if (GLOBAL_OPTIONS.has(option) || allowed.has(option)) continue; const flag = `--${option.replaceAll("_", "-")}`; const helpCommand = command.action ? `flatkey ${command.group} ${command.action} --help` : `flatkey ${command.group} --help`; throw new Error(`Unknown option ${flag} for flatkey ${key}. Run \`${helpCommand}\` to see supported options.`); } return command; } export async function main(argv, deps = {}) { const stdout = deps.stdout ?? process.stdout; const stderr = deps.stderr ?? process.stderr; const command = parseArgv(argv); if (command.options.help) { const result = await runCommand(command, { ...deps, stdout, stderr }); stdout.write(`${formatHuman(result)}\n`); return; } if (command.group === "onboard") { const { writeConfig } = await import("./config.js"); const configPath = await writeConfig({ apiKey: command.options.api_key, configDir: deps.configDir }); stdout.write(`Saved Flatkey config: ${configPath}\n`); await maybeWriteUpdateNotice(command, { ...deps, stderr }); return; } const result = await runCommand(command, { ...deps, stdout, stderr }); if (result !== undefined) { stdout.write( command.options.json ? `${JSON.stringify(result)}\n` : `${formatHuman(result)}\n`, ); } await maybeWriteUpdateNotice(command, { ...deps, stderr }); } export async function runCommand(command, deps = {}) { const stdout = deps.stdout ?? process.stdout; const stderr = deps.stderr ?? process.stderr; if (command.group === "help") { const { getAiHelp, getCommandHelp, getHumanHelp } = await import("./help.js"); if (command.options.command) return getCommandHelp(command.options.command); return command.options.ai ? getAiHelp() : getHumanHelp(); } if (command.options.help) { const { getCommandHelp } = await import("./help.js"); return getCommandHelp(command.group, command.action); } if (command.group === "version") { const version = await readPackageVersion(); return command.options.json ? { version } : version; } if (command.group === "models") { return handleModels(command, { ...deps, stdout, stderr }); } if (command.group === "login") { return handleLogin(command, { ...deps, stdout, stderr }); } if (command.group === "logout") { return handleLogout(command, deps); } if (command.group === "auth") { if (command.action !== "status") { throw new Error(`Unknown action for auth: ${command.action}`); } return handleAuthStatus(command, deps); } if (command.group === "credits" || command.group === "status") { return handleUtility(command, { ...deps, stdout, stderr }); } if (["image", "video", "audio", "text"].includes(command.group)) { if (command.group === "audio" && command.action === "voices") { return handleVoices(command, { ...deps, stdout, stderr }); } const validAction = command.group === "audio" ? ["generate", "sfx", "music"].includes(command.action) : command.group === "image" ? ["generate", "upload"].includes(command.action) : command.group === "video" ? ["generate", "copy"].includes(command.action) : command.action === "generate"; if (!validAction) { throw new Error(`Unknown action for ${command.group}: ${command.action}`); } if (command.group === "image" && command.action === "upload") { return handleImageUpload(command, { ...deps, stdout, stderr }); } return handleGenerate(command, { ...deps, stdout, stderr }); } throw new Error(`Unknown command: ${command.group}`); } async function handleLogin(command, deps) { const { ensureDeviceId, readConfig, resolveOrigins, writeAuthConfig } = await import("./config.js"); const { DEFAULT_CONSOLE_URL, createDeviceAuthorization, pollDeviceAuthorization } = await import("./api.js"); const deviceId = await ensureDeviceId({ configDir: deps.configDir }); const version = await readPackageVersion(); const { consoleOrigin } = await resolveOrigins({ consoleUrl: command.options.console_url, env: deps.env ?? process.env, configDir: deps.configDir, }); const requestOptions = { consoleUrl: consoleOrigin ?? DEFAULT_CONSOLE_URL, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), }; const authorization = await createDeviceAuthorization({ deviceId, clientName: "flatkey-cli", clientVersion: version, ...requestOptions, }); const data = authorization?.data ?? authorization; if (!data?.device_code || !data?.verification_uri_complete) { throw new Error("Flatkey login failed: missing device authorization response."); } if (!command.options.json) { deps.stdout?.write?.(`Open this URL to approve Flatkey CLI:\n${data.verification_uri_complete}\n\n`); } if (command.options.open !== false && command.options.no_open !== true) { await openBrowser(data.verification_uri_complete, deps); } const initialIntervalMs = Math.max(Number(data.interval ?? 5), 5) * 1000; const deadline = Date.now() + Math.max(Number(data.expires_in ?? 600), 1) * 1000; const startedAt = Date.now(); while (Date.now() < deadline) { await delay(nextLoginPollDelay(startedAt, initialIntervalMs), deps); const poll = await pollDeviceAuthorization({ deviceCode: data.device_code, ...requestOptions, }); const pollData = poll?.data ?? poll; if (pollData?.status === "approved") { const account = accountFromAuthData(pollData); if (!pollData.api_key) { const saved = await readConfig(deps.configDir); if (typeof saved?.apiKey === "string" && saved.apiKey.trim() !== "") { const configPath = await writeAuthConfig({ apiKey: saved.apiKey, auth: { deviceId, userId: pollData.user_id ?? saved.auth?.userId, tokenId: pollData.token_id ?? saved.auth?.tokenId, account: account ?? saved.auth?.account, loginAt: Math.floor(Date.now() / 1000), }, configDir: deps.configDir, }); return command.options.json ? { success: true, configPath, account: stripDisplayOnlyIds(account ?? saved.auth?.account), reusedConfig: true, } : `Flatkey CLI already authorized. Saved config: ${configPath}`; } throw new Error("Flatkey login was approved, but no API key was returned. The authorization may have already been consumed. Run `flatkey login` again."); } const configPath = await writeAuthConfig({ apiKey: pollData.api_key, auth: { deviceId, userId: pollData.user_id, tokenId: pollData.token_id, account, loginAt: Math.floor(Date.now() / 1000), }, configDir: deps.configDir, }); return command.options.json ? { success: true, configPath, account: stripDisplayOnlyIds(account), } : `Flatkey CLI authorized. Saved config: ${configPath}`; } if (pollData?.status === "denied") { throw new Error("Flatkey login denied."); } if (pollData?.status === "expired") { throw new Error("Flatkey login expired. Run `flatkey login` again."); } } throw new Error("Flatkey login timed out. Run `flatkey login` again."); } function nextLoginPollDelay(startedAt, initialIntervalMs) { const elapsed = Date.now() - startedAt; const base = elapsed < 30_000 ? initialIntervalMs : elapsed < 120_000 ? Math.max(initialIntervalMs, 10_000) : Math.max(initialIntervalMs, 15_000); return base + Math.floor(Math.random() * 800); } async function delay(ms, deps = {}) { const sleep = deps.sleep ?? ((duration) => new Promise((resolve) => setTimeout(resolve, duration))); return sleep(ms); } async function openBrowser(url, deps = {}) { if (deps.openBrowser) return deps.openBrowser(url); const { spawn } = await import("node:child_process"); const platform = deps.platform ?? process.platform; const command = platform === "darwin" ? "open" : platform === "win32" ? "cmd" : "xdg-open"; const args = platform === "win32" ? ["/c", "start", "", url] : [url]; try { const child = spawn(command, args, { stdio: "ignore", detached: true }); child.unref(); } catch { // Printed URL is enough when open is unavailable. } } function maskKey(key) { if (!key) return ""; if (key.length <= 8) return `${key.slice(0, 2)}****${key.slice(-2)}`; return `${key.slice(0, 6)}...${key.slice(-4)}`; } function formatAuthStatus(status) { if (!status.authenticated) return "Not authenticated"; return `Authenticated via ${status.source}: ${status.key}`; } function firstNonEmpty(...values) { return values.find((value) => typeof value === "string" && value.trim() !== ""); } async function handleLogout(command, deps = {}) { const { clearSavedApiKey } = await import("./config.js"); const configPath = await clearSavedApiKey({ configDir: deps.configDir }); return command.options.json ? { success: true, configPath } : `Removed saved Flatkey API key from ${configPath}`; } async function handleAuthStatus(command, deps) { const { readConfig, resolveApiKey } = await import("./config.js"); const saved = await readConfig(deps.configDir); let apiKey; try { apiKey = await resolveApiKey({ apiKey: command.options.api_key, env: deps.env ?? process.env, configDir: deps.configDir, }); } catch { apiKey = ""; } const status = { authenticated: Boolean(apiKey), source: command.options.api_key ? "option" : saved?.apiKey ? "config" : (deps.env ?? process.env).FLATKEY_API_KEY ? "env" : "none", key: maskKey(apiKey), auth: saved?.auth ?? null, }; return command.options.json ? status : formatAuthStatus(status); } async function handleImageUpload(command, deps) { const { basename } = await import("node:path"); const { readFile } = await import("node:fs/promises"); const { resolveApiKey, resolveOrigins } = await import("./config.js"); const { DEFAULT_CONSOLE_URL, uploadTempMediaImage } = await import("./api.js"); const file = command.options.file; if (typeof file !== "string" || file.trim() === "") { throw new Error("Missing --file value. Run `flatkey image upload --help` to see supported options."); } const media = mediaInfoFromPath(file); if (!media || media.kind !== "image") { throw new Error(`Unsupported image file type: ${file}`); } const apiKey = await resolveApiKey({ apiKey: command.options.api_key, env: deps.env ?? process.env, configDir: deps.configDir, }); const { consoleOrigin } = await resolveOrigins({ consoleUrl: command.options.console_url, env: deps.env ?? process.env, configDir: deps.configDir, }); const response = await uploadTempMediaImage({ apiKey, baseUrl: consoleOrigin ?? DEFAULT_CONSOLE_URL, file: await readFile(await expandHomePath(file)), filename: basename(file), contentType: media.contentType, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), }); const data = response?.data ?? response; const signedUrl = extractUploadedMediaUrl(response); if (!signedUrl) { throw new Error("Image upload failed: missing signed_url."); } return { kind: "upload", url: signedUrl, objectKey: data?.object_key, expiresAt: data?.expires_at, expiresIn: data?.expires_in, response, }; } async function handleGenerate(command, deps) { const { resolveApiKey, resolveOrigins } = await import("./config.js"); const { generateAudio, generateAudioMusic, generateAudioSfx, generateImage, generateText, generateVideo, DEFAULT_CONSOLE_URL, getVideo, planAudioMusicRequest, planAudioRequest, planAudioSfxRequest, planImageRequest, planTextRequest, planVideoRequest, uploadTempMediaImage, uploadTempMediaVideo, } = await import("./api.js"); const { createAnimation } = await import("./animation.js"); const { prepareVideoCopy } = await import("./video-copy.js"); const apiKey = command.options.dry_run ? (command.options.api_key ?? "FLATKEY_API_KEY") : await resolveApiKey({ apiKey: command.options.api_key, env: deps.env ?? process.env, configDir: deps.configDir, }); const { routerOrigin } = await resolveOrigins({ baseUrl: command.options.base_url, consoleUrl: command.options.console_url, env: deps.env ?? process.env, configDir: deps.configDir, }); const { consoleOrigin: tempMediaBaseUrl } = await resolveOrigins({ consoleUrl: command.options.console_url, env: deps.env ?? process.env, configDir: deps.configDir, }); const options = { ...command.options, apiKey, baseUrl: routerOrigin ?? DEFAULT_BASE_URL, tempMediaBaseUrl: tempMediaBaseUrl ?? DEFAULT_CONSOLE_URL, env: deps.env ?? process.env, fetch: deps.fetch, verboseLog: verboseLogger(deps.stderr, command.options.verbose), }; if (Array.isArray(command.options.__media_inputs)) { options.__media_inputs = command.options.__media_inputs; } let videoCopy; if (command.group === "video" && command.action === "copy") { if (!command.options.source) { throw new Error("Missing --source value. Run `flatkey video copy --help` to see supported options."); } videoCopy = await (deps.prepareVideoCopy ?? prepareVideoCopy)(command.options, deps); options.prompt ??= "Recreate the reference video as faithfully as possible while following the supplied depth motion."; options.duration = videoCopy.duration; options.__media_inputs = [{ name: "depth_video", value: videoCopy.depthPath, kind: "local", optionName: "file", role: "reference_video", }]; options.__copy_reference_mode = "depth-video"; } if (command.group === "image" || command.group === "video") { try { await prepareMediaInputs(command, options, { apiKey, baseUrl: options.baseUrl, tempMediaBaseUrl: tempMediaBaseUrl ?? DEFAULT_CONSOLE_URL, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), uploadTempMediaImage, uploadTempMediaVideo, }); } catch (error) { await videoCopy?.cleanup?.(); throw error; } } if (command.group === "video" && command.action === "copy" && !options.__media_inputs?.some((entry) => entry.kind === "video")) { throw new Error("Video copy failed to prepare its depth-video reference."); } if (command.options.dry_run) { const request = command.group === "image" ? planImageRequest(options) : command.group === "video" ? planVideoRequest(options) : command.group === "audio" ? command.action === "sfx" ? planAudioSfxRequest(options) : command.action === "music" ? planAudioMusicRequest(options) : planAudioRequest(options) : planTextRequest(options); await videoCopy?.cleanup?.(); return { dryRun: true, kind: command.group, request: redactRequest(request), videoCopy: scrubVideoCopy(videoCopy), copyReferenceMode: options.__copy_reference_mode, }; } const animation = createAnimation({ json: Boolean(command.options.json), stream: deps.stderr, }); animation.start(command.group); try { let response; try { response = command.group === "image" ? await generateImage(options) : command.group === "video" ? await generateVideo(options) : command.group === "audio" ? command.action === "sfx" ? await generateAudioSfx(options) : command.action === "music" ? await generateAudioMusic(options) : await generateAudio(options) : await generateText(options); response = command.group === "video" ? await waitForVideoResult(response, { ...options, getVideo, sleep: deps.sleep }) : response; } catch (error) { if (!videoCopy || options.__copy_reference_mode !== "depth-video" || !isDepthVideoFetchFailure(error)) { throw error; } options.__media_inputs = (videoCopy.referencePaths ?? []).map((value, index) => ({ name: `depth_frame_${String(index + 1).padStart(2, "0")}`, value, kind: "local", optionName: "image", role: index === 0 ? "first_frame" : index === (videoCopy.referencePaths.length - 1) ? "last_frame" : "reference_image", })); await prepareMediaInputs(command, options, { apiKey, baseUrl: options.baseUrl, tempMediaBaseUrl: tempMediaBaseUrl ?? DEFAULT_CONSOLE_URL, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), uploadTempMediaImage, uploadTempMediaVideo, }); options.__copy_reference_mode = "depth-keyframes-fallback"; response = await generateVideo(options); response = await waitForVideoResult(response, { ...options, getVideo, sleep: deps.sleep }); } const artifactResponse = response; if (command.group === "text") { const text = extractText(response); const output = await writeTextOutput(text, command.options.output); return { kind: command.group, text, output, response }; } const outDir = command.options.out ?? "flatkey-output"; const output = command.options.output ?? (command.group === "video" ? await nextArtifactPath({ kind: command.group, outDir }) : undefined); const artifacts = await persistArtifacts({ kind: command.group, response: artifactResponse, outDir, output, fetch: deps.fetch, }); return { kind: command.group, artifacts, response: scrubArtifactResponse(artifactResponse), ...(videoCopy ? { copyReferenceMode: options.__copy_reference_mode } : {}), }; } finally { animation.stop(); await videoCopy?.cleanup?.(); } } async function prepareMediaInputs(command, options, deps) { const mediaInputs = orderedMediaInputs(command, options); if (mediaInputs.length === 0) return; assertMediaReferenceLimit(mediaInputs, command.group, options.model); const resolved = []; for (const input of mediaInputs) { if (input.kind === "local") { resolved.push(await uploadLocalMedia(input.value, command.group, deps, input.optionName ?? input.name)); } else { resolved.push(await confirmRemoteMediaUrl(input.value, command.group, deps, input.name)); } } options.__media_inputs = resolved; } function assertMediaReferenceLimit(mediaInputs, commandGroup, model) { const imageInputs = mediaInputs.filter((entry) => entry.kind !== "video"); const videoInputs = mediaInputs.filter((entry) => entry.kind === "video"); if (isSeedance25Model(model)) { if (imageInputs.length > 30) { throw new Error(`Too many reference images for flatkey ${commandGroup} generate with Seedance 2.5: maximum 30.`); } if (videoInputs.length > 10) { throw new Error(`Too many reference videos for flatkey ${commandGroup} generate with Seedance 2.5: maximum 10.`); } return; } if (imageInputs.length > MAX_REFERENCE_IMAGES) { throw new Error(`Too many reference images for flatkey ${commandGroup} generate: maximum ${MAX_REFERENCE_IMAGES}.`); } } function isSeedance25Model(model) { return String(model ?? "").toLowerCase().replaceAll(/[-_.]/g, "").includes("seedance25"); } function orderedMediaInputs(command, options) { const mediaInputs = Array.isArray(options.__media_inputs) ? options.__media_inputs : []; if (mediaInputs.length > 0 && mediaInputs[0] && Object.prototype.hasOwnProperty.call(mediaInputs[0], "kind")) { return mediaInputs; } if (mediaInputs.length > 0) { return mediaInputs.map((entry) => ({ name: entry.name, value: entry.value, kind: entry.name.endsWith("_url") ? "url" : "local", })); } const legacyInputs = []; const pushLocal = (name, value) => { for (const file of asArray(value)) { legacyInputs.push({ name, value: file, kind: "local" }); } }; const pushUrl = (name, value) => { for (const url of asArray(value)) { legacyInputs.push({ name, value: url, kind: "url" }); } }; pushLocal("file", options.file); pushLocal("image", options.image); pushUrl("image_url", options.image_url); if (command.group === "video") { pushUrl("video_url", options.video_url); pushLocal("first_frame", options.first_frame); pushUrl("first_frame_url", options.first_frame_url); pushLocal("last_frame", options.last_frame); pushUrl("last_frame_url", options.last_frame_url); } return legacyInputs; } async function uploadLocalMedia(file, commandGroup, deps, optionName) { const { basename } = await import("node:path"); const { readFile } = await import("node:fs/promises"); const media = mediaInfoFromPath(file); const allowedKinds = allowedMediaKindsForOption(commandGroup, optionName); if (!media || !allowedKinds.has(media.kind)) { throw new Error(`Unsupported --${optionName.replaceAll("_", "-")} file type for flatkey ${commandGroup} generate: ${file}`); } const uploader = media.kind === "video" ? deps.uploadTempMediaVideo : deps.uploadTempMediaImage; const response = await uploader({ apiKey: deps.apiKey, baseUrl: deps.tempMediaBaseUrl ?? deps.baseUrl, file: await readFile(await expandHomePath(file)), filename: basename(file), contentType: media.contentType, fetch: deps.fetch, verbose: deps.verbose, verboseLog: deps.verboseLog, }); const url = extractUploadedMediaUrl(response); if (!url) throw new Error(`Media upload failed: missing signed_url for ${file}`); return { name: optionName, value: url, kind: media.kind, role: mediaRoleFromOption(optionName, media.kind), mime: media.contentType, }; } async function confirmRemoteMediaUrl(url, commandGroup, deps, optionName) { const fetchImpl = deps.fetch ?? fetch; const response = await fetchImpl(url, { method: "HEAD" }); const media = mediaInfoFromMime(headerValue(response?.headers, "content-type")); const allowedKinds = allowedMediaKindsForOption(commandGroup, optionName); if (!media || !allowedKinds.has(media.kind)) { throw new Error(`Unsupported --${optionName.replaceAll("_", "-")} MIME type for flatkey ${commandGroup} generate: ${headerValue(response?.headers, "content-type") ?? "unknown"}`); } return { name: optionName, value: url, kind: media.kind, role: mediaRoleFromOption(optionName, media.kind), mime: media.contentType, }; } function extractUploadedMediaUrl(response) { const data = response?.data ?? response; return data?.signed_url ?? data?.signedUrl ?? data?.url ?? response?.signed_url ?? response?.signedUrl ?? response?.url; } function mediaInfoFromPath(file) { const lower = String(file).toLowerCase(); if (lower.endsWith(".jpg") || lower.endsWith(".jpeg")) return { kind: "image", contentType: "image/jpeg" }; if (lower.endsWith(".png")) return { kind: "image", contentType: "image/png" }; if (lower.endsWith(".webp")) return { kind: "image", contentType: "image/webp" }; if (lower.endsWith(".mp4")) return { kind: "video", contentType: "video/mp4" }; if (lower.endsWith(".mov")) return { kind: "video", contentType: "video/quicktime" }; if (lower.endsWith(".bmp")) return { kind: "image", contentType: "image/bmp" }; if (lower.endsWith(".tif") || lower.endsWith(".tiff")) return { kind: "image", contentType: "image/tiff" }; if (lower.endsWith(".gif")) return { kind: "image", contentType: "image/gif" }; if (lower.endsWith(".heic")) return { kind: "image", contentType: "image/heic" }; if (lower.endsWith(".heif")) return { kind: "image", contentType: "image/heif" }; return undefined; } function mediaInfoFromMime(contentType) { if (typeof contentType !== "string") return undefined; const lower = contentType.toLowerCase(); if (lower.startsWith("image/jpeg")) return { kind: "image", contentType: "image/jpeg" }; if (lower.startsWith("image/png")) return { kind: "image", contentType: "image/png" }; if (lower.startsWith("image/webp")) return { kind: "image", contentType: "image/webp" }; if (lower.startsWith("video/mp4")) return { kind: "video", contentType: "video/mp4" }; if (lower.startsWith("video/quicktime")) return { kind: "video", contentType: "video/quicktime" }; if (lower.startsWith("image/bmp")) return { kind: "image", contentType: "image/bmp" }; if (lower.startsWith("image/tiff")) return { kind: "image", contentType: "image/tiff" }; if (lower.startsWith("image/gif")) return { kind: "image", contentType: "image/gif" }; if (lower.startsWith("image/heic")) return { kind: "image", contentType: "image/heic" }; if (lower.startsWith("image/heif")) return { kind: "image", contentType: "image/heif" }; return undefined; } function mediaRoleFromOption(optionName, kind) { if (optionName === "first_frame" || optionName === "first_frame_url") return "first_frame"; if (optionName === "last_frame" || optionName === "last_frame_url") return "last_frame"; if (kind === "video") return "reference_video"; return "reference_image"; } function allowedMediaKindsForOption(commandGroup, optionName) { if (commandGroup === "image") return new Set(["image"]); if (optionName === "file") return new Set(["image", "video"]); if (optionName === "video_url") return new Set(["video"]); if (optionName === "first_frame" || optionName === "first_frame_url" || optionName === "last_frame" || optionName === "last_frame_url" || optionName === "image" || optionName === "image_url") { return new Set(["image"]); } return new Set(["image"]); } function headerValue(headers, name) { if (!headers) return undefined; if (typeof headers.get === "function") { return headers.get(name) ?? headers.get(name.toLowerCase()); } return headers[name] ?? headers[name.toLowerCase()]; } async function waitForVideoResult(response, options) { if (hasArtifact(response)) return response; const taskId = videoTaskId(response); if (!taskId) return response; const timeoutMs = parsePositiveInteger( options.video_wait_timeout_ms ?? options.env?.FLATKEY_VIDEO_WAIT_TIMEOUT_MS, 600_000, ); const intervalMs = parsePositiveInteger( options.video_poll_interval_ms ?? options.env?.FLATKEY_VIDEO_POLL_INTERVAL_MS, 5_000, ); const deadline = Date.now() + timeoutMs; let last = response; while (Date.now() <= deadline) { last = await options.getVideo(options, taskId); if (hasArtifact(last)) return last; if (isVideoDone(last)) return withVideoContentFallback(last, options, taskId); if (isVideoFailed(last)) { const message = last?.error?.message ?? last?.message ?? `Video generation failed: ${taskId}`; throw new Error(message); } await delay(intervalMs, { sleep: options.sleep }); } throw new Error(`Video task still processing after ${Math.round(timeoutMs / 1000)}s: ${taskId}`); } function withVideoContentFallback(response, options, taskId) { const baseUrl = String(options.baseUrl ?? "").replace(/\/$/, ""); if (!baseUrl || !taskId) return response; return { ...response, metadata: { ...(response.metadata ?? {}), url: `${baseUrl}/v1/videos/${encodeURIComponent(taskId)}/content`, }, }; } function hasArtifact(response) { return Boolean( response?.metadata?.url || response?.metadata?.temp_url || response?.url || response?.temp_url || response?.video_url?.url || response?.video?.url || response?.video?.temp_url || response?.data?.some?.((item) => item?.url || item?.temp_url || item?.b64_json || item?.base64 || item?.data) || response?.artifacts?.some?.((item) => item?.url || item?.temp_url || item?.path) || response?.content?.some?.((item) => item?.url || item?.video_url?.url || item?.data_url || item?.b64_json || item?.base64 || item?.data), ); } function videoTaskId(response) { return firstNonEmpty(response?.id, response?.task_id, response?.taskId, response?.data?.id, response?.data?.task_id); } function isVideoDone(response) { return ["completed", "done", "succeeded", "success"].includes(String(response?.status ?? "").toLowerCase()); } function isVideoFailed(response) { return ["failed", "failure", "cancelled", "canceled"].includes(String(response?.status ?? "").toLowerCase()) || Boolean(response?.error); } function parsePositiveInteger(value, fallback) { const parsed = Number.parseInt(value, 10); return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback; } function scrubArtifactResponse(value) { if (Array.isArray(value)) return value.map(scrubArtifactResponse); if (!value || typeof value !== "object") { if (typeof value === "string" && value.startsWith("data:")) return ""; return value; } return Object.fromEntries( Object.entries(value).map(([key, entry]) => { if (["b64_json", "base64", "data"].includes(key) && typeof entry === "string") { return [key, ""]; } if (["url", "data_url", "dataUrl"].includes(key) && typeof entry === "string" && entry.startsWith("data:")) { return [key, ""]; } return [key, scrubArtifactResponse(entry)]; }), ); } function scrubVideoCopy(value) { if (!value) return undefined; return { source: value.source, depthPath: value.depthPath, referencePaths: value.referencePaths, duration: value.duration, sourceInfo: value.sourceInfo, helper: value.helper, }; } function isDepthVideoFetchFailure(error) { const code = String(error?.code ?? "").toLowerCase(); const message = String(error?.message ?? error).toLowerCase(); return code.includes("fail_to_fetch") || code.includes("video_fetch") || message.includes("fail_to_fetch") || message.includes("failed to fetch") || message.includes("unable to fetch") || message.includes("video reference"); } async function handleVoices(command, deps) { const { resolveApiKey, resolveOrigins } = await import("./config.js"); const { getVoices } = await import("./api.js"); const apiKey = await resolveApiKey({ apiKey: command.options.api_key, env: deps.env ?? process.env, configDir: deps.configDir, }); const { routerOrigin } = await resolveOrigins({ baseUrl: command.options.base_url, env: deps.env ?? process.env, configDir: deps.configDir, }); return getVoices({ apiKey, baseUrl: routerOrigin, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), }); } function extractText(response) { return response?.choices?.[0]?.message?.content ?? response?.output_text ?? response?.text ?? ""; } async function writeTextOutput(text, output) { if (!output) return undefined; output = await expandHomePath(output); const { mkdir, writeFile } = await import("node:fs/promises"); const { dirname } = await import("node:path"); await mkdir(dirname(output), { recursive: true }); await writeFile(output, text); return output; } async function expandHomePath(path) { if (typeof path !== "string") return path; if (path !== "~" && !path.startsWith("~/")) return path; const { homedir } = await import("node:os"); const { join } = await import("node:path"); if (path === "~") return homedir(); return join(homedir(), path.slice(2)); } function redactRequest(request) { return { ...request, headers: Object.fromEntries( Object.entries(request.headers ?? {}).map(([key, value]) => [ key, key.toLowerCase() === "authorization" ? "Bearer " : value, ]), ), }; } async function handleUtility(command, deps) { const { readConfig, resolveApiKey, resolveOrigins } = await import("./config.js"); const saved = await readConfig(deps.configDir); const { getCredits, getStatus } = await import("./api.js"); const apiKey = await resolveApiKey({ apiKey: command.options.api_key, env: deps.env ?? process.env, configDir: deps.configDir, }); const { consoleOrigin } = await resolveOrigins({ baseUrl: command.options.base_url, env: deps.env ?? process.env, configDir: deps.configDir, }); const options = { apiKey, baseUrl: consoleOrigin, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), }; if (command.group === "credits") return getCredits(options); const status = sanitizeStatusResponse(await getStatus(options)); const account = effectiveAccountForStatus({ command, saved, apiKey }); if (!account || !status || typeof status !== "object" || Array.isArray(status) || status.account !== undefined) { return command.options.json ? status : extractStatusDisplayFields(status); } const mergedStatus = sanitizeStatusResponse({ ...status, account }); return command.options.json ? mergedStatus : extractStatusDisplayFields(mergedStatus); } function effectiveAccountForStatus({ command, saved, apiKey }) { if (command.options.api_key || !saved?.apiKey || saved.apiKey !== apiKey) return null; if (saved.auth?.account !== undefined) return saved.auth.account; return accountFromAuthData(saved.auth); } function accountFromAuthData(data) { if (!data || typeof data !== "object") return null; const email = data.account?.email ?? data.email ?? data.userEmail ?? data.user_email; const name = data.account?.name ?? data.name; const userId = data.account?.userId ?? data.account?.user_id ?? data.userId ?? data.user_id; if (email === undefined && name === undefined && userId === undefined) return null; return Object.fromEntries( Object.entries({ email, name, userId, }).filter(([, value]) => value !== undefined && value !== null), ); } function sanitizeStatusResponse(status) { if (!status || typeof status !== "object") return status; if (Array.isArray(status)) { return status.map((entry) => sanitizeStatusResponse(entry)); } return Object.fromEntries( Object.entries(status) .filter(([key]) => !["userId", "user_id"].includes(key)) .map(([key, value]) => [key, sanitizeStatusResponse(value)]), ); } function stripDisplayOnlyIds(value) { if (!value || typeof value !== "object") return value; if (Array.isArray(value)) { return value.map((entry) => stripDisplayOnlyIds(entry)); } return Object.fromEntries( Object.entries(value) .filter(([key]) => !["userId", "user_id", "tokenId", "token_id"].includes(key)) .map(([key, nested]) => [key, stripDisplayOnlyIds(nested)]), ); } function extractStatusDisplayFields(status) { if (!status || typeof status !== "object") return status; const email = status.email ?? status.account?.email ?? status.user?.email; const name = status.name ?? status.account?.name ?? status.user?.name; const result = {}; if (email !== undefined) result.email = email; if (name !== undefined) result.name = name; return result; } async function handleModels(command, deps) { const { resolveApiKey, resolveOrigins } = await import("./config.js"); const { getModels } = await import("./api.js"); const { normalizeModels } = await import("./models.js"); const apiKey = await resolveApiKey({ apiKey: command.options.api_key, env: deps.env ?? process.env, configDir: deps.configDir, }); const { consoleOrigin } = await resolveOrigins({ baseUrl: command.options.base_url, env: deps.env ?? process.env, configDir: deps.configDir, }); const response = await getModels({ apiKey, baseUrl: consoleOrigin, fetch: deps.fetch, verbose: command.options.verbose, verboseLog: verboseLogger(deps.stderr, command.options.verbose), }); return { models: normalizeModels(response, command.options.type) }; } function verboseLogger(stream, enabled) { if (!enabled) return () => {}; return (line) => { if (typeof line === "string") { stream?.write?.(`${line}\n`); } }; } function formatHuman(result) { if (typeof result === "string") return result; if (!result || typeof result !== "object") return String(result); if (result.dryRun && result.request) return formatDryRun(result); if (result.kind === "upload") return formatUploadResult(result); if (result.kind) return formatGenerationResult(result); if (Array.isArray(result.models)) return formatModels(result.models); if (Array.isArray(result.voices)) return formatVoices(result.voices); if (typeof result.authenticated === "boolean") return formatAuthStatus(result); return formatKeyValues(result); } function formatDryRun(result) { const lines = [ `Dry run: ${result.kind}`, `${result.request.method ?? "GET"} ${result.request.url}`, ]; if (result.request.body !== undefined) { lines.push("Body:"); lines.push(JSON.stringify(result.request.body, null, 2)); } return lines.join("\n"); } function formatUploadResult(result) { const lines = ["Image uploaded:"]; if (result.url) lines.push(`URL: ${result.url}`); if (result.expiresIn) lines.push(`Expires in: ${result.expiresIn}s`); return lines.join("\n"); } function formatGenerationResult(result) { if (result.kind === "text") { const lines = [result.text || "(empty text)"]; if (result.output) lines.push(`Saved: ${result.output}`); return lines.join("\n"); } const artifacts = Array.isArray(result.artifacts) ? result.artifacts : []; if (artifacts.length === 0) return `${titleCase(result.kind)} generated. No artifacts returned.`; const lines = [`${titleCase(result.kind)} generated:`]; for (const artifact of artifacts) { if (artifact.path) lines.push(`- Saved: ${artifact.path}`); else if (artifact.url) lines.push(`- URL: ${artifact.url}`); else lines.push(`- ${JSON.stringify(artifact)}`); } return lines.join("\n"); } function formatModels(models) { if (models.length === 0) return "No models available."; return [ `Available models (${models.length}):`, formatTable( ["Model", "Type", "Source"], models.map((model) => [ model.id, model.type ?? "", model.source ?? "", ]), ), ].join("\n"); } function formatVoices(voices) { if (voices.length === 0) return "No voices available."; const lines = [`Available voices (${voices.length}):`]; for (const voice of voices) { const id = voice.voice_id ?? voice.id; const name = voice.name ? `${voice.name} ` : ""; lines.push(`- ${name}${id ? `(${id})` : ""}`.trim()); } return lines.join("\n"); } function formatKeyValues(result) { const entries = Object.entries(result); if (entries.length === 0) return "OK"; const lines = entries .map(([key, value]) => `${humanLabel(key)}: ${formatScalar(value)}`) const warning = lowCreditWarning(result); if (warning) lines.push(warning); return lines.join("\n"); } function lowCreditWarning(result) { const credits = extractCreditAmount(result); if (credits === undefined || credits >= 10) return ""; return `Low credit warning: remaining credits are ${credits}. Top up soon.`; } function extractCreditAmount(result) { const creditKeys = new Set([ "credit", "credits", "remaining", "balance", "total_available", "totalAvailable", "available_balance", "availableBalance", ]); const stack = [result]; const seen = new Set(); while (stack.length > 0) { const value = stack.shift(); if (!value || typeof value !== "object" || seen.has(value)) continue; seen.add(value); for (const [key, entry] of Object.entries(value)) { if (creditKeys.has(key)) { const number = Number(entry); if (Number.isFinite(number)) return number; } if (entry && typeof entry === "object") stack.push(entry); } } return undefined; } function formatScalar(value) { if (value === null || value === undefined) return ""; if (typeof value === "object") return JSON.stringify(value); return String(value); } function humanLabel(key) { return key .replaceAll("_", " ") .replace(/([a-z])([A-Z])/g, "$1 $2") .replace(/^./, (char) => char.toUpperCase()); } function titleCase(value) { return String(value).replace(/^./, (char) => char.toUpperCase()); } function formatTable(headers, rows) { const widths = headers.map((header, index) => Math.max( header.length, ...rows.map((row) => String(row[index] ?? "").length), )); const line = (cells) => cells .map((cell, index) => String(cell ?? "").padEnd(widths[index])) .join(" ") .trimEnd(); return [ line(headers), line(widths.map((width) => "-".repeat(width))), ...rows.map(line), ].join("\n"); } async function readPackageVersion() { const { readFile } = await import("node:fs/promises"); const packageUrl = new URL("../package.json", import.meta.url); return JSON.parse(await readFile(packageUrl, "utf8")).version; } async function maybeWriteUpdateNotice(command, deps = {}) { if (command.options.json || command.options.help || command.group === "help" || command.group === "version") { return; } try { const current = await readPackageVersion(); const latest = await fetchLatestPackageVersion(deps); if (!latest || compareVersions(latest, current) <= 0) return; deps.stderr?.write?.([ `\nFlatkey CLI update available: ${current} -> ${latest}`, "Upgrade: npm install -g @flatkey-ai/cli", "", ].join("\n")); } catch { // Update checks must never break normal CLI commands. } } async function fetchLatestPackageVersion(deps = {}) { const { CLI_REQUEST_HEADERS } = await import("./requestHeaders.js"); const fetchImpl = deps.fetch ?? globalThis.fetch; if (typeof fetchImpl !== "function") return undefined; const response = await fetchImpl("https://registry.npmjs.org/@flatkey-ai%2fcli/latest", { headers: CLI_REQUEST_HEADERS, signal: typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function" ? AbortSignal.timeout(750) : undefined, }); if (!response?.ok) return undefined; const body = await response.json(); return typeof body?.version === "string" ? body.version : undefined; } function compareVersions(left, right) { const leftParts = parseVersionParts(left); const rightParts = parseVersionParts(right); for (let index = 0; index < Math.max(leftParts.length, rightParts.length); index += 1) { const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0); if (difference !== 0) return difference; } return 0; } function parseVersionParts(version) { return String(version) .split("-", 1)[0] .split(".") .map((part) => Number.parseInt(part, 10)) .map((part) => Number.isFinite(part) ? part : 0); } # ===== file: src/config.js ===== import { mkdir, readFile, writeFile, chmod } from "node:fs/promises"; import { randomUUID } from "node:crypto"; import { homedir } from "node:os"; import { join } from "node:path"; export const ROUTER_ORIGIN_KEY = "routerOrigin"; export const CONSOLE_ORIGIN_KEY = "consoleOrigin"; export function getDefaultConfigDir() { return join(homedir(), ".config", "flatkey"); } export function getConfigPath(configDir = getDefaultConfigDir()) { return join(configDir, "config.json"); } export async function resolveApiKey({ apiKey, env = process.env, configDir = getDefaultConfigDir(), } = {}) { if (apiKey) return apiKey; const saved = await readSavedConfig(configDir); if (saved?.apiKey) return saved.apiKey; if (env.FLATKEY_API_KEY) return env.FLATKEY_API_KEY; throw new Error( "Missing or invalid Flatkey API key. Run `flatkey login`, or create a key at https://console.flatkey.ai/keys and run `flatkey onboard --api-key `.", ); } export async function resolveOrigins({ baseUrl, consoleUrl, env = process.env, configDir = getDefaultConfigDir(), } = {}) { const saved = await readSavedConfig(configDir); return { routerOrigin: firstNonEmpty( baseUrl, saved?.[ROUTER_ORIGIN_KEY], saved?.ROUTER_ORIGIN, env.ROUTER_ORIGIN, ), consoleOrigin: firstNonEmpty( consoleUrl, baseUrl, saved?.[CONSOLE_ORIGIN_KEY], saved?.CONSOLE_ORIGIN, env.CONSOLE_ORIGIN, ), }; } export async function writeConfig({ apiKey, configDir = getDefaultConfigDir() }) { if (typeof apiKey !== "string" || apiKey.trim() === "") { throw new Error("Missing --api-key value. Create a key at https://console.flatkey.ai/keys, then run `flatkey onboard --api-key `."); } await mkdir(configDir, { recursive: true }); const configPath = getConfigPath(configDir); const saved = await readSavedConfig(configDir) ?? {}; await writeFile(configPath, `${JSON.stringify({ ...saved, apiKey }, null, 2)}\n`, { mode: 0o600, }); try { await chmod(configPath, 0o600); } catch (error) { if (process.platform !== "win32") throw error; } return configPath; } export async function writeAuthConfig({ apiKey, auth, configDir = getDefaultConfigDir(), }) { if (typeof apiKey !== "string" || apiKey.trim() === "") { throw new Error("Missing API key from Flatkey login response."); } const saved = await readSavedConfig(configDir) ?? {}; const next = { ...saved, apiKey, auth: { ...(saved.auth ?? {}), ...auth, type: "device", }, }; await mkdir(configDir, { recursive: true }); const configPath = getConfigPath(configDir); await writeFile(configPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, }); try { await chmod(configPath, 0o600); } catch (error) { if (process.platform !== "win32") throw error; } return configPath; } export async function ensureDeviceId({ configDir = getDefaultConfigDir() } = {}) { const saved = await readSavedConfig(configDir); if (typeof saved?.auth?.deviceId === "string" && saved.auth.deviceId) { return saved.auth.deviceId; } return randomUUID(); } export async function clearSavedApiKey({ configDir = getDefaultConfigDir() } = {}) { const saved = await readSavedConfig(configDir); if (!saved) return getConfigPath(configDir); const next = { ...saved }; delete next.apiKey; await mkdir(configDir, { recursive: true }); const configPath = getConfigPath(configDir); await writeFile(configPath, `${JSON.stringify(next, null, 2)}\n`, { mode: 0o600, }); return configPath; } export async function readConfig(configDir = getDefaultConfigDir()) { return readSavedConfig(configDir); } async function readSavedConfig(configDir) { try { return JSON.parse(await readFile(getConfigPath(configDir), "utf8")); } catch (error) { if (error.code === "ENOENT") return undefined; throw error; } } function firstNonEmpty(...values) { return values.find((value) => typeof value === "string" && value.trim() !== ""); } # ===== file: src/help.js ===== export function getAiHelp() { return `Flatkey CLI protocol for agents Setup: - Prefer browser auth: flatkey login - Or env: FLATKEY_API_KEY= - Create a key at https://console.flatkey.ai/keys - Or save key: flatkey onboard --api-key - Use --json for machine-readable output. JSON mode: - stdout contains only JSON. - stderr contains JSON errors on failure. - ASCII animation and human logs are disabled. Commands: - flatkey image generate --prompt "" --json [--model ] [--file ] [--image-url ] [--output image.png] - flatkey video generate --prompt "" --json [--model seedance2] [--file ] [--image-url ] [--video-url ] [--ratio 16:9] [--resolution 720p] [--output video.mp4] - flatkey video copy --source input.mp4 --json [--model seedance2] [--frame-ratio 80] [--depth-resolution 480p] [--output video.mp4] - flatkey audio generate --prompt "" --json [--voice-id ] [--model eleven_multilingual_v2] [--output speech.mp3] - flatkey audio sfx --prompt "" --json [--duration ] [--output sfx.mp3] - flatkey audio music --prompt "" --json [--music-length-ms ] [--output music.mp3] - flatkey audio voices --json - flatkey text generate --prompt "" --json [--model gpt-5.5] [--output text.txt] - flatkey credits --json - flatkey status --json - flatkey models --json [--type image|video|audio|text] - flatkey login [--no-open] [--console-url ] - flatkey logout - flatkey auth status --json - flatkey help --ai Environment: - FLATKEY_API_KEY: Flatkey API key. - ROUTER_ORIGIN: Override generation router origin, e.g. staging router. - CONSOLE_ORIGIN: Override console API origin, e.g. staging console. - Default router: https://router.flatkey.ai Recovery: - Missing key: create one at https://console.flatkey.ai/keys, then run flatkey onboard --api-key or set FLATKEY_API_KEY. - Unknown model: run flatkey models --json, then retry with a listed model id. - Unknown voice: run flatkey audio voices --json, then retry with a listed voice_id. - API failure: inspect stderr JSON or HTTP message, then retry only after fixing request or credits. `; } export function getHumanHelp() { return `Usage: flatkey [options] Commands: login Authorize CLI in browser logout Remove saved Flatkey API key auth status Show saved auth state onboard --api-key Save Flatkey API key from https://console.flatkey.ai/keys image generate --prompt Generate image image upload --file Upload local image and return a temporary URL video generate --prompt Generate video video copy --source Recreate a 5-15s video from Depth Anything V2 motion audio generate --prompt Generate speech with ElevenLabs voices audio sfx --prompt Generate sound effects audio music --prompt Generate music audio voices List available voices text generate --prompt Generate text credits Show remaining credits status Show usage/status models List available models help --ai Print agent-focused usage guide Global options: --json Print machine-readable JSON --file Attach local media input --image-url Add remote image input, repeatable --video-url Add remote video input, repeatable --output, -o Write generated output to a local file --verbose Print request/response logs to stderr --base-url Override Flatkey router URL Environment: ROUTER_ORIGIN Override generation router origin CONSOLE_ORIGIN Override console API origin --console-url Override Flatkey console URL for login Video options: --ratio 16:9, 9:16, 4:3, 3:4, 21:9, 1:1, or adaptive --resolution 480p, 720p, or 1080p `; } const COMMAND_HELP = { audio: `Usage: flatkey audio [options] Actions: generate --prompt Generate speech sfx --prompt Generate sound effects music --prompt Generate music voices List available voices Options: --json Print machine-readable JSON --output, -o Write generated output to a local file --model Override model id --voice-id Voice id for speech generation --duration Duration for sound effects --music-length-ms Music length in milliseconds --help Show audio help`, "audio generate": `Usage: flatkey audio generate --prompt [options] Options: --voice-id Voice id --model Model id, default eleven_multilingual_v2 --stability <0..1> Voice stability --similarity-boost <0..1> Voice similarity boost --style <0..1> Voice style --output, -o Write speech file --json Print machine-readable JSON`, "audio music": `Usage: flatkey audio music --prompt [options] Options: --music-length-ms Music length in milliseconds --output, -o Write music file --json Print machine-readable JSON`, "audio sfx": `Usage: flatkey audio sfx --prompt [options] Options: --duration Sound effect duration --output, -o Write sound effect file --json Print machine-readable JSON`, "audio voices": `Usage: flatkey audio voices [options] Options: --json Print machine-readable JSON`, credits: `Usage: flatkey credits [options] Options: --json Print machine-readable JSON`, auth: `Usage: flatkey auth [options] Actions: status Show saved auth state Options: --json Print machine-readable JSON`, "auth status": `Usage: flatkey auth status [options] Options: --json Print machine-readable JSON`, help: `Usage: flatkey help [command] [options] Options: --ai Print agent-focused usage guide`, image: `Usage: flatkey image [options] Commands: generate --prompt Generate image upload --file Upload local image and return a temporary URL Options: --json Print machine-readable JSON`, "image upload": `Usage: flatkey image upload --file [options] Options: --file Local image file to upload --json Print machine-readable JSON`, "image generate": `Usage: flatkey image generate --prompt [options] Options: --model Model id --size Image size for OpenAI-style image models --quality Image quality for supported models --n Number of images for supported models --file Local image input, repeatable --image-url Remote image input, repeatable --output, -o Write image file --json Print machine-readable JSON`, models: `Usage: flatkey models [options] Options: --type Filter: image, video, audio, or text --json Print machine-readable JSON`, login: `Usage: flatkey login [options] Options: --no-open Print approval URL without opening a browser --console-url Override Flatkey console URL --json Print machine-readable JSON`, logout: `Usage: flatkey logout [options] Options: --json Print machine-readable JSON`, onboard: `Usage: flatkey onboard --api-key Create a Flatkey API key first: https://console.flatkey.ai/keys Options: --api-key Flatkey API key to save`, status: `Usage: flatkey status [options] Options: --json Print machine-readable JSON`, text: `Usage: flatkey text generate --prompt [options] Options: --model Model id, default gpt-5.5 --output, -o Write text file --json Print machine-readable JSON`, "text generate": `Usage: flatkey text generate --prompt [options] Options: --model Model id, default gpt-5.5 --output, -o Write text file --json Print machine-readable JSON`, version: `Usage: flatkey version [options] Aliases: flatkey --version flatkey -v Options: --json Print machine-readable JSON`, video: `Usage: flatkey video [options] Commands: generate --prompt Generate video copy --source Recreate a 5-15s video from local depth motion Options: --model Model id, default seedance-2.0-pro --duration Video duration --ratio 16:9, 9:16, 4:3, 3:4, 21:9, 1:1, or adaptive --resolution 480p, 720p, or 1080p --generate-audio Generate audio, default true --output, -o Write video file --json Print machine-readable JSON`, "video copy": `Usage: flatkey video copy --source [options] Options: --source Local source video, must be 5-15 seconds --frame-ratio <20..100> Percent of frames kept for depth, default 100 --depth-resolution original, 480p, or 320p; default 480p --depth-location Directory for temporary depth video files --keep-depth Keep generated depth video and reference frames --model Model id, default seedance-2.0-pro --prompt Prompt override for copy generation --duration Must match source duration, 5-15 seconds --ratio 16:9, 9:16, 4:3, 3:4, 21:9, or 1:1 --resolution 480p, 720p, or 1080p --generate-audio Generate audio, default true --fps Frames per second --output, -o Write video file --json Print machine-readable JSON`, "video generate": `Usage: flatkey video generate --prompt [options] Options: --model Model id, default seedance-2.0-pro --duration Video duration --ratio 16:9, 9:16, 4:3, 3:4, 21:9, or 1:1 --resolution 480p, 720p, or 1080p --generate-audio Generate audio, default true --image Upload local reference image, repeatable --image-url Add reference image URL, repeatable --file Local image or video input, repeatable --first-frame Upload local first frame image --video-url Add reference video URL, repeatable; Seedance 2.5 supports up to 10 --first-frame-url Add first frame image URL --last-frame Upload local last frame image --last-frame-url Add last frame image URL --fps Frames per second --output, -o Write video file --json Print machine-readable JSON`, }; export function getCommandHelp(group, action) { const key = action ? `${group} ${action}` : group; const help = COMMAND_HELP[key]; if (!help) { throw new Error(`Unknown help topic: ${key}`); } return help; } # ===== file: src/models.js ===== export function normalizeModels(response, type) { const rawModels = Array.isArray(response?.data) ? response.data : Array.isArray(response?.models) ? response.models : []; return rawModels .map((model) => ({ id: model.id, type: model.type ?? inferType(model), source: "remote", })) .filter((model) => model.id && model.type) .filter((model) => !type || model.type === type); } function inferType(model) { if (model.capabilities?.includes("video")) return "video"; if (model.capabilities?.includes("audio")) return "audio"; if (model.capabilities?.includes("image")) return "image"; if (model.capabilities?.includes("text")) return "text"; if (/image|nano-banana/i.test(model.id)) return "image"; if (/seedance|veo|sora|video/i.test(model.id)) return "video"; if (/tts|audio|voice|speech/i.test(model.id)) return "audio"; if (model.object === "model") return "text"; return undefined; } # ===== file: src/requestHeaders.js ===== export const CLI_REQUEST_HEADERS = { "x-flatkey-client": "cli", }; export function withCliRequestHeaders(headers = {}) { return { ...headers, ...CLI_REQUEST_HEADERS, }; } # ===== file: src/video-copy.js ===== import { access, mkdir, rm } from "node:fs/promises"; import { homedir, tmpdir } from "node:os"; import { join } from "node:path"; import { spawn } from "node:child_process"; export const MIN_COPY_DURATION_SECONDS = 5; export const MAX_COPY_DURATION_SECONDS = 15; export const DEFAULT_FRAME_RATIO = 100; export const DEFAULT_DEPTH_RESOLUTION = "480p"; export async function prepareVideoCopy(options, deps = {}) { const source = await expandHomePath(options.source); const sourceInfo = await inspectVideo(source, deps); const duration = sourceInfo.duration; validateCopyDuration(duration, "source video"); const requestedDuration = options.duration === undefined ? duration : parseDuration(options.duration, "--duration"); validateCopyDuration(requestedDuration, "--duration"); if (Math.abs(requestedDuration - duration) > 0.01) { throw new Error( `--duration must match the source video duration (${formatSeconds(duration)}s); time stretching is not supported by video copy.`, ); } const depthRoot = await resolveDepthLocation(options.depth_location, deps); const workDir = join(depthRoot, `copy-${Date.now()}-${Math.random().toString(16).slice(2)}`); await mkdir(workDir, { recursive: true }); const depthPath = join(workDir, "depth.mp4"); let helperResult; try { helperResult = await runDepthHelper({ source, output: depthPath, frameRatio: parseFrameRatio(options.frame_ratio), resolution: parseDepthResolution(options.depth_resolution), model: options.depth_model, workDir, }, deps); } catch (error) { if (!options.keep_depth) await rm(workDir, { recursive: true, force: true }); throw error; } let referencePaths; try { referencePaths = await (deps.extractReferenceFrames ?? extractReferenceFrames)({ source: helperResult.output ?? depthPath, outputDir: workDir, duration, ffmpegPath: deps.ffmpegPath, env: deps.env, }, deps); } catch (error) { if (!options.keep_depth) await rm(workDir, { recursive: true, force: true }); throw error; } return { source, depthPath: helperResult.output ?? depthPath, referencePaths, workDir, duration: requestedDuration, sourceInfo, helper: helperResult, cleanup: async () => { if (!options.keep_depth) { await rm(workDir, { recursive: true, force: true }); } }, }; } export function validateCopyDuration(value, label = "duration") { const duration = parseDuration(value, label); if (duration < MIN_COPY_DURATION_SECONDS || duration > MAX_COPY_DURATION_SECONDS) { throw new Error( `${label} must be between ${MIN_COPY_DURATION_SECONDS} and ${MAX_COPY_DURATION_SECONDS} seconds; received ${formatSeconds(duration)}s.`, ); } return duration; } export function parseDuration(value, label = "duration") { const duration = Number(value); if (!Number.isFinite(duration) || duration <= 0) { throw new Error(`${label} must be a positive number of seconds.`);