Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion open-sse/executors/antigravity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ export class AntigravityExecutor extends BaseExecutor {
}

transformRequest(model, body, stream, credentials) {
// TODO: Consider removing project override like gemini-cli.ts — stored projectId
// can become stale for Cloud Code accounts, causing 403 "has not been used in project X".
// Antigravity accounts may have more stable project IDs, but the risk exists.
const bodyProjectId = body?.project;
const credentialsProjectId = credentials?.projectId;
const allowBodyProjectOverride = process.env.OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE === "1";
Expand Down Expand Up @@ -210,7 +213,7 @@ export class AntigravityExecutor extends BaseExecutor {
const url = this.buildUrl(model, stream, urlIndex);
const headers = this.buildHeaders(credentials, stream);
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
const transformedBody = this.transformRequest(model, body, stream, credentials);
const transformedBody = await this.transformRequest(model, body, stream, credentials);

// Initialize retry counter for this URL
if (!retryAttemptsByUrl[urlIndex]) {
Expand Down
2 changes: 1 addition & 1 deletion open-sse/executors/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ export class BaseExecutor {
}
}

const transformedBody = this.transformRequest(model, body, stream, credentials);
const transformedBody = await this.transformRequest(model, body, stream, credentials);

try {
// Apply timeout to all requests. Non-streaming requests need this to prevent
Expand Down
2 changes: 1 addition & 1 deletion open-sse/executors/cursor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ export class CursorExecutor extends BaseExecutor {
const url = this.buildUrl();
const headers = this.buildHeaders(credentials);
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
const transformedBody = this.transformRequest(model, body, stream, credentials);
const transformedBody = await this.transformRequest(model, body, stream, credentials);

try {
const response: CursorHttpResponse = http2
Expand Down
110 changes: 95 additions & 15 deletions open-sse/executors/gemini-cli.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
import { BaseExecutor } from "./base.ts";
import { PROVIDERS, OAUTH_ENDPOINTS } from "../config/constants.ts";

export class GeminiCLIExecutor extends BaseExecutor {
private _currentModel: string = "";
const LOAD_CODE_ASSIST_URL = "https://cloudcode-pa.googleapis.com/v1internal:loadCodeAssist";
const PROJECT_TTL_MS = 30_000; // 30 seconds — matches native Gemini CLI
const MAX_CACHE_SIZE = 100;
const LOAD_CODE_ASSIST_TIMEOUT_MS = 10_000; // 10 seconds timeout

// Per-account cache: accessToken -> { projectId, expiresAt }
const projectCache = new Map<string, { projectId: string; expiresAt: number }>();

export class GeminiCLIExecutor extends BaseExecutor {
constructor() {
super("gemini-cli", PROVIDERS["gemini-cli"]);
}
Expand All @@ -18,28 +24,102 @@ export class GeminiCLIExecutor extends BaseExecutor {
"Content-Type": "application/json",
Authorization: `Bearer ${credentials.accessToken}`,
// Fingerprint headers matching native GeminiCLI client (prevents upstream rejection)
"User-Agent": `GeminiCLI/0.31.0/${this._currentModel || "unknown"} (linux; x64)`,
"User-Agent": "GeminiCLI/0.31.0/unknown (linux; x64)",
"X-Goog-Api-Client": "google-genai-sdk/1.41.0 gl-node/v22.19.0",
...(stream && { Accept: "text/event-stream" }),
...(credentials?.projectId && { "x-goog-user-project": credentials.projectId }),
// NOTE: x-goog-user-project removed — the stored projectId can become stale for
// free-tier accounts, causing 403 "Cloud Code Private API has not been used in
// project X". The API resolves the correct project from the OAuth token alone.
};
}

transformRequest(model, body, stream, credentials) {
// Capture model so buildHeaders (called after transformRequest) can include it in User-Agent
this._currentModel = model || "";
/**
* Fetch the current cloudaicompanionProject via loadCodeAssist API.
* Native Gemini CLI refreshes this every 30 seconds — OmniRoute stores it once
* at OAuth connection time, so it goes stale. This method keeps it fresh.
*/
async refreshProject(accessToken: string): Promise<string | null> {
// Check cache
const cached = projectCache.get(accessToken);
if (cached && cached.expiresAt > Date.now()) {
return cached.projectId;
}
Comment on lines +43 to +48

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This implementation is susceptible to a "thundering herd" issue. If multiple concurrent requests arrive for the same accessToken while the cache is empty or expired, they will all bypass the cache check and trigger separate fetch calls to the Google API. This can lead to unnecessary load and potential rate limiting. Consider deduplicating in-flight requests using a shared Map of promises.


try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), LOAD_CODE_ASSIST_TIMEOUT_MS);

let response;
try {
response = await fetch(LOAD_CODE_ASSIST_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
metadata: {
ideType: "IDE_UNSPECIFIED",
platform: "PLATFORM_UNSPECIFIED",
pluginType: "GEMINI",
},
}),
signal: controller.signal,
});
} finally {
clearTimeout(timeoutId);
}

const allowBodyProjectOverride = process.env.OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE === "1";
if (!response.ok) {
console.warn(
`[OmniRoute] loadCodeAssist returned ${response.status} — falling back to stored projectId`
);
return null;
}

// Default: prefer OAuth-stored projectId. Incoming body.project can be stale
// when clients cache older Cloud Code project values.
// Opt-in escape hatch: set OMNIROUTE_ALLOW_BODY_PROJECT_OVERRIDE=1.
if (allowBodyProjectOverride && body?.project) {
return body;
const data = await response.json();
let projectId = "";
if (typeof data.cloudaicompanionProject === "string") {
projectId = data.cloudaicompanionProject.trim();
} else if (data.cloudaicompanionProject?.id) {
projectId = data.cloudaicompanionProject.id.trim();
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

It's safer to verify that id is a string before calling .trim(). If the API returns a non-string value (e.g., a number), this will throw an error and crash the request processing.

Suggested change
} else if (data.cloudaicompanionProject?.id) {
projectId = data.cloudaicompanionProject.id.trim();
}
} else if (typeof data.cloudaicompanionProject?.id === "string") {
projectId = data.cloudaicompanionProject.id.trim();
}


if (!projectId) {
console.warn("[OmniRoute] loadCodeAssist returned no project — falling back to stored projectId");
return null;
}

// Cache for 30 seconds (evict stale entries if cache is full)
if (projectCache.size >= MAX_CACHE_SIZE) {
const now = Date.now();
for (const [key, val] of projectCache) {
if (val.expiresAt <= now) projectCache.delete(key);
}
}
Comment on lines +110 to +120

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current eviction logic only removes expired entries. If the cache is full of valid (non-expired) entries, it will continue to grow beyond MAX_CACHE_SIZE because projectCache.set is called regardless of whether any space was cleared. To strictly enforce the limit, you should remove the oldest entry if the cache is still full after the expiration cleanup.

Suggested change
if (projectCache.size >= MAX_CACHE_SIZE) {
const now = Date.now();
for (const [key, val] of projectCache) {
if (val.expiresAt <= now) projectCache.delete(key);
}
}
if (projectCache.size >= MAX_CACHE_SIZE) {
const now = Date.now();
for (const [key, val] of projectCache) {
if (val.expiresAt <= now) projectCache.delete(key);
}
// If still full, evict the oldest entry (Map maintains insertion order)
if (projectCache.size >= MAX_CACHE_SIZE) {
const firstKey = projectCache.keys().next().value;
if (firstKey !== undefined) projectCache.delete(firstKey);
}
}

projectCache.set(accessToken, {
projectId,
expiresAt: Date.now() + PROJECT_TTL_MS,
});

return projectId;
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
console.warn(`[OmniRoute] loadCodeAssist failed (${msg}) — falling back to stored projectId`);
return null;
}
}

if (credentials?.projectId) {
body.project = credentials.projectId;
async transformRequest(model, body, stream, credentials) {
// Refresh the project ID via loadCodeAssist (cached for 30s).
// The translator builds the envelope with the stale stored projectId —
// we replace it here with the fresh one before sending to the API.
if (body && typeof body === "object" && body.request && credentials.accessToken) {
const freshProject = await this.refreshProject(credentials.accessToken);
if (freshProject) {
body.project = freshProject;
}
// If refresh failed, keep the stale projectId as a best-effort fallback
}
return body;
}
Expand Down
2 changes: 1 addition & 1 deletion open-sse/executors/kiro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ export class KiroExecutor extends BaseExecutor {
const url = this.buildUrl(model, stream, 0);
const headers = this.buildHeaders(credentials, stream);
mergeUpstreamExtraHeaders(headers, upstreamExtraHeaders);
const transformedBody = this.transformRequest(model, body, stream, credentials);
const transformedBody = await this.transformRequest(model, body, stream, credentials);

const response = await fetch(url, {
method: "POST",
Expand Down
10 changes: 10 additions & 0 deletions open-sse/handlers/chatCore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,16 @@ export async function handleChatCore({
lastError: message,
errorCode: statusCode,
});
} else if (errorType === PROVIDER_ERROR_TYPES.PROJECT_ROUTE_ERROR) {
// Cloud Code 403 with stale project: not a ban, keep account active.
await updateProviderConnection(connectionId, {
lastErrorType: errorType,
lastError: message,
errorCode: statusCode,
});
console.warn(
`[provider] Node ${connectionId} project routing error (${statusCode}) — not banning`
);
}
} catch {
// Best-effort state update; request flow should continue with fallback handling.
Expand Down
11 changes: 10 additions & 1 deletion open-sse/services/errorClassifier.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ export const PROVIDER_ERROR_TYPES = {
FORBIDDEN: "forbidden", // 403 — account banned/revoked, disable node
SERVER_ERROR: "server_error", // 500/502/503 — retry limited
QUOTA_EXHAUSTED: "quota_exhausted", // 402/429/400 + billing signals
PROJECT_ROUTE_ERROR: "project_route_error", // 403 + stale project — transient, not a ban
};

function responseBodyToString(responseBody: unknown): string {
Expand Down Expand Up @@ -49,7 +50,15 @@ export function classifyProviderError(statusCode: number, responseBody: unknown)
if (statusCode === 403 && accountDeactivated) {
return PROVIDER_ERROR_TYPES.ACCOUNT_DEACTIVATED;
}
if (statusCode === 403) return PROVIDER_ERROR_TYPES.FORBIDDEN;
if (statusCode === 403) {
// Cloud Code API returns 403 with "has not been used in project X" when the project
// field is wrong or stale. This is a routing/config error, not an account ban.
// Classify as project_route_error so the account stays active but the error is tracked.
if (bodyStr.includes("has not been used in project")) {
return PROVIDER_ERROR_TYPES.PROJECT_ROUTE_ERROR;
}
return PROVIDER_ERROR_TYPES.FORBIDDEN;
}
if (statusCode >= 500) return PROVIDER_ERROR_TYPES.SERVER_ERROR;

return null;
Expand Down
6 changes: 3 additions & 3 deletions open-sse/translator/request/openai-to-gemini.ts
Original file line number Diff line number Diff line change
Expand Up @@ -339,12 +339,12 @@ export function openaiToGeminiCLIRequest(model, body, stream) {

// Wrap Gemini CLI format in Cloud Code wrapper
function wrapInCloudCodeEnvelope(model, geminiCLI, credentials = null, isAntigravity = false) {
// Both Antigravity and Gemini CLI need the project field for the Cloud Code API.
// For Gemini CLI, the stored projectId may be stale; the executor's transformRequest
// refreshes it via loadCodeAssist before the request is sent to the API.
let projectId = credentials?.projectId;

if (!projectId) {
// Graceful fallback: warn instead of hard-throw so the request reaches
// the provider and fails with a meaningful provider-side error (#338).
// Users who reconnect OAuth will get their real projectId loaded.
console.warn(
`[OmniRoute] ${isAntigravity ? "Antigravity" : "GeminiCLI"} account is missing projectId. ` +
`Attempting request with empty project — reconnect OAuth to resolve.`
Expand Down
15 changes: 11 additions & 4 deletions open-sse/utils/stream.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
filterUsageForFormat,
COLORS,
} from "./usageTracking.ts";
import { parseSSELine, hasValuableContent, fixInvalidId, formatSSE } from "./streamHelpers.ts";
import { parseSSELine, hasValuableContent, fixInvalidId, formatSSE, unwrapGeminiChunk } from "./streamHelpers.ts";
import {
createStructuredSSECollector,
buildStreamSummaryFromEvents,
Expand Down Expand Up @@ -531,9 +531,16 @@ export function createSSEStream(options: StreamOptions = {}) {
}
}

// Gemini format - may have multiple parts
if (parsed.candidates?.[0]?.content?.parts) {
for (const part of parsed.candidates[0].content.parts) {
// Gemini / Cloud Code format - may have multiple parts
// Cloud Code API wraps in { response: { candidates: [...] } }, so unwrap.
// Only applies to Gemini-family formats — skip for OpenAI, Claude, etc.
const isGeminiFormat =
targetFormat === FORMATS.GEMINI ||
targetFormat === FORMATS.GEMINI_CLI ||
targetFormat === FORMATS.ANTIGRAVITY;
const geminiChunk = isGeminiFormat ? unwrapGeminiChunk(parsed) : parsed;
if (geminiChunk.candidates?.[0]?.content?.parts) {
for (const part of geminiChunk.candidates[0].content.parts) {
if (part.text && typeof part.text === "string") {
totalContentLength += part.text.length;
if (state?.accumulatedContent !== undefined) state.accumulatedContent += part.text;
Expand Down
9 changes: 9 additions & 0 deletions open-sse/utils/streamHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ export function hasValuableContent(chunk, format) {
return true; // Other formats: keep all chunks
}

/**
* Unwrap Cloud Code API envelope from a Gemini response chunk.
* The Cloud Code API wraps responses in { response: { candidates: [...] } }
* while standard Gemini returns { candidates: [...] } directly.
*/
export function unwrapGeminiChunk(parsed) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Incorrect unwrapping logic - handles edge case incorrectly

The ternary parsed.candidates ? parsed : parsed.response || parsed has a bug:

  • When parsed.response exists but is null (not undefined), the expression parsed.response || parsed returns parsed (truthy check fails because null is falsy).
  • This means unwrapGeminiChunk({ candidates: [...], response: null }) incorrectly returns parsed (with top-level candidates), while unwrapGeminiChunk({ response: null }) incorrectly returns parsed (the input).

Correct logic: Only unwrap when candidates is NOT at top level AND response exists:

export function unwrapGeminiChunk(parsed) {
  if (!parsed.candidates && parsed.response) {
    return parsed.response;
  }
  return parsed;
}

The test at line 96 (returns parsed when response exists but is null/undefined) should actually fail with the current implementation since null is falsy and would trigger the || parsed fallback.

return parsed.candidates ? parsed : parsed.response || parsed;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Use explicit !== null check for null safety

Consider changing parsed.response || parsed to parsed.response !== undefined ? parsed.response : parsed for clarity and to handle the null case explicitly.

}

// Fix invalid id (generic or too short)
export function fixInvalidId(parsed) {
if (parsed.id && (parsed.id === "chat" || parsed.id === "completion" || parsed.id.length < 8)) {
Expand Down
24 changes: 24 additions & 0 deletions tests/unit/error-classifier.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,27 @@ test("classifyProviderError: 429 without billing signal => RATE_LIMITED", () =>
const result = classifyProviderError(429, { error: { message: "too many requests" } });
assert.equal(result, PROVIDER_ERROR_TYPES.RATE_LIMITED);
});

test("classifyProviderError: 403 with 'has not been used in project' => PROJECT_ROUTE_ERROR (transient)", () => {
const result = classifyProviderError(403, {
error: {
message: "Cloud Code Private API has not been used in project 12345 before or it is disabled.",
},
});
assert.equal(result, PROVIDER_ERROR_TYPES.PROJECT_ROUTE_ERROR);
});

test("classifyProviderError: 403 plain => FORBIDDEN (terminal)", () => {
const result = classifyProviderError(403, {
error: { message: "The caller does not have permission" },
});
assert.equal(result, PROVIDER_ERROR_TYPES.FORBIDDEN);
});

test("classifyProviderError: 403 with project string as plain string body => PROJECT_ROUTE_ERROR", () => {
const body = JSON.stringify({
error: { message: "API has not been used in project abc-xyz before" },
});
const result = classifyProviderError(403, body);
assert.equal(result, PROVIDER_ERROR_TYPES.PROJECT_ROUTE_ERROR);
});
41 changes: 40 additions & 1 deletion tests/unit/streamHelpers.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { describe, it } from "node:test";
import assert from "node:assert";
import { hasValuableContent } from "../../open-sse/utils/streamHelpers.ts";
import { hasValuableContent, unwrapGeminiChunk } from "../../open-sse/utils/streamHelpers.ts";
import { FORMATS } from "../../open-sse/translator/formats.ts";

describe("hasValuableContent", () => {
Expand Down Expand Up @@ -70,3 +70,42 @@ describe("hasValuableContent", () => {
});
});
});

describe("unwrapGeminiChunk", () => {
it("returns chunk directly when candidates is at top level (standard Gemini)", () => {
const chunk = { candidates: [{ content: { parts: [{ text: "Hi" }] } }], usageMetadata: {} };
const result = unwrapGeminiChunk(chunk);
assert.strictEqual(result, chunk);
});

it("unwraps Cloud Code envelope { response: { candidates: [...] } }", () => {
const inner = { candidates: [{ content: { parts: [{ text: "Hello" }] } }] };
const chunk = { response: inner, modelVersion: "gemini-2.5-flash" };
const result = unwrapGeminiChunk(chunk);
assert.strictEqual(result, inner);
assert.deepEqual(result.candidates[0].content.parts[0].text, "Hello");
});

it("returns parsed directly when no candidates and no response", () => {
const chunk = { someOther: "data" };
const result = unwrapGeminiChunk(chunk);
assert.strictEqual(result, chunk);
});

it("returns parsed when response exists but is null/undefined", () => {
const chunk = { response: null, other: "data" };

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: Test may pass incorrectly due to bug in unwrapGeminiChunk

The test returns parsed when response exists but null/undefined expects parsed to be returned when response: null. However, because the implementation uses parsed.response || parsed, the falsy null causes the fallback to parsed, making the test pass for the wrong reason.

If the implementation is fixed to if (!parsed.candidates && parsed.response), this test will fail because parsed.response (null) won't trigger the unwrap, and the function will correctly return parsed. The test should either be removed or updated to test response: undefined instead of response: null.

const result = unwrapGeminiChunk(chunk);
assert.strictEqual(result, chunk);
});

it("prefers top-level candidates over response when both exist", () => {
const inner = { candidates: [{ content: { parts: [{ text: "inner" }] } }] };
const chunk = {
candidates: [{ content: { parts: [{ text: "outer" }] } }],
response: inner,
};
const result = unwrapGeminiChunk(chunk);
assert.strictEqual(result, chunk);
assert.equal(result.candidates[0].content.parts[0].text, "outer");
});
});