Files
OmniRoute/tests/unit/image-generation-handler.test.ts
Diego Rodrigues de Sa e Souza a7ae9550bd Release v3.8.36 (#4854)
* chore(release): open v3.8.36 development cycle

* refactor(chatCore): extrai resolveCompressionSettings (#3501) (#4826)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 1/13)

* refactor(chatCore): extrai predicados puros de combo de compressão (#3501) (#4824)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 2/13)

* refactor(chatCore): extrai emitOutputStyleTelemetry (#3501) (#4811)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 3/13)

* refactor(chatCore): extrai writeCompressionAnalytics (bloco analytics completo, #3501) (#4817)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 4/13)

* refactor(chatCore): extrai runPluginOnRequestHook (#3501) (#4827)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 5/13)

* refactor(chatCore): extrai applyClientUsageBuffer (buffer/estimate de usage non-streaming, #3501) (#4832)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 6/13)

* refactor(chatCore): extrai buildPostCallGuardrailContext (contexto guardrail post-call, #3501) (#4831)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 7/13)

* refactor(chatCore): extrai storeSemanticCacheResponse (cache-store non-streaming, #3501) (#4828)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 8/13)

* refactor(chatCore): extrai buildNonStreamingResponseHeaders (headers de resposta non-streaming, #3501) (#4835)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 9/13)

* refactor(chatCore): extrai maybeConvertJsonBodyToSse (#3089 JSON→SSE streaming, #3501) (#4833)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 10/13)

* refactor(chatCore): extrai assembleStreamingResponseHeaders (headers de resposta streaming, #3501) (#4836)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 11/13)

* refactor(chatCore): extrai storeStreamingSemanticCacheResponse (cache-store streaming, #3501) (#4829)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 12/13)

* refactor(chatCore): extrai assembleStreamingPipeline (chain de transforms streaming, #3501) (#4837)

Integrated into release/v3.8.36 (#3501 chatCore extraction stack 13/13)

* ci(quality): shift heavy validations to the PR→release fast-path (release-acceleration) (#4857)

* feat(quality): add check:test-runner-api gate (vitest-only dirs must use vitest API)

* feat(release): reusable CHANGELOG i18n-mirror sync script

* chore(ops): add prune-stale-worktrees.sh (dry-run by default)

* ci(quality): run test-runner-api + docs-all + vitest + full unit suite on PR->release fast-path

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(quota): cota exclusiva lista qtSd/ no /v1/models (#4806) + limite EPSILON não bloqueia (#4830)

Integrated into release/v3.8.36 — quota-exclusive qtSd/ listing (#4806) + EPSILON placeholder no longer blocks; rebuilt from stale base (3 defining commits cherry-picked clean over release tip)

* feat(sse): add Google Flow video-generation provider (#4569) (#4769)

Integrated into release/v3.8.36 — Google Flow video-generation provider (#4569), release-green validated (typecheck + 21 tests + file-size)

* fix(api): auth on compression run-telemetry + document OMNIROUTE_EVAL_CREDENTIALS (#4694, #4720) (#4796)

Integrated into release/v3.8.36 — auth on compression run-telemetry + OMNIROUTE_EVAL_CREDENTIALS doc, release-green validated (typecheck + 3 tests + env-doc-sync)

* fix(translator): strip top-level client_metadata on the OpenAI passthrough (port from 9router#1157) (#4624)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(translator): normalize `developer` role to `system` for OpenAI-format providers (#4625)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(translator): emit </think> close marker for Anthropic thinking blocks (#4633)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(translator): normalize tools to Anthropic-native shape for non-Anthropic providers (#4650)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(gemini): preserve `pattern` in antigravity tool schema sanitizer (#4651)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(perplexity): validate API keys via /v1/models endpoint (#4654)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(image): prevent compatible nodes from shadowing provider aliases (#4656)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(cli-tools): tolerate JSONC (comments, trailing commas) in tool settings (#4659)

Integrated into release/v3.8.36 — port (rebuilt from stale base; defining commit cherry-picked clean over release tip, release-green validated)

* fix(security): validate kiro region to prevent SSRF (GHSA-6mwv-4mrm-5p3m) (#4629)

Integrated into release/v3.8.36 — kiro region SSRF guard (GHSA-6mwv-4mrm-5p3m), port rebuilt clean over release tip

* fix(cli): harden the systray2 tray runtime (port of 9router#1080) (#4628)

Integrated into release/v3.8.36 — port rebuilt clean over release tip, release-green validated

* fix(test): validate anthropic-compatible connections via POST /v1/messages (#4657)

Integrated into release/v3.8.36 — anthropic-compat validation via POST /v1/messages (port 584cf66a), rebuilt clean + baseline; release-green

* fix(executors): strip params unsupported by the target provider/model (#4658)

Integrated into release/v3.8.36 — port rebuilt clean over release tip, release-green validated

* fix(claude-oauth): respect 429 backoff on usage endpoint to reduce spam (#4655)

Integrated into release/v3.8.36 — port rebuilt clean over release tip, release-green validated

* feat(api/v1): include alias-backed models in /v1/models listing (#4630)

Integrated into release/v3.8.36 — port rebuilt clean over release tip, release-green validated

* chore(quality): rebaseline catalog.ts 1574->1577 (#4630 aliases sobre quota-exclusive da release) (#4879)

rebaseline

* feat(compression): Kiro/CodeWhisperer tool-result compression engine (#4635)

Integrated into release/v3.8.36 — port rebuilt clean, release-green

* fix(security): don't trust loopback socket as local when behind reverse proxy (#4632)

Integrated into release/v3.8.36 — port rebuilt clean, release-green

* fix(opencode): preserve DeepSeek reasoning content in streamed responses (#4631)

Integrated into release/v3.8.36 — DeepSeek reasoning_content injection (port #1099); release-green

* fix(copilot,antigravity): cap maxOutputTokens at 16384 to stop "Invalid Argument" 400 (#4636)

Integrated into release/v3.8.36 — cap maxOutputTokens 16384 antigravity (port #779); release-green

* fix(dashboard): show custom vision models in LLM selector (#4653)

Integrated into release/v3.8.36 — custom vision models in LLM selector (port 5e5e78d3); release-green

* fix(claude): omit adaptive thinking + output_config.effort for haiku (#4661)

Integrated into release/v3.8.36 — haiku adaptive-thinking omit (port); release-green

* feat(provider): CodeBuddy CN (copilot.tencent.com) — full stack (#4664)

Integrated into release/v3.8.36 — CodeBuddy CN provider (port efd20be8); usage.ts import + public-creds allowlist line reconciled; release-green

* feat(combo): Fusion strategy — parallel panel + judge synthesis (16th strategy) (#4652)

Integrated into release/v3.8.36 — Fusion combo strategy (16th, port 87e5c1c6); combo.ts baseline reconciled; release-green

* feat(proxy-pool): Deno Deploy relays + group action buttons (#4643)

Integrated into release/v3.8.36 — Deno Deploy relays (port #1437); proxies.ts baseline reconciled + env docs restored; release-green

* fix(security): pin image fetch DNS resolution to prevent SSRF rebinding (GHSA-cmhj-wh2f-9cgx) (#4634)

Integrated into release/v3.8.36 — pin DNS for image fetch SSRF rebinding guard (GHSA-cmhj-wh2f-9cgx, port c7d07448); caller DNS stubs + test-file baseline reconciled; release-green

* fix(github): route Copilot Codex models to /responses (port from 9router#102) (#4626)

Integrated into release/v3.8.36 — route Copilot Codex models to /responses (port #102); release-green

* fix(copilot): never route Gemini/Claude variants to /responses (chat-completions only) (#4627)

Integrated into release/v3.8.36 — never route Gemini/Claude to /responses (port #1536); fused with #4626 codex routing via supportsResponsesEndpoint gate; release-green

* docs(ops): add canonical incident response runbook (#4868)

Integrated into release/v3.8.36

* docs(perf): add per-endpoint p50/p95/p99 latency + cost budgets (#4867)

Integrated into release/v3.8.36

* fix(proxy): fan out direct dispatcher streams (#4803)

Integrated into release/v3.8.36

* fix(antigravity): exclude standard Gemini rate limit message from quota exhaustion keywords (#4810)

Integrated into release/v3.8.36

* fix(sse): skip third-party tool-name cloak for Anthropic server tools (#4808)

Integrated into release/v3.8.36

* fix(install): make transformers optional for CUDA-host installs (#4807)

Integrated into release/v3.8.36

* fix(combo): propagate selected connection ID to fallback error responses for correct model lockout (#4809)

Integrated into release/v3.8.36

* fix db storage tuning settings (#4834)

Integrated into release/v3.8.36

* fix(sse): drop ccp pin when pinned provider is durably unhealthy (failover + anti-flap) (#4864)

Integrated into release/v3.8.36

* fix(claude): skip mcp__ tool-name cloak + guard missing connectionId (#4861)

Integrated into release/v3.8.36

* chore(quality): reconcile env-doc + file-size base-reds in release/v3.8.36 (#4886)

- env-doc-sync: document PIN_DROP_BACKOFF_LEVEL / PIN_DROP_GRACE_MS (added by the
  ccp-pin health gate #4864) in .env.example + ENVIRONMENT.md.
- file-size: rebaseline image-generation-handler.test.ts 1996 -> 2019 to its actual
  size (pre-existing drift).

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(codex): drop non-standard codex.* events that break responses.stream (env-gated, #4602) (#4715)

Integrated into release/v3.8.36

* feat(routing): honor X-Route-Model header to override body.model (#4863)

Integrated into release/v3.8.36

* feat(live-ws): allow non-loopback clients via LIVE_WS_ALLOWED_HOSTS (closes #4873) (#4877)

Integrated into release/v3.8.36 (live-ws + combo-api commits; Tailscale CGNAT commit held pending opt-in/opt-out decision)

* chore(claude,codex): bump pinned CLI identity — Claude 2.1.158→2.1.187, Codex 0.132.0→0.142.0 (#4883)

Integrated into release/v3.8.36

* fix(security): SSRF allowlist bypass via x-relay-path nos relays Deno/Vercel (#4899)

Integrated into release/v3.8.36

* feat(quota): recuperação proativa de conexões em cooldown (cron heal) [Fase 3 #8] (#4900)

Integrated into release/v3.8.36

* fix(quota): policy inválida não vaza allow + guard connectionIds vazio [Fase 3 #10] (#4901)

Integrated into release/v3.8.36

* feat(quota): saturação real do Claude no fair-share via /api/oauth/usage (#4885)

Integrated into release/v3.8.36

* chore(dashboard): rename Qoder display label from "Qoder AI" to "Qoder" (#4733)

Integrated into release/v3.8.36

* fix(ci): include coverage/lcov.info in coverage-report artifact for SonarQube (#4670)

Integrated into release/v3.8.36

* fix(cli): bump better-sqlite3 runtime pin to 12.10.1 for Node 26 (#4685)

Integrated into release/v3.8.36

* docs: clarify Kiro is ~50 credits/month per account, not unlimited (#4690)

Integrated into release/v3.8.36

* docs(agentbridge): document Electron NODE_EXTRA_CA_CERTS, real model IDs, identity caveat (#4718)

Integrated into release/v3.8.36

* docs(ops): document the release-green family (green-prs, check:release-green, babysit, nightly) (#4679)

Integrated into release/v3.8.36

* fix(translator): replay reasoning_content on plain Xiaomi MiMo turns (port from 9router#1321) (#4639)

Integrated into release/v3.8.36

* feat(opencode-go): advertise glm-5.2 and kimi-k2.7-code (align with official Go endpoints) (#4711)

Integrated into release/v3.8.36

* feat(db): track API endpoint dimension on usage_history (#4676)

Integrated into release/v3.8.36 (migration renumbered 103→105; endpoint plumbed through extracted usage-stats helpers)

* fix(cli): SIGKILL systray child PID before IPC close to avoid macOS NSStatusItem orphan (#4732)

Integrated into release/v3.8.36

* feat(proxy-pool): Cloudflare Workers proxy deployer + pool integration (#4640)

Integrated into release/v3.8.36 (relay type added to RELAY_TYPES set; dropdown UX preserved + Cloudflare item added; proxies.ts file-size rebaselined 1057→1060)

* chore(quality): conserta base-red de release/v3.8.36 (gates + 7 testes + build MDX) (#4915)

A base tinha base-red sistêmica herdada de PRs de outras sessões, bloqueando
TODOS os PRs do ciclo (o TIA roda a suíte full em fail-safe p/ diffs hub).

4 Fast Quality Gates:
- test-discovery (#4877): live-server-allowlist.test.ts em tests/unit/server/
  (não-coletado) + vitest → nunca rodava. Convertido p/ node:test em tests/unit/security/.
- any-budget:t11 (#4664): 3 explicit-any em tokenRefresh.ts tipados (sem crescer file-size).
- docs-symbols (#4868): rotas inexistentes → /api/system/version e
  PUT /api/providers/{id} {isActive:false}.
- docs-all fabricated-claim (#4868 + #4718): 5 bin/*.sh reais criados (rollback,
  snapshot-data, restore-data, restore-policies, cold-start-bench) + _ops-common.sh
  (snapshot VACUUM INTO, guards de confirmação/TTY, testes de contrato); NODE_EXTRA_CA_CERTS
  (env de runtime Node) na allowlist do checker.

7 testes unit base-red (de features alheias à quota):
- oauth-providers-config (#4664): teste alinhado ao provider codebuddy-cn do registry.
- antigravity-model-aliases (#4636): maxOutputTokens esperado 32769→16384 (cap intencional).
- provider-request-capture #4091 (#4861): exemplo do teste trocado de mcp__ (que #4861
  isenta de cloak por causa dos 400s de assimetria de histórico) para um tool de terceiro
  cloakável — preserva o invariante de #4091 SEM reverter #4861.
- combo-error-response: convertido de vitest p/ node:test (era coletado pelo glob node:test
  e crashava); api/** e server/** removidos do vitest.config (config morta).

Build MDX (dast-smoke, #4679):
- docs/ops/RELEASE_GREEN.md não tinha frontmatter `title` → fumadocs-mdx rejeitava no
  webpack compile ("invalid frontmatter: title expected string"), quebrando o next build
  (e o deploy). Frontmatter title adicionado (único doc do collection sem ele).

17/17 Fast Quality Gates + suíte unit completa (17737 testes, 0 fail) + vitest verdes localmente.

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(quota): saturação proativa por headers de tokens (universal) [Fase 3 #2] (#4907)

storeRateLimitHeaders só capturava os headers de REQUESTS (RPM/min), que não
refletem a pressão de TOKENS. Agora também parseia os headers de tokens (em toda
resposta, sucesso também) para throttle proativo antes do 429:
- Anthropic: anthropic-ratelimit-tokens-{limit,remaining,reset} (+ input/output), RFC3339.
- OpenAI: x-ratelimit-{limit,remaining,reset}-tokens, reset em duração (6m0s).

saturation = 1 − remaining/limit; resetAt normalizado a epoch (parse de duração
ReDoS-safe). getTokenHeaderSaturation por (provider, connectionId). fetchGeneric-
Saturation passa a usar esse sinal (complementa o oauth/usage do #1, que segue
primário p/ Claude). Fail-open, cache mantido, request-path inalterado.

16 testes novos + regressão (oauth/usage #1 8/8, signals 6/6) = 30/30;
typecheck:core + eslint limpos.

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(quota): estratégia de combo "headroom" — seleção por folga de cota [Fase 3 #4] (#4908)

Nova estratégia de roteamento que escolhe a conexão com MAIS folga de plano:
headroom = 1 − max(util_5h, util_7d) (técnica do dario), via getSaturation
(melhorado p/ Claude no #1). Proativo em vez de só fill-first reativo.

- Helper PURO headroomRanking.ts (computeHeadroom + rankByHeadroom; saturação
  injetada, não-mutante, tie-break estável, fail-open).
- Orderer async em combo/quotaStrategies.ts (reusa a maquinaria reset-aware de
  expansão de conexões + concorrência limitada; seam injetável).
- Registrada como "headroom" em routingStrategies (combo-only); fill-first segue
  default — nenhuma estratégia existente tocada.
- baseline file-size combo.ts 3168->3180 (só +12L de dispatch; lógica fora do god-file).

16 testes novos + combo-strategies 15/15 = 31/31; typecheck:core + eslint +
file-size limpos.

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(quota): cap per-(key,model) — quota_allocation_model_caps [Fase 3 #7] (#4927)

* feat(quota): cap per-(key,model) com tabela quota_allocation_model_caps [Fase 3 #7]

Fecha o buraco onde uma API key pode drenar o pool inteiro consumindo um único modelo.

Tabela nova: quota_allocation_model_caps(pool_id, api_key_id, model, cap_value, cap_unit)
PK composta (pool_id, api_key_id, model). cap_unit alinhado ao QuotaUnit existente.

Comportamento: keyA acima do cap para modelo M → bloqueada somente em M; ainda
permitida em qualquer outro modelo no mesmo pool. Cap <= EPSILON → ignorado (seed).

Consumo por-(key,model) usa bucket segregado no quota_consumption existente
(poolId mangled ':model:<model>') com window fixa 'hourly'; nenhuma nova tabela
ou método de store necessário.

Módulo novo: src/lib/db/quotaModelCaps.ts (getModelCap/setModelCap/deleteModelCap/listModelCaps)
enforce.ts ganha o pre-check em enforceQuotaShare + recording em recordConsumption.
EnforceInput e RecordConsumptionInput ganham model?: string (backward-compatible).
localDb.ts re-exporta os 4 helpers (Hard Rule #2).

TDD: tests/unit/quota-per-key-model.test.ts — 4 cenários (bloqueia em M, permite em M2,
sem cap → sem bloqueio, EPSILON → ignorado). Todos os gates de qualidade passam.

* feat(quota): plumba model resolvido no hot path para ativar o per-(key,model) cap [Fase 3 #7]

A tabela/enforce do commit anterior estavam INERTES: o hot path não passava `model`
ao enforce nem ao record, então nenhum model-cap disparava em produção.

Plumbagem (model resolvido = mesma var usada no log/roteamento, pós background-redirect/alias):
- chatCore.ts: enforceQuotaShare ganha `model`; scheduleQuotaShareConsumption recebe `model`.
- chatCore/quotaShareConsumption.ts: threade `model` no RecordConsumptionInput (non-streaming).
- spendRecorder.ts: recordStreamingConsumption já recebia `model` — agora o coloca no
  RecordConsumptionInput (streaming accrue por-modelo).
- embeddings.ts: enforce + record ganham `model`.

Namespace do cap = id do modelo RESOLVIDO (o mesmo de modelForScope/pendingScope/getUnsupportedParams),
não o requestedModel cru nem o finalModelToUpstream (sem prefixo de provider). Operador configura
o cap contra esse id. `model || undefined` em todos os pontos: vazio/null → check pulado (fail-safe,
zero latência — só um campo no objeto).

Teste de integração novo (tests/unit/quota-per-key-model-hotpath.test.ts): prova end-to-end que
N consumos via scheduleQuotaShareConsumption({model}) → enforceQuotaShare({model}) bloqueia, e que
outro modelo no mesmo pool ainda passa; + guard de que enforce SEM model nunca dispara model-cap.

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(quota): session stickiness p/ integridade de prompt-cache [Fase 3 #5] (#4929)

* feat(quota): session stickiness p/ integridade de prompt-cache [Fase 3 #5]

Adiciona stickiness de sessão ao roteamento de combo: uma conversa multi-turno
é roteada para a MESMA conexão enquanto ela permanecer saudável, evitando a
perda do prompt-cache do provider (custo 5-10× sem stickiness, efeito conhecido
no dario/clewdr).

Implementação:
- `open-sse/services/combo/sessionStickiness.ts` (novo, <800 linhas):
  mapa em memória (messageHash → connectionId) com TTL 15 min + cap 500 entradas;
  `applySessionStickiness` promove a conexão sticky ao índice 0 dos targets
  ordenados pelo strategy, guardado por `computeHeadroom > 0.15` (threshold);
  quando saturada (headroom ≤ 0.15), o binding é limpo e a seleção normal reage.
  Hash da sessão = SHA-256 dos primeiros chars da 1ª mensagem user → 16 hex chars.
  Seam de teste: `__setStickinessHeadroomFetcherForTests`.
- `open-sse/services/combo.ts`: import + 2 pontos de integração (pré-eval-scores
  e pós-success), dentro do orçamento congelado de 3180 linhas.
- `tests/unit/combo-session-stickiness.test.ts`: 19 testes node:test + assert/strict,
  todos via injeção de fetcher (zero rede/DB).

Threshold 0.15: conexão a >85% de utilização está a um burst de rate-limit;
o benefício de cache não compensa manter-se numa conexão degradada. Valor
alinhado com a zona de soft-penalty do restante do engine de quota-share.

* test(combo): isola combo-strategies da session stickiness (#5)

selectedConnectionFor reusa o mesmo body, então o sticky map (#5) fixava a
connection após a 1ª chamada e quebrava o round-robin tie-break do teste
reset-aware. Limpa o sticky map no início da helper — a stickiness tem suíte
própria (combo-session-stickiness). Sem enfraquecer asserts.

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(quota): buckets multi-janela por conexão (5h/7d/per-model) [Fase 3 #3] (#4928)

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* refactor(providers): decompõe catálogo providers.ts em módulos de dados (godfile sweep, #3501) (#4917)

Integrado em release/v3.8.36 (godfile sweep providers.ts, #3501)

* refactor(pricing): decompõe pricing.ts em shared-tiers + DEFAULT_PRICING particionado (godfile sweep, #3501) (#4918)

Integrado em release/v3.8.36 (godfile sweep pricing.ts, #3501)

* refactor(api): extrai camada-folha pura de validation.ts (URL/headers/transport) (#4921)

Integrado em release/v3.8.36 (validation.ts split fatia 1 — leaf layer)

* refactor(api): extrai validators web-cookie + Meta AI de validation.ts (#4922)

Integrado em release/v3.8.36 (validation.ts split fatia 2 — web-cookie + Meta AI)

* refactor(api): extrai validators enterprise-cloud + probe compartilhado de validation.ts (#4923)

Integrado em release/v3.8.36 (validation.ts split fatia 3 — enterprise-cloud + probe)

* refactor(api): extrai validators áudio/speech + misc apikey de validation.ts (#4930)

Integrado em release/v3.8.36 (validation.ts split fatia 4 — áudio/speech + misc apikey)

* feat(quota): estratégia dedicada de quota-share (DRR + P2C in-flight + gating per-model) [Fase 3 #9] (#4939)

* feat(quota): estratégia dedicada de quota-share (DRR + P2C in-flight + gating per-model) [Fase 3 #9]

Estratégia interna "quota-share" isolada num módulo dedicado — NÃO toca a seleção/
fair-share genérica (decisão do dono: não mexer no que já funciona). Os combos qtSd/
(quotaCombos.ts) passam de fill-first para essa strategy; combo.ts ganha só 1 branch
de dispatch que delega 100% ao módulo (nenhum case existente alterado).

- quotaShareStrategy.ts: gating per-model (isBucketSaturated do #3) + DRR (quantum
  proporcional ao weight) + P2C sobre carga in-flight.
- quotaShareInflight.ts: contador in-flight com TTL/lease de 120s — fallback do
  decrement-on-abort sem precisar instrumentar o combo genérico.
- "quota-share" registrada como strategy INTERNA (não exposta na UI).
- testes de síntese (quota-combo-balancing, quota-multiprovider) alinhados: a strategy
  esperada dos combos qtSd/ passa de "fill-first" para "quota-share" (alinhamento ao novo
  comportamento intencional, não mascaramento — os 73 testes de qtSd/ seguem verdes).

* test(quota-share): alinha 2 scope-guards ao godfile sweep (base-reds que bloqueavam o CI)

Dois testes de "arquivo contém X" quebraram por decomposições de godfile que outras
sessões mergearam no release DURANTE a validação de #9 — NÃO são regressão de #9
(que não toca validation/oauth). Alinhados ao novo layout, asserts preservados:
- proxy-bypass-scope-guard #3226: bypassProxyPatch foi extraído de validation.ts para
  validation/headers.ts (split #4921–#4930) → o teste lê a camada de validação.
- sse-error-passthrough #3324: a windsurf authHint foi extraída de providers.ts para
  providers/oauth.ts → o teste lê o novo local.

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* refactor(api): extrai validators search + embedding/rerank de validation.ts (#4932)

Integrated into release/v3.8.36

* refactor(api): extrai format-validators (OpenAI/Anthropic) de validation.ts (#4933)

Integrated into release/v3.8.36

* refactor(db): extrai model-permission matching de db/apiKeys.ts (#4936)

Integrated into release/v3.8.36

* refactor(db): extrai row-parsers + tipos compartilhados de db/apiKeys.ts (#4943)

Integrated into release/v3.8.36

* refactor(db): extrai column-mapping (snake↔camel) de db/core.ts (#4947)

Integrated into release/v3.8.36

* refactor(db): extrai schema-column reconciliation de db/core.ts (#4948)

Integrated into release/v3.8.36

* refactor(sse): extrai scalar/format helpers de services/usage.ts (#4949)

Integrated into release/v3.8.36

* refactor(sse): extrai quota-core (UsageQuota + builders) de services/usage.ts (#4950)

Integrated into release/v3.8.36

* fix(translator): regroup parallel tool results adjacent to their assistant (#4714) (#4882)

Integrated into release/v3.8.36 (fixes #4714)

* fix(qoder): exchange PAT for jt-* job token before Cosy chat (#4683) (#4884)

Integrated into release/v3.8.36 (fixes #4683)

* refactor(sse): dedup fallback tool_call id helper (#4736)

Integrated into release/v3.8.36

* refactor(open-sse): extract safeParseJSON util, dedup tryParseJSON (#4735)

Integrated into release/v3.8.36

* fix(compression): eliminate ReDoS in math_inline preservation pattern (#4795) (#4838)

Integrated into release/v3.8.36 (fixes #4795)

* fix(combo): fetch models dynamically from custom provider endpoints (#4860)

Integrated into release/v3.8.36

* feat(providers): update volcengine-ark model list with DeepSeek V4 (#4905)

Integrated into release/v3.8.36

* fix(translator): provider thinking compatibility (DeepSeek/Gemini) (#4946)

Integrated into release/v3.8.36

* feat(combo): task-aware routing strategy (#4945)

Integrated into release/v3.8.36

* refactor(sse): extrai a família MiniMax de services/usage.ts (#4952)

Integrated into release/v3.8.36

* refactor(sse): extrai a família GLM de services/usage.ts (#4953)

Integrated into release/v3.8.36

* refactor(sse): extrai a família Antigravity de services/usage.ts (#4956)

Integrated into release/v3.8.36

* fix(dashboard): show custom provider given-name instead of internal id across dashboard pages (#4603) (#4960)

Integrated into release/v3.8.36 (fixes #4603)

* fix(api): evict stale in-memory rate-limit windows to stop slow heap leak (#4041) (#4957)

Integrated into release/v3.8.36 (fixes #4041)

* fix(api): parse /v1/responses body once instead of 3-4x on the hot path (#4041) (#4958)

Integrated into release/v3.8.36 (fixes #4041)

* fix(translator): preserve legitimate empty-string tool arguments in openai-to-claude streaming (#4951) (#4959)

Integrated into release/v3.8.36 (fixes #4951)

* chore(quality): reconcile file-size baseline for #4960 provider-display-name (#4961)

Integrated into release/v3.8.36

* fix(dashboard): restore home provider-topology card hidden by #4596 default (#4963)

Integrated into release/v3.8.36 — restores home topology card (#4596 regression)

* fix(build): drop @omniroute/open-sse from optimizePackageImports (build OOM) (#4968)

Integrated into release/v3.8.36 — fixes build OOM (optimizePackageImports open-sse)

* fix(quota): migração 107 ativa estratégia quota-share nos combos qtSd/ existentes [Fase 3 #9] (#4962)

Integrated into release/v3.8.36

* feat(quota): respeita max_concurrent por conexão no roteamento (#4965)

Integrated into release/v3.8.36

* feat(quota): combo quota-share espera cooldown curto e re-despacha (Variante A) (#4967)

Integrated into release/v3.8.36

* fix(quality): resolve base-reds da release — db-rules allowlist + task-aware router precedence (#4973)

Dois base-reds pré-existentes que reprovavam o CI da release v3.8.36 (Fast
Quality Gates + Unit Tests fast-path), independentes de qualquer feature em voo:

1. check:db-rules / allowlist: os módulos db-internal caseMapping (#4947) e
   schemaColumns (#4948), extraídos de db/core.ts e importados só por ele, não
   estavam em INTENTIONALLY_INTERNAL. Registrados na allowlist (correção
   canônica — são internos legítimos, não re-exportados pelo localDb).

2. auto-strategy honra LKGP/cost (combo-routing-engine.test.ts, 2 testes): o
   task-aware reordering (#4945, reorderByTaskWeight) roda para strategy "auto" e
   era aplicado DEPOIS do router explícito (selectWithStrategy: lkgp/cost),
   sobrescrevendo o orderedTargets[0] que o operador escolheu. Instrumentação
   provou: post-filter [0]=claude (LKGP) → post-task [0]=gpt-oss. Correção: quando
   o auto usa router explícito, preserva o [0] dele e deixa o task-aware refinar
   só a cauda de fallback. gpt-oss-120b PERMANECE tool-capable (não é mudança de
   catálogo; o model-capabilities-registry test segue verde).

Validado: 121 testes (combo-routing-engine + combo-task-aware + registry) verdes,
red-check confirmado, db-rules/file-size/typecheck/lint/prettier OK.

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(quota): serializa concorrência por conexão no caminho quota-share (FASE 2.1) (#4970)

O gating de quota-share em selectQuotaShareTarget é fail-open: uma conexão
at-cap só é despriorizada, nunca bloqueada. Com 1 conexão por conta de
assinatura (caso comum), chamadas concorrentes ainda floodam a conta (→ 429 +
cooldown) — provado live na .15: 3 chamadas concorrentes com max_concurrent=1
despacharam todas em 94ms.

Adiciona um semáforo POR CONEXÃO em torno do dispatch quota-share: chamadas
excedentes esperam na fila em vez de floodar (key qsconn:<connectionId>, cap =
max_concurrent da conexão). Fail-open em fila saturada/timeout para nunca
piorar disponibilidade. Gated por strategy===quota-share + kill-switch
resilienceSettings.quotaShareConcurrencyLimit (default on; UI no ResilienceTab).

Lógica extraível isolada no leaf puro combo/quotaShareConcurrency.ts
(unit-testado: estabilidade da key, no-op sem cap, serialização real,
fail-open). Settings + schema + UI espelham comboCooldownWait.

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* docs(resilience): document Quota-Share Concurrency Control (max_concurrent + serialization + cooldown-wait) (#4980)

Documents the v3.8.36 quota-share concurrency layers in RESILIENCE_GUIDE.md:
per-connection max_concurrent cap, the quota-share request serialization semaphore
(FASE 2.1, qsconn:<connectionId>, fail-open, kill-switch), and the combo
cooldown-aware retry — so operators know how to cap a subscription account's
concurrency and why the routing gate alone cannot contain a single-connection flood.

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(dashboard): proxy-pool success gating, sync timestamp, opt-in Redis (#4878) (#4988)

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(sse): fail over on 400 responses carrying rate-limit text (#4976) (#4986)

* fix(sse): fail over on 400 responses carrying rate-limit text (#4976)

* chore(quality): rebaseline accountFallback.ts file-size for #4976 fix

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(compression): stop RTK over-truncating file-read tool results (#4559) (#4987)

* fix(compression): stop RTK over-truncating file-read tool results (#4559)

* chore(quality): trim #4559 comment to keep rtk/index.ts within size cap

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(sse): honor per-account proxies and fingerprint rotation in opencode executor (#4954) (#4989)

* fix(sse): honor per-account proxies and fingerprint rotation in opencode executor (#4954)

* chore(quality): rebaseline auth.ts file-size for #4954 (+39: synthetic no-auth providerSpecificData hydration of fingerprints/accountProxies; irreducible credential-path wiring, covered by opencode-proxy-rotation-4954.test.ts + 159 auth/noauth regression)

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(sse): soft-penalize exhausted providers in auto-combo scoring (#4540) (#4990)

* fix(sse): soft-penalize exhausted providers in auto-combo scoring (#4540)

* chore(quality): document STATUS_SOFT_DEPRIORITIZE_FACTOR + rebaseline combo.ts for #4540

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(dashboard): switch to visible filter after auto-hiding failed models in test-all (#4887) (#4991)

* fix(dashboard): switch to visible filter after auto-hiding failed models in OAuth provider test-all (#4887)

* test(dashboard): move #4887 test into tests/unit/ui so a CI runner collects it

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(pollinations): only enable jsonMode when JSON output is requested (#3981) (#5009)

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(antigravity): default safetySettings to all-OFF for parity with native Gemini paths (#5003) (#5008)

* fix(antigravity): default safetySettings to all-OFF for parity with native Gemini paths (#5003)

* docs(changelog): restore #3981 pollinations entry eaten by merge

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* fix(chatgpt-web): map advertised gpt-5.5/5.4-pro/5.2-pro slugs to prevent silent model substitution (#4665) (#5010)

* fix(chatgpt-web): map advertised gpt-5.5/5.4-pro/5.2-pro slugs to prevent silent model substitution (#4665)

MODEL_MAP was missing the advertised catalog ids gpt-5.5, gpt-5.5-pro,
gpt-5.4-pro and gpt-5.2-pro, so MODEL_MAP[model] ?? model sent the dot-form
id verbatim to the ChatGPT backend-api, which silently rejected it and served
the default Plus model. Map each to its dash-form slug. gpt-4-5 is already
dash-form and falls through correctly, so it is intentionally left unmapped.

Extends the executor MODEL_MAP test with the four ids and adds a drift guard
asserting every advertised dot-form catalog id reaches the backend in dash-form
(never verbatim), guarding future catalog<->map drift.

file-size: tests/unit/chatgpt-web.test.ts frozen baseline 2809->2855 (+46) for
the added test cases and drift-guard test; executor source unchanged in baseline.

* docs(changelog): restore #3981/#5003 entries eaten by merge

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* feat(combos): add editable per-combo description field persisted via /api/combos (#5005) (#5011)

* feat(combos): add editable per-combo description field persisted via /api/combos (#5005)

* docs(changelog): restore #3981/#5003/#4665 entries eaten by merge

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>

* Fix Ollama Cloud max reasoning effort (#4993)

Integrated into release/v3.8.36

* fix(copilot): replace execSync with execFile to prevent command injection (#5024)

Integrated into release/v3.8.36

* fix(plugin): auth.json dual-key fallback for auto-prefix migration (#5027)

Integrated into release/v3.8.36

* feat(endpoint): per-endpoint custom system prompt injection (#5022)

Integrated into release/v3.8.36

* fix(headroom): translate openai-responses input through OpenAI for compression (#5023)

Integrated into release/v3.8.36

* docs(changelog): add entries for #4993, #5024, #5027 (release notes credit)

* fix(api): stop /api/system/env/repair 500 on packaged install (#5006) (#5028)

* fix(api): stop /api/system/env/repair 500 on packaged install — lazy createRequire in sync-env.mjs (#5006)

scripts/dev/sync-env.mjs ran createRequire(import.meta.url) at module
top-level. When webpack bundles it into the standalone env-repair route,
import.meta.url is frozen to the build-machine path (file:///home/runner/...)
and createRequire throws during module evaluation, so the whole route
module fails to load and every GET returns HTTP 500 — breaking the
onboarding wizard on packaged/global installs.

- Move createRequire into the guarded better-sqlite3 block (only place
  that needs it); a bad import.meta.url now returns the safe default.
- resolveRootDir() falls back to process.cwd() when fileURLToPath throws.
- route.ts passes an explicit rootDir (process.cwd()) so the helper never
  derives the root from the frozen import.meta.url, matching the .env
  target used by createEnvBackup().
- Regression guard: assert sync-env.mjs has no top-level createRequire +
  getEnvSyncPlan(oauth) works with explicit rootDir without throwing.

* docs(changelog): restore #4993/#5023/#5024/#5027 + custom-system-prompt/headroom entries eaten by release merge

* chore(quality): rebaseline 3 inherited base-reds from release merge

Files NOT touched by this PR — grew on release/v3.8.36 via --admin merges and
inherited here through 'git merge origin/release':
- open-sse/executors/base.ts 1414->1416 (#4993 Ollama Cloud max-effort)
- src/lib/db/settings.ts 1149->1151 (#5023 custom system prompt)
- src/app/(dashboard)/.../endpoint/EndpointPageClient.tsx 2570->2612 (custom system prompt UI)

* chore(release): finalize v3.8.36 CHANGELOG + docs (2026-06-25)

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <souzamiriamrodrigues790@gmail.com>
Co-authored-by: KooshaPari <42529354+KooshaPari@users.noreply.github.com>
Co-authored-by: Makcim Ivanov <makcimbx@gmail.com>
Co-authored-by: Chewji <126886556+Chewji9875@users.noreply.github.com>
Co-authored-by: Anton <39598727+NomenAK@users.noreply.github.com>
Co-authored-by: Demiurge The Single <megamen932@gmail.com>
Co-authored-by: Randi <55005611+rdself@users.noreply.github.com>
Co-authored-by: Éder Costa <eder.almeida.costa@gmail.com>
Co-authored-by: Jefferson Felizardo <jeffer1312@gmail.com>
Co-authored-by: Arthur Bodera <abodera@gmail.com>
Co-authored-by: Hamsa_M <116961508+hamsa0x7@users.noreply.github.com>
Co-authored-by: Hernan Javier Ardila Sanchez <hjasgr@gmail.com>
2026-06-25 13:17:40 -03:00

2019 lines
60 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import dns from "node:dns";
import { mkdtempSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
process.env.DATA_DIR = mkdtempSync(join(tmpdir(), "omniroute-images-"));
// Stub DNS for fetchRemoteImage's GHSA-cmhj-wh2f-9cgx DNS-rebinding guard
// (assertHostnameResolvesPublic in src/shared/network/remoteImageFetch.ts).
// Several image-handler tests (Fal AI URL->b64 normalization, BFL polling
// with base64 input images, NanoBanana polling with URL->b64 conversion)
// mock globalThis.fetch with example.com URLs that don't resolve in CI; the
// handler invokes fetchRemoteImage without exposing a `lookup` injection
// point, so we monkey-patch dns.promises.lookup to always return a public IP
// so the rebinding guard passes and the test exercises the mocked fetch
// behaviour as intended. Node --test runs each file in its own process, so
// this rebinding does not leak across files.
const originalDnsLookup = dns.promises.lookup;
(dns.promises as { lookup: unknown }).lookup = (async (
_hostname: string,
options?: { all?: boolean }
) => {
const record = { address: "203.0.113.1", family: 4 };
return options && options.all ? [record] : record;
}) as typeof dns.promises.lookup;
process.on("exit", () => {
(dns.promises as { lookup: unknown }).lookup = originalDnsLookup;
});
const { IMAGE_PROVIDERS, parseImageModel, getAllImageModels } =
await import("../../open-sse/config/imageRegistry.ts");
const { handleImageGeneration } = await import("../../open-sse/handlers/imageGeneration.ts");
function immediateTimeout(callback, _ms, ...args) {
if (typeof callback === "function") callback(...args);
return 0;
}
function createLogRecorder() {
const entries = [];
return {
entries,
info(tag, message) {
entries.push({ level: "info", tag, message });
},
error(tag, message) {
entries.push({ level: "error", tag, message });
},
warn(tag, message) {
entries.push({ level: "warn", tag, message });
},
};
}
test("handleImageGeneration routes OpenAI-compatible providers and forwards image options", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
return new Response(
JSON.stringify({
created: 123,
data: [{ url: "https://cdn.example.com/image.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "openai/gpt-image-2",
prompt: "city skyline",
n: 2,
size: "1024x1536",
quality: "hd",
response_format: "url",
style: "vivid",
},
credentials: { apiKey: "image-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://api.openai.com/v1/images/generations");
assert.equal(captured.headers.Authorization, "Bearer image-key");
assert.deepEqual(captured.body, {
model: "gpt-image-2",
prompt: "city skyline",
n: 2,
size: "1024x1536",
quality: "hd",
response_format: "url",
style: "vivid",
});
assert.equal(result.data.data[0].url, "https://cdn.example.com/image.png");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration uses synthetic OpenAI-compatible routing for resolved custom providers", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
body: JSON.parse(String(options.body || "{}")),
headers: options.headers,
};
return new Response(JSON.stringify({ data: [{ b64_json: "ZmFrZQ==" }] }), {
status: 200,
headers: { "content-type": "application/json" },
});
};
try {
const result = await handleImageGeneration({
body: {
model: "custom-provider/super-image",
prompt: "retro poster",
},
credentials: {
apiKey: "custom-key",
baseUrl: "https://custom.example.com/v1/images/generations",
},
resolvedProvider: "custom-provider",
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://custom.example.com/v1/images/generations");
assert.equal(captured.headers.Authorization, "Bearer custom-key");
assert.deepEqual(captured.body, {
model: "super-image",
prompt: "retro poster",
});
assert.equal(result.data.data[0].b64_json, "ZmFrZQ==");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration polls KIE image tasks and returns URLs on success", async () => {
const originalFetch = globalThis.fetch;
let createPayload;
let pollUrl = "";
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "https://api.kie.ai/api/v1/gpt4o-image/generate") {
createPayload = JSON.parse(String(options.body || "{}"));
return new Response(JSON.stringify({ code: 200, data: { taskId: "kie-task-1" } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (stringUrl.startsWith("https://api.kie.ai/api/v1/gpt4o-image/record-info")) {
pollUrl = stringUrl;
return new Response(
JSON.stringify({
code: 200,
data: {
status: "SUCCESS",
response: {
resultUrls: ["https://example.com/kie-image.png"],
},
},
}),
{
status: 200,
headers: { "content-type": "application/json" },
}
);
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "kie/gpt4o-image",
prompt: "city skyline at dusk",
size: "1:1",
n: 1,
},
credentials: { apiKey: "kie-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(createPayload.prompt, "city skyline at dusk");
assert.equal(createPayload.size, "1:1");
assert.equal(createPayload.nVariants, 1);
assert.match(pollUrl, /taskId=kie-task-1/);
assert.equal(result.data.data[0].url, "https://example.com/kie-image.png");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration maps Hyperbolic size parameters and normalizes base64 images", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (_url, options = {}) => {
captured = JSON.parse(String(options.body || "{}"));
return new Response(
JSON.stringify({
images: [{ image: "aW1hZ2UtMQ==" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "hyperbolic/FLUX.1-dev",
prompt: "futuristic tower",
size: "512x1024",
},
credentials: { apiKey: "hyper-key" },
log: null,
});
assert.deepEqual(captured, {
model_name: "FLUX.1-dev",
prompt: "futuristic tower",
height: 1024,
width: 512,
backend: "auto",
});
assert.equal(result.success, true);
assert.equal(result.data.data[0].b64_json, "aW1hZ2UtMQ==");
assert.equal(result.data.data[0].revised_prompt, "futuristic tower");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration maps SD WebUI payload shape and batch size", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (_url, options = {}) => {
captured = JSON.parse(String(options.body || "{}"));
return new Response(
JSON.stringify({
images: ["YmFzZTY0LWltYWdl"],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "sdwebui/sdxl-base-1.0",
prompt: "forest cabin",
negative_prompt: "low quality",
size: "768x768",
steps: 30,
cfg_scale: 9,
sampler: "DPM++",
n: 3,
},
credentials: null,
log: null,
});
assert.equal(result.success, true);
assert.deepEqual(captured, {
prompt: "forest cabin",
negative_prompt: "low quality",
width: 768,
height: 768,
steps: 30,
cfg_scale: 9,
sampler_name: "DPM++",
batch_size: 3,
override_settings: {
sd_model_checkpoint: "sdxl-base-1.0",
},
});
assert.equal(result.data.data[0].b64_json, "YmFzZTY0LWltYWdl");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration rejects invalid model strings", async () => {
const result = await handleImageGeneration({
body: {
model: "not-a-provider-qualified-image-model",
prompt: "oops",
},
credentials: { apiKey: "x" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 400);
assert.match(result.error, /Invalid image model/);
});
test("handleImageGeneration treats unknown provider prefixes as invalid image models", async () => {
const result = await handleImageGeneration({
body: {
model: "mystery/model-1",
prompt: "oops",
},
credentials: { apiKey: "x" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 400);
assert.match(result.error, /Invalid image model: mystery\/model-1/);
});
test("image registry resolves flux aliases and exposes planned catalog aliases", () => {
assert.deepEqual(parseImageModel("flux-kontext"), {
provider: "black-forest-labs",
model: "flux-kontext-pro",
});
assert.deepEqual(parseImageModel("pollinations/kontext"), {
provider: "black-forest-labs",
model: "flux-kontext-pro",
});
assert.deepEqual(parseImageModel("flux-2-dev"), {
provider: "together",
model: "black-forest-labs/FLUX.2-dev",
});
const modelIds = new Set(getAllImageModels().map((model) => model.id));
const flux2Dev = getAllImageModels().find((model) => model.id === "flux-2-dev");
const fluxKontext = getAllImageModels().find((model) => model.id === "flux-kontext");
for (const alias of [
"flux-kontext",
"flux-kontext-max",
"flux-2-max",
"flux-2-pro",
"flux-2-flex",
"flux-2-dev",
]) {
assert.equal(modelIds.has(alias), true, `Expected alias ${alias} in image catalog`);
}
assert.deepEqual(flux2Dev?.inputModalities, ["text", "image"]);
assert.deepEqual(fluxKontext?.inputModalities, ["text", "image"]);
});
test("handleImageGeneration calls Fal AI with Key auth and normalizes URL results to base64", async () => {
const originalFetch = globalThis.fetch;
let requestCapture;
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "https://fal.run/fal-ai/flux-pro/v1.1-ultra") {
requestCapture = {
url: stringUrl,
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
return new Response(
JSON.stringify({
images: [{ url: "https://cdn.example.com/fal-ultra.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (stringUrl === "https://cdn.example.com/fal-ultra.png") {
return new Response(new Uint8Array([5, 6, 7]), {
status: 200,
headers: { "content-type": "image/png" },
});
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "fal-ai/fal-ai/flux-pro/v1.1-ultra",
prompt: "cinematic skyline",
size: "1024x1792",
n: 2,
image_url: "https://example.com/source.png",
response_format: "b64_json",
},
credentials: { apiKey: "fal-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(requestCapture.url, "https://fal.run/fal-ai/flux-pro/v1.1-ultra");
assert.equal(requestCapture.headers.Authorization, "Key fal-key");
assert.equal(requestCapture.body.aspect_ratio, "9:16");
assert.equal(requestCapture.body.image_url, "https://example.com/source.png");
assert.equal(requestCapture.body.num_images, 2);
assert.equal(requestCapture.body.sync_mode, true);
assert.equal(result.data.data[0].b64_json, "BQYH");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration routes Stability AI edit models to native endpoints", async () => {
const originalFetch = globalThis.fetch;
let requestCapture;
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "https://example.com/stability-input.png") {
return new Response(new Uint8Array([4, 5]), {
status: 200,
headers: { "content-type": "image/png" },
});
}
if (stringUrl === "https://api.stability.ai/v2beta/stable-image/edit/inpaint") {
requestCapture = {
url: stringUrl,
headers: options.headers,
body: options.body,
};
return new Response(JSON.stringify({ image: "c3RhYmlsaXR5LWltYWdl" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "stability-ai/inpaint",
prompt: "replace the sky with aurora",
negative_prompt: "rain",
image_url: "https://example.com/stability-input.png",
mask: "data:image/png;base64,AA==",
response_format: "b64_json",
},
credentials: { apiKey: "stability-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(requestCapture.url, "https://api.stability.ai/v2beta/stable-image/edit/inpaint");
assert.equal(requestCapture.headers.Authorization, "Bearer stability-key");
assert.equal(requestCapture.headers.Accept, "application/json");
assert.equal(requestCapture.headers["Content-Type"], undefined);
assert.ok(requestCapture.body instanceof FormData);
assert.equal(requestCapture.body.get("prompt"), "replace the sky with aurora");
assert.equal(requestCapture.body.get("negative_prompt"), "rain");
assert.equal(requestCapture.body.get("output_format"), "png");
assert.equal((requestCapture.body.get("image") as Blob).size, 2);
assert.equal((requestCapture.body.get("mask") as Blob).size, 1);
assert.equal(result.data.data[0].b64_json, "c3RhYmlsaXR5LWltYWdl");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration sends Stability AI text generation as multipart form data", async () => {
const originalFetch = globalThis.fetch;
let requestCapture;
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "https://api.stability.ai/v2beta/stable-image/generate/core") {
requestCapture = {
url: stringUrl,
headers: options.headers,
body: options.body,
};
return new Response(JSON.stringify({ image: "c3RhYmlsaXR5LWNvcmU=" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "stability-ai/stable-image-core",
prompt: "city near beach",
size: "1024x1024",
response_format: "b64_json",
},
credentials: { apiKey: "stability-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(requestCapture.url, "https://api.stability.ai/v2beta/stable-image/generate/core");
assert.equal(requestCapture.headers.Authorization, "Bearer stability-key");
assert.equal(requestCapture.headers.Accept, "application/json");
assert.equal(requestCapture.headers["Content-Type"], undefined);
assert.ok(requestCapture.body instanceof FormData);
assert.equal(requestCapture.body.get("prompt"), "city near beach");
assert.equal(requestCapture.body.get("mode"), "text-to-image");
assert.equal(requestCapture.body.get("aspect_ratio"), "1:1");
assert.equal(requestCapture.body.get("output_format"), "png");
assert.equal(result.data.data[0].b64_json, "c3RhYmlsaXR5LWNvcmU=");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration polls Black Forest Labs results and sends base64 input images", async () => {
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;
let createCapture;
let pollCapture;
globalThis.setTimeout = immediateTimeout;
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "https://example.com/bfl-input.png") {
return new Response(new Uint8Array([1, 2]), {
status: 200,
headers: { "content-type": "image/png" },
});
}
if (stringUrl === "https://api.bfl.ai/v1/flux-kontext-pro") {
createCapture = {
url: stringUrl,
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
return new Response(JSON.stringify({ polling_url: "https://api.bfl.ai/result/123" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (stringUrl === "https://api.bfl.ai/result/123") {
pollCapture = {
url: stringUrl,
headers: options.headers,
};
return new Response(
JSON.stringify({
status: "Ready",
result: { sample: "https://cdn.example.com/bfl-result.png" },
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (stringUrl === "https://cdn.example.com/bfl-result.png") {
return new Response(new Uint8Array([9, 8, 7]), {
status: 200,
headers: { "content-type": "image/png" },
});
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "black-forest-labs/flux-kontext-pro",
prompt: "change the car color to blue",
image_url: "https://example.com/bfl-input.png",
size: "1024x1792",
response_format: "b64_json",
},
credentials: { apiKey: "bfl-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(createCapture.url, "https://api.bfl.ai/v1/flux-kontext-pro");
assert.equal(createCapture.headers["x-key"], "bfl-key");
assert.equal(createCapture.body.input_image, "AQI=");
assert.equal(createCapture.body.aspect_ratio, "9:16");
assert.equal(pollCapture.headers["x-key"], "bfl-key");
assert.equal(result.data.data[0].b64_json, "CQgH");
} finally {
globalThis.fetch = originalFetch;
globalThis.setTimeout = originalSetTimeout;
}
});
test("handleImageGeneration calls native Recraft endpoint with model in body", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
return new Response(
JSON.stringify({
data: [{ url: "https://cdn.example.com/recraft.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "recraft/recraftv3",
prompt: "vector fox logo",
size: "1024x1024",
style: "digital_illustration",
},
credentials: { apiKey: "recraft-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://external.api.recraft.ai/v1/images/generations");
assert.equal(captured.headers.Authorization, "Bearer recraft-key");
assert.deepEqual(captured.body, {
model: "recraftv3",
prompt: "vector fox logo",
size: "1024x1024",
style: "digital_illustration",
});
assert.equal(result.data.data[0].url, "https://cdn.example.com/recraft.png");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration uploads source images to Topaz and returns base64 output", async () => {
const originalFetch = globalThis.fetch;
let requestCapture;
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "https://example.com/topaz-input.png") {
return new Response(new Uint8Array([1, 2, 3]), {
status: 200,
headers: { "content-type": "image/png" },
});
}
if (stringUrl === "https://api.topazlabs.com/image/v1/enhance") {
const formData = options.body as FormData;
requestCapture = {
url: stringUrl,
headers: options.headers,
outputWidth: formData.get("output_width"),
outputHeight: formData.get("output_height"),
image: formData.get("image"),
};
return new Response(new Uint8Array([7, 7, 7]), {
status: 200,
headers: { "content-type": "image/jpeg" },
});
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "topaz/topaz-enhance",
prompt: "enhance image",
image_url: "https://example.com/topaz-input.png",
size: "2048x2048",
response_format: "b64_json",
},
credentials: { apiKey: "topaz-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(requestCapture.url, "https://api.topazlabs.com/image/v1/enhance");
assert.equal(requestCapture.headers["X-API-Key"], "topaz-key");
assert.equal(requestCapture.outputWidth, "2048");
assert.equal(requestCapture.outputHeight, "2048");
assert.ok(requestCapture.image instanceof File);
assert.equal(result.data.data[0].b64_json, "BwcH");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration sends Antigravity image requests with native image_gen envelope", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
return new Response(
JSON.stringify({
response: {
candidates: [
{
content: {
parts: [
{
thoughtSignature: "signature",
inlineData: { mimeType: "image/jpeg", data: "YmFzZTY0LWdlbWluaQ==" },
},
],
},
},
],
modelVersion: "gemini-3.1-flash-image",
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "antigravity/gemini-3.1-flash-image-preview",
prompt: "painted beach",
size: "1024x1024",
aspect_ratio: "not-a-ratio",
},
credentials: { accessToken: "ag-token", projectId: "project-123" },
log: null,
});
assert.equal(result.success, true);
assert.equal(
captured.url,
"https://daily-cloudcode-pa.googleapis.com/v1internal:generateContent"
);
assert.equal(captured.headers.Authorization, "Bearer ag-token");
assert.equal(captured.headers["x-client-name"], "antigravity");
assert.equal(captured.headers["x-goog-user-project"], undefined);
assert.match(captured.headers["User-Agent"], /^Antigravity\//);
assert.equal(captured.headers["x-goog-api-client"], undefined);
assert.equal(captured.body.project, "project-123");
assert.match(captured.body.requestId, /^image_gen\//);
assert.equal(captured.body.model, "gemini-3.1-flash-image");
assert.equal(captured.body.userAgent, "antigravity");
assert.equal(captured.body.requestType, "image_gen");
assert.deepEqual(captured.body.request, {
contents: [{ role: "user", parts: [{ text: "painted beach" }] }],
generationConfig: {
candidateCount: 1,
imageConfig: { aspectRatio: "1:1" },
},
});
assert.deepEqual(result.data.data, [
{ b64_json: "YmFzZTY0LWdlbWluaQ==", revised_prompt: "painted beach" },
]);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration rejects Antigravity image requests without projectId", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => {
throw new Error("fetch should not be called without an Antigravity projectId");
};
try {
const result = await handleImageGeneration({
body: {
model: "antigravity/gemini-3.1-flash-image",
prompt: "painted forest",
size: "1024x1024",
},
credentials: { accessToken: "ag-token" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 400);
assert.match(String(result.error), /Missing Google projectId/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration sends Antigravity image requests without billing project header", async () => {
const originalFetch = globalThis.fetch;
const calls = [];
globalThis.fetch = async (url, options = {}) => {
calls.push({
url: String(url),
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
});
return new Response(
JSON.stringify({
response: {
candidates: [
{
content: {
parts: [
{
inlineData: { mimeType: "image/jpeg", data: "YmFzZTY0LXJldHJ5" },
},
],
},
},
],
modelVersion: "gemini-3.1-flash-image",
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "antigravity/gemini-3.1-flash-image",
prompt: "painted forest",
size: "1024x1024",
},
credentials: { accessToken: "ag-token", projectId: "project-123" },
log: null,
});
assert.equal(result.success, true);
assert.equal(calls.length, 1);
assert.equal(calls[0].headers["x-goog-user-project"], undefined);
assert.equal(calls[0].body.project, "project-123");
assert.deepEqual(result.data.data, [
{ b64_json: "YmFzZTY0LXJldHJ5", revised_prompt: "painted forest" },
]);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration sanitizes Antigravity upstream error payloads", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () =>
new Response(
JSON.stringify({
error: {
code: 500,
message:
"failed at /Users/backryun/OmniRoute/open-sse/handlers/imageGeneration.ts:1\nstack",
status: "INTERNAL",
},
}),
{ status: 500, headers: { "content-type": "application/json" } }
);
try {
const result = await handleImageGeneration({
body: {
model: "antigravity/gemini-3.1-flash-image",
prompt: "painted forest",
size: "1024x1024",
},
credentials: { accessToken: "ag-token", projectId: "project-123" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 500);
assert.equal(result.error.error.message, "failed at <path>");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration retries Nebius against the fallback URL after retryable failures", async () => {
const originalFetch = globalThis.fetch;
const calls = [];
globalThis.fetch = async (url, options = {}) => {
calls.push({
url: String(url),
body: JSON.parse(String(options.body || "{}")),
headers: options.headers,
});
if (calls.length === 1) {
return new Response("primary missing", { status: 404 });
}
return new Response(
JSON.stringify({
created: 321,
data: [{ url: "https://cdn.example.com/fallback.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "nebius/black-forest-labs/flux-dev",
prompt: "fallback skyline",
},
credentials: { apiKey: "nebius-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(calls.length, 2);
assert.equal(calls[0].url, "https://api.tokenfactory.nebius.com/v1/images/generations");
assert.equal(calls[1].url, "https://api.studio.nebius.com/v1/images/generations");
assert.equal(calls[1].headers.Authorization, "Bearer nebius-key");
assert.deepEqual(calls[1].body, {
model: "black-forest-labs/flux-dev",
prompt: "fallback skyline",
});
assert.deepEqual(result.data.data, [{ url: "https://cdn.example.com/fallback.png" }]);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration supports NanoBanana synchronous flash responses", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
body: JSON.parse(String(options.body || "{}")),
headers: options.headers,
};
return new Response(JSON.stringify({ image: "bmFub2JhbmFuYS1pbWFnZQ==" }), {
status: 200,
headers: { "content-type": "application/json" },
});
};
try {
const result = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-flash",
prompt: "banana robot",
n: 2,
size: "1024x1792",
},
credentials: { apiKey: "banana-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://api.nanobananaapi.ai/api/v1/nanobanana/generate");
assert.equal(captured.headers.Authorization, "Bearer banana-key");
assert.deepEqual(captured.body, {
prompt: "banana robot",
type: "TEXTTOIAMGE",
numImages: 2,
image_size: "9:16",
});
assert.deepEqual(result.data.data, [
{ b64_json: "bmFub2JhbmFuYS1pbWFnZQ==", revised_prompt: "banana robot" },
]);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration uses the NanoBanana pro endpoint and keeps sync data payloads", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
body: JSON.parse(String(options.body || "{}")),
};
return new Response(
JSON.stringify({
data: [{ url: "https://cdn.example.com/pro-image.png", revised_prompt: "banana pro" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-pro",
prompt: "banana pro",
size: "1024x1024",
quality: "hd",
imageUrls: ["https://example.com/ref.png"],
},
credentials: { apiKey: "banana-pro-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://api.nanobananaapi.ai/api/v1/nanobanana/generate-pro");
assert.deepEqual(captured.body, {
prompt: "banana pro",
resolution: "2K",
aspectRatio: "1:1",
imageUrls: ["https://example.com/ref.png"],
});
assert.deepEqual(result.data.data, [
{ url: "https://cdn.example.com/pro-image.png", revised_prompt: "banana pro" },
]);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration polls NanoBanana task results and converts URLs to base64 when requested", async () => {
const originalFetch = globalThis.fetch;
const calls = [];
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
calls.push(stringUrl);
if (stringUrl === "https://api.nanobananaapi.ai/api/v1/nanobanana/generate") {
return new Response(JSON.stringify({ taskId: "task-1" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (stringUrl === "https://api.nanobananaapi.ai/api/v1/nanobanana/record-info?taskId=task-1") {
return new Response(
JSON.stringify({
data: {
successFlag: 1,
response: { resultImageUrl: "https://cdn.example.com/result.png" },
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (stringUrl === "https://cdn.example.com/result.png") {
return new Response(new Uint8Array([1, 2, 3, 4]), { status: 200 });
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-flash",
prompt: "banana async",
response_format: "b64_json",
},
credentials: { apiKey: "banana-key" },
log: null,
});
assert.equal(result.success, true);
assert.deepEqual(calls, [
"https://api.nanobananaapi.ai/api/v1/nanobanana/generate",
"https://api.nanobananaapi.ai/api/v1/nanobanana/record-info?taskId=task-1",
"https://cdn.example.com/result.png",
]);
assert.deepEqual(result.data.data, [{ b64_json: "AQIDBA==", revised_prompt: "banana async" }]);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration rejects NanoBanana submissions that never return a task identifier", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () =>
new Response(JSON.stringify({ ok: true }), {
status: 200,
headers: { "content-type": "application/json" },
});
try {
const result = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-flash",
prompt: "banana missing task",
},
credentials: { apiKey: "banana-key" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 502);
assert.match(result.error, /did not return taskId/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration executes ComfyUI workflows and normalizes image outputs", async () => {
const originalFetch = globalThis.fetch;
const originalSetTimeout = globalThis.setTimeout;
let promptBody;
globalThis.setTimeout = immediateTimeout;
globalThis.fetch = async (url, options = {}) => {
const stringUrl = String(url);
if (stringUrl === "http://localhost:8188/prompt") {
promptBody = JSON.parse(String(options.body || "{}"));
return new Response(JSON.stringify({ prompt_id: "image-1" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (stringUrl === "http://localhost:8188/history/image-1") {
return new Response(
JSON.stringify({
"image-1": {
outputs: {
9: {
images: [{ filename: "frame.png", subfolder: "out", type: "output" }],
},
},
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (stringUrl.includes("/view?")) {
return new Response(new Uint8Array([9, 9, 9]), { status: 200 });
}
throw new Error(`Unexpected URL: ${stringUrl}`);
};
try {
const result = await handleImageGeneration({
body: {
model: "comfyui/flux-dev",
prompt: "comfy forest",
negative_prompt: "blurry",
size: "768x512",
n: 2,
},
credentials: null,
log: null,
});
assert.equal(result.success, true);
assert.equal(promptBody.prompt["5"].inputs.width, 768);
assert.equal(promptBody.prompt["5"].inputs.height, 512);
assert.equal(promptBody.prompt["5"].inputs.batch_size, 2);
assert.deepEqual(result.data.data, [{ b64_json: "CQkJ", revised_prompt: "comfy forest" }]);
} finally {
globalThis.fetch = originalFetch;
globalThis.setTimeout = originalSetTimeout;
}
});
test("handleImageGeneration returns provider errors when ComfyUI submission fails", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => new Response("boom", { status: 500 });
try {
const result = await handleImageGeneration({
body: {
model: "comfyui/flux-dev",
prompt: "broken workflow",
},
credentials: null,
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 502);
assert.match(result.error, /ComfyUI submit failed \(500\): boom/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration supports dynamically registered Imagen3 providers", async () => {
const originalFetch = globalThis.fetch;
const originalProvider = IMAGE_PROVIDERS.imagen3;
let captured;
IMAGE_PROVIDERS.imagen3 = {
id: "imagen3",
baseUrl: "https://imagen.example.com/v1/generate",
authType: "apikey",
authHeader: "bearer",
format: "imagen3",
models: [{ id: "image-gen", name: "Image Gen" }],
supportedSizes: ["1024x1024"],
};
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
return new Response(
JSON.stringify({
created: 42,
images: [{ image: "aW1hZ2VuLTM=" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "imagen3/image-gen",
prompt: "vertex skyline",
size: "1792x1024",
},
credentials: { apiKey: "imagen-key" },
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://imagen.example.com/v1/generate");
assert.equal(captured.headers.Authorization, "Bearer imagen-key");
assert.deepEqual(captured.body, {
prompt: "vertex skyline",
aspect_ratio: "16:9",
number_of_images: 1,
});
assert.deepEqual(result.data.data, [
{ b64_json: "aW1hZ2VuLTM=", revised_prompt: "vertex skyline" },
]);
} finally {
globalThis.fetch = originalFetch;
if (originalProvider) {
IMAGE_PROVIDERS.imagen3 = originalProvider;
} else {
delete IMAGE_PROVIDERS.imagen3;
}
}
});
test("handleImageGeneration preserves Imagen3 data arrays when providers already return OpenAI-like payloads", async () => {
const originalFetch = globalThis.fetch;
const originalProvider = IMAGE_PROVIDERS.imagen3;
IMAGE_PROVIDERS.imagen3 = {
id: "imagen3",
baseUrl: "https://imagen.example.com/v1/generate",
authType: "apikey",
authHeader: "bearer",
format: "imagen3",
models: [{ id: "image-gen", name: "Image Gen" }],
supportedSizes: ["1024x1024"],
};
globalThis.fetch = async () =>
new Response(
JSON.stringify({
data: [{ url: "https://cdn.example.com/already-normalized.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
try {
const result = await handleImageGeneration({
body: {
model: "imagen3/image-gen",
prompt: "normalized payload",
},
credentials: { apiKey: "imagen-key" },
log: null,
});
assert.equal(result.success, true);
assert.deepEqual(result.data.data, [{ url: "https://cdn.example.com/already-normalized.png" }]);
} finally {
globalThis.fetch = originalFetch;
if (originalProvider) {
IMAGE_PROVIDERS.imagen3 = originalProvider;
} else {
delete IMAGE_PROVIDERS.imagen3;
}
}
});
test("handleImageGeneration returns provider errors when Imagen3 fetch throws", async () => {
const originalFetch = globalThis.fetch;
const originalProvider = IMAGE_PROVIDERS.imagen3;
IMAGE_PROVIDERS.imagen3 = {
id: "imagen3",
baseUrl: "https://imagen.example.com/v1/generate",
authType: "apikey",
authHeader: "bearer",
format: "imagen3",
models: [{ id: "image-gen", name: "Image Gen" }],
supportedSizes: ["1024x1024"],
};
globalThis.fetch = async () => {
throw new Error("imagen upstream timeout");
};
try {
const result = await handleImageGeneration({
body: {
model: "imagen3/image-gen",
prompt: "broken imagen",
},
credentials: { apiKey: "imagen-key" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 502);
assert.equal(result.error, "Image provider error: imagen upstream timeout");
} finally {
globalThis.fetch = originalFetch;
if (originalProvider) {
IMAGE_PROVIDERS.imagen3 = originalProvider;
} else {
delete IMAGE_PROVIDERS.imagen3;
}
}
});
test("handleImageGeneration uses the default synthetic base URL for resolved custom providers without baseUrl", async () => {
const originalFetch = globalThis.fetch;
let capturedUrl;
globalThis.fetch = async (url) => {
capturedUrl = String(url);
return new Response(JSON.stringify({ data: [{ b64_json: "ZmFrZS1jdXN0b20=" }] }), {
status: 200,
headers: { "content-type": "application/json" },
});
};
try {
const result = await handleImageGeneration({
body: {
model: "custom-provider/super-image",
prompt: "fallback base url",
},
credentials: { apiKey: "custom-key" },
resolvedProvider: "custom-provider",
log: null,
});
assert.equal(result.success, true);
assert.equal(
capturedUrl,
"https://generativelanguage.googleapis.com/v1beta/openai/images/generations"
);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration logs OpenAI-compatible upstream failures and transport errors", async () => {
const originalFetch = globalThis.fetch;
const log = createLogRecorder();
globalThis.fetch = async () => new Response("primary unavailable", { status: 503 });
try {
const failed = await handleImageGeneration({
body: {
model: "openai/gpt-image-2",
prompt: "broken upstream",
},
credentials: { apiKey: "image-key" },
log,
});
assert.equal(failed.success, false);
assert.equal(failed.status, 503);
assert.match(log.entries.at(-1).message, /openai error 503/);
} finally {
globalThis.fetch = originalFetch;
}
globalThis.fetch = async () => {
throw new Error("socket closed");
};
try {
const errored = await handleImageGeneration({
body: {
model: "openai/gpt-image-2",
prompt: "transport issue",
},
credentials: { apiKey: "image-key" },
log,
});
assert.equal(errored.success, false);
assert.equal(errored.status, 502);
assert.equal(errored.error, "Image provider error: socket closed");
assert.match(log.entries.at(-1).message, /socket closed/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration logs Nebius fallback attempts before succeeding", async () => {
const originalFetch = globalThis.fetch;
const log = createLogRecorder();
let callCount = 0;
globalThis.fetch = async (url) => {
callCount += 1;
if (callCount === 1) {
assert.equal(String(url), "https://api.tokenfactory.nebius.com/v1/images/generations");
return new Response("primary missing", { status: 404 });
}
return new Response(
JSON.stringify({
data: [{ url: "https://cdn.example.com/fallback-logged.png" }],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const result = await handleImageGeneration({
body: {
model: "nebius/black-forest-labs/flux-dev",
prompt: "fallback logging",
},
credentials: { apiKey: "nebius-key" },
log,
});
assert.equal(result.success, true);
assert.equal(
log.entries.some((entry) => entry.level === "info" && /trying fallback/.test(entry.message)),
true
);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration surfaces Hyperbolic upstream failures and fetch exceptions", async () => {
const originalFetch = globalThis.fetch;
const log = createLogRecorder();
globalThis.fetch = async () => new Response("hyperbolic unavailable", { status: 429 });
try {
const failed = await handleImageGeneration({
body: {
model: "hyperbolic/FLUX.1-dev",
prompt: "too busy",
},
credentials: { apiKey: "hyper-key" },
log,
});
assert.equal(failed.success, false);
assert.equal(failed.status, 429);
assert.equal(failed.error, "hyperbolic unavailable");
} finally {
globalThis.fetch = originalFetch;
}
globalThis.fetch = async () => {
throw new Error("hyperbolic network down");
};
try {
const errored = await handleImageGeneration({
body: {
model: "hyperbolic/FLUX.1-dev",
prompt: "network issue",
},
credentials: { apiKey: "hyper-key" },
log,
});
assert.equal(errored.success, false);
assert.equal(errored.status, 502);
assert.equal(errored.error, "Image provider error: hyperbolic network down");
assert.match(log.entries.at(-1).message, /hyperbolic network down/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration handles NanoBanana missing statusUrl, failed tasks and empty completed payloads", async () => {
const originalFetch = globalThis.fetch;
const originalProvider = structuredClone(IMAGE_PROVIDERS.nanobanana);
const log = createLogRecorder();
IMAGE_PROVIDERS.nanobanana = {
...IMAGE_PROVIDERS.nanobanana,
statusUrl: undefined,
};
globalThis.fetch = async () =>
new Response(JSON.stringify({ taskId: "task-missing-status" }), {
status: 200,
headers: { "content-type": "application/json" },
});
try {
const missingStatusUrl = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-flash",
prompt: "missing status url",
},
credentials: { apiKey: "banana-key" },
log,
});
assert.equal(missingStatusUrl.success, false);
assert.equal(missingStatusUrl.status, 500);
assert.match(missingStatusUrl.error, /statusUrl is not configured/);
} finally {
IMAGE_PROVIDERS.nanobanana = originalProvider;
globalThis.fetch = originalFetch;
}
globalThis.fetch = async (url) => {
const stringUrl = String(url);
if (stringUrl.endsWith("/generate")) {
return new Response(JSON.stringify({ taskId: "task-failed" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
return new Response(
JSON.stringify({
data: { successFlag: 2, errorMessage: "NanoBanana generation failed" },
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const failedTask = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-flash",
prompt: "failed task",
poll_interval_ms: 1,
},
credentials: { apiKey: "banana-key" },
log,
});
assert.equal(failedTask.success, false);
assert.equal(failedTask.status, 502);
assert.equal(failedTask.error, "NanoBanana generation failed");
} finally {
globalThis.fetch = originalFetch;
}
globalThis.fetch = async (url) => {
const stringUrl = String(url);
if (stringUrl.endsWith("/generate")) {
return new Response(JSON.stringify({ taskId: "task-empty" }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
return new Response(
JSON.stringify({
data: { successFlag: 1, response: {} },
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
};
try {
const completedWithoutPayload = await handleImageGeneration({
body: {
model: "nanobanana/nanobanana-flash",
prompt: "empty payload",
poll_interval_ms: 1,
},
credentials: { apiKey: "banana-key" },
log,
});
assert.equal(completedWithoutPayload.success, true);
assert.deepEqual(completedWithoutPayload.data.data, []);
assert.equal(
log.entries.some(
(entry) => entry.level === "warn" && /completed without image payload/.test(entry.message)
),
true
);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration surfaces SD WebUI upstream and transport failures", async () => {
const originalFetch = globalThis.fetch;
const log = createLogRecorder();
globalThis.fetch = async () => new Response("sdwebui error", { status: 500 });
try {
const failed = await handleImageGeneration({
body: {
model: "sdwebui/sdxl-base-1.0",
prompt: "broken sdwebui",
},
credentials: null,
log,
});
assert.equal(failed.success, false);
assert.equal(failed.status, 500);
assert.equal(failed.error, "sdwebui error");
} finally {
globalThis.fetch = originalFetch;
}
globalThis.fetch = async () => {
throw new Error("socket hang up");
};
try {
const errored = await handleImageGeneration({
body: {
model: "sdwebui/sdxl-base-1.0",
prompt: "sdwebui transport issue",
},
credentials: null,
log,
});
assert.equal(errored.success, false);
assert.equal(errored.status, 502);
assert.equal(errored.error, "Image provider error: socket hang up");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration normalizes Imagen3 single-image payloads and non-ok responses", async () => {
const originalFetch = globalThis.fetch;
const originalProvider = IMAGE_PROVIDERS.imagen3;
IMAGE_PROVIDERS.imagen3 = {
id: "imagen3",
baseUrl: "https://imagen.example.com/v1/generate",
authType: "apikey",
authHeader: "bearer",
format: "imagen3",
models: [{ id: "image-gen", name: "Image Gen" }],
supportedSizes: ["1024x1024"],
};
globalThis.fetch = async () =>
new Response(JSON.stringify({ image: "aW1hZ2VuLXNpbmdsZQ==" }), {
status: 200,
headers: { "content-type": "application/json" },
});
try {
const singleObject = await handleImageGeneration({
body: {
model: "imagen3/image-gen",
prompt: "single image",
},
credentials: { apiKey: "imagen-key" },
log: null,
});
assert.equal(singleObject.success, true);
assert.deepEqual(singleObject.data.data, [
{ b64_json: "aW1hZ2VuLXNpbmdsZQ==", url: undefined, revised_prompt: "single image" },
]);
} finally {
globalThis.fetch = originalFetch;
}
globalThis.fetch = async () => new Response("imagen failed", { status: 503 });
try {
const failed = await handleImageGeneration({
body: {
model: "imagen3/image-gen",
prompt: "imagen failed",
},
credentials: { apiKey: "imagen-key" },
log: createLogRecorder(),
});
assert.equal(failed.success, false);
assert.equal(failed.status, 503);
assert.equal(failed.error, "imagen failed");
} finally {
globalThis.fetch = originalFetch;
if (originalProvider) {
IMAGE_PROVIDERS.imagen3 = originalProvider;
} else {
delete IMAGE_PROVIDERS.imagen3;
}
}
});
const { extractImageGenerationCalls } = await import("../../open-sse/handlers/imageGeneration.ts");
function buildCodexSSE(items) {
const frames = items.map((item) => JSON.stringify({ type: "response.output_item.done", item }));
return frames.map((frame) => `event: response.output_item.done\ndata: ${frame}\n`).join("\n");
}
test("extractImageGenerationCalls pulls base64 PNG from image_generation_call output items", () => {
const sse = buildCodexSSE([
{
type: "image_generation_call",
id: "ig_1",
status: "completed",
revised_prompt: "a small kitten",
result: "aGVsbG8=",
},
]);
const calls = extractImageGenerationCalls(sse);
assert.equal(calls.length, 1);
assert.equal(calls[0].b64, "aGVsbG8=");
assert.equal(calls[0].revisedPrompt, "a small kitten");
});
test("extractImageGenerationCalls ignores unrelated events and malformed lines", () => {
const sse = [
"event: response.in_progress",
`data: ${JSON.stringify({ type: "response.in_progress" })}`,
"",
"data: not-json",
"",
"event: response.output_item.done",
`data: ${JSON.stringify({
type: "response.output_item.done",
item: { type: "message", role: "assistant", content: [] },
})}`,
"",
"data: [DONE]",
].join("\n");
assert.deepEqual(extractImageGenerationCalls(sse), []);
});
test("handleImageGeneration routes codex image requests through /responses with image_generation tool", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (url, options = {}) => {
captured = {
url: String(url),
headers: options.headers,
body: JSON.parse(String(options.body || "{}")),
};
const sse = buildCodexSSE([
{
type: "image_generation_call",
id: "ig_1",
status: "completed",
revised_prompt: "happy red kitten",
result: "a2l0dGVu",
},
]);
return new Response(sse, {
status: 200,
headers: { "content-type": "text/event-stream" },
});
};
try {
const result = await handleImageGeneration({
body: {
model: "codex/gpt-5.4",
prompt: "Draw a happy red kitten",
response_format: "b64_json",
},
credentials: {
accessToken: "codex-token",
providerSpecificData: { workspaceId: "acct-123" },
},
log: null,
});
assert.equal(result.success, true);
assert.equal(captured.url, "https://chatgpt.com/backend-api/codex/responses");
assert.equal(captured.headers.Authorization, "Bearer codex-token");
assert.equal(captured.headers["chatgpt-account-id"], "acct-123");
assert.equal(captured.body.model, "gpt-5.4");
assert.equal(captured.body.stream, true);
assert.equal(captured.body.store, false);
assert.deepEqual(captured.body.tools, [{ type: "image_generation", output_format: "png" }]);
assert.equal(captured.body.input[0].role, "user");
assert.equal(captured.body.input[0].content[0].text, "Draw a happy red kitten");
assert.equal(result.data.data[0].b64_json, "a2l0dGVu");
assert.equal(result.data.data[0].revised_prompt, "happy red kitten");
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration (codex) returns a data URL when response_format is not b64_json", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => {
const sse = buildCodexSSE([
{ type: "image_generation_call", id: "ig_2", status: "completed", result: "YWJjZA==" },
]);
return new Response(sse, { status: 200 });
};
try {
const result = await handleImageGeneration({
body: { model: "cx/gpt-5.4", prompt: "kitten" },
credentials: { accessToken: "codex-token" },
log: null,
});
assert.equal(result.success, true);
assert.equal(result.data.data[0].url, "data:image/png;base64,YWJjZA==");
assert.equal(result.data.data[0].b64_json, undefined);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration (codex) fans out n>1 requests in parallel", async () => {
const originalFetch = globalThis.fetch;
const calls = [];
let releaseFirst;
let pending;
globalThis.fetch = async (_url, options = {}) => {
const index = calls.length;
calls.push(JSON.parse(String(options.body || "{}")));
const sse = buildCodexSSE([
{
type: "image_generation_call",
id: `ig_${index + 1}`,
status: "completed",
result: index === 0 ? "Zmlyc3Q=" : "c2Vjb25k",
},
]);
if (index === 0) {
return new Promise((resolve) => {
releaseFirst = () => resolve(new Response(sse, { status: 200 }));
});
}
return new Response(sse, { status: 200 });
};
try {
pending = handleImageGeneration({
body: {
model: "codex/gpt-5.4",
prompt: "kitten",
n: 2,
response_format: "b64_json",
},
credentials: { accessToken: "codex-token" },
log: null,
});
await Promise.resolve();
assert.equal(calls.length, 2);
assert.deepEqual(
calls.map((call) => call.input[0].content[0].text),
["kitten", "kitten"]
);
releaseFirst();
const result = await pending;
assert.equal(result.success, true);
assert.deepEqual(
result.data.data.map((item) => item.b64_json),
["Zmlyc3Q=", "c2Vjb25k"]
);
} finally {
if (releaseFirst) releaseFirst();
if (pending) await pending.catch(() => {});
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration (codex) surfaces an error when no image_generation_call is emitted", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () => {
const sse = buildCodexSSE([
{ type: "message", role: "assistant", content: [{ type: "output_text", text: "hi" }] },
]);
return new Response(sse, { status: 200 });
};
try {
const result = await handleImageGeneration({
body: { model: "codex/gpt-5.4", prompt: "kitten" },
credentials: { accessToken: "codex-token" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 502);
assert.match(result.error, /image_generation_call/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration (codex) propagates upstream HTTP errors", async () => {
const originalFetch = globalThis.fetch;
globalThis.fetch = async () =>
new Response("upstream boom", { status: 403, headers: { "content-type": "text/plain" } });
try {
const result = await handleImageGeneration({
body: { model: "codex/gpt-5.4", prompt: "kitten" },
credentials: { accessToken: "codex-token" },
log: null,
});
assert.equal(result.success, false);
assert.equal(result.status, 403);
assert.match(result.error, /upstream boom/);
} finally {
globalThis.fetch = originalFetch;
}
});
test("handleImageGeneration (codex) forwards size and maps GPT-Image quality to hosted tool config", async () => {
const originalFetch = globalThis.fetch;
let captured;
globalThis.fetch = async (_url, options = {}) => {
captured = JSON.parse(String(options.body || "{}"));
const sse = buildCodexSSE([
{ type: "image_generation_call", id: "ig_1", status: "completed", result: "YWJj" },
]);
return new Response(sse, { status: 200 });
};
try {
await handleImageGeneration({
body: {
model: "codex/gpt-5.4",
prompt: "kitten",
size: "1024x1792",
quality: "hd",
},
credentials: { accessToken: "codex-token" },
log: null,
});
assert.deepEqual(captured.tools, [
{
type: "image_generation",
output_format: "png",
size: "1024x1792",
quality: "high",
},
]);
await handleImageGeneration({
body: { model: "codex/gpt-5.4", prompt: "kitten", quality: "standard" },
credentials: { accessToken: "codex-token" },
log: null,
});
assert.equal(captured.tools[0].quality, "medium");
await handleImageGeneration({
body: { model: "codex/gpt-5.4", prompt: "kitten" },
credentials: { accessToken: "codex-token" },
log: null,
});
assert.deepEqual(captured.tools, [{ type: "image_generation", output_format: "png" }]);
} finally {
globalThis.fetch = originalFetch;
}
});