* feat(db): include xp_audit_log in automatic retention/prune (#6801)
* fix(i18n): mirror retentionXpAuditLog into pt-BR.json (#6801)
pt.json and pt-BR.json are distinct files; the key landed only in pt.json,
so the i18n pt-BR integrity test (no drift, #6695) went red.
Fusion's panel-model extraction in combo.ts only recognized plain string
or {model: string} entries in combo.models; a {kind:"combo-ref", comboName}
step (a first-class, Zod-validated combo-step shape the dashboard already
lets you add to a fusion panel) had neither field, so it was silently
filtered out — no error, no warning, and an opaque 400 if it was the only
panel member.
A combo-ref panel member is now dispatched as one black-box panel voice
(a recursive handleComboChat call into the referenced combo, reusing the
same executeComboRefUnit + cycle/depth guards every other combo-ref-
consuming strategy already uses), not a fan-out of the referenced combo's
own targets.
New module open-sse/services/combo/fusionPanel.ts keeps the frozen
combo.ts god-file's growth minimal (extraction/dispatch-wrapper logic
lives there; the fusion branch itself only wires it in).
Add a per-connection cache capability override (supportsPromptCaching,
cacheControlPassthrough) stored in provider_specific_data.cache, consulted
first by providerSupportsCaching() / providerHonorsOpenAIFormatCacheControl()
before falling back to the hardcoded CACHING_PROVIDERS name sets. Unblocks
prompt_cache_key injection, the compression cache-aware guard, and
cache_control passthrough for openai-compatible-chat-<uuid>-style custom
connections that can never match the hardcoded provider-name sets. Default
(no override) is byte-identical to current behavior.
* fix(sse): project non-streaming JSON back to the Gemini/Antigravity envelope
The streaming and non-streaming response paths disagreed on how a response is
projected back into a non-OpenAI client's wire format.
Streaming goes through the translator registry, where the
FORMATS.OPENAI -> FORMATS.ANTIGRAVITY translator
(open-sse/translator/response/openai-to-antigravity.ts) projects each OpenAI
chunk into the `{ response: { candidates: [...] } }` envelope, mapping
tool_calls to `functionCall` parts and reasoning to `thought` parts.
The non-streaming path uses translateNonStreamingResponse() instead. Its
"Phase 3: translate back to client source format" step only special-cased
FORMATS.CLAUDE — every other non-OpenAI client format fell through and returned
the raw OpenAI chat.completion intermediate. A Gemini/Antigravity client issuing
a non-streaming request therefore received `choices[]`/`tool_calls` instead of
`candidates[]`/`functionCall`: the client's parser sees no candidates and the
function calls are effectively dropped, so tool-calling silently breaks on the
JSON path while working over SSE.
Adds convertOpenAINonStreamingToGeminiFamily() and wires it into Phase 3 for
FORMATS.GEMINI / FORMATS.ANTIGRAVITY, mirroring the shape the streaming
translator already emits so both paths agree. Tool-call `arguments` are parsed
through a non-throwing helper: a provider emitting truncated JSON degrades that
call's args to `{}` rather than raising an uncaught SyntaxError in the shared
response hot path (matching the streaming translator's behaviour).
Scoped deliberately narrow: only the Gemini-family projection gap proven by the
failing test is closed. The Ollama/Responses projections and the SSE terminal
tracker from the upstream change are not ported — OmniRoute has no OLLAMA format
in FORMATS, and its Responses/[DONE] handling already lives in
nonStreamingSse.ts + the registry.
Co-authored-by: W ARELIK <warelik@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2348
* chore(changelog): fragment for #7255
---------
Co-authored-by: W ARELIK <warelik@users.noreply.github.com>
* fix(build): isolate Windows HOME/AppData during next build
next build's static-generation glob scan and framework cache helpers walk
%USERPROFILE%/AppData, which on GitHub-hosted Windows runners (and some
OneDrive-backed dev profiles) contains reparse points/junctions that raise
EPERM during Next's file-system scans. .github/workflows/electron-release.yml
already patches USERPROFILE for that one CI job ("Sanitize Windows home
directory" step), but a local `npm run build` on Windows — or any other
Windows CI path that calls scripts/build/build-next-isolated.mjs directly —
hits the same EPERM unprotected, and the existing CI patch does not touch
APPDATA/LOCALAPPDATA at all.
Folds the isolation into resolveNextBuildEnv() (the existing seam every
caller of build-next-isolated.mjs already goes through), rather than adding
a second build entrypoint the way upstream's scripts/build-app.js does:
on win32, HOME/USERPROFILE/APPDATA/LOCALAPPDATA are pointed at a fresh
per-process temp profile dir, created just-in-time via the new
ensureWindowsBuildProfileDirs() before spawning `next build`. Skipped when a
caller has already sandboxed the build via NEXT_DIST_DIR (the existing
signal this file reads for isolated-build callers, e.g. CLI packaging), so
nested build invocations are never double-isolated. Non-Windows behavior is
unchanged.
Co-authored-by: KunN21 <kunn21.nv@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2402
* chore(changelog): fragment for #7249
---------
Co-authored-by: KunN21 <kunn21.nv@gmail.com>
* fix(sse): reconstruct Claude-format content in synthetic bypass responses
handleBypassRequest() returns a canned response for CLI warmup/title-
extraction patterns without calling the provider. For Claude-format
clients (e.g. Claude Code CLI), the non-streaming path merged translated
SSE chunks by taking message_start.message as-is — but the
openai-to-claude translator always initializes that message with
content: [] and streams the actual text via separate
content_block_start/delta events. Every synthetic Claude-format
bypass response therefore silently returned empty content.
mergeChunksToResponse() now rebuilds the content array from
content_block_start/delta events (mirroring the streaming path) and
carries over stop_reason/stop_sequence from message_delta. Extracted
the response-builder helpers (createOpenAIResponse,
create{Non}StreamingResponse, mergeChunksToResponse) out of
bypassHandler.ts into a new open-sse/utils/bypassResponse.ts module so
this logic has a single owner instead of being duplicated inline.
Co-authored-by: KunN-21 <kunn21.nv@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2404
* chore(changelog): fragment for #7248
* refactor(sse): extract Claude chunk-merge helpers to fix complexity ratchet
mergeChunksToResponse() regressed both quality ratchets by +1
(complexity 2057>2056, cognitive 891>890). Split the Claude-format
reconstruction into buildClaudeContentBlocks(), applyClaudeMessageDelta()
and mergeClaudeChunks() — same behavior, verified by the existing
bypass-response-claude-merge.test.ts (4/4 passing unchanged).
---------
Co-authored-by: KunN-21 <kunn21.nv@gmail.com>
* fix(nvidia): expand NIM chat model catalog with newly-observed models
NVIDIA NIM's live catalog has added several chat-completions-capable models
since the registry was last swept (#6108): Llama 3.x/4 family, Mistral
variants, several Nemotron/Nemoguard safety and reasoning models, Qwen3-Next,
and a few smaller vendor models (Sarvam, Stockmark, Upstage). Adds them to
open-sse/config/providers/registry/nvidia/index.ts with supportsReasoning /
supportsVision flags where applicable.
minimaxai/minimax-m3 is intentionally NOT re-added — it stays excluded per
the #3329 guard (still 404s for most callers). Two non-chat entries from the
upstream sweep (nvidia/gliner-pii — an NER/PII tagger, and
google/diffusiongemma-26b-a4b-it — a diffusion model) are dropped: this
registry only models the /v1/chat/completions surface, and OmniRoute already
covers NVIDIA's embedding/ASR/TTS models separately in embeddingRegistry.ts
and audioRegistry.ts. Upstream's per-model `thinkingFormat` capability
override (a legacy open-sse/providers/capabilities.js concept) has no
OmniRoute equivalent — reasoning-param translation here is scoped per
PROVIDER (translator/paramSupport.ts, executors/default.ts), not per model,
so only the catalog needed porting.
Co-authored-by: baibiao <baibiaoxxl123@outlook.com>
Inspired-by: https://github.com/decolua/9router/pull/2373
* chore(changelog): fragment for #7247
---------
Co-authored-by: baibiao <baibiaoxxl123@outlook.com>
* feat(provider): add Chenzk API OpenAI-compatible gateway
Registers Chenzk (chenzk.top) as a new API-key gateway provider — an
OpenAI-compatible aggregator exposing GPT/Claude/DeepSeek/GLM model groups
behind one endpoint. Adapted to OmniRoute's directory-per-provider registry
(open-sse/config/providers/registry/) and metadata catalog
(src/shared/constants/providers/apikey/gateways.ts), following the same
passthrough-models pattern already used for kenari/x5lab/sumopod (live
/v1/models catalog resolves the model list instead of a hardcoded array).
Co-authored-by: Ahmad Putra Cahyo <CahyokPutraDev99@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2437
* chore(changelog): fragment for #7246
* test(provider): regen golden snapshot + bump family-count for Chenzk gateway
The Chenzk provider added in a616b88c9 registered a new APIKEY_PROVIDERS
entry (gateways.ts) but did not update the two characterization tests
that assert exact provider counts: the translate-path golden snapshot
(missing the chenzk entry) and the 167-entry family-merge count in
providers-constants-split.test.ts (now 168, verified as a strict
partition sum across the 6 family files, no loss/dup).
Co-authored-by: Ahmad Putra Cahyo <CahyokPutraDev99@users.noreply.github.com>
---------
Co-authored-by: Ahmad Putra Cahyo <CahyokPutraDev99@users.noreply.github.com>
* fix(sse): route the public OpenAI GPT-5.6 family through the Responses API
OpenAI's Chat Completions endpoint rejects GPT-5.6 requests that combine
function tools with an active reasoning_effort:
400 "Function tools with reasoning_effort are not supported for
<model> in /v1/chat/completions. Please use /v1/responses instead."
The openai (API-key) registry entries for gpt-5.6 / -sol / -terra / -luna
were missing the per-model `targetFormat` tag, so every request was posted
to /v1/chat/completions. Any agentic client sending tools + reasoning to
openai/gpt-5.6-sol hit the 400 and burned a combo fallback attempt.
OmniRoute already has the generic mechanism this needs — the same
per-model `targetFormat: "openai-responses"` override that routes
gpt-5.5-pro / gpt-5.4-pro (#5842). It drives BOTH the outbound URL
(DefaultExecutor.buildUrl → api.openai.com/v1/responses) and the body
translation (chatCore's resolveChatCoreTargetFormat → openai-responses).
Tagging GPT_5_6_API_CAPABILITIES is therefore the whole fix; no new
transport table or routing branch is required.
Scoped to the public OpenAI API catalog: the codex provider has its own
Responses transport and is untouched.
Co-authored-by: Sutarto Jordan Chrisfivo <Jordannst@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2547
* chore(changelog): fragment for #7242
---------
Co-authored-by: Sutarto Jordan Chrisfivo <Jordannst@users.noreply.github.com>
* feat(cli): add Grok Build CLI tool setup (~/.grok/config.toml)
Registers xAI's Grok Build TUI coding agent as a configurable CLI tool in
/dashboard/cli-code, so OmniRoute can write itself in as a custom model
provider in ~/.grok/config.toml.
Mechanism: Grok Build reads a TOML config that can hold several user-defined
[model.*] sections plus a [models].default pointer. Unlike the sibling Forge
handler (which owns its whole config file and can full-replace it), this one
surgically upserts ONLY the [model.omniroute] section and rewrites
[models].default, leaving every other section byte-intact. Apply records the
previous default in an `# omniroute-prev-default` marker comment so Reset can
restore the user's original default instead of guessing.
Built on OmniRoute's existing CLI-tools infrastructure rather than replaying
the upstream shape: getCliRuntimeStatus() for detection (no ad-hoc
`which grok` exec), Zod validation via cliModelConfigSchema, the write guard,
createBackup(), the cliToolState DB module, and sanitizeErrorMessage() for
every error path (Hard Rule #12).
Security: GET reaches getCliRuntimeStatus(), which spawns a child process to
locate and healthcheck the `grok` binary. That is the same transitive-spawn
surface that classified /api/skills/collect/, so the route is registered in
LOCAL_ONLY_API_PREFIXES and loopback-enforced before any auth check
(Hard Rules #15 + #17). Writing a local CLI's config file is inherently a
local-machine operation, so this costs no real capability.
Co-authored-by: rixzkiye <rizkiyemubarok05@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2571
* chore(changelog): fragment for #7241
* fix(cli): shrink cliTools.ts/cliRuntime.ts under the file-size ratchet + fix stale catalog counts
The grok-build registry/runtime entries pushed cliTools.ts (916->932) and
cliRuntime.ts (1128->1137) past their frozen file-size caps. Extract the
grok-build entries into cliToolsGrokBuild.ts (registry, typed) and
cliRuntimeGrokBuild.ts (runtime metadata, deliberately untyped/no
cliCatalog import so it doesn't drag that schema file into the
typecheck:core curated allowlist's transitive graph). The amp runtime
entry rides along in the same runtime file for the extra headroom needed
to clear cliRuntime.ts's cap with zero slack.
Also update the two catalog-cardinality canaries (cli-tools-schema.test.ts,
cli-catalog-counts.test.ts) and EXPECTED_CODE_COUNT to include grok-build:
20->21 visible code entries, 24->25 total code entries, 32->33 grand total.
Fixes CI reds on #7241 surviving a release/v3.8.49 merge: Fast Quality
Gates (check:file-size) and Unit Tests fast-path (1/4, 2/4).
* test(stryker): register grok-build route-guard test in tap.testFiles
check:mutation-test-coverage --strict flagged
tests/unit/route-guard-grok-build-settings-local-only.test.ts as a covering
unit test for src/server/authz/routeGuard.ts missing from
stryker.conf.json's tap.testFiles allowlist (only became reachable once the
Fast Quality Gates job got past the file-size fix earlier in this branch).
---------
Co-authored-by: rixzkiye <rizkiyemubarok05@gmail.com>
* feat(dashboard): add Type filter and easiest-first sort to Free Provider Rankings (#6915)
Adds sort/filter controls keyed on provider auth type (NOAUTH/OAUTH/APIKEY)
to /dashboard/free-provider-rankings so zero-setup providers can be
surfaced without eyeballing the Type column:
- Type filter chips (All / No Signup / OAuth Login / API Key), client-side
over the already-fetched rankings (no API change).
- "Easiest first" sort toggle groups NOAUTH < OAUTH < APIKEY while
preserving the existing score-descending order within each group
(stable sort).
- Type column legend/tooltip explaining what each auth type means.
- Pure filter/sort logic extracted to a new freeProviderRankingsAuthType.ts
module (no DB imports) rather than freeProviderRankings.ts, so importing
it from the "use client" page does not pull server-only DB wiring
(fs/path/better-sqlite3) into the client bundle; freeProviderRankings.ts
re-exports both for API/test parity.
- i18n keys added to en.json + __MISSING__ placeholders synced to all 42
locale mirrors (consistent with the existing untranslated-key convention).
* test(6915): move page test to tests/unit/ui so a runner actually collects it
The .test.tsx sat at tests/unit/ top-level, which no runner collects
(vitest ui filters on tests/unit/ui) — check:test-discovery flagged it as
a new orphan: the test never ran. Moved under tests/unit/ui/ and switched
the dynamic import to the @/ alias (the convention of its neighbours).
6/6 now pass under test:vitest:ui.
* fix(types): explicit unknown hop on the getProviderConnections cast (#6915)
The dashboard-typecheck gate (added by #7203, after this branch was cut)
scopes tsc to the src/app/(dashboard) import graph. This PR's page.tsx now
imports freeProviderRankingsAuthType, which type-imports freeProviderRankings
— dragging that module into the graph for the first time and surfacing its
pre-existing TS2352 (JsonRecord[] -> ConnectionState[] is a structural subset).
Fixed the cast rather than widening the frozen baseline.
* fix(api): bulk-add API keys no longer overwrite existing connections
createProviderConnection upserts apikey connections BY NAME (same provider +
auth_type "apikey" + same name updates the row in place, replacing its
apiKey/priority/testStatus instead of inserting). The bulk-add route
auto-names unnamed lines "Key 1", "Key 2", ... restarting from 1 on every
request, blind to names already saved for the provider — so re-running a
bulk paste against a provider that already had "Key 1" silently replaced it
instead of adding a new connection alongside it. The same collision could
also happen within one batch for two identical custom name|apiKey lines.
Add resolveBulkNameCollisions (src/shared/utils/bulkApiKeyParser.ts): gap-fills
the smallest free "<name> <n>" suffix against both existing connection names
and names already assigned earlier in the same batch, so a name is never
reused. Wire it into POST /api/providers/bulk before the create loop, fetching
existing apikey connection names via the existing getProviderConnections db
module (no raw SQL added to the route).
Co-authored-by: asynx6 <sahrulbeni656@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2587
* chore(changelog): fragment for #7234
---------
Co-authored-by: asynx6 <sahrulbeni656@gmail.com>
Codex Responses API strict mode forces every "optional" tool property into
`required`, so a model that intends to OMIT an optional enum property (no
declared `default`, e.g. Agent.isolation: enum["worktree","remote"]) must
still emit a concrete value. Neither of the two ops shipped in #6992
(drop-if-default, generalized drop-if-empty) can catch this: drop-if-default
needs a declared default (none exists); drop-if-empty needs an empty
string/array (the emitted value is non-empty).
Adds a paired request/response transform scoped strictly to
targetFormat === OPENAI_RESPONSES:
- Request side: injectOptionalEnumOmissionSentinel/-ForTools widen no-default
optional enum properties to accept `null` (OpenAI's own documented
nullable-union idiom for this exact strict-mode limitation).
- Response side: isDroppableNullEntry drops the key when the model emits
`null` for a non-required, schema-declared property, reusing the existing
#6992 toolSchemas plumbing (no new tracking structure needed).
* feat(providers): editable ComfyUI base-URL field + per-connection override for image/video/music generation (#6928)
Adds a shared resolveComfyUiBaseUrl() helper (open-sse/utils/comfyuiClient.ts) that
prefers a per-connection providerSpecificData.baseUrl override over the registry
default, wired through the comfyui dispatch branch in the image, video, and music
generation handlers plus a best-effort authType:"none" credential lookup in all
three /v1/{images,videos,music}/generations routes (never hard-fails when no
connection exists, so zero-config localhost users are unaffected).
Surfaces an editable base-URL field on the ComfyUI connection form by adding it to
CONFIGURABLE_BASE_URL_PROVIDERS / DEFAULT_PROVIDER_BASE_URLS /
getProviderBaseUrlPlaceholder in providerPageHelpers.ts, so Docker-network setups
(e.g. http://comfyui:8188) can be configured the same way self-hosted chat
providers are.
Closes#6928
* refactor(6928): extract local-override credential lookup in media routes
The inline per-connection override block nested if>if inside the music and
videos POST handlers, taking each to cognitive complexity 16 (>15) — two NEW
violations that broke check:complexity-ratchets (892 > baseline 890).
Extracted resolveLocalOverrideCredentials() in both routes; behaviour is
unchanged. cognitive-complexity back to 890 = baseline.
* feat(dashboard): replace free-text model inputs with hidePaid-aware Selects (#6540)
Swap RoutingTab.webSearchRouteModel, ComboDefaultsTab.handoffModel, and
BackgroundDegradationTab's from/to fields from free-text inputs to a new
shared ModelSelectField fed by the already hidePaidModels-aware
GET /api/models, with an off-catalog "(custom)" fallback so an existing
saved value is never silently dropped. ModelRoutingSection's glob pattern
field gets a fail-open "matches only paid models" warning instead, since
it's a wildcard matcher rather than a single model id.
Adds save-time paid-target rejection (PAID_MODEL_TARGET_BLOCKED, 400) on
PATCH /api/settings, PATCH /api/settings/combo-defaults, and PUT
/api/settings/background-degradation when hidePaidModels is on, failing
open for aliases/combo names/unrecognized providers.
globToRegex is extracted from lib/db/modelComboMappings.ts into a new
dependency-free shared/utils/globPattern.ts so both the DB module and the
new client-side pattern heuristic reuse the same regex-building logic.
* refactor(6540): extract paid-target guard in background-degradation PUT
The inline hidePaid check nested if>if>for>if inside the PUT handler,
pushing its cognitive complexity to 16 (>15) — a NEW violation that broke
the check:complexity-ratchets gate (891 > baseline 890). Extracted the
check into a module-local hasBlockedPaidTarget() helper; behaviour and
response body are unchanged. cognitive-complexity back to 890 = baseline.
* fix(i18n): mirror paidModelPatternWarning into pt-BR.json (#6540)
The new key landed only in en.json; the i18n pt-BR integrity test
(no drift, #6695) requires pt-BR.json to carry every en.json key.
* feat(mitm): add Antigravity reasoning-effort overrides
The Antigravity MITM alias mapping only ever swapped the destination model;
there was no way to override the reasoning effort Antigravity's own
thinkingConfig requested. Alias entries are now `{ model?, reasoningEffort? }`
(a legacy plain-string mapping still normalizes to `{ model }`, so no DB
migration is required). The standalone proxy (server.cjs) forwards the chosen
tier as a top-level `reasoningEffortOverride` on the intercepted request; the
antigravity->openai translator honors it ahead of its thinkingConfig-derived
guess, and an explicit "none" suppresses reasoning_effort entirely even when
Antigravity's own request asked for thinking. Reuses the existing canonical
5-tier reasoning vocabulary (`@/shared/reasoning/effortStandardization.ts`,
with max/extra aliasing to xhigh) instead of introducing a new one. The API
route validates the reasoning-effort value at the boundary and the Antigravity
tool card UI now exposes a per-model reasoning-effort selector alongside the
existing model-mapping input.
Co-authored-by: Truong Fiu <gnourtf@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2584
* chore(changelog): fragment for #7228
---------
Co-authored-by: Truong Fiu <gnourtf@gmail.com>
* feat(sse): route GitHub Copilot Claude models through native /v1/messages
GitHub Copilot's /chat/completions and /responses endpoints never surface
prompt-cache token counts (cached_tokens) for Claude models, and round-tripping
Claude tool_use/tool_result/thinking content blocks through the OpenAI shape
is lossy. Copilot also exposes an Anthropic-native /v1/messages shim that
reports cached_tokens correctly and accepts native content blocks as-is.
Tag each github registry claude-* model with targetFormat: "claude" so
chatCore.ts translates the request to Anthropic-native shape before the
executor ever sees it (the same mechanism opencode/zen's Qwen entries and
opencode/go already use), and teach the github executor's buildUrl() /
buildHeaders() to dispatch those models at the new messagesUrl
(api.githubcopilot.com/v1/messages) with the required anthropic-version
header. transformRequest() now skips its /chat/completions-only quirks
(content-part flattening, trailing-assistant-prefill drop, the
response_format-as-system-prompt workaround) for the native path — the first
would destroy native tool_use/tool_result blocks, the prefill drop is
unnecessary because the real Anthropic API supports assistant prefill, and
the response_format workaround is superseded by the generic openai-to-claude
translator's own JSON-mode handling.
Co-authored-by: luoyide <ydhome.code@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2608
* chore(changelog): fragment for #7223
* fix(sse): green PR #7223 CI — complexity ratchet + stale test expectations
- Extract applyChatCompletionsOnlyQuirks() and resolveInitiatorHeader()
out of GithubExecutor.transformRequest()/buildHeaders() so the two
methods drop back under the complexity/cognitive-complexity ratchets
(2058/891 -> 2056/890, matching the frozen baseline). No behavior
change — same guards, just relocated.
- Update 4 pre-existing unit tests that hard-coded now-native claude-*
Copilot ids (claude-sonnet-4.5/4.6) to exercise the /chat/completions
legacy path via an unregistered id (claude-sonnet-4), matching the
sibling test already using that pattern. These ids now intentionally
route to the native /v1/messages shim added by this PR, which
correctly skips the /chat/completions-only workarounds these tests
were built to verify — the native path's own coverage lives in
github-copilot-claude-native-messages.test.ts.
- Split the routing invariant test (copilot-gemini-claude-route-no-responses.test.ts)
into a Claude case (expects /v1/messages) and a Gemini case (still
expects /chat/completions), reflecting the intentional routing change.
---------
Co-authored-by: luoyide <ydhome.code@gmail.com>
Extracts the routing-combo compression-mode dropdown (Default/Off/Lite/
Standard/Aggressive/Ultra) from the combo card into a shared
ComboCompressionModeSelect component, reused on both the combo card
(compact) and the Compression Combos page's "Assign to routing" list
under Context & Cache. Both surfaces persist through the existing
PUT /api/combos/{id} route -- no backend or schema change.
* feat(dashboard): add reorder-by-availability button to provider connections
Adds a "Reorder" action to the provider detail Connections toolbar that
sorts a provider's connections so available ones float to the top and
unavailable ones sink to the bottom, then persists the new order via the
existing per-connection priority PUT endpoint (same pattern already used
by handleSwapPriority).
Availability is computed with OmniRoute's own resilience model rather than
upstream's `modelLock_*` convention: a connection counts as available when
its effective status (testStatus, adjusted for the lazy connection-cooldown
window via rateLimitedUntil) is active/success — mirroring the exact logic
ConnectionRow already uses for its status badge, so the button and the row
badges never disagree. The sort is a stable Array.prototype.sort, so
connections keep their relative order within each availability group.
New pure helpers (sortConnectionsByAvailability, isConnectionAvailable,
getConnectionEffectiveStatus) live in connectionRowHelpers.ts and are
covered by a dedicated unit test, including the cooldown-lazy-recovery
edge case. i18n keys added to all 43 locales.
Co-authored-by: Fazril Syaveral Hillaby <fazriloke18@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2558
* chore(changelog): fragment for #7211
* fix(dashboard): extract reorder-by-availability into its own hook (file-size ratchet)
The reorder-by-availability feature pushed useProviderConnections.ts to 974
lines, past its frozen file-size cap (954). Extract the handler + its state
into a dedicated useReorderByAvailability hook, following the same pattern
already used for useModelVisibilityHandlers/useModelImportHandlers — no
behavior change, same tests still cover the sort logic in
connectionRowHelpers.ts.
* fix(dashboard): type the reorder hook's notifier explicitly (dashboard-typecheck TS2339)
ReturnType<typeof useNotificationStore> resolves to unknown under the
dashboard-scoped tsconfig gate (#7203), so notify.error tripped TS2339.
The hook only needs error(), so declare that minimal surface directly.
---------
Co-authored-by: Fazril Syaveral Hillaby <fazriloke18@gmail.com>
* feat(dashboard): show Codex plan label in provider and quota views
ConnectionRow on the provider-detail page never surfaced the Codex
subscription plan captured at OAuth import time
(providerSpecificData.chatgptPlanType, src/lib/oauth/services/codexImport.ts)
anywhere in the row UI. Added a small pure helper, getCodexPlanLabel, and a
Badge in ConnectionRow gated on isCodex.
Separately, the quota view's plan-badge machinery (resolvePlanValue /
tierByConnection / QuotaCardHeader) already existed for all providers, but
its persisted-metadata fallback list omitted chatgptPlanType. When the live
Codex usage endpoint has no plan_type/planType field, the usage service
reports the literal string "unknown" (open-sse/services/usage/codex.ts),
which resolvePlanValue's normalizePlanCandidate() filters out — so the quota
badge fell through to "Unknown" instead of the plan captured at login.
Added chatgptPlanType to the persisted candidate list.
Co-authored-by: Carmelo Campos <carmelogunsroses@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2570
* chore(changelog): fragment for #7210
* fix(dashboard): extract getCodexPlanLabel to unfreeze providerPageHelpers.ts
The Fast Quality Gates file-size ratchet froze
providerPageHelpers.ts at 1053 lines; adding getCodexPlanLabel
inline pushed it to 1067. Move the self-contained helper into its
own codexPlanLabel.ts module instead of growing the frozen file,
and repoint ConnectionRow.tsx + the regression test at the new
location. No behavior change.
---------
Co-authored-by: Carmelo Campos <carmelogunsroses@gmail.com>
* feat(kiro): register GPT-5.6 Sol/Terra/Luna model family
Kiro announced its first OpenAI-family models on 2026-07-14
(kiro.dev/changelog/models): GPT-5.6 Sol (flagship), Terra (balanced
mid-tier) and Luna (fastest/cheapest), all sharing a 272k context
window. Registers the three base model ids in the kiro provider
registry with contextLength/maxOutputTokens so getResolvedModelCapabilities()
resolves the real 272k window instead of falling back to the generic
default. OmniRoute derives the thinking/agentic synthetic variants and
per-account rate multipliers dynamically at discovery time
(open-sse/services/kiroModels.ts), so only the three base entries need
static registration here.
Co-authored-by: Edison42 <gn00742754@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2596
* chore(changelog): fragment for #7209
* fix(kiro): add GPT-5.6 Sol/Terra/Luna pricing rows
The registry additions in this PR exposed three new Kiro model ids
without matching pricing rows, tripping the catalog invariant that
every Kiro registry model must resolve a non-zero pricing row
(tests/unit/catalog-updates-v3x.test.ts) — the models would have
billed at $0.00.
Reuses the shared GPT_5_6_{SOL,TERRA,LUNA}_PRICING tiers already used
by the codex and openai aliases.
---------
Co-authored-by: Edison42 <gn00742754@gmail.com>
* fix(cli): fast-path --version to skip full CLI bootstrap
`omniroute --version` ran the entire CLI bootstrap before printing the
version: the tsx/esm + polyfill imports, env-file loading, and
Commander's ~70-command registration (importing DB, providers, OAuth,
and other heavy modules). That took ~1.5s just to print a version
string.
Add isVersionFastPath() (bin/cli/utils/versionFastPath.mjs) and check it
at the very top of bin/omniroute.mjs, before any of that work runs. It
only trips for an unambiguous bare `--version`/`-V` invocation (no other
args), so it never changes behavior for real commands or for `--help`
(whose output is generated dynamically from every registered
subcommand, so it still needs full registration and is deliberately not
fast-pathed).
`--version` now returns in ~0.3s instead of ~1.5s locally.
Co-authored-by: Sutarto Jordan Chrisfivo <Jordannst@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2414
* chore(changelog): fragment for #7208
* fix(build): enforce bin/cli/utils/versionFastPath.mjs in the pack-artifact gate
bin/omniroute.mjs now imports ./cli/utils/versionFastPath.mjs on its boot path
(the --version fast-path). bin/cli/ is only an allowlist PREFIX, so the file
vanishing from the npm tarball would never fail the unexpected-paths check --
only PACK_ARTIFACT_REQUIRED_PATHS makes its absence loud (#7065 class).
Adds the required path and updates the hardcoded expectation in
pack-artifact-policy.test.ts, matching the existing data-dir.mjs /
storageKeyProvision.mjs entries. Fixes the red in
tests/unit/pack-artifact-entrypoint-closures.test.ts, which derives the
requirement from the entrypoint's own imports.
---------
Co-authored-by: Sutarto Jordan Chrisfivo <Jordannst@users.noreply.github.com>
* fix(translator): register openai response projection for gemini clients
The response-translator registry had an OpenAI -> Antigravity response
projection registered, but no OpenAI -> Gemini one. When a client request is
detected as Gemini format (body-shape match on `contents: [...]`, per
detectFormat()) and combo routing lands the request on an OpenAI-native
provider, translateResponse() fell through its hub-and-spoke path with no
`openai -> gemini` translator registered, so the raw OpenAI
`chat.completion.chunk` shape reached the client unchanged instead of the
shared Gemini `response.candidates[]` envelope.
Registers FORMATS.OPENAI -> FORMATS.GEMINI reusing the existing
openaiToAntigravityResponse projection — Gemini and Antigravity already
share the same wrapped `{ response: { candidates: [...] } }` envelope
elsewhere in the pipeline (see the unwrapGeminiChunk callers in
open-sse/utils/stream.ts, which treat FORMATS.GEMINI and FORMATS.ANTIGRAVITY
identically), so no new conversion logic is introduced.
Co-authored-by: W ARELIK <warelik@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2399
* chore(changelog): fragment for #7207
---------
Co-authored-by: W ARELIK <warelik@users.noreply.github.com>
* fix(translator): preserve Gemini thought parts as reasoning_content on the OpenAI request bridge
Gemini thinking-mode output marks internal reasoning with `part.thought === true`
inside a content's `parts` array. geminiToOpenAIRequest() ran every part (thought
or not) through the same text-part branch, so a thought part was merged straight
into the message's visible `content` — leaking private reasoning into whatever the
OpenAI pivot forwarded downstream, and hiding it from Reasoning Replay Cache (which
only ever inspects `reasoning_content`).
Add convertGeminiContentWithReasoning(): split out `thought: true` parts before
delegating to the existing convertGeminiContent(), then re-attach the joined
thought text as `reasoning_content` on the resulting message (skipping tool/
functionResponse messages, whose schema has no such field). Non-strict-provider
stripping and reasoning-replay injection in translator/index.ts are untouched —
this only fixes what reasoning_content gets populated with on this one inbound
hop.
Co-authored-by: W ARELIK <warelik@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2401
* chore(changelog): fragment for #7206
---------
Co-authored-by: W ARELIK <warelik@users.noreply.github.com>
tryAwsSsoCache() only resolved clientId/clientSecret via data.clientIdHash -> <hash>.json. Newer kiro-auth-token.json files instead carry a top-level clientId directly, so that lookup silently failed and left clientId/clientSecret null, sending the dashboard's Import Token POST down the non-IDC path. That path (KiroService.validateImportToken -> readCachedClientCredentials) picked a client registration by region + latest-expiry across ALL cached SSO client registrations, ignoring the token's actual clientId — on a machine with multiple stale registrations this returned a mismatched clientId/clientSecret pair, producing 'Bad credentials' on refresh.
Fix: resolve clientId/clientSecret by scanning the cache for a registration file whose own clientId matches the token's clientId (falling back to clientIdHash first, then a direct-match scan), and thread an optional clientId hint into readCachedClientCredentials()/validateImportToken() so an exact match always wins over the region/latest-expiry heuristic.
Reported-by: Asher (@XCrag) (https://github.com/decolua/9router/issues/1253)
* fix(providers): add MiniMax image-generation provider (port from 9router#2482)
MiniMax already had entries in the music/audio/video registries, but no entry at all in imageRegistry.ts and no dedicated provider handler under open-sse/handlers/imageGeneration/providers/. A MiniMax image-model request therefore fell through the format dispatch in imageGeneration.ts to a 404/unmatched-format response instead of reaching MiniMax's synchronous image_generation endpoint.
Registers a minimax image provider (format: minimax-image, models image-01/image-01-live) and a new handleMinimaxImageGeneration handler that POSTs to https://api.minimax.io/v1/image_generation and normalizes data.image_urls into the OpenAI-compatible images payload.
Reported-by: felipeleite (https://github.com/decolua/9router/issues/2482)
* refactor(providers): split KIE image catalog out of imageRegistry to respect file-size cap
imageRegistry.ts hit 805 lines after adding the MiniMax image provider (cap is
800). Extract the KIE image-model catalog (largest single provider entry,
~35 models) into its own semantic-family module,
providers/registry/kie/imageModels.ts, following the same pattern already
used for LMARENA_DIRECT_IMAGE_MODELS. imageRegistry.ts now imports
KIE_IMAGE_MODELS instead of inlining the list.
Also update minimax-media-servicekinds.test.ts: getRegistryMediaKinds derives
membership by design from every registry in MEDIA_KIND_REGISTRIES, including
IMAGE_PROVIDERS. Now that minimax is a key in IMAGE_PROVIDERS, it correctly
gains the "image" kind alongside tts/video/music — the same behavior already
asserted for openai in this file. The exact-match assertion is updated to
["image","music","tts","video"]; the other assertions (which only check
.includes for tts/video/music/llm) were already correct and untouched.
* fix(providers): extract minimax image-gen helpers to fix complexity ratchet
check:complexity-ratchets regressed 2056 -> 2058 (handleMinimaxImageGeneration:
complexity 25, max-lines-per-function 97). Split logging, upstream-error,
no-images, success and fetch-error branches into small named helpers so the
handler stays within the cyclomatic-complexity (15) and max-lines-per-function
(80) ratchets. No behavior change; existing minimax-image-provider-2482 and
minimax-media-servicekinds unit tests still pass.
* feat(providers): curated OpenRouter embeddings catalog + specialty merge in live discovery (#6976)
OpenRouter serves embeddings via a dedicated OpenAI-compatible
/api/v1/embeddings endpoint that is omitted from /v1/models, and the
embeddingRegistry entry for it was stale (3 legacy ids). Meanwhile
providerModelsConfig gives openrouter a live discovery config, so
buildApiDiscoveryResponse's success path returned only the live chat
catalog verbatim — the specialty (embeddings/rerank) static catalog was
only ever merged in on the no-config local_catalog fallback, so OpenRouter
embeddings never surfaced through model discovery.
Refreshed the curated openrouter embeddingRegistry lineup (ids verified
against https://openrouter.ai/docs/api/reference/embeddings and the
collections page) and added a scoped, additive merge
(mergeSpecialtyCatalogIntoLiveModels, allowlisted to openrouter) that folds
embeddings/rerank entries from getStaticModelsForProvider() into the live
discovery response, deduped by id. Scoped as an allowlist rather than a
blanket merge because some providers (e.g. Gemini) already return
embedding models directly from their live /v1/models endpoint, where a
blind merge would risk stale/duplicate entries.
* test(providers): type the models discovery payload instead of any (#6976)
no-explicit-any is an error under tests/ (#6218), so the 4 `any`
usages in the new discovery assertions failed the max-warnings-0
lint gate. Replace them with an explicit ModelsResponseBody shape —
type-only change, all 13 assertions unchanged and still passing.
* test(providers): type the openrouter merge assertion callback (#6976)
The new #6976 assertion added a 56th explicit `any` to this file,
one over the 55 frozen in config/quality/eslint-suppressions.json,
tripping the max-warnings-0 lint gate. Type the callback param
instead of raising the frozen count — the debt ratchet only decreases.
All 59 tests still pass.
* fix(dashboard): hide disabled provider connections from combo builder
The combos page's fetchData() only filtered available connections by
testStatus ("active"/"success"), so a connection the user had
explicitly disabled (isActive: false) could still show up in the
combo builder if it carried a stale testStatus from before it was
disabled.
Add filterActiveConnections() in src/shared/utils/connectionStatus.ts
and apply it ahead of the existing testStatus filter.
Co-authored-by: itolstov <attid0@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2526
* chore(changelog): fragment for #6984
* fix(combos): keep combos page within frozen size cap
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(combos): extract filterUsableConnections to shrink the combos god-file
The combos page only filtered provider connections on testStatus, so a
connection the user had explicitly disabled survived with a stale
"active"/"success" status. The isActive + testStatus gate now lives in
the shared connectionStatus util as filterUsableConnections(), which the
page calls in a single line.
This keeps src/app/(dashboard)/dashboard/combos/page.tsx BELOW its frozen
file-size cap (4653 vs 4655 congelado — the file shrinks by 2 lines vs the
release tip) without touching config/quality/file-size-baseline.json, as
the gate asks ("modularize/extraia (DRY) para encolher").
The regression test now exercises filterUsableConnections directly instead
of hand-mirroring the page's filter chain, so it guards the real code path.
Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>
* fix(combos): drop nullish entries in filterActiveConnections
`connection?.isActive !== false` evaluated to true for null/undefined
entries, so nullish elements survived the filter. Callers read properties
off the result — filterUsableConnections() reads `connection.testStatus`
— which would throw "TypeError: Cannot read properties of null".
Guard with an explicit truthiness check. Covered by a test that fails
against the previous predicate.
Reported-by: gemini-code-assist
Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>
---------
Co-authored-by: itolstov <attid0@gmail.com>
getStaticModelsForProvider() only defined literal catalogs for
linkup-search, ollama-search, and searchapi-search out of the 12 ids in
SEARCH_PROVIDERS. The other 9 (serper-search, brave-search,
perplexity-search, exa-search, tavily-search, google-pse-search,
youcom-search, searxng-search, zai-search) returned undefined and hit
the 400 "does not support models listing" tail in the models route
during the "Import Models" step.
Instead of adding 9 more one-off literal entries, generalize the class:
when a provider has no dedicated STATIC_MODEL_PROVIDERS entry, fall
back to a catalog derived from SEARCH_PROVIDERS[id].searchTypes (every
search-registry entry already declares this). Future search providers
added to searchRegistry.ts automatically get a usable catalog with zero
extra code.
Closes#7529
ResponsesWsSession.persistHistory() guarded on a single historyLogged
boolean set once for the lifetime of the WebSocket connection. When a
Codex client reuses one connection for multiple sequential
response.create turns, only the first terminal event was persisted to
call_logs — every subsequent turn's usage/history was silently
dropped. firstResponseBody had the same per-connection freeze (||=),
so even a hypothetical second log entry would still carry turn 1's
request body.
Replace the boolean with a Set keyed by the terminal event's
response.id (falling back to a session-scoped sentinel for
session-ending failure paths that don't carry a response id: prepare
failure, upstream error/close, connect failure), and track each
turn's own request body via currentRequestBody instead of freezing on
firstResponseBody. This logs exactly once per logical turn while
keeping session-ending failures logged exactly once, and each logged
call now carries its own terminal response id and request payload.
Regression test: tests/unit/responses-ws-proxy-multi-turn-history.test.ts
opens one WS connection, sends two response.create turns, and asserts
two distinct call-log entries land at the internal bridge, each with
its own response id and request body.
Closes#7388
* fix(sse): sanitize empty-signature thinking blocks + hoist strict-provider system messages (#6953, #7293)
#6953: prepareClaudeRequest's "preserve latest-assistant thinking verbatim"
guard (claudeHelper.ts, anti-400 for legitimate Anthropic replay) did not
distinguish a genuine Claude signature from an empty one fabricated by a
non-Anthropic leg (e.g. codex reasoning_content). It forwarded signature:""
verbatim to Anthropic, which always 400s ("Invalid signature in thinking
block"), permanently locking combo routing onto the non-Anthropic leg. The
response-side half of this bug (openai-to-claude.ts synthesizing the empty
signature in the first place) was already fixed by #6982/PR#6982; this PR
closes the remaining request-side half. Fix: the verbatim-preserve guard now
requires every thinking-ish block on the latest assistant message to carry a
non-empty signature/data; otherwise it falls through to the existing
sanitization path (redacted_thinking + DEFAULT_THINKING_CLAUDE_SIGNATURE)
already applied to older turns.
#7293: translateRequest() is the single outbound choke point every chat
request passes through, including same-format (OpenAI→OpenAI) passthrough
where none of the format-specific translators run. systemMessageMustBeFirst()
/ PROVIDERS_SYSTEM_MUST_BE_FIRST (src/lib/memory/injection.ts, #6135/PR#6225)
was only consulted by the memory injector, so a client-injected system
message landing mid-array (OpenCode/Kilo Code style clients, Discussion
#6129) reached strict providers (xiaomi-mimo) untouched and 400'd. Fix: a new
helper (open-sse/translator/helpers/strictSystemHoist.ts) hoists every system
message onto index 0 for strict providers, reusing systemMessageMustBeFirst()
as the single source of truth, merging (never dropping) multiple offenders in
original order, and no-op'ing (same array reference) for non-strict providers
and already-compliant requests to preserve prompt-cache prefix stability.
Both defects live in the same file cluster (openai-to-claude request-path
translator + its helpers), hence one PR for both issues per triage guidance.
Regression tests:
- tests/unit/repro-6953.test.ts — RED (actual signature:'' forwarded) → GREEN
- tests/unit/probe-7293-strict-system-hoist.test.ts — RED (system message
left at index 10 of 70) → GREEN, plus multi-offender merge, existing-leading
merge, non-strict-provider no-op, and already-compliant no-op cases.
Gates run: file-size, complexity, cognitive-complexity (both at/under
baseline), typecheck:core (clean), eslint on changed files (clean),
test:vitest (254/254 green), plus all directly relevant existing suites
(translator-claude-helper-thinking, translator-xiaomi-mimo-reasoning-replay,
memory-system-first-6135, dashscope-cache-control-openai-2069,
xiaomi-mimo-provider, role-normalizer, translation.golden,
translators.property, translator-helper-branches, translator-claude-to-openai,
translator-same-format-null-flush — all green).
Closes#6953Closes#7293
* chore(quality): prune the now-stale claudeHelper no-explicit-any suppression (#6953)
The #6953 fix removed the single `any` that config/quality/eslint-suppressions.json
still had frozen for open-sse/translator/helpers/claudeHelper.ts, so the entry became
stale and ESLint's stale-suppression enforcement failed the 'No new ESLint warnings'
gate — the gate went red because the code got better.
Pruned that one entry only (never a global --prune-suppressions: other entries are
other sessions' frozen debt).
Z.AI's glm-4.6v vision endpoint enforces a 32768 max_tokens ceiling
server-side and 400s when a client sends a larger explicit max_tokens (e.g.
a client defaulting to 65536). paramSupport.ts's STRIP_RULES already has a
working clampToModelMaxOutput/maxOutputCap mechanism (used today for a
VolcEngine Kimi rule) but had no entry for zai/glm + glm-4.6v.
Added two rules: "zai" uses a fixed maxOutputCap (glm-4.6v is only reachable
there as a custom model attached to the connection, so it is not in
PROVIDER_MODELS["zai"] and clampToModelMaxOutput would find no catalog
ceiling); "glm" uses clampToModelMaxOutput (glm-4.6v IS in the registry
catalog there, GLM_SHARED_MODELS, maxOutputTokens: 32768).
Also discovered and fixed a second, deeper bug the "glm" rule alone would
not have caught: GlmExecutor.execute() drives its own fetch flow
(executeTransport()/transformForTransport()) and never runs through
DefaultExecutor.execute()'s stripUnsupportedParams() call site — so a
STRIP_RULES clamp entry for provider "glm" was dead code until
transformForTransport() now calls stripUnsupportedParams() directly.
Regression tests: tests/unit/zai-glm-max-tokens-clamp-7364.test.ts (reused
from the triage plan-file's RED probe, sanity assertion updated to lock the
fix instead of the bug) and tests/unit/glm-executor-max-tokens-clamp-7364.test.ts
(proves the real GlmExecutor.transformForTransport wiring, not just the
STRIP_RULES entry in isolation).
Gates run: check-file-size, check-complexity, check-cognitive-complexity,
typecheck:core, eslint (suppressions), tests/unit/zai-glm-max-tokens-clamp-7364.test.ts,
tests/unit/glm-executor-max-tokens-clamp-7364.test.ts,
tests/unit/executors-strip-unsupported-params.test.ts,
tests/unit/nvidia-minimax-thinking-strip.test.ts, tests/unit/glm-executor.test.ts — all green.
Refs #7364
DefaultExecutor.buildUrl()'s "zai"/"glm-coding-apikey" case always returned
the Anthropic Messages URL, ignoring a per-model targetFormat override
(custom-model dropdown, #2905) that resolves to "openai" — e.g. for a vision
model like glm-4.6v. chatCore/executionCredentials.ts now threads the
resolved override onto providerSpecificData.targetFormat so buildUrl (via
the new default/zaiFormatOverride.ts helper, extracted to respect the
file-size ratchet) can route to the OpenAI-compatible endpoint instead.
Separately, custom-model id lookup (lookupCustomModelMeta in
src/sse/services/model.ts, getCustomModelRow in src/lib/db/models.ts) did an
exact, case-sensitive match, so a model saved as "glm-4.6v" was invisible
when looked up as "glm-4.6V". Both now fall back to a case-insensitive match
after the exact match fails.
Regression tests: tests/unit/zai-glm-target-format-override.test.ts (reused
from the triage plan-file's RED probe) and
tests/unit/zai-execution-credentials-target-format-7364.test.ts (production
wiring in executionCredentials.ts).
Gates run: check-file-size, check-complexity, check-cognitive-complexity,
typecheck:core, eslint (suppressions), tests/unit/zai-glm-target-format-override.test.ts,
tests/unit/zai-execution-credentials-target-format-7364.test.ts,
tests/unit/executor-default-base.test.ts, tests/unit/custom-model-target-format.test.ts,
tests/unit/chatcore-execution-credentials.test.ts, tests/unit/chatcore-target-format.test.ts,
tests/unit/model-resolver.test.ts, tests/unit/model-alias-provider-resolution.test.ts,
tests/unit/combo-custom-provider-resolution.test.ts — all green.
Refs #7364
detectBinary() in tool-detector.ts never checked process.platform and never
passed shell:true, so on native Windows an installed CLI (npm installs
claude/codex/opencode as .cmd shims) was reported as NOT installed:
1. execFileImpl(binary, ["--version"]) fails without shell:true for .cmd
shims (Node's CVE-2024-27980 hardening).
2. the `which` fallback doesn't exist on native Windows (no WSL/git-bash).
Both threw, both were swallowed by empty catches, detectBinary returned
{installed: false}. cliRuntime.ts::locateCommand already solved this for the
runtime-spawn path (#968) but never propagated here — re-drift, per the
issue title.
Exports locateCommand from cliRuntime.ts and reuses it (+ shouldUseShellForCommand,
+ getLookupEnv) for the win32 existence/path probe in tool-detector.ts, keeping
the --version probe local but shell-gated. Also routes the which fallback through
the injectable execFileImpl hook (it previously called the raw execFileAsync,
making it unmockable and prone to false-positives from a real system which).
Root cause: waitForImageViaWebSocket() only parsed the singular
update_content.message (object) / payload.message / data.message shapes
in the celsius WebSocket frames chatgpt.com uses to deliver async
image_gen results. Some chatgpt.com deployments deliver the completed
tool-role image_asset_pointer message inside update_content.messages[]
(a plural array of { message: {...} } wrappers) instead, which produced
zero candidates, so the listener idled out the timeout and the request
failed with the generic 'ChatGPT Web completed without returning image
markdown' 502 with no x_image_resolution_failed flag.
Fix: also read update_content.messages[] and push each wrapped message
into the same candidate pipeline used for the singular shape.
Regression test: tests/unit/chatgpt-web-async-image-ws-shapes-7357.test.ts
drives the real ChatGptWebExecutor.execute() end-to-end (real SSE
parsing, real pollForAsyncImage()/waitForImageViaWebSocket()), mocking
only the network edges (tlsFetchChatGpt + global WebSocket), and proves
the plural-array frame now resolves to image markdown instead of being
dropped.
Gates run: check-file-size (OK), check-complexity (OK, 2054 <= 2056
baseline), check-cognitive-complexity (OK, 889 <= 890 baseline),
typecheck:core (clean), eslint on changed files (clean), full
tests/unit/chatgpt-web.test.ts (89/89), chatgpt-web-image-silentdrop.test.ts,
chatgpt-web-tools-5240.test.ts, chatgpt-web-models-split.test.ts,
chatgpt-web-sha3-boringssl-5531.test.ts, chatgpt-web-handoff-resume.test.ts,
chatgpt-web-citations(-escape).test.ts all pass.
captureCurrentProviderRequest mirrors every Bedrock Converse request into the
pending-request log tracker right after openAIToBedrockConverse() builds it,
including the decoded image.source.bytes Uint8Array. sanitizePayloadPII() and
redactPayload() in src/lib/logPayloads.ts both gate their recursive walk on
Array.isArray(), which is false for typed arrays, so each image fell into the
generic-object branch and got enumerated one JS key per decoded byte (twice,
once per function) before any truncation bound applied. For 3x ~1MB images
this took ~4s of synchronous, event-loop-blocking work, matching the
reporter's "1-2 images OK, 3+ fails" threshold and their --stack-size
observation (data-width pressure, not call-depth).
Add an opaque-binary short-circuit (ArrayBuffer.isView) ahead of the
Array.isArray branch in both functions, returning a fixed-size placeholder
instead of recursing. Apply the same guard to cloneBoundedForLog() in
open-sse/utils/requestLogger.ts for defense-in-depth (same blind spot, only
accidentally safe today via its own key-count slice).
Regression test reproduces the exact reporter shape (3x 1MB images) through
the real openAIToBedrockConverse() converter and protectPayloadForLog(),
asserting completion well under the previous ~4s and that binary bytes are
never expanded into per-byte object keys.
resolveRequestedModel() only special-cased "auto" and the composer
"-fast" suffix; every pinned Claude/GPT id carrying an effort/reasoning
suffix (e.g. "claude-opus-4-8-high", "gpt-5.5-high") fell through and
was sent to cursor's server verbatim as model_id, with an empty
parameters array. Cursor has no route for the suffixed id -- it only
knows the base id plus an out-of-band ModelParameter -- so it accepted
the request but returned an empty turn.
Split the known effort suffixes (-low/-medium/-high/-xhigh/-max) off
the base id: Claude ids surface an {id:"effort", value} parameter,
GPT ids surface {id:"reasoning", value}, matching the real cursor-agent
client's wire format. encodeAgentRunRequest()'s ModelDetails fields
derive from the same resolved base id, so the #3714 pinned-model
ModelDetails envelope stays correct without further changes.
Updates the existing resolveRequestedModel test that locked in the
buggy verbatim pass-through, and the #3714 ModelDetails test to assert
against the base id. Adds a dedicated regression test file proving the
Claude/GPT split plus non-regression of the "-fast" toggle and
unsuffixed ids.
#7268: classifyProviderError() only inspected the response body for
model-unavailable wording on 400/403/404, so a 401 body like "Model X is
not supported" (free-tier/aggregator providers) fell through to a generic
UNAUTHORIZED classification. Because chatCore.ts only calls lockModel(...,
"model_not_found", ...) on the MODEL_NOT_FOUND branch, the broken model was
never locked out and auto-combo kept re-selecting it every request. Added a
shared containsModelUnavailableMessage() regex (bounded, ReDoS-safe) in
errorClassifier.ts, consulted by the 401 branch before falling back to
ACCOUNT_DEACTIVATED/UNAUTHORIZED, and reused by modelFamilyFallback.ts's
isModelUnavailableError() for the literal "<model> is not supported" phrasing.
#7387: applySessionStickiness() (combo-level session stickiness) only gated
a sticky pin's release on testStatus (credits_exhausted/banned/expired) and
rateLimitedUntil (#6692's fix). It never consulted isAccountQuotaExhausted()
(src/domain/quotaCache.ts) — the authoritative per-window (5h/weekly) quota
signal that src/sse/services/auth.ts and sessionAffinityPin.ts (the
provider-level pin) already gate on. A connection whose quota window was
depleted, but that hadn't yet received a hard failure severe enough to flip
testStatus/rateLimitedUntil, was re-promoted to position 0 on every request
regardless of routing strategy. Added isStickyConnectionQuotaExhausted(), a
dynamic-import seam (mirroring resolveConnectionHealth/resolveSaturation, no
new static edge from open-sse/ into src/domain/) with an injectable checker
for tests, gating the release condition alongside the existing checks.
Regression tests: tests/unit/repro-7268-401-model-not-supported-lockout.test.ts,
tests/unit/repro-7387-sticky-quota-exhausted.test.ts (both RED before, GREEN
after). Existing sticky/error-classifier suites re-run and stay green.
Closes#7268Closes#7387
- byProvider now resolves the internal provider id to its configured
display name via getProviderById() (fallback: raw id for providers
not in the static registry). Fixes the Usage page showing "codex"
instead of "OpenAI Codex".
- byModel's in-memory dedup key now uses the normalized model name
instead of the raw one, so the same logical model recorded under a
bare and a provider-prefixed spelling (e.g. "glm-5.2" vs
"z-ai/glm-5.2") merges into a single aggregated row instead of
appearing twice with the same displayed name.
- Introduces a local UsageRows type alias in route.ts to shrink the
repeated "as Array<Record<string, unknown>>" casts back under the
frozen file-size baseline once the file was touched.
* fix(dashboard): resolve costs page 500 from out-of-scope t() in TopListCard (#7272)
TopListCard (CostOverviewTab.tsx) referenced the bare identifier `t`
from an outer component's scope when rendering the zero-cost /
!hasCostData branch, throwing "ReferenceError: t is not defined" and
crashing /dashboard/costs?range=all&apiKeyIds=...&groupBy=model
whenever a filtered slice landed only $0-cost rows.
Extracted TopListCard into its own component file and threaded the
resolved legacyFreeLabel string in as a prop, mirroring the existing
CostBreakdownTable pattern in the same file. Also fixes a case of the
typecheck:core dashboard .tsx coverage gap tracked in #7033.
* test(dashboard): move TopListCard #7272 regression test to vitest UI project
The node:test unit runner cannot load TopListCard's import chain
(@/shared/components -> ProviderIcon -> @lobehub/icons ESM), which made
the "Impacted unit tests (TIA subset; blocking)" CI job red with
"Unexpected token 'export'" on tests/unit/costs-toplistcard-legacy-free-label-7272.test.ts.
Moved the regression test to tests/unit/ui/ and rewrote it against the
vitest UI project (test:vitest:ui, blocking in the test-vitest CI job),
which handles the ESM import chain natively. Verified the test still
fails with "ReferenceError: t is not defined" against the pre-#7272
TopListCard body and passes against the fixed component.
* fix(db): pre-init sql.js WASM ahead of any getDbInstance() consumer (#7288)
* fix(db): close sqljs preinit ordering gap without top-level await (#7288)
The previous fix added a top-level await barrier at the bottom of
src/lib/db/core.ts to guarantee sql.js pre-init before any consumer
reached getDbInstance(). That made core.ts an async ES module, which
broke esbuild's CJS require() bundling for every test file that does
require("../../src/lib/db/core.ts") (tsx's CJS require hook rejects
requiring a transitive dependency with a top-level await), and caused
unrelated tests running in the same node:test process to fail with
"Promise resolution is still pending but the event loop has already
resolved".
Move the fix to the real startup entrypoint instead: registerNodejs()
(src/instrumentation-node.ts) now awaits ensureDbReadyForBoot() before
ensureSecrets()/clearStaleCrashCooldowns()/getSettings()/initAuditLog(),
all of which reach getDbInstance() transitively. ensureDbInitialized()
is idempotent, so later getDbInstance() calls are free cache reads.
The driverFactory.ts error-surfacing improvements from the original
#7288 fix (logging swallowed sync-driver errors, surfacing the real
sql.js pre-init failure instead of the generic "not pre-initialized
yet" message) are unchanged.
Updated tests/unit/db-sqljs-preinit-ordering-gap-7288.test.ts to prove:
no top-level await in core.ts, the corrected call order in
registerNodejs() (source-order assertion), and the original
getDbInstance()-no-longer-throws-the-misleading-message behavior driven
via the same warm-up path ensureDbReadyForBoot() now guarantees ahead
of every other startup step.
* refactor(db): drop the orphaned preInitSqlJsIfSyncDriversUnavailable helper (#7288)
Moving the ordering guarantee to registerNodejs() left this exported
helper with zero production callers — its own docblock still claimed it
was 'Chamada no top level de core.ts', describing an architecture the
hotfix removed. It was also redundant: ensureDbInitialized() already does
tryOpenSync-then-preInitSqlJs on the real boot path (core.ts:1358).
Its two tests exercised the helper as a stand-in for the real warm-up
('Simulates the fixed ordering'), so they proved a simulation rather than
production behaviour. They now drive ensureDbReadyForBoot()/tryOpenSync()
directly. The ordering guard still fails against the unfixed
instrumentation-node.ts (verified) and the whole file is 4/4 green.
The live parts of the driverFactory change (logSwallowedDriverError,
getSqlJsPreInitError) are untouched — both have real callers.
validateResponseQuality() only recognized Claude SSE lifecycle events
(message_start/content_block_*/message_stop/message_delta.stop_reason).
An OpenAI-shape stream (choices[].delta) that emits some bytes (e.g. a
role-only delta) and then closes without ever carrying finish_reason
(and without a data: [DONE] sentinel) fell through to the generic
replay branch and was forwarded to the client as a success instead of
triggering combo failover.
Adds OpenAI-shape lifecycle tracking (hasChoicePayload/hasTerminalMarker)
parallel to the existing Claude tracking: when an OpenAI-shape chunk was
seen but the stream ends without finish_reason or [DONE], and no
recognized content was found, mark the response invalid so combo
failover retries a sibling target. Healthy OpenAI streams (finish_reason
present, or real content found) are unaffected — they exit the peek
loop before reaching this check, preserving the #3399/#3685
pass-through contract.
Regression test: tests/unit/combo-streaming-openai-no-finish-reason-7285.test.ts
Root cause: validateOpenAILikeProvider's chat-probe status handling
(src/lib/providers/validation/openaiFormat.ts) only special-cased
401/403, 404/405, and >=500 — every other status, including 429, fell
through to the unqualified return { valid: true, error: null }. For
permanently-throttled free tiers (e.g. opencode-zen, classified
'avoid' in freeTierCatalog.ts), the dashboard connection Test reported
green forever while real traffic hit 429 on every request, with no
signal to the user.
Fix mirrors the existing validateBedrockProvider 429 precedent in the
same file: keep valid:true (the key is accepted) but add a warning
field describing the rate limit, instead of an indistinguishable pass.
Regression test: tests/unit/issue-7284-connection-test-masks-429.test.ts
mocks a 404 /models probe followed by a 429 chat probe and asserts the
result now carries { valid: true, error: null, warning: <rate-limit string> }.
Gates run (all green):
- node --import tsx/esm --test tests/unit/issue-7284-connection-test-masks-429.test.ts
- node --import tsx/esm --test tests/unit/provider-validation-firepass-403.test.ts tests/unit/validation-format-validators-split.test.ts (existing tests of the touched area, unaffected)
- node scripts/check/check-file-size.mjs
- node scripts/check/check-complexity.mjs (2054/2056 baseline, unchanged)
- node scripts/check/check-cognitive-complexity.mjs (889/890 baseline, unchanged)
- npm run typecheck:core
- npx eslint --suppressions-location config/quality/eslint-suppressions.json <changed files>
Termux/Android's Node reports process.platform === 'android'.
playwright-core's serverRegistry.js throws 'Unsupported platform:
<platform>' from a top-level IIFE at require time, so merely
importing the playwright package crashed — no browser ever launched.
claudeTurnstileSolver.ts was the only playwright consumer in the
codebase with a static top-level import; every other call site
(browserPool.ts, inAppLoginService.ts) already lazy-loads it. That
static import is unconditionally reachable from the Next.js
instrumentation hook on every boot via open-sse/executors/index.ts,
so any unsupported platform crashed the whole server at startup
regardless of which provider was configured.
Fix: import type { Browser, Page } (erased at compile time) and move
the chromium binding to a lazy await import("playwright") inside
solveTurnstile(), matching the existing pattern.