Commit Graph

1508 Commits

Author SHA1 Message Date
Diego Rodrigues de Sa e Souza
f1ea77fd04 fix(providers): detect expired gemini-web sessions and add testConnection (#9407) 2026-08-04 23:28:30 -03:00
Diego Rodrigues de Sa e Souza
85f30d4da8 fix(api): fall back to slugified provider name when prefix is empty (#9416) 2026-08-04 23:28:26 -03:00
Diego Rodrigues de Sa e Souza
ab560cce7b fix(providers): map kimi-web/K3 to K2D5 scenario to fix resource_exhausted (#9338) 2026-08-04 23:28:21 -03:00
Diego Rodrigues de Sa e Souza
6b531fbacd fix(claude): remove unconditional always-mode return in claudeClassifierCompat (#9276) 2026-08-04 21:36:54 -03:00
Diego Rodrigues de Sa e Souza
b07182c72a fix(security): require auth for /v1/models when management auth is configured (#9320) 2026-08-04 21:36:41 -03:00
Diego Rodrigues de Sa e Souza
7e55abbc41 fix(vision-bridge): do not select unreachable describe-model when no vision provider is connected (#8430) 2026-08-04 21:36:34 -03:00
Diego Rodrigues de Sa e Souza
b0501642dd fix(providers): anthropic strips code-execution/skills beta flag, causing container rejection (#9064) 2026-08-04 21:36:18 -03:00
Diego Rodrigues de Sa e Souza
7d46d4039f fix(perplexity-web): update catalog to use 'copilot' mode and fix model IDs (#8989) 2026-08-04 21:36:13 -03:00
Diego Rodrigues de Sa e Souza
d502f144b9 fix(providers): copilot-m365-web enterprise turns send disconnectBehavior=continue (#8971) 2026-08-04 21:36:09 -03:00
Diego Rodrigues de Sa e Souza
eaea0347ac fix(executor): guard claude/anthropic buildHeaders against empty credentials and extend dual-Bearer parity for third-party baseUrls (#8653) 2026-08-04 21:36:04 -03:00
Diego Rodrigues de Sa e Souza
37edd74f2d fix(proxy-health): include credentials in proxy health check URLs (#8853) 2026-08-04 21:36:00 -03:00
Diego Rodrigues de Sa e Souza
0b70a14a3b fix(auth): setting first dashboard login password no longer fails with HTTP 400 PASSWORD_REQUIRED (#8950) 2026-08-04 21:35:29 -03:00
Nick Sullivan
7b8055c7f8 fix(resilience): count STREAM_EARLY_EOF as a provider failure in combo routing (#9251)
* fix(resilience): count STREAM_EARLY_EOF as a provider failure in combo routing

A STREAM_EARLY_EOF is an upstream that accepted the request (HTTP 200), opened
the SSE stream, then closed it without emitting a single non-ping event. The
combo path classified it together with STREAM_READINESS_TIMEOUT through
isStreamReadinessFailureErrorBody(), and the readiness exemption in
shouldRecordProviderBreakerFailure meant the whole-provider circuit breaker
never saw it.

During a provider-wide outage that makes the breaker blind. Over a 7-day window
on our router we recorded 311 of these events, 302 of them on one model, 265
inside the upstream's published incident window — and the provider breaker sat
at CLOSED / failure_count=0 the entire time. Every request kept being dispatched
to the failing provider instead of shedding to the next combo target.

The two codes are different signals. The readiness probe is a pre-flight
liveness check on a connection we have not committed to, so failing it means
"this connection looks stale". An early EOF means the provider took the request
and then failed to serve it. The single-model path already treats it that way:
shouldTripProviderBreakerForResult has no readiness exemption, so a 502 early
EOF trips the breaker there. This makes the combo path consistent.

isStreamReadinessFailureErrorBody keeps matching both codes, because the
transient-retry and round-robin semaphore-cooldown paths in combo.ts do want
identical treatment for both. Only the breaker needs to tell them apart, so the
distinction is added as a narrow predicate and an optional argument rather than
by changing the shared classifier. Omitting the new argument reproduces the
previous behaviour exactly.

Follows the additive-override pattern established by the isProxyUnreachable
work, and leaves the existing exclusions for client aborts and plain 429s
untouched.

* test: register stream-early-eof-breaker in stryker tap.testFiles

The mutation test-coverage gate (check:mutation-test-coverage --strict)
detects unit tests that cover a mutated module but are missing from
stryker.conf.json tap.testFiles, so their mutant kills would not count.

comboPredicates.ts is one of the mutated modules, and the new
stream-early-eof-breaker.test.ts covers it, so the gate correctly flagged
the omission. 8376-econnrefused-breaker.test.ts -- the test this one is
modeled on -- is already registered; this just brings the new file in line.

No production code change.

---------

Co-authored-by: Nick Sullivan <nick@technick.ai>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
2026-08-04 18:07:09 -03:00
Xiangzhe
3440c118e0 feat(usage): show Grok Build billing limits (#9205)
* feat(usage): show Grok Build billing limits

* test(usage): keep Grok quota reset fixture in the future

* fix(i18n): add Grok billing labels to pt-BR

* fix(i18n): add Grok billing labels to Vietnamese
2026-08-04 18:07:02 -03:00
nguyenha935
712910612b fix(db): bundle and verify the sql.js fallback (#9044)
Co-authored-by: nguyenha935 <208228297+nguyenha935@users.noreply.github.com>
2026-08-04 18:06:55 -03:00
Bob.Hou
8027c60726 test(sse): expect the trailing period in the no-credentials message (#9392)
#9275 started appending a candidate-alias hint to the zero-active-credentials
error and terminated the provider name with a period, so the two sentences read
as one message. The two vscode tokenized-route tests still assert the old
unterminated string and now fail on every pull request opened against this
branch.

The Quality Gates workflow only runs on pull_request to release/**, never on
push, so the branch itself never re-runs these shards and the drift stayed
invisible after the merge.

Assert what the handler actually produces. Keeping the comparison exact rather
than loosening it to a prefix match is deliberate -- the exact form is what
caught the drift.

Signed-off-by: Minxi Hou <houminxi@gmail.com>
2026-08-04 17:08:14 -03:00
Diego Rodrigues de Sa e Souza
4a3dcf6b0b fix(routing): only let Codex-native bare ids preempt a provider when codex is active (#9447)
* fix(routing): only let Codex-native bare ids preempt a provider when codex is active

#9275 widened CODEX_NATIVE_UNPREFIXED_MODELS from a single id to gpt-5.5 plus the
gpt-5.6-sol/terra/luna tiers, so bare Codex CLI ids would reach the ChatGPT
subscription instead of fanning out to whichever provider won the inference race.
The early return it added never consulted the active-provider set, which made the
codex-only guard 30 lines below unreachable for every id in the set:

  if (CODEX_NATIVE_UNPREFIXED_MODELS.has(modelId)) return { provider: "codex", ... }

An OpenAI-only install therefore had bare gpt-5.5 routed to codex and failed with
'no active credentials for provider: codex' on a model OpenAI serves, and an install
whose codex connection was merely inactive failed identically. This also silently
reverted #5887's compatibility boundary.

The preference now only PREEMPTS another provider when a codex connection is active.
Ids that no other provider catalogs (codex-auto-review) still resolve to codex with no
connection at all — there is nothing to preempt and 'no codex credentials' is the
honest error. With codex active the preference still beats OpenAI, which is the point
of #9275, and an explicit openai/ prefix overrides it either way.

Tests: the three assertions that encode the intended #9275 change now expect codex
(plus a new one pinning the explicit-prefix override); the rest were already correct
and pass again untouched. Adds a regression test for the OpenAI-only case.

* docs(changelog): correct fragment id to #9447

* test(routing): seed an active codex connection in the bare-precedence guards

The two files #9275 added assert that bare gpt-5.5 / gpt-5.6-sol reach codex, but
they ran against an empty database — so they also pinned 'codex wins with no codex
connection at all', which is the regression #9447 removes. That put them in direct
contradiction with plan3-p0 / chat-helpers / codex-gpt55-routing-5887, which assert
openai for the very same input: no implementation could satisfy both, which is why
the release could not go green.

Seeding an active codex connection keeps the contract these files were written to
guard (codex beats openai for a Codex-native bare id) while dropping the accidental
'even with no codex configured' half. Cases that need no connection are left as they
were: the tier-only ids and codex-auto-review have no alternative provider to preempt,
and the explicit-prefix overrides are unaffected.

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-04 17:08:08 -03:00
Diego Rodrigues de Sa e Souza
16ed707148 feat(providers): filter detail connections server-side (#9247)
* feat(providers): filter detail connections server-side

Filter provider detail requests at the database boundary while preserving
the full per-provider connection set needed by search, pagination, and bulk
actions. Alias-backed provider pages keep their existing aggregate behavior.

Co-authored-by: RobertsXML <RobertsXML@proton.me>
Inspired-by: https://github.com/decolua/9router/pull/2998

* chore(changelog): fragment for #9247

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: RobertsXML <RobertsXML@proton.me>
2026-08-04 14:34:22 -03:00
Dizzle
8b97ef99aa fix(db): persist account egress IP into proxy_logs (#9291)
* fix(db): persist account egress IP into proxy_logs

The account egress IP (outbound IP the upstream saw, resolved via proxyEgress.ts
echo-IP probe with 5-min cache) was computed and surfaced in the proxy_logs
console and ring buffer, but never persisted: proxy_logs.egress_ip did not
exist, so the value was lost on restart and real traffic could not be
attributed to the node/IP active at that instant.

- migration 134 adds proxy_logs.egress_ip (nullable, backward-compatible)
- schemaColumns.ensureProxyLogsColumns() idempotent reconciler
- proxyLogger self-heals the schema in loadFromDb(), persists egress_ip on
  INSERT, and matches it in search
Follows the session_tag (#8249) migration + schemaColumns reconciler pattern;
base SCHEMA_SQL untouched.

* docs(changelog): add 9291 fragment for proxy_logs egress_ip

---------

Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
2026-08-04 14:34:17 -03:00
Dizzle
e50f2329dc fix(lib): memoize catalog pricing/capability lookups to fix cold /v1/models freeze (#8697) (#8987)
Root cause: a cold GET /v1/models catalog rebuild froze the entire server 41-54s.
node --prof profiling found a systemic missing-memoization pattern — a per-model
function rescanning a static or synced data structure with Object.entries()/
Object.keys() (or hitting SQLite) on every call instead of once per rebuild. Fixed
6 instances of the same pattern, found by iteratively re-profiling the full catalog
sweep after each fix (plus a whitebox review pass) until no further hotspot of this
shape remained:

1. getModelsDevPricing() (modelsDevSync.ts) — re-ran a synchronous SQLite query and
   re-JSON.parse'd ~180 blobs on every call (up to ~6091x instead of once per
   request). Memoized via the existing modelCatalogCacheVersion invalidation signal
   (same pattern as getCachedRawProviderConnections/getCachedProviderNodes in
   db/readCache.ts). Dominant cost of the original 41-54s freeze.

2. findInsensitive() (modelMetadataRegistry.ts, resolveCatalogPricing) — rebuilt a
   full Object.entries() scan on every case-insensitive lookup miss, twice per
   model. Replaced with a lowercase-key index built once per distinct pricing
   object and cached by identity (WeakMap). Warns once at index-build time on a
   case-insensitive key collision instead of silently discarding the second value.

3. getSyncedCapability() (modelsDevSync.ts) — ran a per-model SQLite SELECT on cold
   cache instead of self-warming the whole-table cache; no caller in the
   /v1/models build path ever primed it, so a cold rebuild ran one SQLite
   round-trip per model per call site. Now self-warms via the existing bulk
   getSyncedCapabilities() on first miss. Measured as the dominant remaining cost
   after fixes 1-2 (~70% of a full catalog sweep).

4. getCanonicalModelSpecId() (shared/constants/modelSpecs.ts) — up to 3 separate
   linear scans over the static MODEL_SPECS table per call (exact ci, alias ci,
   prefix). Replaced with a lazy, lowercase-key index built once (MODEL_SPECS never
   changes at runtime); prefix-match iteration order preserved exactly so
   resolution outcomes are unchanged.

5. getStaticSpecCanonicalModelId() (modelCapabilities.ts) — duplicated the same
   exact+alias scan as (4) in a second, separate rescan. Now reuses the shared
   index via a new exported helper (findModelSpecIdByExactOrAlias) instead of
   maintaining a second cache over the same static table.
   reverseModelsDevProviders() (modelCapabilities.ts) — rescanned
   Object.entries(MODELS_DEV_PROVIDER_MAP) (also static) on every call; memoized
   by provider key. Result is frozen (readonly) since it is now shared across
   calls instead of freshly allocated each time.

6. resolveModelAlias() (shared/constants/modelSpecs.ts) — rescanned
   Object.entries(MODEL_SPECS) unconditionally once per model (verified 1:1 call
   ratio, no short-circuit). Case-sensitive exact match (Array.includes(), no
   .toLowerCase()) — uses a dedicated exact-match index, deliberately not the
   case-insensitive alias index from fix 4/5 (would silently broaden matches).

Measured on a 1940-pair real-catalog sample (static PROVIDER_MODELS registry):
cold sweep 828ms -> 356ms after fixes 3-5 on top of 1-2, extrapolating to roughly
1s on the real ~6091-model catalog, down from the original 41-54s freeze.

Complementary to the stale-serve fix in #8801 (upstream) — neither alone
eliminates the freeze.

Tests: call-count regression guards for every fix (DB prepare / Object.entries /
Object.keys call counts staying constant instead of scaling with iteration count),
plus correctness coverage for case-insensitive/case-sensitive resolution. All
pre-existing consumer suites re-verified passing (96 tests total across 19 files).

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-04 14:34:10 -03:00
Xiangzhe
455906c181 fix(reasoning): forward Ollama Cloud thinking (#9290) 2026-08-04 14:34:02 -03:00
Bob.Hou
b6bcc491bc fix(token-refresh): exempt transient errors from exponential backoff (#9242)
* fix(token-refresh): exempt transient errors from exponential backoff

A refresh that failed on a network timeout was treated exactly like one
that failed on a revoked token: the streak incremented and the circuit
backed off exponentially, up to four hours. A brief upstream blip could
therefore park a healthy account for the rest of the day.

Transient failures now take a flat two-minute retry window instead of
advancing the streak. Classification checks structured signals first
(err.name for AbortError/TimeoutError, then err.code and err.cause.code)
and only falls back to matching the message text, so it does not depend
on upstream wording. Everything else keeps the existing exponential path.

Two properties worth preserving on sight:

  - A transient failure never shortens a longer permanent backoff. The
    new window is only adopted when the existing one is not already
    further out.
  - testStatus is preserved on both paths, so a connection whose access
    token is still valid keeps serving requests while its refresh
    retries.

Only a successful refresh clears the circuit. A successful request does
not, because requests do not refresh tokens.

* chore(quality): rebaseline file-size for tokenHealthCheck.ts

src/lib/tokenHealthCheck.ts lands at 1021 lines, above the 1000 cap. The
file consolidates token-refresh health checking that was previously split
across auth.ts and tokenRefresh.ts, and the refresh circuit state machine
does not divide cleanly, so splitting it to satisfy the cap would cost
more than it buys.

Scoped to this file only. Baseline entries for files this branch does not
touch are left at their upstream values.
2026-08-04 14:33:54 -03:00
NOXX - Commiter
45d375aa0b fix(api): defer media body size limits to providers (#8843)
Image and video payloads vary by provider and base64 encoding adds substantial overhead. Exempt media routes from OmniRoute's global request-body cap so provider-specific validation determines whether a request is too large. Keep finite body limits for non-media routes and cover both header and streamed-body admission paths.
2026-08-04 14:33:48 -03:00
Diego Rodrigues de Sa e Souza
f11d883f22 fix(cli-tools): enable Apply for compatible providers (#9250)
* fix(cli-tools): resolve models for compatible providers

Keep the CLI tools Apply flow usable when a dynamic OpenAI-compatible or
Anthropic-compatible connection has no static catalog entry. Resolve its
public prefix, connection default model, and prefix-backed catalog entries
before gating the cards.

Co-authored-by: lazysaltyfish <7127935+lazysaltyfish@users.noreply.github.com>
Inspired-by: https://github.com/decolua/9router/pull/2995

* chore(changelog): fragment for #9250

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: lazysaltyfish <7127935+lazysaltyfish@users.noreply.github.com>
2026-08-04 10:06:37 -03:00
Diego Rodrigues de Sa e Souza
2cb77bbca7 fix(translator): harden Claude format detection for model validation (#9253)
* fix(translator): harden Claude format detection for model validation

Co-authored-by: Ervareza Naurian <rianskp644@gmail.com>
Inspired-by: https://github.com/decolua/9router/pull/2949

* chore(changelog): fragment for #9253

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: Ervareza Naurian <rianskp644@gmail.com>
2026-08-04 10:06:31 -03:00
Shixi Li
a8216c92fe fix(sse): preserve error-only stream diagnostics (#9022)
* fix(sse): preserve error-only stream diagnostics

* test(ci): register stream readiness mutation coverage

* chore(changelog): finalize PR 9022 fragment
2026-08-04 10:06:25 -03:00
ikelvingo
c790b57af8 fix(translator): pass output_config.effort=max through verbatim (#9053)
The claude->openai translator was unconditionally rewriting max to xhigh, which broke any OpenAI-shape upstream that accepts max literally (e.g. ollama-cloud, opencode-go deepseek, moonshot k3, native Claude). Provider-aware effort policy is owned by sanitizeReasoningEffortForProvider in the executor; the translator should only do form conversion.

Regression guard: tests/unit/base-executor-sanitize-effort.test.ts end-to-end case (claude -> ollama-cloud preserves max).
2026-08-04 10:06:18 -03:00
Bob.Hou
9ee6435f0e fix(classify): recognize Modal 'usage limit reached' as quota exhausted (#9079)
Modal-hosted OpenAI-compatible endpoints (self-hosted Kimi K3 via
Modal free tier) return HTTP 429 with body {"error":"usage limit
reached"} when the account's credit is exhausted. Previously no
QUOTA_PATTERNS regex matched this bare-string error shape, so the 429
fell through to rate_limit (60s short cooldown). Combined with combo
round-robin's per-conversation session stickiness (#3825), this kept
re-targeting the same exhausted connection every turn instead of
locking it out and failing over to an account with remaining credit.

Add a substring pattern matching the JSON key/value pair
"error":"usage limit reached" with tolerance for trailing
punctuation and whitespace. Only the exact "error" key matches;
different keys or qualified transient messages like "Per-minute usage
limit reached" stay classified as rate_limit.

Signed-off-by: Minxi Hou <houminxi@gmail.com>
2026-08-04 10:05:56 -03:00
MumuTW
2e5854906d docs: slim AGENTS.md (#8839) 2026-08-04 10:05:29 -03:00
Diego Rodrigues de Sa e Souza
7163081f5e fix(agentrouter): retry on 400 content-blocked + burst guard (#9323)
The agentrouter.org upstream WAF returns 400 content-blocked
intermittently when:
  1. messages[].content contains a blocked keyword (Lorem ipsum, the
     phrase 'language model' alone, 'virtual assistant', etc.); or
  2. Requests from the same IP/key arrive in a burst, after which the
     WAF's per-IP suspicion bucket starts blocking content that would
     normally pass. The bucket relaxes after ~5-10s of idle.

Apply three mitigations:

1. Burst guard (open-sse/services/wafRateLimit.ts)
   Per-bucket (provider+url) gate that enforces a 500ms minimum gap
   between outbound requests to agentrouter. Configurable via
   configureWafRateLimit(). Tested in tests/unit/wafRateLimit.test.ts.

2. Reactive retry (BaseExecutor.WAF_RETRY_CONFIG in base.ts)
   New WAF_RETRY_CONFIG with maxAttempts=2, delayMs=1500,
   backoffMultiplier=2. When the upstream returns 400 with a body that
   matches /content[_-]blocked/i, retry the same URL with exponential
   backoff (1.5s, 3.0s) before falling through to the 429/401/fallback
   chain. Tested in tests/unit/base-executor-waf-retry.test.ts.

3. Documentation (docs/security/AGENTROUTER_WAF.md)
   Blocklist of always-blocked and almost-always-blocked patterns,
   behavior under load, guidance for prompts/tool output, and pointers
   to the relevant code paths in OmniRoute.

These are belt-and-suspenders: the burst guard prevents the WAF from
activating on normal traffic, and the reactive retry recovers when it
does anyway. Together they should eliminate the intermittent
400 content-blocked that Claude Code sees when running through
agentrouter via OmniRoute.

Refs #9275 follow-up. Test: 'WAF retry config shape' and 'WAF retry
differs from generic' guard the WAF_RETRY_CONFIG contract so future
refactors don't accidentally collapse the two retry paths.

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-03 18:22:14 -03:00
Diego Rodrigues de Sa e Souza
a72e1656eb fix(routing): bare model ids route to codex first; validate synced candidates (#9275)
* fix(routing): bare model ids route to codex first; validate synced candidates

Two bare-model-routing bugs surfaced in the field when an OmniRoute
deployment had a codex subscription whose cookie quota was exhausted
(retry-after 429047s / ~5 days) AND an active kiro connection whose
upstream sync briefly advertised 'claude-opus-5' before kiro vendored
it into the static registry.

  1. Bare 'gpt-5.6-sol' (and friends) routed to the codex provider even
     when the user had explicitly configured 'agentrouter' as their
     provider (via model_provider in codex CLI). With codex in cooldown,
     every bare request 429'd. Fix: extend CODEX_NATIVE_UNPREFIXED_MODELS
     to include the full gpt-5.6-sol tier set + gpt-5.5 + the related
     codex-native ids. The Codex CLI default is now actually honored;
     users can still prefix 'agentrouter/gpt-5.6-sol' to opt into a
     specific provider.

  2. Bare 'claude-opus-5' silently routed to 'kiro' when kiro's synced
     /v1/models catalog had that id (likely from a transient upstream
     quirk). kiro's static registry never cataloged claude-opus-5, so
     the upstream call 404'd. Fix: validate activeSyncedProviders against
     MODEL_TO_PROVIDERS before merging them into the candidate list.
     Auto-discovery still wins when the model id has no static entry
     (brand-new models from upstream keep working).

Bonus: when handleNoCredentials returns a 404 'No active credentials for
provider: X' error, surface the top-3 candidate aliases (e.g.
'anthropic/claude-opus-5, claude/claude-opus-5, agentrouter/claude-opus-5')
so the operator can pick a working prefix instead of staring at a wall.

Tests (all pass, 25 regression tests preserved):
  - tests/unit/fix-bare-model-precedence.test.ts (7 tests)
  - tests/unit/fix-synced-model-validation.test.ts (3 tests)
  - tests/unit/fix-error-message-candidates.test.ts (3 tests)
  - tests/unit/fix-bare-routing-fallback.test.ts (7 tests)

* fix(tests): replace lorem ipsum with neutral text to avoid agentrouter WAF

The agentrouter.org WAF blocks requests containing 'lorem ipsum' in
messages[].content. When Claude Code reads test files via the Read tool,
the content appears in tool_result blocks which can trigger the filter.

Replace 'lorem ipsum dolor sit amet' with 'example content for testing
purposes' in compression harness test to avoid false positives.

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-03 18:09:31 -03:00
Diego Rodrigues de Sa e Souza
92e8960f77 feat(models): functional gateway mirrors + fix synced-substitution (#9217)
* fix(models): preserve static registry models not covered by synced discovery

* feat(models): add functional gateway mirror synthesizer

* feat(models): add functional gateway mirror gate predicate

* feat(models): add functional gateway mirror DB gate

* feat(models): wire functional gateway mirrors into /v1/models

* refactor(models): extract synced-coverage helper to pure leaf (file-size gate)

* fix(db): re-export functional gateway mirrors gate from localDb (db-rules)

* fix(i18n): translate functional gateway mirror flag for Vietnamese (locale completeness)

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-02 20:35:58 -03:00
Diego Rodrigues de Sa e Souza
35405be602 fix(agentrouter): infer protocol from client endpoint
fix(agentrouter): infer protocol from client endpoint

- /v1/responses resolves AgentRouter as openai-responses
- /v1/chat/completions resolves AgentRouter as openai
- /v1/messages resolves AgentRouter as claude
- Per-request protocol and credential cloning (no SQLite mutation)
- Codex 0.146.0 and Claude Code 2.1.220 identity alignment
- response.completed.usage.total_tokens normalization for strict Codex clients

Closes #9224
2026-08-02 15:10:54 -03:00
diegosouzapw
d53f9bd813 fix(responses): avoid usage normalization short-circuit 2026-08-02 10:05:03 -03:00
Diego Rodrigues de Sa e Souza
7b2e4b4837 fix(responses): normalize terminal usage for Codex (#9192)
* fix(responses): normalize terminal usage for Codex

* refactor(responses): reduce stream gate growth

* refactor(responses): keep stream within size ratchet

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-02 02:29:21 -03:00
diegosouzapw
ec150a0069 fix(agentrouter): honor alternate protocol in chat pipeline 2026-08-01 13:38:25 -03:00
diegosouzapw
564c204efe fix(agentrouter): support Claude and Codex protocols 2026-08-01 12:18:09 -03:00
Diego Rodrigues de Sa e Souza
b38f3a4c02 feat(test:scoped): add TIA-based local test runner (#8084 D1) (#9143)
- npm run test:scoped: runs only tests impacted by your changes
- npm run test:scoped:staged: for staged changes (pre-commit)
- Uses select-impacted-tests.mjs with impact map when available
- Falls back to heuristic (changed test files) when no map
- Hub file changes suggest full suite
- 7 unit tests for the selection logic

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-01 11:32:04 -03:00
Diego Rodrigues de Sa e Souza
0ef50886ef feat(g1): rewrite combo-strategy check to runtime-import approach (#9131)
G1 (v3.8.51): section (2) of check-known-symbols no longer regex-scans
strategy === "..." literals from combo source. The handled set now comes
from a runtime-imported dispatch registry (open-sse/services/combo/
strategyDispatch.ts) that imports the real ordering functions and enumerates
which strategies they implement. This keeps the canonical-not-handled gate
correct under the upcoming R0.3 registry dispatch, which removes the
strategy === branches the regex relied on.

- Adds HANDLED_COMBO_STRATEGIES registry (all 20 canonical strategies) + binds
  the real dispatch leaves (applyStrategyOrdering, resolveAutoStrategyOrder,
  tryFusionDispatch, tryPipelineDispatch, resolveComboTargetPipeline).
- main() imports the registry instead of reading/sourcing combo files.
- extractHandledStrategies + diffComboStrategies stay exported (pure, tested).
- New TDD test proves the runtime enumeration covers canonical exactly.

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-01 11:08:49 -03:00
Diego Rodrigues de Sa e Souza
8fac6bcd48 feat(.50): completa itens restantes — G13, G14, gap34, docs, R0.2 (#9126)
* feat(ci): G0 — quality rail (PR→release/**) ganha ratchets+segurança do trilho A

O refactor de god-files do trilho 3.8.50→3.9.0 acontece em PRs→release/**, e esse
trilho pulava o motor de ratchet, o CodeQL ratchet e todos os scanners de segurança
— exatamente onde a rede era necessária (5 das 13 causas da reconciliação de 07-24
eram regressões reais shipadas por CI verde por-PR).

Modo enxuto, jobs EXISTENTES (a .51 consolida lanes; nenhum job novo):

- lint-guard: quality:collect + ratchet --allow-missing + require-tighten +
  check:codeql-ratchet. O job já escreve .artifacts/eslint-results.json, então o
  motor entra a custo ZERO de ESLint (um inventário, dois consumidores). Coverage
  ausente degrada gracioso (--allow-missing); autoridade de coverage segue no
  trilho A. + permissions security-events:read para o CodeQL ratchet.
- fast-gates: check:cycles, check:lockfile, duplication, dead-code, type-coverage,
  compression-budget + install endurecido dos scanners (gh release download,
  zizmor PINADO 1.25.2 = mesmo auditor do ci.yml) + secrets/vuln/workflows/
  openapi-breaking com --ratchet (self-skip sem binário; só regressão medida bloqueia).
- Fora de propósito: bundle-size (self-skip sem build → configuração morta) e o
  run de coverage (fast-unit já roda a suíte cheia).

Runners intocados: guard tests/unit/vps-runner-variable-scope.test.ts verde;
teste novo tests/unit/quality-rail-gate-membership.test.ts pina a MEMBERSHIP dos
gates no trilho B (red antes da edição, green depois).

Validação no tip puro (nenhum base-red fabricado para a fila de PRs abertos):
cycles OK · lockfile OK · duplication 4.26% (base 5.72%) · dead-code 226 (base
227) · type-coverage 94.13% (base 92.17%) · compression OK · secrets 0 (base 0) ·
vuln 5 (base 10) · codeql 0 (base 0) · oasdiff 0 (base 0) · zizmor 178 (base 190)
· actionlint exit 0 no arquivo editado · quality-ratchet 56 métricas OK +
require-tighten OK com --allow-missing.

Refs #8084

* feat(.50): G13 golden-set, G14 import boundaries, gap34 deterministic, docs sync, R0.2 dead hooks

Integra os itens restantes da 3.8.50:

- G13: golden-set determinístico para combo.ts e chatCore.ts via seams públicas
- G14: no-restricted-imports para localDb barrel fora de src/lib/db/ e executors em src/app/
- Gap34: teste determinístico de timeout DuckDuckGo sem rede real
- Docs: golden path de contribuição + sincronização de números canônicos
- R0.2: remoção dos 7 hooks mortos do BUILTIN_EVENTS + UI marketplace ajustada

* fix(r0.2): remove marketplace tab remnants from plugins page — fixes dashboard typecheck regression

* chore(r0.2): remove pluginWorker.ts, signing.ts, sandbox.ts — zero importers confirmed

* fix(docs): remove OMNIROUTE_PLUGINS_ALLOW_EXEC reference — env var removed with pluginWorker.ts in R0.2

* fix(env): remove dead OMNIROUTE_PLUGINS_ALLOW_EXEC from .env.example — consumer removed in R0.2

* fix(test): update sidebar-visibility assertion for R0.2 marketplace removal

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-01 10:44:23 -03:00
Diego Rodrigues de Sa e Souza
45c91e22c2 feat(ci): G0 — quality rail (PR→release/**) ganha ratchets+segurança do trilho A (#9108)
O refactor de god-files do trilho 3.8.50→3.9.0 acontece em PRs→release/**, e esse
trilho pulava o motor de ratchet, o CodeQL ratchet e todos os scanners de segurança
— exatamente onde a rede era necessária (5 das 13 causas da reconciliação de 07-24
eram regressões reais shipadas por CI verde por-PR).

Modo enxuto, jobs EXISTENTES (a .51 consolida lanes; nenhum job novo):

- lint-guard: quality:collect + ratchet --allow-missing + require-tighten +
  check:codeql-ratchet. O job já escreve .artifacts/eslint-results.json, então o
  motor entra a custo ZERO de ESLint (um inventário, dois consumidores). Coverage
  ausente degrada gracioso (--allow-missing); autoridade de coverage segue no
  trilho A. + permissions security-events:read para o CodeQL ratchet.
- fast-gates: check:cycles, check:lockfile, duplication, dead-code, type-coverage,
  compression-budget + install endurecido dos scanners (gh release download,
  zizmor PINADO 1.25.2 = mesmo auditor do ci.yml) + secrets/vuln/workflows/
  openapi-breaking com --ratchet (self-skip sem binário; só regressão medida bloqueia).
- Fora de propósito: bundle-size (self-skip sem build → configuração morta) e o
  run de coverage (fast-unit já roda a suíte cheia).

Runners intocados: guard tests/unit/vps-runner-variable-scope.test.ts verde;
teste novo tests/unit/quality-rail-gate-membership.test.ts pina a MEMBERSHIP dos
gates no trilho B (red antes da edição, green depois).

Validação no tip puro (nenhum base-red fabricado para a fila de PRs abertos):
cycles OK · lockfile OK · duplication 4.26% (base 5.72%) · dead-code 226 (base
227) · type-coverage 94.13% (base 92.17%) · compression OK · secrets 0 (base 0) ·
vuln 5 (base 10) · codeql 0 (base 0) · oasdiff 0 (base 0) · zizmor 178 (base 190)
· actionlint exit 0 no arquivo editado · quality-ratchet 56 métricas OK +
require-tighten OK com --allow-missing.

Refs #8084

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-08-01 09:55:02 -03:00
Diego Rodrigues de Sa e Souza
371c10ea5f feat(sse): Cheaper Inference provider — chat + native Responses + images, sponsor rail 2nd (#9043)
Registers Cheaper Inference (api.cheaperinference.com) as an OSS-sponsor gateway provider.

- Canonical provider `cheaperinference` (alias `cinf`) + routing registry with 39 measured text models
- Dedicated executor: forces `store:false` on the native /v1/responses endpoint (the shared strip in
  chatCore.ts deletes `store` for every provider != openai, so without this every Responses request
  400'd) and resolves chat-vs-responses URL from the per-model targetFormat
- 3 image models (grok-imagine, nano-banana-pro, nano-banana-2), prefix-only: the two nano-banana ids
  already belong to adobe-firefly, which keeps the bare-id routing
- Resale pricing measured from GET /v1/models (30% off list); sponsor rail Kimi 1st / Cheaper
  Inference 2nd via an explicit rank map; supporter badge in 43 locales; README row

No quota card: the gateway exposes no balance API (/v1/wallet and /v1/balance both 404).

Validated live end-to-end through OmniRoute: chat, native Responses, streaming and image generation
all 200 with real content; the Firefly collision guard verified at runtime.
2026-07-31 07:53:41 -03:00
Diego Rodrigues de Sa e Souza
9b3efef806 fix(ci): five workflow defects, one of them shipping the wrong dmg to Intel Macs (#8988)
* fix(ci): five workflow defects, one of them shipping the wrong dmg to Intel Macs

Gaps 31, 19, 16, 30 and 12 of the v3.8.49 process dossier.

## 31 — LIVE BUG: an Intel Mac downloads the ARM dmg

electron-builder runs once per macOS job and each run emits its own
`latest-mac.yml` listing only its own dmg — measured at 338 and 350 bytes,
different content, identical filename. `download-artifact` with
`merge-multiple: true` resolves that collision by ARRIVAL ORDER, so one silently
overwrites the other. arm64 won in the published v3.8.48.

Why that breaks Intel, from electron-updater's own selection code
(out/providers/Provider.js):

    files.find(it => [...].some(n => n.includes(process.arch))) ?? files.shift()

The Intel dmg is `OmniRoute-X.Y.Z.dmg` — no arch suffix. On Intel `process.arch`
is "x64", nothing matches, and the fallback takes the FIRST entry. With an
arm64-only manifest that is the ARM build.

So ORDER is the fix, not tidiness: the un-suffixed entry must be first, because
it is the only one reachable through that fallback. `merge-multiple` is now off
(per-artifact subdirectories) and a new
`scripts/release/merge-mac-update-manifest.mjs` merges them deliberately. It
refuses to write when the inputs disagree on version — a manifest stitched from
two builds points at files that were never published together, which is worse
than no manifest.

Validated against the REAL v3.8.49 manifests, not just fixtures: the script
reproduces byte-for-byte the manifest I hand-merged and published, including
both sha512 values and the newer releaseDate.

## 19 — one variable, two opposite machines

`USE_VPS_RUNNER` governed the build and the test jobs together. The build needs
the .113's RAM; the tests need the hosted runner's link. Measured 2026-07-29:
`actions/setup-node` took 20m06s on .113 with 4 concurrent runners versus 16s
hosted (npm cache restore saturating the link), while the tests themselves tied
— 2m54 vs 2m31.

Self-hosted is therefore strictly worse for tests, so rather than add a second
variable to configure, `test-unit`, `test-vitest`, `fast-unit` and `fast-vitest`
are pinned to `ubuntu-latest`. `quality.yml`'s `fast-gates` deliberately keeps
the variable — I have no measurement for it, and guessing is what produced this
gap.

## 16 — a flaky shard sent the publish into the 40-minute build

The artifact reuse filter required `conclusion == "success"` on the whole run, so
any unrelated red shard discarded a perfectly good tree. The artifact is only
uploaded if the Build job succeeded, so its PRESENCE is the accurate signal. Now
it takes the 5 most recent candidate runs and tries each download until one
works. `head_repository.full_name == env.REPO` stays — that clause is the
artifact-poisoning guard, not a filter refinement.

## 30 — the gate that could be bypassed at merge

`check:agent-skills-sync` lived only in quality.yml's PR-only Merge-integrity
job, because the CHANGELOG half of that job needs a base to diff against. This
half does not. Keeping it PR-only left a real hole: this cycle's merge trains
landed with `--admin`, which bypasses required checks, so three SKILL.md files
drifted, rode the release squash into `main`, and the sync-back turned them into
a base-red blocking EVERY PR into release/v3.8.50 until #8954. It now also runs
in ci.yml's lint job, which runs on push to `main`.

## 12 — a cancelled gate reads like a passing one

The dashboard already renders ` CANCELLED` per job, so my dossier entry was
imprecise: they do not vanish, they sit buried mid-table. A cancelled job
reported no verdict at all, and this cycle the Vitest job was cancelled in rounds
1, 2 and 3 — it finished only in round 4, revealing a suite broken the whole
cycle plus two production bugs. The summary now opens with a banner naming every
cancelled job and saying plainly that nothing was checked.

    node --import tsx/esm --test tests/unit/mac-update-manifest-merge.test.ts   # 11 pass
    merge against the real v3.8.49 manifests → both dmgs, Intel first
    all four workflows parse; check:workflows --ratchet → 178, baseline 190

* docs(changelog): fragment for #8988

* test(ci): align the artifact-provenance guard with the gap-16 criterion

My own assertion from #8953 encoded the criterion this PR deliberately removes:
it required `.conclusion == "success"` on the whole CI run, which discarded a
perfectly good build tree whenever any unrelated shard went red — pushing the
publish into the 40-minute build the fast path exists to avoid.

Inverted rather than deleted, and the replacement is strictly stronger. It now
pins three things where the old one pinned one: that the loose criterion is gone,
that the step actually probes for the artifact (the accurate signal, since it is
only uploaded when the Build job succeeded), and that it probes MORE THAN ONE
candidate run — without which a single miss still falls back to a full build.

The provenance clause it was originally written to protect
(head_repository.full_name == env.REPO) is untouched and still asserted above.

* fix(ci): finish gap 19 — pin fast-gates and give USE_VPS_RUNNER one meaning

This was left deliberately partial because `fast-gates` had never been measured,
and guessing is what produced gap 19 in the first place. Measured now, and the
evidence is cleaner than expected:

    fast-gates, 160 quality.yml runs .... ZERO self-hosted samples
                                          every non-skipped one is "GitHub Actions NNNN"
    median duration, 72 successful runs .. 5.6 min hosted

The classifier is not at fault — in the same window ci.yml's Build demonstrably
ran on omniroute-113-7 and omniroute-113-6, so self-hosted runs are visible when
they happen. The USE_VPS_RUNNER expression on this job was dead configuration.

And had it ever fired it would have inherited the measured penalty, because this
job's first two steps are exactly the bottleneck:

    actions/setup-node on .113 with 4 concurrent runners .... 20m06s
    actions/setup-node hosted ..............................     16s

So it is pinned rather than switched, and the second variable the gap proposed
(USE_VPS_RUNNER_BUILD / _TESTS) turns out to be unnecessary. After this the
variable governs exactly five jobs, all of them build-like:

    ci.yml:build · quality.yml:build · npm-publish:publish
    nightly-release-green: release-green, main-green

One variable, one meaning: "this job needs the .113's memory". A guard test pins
that — it fails if the variable is ever attached to a test-like job again, and it
also asserts the build KEEPS it, so nobody closes this gap by removing the
variable outright.

    node --import tsx/esm --test tests/unit/vps-runner-variable-scope.test.ts   # 3 pass
    check:workflows --ratchet → 178, baseline 190

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 12:49:52 -03:00
Diego Rodrigues de Sa e Souza
494b1c961a fix(ci): close six release-process gaps from the v3.8.49 run (#8985)
* fix(ci): stop the reconciliation range and the fragment sweep from hiding work

Two release-tooling defects found during the v3.8.49 run (gaps 4 and 7 of the
process dossier). Both fail by hiding work rather than announcing themselves,
which is why each one had already cost a real mistake.

## The reconciliation range was 62× too wide

`list-uncovered-commits.mjs` bounded its scan with `git describe --tags`. Releases
reach `main` by SQUASH, so no commit on a release branch is ever an ancestor of the
tag, and `vPREV..HEAD` re-lists the un-squashed history of every earlier cycle.
Measured on release/v3.8.50 @ 7eca04fd12:

    v3.8.49..HEAD ....... 1361 commits
    cycle open..HEAD .....   22 commits

The report drowns in noise, and that is how a previous reconciliation let ~200 PRs
through with no CHANGELOG bullet.

The base is now resolved by CONTENT — the oldest commit that introduced this
version string into package.json — deliberately NOT by commit subject, because the
subject has already changed format once:

    chore(release): bump v3.8.49 (development cycle version)     older
    chore(release): open v3.8.50 development cycle               current

A message-matching resolver would have silently reverted to the broken tag base the
first time someone reworded the bump. The fallback now writes a WARNING to stderr
explaining that a tag range re-lists previous cycles, so a shallow clone degrades
loudly instead of quietly reproducing the bug. One of the five tests asserts
exactly that the warning says "squash" and "noise".

## The back-merge resurrects fragments that already shipped

The release lands on `main` as one squash commit, so `main` still carries every
`changelog.d/` fragment the reconciliation folded in and deleted. Back-merging
`main` restores all of them — 191 in the v3.8.49 run. Nothing breaks at that
instant; the next aggregation folds them in a SECOND time and the section grows
duplicates that have to be hand-unpicked.

New `scripts/release/sweep-stale-fragments.mjs` (`npm run sweep:stale-fragments`)
reports them, and `--apply` removes them. Report mode exits 1 so the back-merge
step can gate on it.

The identity rule took two attempts, and the second one exists because running the
script against the live repo refuted the first. Matching on any `#N` in the bullet
flagged `changelog.d/features/8980-deprecate-gemini-cli-provider.md` as stale,
because that bullet cites issue **#7034** for context and #7034 shipped in an
earlier cycle — it would have deleted an unreleased fragment and dropped its
credit. A bullet routinely cites issues it merely references; only the
`<PR-number>-<slug>.md` filename says which PR the fragment *is*. That case is now
a regression test.

Every ambiguous case resolves toward KEEPING: no number in the filename falls back
to normalized text, text shorter than 12 chars is never matched, and anything
matching neither is kept. A surviving duplicate is a nuisance someone notices; a
deleted fragment silently costs a contributor their credit.

    node --import tsx/esm --test tests/unit/release-cycle-base-resolver.test.ts   # 5 pass
    node --import tsx/esm --test tests/unit/sweep-stale-fragments.test.ts         # 11 pass
    node scripts/release/list-uncovered-commits.mjs --json
      → base ed2db6cb19, baseSource "cycle-open", total 22   (was 1361)
    node scripts/release/sweep-stale-fragments.mjs
      → 4 fragments, 0 stale, exit 0

* docs(changelog): fragment for #8985

* fix(ci): four quality gates that punished the wrong thing

Gaps 6, 9, 10 and 23 of the v3.8.49 process dossier. Each one either blocked
work it should have waved through, or reported a number that was never the
code's.

## 6 — test-masking is unusable at release scale

My own dossier entry for this was WRONG and the measurement says so:

    tracked test files ............ 3977      (I had written 1277)
    absolute tautology scan ....... ~1 s      (I had written >30 min)
    the diff uses base...HEAD                 three dots — already merge-base
    diff vs release branch ........ 0 files, 0 s
    diff vs main (today) .......... 3 files, 0 s

The base choice was never the problem, and it cannot be reproduced today at
all: `main` has since received the v3.8.49 squash, so the merge-base is recent.
The pathology only exists DURING a release, in the window before `main` gets the
squash — then the merge-base is the PREVIOUS cycle's fork point and the diff
legitimately spans the whole cycle (~1277 changed test files, each costing a
`git show` process plus a full regex pass). That is the same squash-merge
topology as gap 4, and it is why the check ran twice without finishing.

Fix: above 300 changed test files the per-file diff subchecks are skipped, since
every one of those files was already gated by this check on its own PR. The
absolute tautology scan still runs unconditionally over all 3977 files, so the
floor is untouched. The skip is deliberately loud — a silent skip is gap 12,
which cost two production bugs this cycle. `shouldSkipDiffSubchecks` never skips
on unparseable input, so a broken count cannot disable the gate.

## 9 — a capital letter invalidated 41 translations

`"Reset Defaults"` → `"Reset defaults"` marked the key stale in 41 locales. Every
translation was still correct, and in locales with no letter case the "fix" is
not expressible. Worse, the escape hatch (`__MISSING__:`) is BANNED in `vi` by
tests/unit/i18n-vi-completeness.test.ts, so `vi` had no legitimate way out.

`isCosmeticRewrite` folds case, whitespace runs and trailing punctuation — and
nothing else. Most of the nine tests exist to pin what is NOT cosmetic: a changed
word, an added word, and any edit inside an interpolation like `{count}` all
still flag. Two end-to-end tests hold both directions: a cosmetic edit leaves
every locale alone, a real rewrite still flags all of them.

## 10 — the ratchet compared numbers from two different auditors

`pipx install zizmor` was unpinned, so the runner installed whatever PyPI served
that day and measured 1 finding MORE than the devbox on the identical commit
(190 vs 189) — a second rebaseline push per release, chasing a number that was
never the code's. Pinned to 1.25.2 (what the devbox runs), and
check-workflows.mjs now prints `zizmorVersion=` next to the count so any future
rebaseline is traceable to the tool that produced it.

## 23 — a PR pointed at its own branch

#8912 has head == base == release/v3.8.50: no diff, can never merge, and it sits
in the queue with a full check board on every push to that branch. It survived
because nothing looks wrong — the checks pass, since there is nothing to check.

New guard in the `changes` job (one field comparison, before anything is spent).
The distinction that makes it safe to block on: an equal head/base BRANCH is
conclusive, an equal head/base SHA is NOT — a branch cut moments ago has an
identical tip and is legitimate, so that case warns instead of failing. Half a
signal never fails either.

    node --import tsx/esm --test tests/unit/test-masking-release-scale.test.ts   # 6 pass
    node --import tsx/esm --test tests/unit/ui-value-drift-cosmetic.test.ts      # 9 pass
    node --import tsx/esm --test tests/unit/pr-self-target-guard.test.ts         # 7 pass
    check:workflows --ratchet → 178 findings, zizmorVersion=zizmor 1.25.2, baseline 190
    the i18n suite is unaffected (5 files re-run, all green)

* fix(ci): allowlist the four CI-only env vars the new gates read

The env-doc-sync gate failed three unit shards plus Docs Gates on this PR, and it
was right to: it requires every `process.env.X` read in code to be documented in
`.env.example`, and this PR introduced four new reads.

They do not belong in `.env.example`. That file is OmniRoute's runtime
configuration; these are CI signals with no meaning in a user's `.env`:

    HEAD_REF / HEAD_SHA / BASE_SHA   the `changes` job passes github.head_ref,
                                     github.base_ref and the PR head/base SHAs to
                                     the self-targeting-PR guard
    TEST_MASKING_MAX_CHANGED_TESTS   the escape hatch that raises the test-masking
                                     gate's release-scale skip threshold

So they go in IGNORE_FROM_CODE, which exists for exactly this and already carries
the precedent one line above: `BASE_REF`, allowlisted because CI passes it to the
OpenAPI breaking-change gate. `BASE_REF` being already listed is also why only
four of my five reads failed.

Each entry carries its justification and the script that reads it, per the
allowlist policy.

    node --import tsx/esm --test tests/unit/issue-7793-env-doc-sync-repro.test.ts   # 1 pass
    npm run check:env-doc-sync → all three directions in sync

* fix(i18n): narrow the cosmetic-rewrite exemption to the scope actually reported

The gap-9 fix folded whitespace in addition to case, and that collided with a
pre-existing test which pins the opposite — tests/unit/i18n-ui-value-drift.test.ts,
"a value that only changes whitespace still counts as an edit". Its comment states
the reasoning:

    Conservative on purpose: trailing-space churn is rare, and treating it as a
    no-op would let a real reword slip through behind an innocuous-looking diff.

That is a documented decision by whoever wrote it. The problem actually reported
was CASE — `"Reset Defaults"` → `"Reset defaults"` invalidating 41 correct
translations — and whitespace was scope I added on my own. Reversing someone
else's reasoned call, silently, to fix something nobody reported is not this
change's job, so the exemption is narrowed to case + trailing terminal
punctuation. No test pins either of those.

The reported case is still fixed, verified end to end: that rewrite invalidates 0
locales. And whitespace is now asserted NON-cosmetic in my own test file too, so a
later tidy-up cannot quietly fold it back in.

    node --import tsx/esm --test tests/unit/i18n-ui-value-drift.test.ts     # 11 pass (pre-existing)
    node --import tsx/esm --test tests/unit/ui-value-drift-cosmetic.test.ts # 10 pass

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 12:41:34 -03:00
Diego Rodrigues de Sa e Souza
2c243cf1fc feat(sse): deprecate the gemini-cli upstream provider with a real migration path (#8980)
* feat(sse): deprecate the gemini-cli upstream provider with a real migration path

Stored `gemini-cli` connections were being kept alive for nothing. Measured before
touching anything:

  routable?    absent from PROVIDERS, from REGISTRY, from OAUTH_PROVIDERS, and no
               executor references it → the connection can NEVER serve a request
  refreshing?  yes, and successfully — it redeemed against PROVIDERS.gemini's client
               (681255809395-oo8ft2o…), the same public Gemini CLI / Code Assist OAuth
               client

So the scheduler made periodic upstream calls to Google to keep a credential fresh
that had nowhere to go. That is the waste this removes.

This is a deprecation, not a deletion, and the difference is deliberate. The path was
not dead code: #8232 added it after a user report (the UI advertises automatic OAuth
rotation and these rows never rotated), and #8275 narrowed it to exactly the legacy
refresh. Simply dropping it from `supportsTokenRefresh` would have produced a SILENT
skip — `Skipping … (refresh unsupported)` — leaving the row at "active" forever, doing
nothing. Worse than before.

Instead:

  DEPRECATED_PROVIDERS + isDeprecatedProvider/getDeprecationNotice in tokenRefresh
      one place naming the provider and where to migrate. A test asserts the migration
      target is itself routable, so the notice can never point somewhere useless.

  _getAccessTokenInternal returns the ESTABLISHED unrecoverable envelope
      { error: "unrecoverable_refresh_error", code: "provider_deprecated", migrateTo }
      Reusing `error` means isUnrecoverableRefreshError and the manual-refresh route
      already stop retrying — no new contract for callers to learn. The distinct `code`
      is what makes it legible. A bare `null` would read as transient and retry forever.

  tokenHealthCheck marks the connection terminal with the reason
      Placed after the existing terminal-status guard, which makes it idempotent for
      free: once "expired", later sweeps skip the row, so it writes once instead of
      rewriting the same reason every cycle.

  the manual-refresh route stops lying
      It said "Refresh token expired. Please re-authenticate this account." — false
      here: the token is fine, the provider is gone. Re-authenticating would loop
      against something that no longer exists. It now reports the deprecation and the
      migration target.

`gemini` uses the same OAuth client, so re-adding the account there is a working path,
not advice to start over.

Deliberately NOT touched:

  Category A — the gemini-cli CLIENT identity (#7034): clientIdentityProfiles.ts,
      clientApi.ts, googApiKeyAuth.ts. Same string, opposite direction — requests
      ARRIVING from the Gemini CLI, where OmniRoute is the server. Deleting these is the
      failure this change must never cause, so a test now asserts the profile survives.
      Audited: `git diff --name-only` touches none of those files.

  errorClassifier.ts's isCloudCodeProvider list still names gemini-cli. It is a
      defensive 403→PROJECT_ROUTE_ERROR list shared with cloudcode/cloud-code; the entry
      is unreachable for a non-routable provider, and editing a shared classification
      path for a dead string is risk without upside.

Tests — 42 across the six files that mention the identifier, all green:

    gemini-cli-legacy-refresh.test.ts        5   (3 assertions REWRITTEN, see below)
    gemini-cli-deprecation.test.ts           5   (new)
    client-identity-profiles.test.ts         9   (category A, untouched)
    service-token-refresh.test.ts           14
    errorclassifier-antigravity-403.test.ts  4
    gemini-cli-ansi-sanitization.test.ts     5   (category C, untouched)

The three rewritten assertions in the legacy file are alignment, not weakening, and the
gate is right to ask: each is now STRONGER. "refresh succeeds against Google's token
endpoint" became "zero upstream calls happen at all"; "a 400 surfaces invalid_grant"
became "the envelope is unchanged but the code says provider_deprecated" plus a control
asserting `gemini` still reports invalid_grant, proving the real path was not blunted.
The file's header keeps the whole #8232#8275 → deprecation arc, because each step is
why the next made sense. Count unchanged; no test deleted, so no allowlist entry needed.

* docs(changelog): fragment for #8980

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 09:36:54 -03:00
Diego Rodrigues de Sa e Souza
7eca04fd12 feat(ci): gate the publish on clean-install AND upgrade-over-previous (#8953)
* feat(ci): gate the publish on clean-install AND upgrade-over-previous

`check:pack-boot` proves a fresh install boots. It does not prove the path that actually
broke us: installing over an existing version, where ~110 SQLite migrations run against a
populated database. v3.8.48 shipped as a hotfix because the published 3.8.47 crashed on
boot, and the v3.8.49 upgrade path was only ever exercised end-to-end by hand — on VPS .16,
against a real 3.8.48 install with a 165 MB database, AFTER publishing. That is backwards.

New gate (`scripts/check/check-install-upgrade.mjs`), wired into npm-publish.yml as step 12,
BEFORE `npm stage publish` — so a broken upgrade never reaches the registry and a staged
package that is never approved simply expires, with no `npm deprecate` needed:

- Phase A: fresh prefix + fresh DATA_DIR, install the packed tarball, boot, health.
- Phase B: fresh prefix + fresh DATA_DIR, install the PREVIOUS published version, boot it
  (creates + migrates the DB), stop, install the tarball over the SAME prefix, boot against
  the SAME DATA_DIR. Asserts no table present before the upgrade was dropped.
- Schema convergence, and its DIRECTION is the whole point:
    fresh − upgraded ≠ ∅  → FAIL. Structure a clean install creates but an upgrade does not
                            means every existing user is missing it. Not allowlistable.
    upgraded − fresh ≠ ∅  → residue; fails only when NEW (allowlist carries the known ones).

A naive symmetric check would either block every release on harmless residue or, if relaxed,
let the dangerous direction through. Measured on VPS .16 (2026-07-30): a real 3.8.48 install
upgraded to 3.8.49 ended with 117 tables against 116 for a clean 3.8.49 install — the extra
being `cache_metrics`, recorded in config/quality/install-upgrade-allowlist.json with the
measurement. Both installs healthy, zero `no such table` in 150 log lines.

`evaluateConvergence` is exported and pure so the asymmetry is testable without packing,
installing or booting anything (same reason check-test-masking exports its helpers):
tests/unit/check-install-upgrade-convergence.test.ts, 8 cases, ~6ms.

A previous version that fails to boot degrades to a warning — a historically bad publish
must not block the current one. Uses node:sqlite (Node 24, already the publish job's
runtime): no new dependency.

* fix(ci): require the reused next-build artifact to come from this repository

CodeQL raised actions/artifact-poisoning/critical on the `next-build` fast path
this PR builds on (#8941). The finding is real and it sits on the path that
produces the published npm tarball.

The step picks a CI run by querying the runs API for `head_sha` and filtering on
`name == "CI" and conclusion == "success"`. That query also returns
`pull_request` runs from FORKS: they execute in this repository's context and
upload their own `next-build`, built from fork-controlled source. Measured
today, 57 runs in this repo have a `head_repository` other than the repo itself.
So the selection trusted bytes by coincidence of commit SHA — anything that made
a fork's head commit coincide with the publish commit could put attacker-built
bytes on npm.

Adds `and .head_repository.full_name == env.REPO` to the selection. Provenance
is now explicit; `head_sha` still carries tree-equality. Verified against the
live API using the expression extracted from the workflow itself — the same
single run (30518663668) is selected either way for the current tip, so the fast
path keeps working while every fork run is excluded.

Not a dismissal (hard rule #14) — the clause removes the flagged trust.

    node --import tsx/esm --test tests/unit/npm-publish-artifact-provenance.test.ts
    # 3 pass, 0 fail        (base: 2 pass, 1 fail)

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 09:07:57 -03:00
Diego Rodrigues de Sa e Souza
888ce1a73b chore(sse): drop the iflow entry from the token-refresh TTL map (#8966)
* chore(sse): drop the iflow entry from the token-refresh TTL map

The `iflow` provider was removed from the product, but its 24-hour refresh-lead
entry outlived it in REFRESH_LEAD_MS. Surfaced during v3.8.49 homologation on the
production VPS, where startup logs carry:

    [CREDENTIALS] Warning: unknown provider "iflow" in credentials file, skipping.

Measured across src/, open-sse/, tests/ and docs/ — the identifier had exactly two
occurrences repo-wide: the map entry and one test assertion. Nothing dispatches on
it, so `getRefreshLeadMs("iflow")` now falls through to TOKEN_EXPIRY_BUFFER_MS like
any other unknown provider.

The test assertion was not deleted, it was MOVED: from "returns explicit lead time
for known providers" to "falls back to TOKEN_EXPIRY_BUFFER_MS for unknown
providers". That is alignment to the new behavior and strictly more coverage than
before — a silent reintroduction of the entry now turns the fallback case red
instead of passing unnoticed. Flagged explicitly because the test-masking gate
rightly treats a removed assertion as suspicious.

Also removes the now-redundant "Non-rotating providers" section header: every
remaining entry under it is Google-backed and the following comment already says
"permanent (non-rotating)".

    node --import tsx/esm --test tests/unit/service-token-refresh.test.ts
    # 14 pass, 0 fail

* docs(changelog): fragment for #8966

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 09:07:54 -03:00
Diego Rodrigues de Sa e Souza
a36dbcfd88 fix(ci): stop one failing platform from taking the whole desktop channel down (#8957)
v3.8.49 shipped with ZERO release assets. v3.8.48 had 16. Every gate was green.

Measured from run 30503231362, not inferred:

    Build Electron (windows) ....... success
    Build Electron (macos-intel) ... success
    Build Electron (macos-arm64) ... success
    Build Electron (linux) ......... failure
    Create Release ................. skipped
    Publish to npm ................. skipped

The linux leg died 8 min into "Creating an optimized production build" with
"The runner has received a shutdown signal" and no exit code, on runner
`GitHub Actions 1000378558` — github-hosted, so this was the VM being
reclaimed, not a Node heap error. Reproduced on a 32 GB machine from the exact
tag commit: the same build succeeds and peaks past 18 GB.

Three independent defects compounded, one fix each:

1. Turbopack allocates natively (Rust, off the V8 heap), so the existing
   --max_old_space_size=6144 does not bound it. The project already documents
   the webpack fallback as the escape hatch for RAM-constrained machines
   (docs/reference/ENVIRONMENT.md, #6409), and nightly-compat already applies
   it for the same reason on Node 26 (#8090). The linux leg now selects it;
   Windows/macOS keep Turbopack since they build fine and it is faster.

2. `release` gated on `needs: [validate, build]` with no `if:`, so ONE failing
   leg skipped it and discarded the three artifacts that DID build — 1.7 GB,
   still retained — plus the source archives, which depend on no build at all.
   Fail-closed made a partial failure look total. It is now fail-partial:
   attach what exists, still requiring `validate` to have passed.

3. Nothing asserted the release HAS assets, so 16 binaries and 0 binaries were
   indistinguishable to CI. New `verify-desktop-assets` job asserts one asset
   per platform and fails loudly.

The check is a separate job on purpose: failing inside `release` would cascade
into `publish-npm` (`needs: [validate, release]`) and block the npm channel
over a desktop-only gap. Now the assets attach, npm still publishes, and an
incomplete desktop channel is a red job instead of silence.

TDD: 3 of the 4 new assertions fail on the tip of release/v3.8.50 and pass
with this change. The 4th asserts a negative (publish-npm must not gain a
dependency on the asset check) and guards against future regression rather
than reproducing the bug.

    node --import tsx/esm --test tests/unit/electron-release-desktop-channel-8949.test.ts
    # 4 pass, 0 fail        (base: 1 pass, 3 fail)
    check:workflows --ratchet → 189 findings, baseline 190, no regression

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 09:07:29 -03:00
Diego Rodrigues de Sa e Souza
321488abee chore(ci): remove two fork-owned publish workflows that rode in by accident (#8967)
* chore(ci): remove two fork-owned publish workflows that rode in by accident

Both files publish to a DIFFERENT owner's GHCR namespace, and both arrived as an
unrelated extra file inside an otherwise on-topic PR:

    build-fork.yml            added by #1528 (scope: SSE translator, Qiwen Chen)
                              env IMAGE_NAME: ghcr.io/kang-heewon/omniroute
                              if: github.repository == 'kang-heewon/OmniRoute'
                              100+ runs instantiated here

    build-rinseaid-image.yml  added by #8729 (scope: SSE reasoning)
                              tags: ghcr.io/rinseaid/omniroute:...
                              no repository guard at all — 0 runs

Neither can ever succeed: this repository's GITHUB_TOKEN cannot write to another
owner's namespace. The cost is not a breach, it is noise. build-fork.yml's guard
sits on the JOB, not the workflow, so GitHub instantiates a run on every push to
main and every v* tag and then skips the job — which is why every release check
board has carried a permanently skipped "Publish Fork Image to GHCR" entry.
build-rinseaid-image.yml never fires because its trigger branch
(`build-k3-reasoning-image`) does not exist in this repo.

Only build-fork.yml was pre-approved (2026-07-30). The second was found while
executing: grepping the workflow directory for registry namespaces turned up
ghcr.io/rinseaid alongside ghcr.io/kang-heewon. Same defect, same remedy, so both
go — easy to split if that is preferred.

Nothing else is touched. Specifically NOT touched: the 14 `kang-heewon` credit
links in CHANGELOG.md (real contributions), their 42 i18n mirrors, and the
historical `- **ci:** update build-fork workflow…` entry from #2055. Measured: 0
of the 14 credit mentions concern build-fork, so no credit line is involved
either way. `git status` shows exactly two deletions and one new test.

TDD — the guard names both offenders before the removal and passes after:

    node --import tsx/esm --test tests/unit/workflows-no-foreign-fork-publishers.test.ts
    # before: 0 pass, 2 fail  →  build-fork.yml → ghcr.io/kang-heewon
    #                            build-rinseaid-image.yml → ghcr.io/rinseaid
    # after:  2 pass, 0 fail

Zizmor findings drop 190 → 178 (both files use unpinned docker/* and checkout
actions). The baseline is deliberately NOT rebaselined here: the metric direction
is `down` so a drop cannot break the ratchet, tightening it to exactly 178 would
leave zero headroom and self-break on drift, and validate-release-green states
the convention outright — "Any drift above is rebaselined at release, not a
contributor concern."

* docs(changelog): fragment for #8967

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 09:07:23 -03:00
Diego Rodrigues de Sa e Souza
14992ceebe test(ci): stop the promote-latest guard from racing the script's early exit (#8977)
* test(ci): stop the promote-latest guard from racing the script's early exit

`Unit Tests fast-path (2/4)` went red on two unrelated PRs today (#8953, #8966),
always on the same case, always with `Error: spawnSync bash EPIPE` — never an
assertion. The file passes locally in 1.8s, so it read as load-related noise. It
is not: it is a race with a precise, reproducible mechanism.

should-promote-latest.sh decides a pre-release VERSION and exits BEFORE reading
stdin at all:

    case "$VERSION" in
      *-*) echo "false"; exit 0 ;;
    esac

The test harness passed the candidate tags via execFileSync's `input:`, i.e. a
pipe. The child exits, its read end closes, and the parent's write raises EPIPE —
so the test throws before asserting anything. Whether the write lands first
depends on the 64 KB pipe buffer and the scheduler, which is exactly why it
failed intermittently under four concurrent shards while passing in isolation.

Measured, not inferred — same version, growing payload:

         2 tags (     11 bytes) → ok
       100 tags (    689 bytes) → ok
     5 000 tags ( 43 889 bytes) → ok
    20 000 tags (188 889 bytes) → EPIPE, every time

Fix: back stdin with a real FILE instead of a pipe. A file has no reader to lose,
so the child may exit whenever it likes. The script's interface is untouched — it
still reads candidate tags from stdin, exactly as docker-publish.yml pipes them.

Production is NOT affected, and that was checked rather than assumed:
docker-publish.yml short-circuits pre-releases before the helper is ever called
(`elif printf '%s' "$VERSION" | grep -qE -- '-(rc|alpha|beta|pre|next)'`), so the
early-exit branch is unreachable there. Only the test exercised it. No production
file changes here.

TDD — the new case is the guard for the harness itself, run against both helpers:

    node --import tsx/esm --test tests/unit/build/should-promote-latest-5301.test.ts
    # new helper (file-backed stdin): 9 pass, 0 fail
    # old helper (input: pipe):       8 pass, 1 fail → Error: spawnSync bash EPIPE

* docs(changelog): fragment for #8977

---------

Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
2026-07-30 09:07:19 -03:00