Files
OmniRoute/open-sse/executors/veoaifree-web.ts
Diego Rodrigues de Sa e Souza bf8b56b29f Release v3.8.20 (#3547)
* chore(release): open v3.8.20 development cycle

* fix(images): prefer bare combos over image aliases (#3527)

Integrated into release/v3.8.20

* fix(translator): map Codex local_shell tool (#3534)

Integrated into release/v3.8.20

* fix(usage): make opencode-go quota fetcher fail-open instead of throwing 500 (#3522)

Integrated into release/v3.8.20

* Fix Runtime page breaker state rendering (#3533)

Integrated into release/v3.8.20

* Expose provider breaker degradation threshold setting (#3535)

Integrated into release/v3.8.20

* fix(executor): strip provider prefix from versioned built-in tool model field (#3532)

Integrated into release/v3.8.20

* feat(providers): add Claude Fable 5 support (#3524)

Integrated into release/v3.8.20

* feat(resilience): add global provider cooldown tracking to prevent combo re-walking (#3556)

Integrated into release/v3.8.20 (default OFF, opt-in)

* fix(translator): scope thoughtSignature bypass to Antigravity/CLI only (#3560)

Integrated into release/v3.8.20. Co-authored-by: Six7Day <six7day@gmail.com>

* fix(routing): normalize thinking:disabled for combo-substituted models that reject it (#3554) (#3563)

Integrated into release/v3.8.20

* fix(usage): accept 0/empty budget limits so the dashboard can save and clear (#3537) (#3564)

Integrated into release/v3.8.20

* docs(changelog): credit @Six7Day for #3560 thoughtSignature fix (#3414)

The #3560 squash co-author trailer landed inline (unparsed by GitHub), so add
an explicit CHANGELOG credit ensuring @Six7Day (original #3414) and @oyi77 are
on the public record for the Gemini thoughtSignature fix.

* fix(gamification): dedup badge unlock via user_badges so events don't re-fire every request (#3472) (#3565)

Integrated into release/v3.8.20

* fix(routing): pass through 'auto' keyword on codex /v1/responses instead of rewriting to codex/auto (#3509) (#3566)

Integrated into release/v3.8.20

* fix(cli-tools): normalize apiKey null in guide-settings schema so cloud-mode config saves (#3552) (#3567)

Integrated into release/v3.8.20

* fix(catalog): reclassify PublicAI from keyless to one-time-initial (requires API key) (#3558) (#3568)

Integrated into release/v3.8.20

* fix(gemini-web): surface missing Playwright browser as actionable 503 + cooldown hint, not a retryable 500 loop (#3516) (#3570)

Integrated into release/v3.8.20

* fix(security): sanitize raw err.message in web executors + embeddings/search response bodies (Rule #12) (#3494, #3495) (#3573)

Integrated into release/v3.8.20

* fix(dashboard): point CustomHostsManager + FeatureFlagsGrid at real routes (#3486, #3487) (#3574)

Integrated into release/v3.8.20

* chore(providers): remove dead krutrim entry (#3483) + docs(api): fix agent-bridge per-agent state route (#3489) (#3575)

Integrated into release/v3.8.20

* docs(api): correct API_REFERENCE.md paths for skills/plugins/admin/cache/acp/system-info (#3497) (#3577)

Integrated into release/v3.8.20

* fix(proxy): drive SOCKS5 UI option from runtime ENABLE_SOCKS5_PROXY, not build-time NEXT_PUBLIC (#3508) (#3579)

Integrated into release/v3.8.20

* fix(playground): filter playground models by node prefix so custom-endpoint models appear (#3505) (#3581)

Integrated into release/v3.8.20

* fix(usage): show an informative message instead of a blank Kiro quota card when no usage breakdown (#3506) (#3582)

Integrated into release/v3.8.20

* docs(changelog): add the #3506 Kiro quota entry (missed in #3582 due to a stale-base CHANGELOG anchor) (#3583)

Integrated into release/v3.8.20

* fix(auto-update): use stable PROJECT_ROOT walker, not frozen process.cwd() (#3561)

Integrated into release/v3.8.20. Auto-update PROJECT_ROOT now uses a stable __dirname-anchored upward walker instead of the no-op process.cwd() resolver.

* fix: address PR #3518 review comments (lifecycle hooks, regex, indentation, route params) (#3562)

Integrated into release/v3.8.20. Addresses #3518 review: regex literals, logs/[id] route params (Next 16), indentation, and wires plugin lifecycle hooks (onInstall/onActivate/onDeactivate/onUninstall) in the loader so manager.ts can register them. Adds Rule #18 regression test.

* docs(changelog): credit @ViFigueiredo (#3423) for PROJECT_ROOT + log #3561/#3562 (v3.8.20)

* fix: openai to gemini incorrectly translates historical tool calls into text (#3569)

Integrated into release/v3.8.20. Standard Gemini direct path now maps historical tool calls to native functionCall/functionResponse parts (signaturelessToolCallMode: native) instead of inert text — validated against the real Gemini API (gemini-2.5-flash returns 200 for signatureless native functionCall, even with tools+thinking; Hard Rule #18). Eliminates the text-serialization leak. Antigravity/CLI sentinel path (#3560) untouched.

* docs(changelog)+test: reconcile standard-Gemini native mode (#3569) — update round-2 rationale comment + log VPS validation

* docs(changelog): reconcile v3.8.20 — add 9 missing bullets + move [Unreleased] to versioned section

* docs(changelog): complete v3.8.20 reconciliation — 27 bullets, 11 contributors

---------

Co-authored-by: Alexander Averyanov <alex@averyan.ru>
Co-authored-by: Hakan Kurşun <bykamaka@gmail.com>
Co-authored-by: Wilson <pedbookmed@gmail.com>
Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Giorgos Giakoumettis <giorgos@yiakoumettis.gr>
Co-authored-by: PizzaV <103120356+pizzav-xyz@users.noreply.github.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Markus Hartung <mail@hartmark.se>
2026-06-10 13:49:08 -03:00

393 lines
12 KiB
TypeScript

/**
* VeoAIFreeWebExecutor — Veo AI Free Multi-Tool Provider
*
* Routes requests through veoaifree.com's WordPress AJAX API.
* Supports: text-to-video, image-to-video, image generation, TTS, prompt enhancement.
*
* No auth required. Rate limited to 6 requests/hour per IP.
*/
import { BaseExecutor, type ExecuteInput } from "./base.ts";
import { sanitizeErrorMessage } from "../utils/error.ts";
const BASE_URL = "https://veoaifree.com";
const AJAX_URL = `${BASE_URL}/wp-admin/admin-ajax.php`;
const TTS_URL = `${BASE_URL}/video/googletts.php`;
const USER_AGENT =
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36";
const POLL_INTERVAL_MS = 20_000;
const MAX_POLLS = 30; // 10 minutes max
const FETCH_TIMEOUT_MS = 30_000;
// ─── Helpers ────────────────────────────────────────────────────────────────
function throwIfAborted(signal?: AbortSignal): void {
if (signal?.aborted) {
throw signal.reason instanceof Error ? signal.reason : new Error("Request aborted");
}
}
function withTimeout(signal?: AbortSignal): { signal: AbortSignal; cleanup: () => void } {
const controller = new AbortController();
const abort = () => controller.abort(signal?.reason || new Error("Request aborted"));
const timeout = setTimeout(
() => controller.abort(new Error("VeoAIFree request timed out")),
FETCH_TIMEOUT_MS
);
if (signal?.aborted) {
abort();
} else {
signal?.addEventListener("abort", abort, { once: true });
}
return {
signal: controller.signal,
cleanup: () => {
clearTimeout(timeout);
signal?.removeEventListener("abort", abort);
},
};
}
async function fetchWithTimeout(
url: string,
init: RequestInit = {},
signal?: AbortSignal
): Promise<Response> {
throwIfAborted(signal);
const timeout = withTimeout(signal);
try {
return await fetch(url, { ...init, signal: timeout.signal });
} finally {
timeout.cleanup();
}
}
function waitForPoll(signal?: AbortSignal): Promise<void> {
throwIfAborted(signal);
let abort: (() => void) | undefined;
return new Promise((resolve, reject) => {
const timeout = setTimeout(resolve, POLL_INTERVAL_MS);
abort = () => {
clearTimeout(timeout);
reject(signal?.reason instanceof Error ? signal.reason : new Error("Request aborted"));
};
signal?.addEventListener("abort", abort, { once: true });
}).finally(() => {
if (abort) signal?.removeEventListener("abort", abort);
});
}
async function fetchNonce(signal?: AbortSignal): Promise<string> {
const res = await fetchWithTimeout(BASE_URL, { headers: { "User-Agent": USER_AGENT } }, signal);
const html = await res.text();
const match = html.match(/nonce":"([a-f0-9]+)"/);
if (!match) throw new Error("Failed to extract CSRF nonce from veoaifree.com");
return match[1];
}
async function postAjax(
nonce: string,
params: Record<string, string>,
signal?: AbortSignal
): Promise<string> {
const body = new URLSearchParams({ action: "veo_video_generator", nonce, ...params });
const res = await fetchWithTimeout(
AJAX_URL,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"User-Agent": USER_AGENT,
Origin: BASE_URL,
Referer: `${BASE_URL}/`,
},
body: body.toString(),
},
signal
);
return res.text();
}
function jsonResp(data: unknown, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
headers: { "Content-Type": "application/json" },
});
}
function errResp(message: string, status = 502): Response {
return jsonResp({ error: { message } }, status);
}
// ─── Intent Detection ───────────────────────────────────────────────────────
type ToolIntent = "video" | "image" | "tts" | "enhance";
export function detectIntent(model?: string, prompt?: string): ToolIntent {
const m = (model || "").toLowerCase();
if (m.includes("tts") || m.includes("speech") || m.includes("audio")) return "tts";
if (m.includes("image") || m.includes("banana") || m.includes("imagen")) return "image";
if (m.includes("enhance") || m.includes("prompt")) return "enhance";
if (m.includes("video") || m.includes("veo") || m.includes("seedance")) return "video";
// Auto-detect from prompt
const p = (prompt || "").toLowerCase();
if (p.startsWith("generate image") || p.startsWith("create image") || p.startsWith("draw "))
return "image";
if (p.startsWith("enhance") || p.startsWith("improve prompt")) return "enhance";
return "video"; // default
}
// ─── Tool Handlers ──────────────────────────────────────────────────────────
async function handleVideo(
nonce: string,
prompt: string,
aspectRatio: string,
signal?: AbortSignal
): Promise<Response> {
// Generate
const genResult = await postAjax(
nonce,
{
prompt,
totalVariations: "1",
aspectRatio,
actionType: "full-video-generate",
},
signal
);
const sceneData = genResult.trim();
if (!sceneData || sceneData === "0" || sceneData.toLowerCase().includes("error")) {
return errResp("Video generation failed");
}
// Poll
for (let i = 0; i < MAX_POLLS; i++) {
await waitForPoll(signal);
throwIfAborted(signal);
try {
const pollResult = await postAjax(
nonce,
{
sceneData,
actionType: "final-video-results",
},
signal
);
const trimmed = pollResult.trim();
if (trimmed && trimmed !== "0" && !trimmed.toLowerCase().includes("error")) {
const urls = trimmed
.split(/[,\n]/)
.map((u) => u.trim())
.filter((u) => u.startsWith("http"));
if (urls.length > 0) {
return jsonResp({
object: "video.generation",
data: urls.map((url) => ({ url, type: "video" })),
status: "completed",
});
}
}
} catch {
/* continue polling */
}
}
return errResp("Video generation timed out after 10 minutes", 504);
}
async function handleImage(
nonce: string,
prompt: string,
aspectRatio: string,
signal?: AbortSignal
): Promise<Response> {
const result = await postAjax(
nonce,
{
promptIMG: prompt,
totalVariationsIMG: "1",
aspectRatioIMG: aspectRatio,
actionType: "banan-image-generator",
},
signal
);
const trimmed = result.trim();
if (!trimmed || trimmed === "0" || trimmed.toLowerCase().includes("error")) {
return errResp("Image generation failed");
}
// Response is comma-separated base64 PNGs or URLs
const parts = trimmed
.split(",")
.map((s) => s.trim())
.filter(Boolean);
const images = parts.map((p) =>
p.startsWith("http") ? { url: p, type: "image" } : { b64_json: p, type: "image" }
);
return jsonResp({ object: "image.generation", data: images, status: "completed" });
}
async function handleTTS(
prompt: string,
voice?: string,
lang?: string,
signal?: AbortSignal
): Promise<Response> {
// Parse prompt for text and optional voice instructions
const text = prompt;
const selectedVoice = voice || "en-US-AvaNeural";
const selectedLang = lang || "en-US";
const res = await fetchWithTimeout(
TTS_URL,
{
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": USER_AGENT,
Origin: BASE_URL,
Referer: `${BASE_URL}/free-ai-text-to-speech/`,
},
body: JSON.stringify({
text: text.slice(0, 10000),
voice: selectedVoice,
lang: selectedLang,
pitch: "0",
speed: "1.0",
}),
},
signal
);
if (!res.ok) {
return errResp(`TTS failed (${res.status})`);
}
const contentType = res.headers.get("content-type") || "";
if (
contentType.includes("audio") ||
contentType.includes("octet-stream") ||
contentType.includes("wav")
) {
// Return audio directly
return new Response(res.body, {
headers: {
"Content-Type": contentType.includes("wav") ? "audio/wav" : "audio/mpeg",
"Content-Disposition": 'attachment; filename="speech.wav"',
},
});
}
// JSON response with base64 audio_data
const data = await res.text();
try {
const json = JSON.parse(data);
if (json.audio_data) {
return jsonResp({ object: "audio.speech", audio: json.audio_data, status: "completed" });
}
if (json.url) {
return jsonResp({ object: "audio.speech", url: json.url, status: "completed" });
}
} catch {
/* not JSON */
}
return errResp("TTS unexpected response format");
}
async function handleEnhance(
nonce: string,
prompt: string,
signal?: AbortSignal
): Promise<Response> {
const result = await postAjax(
nonce,
{
prompt,
actionType: "main-prompt-generation",
},
signal
);
const trimmed = result.trim();
if (!trimmed || trimmed === "0") {
return errResp("Prompt enhancement failed");
}
return jsonResp({ object: "prompt.enhancement", enhanced: trimmed, status: "completed" });
}
// ─── Executor ───────────────────────────────────────────────────────────────
export class VeoAIFreeWebExecutor extends BaseExecutor {
constructor() {
super("veoaifree-web", { id: "veoaifree-web", baseUrl: BASE_URL });
}
async execute(input: ExecuteInput): Promise<{
response: Response;
url: string;
headers: Record<string, string>;
transformedBody: unknown;
}> {
const body = input.body as Record<string, unknown> | undefined;
const model = input.model || (body?.model as string) || "veo-3.1";
// Extract prompt
const messages = (body?.messages as Array<Record<string, unknown>>) || [];
const userMsg = messages.filter((m) => m.role === "user").pop();
const systemMsg = messages.filter((m) => m.role === "system").pop();
const prompt = (userMsg?.content as string) || "";
const systemText = (systemMsg?.content as string) || "";
if (!prompt.trim()) {
return {
response: errResp("No prompt provided", 400),
url: AJAX_URL,
headers: {},
transformedBody: null,
};
}
// Detect intent
const intent = detectIntent(model, prompt);
// TTS doesn't need nonce
if (intent === "tts") {
const voiceMatch = systemText.match(/voice:\s*(\S+)/);
const langMatch = systemText.match(/lang:\s*(\S+)/);
const resp = await handleTTS(prompt, voiceMatch?.[1], langMatch?.[1], input.signal);
return { response: resp, url: TTS_URL, headers: {}, transformedBody: { intent, model } };
}
// Get nonce for AJAX endpoints
let nonce: string;
try {
nonce = await fetchNonce(input.signal);
} catch (err) {
const msg = err instanceof Error ? err.message : "Failed to get nonce";
return { response: errResp(sanitizeErrorMessage(msg)), url: BASE_URL, headers: {}, transformedBody: null };
}
// Extract aspect ratio from system prompt or default
const arMatch = systemText.match(/aspect[_-]?ratio:\s*(\S+)/i);
const aspectRatio = arMatch?.[1] || "VIDEO_ASPECT_RATIO_LANDSCAPE";
let resp: Response;
switch (intent) {
case "image":
resp = await handleImage(
nonce,
prompt,
aspectRatio.replace("VIDEO_", "IMAGE_"),
input.signal
);
break;
case "enhance":
resp = await handleEnhance(nonce, prompt, input.signal);
break;
default:
resp = await handleVideo(nonce, prompt, aspectRatio, input.signal);
}
return { response: resp, url: AJAX_URL, headers: {}, transformedBody: { intent, model } };
}
}