Files
OmniRoute/tests/unit/translator-openai-to-gemini.test.ts
Diego Rodrigues de Sa e Souza f59f8daa94 Release v3.8.6 (#2804)
* fix(gemini): preserve structured tool calls for antigravity

* fix(gemini): parse prefixed textual tool calls

* fix(antigravity): preserve textual SSE tool calls

* fix(stream): normalize textual passthrough tool calls

* fix(stream): normalize split textual tool calls

* fix(stream): suppress malformed textual tool calls

* fix(stream): suppress compact malformed tool calls

* fix(stream): emit structured textual tool calls

* fix(stream): suppress unknown textual tool calls

* fix(stream): normalize responses textual tool calls

* chore: ignore .claude/settings.local.json (per-user Claude Code permissions)

* fix(opencode-go): route qwen3.x via claude messages + repair fixMissingToolResponses for Claude-shape upstreams (#2791)

Integrated into release/v3.8.6

* fix: resolve npm install warnings — remove dead deps, relax engine constraint (#2792)

Integrated into release/v3.8.6

* fix: register missing web-cookie validators (claude-web, gemini-web, copilot-web, t3-web) (#2793)

Integrated into release/v3.8.6

* fix: Error: Unable to inspect existing database #2771 (#2795)

Integrated into release/v3.8.6

* fix(oauth): repair Google loopback callback flow (#2796)

Integrated into release/v3.8.6

* feat(logs): add clean history button (#2799)

Integrated into release/v3.8.6

* [codex] home: restore settings-driven home layout and quota auto-refresh (#2800)

Integrated into release/v3.8.6

* fix(gemini): emit signaturelessToolCallMode:text for GEMINI format models (#2801)

Integrated into release/v3.8.6

* feat(modelSpecs): align opencode-go family with upstream provider limits (#2802)

Integrated into release/v3.8.6

* chore: apply unit test fixes, polyfills, and environment precedence fixes

* docs(agents): atualiza fluxos de release e triagem

Expande os workflows de release para incluir auditoria de segurança,
CHANGELOG completo por commits, quality gate obrigatório, homologação em
VPS local, publicação oficial, deploy em Akamai e validação de artefatos.

Reorganiza a triagem de features com arquivos permanentes por bucket,
suporte a itens em andamento, regra de reclaim após 15 dias e novo
tratamento para ideias viáveis catalogadas.

Corrige a orientação de revisão de discussões para usar a ordem
cronológica real dos comentários e respostas ao identificar a última
atividade.

* fix(lockout): classify Gemini Antigravity resource exhaustion as quota_exhausted

* fix(reasoning): gate replay by interleaved field

* docs(rule-16): permit human Co-authored-by, restrict only AI/bot trailers

Rule #16 previously banned all `Co-Authored-By` trailers absolutely.
That blocked the upstream-port workflows (`/port-upstream-features` and
`/port-upstream-issues`), which must credit human upstream PR authors
and issue reporters in OmniRoute commits.

Refine the rule to ban only AI/bot-attributed trailers (Claude, GPT,
Copilot, Bot; anthropic.com / openai.com / bot-owned noreply.github.com
emails) while allowing standard human `Co-authored-by: Name <email>`
attribution.

Sync the rule across the source CLAUDE.md, the E2E shakedown doc note,
and 41 i18n translations.

* fix(gitlawb): add specialty validators for connection test — bypass /models probe

GitLawB OpenGateway API (xiaomi-mimo compatible) does not expose a /models
endpoint, causing validateOpenAILikeProvider to 404 on the initial probe
and report 'Provider validation endpoint not supported'.

Add specialty validators for both gitlawb and gitlawb-gmi that follow the
same pattern as the existing xiaomi-mimo validator: skip GET /models,
validate directly via POST /chat/completions with a minimal test message.
Any 401/403 response means an invalid key; all other responses mean auth
is OK.

Fixes test-connection returning 404 for GitLawB providers.

* test(gitlawb): add 12 unit tests for gitlawb and gitlawb-gmi specialty validators

Covers success, auth failure (401/403), non-auth acceptance (400/422/429),
network errors, and custom baseUrl overrides for both providers.

* feat(gitlawb): serve models from static registry without API-unavailable warning

GitLawB's OpenGateway API does not expose a /models endpoint per
provider-path. Previously the models route fell through to the generic
fallback which returned static catalog models with the misleading
'API unavailable — using local catalog' warning.

Now gitlawb and gitlawb-gmi are handled as static model providers
(same pattern as reka and qwen OAuth) — models are served from the
provider registry without any warning, since all registered models
are functional via POST /chat/completions.

* refactor(gitlawb): extract shared opengateway validator factory, fix docs path in test

- Extract gitlawb/gitlawb-gmi validators into buildOpengatewayValidator factory
- Fix dockerignore-docs-coverage test: update stale docs/AUTO-COMBO.md -> docs/routing/AUTO-COMBO.md

* fix(reasoning): guard interleaved capability lookup

* feat(gitlawb): dynamic model fetch with gmi-cloud fallback

Hybrid approach:
- gitlawb (xiaomi-mimo): dynamic /models endpoint → 356 models
- gitlawb-gmi (gmi-cloud): 404 fallback → local catalog gracefully
Mimics Gitlawb/openclaude's model-routing pattern

* i18n(pt-BR): complete missing translations and sync with en.json

* feat(build): nix multi-OS package manager install (#2806)

Integrated into release/v3.8.6

* fix(i18n): translate 144 new __MISSING__ pt-BR strings (#2816)

Integrated into release/v3.8.6

* chore(docs): set coverage gate to 40/40/40/40 in CLAUDE.md

Aligns the documented coverage gate with the v3.8.6 release decision
(lowered from 75/75/75/70). Matches the threshold already set in
package.json by the large feature PRs (planos 11-22).

* fix(cli): respect PORT env var in serve command (#2845)

Integrated into release/v3.8.6.

* fix(deepseek-web): return 400 when client sends tools[] - chat.deepseek.com has no tool support (#2854)

Integrated into release/v3.8.6.

* fix(qoder): reject invalid/expired PATs returning Cosy 500 error (#2860)

Integrated into release/v3.8.6.

* fix(cli): register openclaw in tool-detector (#2833) (#2850)

Integrated into release/v3.8.6.

* fix(api): include noAuth providers in /v1/models catalog (#2798) (#2814)

Integrated into release/v3.8.6.

* fix(combo): resolve custom provider targets via combo name (#2778) (#2812)

Integrated into release/v3.8.6.

* fix(translator): strip safety_identifier in openai-responses cleanup (#2770) (#2809)

Integrated into release/v3.8.6.

* fix(quota): honor explicit per-connection preflight opt-out (#2831) (#2844)

Integrated into release/v3.8.6.

* fix(usage): un-invert GitHub Copilot Free/limited quota — limited_user_quotas is remaining (#2876) (#2881)

Integrated into release/v3.8.6.

* fix(nous-research): correct baseUrl to include /chat/completions (#2826) (#2835)

Integrated into release/v3.8.6.

* fix(opencode): qwen3.x max/plus models lack vision support (#2822) (#2836)

Integrated into release/v3.8.6.

* fix(translator): pass-through tool_search built-in tool type (#2766) (#2811)

Integrated into release/v3.8.6.

* fix(github): route claude-opus-4.6 via chat completions (#2821)

Integrated into release/v3.8.6.

* docs(oauth): add Windsurf login fix design (Phase 1 hotfix + Phase 2 Firebase OAuth)

Two-phase plan to fix the broken Windsurf OAuth flow:
- Phase 1: drop the dead app.devin.ai/editor/signin PKCE path, promote
  import-token from windsurf.com/show-auth-token as the primary path
- Phase 2: port Firebase OAuth + RegisterUser flow from
  fendoushaonian/WindSurf-gRPC-API for full browser-based automation

Spec only - no code changes yet.

* docs(plan): Phase 1 windsurf login hotfix implementation plan

10 tasks covering:
- TDD assertions for flowType + 410 Gone responses
- Provider switch to import_token
- Route handler retiring authorize/start-callback-server/poll-callback
- OAuthModal UI override
- i18n sync
- Verification + PR steps

* fix(cli): replace cli-table3 with hand-rolled formatter (#2752) (#2813)

Integrated into release/v3.8.6.

* fix(skills): skip interception for unregistered client-native tools (#2815) (#2817)

Integrated into release/v3.8.6.

* feat(sse): add RTK filters for kubectl, docker-build, composer, gh (#2824)

Integrated into release/v3.8.6.

* fix(geminiHelper): support rec.image content shape + warn on dropped remote URLs (refs #2807) (#2855)

Integrated into release/v3.8.6.

* fix(cli): allow nullable/optional apiKey in cliMitmStartSchema (#2857)

Integrated into release/v3.8.6.

* fix(combo): preserve system messages during context handoff summary generation (#2865)

Integrated into release/v3.8.6.

* fix: wire CLIProxyAPI fallback settings into chatCore routing engine (#2866)

Integrated into release/v3.8.6.

* fix(usage): add opencode quota fetcher (#2852) (#2867)

Integrated into release/v3.8.6.

* feat(claude): default xhigh support for newer Opus models (#2874)

Integrated into release/v3.8.6.

* fix(cli): restore omniroute logs command stream (#2756) (#2810)

Integrated into release/v3.8.6.

* fix(combo): normalize upstream Headers for Node 24 undici interop (#2751) (#2823)

Integrated into release/v3.8.6.

* Rename proxy log Public IP to Client IP (#2880)

Integrated into release/v3.8.6.

* fix(claude): preserve max effort for supported models (#2875)

Integrated into release/v3.8.6.

* fix(oauth): switch windsurf provider to import_token flow

The PKCE auth URL targeting app.devin.ai/editor/signin returns 404
post-rebrand. Until Phase 2 ports Firebase OAuth + RegisterUser, the
only supported path is import-token via windsurf.com/show-auth-token.

- windsurf.ts: drop buildAuthUrl, set flowType=import_token
- generateAuthData returns supported:false + helpful error for windsurf/devin-cli
- tests: assert flowType + disabled stub

* fix(oauth): return 410 Gone for retired windsurf/devin-cli PKCE actions

start-callback-server, authorize, and poll-callback (GET + POST) now
return 410 Gone with a pointer to /import-token. The 410 short-circuit
runs before auth so the response is honest about the action being
permanently gone, not gated. Codex PKCE flow unchanged.

Tests: 5 new assertions cover GET + POST 410 paths and a Codex
regression check.

* refactor(oauth): annotate retired PKCE fields in WINDSURF_CONFIG

No behaviour change - comment-only update documenting that authorizeUrl,
codeChallengeMethod, callbackPort, callbackPath, apiServerUrl, and
exchangePath are no longer consumed. Active fields (inferenceUrl,
showAuthTokenUrl, firebaseApiKey, ideName) called out separately.

* fix(cli,docs): use requireCliToolsAuth in logs route + document OPENCODE quota env

Post-merge contract fixes for v3.8.6:
- src/app/api/cli-tools/logs/route.ts (#2810) now uses the shared
  requireCliToolsAuth guard (param renamed req->request) to satisfy the
  cli-tools-auth-hardening contract test.
- Document OMNIROUTE_OPENCODE_QUOTA_URL (#2867) in docs/reference/ENVIRONMENT.md
  to satisfy the env/docs sync contract.

* fix(dashboard): force import-token panel for windsurf/devin-cli

Phase 1 hotfix: hide the 'Browser Login' tab and start in Paste API Key
mode. Removes windsurf/devin-cli from PKCE_CALLBACK_SERVER_PROVIDERS so
no callback server is started for them. Codex still uses the PKCE flow.

The 'Get token' link continues to point at windsurf.com/show-auth-token
via the existing supportsTokenPaste form copy.

* fix(oauth): windsurf import-token mapTokens signature mismatch

The route at `src/app/api/oauth/[provider]/[action]/route.ts` invokes
`providerData.mapTokens({ accessToken: token })` (object), matching the
cursor/kiro signature. The windsurf provider was declared with
`mapTokens(token: string)` instead, so the entire object was stored as
`accessToken`. When the connection record reached the SQLite layer it
crashed with:

  SQLite3 can only bind numbers, strings, bigints, buffers, and null

Fix by aligning windsurf's `mapTokens` signature with the route caller
and the cursor/kiro convention. Also dedupe a copy-pasted second
`if (action === "import-token")` block in the route handler — the
second block was unreachable but identical to the first.

Adds two regression tests asserting that
`provider.mapTokens({ accessToken })` returns a string `accessToken` for
both windsurf and devin-cli, so a future signature drift trips the gate
instead of the SQLite bind error in production.

* feat(compression): expand pt-BR pack with troglodita rules (15 → 49) (#2818)

Integrated into release/v3.8.6

* fix(sse): repair RTK engine defaults so dedup and direct calls work (#2825)

Integrated into release/v3.8.6

* fix(mcp): redirect console.log/warn to stderr in --mcp stdio mode (#2840)

Integrated into release/v3.8.6

* fix(gemini-cli): prefer real project IDs over default-project (#2841)

Integrated into release/v3.8.6

* fix(opencode-go): add provider limits quota fetcher (#2861)

Integrated into release/v3.8.6

* Audit & add web cookie providers: fix 4 missing registry entries + DuckDuckGo (#2862)

Integrated into release/v3.8.6

* fix(antigravity): harden signatureless tool history (#2878)

Integrated into release/v3.8.6

* fix: provider model sync pruning and dynamic antigravity MITM proxy mappings (#2886)

Integrated into release/v3.8.6

* feat(usage): per-API-key token limits scoped to model/provider/global (#2888)

Integrated into release/v3.8.6

* fix(audio): build multipart body manually to preserve Content-Type (#2842)

Integrated into release/v3.8.6

* refactor: remove agent skill documentation files and streamline maintenance workflows

* test(stabilization): resolve unit test failures in blackbox-web, schema-coercion, translator-helper-branches, usage-service-hardening, and audio-transcription

* fix(security): mitigate Socket.dev supply-chain findings + secrets opt-in + minimal build profile (#2863) (#2871)

Two real security gaps closed and four cosmetic Socket.dev fingerprints removed.
See docs/security/SOCKET_DEV_FINDINGS.md for the per-finding maintainer
attestation.

Real bugs fixed:
- cloudSync: HMAC verification of `X-Cloud-Sig` + opt-in
  `OMNIROUTE_CLOUD_SYNC_SECRETS=true` before overwriting `accessToken` /
  `refreshToken` / `providerSpecificData` from a remote response. Closes the
  silent-credential-swap surface (a misconfigured or hostile CLOUD_URL could
  previously replace local tokens unverified).
- Zed import: split into 2-step `/discover` + `/import` flow. `/import` now
  requires `confirmedAccounts: [{ service, account, fingerprint }]` and
  re-reads the keychain server-side to filter by fingerprint, so a tampered
  discover response cannot trick the endpoint into saving an unrelated token.

Cosmetic Socket.dev mitigations:
- runElevatedPowerShell writes the elevated payload to a per-call temp `.ps1`
  file (mode 0o600) and references it via `-File`. Removes the textbook
  `-EncodedCommand <base64utf16le>` pattern flagged as malware by Socket's AI
  classifier.
- Maintainer attestation `SECURITY-AUDITOR-NOTE:` blocks added at every
  flagged call site pointing to `docs/security/SOCKET_DEV_FINDINGS.md`.

Build-time hardening:
- `OMNIROUTE_BUILD_PROFILE=minimal` (`npm run build:secure`) physically
  removes the four sensitive modules from the standalone bundle via webpack
  `NormalModuleReplacementPlugin`. Stubs throw `FeatureDisabledError` at
  runtime. Intended for the `omniroute-secure` artifact.

Tests:
- 24 new unit tests in `tests/unit/security/` covering the wrapper builder,
  HMAC verification (4 cases), credential fingerprint determinism (5 cases),
  confirmedAccounts validation + fingerprint filtering (6 cases), and the
  minimal-build stubs (5 cases).

Docs:
- New `docs/security/SOCKET_DEV_FINDINGS.md` — per-finding attestation.
- New `socket.yml` — Socket.dev v2 config pointing at the attestation.
- Updated `SECURITY.md` — supply-chain scanner section.
- Updated `.env.example` — three new env vars documented.

Backwards compatibility:
- Cloud sync token overwrite is OFF by default. Users who relied on
  it must set `OMNIROUTE_CLOUD_SYNC_SECRETS=true`. Breaking change documented
  in CHANGELOG.
- Zed import 2-step is the new default; legacy 1-step preserved behind
  `OMNIROUTE_ZED_IMPORT_LEGACY_ONE_STEP=true` and will be removed in v3.9.

Closes #2863

* fix(security): redact public Firebase Web key from windsurf spec; doc SHA-256 cache-key rationale (#2894)

Two security-scanning findings on release/v3.8.6:

- Secret-scanning alert 7 (google_api_key): the windsurf login-fix design spec
  embedded the literal public Firebase Web API key on two lines. Firebase Web
  API keys are non-sensitive by design (they identify the project; access is
  gated by Firebase Security Rules + key restrictions), but the literal trips
  secret scanning. Redacted to a placeholder; the embedded default still goes
  through resolvePublicCred per rule #11.

- Code-scanning alert 261 (js/insufficient-password-hash): tokenCacheKey() uses
  SHA-256 to derive an in-memory cache key from the session token, not for
  password-at-rest storage. Added a comment documenting why CWE-916 KDFs do not
  apply (false positive).

* fix(ci): resolve release/v3.8.6 gate failures (docs-sync, any-budget, pack-artifact) (#2895)

* fix(ci): resolve release/v3.8.6 gate failures (docs-sync, any-budget, pack-artifact)

Three CI gates failed on release/v3.8.6 (run 26630300877):

- docs-sync: CHANGELOG had a spurious "## [3.8.6-patch]" section above
  "## [3.8.6]", so the latest release no longer matched package.json (3.8.6)
  and the 41 i18n CHANGELOG mirrors were flagged as missing that section.
  Fold the lone #2752 entry into [3.8.6] and drop the patch heading.
- any-budget:t11: open-sse/handlers/chatCore.ts regressed to 1 explicit `any`
  (budget 0). Type the persist callback arg as Record<string, unknown>, which
  matches runWithOnPersist's RefreshPersistFn contract exactly.
- pack-artifact: open-sse/utils/setupPolyfill.ts ships via package.json "files"
  (bin/omniroute.mjs imports it at startup) but was missing from the pack
  policy allowlist. Allow it and add a regression test.

* fix(security): redact public Firebase Web key from windsurf spec

Redact the literal public Firebase Web API key (secret-scanning #7) to a
placeholder, mirroring the redaction on release/v3.8.6 (PR #2894) and the
windsurf fix branch. Non-sensitive public Web key; trips secret scanning.

* feat(combo): Zero-Latency Combos (Hedging, Proactive Compression, Predictive TTFT) (#2868)

* feat(combo): implement zero-latency combo optimizations (hedging, proactive compression, predictive TTFT)

* fix(combo): fix predictive TTFT skip logic and unhandled promise rejections

---------

Co-authored-by: Automation <automation@omniroute>

* feat: implement automated skill workflows and update system configuration and validation schemas

* test: eliminate dynamic cast warnings in cloud-sync unit test

* test: isolate services-branch-hardening database directory to avoid concurrency issues

* feat(providers): add 7 new web-cookie providers + research catalog + discovery tool

New providers:
- huggingchat: free LLM chat via huggingface.co/chat (no subscription)
- phind: free dev-focused AI chat via phind.com/api/agent
- poe-web: multi-model chat via poe.com GraphQL (p-b cookie)
- venice-web: privacy-focused AI chat via venice.ai (session cookie)
- v0-vercel-web: Vercel v0 code gen via v0.dev (session cookie)
- kimi-web: Moonshot Kimi chat via kimi.moonshot.cn (session cookie)
- doubao-web: ByteDance Doubao chat via doubao.com (session cookie)

Additional:
- Research catalog: docs/research/UNLIMITED_LLM_ACCESS.md
- Discovery tool design + stub: src/lib/discovery/ + migration 073
- Unit tests: 33 tests for all 7 providers
- Shared helpers consolidated in error.ts (slop cleanup)
- All registered in WEB_COOKIE_PROVIDERS + providerRegistry + webSessionCredentials

Closes #2885

* fix(typecheck): resolve typecheck errors in combo spec and compression modules

* feat(api,oauth): add `agy` (Antigravity CLI) standalone provider with CLI token import (#2899)

Add a standalone OAuth provider `agy` (Antigravity CLI) next to gemini-cli/antigravity.
It reuses the antigravity inference backend (identical Google client_id +
daily-cloudcode-pa.googleapis.com endpoint, executor and token-refresh) but ships its own
model catalog — including the Claude models the backend exposes (claude-opus-4-6-thinking,
claude-sonnet-4-6) — its own account pool, and four ways to connect:

- token-file import (paste/upload the agy oauth token JSON)
- auto-detect a local CLI login (~/.gemini/antigravity-cli/antigravity-oauth-token)
- browser OAuth (via the shared OAuthModal Google loopback flow)
- bulk / ZIP import

New routes: POST /api/providers/agy-auth/{import,import-bulk,zip-extract,apply-local}.
Catalog pinned from the live :fetchAvailableModels endpoint. Docs (openapi.yaml,
ENVIRONMENT.md, .env.example, CHANGELOG) updated; new unit tests for registration,
the token parser, and route auth-hardening.

* fix(security): redact public Firebase Web key from windsurf spec (#2896)

Redact the literal public Firebase Web API key (secret-scanning #7) to a
placeholder. Firebase Web API keys are non-sensitive by design but the literal
trips GitHub secret scanning. Mirrors the redaction landed on release/v3.8.6
(PR #2894). Embedded default still flows through resolvePublicCred (rule #11).

* Pr 2871 (#2897)

* fix(security): mitigate Socket.dev supply-chain findings + secrets opt-in + minimal build profile (#2863)

Two real security gaps closed and four cosmetic Socket.dev fingerprints removed.
See docs/security/SOCKET_DEV_FINDINGS.md for the per-finding maintainer
attestation.

Real bugs fixed:
- cloudSync: HMAC verification of `X-Cloud-Sig` + opt-in
  `OMNIROUTE_CLOUD_SYNC_SECRETS=true` before overwriting `accessToken` /
  `refreshToken` / `providerSpecificData` from a remote response. Closes the
  silent-credential-swap surface (a misconfigured or hostile CLOUD_URL could
  previously replace local tokens unverified).
- Zed import: split into 2-step `/discover` + `/import` flow. `/import` now
  requires `confirmedAccounts: [{ service, account, fingerprint }]` and
  re-reads the keychain server-side to filter by fingerprint, so a tampered
  discover response cannot trick the endpoint into saving an unrelated token.

Cosmetic Socket.dev mitigations:
- runElevatedPowerShell writes the elevated payload to a per-call temp `.ps1`
  file (mode 0o600) and references it via `-File`. Removes the textbook
  `-EncodedCommand <base64utf16le>` pattern flagged as malware by Socket's AI
  classifier.
- Maintainer attestation `SECURITY-AUDITOR-NOTE:` blocks added at every
  flagged call site pointing to `docs/security/SOCKET_DEV_FINDINGS.md`.

Build-time hardening:
- `OMNIROUTE_BUILD_PROFILE=minimal` (`npm run build:secure`) physically
  removes the four sensitive modules from the standalone bundle via webpack
  `NormalModuleReplacementPlugin`. Stubs throw `FeatureDisabledError` at
  runtime. Intended for the `omniroute-secure` artifact.

Tests:
- 24 new unit tests in `tests/unit/security/` covering the wrapper builder,
  HMAC verification (4 cases), credential fingerprint determinism (5 cases),
  confirmedAccounts validation + fingerprint filtering (6 cases), and the
  minimal-build stubs (5 cases).

Docs:
- New `docs/security/SOCKET_DEV_FINDINGS.md` — per-finding attestation.
- New `socket.yml` — Socket.dev v2 config pointing at the attestation.
- Updated `SECURITY.md` — supply-chain scanner section.
- Updated `.env.example` — three new env vars documented.

Backwards compatibility:
- Cloud sync token overwrite is OFF by default. Users who relied on
  it must set `OMNIROUTE_CLOUD_SYNC_SECRETS=true`. Breaking change documented
  in CHANGELOG.
- Zed import 2-step is the new default; legacy 1-step preserved behind
  `OMNIROUTE_ZED_IMPORT_LEGACY_ONE_STEP=true` and will be removed in v3.9.

Closes #2863

* feat: implement automated skill workflows and update system configuration and validation schemas

* test: eliminate dynamic cast warnings in cloud-sync unit test

* test: isolate services-branch-hardening database directory to avoid concurrency issues

* chore(docs): refresh generated docs collection index

Update the generated Fumadocs browser collection mapping to keep
documentation imports in sync with the current docs structure.

* docs: update generated browser docs collection manifest

Refresh the generated Fumadocs browser collection mapping so the docs site can resolve the current documentation files correctly.

---------

Co-authored-by: OpenClaw <openclaw@kuzhomesrv.local>
Co-authored-by: Dmitry Kuznetsov <139351986+dmitry@users.noreply.local>
Co-authored-by: KuzyaBot <kuzya@local>
Co-authored-by: JeferssonLemes <jeferssondev@gmail.com>
Co-authored-by: Paijo <14921983+oyi77@users.noreply.github.com>
Co-authored-by: Markus Hartung <mail@hartmark.se>
Co-authored-by: akarray <akarray@users.noreply.github.com>
Co-authored-by: Apostol Apostolov <theapoapostolov@gmail.com>
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
Co-authored-by: Dmitry Kuznetsov <dmitry@kuznetsov.me>
Co-authored-by: Nikolay Alafuzov <alafuzov_nn@rusklimat.ru>
Co-authored-by: oyi77 <oyi77@users.noreply.github.com>
Co-authored-by: Ronaldo Davi <alltomatos@users.noreply.github.com>
Co-authored-by: levonk <277861+levonk@users.noreply.github.com>
Co-authored-by: Lenine Júnior <lenine@engrene.com.br>
Co-authored-by: Annas Alghoffar <aag.annas@gmail.com>
Co-authored-by: Tushar Agarwal <76201310+Tushar49@users.noreply.github.com>
Co-authored-by: GreatLiu <eurasiaxz@qq.com>
Co-authored-by: yuna amelia <230527278+yunaamelia@users.noreply.github.com>
Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Container <78986709+disonjer@users.noreply.github.com>
Co-authored-by: nickwizard <35692452+nickwizard@users.noreply.github.com>
Co-authored-by: Rajvardhan Patil <rajvardhanpatil7890@gmail.com>
Co-authored-by: Raxxoor <manker_lol@hotmail.com>
Co-authored-by: Muhammad Mugni Hadi <mugnimaestra3@gmail.com>
Co-authored-by: mi <123757457+soyelmismo@users.noreply.github.com>
Co-authored-by: Automation <automation@omniroute>
2026-05-29 12:44:29 -03:00

1155 lines
40 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
const { openaiToAntigravityRequest, openaiToGeminiCLIRequest, openaiToGeminiRequest } =
await import("../../open-sse/translator/request/openai-to-gemini.ts");
const { getRequestTranslator } = await import("../../open-sse/translator/registry.ts");
const { FORMATS } = await import("../../open-sse/translator/formats.ts");
const {
DEFAULT_SAFETY_SETTINGS,
cleanJSONSchemaForAntigravity,
convertOpenAIContentToParts,
generateRequestId,
generateSessionId,
tryParseJSON,
} = await import("../../open-sse/translator/helpers/geminiHelper.ts");
const { ANTIGRAVITY_DEFAULT_SYSTEM } = await import("../../open-sse/config/constants.ts");
type UnknownRecord = Record<string, unknown>;
function getFunctionCall(part: unknown) {
assert.ok(part && typeof part === "object", "expected Gemini functionCall part");
const functionCall = (part as UnknownRecord).functionCall;
assert.ok(functionCall && typeof functionCall === "object", "expected functionCall payload");
return functionCall as { id?: string; name: string; args?: unknown };
}
function getFunctionResponse(part: unknown) {
assert.ok(part && typeof part === "object", "expected Gemini functionResponse part");
const functionResponse = (part as UnknownRecord).functionResponse;
assert.ok(
functionResponse && typeof functionResponse === "object",
"expected functionResponse payload"
);
return functionResponse as { id?: string; name: string; response?: unknown };
}
function getFunctionDeclarationParameters(parameters: unknown) {
assert.ok(
parameters && typeof parameters === "object",
"expected function declaration parameters"
);
return parameters as UnknownRecord & {
properties?: Record<string, UnknownRecord>;
examples?: unknown;
$schema?: unknown;
};
}
test("OpenAI -> Gemini helper converts text, images and files into Gemini parts", () => {
// Suppress warn emitted for the remote https://example.com/skip.png URL in the
// fixture below — that warn is expected and tested separately. Suppressing here
// keeps stderr clean so CI does not flag spurious output.
const originalWarn = console.warn;
console.warn = () => {};
try {
const parts = convertOpenAIContentToParts([
{ type: "text", text: "Hello" },
{ type: "image_url", image_url: { url: "data:image/png;base64,abc" } },
{ type: "file_url", file_url: { url: "data:application/pdf;base64,Zm9v" } },
{ type: "document", document: { url: "data:text/plain;base64,YmFy" } },
{ type: "image_url", image_url: { url: "https://example.com/skip.png" } },
{ type: "file_url", file_url: { url: "not-a-data-url" } },
]);
assert.deepEqual(parts, [
{ text: "Hello" },
{ inlineData: { mimeType: "image/png", data: "abc" } },
{ inlineData: { mimeType: "application/pdf", data: "Zm9v" } },
{ inlineData: { mimeType: "text/plain", data: "YmFy" } },
]);
assert.deepEqual(convertOpenAIContentToParts("raw text"), [{ text: "raw text" }]);
} finally {
console.warn = originalWarn;
}
});
test("OpenAI -> Gemini helper cleans complex JSON Schema structures for Gemini compatibility", () => {
const cleaned = cleanJSONSchemaForAntigravity({
type: "object",
title: "Root schema",
properties: {
mode: { const: "fast" },
retries: { type: "integer", enum: [1, 2, 3] },
payload: {
anyOf: [
{ type: "null" },
{
type: "object",
properties: {
id: { type: ["string", "null"], minLength: 1 },
nested: {
allOf: [
{
properties: {
a: { type: "string" },
},
required: ["a"],
},
{
properties: {
b: { type: "number" },
},
required: ["missing", "b"],
},
],
},
},
required: ["id", "missing"],
},
],
},
emptyObject: {
type: "object",
additionalProperties: false,
},
},
required: ["mode", "payload", "missingRoot"],
});
assert.equal(cleaned.properties.mode.type, "string");
assert.deepEqual(cleaned.properties.mode.enum, ["fast"]);
assert.equal(cleaned.properties.retries.enum, undefined);
assert.equal(cleaned.properties.payload.type, "object");
assert.equal(cleaned.properties.payload.properties.id.type, "string");
assert.equal("minLength" in cleaned.properties.payload.properties.id, false);
assert.deepEqual(cleaned.properties.payload.required, ["id"]);
assert.deepEqual(cleaned.properties.payload.properties.nested.required.sort(), ["a", "b"]);
assert.deepEqual(cleaned.required.sort(), ["mode", "payload"]);
assert.deepEqual(cleaned.properties.emptyObject.required, ["reason"]);
assert.equal(cleaned.properties.emptyObject.properties.reason.type, "string");
});
test("OpenAI -> Gemini helper inlines local refs and preserves only additionalProperties=true", () => {
const cleaned = cleanJSONSchemaForAntigravity({
type: "object",
$defs: {
Address: {
type: "object",
properties: {
street: { type: "string", minLength: 1 },
},
required: ["street"],
additionalProperties: false,
},
},
properties: {
shipping: { $ref: "#/$defs/Address" },
metadata: {
type: "object",
additionalProperties: true,
},
options: {
type: "object",
additionalProperties: { type: "string" },
},
},
required: ["shipping"],
});
assert.equal(cleaned.$defs, undefined);
assert.equal(cleaned.properties.shipping.$ref, undefined);
assert.equal(cleaned.properties.shipping.properties.street.type, "string");
assert.equal(cleaned.properties.shipping.properties.street.minLength, undefined);
assert.deepEqual(cleaned.properties.shipping.required, ["street"]);
assert.equal(cleaned.properties.shipping.additionalProperties, undefined);
assert.equal(cleaned.properties.metadata.additionalProperties, undefined);
assert.equal(cleaned.properties.options.additionalProperties, undefined);
});
test("OpenAI -> Gemini request maps messages, merged system instructions, tools and response schema", () => {
const result = openaiToGeminiRequest(
"gemini-2.5-pro",
{
messages: [
{ role: "system", content: "Rule A" },
{ role: "system", content: [{ type: "text", text: "Rule B" }] },
{
role: "user",
content: [
{ type: "text", text: "What is the weather?" },
{ type: "image_url", image_url: { url: "data:image/png;base64,abc" } },
],
},
{
role: "assistant",
reasoning_content: "Need live data",
content: "Calling a tool",
tool_calls: [
{
id: "call_1",
type: "function",
function: { name: "weather", arguments: '{"city":"Tokyo"}' },
},
],
},
{
role: "tool",
tool_call_id: "call_1",
content: '{"temp":20}',
},
],
tools: [
{
type: "function",
function: {
name: "weather",
description: "Fetch weather",
parameters: {
type: "object",
properties: {
city: { type: ["string", "null"] },
},
required: ["city"],
},
},
},
],
max_completion_tokens: 2222,
temperature: 0.3,
top_p: 0.9,
stop: ["DONE"],
response_format: {
type: "json_schema",
json_schema: {
schema: {
type: "object",
properties: {
answer: { const: "ok" },
},
required: ["answer"],
},
},
},
},
false
);
assert.equal((result as any).systemInstruction.role, "system");
assert.deepEqual((result as any).systemInstruction.parts, [
{ text: "Rule A" },
{ text: "Rule B" },
]);
assert.equal(result.contents[0].role, "user");
assert.deepEqual(result.contents[0].parts, [
{ text: "What is the weather?" },
{ inlineData: { mimeType: "image/png", data: "abc" } },
]);
const modelTurn = result.contents.find(
(content) => content.role === "model" && content.parts.some((part) => part.functionCall)
);
assert.ok(modelTurn, "expected a model turn with functionCall");
const modelTurnThought = modelTurn.parts[0] as { thought?: boolean; text?: string };
const modelTurnFunctionCall = getFunctionCall(modelTurn.parts[2]);
assert.equal(modelTurn.parts[0].thought, true);
assert.equal(modelTurnThought.text, "Need live data");
assert.equal(modelTurn.parts[1].text, "Calling a tool");
assert.equal(modelTurnFunctionCall.name, "weather");
assert.deepEqual(modelTurnFunctionCall.args, { city: "Tokyo" });
const toolResponseTurn = result.contents.find(
(content) => content.role === "user" && content.parts.some((part) => part.functionResponse)
);
assert.ok(toolResponseTurn, "expected a tool response turn");
assert.deepEqual(getFunctionResponse(toolResponseTurn.parts[0]), {
id: "call_1",
name: "weather",
response: { result: { temp: 20 } },
});
assert.equal((result as any).generationConfig.maxOutputTokens, 2222);
assert.equal((result as any).generationConfig.temperature, 0.3);
assert.equal((result as any).generationConfig.topP, 0.9);
assert.deepEqual((result as any).generationConfig.stopSequences, ["DONE"]);
assert.equal((result as any).generationConfig.responseMimeType, "application/json");
const responseSchema = (result as any).generationConfig.responseSchema as {
properties: { answer: { type: string; enum?: string[] } };
};
assert.equal(responseSchema.properties.answer.type, "string");
assert.deepEqual(responseSchema.properties.answer.enum, ["ok"]);
const parameters = getFunctionDeclarationParameters(
(result as any).tools[0].functionDeclarations[0].parameters
);
assert.deepEqual(parameters, {
type: "object",
properties: {
city: { type: "string" },
},
required: ["city"],
});
assert.deepEqual(result.safetySettings, DEFAULT_SAFETY_SETTINGS);
});
test("OpenAI -> Gemini request preserves custom safety settings and handles system-only requests", () => {
const customSafety = [{ category: "HARM_CATEGORY_HATE_SPEECH", threshold: "BLOCK_ONLY_HIGH" }];
const result = openaiToGeminiRequest(
"gemini-2.5-flash",
{
messages: [{ role: "system", content: "Only rules" }],
safetySettings: customSafety,
},
false
);
assert.deepEqual(result.safetySettings, customSafety);
assert.equal((result as any).systemInstruction, undefined);
assert.equal(result.contents.length, 1);
assert.equal(result.contents[0].role, "user");
assert.deepEqual(result.contents[0].parts, [{ text: "Only rules" }]);
});
test("OpenAI -> Gemini CLI adds thinking config and normalizes namespaced tool names", () => {
const result = openaiToGeminiCLIRequest(
"gemini-2.5-pro",
{
messages: [
{ role: "user", content: "Check weather" },
{
role: "assistant",
tool_calls: [
{
id: "call_1",
type: "function",
function: { name: "ns:weather", arguments: '{"city":"Tokyo"}' },
},
],
},
{
role: "tool",
tool_call_id: "call_1",
content: '{"temp":20}',
},
],
tools: [
{
type: "function",
function: {
name: "ns:weather",
parameters: { type: "object", properties: {} },
},
},
],
reasoning_effort: "high",
},
false
);
assert.equal((result as any).generationConfig.thinkingConfig.includeThoughts, true);
assert.ok((result as any).generationConfig.thinkingConfig.thinkingBudget > 0);
assert.equal((result as any).tools[0].functionDeclarations[0].name, "weather");
assert.equal((result as any)._toolNameMap.get("weather"), "ns:weather");
const modelTurn = result.contents.find((content) => content.role === "model");
assert.ok(modelTurn, "expected a model turn");
assert.equal(getFunctionCall(modelTurn.parts[0]).name, "weather");
const responseTurn = result.contents.find(
(content) => content.role === "user" && content.parts.some((part) => part.functionResponse)
);
assert.ok(responseTurn, "expected a function response turn");
assert.equal(getFunctionResponse(responseTurn.parts[0]).name, "weather");
});
test("OpenAI -> Gemini CLI wraps Cloud Code envelope with native top-level and request keys", async () => {
const { getRequestTranslator } = await import("../../open-sse/translator/registry.ts");
const { FORMATS } = await import("../../open-sse/translator/formats.ts");
await import("../../open-sse/translator/request/openai-to-gemini.ts");
const translate = getRequestTranslator(FORMATS.OPENAI, FORMATS.GEMINI_CLI);
assert.ok(translate, "expected Gemini CLI translator to be registered");
const result = translate(
"models/gemini-2.5-flash",
{ messages: [{ role: "user", content: "Hello" }] },
true,
{ projectId: "projects/demo" }
) as UnknownRecord;
const request = result.request as UnknownRecord;
assert.deepEqual(Object.keys(result), ["model", "project", "user_prompt_id", "request"]);
assert.equal(result.model, "gemini-2.5-flash");
assert.equal(result.project, "projects/demo");
assert.equal(typeof result.user_prompt_id, "string");
assert.equal(result.userAgent, undefined);
assert.equal(result.requestId, undefined);
assert.equal(result.requestType, undefined);
assert.equal(typeof request.session_id, "string");
assert.equal(request.sessionId, undefined);
assert.ok(Array.isArray(request.contents));
});
test("OpenAI -> Gemini request sanitizes long MCP tool names and strips unsupported schema fields", () => {
const longToolName =
"mcp__filesystem__read_multiple_files_with_validation_and_metadata_bundle_v2";
const result = openaiToGeminiRequest(
"gemini-2.5-pro",
{
messages: [
{ role: "user", content: "Read the file set" },
{
role: "assistant",
tool_calls: [
{
id: "call_long_1",
type: "function",
function: { name: longToolName, arguments: '{"paths":["/tmp/a","/tmp/b"]}' },
},
],
},
{
role: "tool",
tool_call_id: "call_long_1",
content: '{"ok":true}',
},
],
tools: [
{
type: "function",
function: {
name: longToolName,
parameters: {
type: "object",
$schema: "http://json-schema.org/draft-07/schema#",
examples: [{ paths: ["/tmp/a"] }],
properties: {
paths: {
type: "array",
items: { type: "string", "x-ui": "hidden" },
},
},
},
},
},
],
},
false
);
const sanitizedToolName = (result as any).tools[0].functionDeclarations[0].name;
assert.ok(longToolName.length > 64);
assert.equal(sanitizedToolName.length, 64);
assert.match(sanitizedToolName, /_[a-f0-9]{8}$/);
assert.equal((result as any)._toolNameMap.get(sanitizedToolName), longToolName);
const modelTurn = result.contents.find((content) => content.role === "model");
assert.ok(modelTurn, "expected a model turn");
assert.equal(getFunctionCall(modelTurn.parts[0]).name, sanitizedToolName);
const toolTurn = result.contents.find(
(content) => content.role === "user" && content.parts.some((part) => part.functionResponse)
);
assert.ok(toolTurn, "expected a tool response turn");
assert.equal(getFunctionResponse(toolTurn.parts[0]).name, sanitizedToolName);
const longToolParameters = getFunctionDeclarationParameters(
(result as any).tools[0].functionDeclarations[0].parameters
) as UnknownRecord & {
properties?: {
paths?: {
items?: UnknownRecord;
};
};
};
assert.equal(longToolParameters.$schema, undefined);
assert.equal(longToolParameters.examples, undefined);
assert.equal(longToolParameters.properties?.paths?.items?.["x-ui"], undefined);
});
test("OpenAI -> Gemini request gives googleSearch precedence over function tools", () => {
const result = openaiToGeminiRequest(
"gemini-2.5-pro",
{
messages: [{ role: "user", content: "Search the web" }],
tools: [
{
type: "function",
function: {
name: "weather",
description: "Fetch weather",
parameters: { type: "object", properties: {} },
},
},
{ type: "web_search" },
],
},
false
);
assert.deepEqual((result as any).tools, [{ googleSearch: {} }]);
});
test("OpenAI -> Antigravity keeps googleSearch without function calling config", () => {
const result = openaiToAntigravityRequest(
"gemini-2.5-pro",
{
messages: [{ role: "user", content: "Search the web" }],
tools: [
{
type: "function",
function: {
name: "weather",
parameters: { type: "object", properties: {} },
},
},
{ type: "web_search_preview" },
],
},
false,
{ projectId: "proj-search" } as any
);
assert.deepEqual((result as any).request?.tools, [{ googleSearch: {} }]);
assert.equal(result.request.toolConfig, undefined);
});
test("OpenAI -> Gemini helper IDs and JSON parsing stay in the expected format", () => {
assert.match(generateRequestId(), /^agent-/);
assert.match(generateSessionId(), /^-\d+$/);
assert.deepEqual(tryParseJSON('{"ok":true}'), { ok: true });
assert.equal(tryParseJSON("not-json"), null as any);
});
test("OpenAI -> Gemini CLI wraps requests like native Cloud Code", () => {
const translate = getRequestTranslator(FORMATS.OPENAI, FORMATS.GEMINI_CLI);
assert.ok(translate, "expected Gemini CLI translator registration");
const envelope = translate(
"gemini-3-flash-preview",
{
messages: [{ role: "user", content: "Hello" }],
reasoning_effort: "high",
},
true,
{ projectId: "project-1" }
) as any;
assert.equal(envelope.model, "gemini-3-flash-preview");
assert.equal(envelope.userAgent, undefined);
assert.equal(envelope.requestId, undefined);
assert.equal(envelope.request.sessionId, undefined);
assert.match(envelope.request.session_id, /^[0-9a-f-]{36}$/i);
assert.equal(envelope.user_prompt_id, envelope.request.session_id);
});
test("OpenAI -> Gemini CLI emits native Cloud Code functionResponse output", () => {
const translate = getRequestTranslator(FORMATS.OPENAI, FORMATS.GEMINI_CLI);
assert.ok(translate, "expected Gemini CLI translator registration");
const envelope = translate(
"gemini-3-flash-preview",
{
messages: [
{ role: "user", content: "Read fixture" },
{
role: "assistant",
tool_calls: [
{
id: "read_file_123_0",
type: "function",
function: { name: "read_file", arguments: '{"file_path":"fixture.txt"}' },
},
],
},
{
role: "tool",
tool_call_id: "read_file_123_0",
content: "The answer is capybara-4729.",
},
],
},
true,
{ projectId: "project-1" }
) as any;
const toolTurn = envelope.request.contents.find(
(content) => content.role === "user" && content.parts.some((part) => part.functionResponse)
);
assert.ok(toolTurn, "expected Gemini CLI tool response turn");
assert.deepEqual(getFunctionResponse(toolTurn.parts[0]), {
id: "read_file_123_0",
name: "read_file",
response: { output: "The answer is capybara-4729." },
});
});
test("OpenAI -> Antigravity wraps Gemini requests in a Cloud Code envelope", () => {
const result = openaiToAntigravityRequest(
"gemini-2.5-pro",
{
messages: [{ role: "user", content: "Hello" }],
tools: [
{
type: "function",
function: {
name: "weather",
parameters: { type: "object", properties: {} },
},
},
],
reasoning_effort: "medium",
},
false,
{ projectId: "proj-1" } as any
);
assert.equal(result.project, "proj-1");
assert.deepEqual(Object.keys(result), [
"project",
"requestId",
"request",
"model",
"userAgent",
"requestType",
"enabledCreditTypes",
]);
assert.equal(result.userAgent, "antigravity");
assert.equal(result.requestType, "agent");
assert.match(result.requestId, /^agent\/\d+\/[0-9a-f]{8}$/);
assert.match(result.request.sessionId, /^-?\d+$/);
assert.deepEqual(result.enabledCreditTypes, ["GOOGLE_ONE_AI"]);
assert.equal(result.request.generationConfig.topK, 40);
assert.equal(result.request.generationConfig.topP, 1.0);
assert.equal(
(result as any).request?.systemInstruction.parts[0].text,
ANTIGRAVITY_DEFAULT_SYSTEM
);
assert.deepEqual(result.request.toolConfig, {
functionCallingConfig: { mode: "VALIDATED" },
});
});
test("OpenAI -> Antigravity Gemini preserves signature-less historical tool calls as inert text", () => {
const result = openaiToAntigravityRequest(
"gemini-3.5-flash-low",
{
messages: [
{ role: "user", content: "Update todo" },
{
role: "assistant",
tool_calls: [
{
id: "call_synthetic_1",
type: "function",
function: { name: "default_api:todowrite_ide", arguments: '{"todos":[]}' },
},
],
},
{
role: "tool",
tool_call_id: "call_synthetic_1",
content: "[]",
},
],
tools: [
{
type: "function",
function: {
name: "default_api:todowrite_ide",
parameters: { type: "object", properties: {} },
},
},
],
},
false,
{ projectId: "proj-antigravity-gemini" } as any
);
const modelTurn = result.request.contents.find((content) => content.role === "model");
assert.ok(modelTurn, "expected a model turn");
assert.ok(
modelTurn.parts.some(
(part) =>
typeof part.text === "string" &&
part.text.includes("Historical tool-call record only") &&
part.text.includes("Tool name: default_api:todowrite_ide") &&
part.text.includes('Tool arguments JSON: {"todos":[]}')
),
"expected signature-less tool call to be preserved as inert text"
);
assert.equal(
modelTurn.parts.some(
(part) => typeof part.text === "string" && part.text.includes("[Tool call:")
),
false,
"signature-less historical call must not use executable textual tool-call markers"
);
assert.equal(
modelTurn.parts.some((part) => part.functionCall),
false,
"signature-less historical call must not be emitted as native functionCall"
);
const toolTurn = result.request.contents.find(
(content) =>
content.role === "user" &&
content.parts.some(
(part) =>
typeof part.text === "string" &&
part.text.includes("Historical tool-response record only") &&
part.text.includes("Tool name: default_api:todowrite_ide") &&
part.text.includes("Tool result: []")
)
);
assert.ok(toolTurn, "expected signature-less tool response to be preserved as inert text");
assert.equal(
toolTurn.parts.some(
(part) => typeof part.text === "string" && part.text.includes("[Tool response:")
),
false,
"signature-less historical response must not use executable textual tool-response markers"
);
assert.equal(
toolTurn.parts.some((part) => part.functionResponse),
false,
"signature-less historical response must not be emitted as native functionResponse"
);
});
test("OpenAI -> Antigravity preserves multiple signature-less historical tool responses as text", () => {
const result = openaiToAntigravityRequest(
"gemini-3.5-flash-low",
{
messages: [
{ role: "user", content: "Inspect OmniRoute config" },
{
role: "assistant",
tool_calls: [
{
id: "call_missing_db",
type: "function",
function: { name: "terminal", arguments: '{"command":"cat data/db.json"}' },
},
{
id: "call_list_dir",
type: "function",
function: { name: "terminal", arguments: '{"command":"ls ~/.omniroute"}' },
},
],
},
{ role: "tool", tool_call_id: "call_missing_db", content: "data/db.json: No such file" },
{ role: "tool", tool_call_id: "call_list_dir", content: "storage.sqlite" },
],
tools: [
{
type: "function",
function: {
name: "terminal",
parameters: { type: "object", properties: {} },
},
},
],
},
false,
{ projectId: "proj-antigravity-gemini" } as any
);
const text = JSON.stringify(result.request.contents);
assert.ok(text.includes("Historical tool-call record only"), "expected signature-less calls as text");
assert.ok(text.includes("Tool name: terminal"), "expected signature-less calls as text");
assert.ok(
text.includes("data/db.json: No such file"),
"expected first signature-less tool response as text"
);
assert.ok(
text.includes("storage.sqlite"),
"expected second signature-less tool response as text"
);
assert.equal(
result.request.contents.some((content) => content.parts.some((part) => part.functionResponse)),
false,
"signature-less historical responses must not be emitted as native functionResponse"
);
});
test("OpenAI -> Antigravity maps Claude-family models to Gemini-compatible schema", () => {
const result = openaiToAntigravityRequest(
"claude-3-7-sonnet",
{
messages: [
{ role: "system", content: "Project rules" },
{ role: "user", content: "Read a file" },
{
role: "assistant",
tool_calls: [
{
id: "call_1",
type: "function",
function: { name: "read_file", arguments: '{"path":"/tmp/demo"}' },
},
],
},
{
role: "tool",
tool_call_id: "call_1",
content: '{"ok":true}',
},
],
tools: [
{
type: "function",
function: {
name: "read_file",
parameters: {
type: "object",
properties: { path: { type: "string" } },
required: ["path"],
},
},
},
],
},
false,
{ projectId: "proj-claude" } as any
);
assert.equal(result.project, "proj-claude");
assert.equal(result.userAgent, "antigravity");
assert.match(result.requestId, /^agent\/\d+\/[0-9a-f]{8}$/);
assert.deepEqual((result as any).enabledCreditTypes, ["GOOGLE_ONE_AI"]);
assert.equal(result.request.systemInstruction.parts[0].text, ANTIGRAVITY_DEFAULT_SYSTEM);
assert.equal(result.request.systemInstruction.parts[1].text, "Project rules");
assert.equal((result as any).request?.generationConfig.maxOutputTokens, undefined);
assert.equal((result as any).request?.messages, undefined);
assert.equal((result as any).request?.system, undefined);
assert.equal((result as any).request?.max_tokens, undefined);
assert.equal((result as any).request?.stream, undefined);
const modelTurn = result.request.contents.find(
(content) => content.role === "model" && content.parts.some((part) => part.functionCall)
);
assert.ok(modelTurn, "expected a Gemini-compatible model turn");
const bridgeFunctionCall = getFunctionCall(modelTurn.parts[0]);
assert.equal(bridgeFunctionCall.name, "read_file");
assert.deepEqual(bridgeFunctionCall.args, { path: "/tmp/demo" });
const toolTurn = result.request.contents.find(
(content) => content.role === "user" && content.parts.some((part) => part.functionResponse)
);
assert.ok(toolTurn, "expected a Gemini-compatible tool response turn");
const toolResultBlock = getFunctionResponse(toolTurn.parts[0]);
assert.equal(toolResultBlock.id, "call_1");
assert.equal((result as any).request?.tools[0].functionDeclarations[0].name, "read_file");
});
test("OpenAI -> Antigravity Claude path sanitizes tool names for Gemini schema", () => {
const longToolName =
"ns:mcp__filesystem__read_multiple_files_with_validation_and_metadata_bundle";
const result = openaiToAntigravityRequest(
"claude-3-7-sonnet",
{
messages: [
{ role: "user", content: "Read a file" },
{
role: "assistant",
tool_calls: [
{
id: "call_long_2",
type: "function",
function: { name: longToolName, arguments: '{"path":"/tmp/demo"}' },
},
],
},
{
role: "tool",
tool_call_id: "call_long_2",
content: '{"ok":true}',
},
],
tools: [
{
type: "function",
function: {
name: longToolName,
parameters: {
type: "object",
properties: { path: { type: "string", "x-ui": "hidden" } },
required: ["path"],
},
},
},
],
},
false,
{ projectId: "proj-claude-map" } as any
);
const sanitizedToolName = (result as any).request?.tools[0].functionDeclarations[0].name;
assert.notEqual(sanitizedToolName, longToolName);
assert.match(
sanitizedToolName,
/^mcp_filesystem_read_multiple_files_with_validation_and__\w{8}$/
);
const modelTurn = result.request.contents.find(
(content) => content.role === "model" && content.parts.some((part) => part.functionCall)
);
assert.ok(modelTurn, "expected a model turn");
const toolUseBlock = getFunctionCall(modelTurn.parts[0]);
assert.equal(toolUseBlock.name, sanitizedToolName);
const toolTurn = result.request.contents.find(
(content) => content.role === "user" && content.parts.some((part) => part.functionResponse)
);
assert.ok(toolTurn, "expected a tool response turn");
const toolResultBlock = getFunctionResponse(toolTurn.parts[0]);
assert.equal(toolResultBlock.id, "call_long_2");
assert.equal(toolResultBlock.name, sanitizedToolName);
assert.deepEqual(toolResultBlock.response, { result: { ok: true } });
});
test("OpenAI -> Antigravity Claude path applies output cap and strips thinkingConfig", () => {
// For Claude on Antigravity, applyAntigravityGenerationDefaults must bump
// maxOutputTokens to thinkingBudget+1 BEFORE the envelope strips thinkingConfig
// (because Claude on Cloud Code does not understand Gemini's thinkingConfig
// shape but still benefits from the larger output cap derived from it).
const result = openaiToAntigravityRequest(
"claude-3-7-sonnet",
{
messages: [{ role: "user", content: "Summarize this" }],
max_completion_tokens: 32000,
reasoning_effort: "high",
},
false,
{ projectId: "proj-claude-thinking" } as any
);
assert.equal((result as any).request?.generationConfig.maxOutputTokens, 32769);
// thinkingConfig must be stripped for Claude — Cloud Code Claude endpoint
// does not understand the Gemini-shape thinkingConfig field.
assert.equal((result as any).request?.generationConfig.thinkingConfig, undefined);
assert.equal((result as any).request?.max_tokens, undefined);
assert.equal((result as any).request?.thinking, undefined);
});
test("OpenAI -> Antigravity Claude path preserves lower requested output and strips thinkingConfig", () => {
const result = openaiToAntigravityRequest(
"claude-3-7-sonnet",
{
messages: [{ role: "user", content: "Short answer" }],
max_completion_tokens: 1000,
reasoning_effort: "high",
},
false,
{ projectId: "proj-claude-short" } as any
);
assert.equal((result as any).request?.generationConfig.maxOutputTokens, 32769);
assert.equal((result as any).request?.generationConfig.thinkingConfig, undefined);
assert.equal((result as any).request?.max_tokens, undefined);
assert.equal((result as any).request?.thinking, undefined);
});
test("OpenAI -> Antigravity Gemini path preserves thinkingConfig (only Claude is stripped)", () => {
// Negative-control for the Claude-thinkingConfig-strip behavior. Gemini models
// on Antigravity must still receive thinkingConfig — only Claude needs it removed
// (Cloud Code Claude endpoint does not understand the Gemini-shape field).
const result = openaiToAntigravityRequest(
"gemini-2.5-pro",
{
messages: [{ role: "user", content: "Summarize this" }],
max_completion_tokens: 32000,
reasoning_effort: "high",
},
false,
{ projectId: "proj-gemini-thinking" } as any
);
// For Gemini, thinkingConfig must remain in place because the Cloud Code
// Gemini endpoint understands and uses it.
assert.ok(
(result as any).request?.generationConfig.thinkingConfig,
"thinkingConfig must be preserved for Gemini models on Antigravity"
);
assert.equal((result as any).request?.generationConfig.thinkingConfig.thinkingBudget > 0, true);
assert.equal((result as any).request?.generationConfig.thinkingConfig.includeThoughts, true);
});
// Regression for #2480: when projectId is stored in providerSpecificData rather than at
// the top level of the credential record, the Antigravity Cloud Code envelope must still
// pick it up — otherwise the /v1beta path 422s with "Missing Google projectId".
test("openaiToAntigravityRequest falls back to providerSpecificData.projectId (#2480)", () => {
const result = openaiToAntigravityRequest(
"gemini-3.1-flash-lite",
{ messages: [{ role: "user", content: "Hello" }] },
false,
{ providerSpecificData: { projectId: "proj-from-psd" } } as any
);
assert.equal(result.project, "proj-from-psd");
});
test("openaiToAntigravityRequest prefers top-level projectId over providerSpecificData (#2480)", () => {
const result = openaiToAntigravityRequest(
"gemini-3.1-flash-lite",
{ messages: [{ role: "user", content: "Hello" }] },
false,
{ projectId: "proj-top", providerSpecificData: { projectId: "proj-psd" } } as any
);
assert.equal(result.project, "proj-top");
});
// Regression for #2515: a PDF sent in the Responses-API `input_file` shape must reach
// Gemini as inlineData instead of being silently dropped.
test("convertOpenAIContentToParts handles input_file file_data (#2515)", () => {
const parts = convertOpenAIContentToParts([
{ type: "input_file", file_data: "JVBERi0xLjcKJ", filename: "doc.pdf" },
]);
const inline = parts.find((p) => (p as any).inlineData);
assert.ok(inline, "input_file with file_data must produce an inlineData part");
assert.equal((inline as any).inlineData.data, "JVBERi0xLjcKJ");
});
test("convertOpenAIContentToParts handles input_file file_url data URI (#2515)", () => {
const parts = convertOpenAIContentToParts([
{ type: "input_file", file_url: "data:application/pdf;base64,QUJD", filename: "d.pdf" },
]);
const inline = parts.find((p) => (p as any).inlineData);
assert.ok(inline, "input_file with file_url data URI must produce an inlineData part");
assert.equal((inline as any).inlineData.data, "QUJD");
assert.equal((inline as any).inlineData.mimeType, "application/pdf");
});
test("convertOpenAIContentToParts handles rec.image with nested {url} as base64 data URI (#2807)", () => {
const parts = convertOpenAIContentToParts([
{ type: "text", text: "What's this?" },
{ type: "image", image: { url: "data:image/png;base64,iVBORw0KGgo=" } },
]);
const inline = parts.find((p) => (p as any).inlineData);
assert.ok(
inline,
"rec.image with nested {url} must produce an inlineData part (was previously silently dropped)"
);
assert.equal((inline as any).inlineData.data, "iVBORw0KGgo=");
assert.equal((inline as any).inlineData.mimeType, "image/png");
});
test("convertOpenAIContentToParts warns and drops remote http(s) URLs (#2807 - until async refactor)", () => {
const originalWarn = console.warn;
const warnings: string[] = [];
console.warn = (...args: unknown[]) => {
warnings.push(args.map(String).join(" "));
};
try {
const parts = convertOpenAIContentToParts([
{ type: "image_url", image_url: { url: "https://example.com/cat.png" } },
]);
const inline = parts.find((p) => (p as any).inlineData);
assert.equal(
inline,
undefined,
"remote URL still cannot be encoded into inlineData (sync function) - that's expected"
);
assert.ok(
warnings.some((w) => /Dropped remote image URL/i.test(w) && /example\.com\/cat\.png/.test(w)),
`expected a warning naming the dropped URL, got: ${JSON.stringify(warnings)}`
);
} finally {
console.warn = originalWarn;
}
});
test("convertOpenAIContentToParts warns and drops rec.image remote http(s) URLs (#2807)", () => {
// rec.image is the alternative content shape emitted by MCP tool wrappers and
// LangChain shim layers. Remote URLs in this shape must also hit the warn-and-drop
// branch rather than being silently ignored.
const originalWarn = console.warn;
const warnings: string[] = [];
console.warn = (...args: unknown[]) => {
warnings.push(args.map(String).join(" "));
};
try {
const parts = convertOpenAIContentToParts([
{ type: "image", image: { url: "https://example.com/remote.png" } },
]);
const inline = parts.find((p) => (p as any).inlineData);
assert.equal(
inline,
undefined,
"rec.image remote URL must not produce an inlineData part (sync function cannot fetch)"
);
assert.ok(
warnings.some(
(w) => /Dropped remote image URL/i.test(w) && /example\.com\/remote\.png/.test(w)
),
`expected a warning naming the dropped rec.image URL, got: ${JSON.stringify(warnings)}`
);
} finally {
console.warn = originalWarn;
}
});
// Regression for #2504: with credentials._signatureNamespace set, a previously-cached
// Gemini thoughtSignature must be re-attached to the functionCall on the follow-up turn.
test("openaiToGeminiRequest re-attaches cached thoughtSignature for FORMATS.GEMINI (#2504)", async () => {
const { buildGeminiThoughtSignatureKey, storeGeminiThoughtSignature } =
await import("../../open-sse/services/geminiThoughtSignatureStore.ts");
const ns = "conn-2504";
const toolId = "call_2504_abc";
storeGeminiThoughtSignature(buildGeminiThoughtSignatureKey(ns, toolId), "SIG_2504_XYZ");
const result: any = openaiToGeminiRequest(
"gemini-2.5-pro-preview",
{
messages: [
{ role: "user", content: "run a tool" },
{
role: "assistant",
tool_calls: [
{ id: toolId, type: "function", function: { name: "Bash", arguments: '{"cmd":"ls"}' } },
],
},
{ role: "tool", tool_call_id: toolId, content: "ok" },
],
},
false,
{ _signatureNamespace: ns }
);
const json = JSON.stringify(result);
assert.ok(
json.includes("SIG_2504_XYZ"),
"cached thoughtSignature must be re-attached to the functionCall"
);
});
test("OpenAI -> Gemini request maps reasoning_effort to thinkingConfig", () => {
const result = openaiToGeminiRequest(
"gemini-2.0-flash-thinking",
{
messages: [{ role: "user", content: "Solve this complex puzzle" }],
reasoning_effort: "high",
},
false
);
assert.ok((result as any).generationConfig.thinkingConfig, "expected thinkingConfig");
assert.equal((result as any).generationConfig.thinkingConfig.includeThoughts, true);
assert.equal((result as any).generationConfig.thinkingConfig.thinkingBudget, 32768);
});
test("OpenAI -> Gemini request maps google_search tool", () => {
const result = openaiToGeminiRequest(
"gemini-2.0-flash",
{
messages: [{ role: "user", content: "What happened today?" }],
tools: [{ type: "function", function: { name: "google_search" } }],
},
false
);
assert.ok(Array.isArray((result as any).tools), "expected tools array");
assert.ok(
(result as any).tools.some((t: any) => t.googleSearch),
"expected googleSearch tool"
);
});