mirror of
https://github.com/diegosouzapw/OmniRoute.git
synced 2026-08-04 22:32:12 +03:00
* 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>
358 lines
12 KiB
TypeScript
358 lines
12 KiB
TypeScript
/**
|
|
* GeminiWebExecutor — Gemini Web Session Provider
|
|
*
|
|
* Routes requests through Google Gemini's web interface using browser
|
|
* cookies + Playwright automation. Translates between OpenAI chat
|
|
* completions format and Gemini's web UI.
|
|
*
|
|
* Auth: Cookie-based (__Secure-1PSID + __Secure-1PSIDTS from gemini.google.com)
|
|
* Method: Playwright browser automation
|
|
*
|
|
* Note: Streaming is pseudo-streaming — waits for full Gemini response then
|
|
* sends as single SSE chunk. Gemini's StreamGenerate endpoint returns complete
|
|
* responses, not chunked streams.
|
|
*/
|
|
|
|
import { BaseExecutor, type ExecuteInput } from "./base.ts";
|
|
import { sanitizeErrorMessage } from "../utils/error.ts";
|
|
|
|
// ─── Constants ──────────────────────────────────────────────────────────────
|
|
|
|
const GEMINI_URL = "https://gemini.google.com/app";
|
|
|
|
/**
|
|
* Whether an error came from Playwright failing to launch because the browser binary is not
|
|
* installed (`chromium.launch: Executable doesn't exist at ...`). This is a host/config
|
|
* problem, not a transient upstream fault, so the executor must NOT surface it as a retryable
|
|
* 500 (which marks the account unavailable and loops / trips the provider breaker). See #3516.
|
|
*/
|
|
export function isMissingBrowserExecutable(message: string): boolean {
|
|
if (!message) return false;
|
|
return /executable doesn't exist|executablenotfound|playwright install|chromium.*download/i.test(
|
|
message
|
|
);
|
|
}
|
|
const GEMINI_USER_AGENT =
|
|
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36";
|
|
|
|
// ─── Types ──────────────────────────────────────────────────────────────────
|
|
|
|
interface GeminiMessage {
|
|
role: string;
|
|
content: string;
|
|
}
|
|
|
|
interface GeminiRequestBody {
|
|
messages: GeminiMessage[];
|
|
model?: string;
|
|
stream?: boolean;
|
|
}
|
|
|
|
// ─── Helpers ────────────────────────────────────────────────────────────────
|
|
|
|
function formatChatCompletion(content: string, model: string, finishReason = "stop") {
|
|
return {
|
|
id: `chatcmpl-${Date.now()}`,
|
|
object: "chat.completion",
|
|
created: Math.floor(Date.now() / 1000),
|
|
model,
|
|
choices: [{ index: 0, message: { role: "assistant", content }, finish_reason: finishReason }],
|
|
usage: { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 },
|
|
};
|
|
}
|
|
|
|
function formatStreamChunk(content: string, model: string, finishReason: string | null = null) {
|
|
return {
|
|
id: `chatcmpl-${Date.now()}`,
|
|
object: "chat.completion.chunk",
|
|
created: Math.floor(Date.now() / 1000),
|
|
model,
|
|
choices: [{ index: 0, delta: content ? { content } : {}, finish_reason: finishReason }],
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Parse cookie string, stripping attributes (Path, Domain, Expires, etc.)
|
|
* Input: full browser cookie string or just "name=value; name2=value2"
|
|
* Output: array of { name, value } pairs
|
|
*/
|
|
function parseCookies(raw: string): Array<{ name: string; value: string }> {
|
|
return raw
|
|
.split(";")
|
|
.map((part) => part.trim())
|
|
.filter(Boolean)
|
|
.map((part) => {
|
|
const eqIdx = part.indexOf("=");
|
|
if (eqIdx === -1) return null;
|
|
const name = part.substring(0, eqIdx).trim();
|
|
const value = part.substring(eqIdx + 1).trim();
|
|
// Skip cookie attributes that aren't name=value pairs
|
|
if (!name || !value) return null;
|
|
const lowerName = name.toLowerCase();
|
|
if (
|
|
["path", "domain", "expires", "max-age", "secure", "httponly", "samesite"].includes(
|
|
lowerName
|
|
)
|
|
) {
|
|
return null;
|
|
}
|
|
return { name, value };
|
|
})
|
|
.filter(Boolean) as Array<{ name: string; value: string }>;
|
|
}
|
|
|
|
/**
|
|
* Parse Gemini StreamGenerate response text.
|
|
*
|
|
* Response format:
|
|
* )]}'
|
|
* <length>
|
|
* [["wrb.fr", null, "<JSON string>"]]
|
|
* <length>
|
|
* [["wrb.fr", null, "<JSON string>"]]
|
|
*
|
|
* The JSON string contains nested array: inner[4][0][1] = ["text chunks"]
|
|
* We return text from the first wrb.fr line that contains content.
|
|
*/
|
|
function parseStreamResponse(raw: string): string {
|
|
const lines = raw.split("\n");
|
|
for (const line of lines) {
|
|
if (!line.trim() || line.trim() === ")]}'" || /^\d+$/.test(line.trim())) continue;
|
|
try {
|
|
const arr = JSON.parse(line);
|
|
if (!Array.isArray(arr) || !arr[0] || arr[0][0] !== "wrb.fr") continue;
|
|
const payload = arr[0]?.[2];
|
|
if (typeof payload !== "string") continue;
|
|
const inner = JSON.parse(payload);
|
|
// Defensive: check each level before accessing
|
|
const responseArray = inner?.[4]?.[0]?.[1];
|
|
if (!Array.isArray(responseArray)) continue;
|
|
const text = responseArray.filter((c: unknown) => typeof c === "string").join("");
|
|
if (text) return text;
|
|
} catch {
|
|
// Skip unparseable lines
|
|
}
|
|
}
|
|
return "";
|
|
}
|
|
|
|
// ─── Executor ───────────────────────────────────────────────────────────────
|
|
|
|
export class GeminiWebExecutor extends BaseExecutor {
|
|
constructor() {
|
|
super("gemini-web", { id: "gemini-web", baseUrl: GEMINI_URL });
|
|
}
|
|
|
|
async execute(input: ExecuteInput) {
|
|
const { model, body, stream, credentials, signal } = input;
|
|
const requestBody = body as GeminiRequestBody;
|
|
|
|
const cookie = credentials.apiKey || "";
|
|
if (!cookie) {
|
|
return {
|
|
response: new Response(JSON.stringify({ error: "Missing Gemini cookies" }), {
|
|
status: 401,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
}
|
|
|
|
const messages = requestBody.messages || [];
|
|
const lastUserMsg = messages.filter((m) => m.role === "user").pop();
|
|
const prompt = lastUserMsg?.content || "";
|
|
|
|
if (!prompt) {
|
|
return {
|
|
response: new Response(JSON.stringify({ error: "No user message found" }), {
|
|
status: 400,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
}
|
|
|
|
let browser: any = null;
|
|
let abortBrowser: (() => void) | null = null;
|
|
try {
|
|
if (signal?.aborted) {
|
|
throw signal.reason instanceof Error ? signal.reason : new Error("Request aborted");
|
|
}
|
|
const { chromium } = await import("playwright");
|
|
browser = await chromium.launch({ headless: true });
|
|
abortBrowser = () => {
|
|
void browser?.close().catch(() => {});
|
|
};
|
|
signal?.addEventListener("abort", abortBrowser, { once: true });
|
|
|
|
const context = await browser.newContext({ userAgent: GEMINI_USER_AGENT });
|
|
|
|
// Parse cookies — strips attributes like Path, Domain, Expires
|
|
const cookiePairs = parseCookies(cookie);
|
|
await context.addCookies(
|
|
cookiePairs.map(({ name, value }) => ({
|
|
name,
|
|
value,
|
|
domain: ".google.com",
|
|
path: "/",
|
|
secure: true,
|
|
}))
|
|
);
|
|
|
|
const page = await context.newPage();
|
|
|
|
// Capture first StreamGenerate response
|
|
let responseText = "";
|
|
let captured = false;
|
|
const responsePromise = new Promise<void>((resolve) => {
|
|
page.on("response", async (resp: any) => {
|
|
if (captured || !resp.url().includes("StreamGenerate")) return;
|
|
captured = true;
|
|
try {
|
|
const raw = await resp.text();
|
|
responseText = parseStreamResponse(raw);
|
|
} catch {
|
|
/* ignore */
|
|
}
|
|
resolve();
|
|
});
|
|
});
|
|
|
|
await page.goto(GEMINI_URL, { waitUntil: "domcontentloaded", timeout: 20000 });
|
|
if (signal?.aborted) {
|
|
throw signal.reason instanceof Error ? signal.reason : new Error("Request aborted");
|
|
}
|
|
await page.waitForTimeout(3000);
|
|
|
|
// Type and send message
|
|
const inputEl = await page.waitForSelector(".ql-editor, [contenteditable='true']", {
|
|
timeout: 10000,
|
|
});
|
|
await inputEl.click();
|
|
await page.keyboard.type(prompt, { delay: 10 });
|
|
await page.waitForTimeout(300);
|
|
await page.keyboard.press("Enter");
|
|
|
|
// Wait for response or timeout
|
|
await Promise.race([responsePromise, page.waitForTimeout(30000)]);
|
|
if (signal?.aborted) {
|
|
throw signal.reason instanceof Error ? signal.reason : new Error("Request aborted");
|
|
}
|
|
|
|
if (!responseText) {
|
|
return {
|
|
response: new Response(JSON.stringify({ error: "No response from Gemini" }), {
|
|
status: 502,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
}
|
|
|
|
const modelId = model || "gemini-2.5-pro";
|
|
|
|
if (stream) {
|
|
// Pseudo-streaming: send complete response as single SSE chunk
|
|
// Gemini's StreamGenerate returns complete responses, not chunked streams
|
|
const encoder = new TextEncoder();
|
|
const readable = new ReadableStream(
|
|
{
|
|
start(controller) {
|
|
controller.enqueue(
|
|
encoder.encode(
|
|
`data: ${JSON.stringify(formatStreamChunk(responseText, modelId))}\n\n`
|
|
)
|
|
);
|
|
controller.enqueue(
|
|
encoder.encode(
|
|
`data: ${JSON.stringify(formatStreamChunk("", modelId, "stop"))}\n\n`
|
|
)
|
|
);
|
|
controller.enqueue(encoder.encode("data: [DONE]\n\n"));
|
|
controller.close();
|
|
},
|
|
},
|
|
{ highWaterMark: 16384 }
|
|
);
|
|
return {
|
|
response: new Response(readable, {
|
|
status: 200,
|
|
headers: {
|
|
"Content-Type": "text/event-stream",
|
|
"Cache-Control": "no-cache",
|
|
Connection: "keep-alive",
|
|
},
|
|
}),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
}
|
|
|
|
return {
|
|
response: new Response(JSON.stringify(formatChatCompletion(responseText, modelId)), {
|
|
status: 200,
|
|
headers: { "Content-Type": "application/json" },
|
|
}),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
} catch (error) {
|
|
const rawMessage = error instanceof Error ? error.message : "Unknown error";
|
|
// #3516: a missing Playwright browser is a host/config problem, not a transient upstream
|
|
// fault. Surface an actionable error and tag it with the connection-cooldown hint so
|
|
// accountFallback skips the provider circuit breaker and applies a short, non-exponential
|
|
// cooldown instead of looping on a retryable 500.
|
|
if (isMissingBrowserExecutable(rawMessage)) {
|
|
return {
|
|
response: new Response(
|
|
JSON.stringify({
|
|
error:
|
|
"Gemini Web requires the Playwright Chromium browser, which is not installed. " +
|
|
"Run `npx playwright install chromium` on the host (or rebuild the Docker image with browsers).",
|
|
}),
|
|
{
|
|
status: 503,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"X-Omni-Fallback-Hint": "connection_cooldown",
|
|
},
|
|
}
|
|
),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
}
|
|
return {
|
|
response: new Response(
|
|
JSON.stringify({
|
|
error: sanitizeErrorMessage(rawMessage),
|
|
}),
|
|
{ status: 500, headers: { "Content-Type": "application/json" } }
|
|
),
|
|
url: GEMINI_URL,
|
|
headers: {},
|
|
transformedBody: body,
|
|
};
|
|
} finally {
|
|
if (abortBrowser) signal?.removeEventListener("abort", abortBrowser);
|
|
// Always close browser to prevent resource leaks
|
|
if (browser) {
|
|
try {
|
|
await browser.close();
|
|
} catch {
|
|
/* ignore close errors */
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|