Anthropic's Messages API rejects a tool whose `input_schema` carries a
composition keyword at the root with:
tools.N.custom.input_schema: input_schema does not support oneOf,
allOf, or anyOf at the top level
The refusal happens before inference, so a single MCP/agent tool carrying
a root-level union fails every request that ships the catalog, and combo
failover cannot recover from it.
Both conversion paths that build a Claude `input_schema` from a client
payload now flatten such a root union into a plain object schema:
object-compatible branches contribute their `properties` (root wins on a
name collision), the root is pinned to `type: "object"`, and only `allOf`
contributes `required` — `anyOf`/`oneOf` branch requirements are
alternatives and promoting them would refuse calls the original schema
accepts. Nested unions are untouched and clean schemas pass through
unchanged.
Closes#13552
* fix(compression): place output-style instruction in top-level system, not messages[0]
Anthropic-shaped bodies reject a synthetic system-role entry unshifted at
messages[0] (the claude passthrough forwards messages unchanged, and the
upstream API requires system content in the top-level system parameter).
Output styles and the caveman output mode now land their instruction in
the top-level system field when it exists (string or content-block array)
and only fall back to a trailing system message for OpenAI-shaped bodies,
which the claude system-role extraction hoists. Custom endpoint system
prompts skip the unshift whenever a top-level system field is present.
All compression options stay enabled; placement-only fix.
Fixes#12584
* test(compression): cover system-instruction placement branches 4 and 6
Adds direct unit cases for the placement ladder branches that had no
coverage, asserting where the instruction lands:
- branch 4: merge into a system message at index >= 1, leaving
messages[0] untouched (plus the skip-over-a-block-content system
message variant).
- branch 6: trailing append when the body has neither a `system` field
nor a string-content system message.
- block-array `system`: appends one block and is idempotent on a second
pass (first coverage of the array path of the marker check).
Also normalizes a malformed non-string/non-array top-level `system`
(e.g. `null`) to "" before the format branch in injectSystemPrompt and
injectCustomSystemPrompt. Previously such a body entered the `system`
branch, matched neither format, and silently dropped the prompt without
falling back to the messages path. Both new guards fail without this
change.
* chore(compression): add changelog fragment for top-level system placement
* fix(test): make npm run test terminate and restore RAYCAST env-doc sync
Two independent defects, both in the test/dev entrypoint layer.
1. `npm run test` never terminated. It was a hand-maintained copy of
`test:unit` that had drifted: it omitted `--test-force-exit` on BOTH
node invocations and dropped the trailing `&& npm run test:unit:serial`.
Per AGENTS.md ('Database Handles in Tests'), unreleased SQLite handles
make Node's native runner hang indefinitely — every sibling script
(`test:unit`, `test:unit:ci`, `test:unit:ci:shard`) already carried the
flag; only `test` did not. Measured on m1max at 84c6ad7c2, same suite
both arms: without the flag the runner was killed at the 420s ceiling
(exit 137, no summary line, 23 orphaned node processes); with it the
runner exited on its own in 419s leaving 1. `test` now delegates to
`test:unit` so the two cannot drift again, which also makes the serial
suite reachable from `npm run test` for the first time.
2. Removing the RAYCAST_* rows from ENVIRONMENT.md (#9) broke
check-env-doc-sync. `parseEnvExampleVars` matches `^#?\s*(VAR)=`, so it
counts COMMENTED-OUT vars: the four entries still sat at
.env.example:1263-1266 and became `envMissingDoc` drift the moment their
docs disappeared. The #9 verification only ran the fabricated-docs gate
and missed this one. The block is dead either way — it documents
open-sse/services/raycast.ts and scripts/raycast/usage-benchmark.mjs,
both deleted with the GPL-derived provider in #11691, and no live code
reads the vars — so it is removed rather than re-documented.
envMissingDoc is now []. The remaining codeMissingEnv failure
(CURSOR_AGENT_BINARY, CURSOR_MAX_FRAME_BYTES, OMNIROOT) is pre-existing
drift on the base, absent from this diff, and left alone.
* chore(stryker): register 3 covering unit tests missing from tap.testFiles
check:mutation-test-coverage --strict fails identically on pristine
release/v3.8.51 (f1e7148c1) with an empty diff — base debt blocking this PR.
- combo-identical-error-streak.test.ts -> comboPredicates.ts
- 13601-header-drop-count-surfaced.test.ts -> responseHeaders.ts
- semantic-cache-no-truncated-writes.test.ts -> semanticCache.ts
* fix(test): keep the #13187 concurrency-4 cap in test:unit
The dedupe made `test` delegate to `test:unit`, but it also silently
reverted the deliberate local concurrency cap from #13187 ("cap local
unit-test concurrency at 4 to avoid exhausting commit charge") back to 20.
Measured on m1max (16 cores), same suite and same tree, only the flag differs:
concurrency=20 -> 356 cancelled, 356 "event loop has already resolved" bailouts
concurrency=4 -> 0 cancelled, 0 bailouts
So 20 does not just slow the run down, it makes the runner abandon tests and
still print a summary -- a false green. Restore 4; termination is preserved via
delegation to test:unit, which already carries --test-force-exit.
* revert(test): drop redundant test-script delegation
The #13187 batch commit (178d25250) already gave `test` both `--test-force-exit` flags and the trailing `&& npm run test:unit:serial` step, so the delegation fix was redundant. It also broke tests/unit/test-serial-quarantine.test.ts, which asserts every parallel runner script ends with the serial step (base 4/4 -> head 3/4). package.json is now byte-identical to base; this PR is the stryker tap.testFiles fix only.
Both packages are only reachable through code paths the standalone
tracer never follows, so they get silently dropped from the built
node_modules/:
- ioredis is a deliberately lazy dependency (#6559 in
rateLimiter.ts) — reached only via a runtime `await
import("ioredis")` in rateLimiter.ts,
warmupScheduler/circuitBreakerFactory.ts and
quota/redisQuotaStore.ts, never through a static top-level import.
Any self-hosted deployment that sets REDIS_URL crashes on first use
with "Cannot find module 'ioredis'".
- bcryptjs is statically imported by
src/lib/auth/managementPassword.ts, so the main server bundle is
fine (Next inlines the small pure-JS package into the compiled
chunk). bin/cli/settings-store.mjs (the `omniroute reset-password`
CLI) is a separate, unbundled entrypoint that needs the real
package physically present in node_modules/ — nothing else
requires it as a loose runtime dependency, so it was never copied.
`node bin/reset-password.mjs --password-stdin` failed with
"Cannot find package 'bcryptjs'" (ERR_MODULE_NOT_FOUND) on an
otherwise healthy production deployment.
Both reproduced on a real self-hosted Docker deployment (v3.8.49/51).
Adds the two entries to EXTRA_MODULE_ENTRIES (the single source of
truth cited in the Dockerfile) and extends the sync/async parity
test with fixtures + assertions for both.
* fix(backend): stop redaction truncating the message after a path (#13144)
`findUnquotedPathEnd` may swallow the rest of a line when it cannot tell
where a path ends, so a Windows path with spaces cannot leak a
`Files\secret` suffix. Two things made that fire far wider than the
function documents at `:606`.
**1. The licence was granted on separator evidence alone.** Every API route
carries slashes, so an ordinary `/v1/x/y` in prose qualified as unequivocal
and truncated everything after it. The image-model 400 lost the one
sentence it exists to deliver:
built ...cannot be used on /v1/chat/completions. Use POST
/v1/images/generations instead.
delivered ...cannot be used on <path>
Now only a Windows path, a file URI, or a known POSIX filesystem root may
swallow the line. @diegosouzapw's `/zz` vs `/etc` probe on the issue is why
this is the condition and not the first-segment check I originally
proposed: both truncated identically, so the root was never the driver.
**2. The ambiguity branch ran before `resolvedExtensionEnd`.** A path whose
end is pinned exactly by a known extension was still treated as ambiguous
the moment any prose followed it, so the endpoint was discarded and the
line swallowed. A determinable extension leaves nothing to fail closed
about -- the whole path is still replaced, suffix included, and the tail
survives:
before Provider failed in <path>
after Provider failed in <path> with api_key='[REDACTED]'
Both halves are independently load-bearing: reverting (1) fails the two
route tests, reverting (2) fails the extension test.
Fail-closed is narrowed, not weakened. `/etc/shadow copy failed` has
nothing to anchor an endpoint on and still collapses to `reading <path>`.
Worth recording that the guard test for that cannot be killed by mutating
either mechanism alone -- the two are mutually redundant, so it takes
disabling both, which is also why this change cannot expose a suffix these
shapes did not already hide.
Test results against base:
chat-rejects-image-only-model red -> GREEN
dashboard-request-failed-redaction its delivered-log assertion now
passes; the test still fails on a
second, unrelated assertion (the
*internal* log is redacted where it
should stay raw) that base never
reached
tunnel-routes-error-sanitization unchanged, independent (a tripwire
asserting the shared sanitizer does
NOT cover a shape it now does)
836/840 pass across the sanitization, redaction and error suites; the
remaining failures are the two above plus mcp-public-error-boundaries,
which passes in isolation on base and on this branch and only flakes under
--test-concurrency=8.
* docs(changelog): fragment for the redaction truncation fix (#13144)
changelog.d/README says a PR adds exactly one fragment rather than editing
CHANGELOG.md, so the aggregation order stays deterministic and siblings
cannot conflict. This one was missing.
* test(redaction): narrow the headline case to the truncation it names
Rebased onto a base that has moved 40 commits; resolveEndpoint gained an
ignoreAmbiguity parameter and route-context callers in that window. The
merge keeps both: base's parameter, plus this PR's two changes (check the
resolved extension BEFORE the ambiguity branch, and drop
hasFilesystemEvidence from the swallow licence).
The headline assertion was that the whole message survives byte for byte.
On the current base the tail survives but the route itself still becomes
<path> in that particular message, because the quoted model slug earlier
in the line carries separators. That is a narrower, separate question from
the truncation this PR fixes, so the test now asserts the remediation
sentence survives and records the <path> substitution explicitly rather
than silently dropping the case.
* test(stryker): register the redaction-truncation test for mutation runs
errorPathRedaction.ts is mutation-tested, so a new covering test has to be
in tap.testFiles or the Stryker sandbox never runs it and its mutants
report as survived. Inserted in the alphabetical run beside the sibling
error-sensitive-redaction.test.ts, following #13036's precedent.
The list has a second, unsorted appended group; left that alone rather
than re-sorting a file this PR only needed one line in.
Requested in review by @diegosouzapw.
* fix(evals): fail a case whose model call errored instead of scoring it passed
runSuite() attached caseMetrics[id].error to the graded result but never forced
`passed` to false. executeEvalCase() returns a failed call as an ordinary output
string ("[ERROR] <message>"), so any expected pattern that happened to match that
text was recorded as a pass. That inflates the reported pass rate, and reports a
non-zero score for a run in which no model was ever reached.
Built-in codex-comparison case codex-07 reproduces it: its pattern is
"try|catch|throw|error|Error" and the provider-resolution failure text ends with
"...added as a combo entry.", so the `try` alternative matches and the case is
scored as passed while carrying a non-empty error.
A case that never reached a model has no measured behaviour to grade, so a
failure is the only honest score.
Refs #13137
* docs(changelog): add fragment for the errored-eval-case fix (#13201)
The two lists are sibling pure-data modules that have to agree, and nothing
compared them. A provider in fetcherProviders but not supportedProviders
computes a quota nobody ever asks for; one in supportedProviders with no
dispatcher case is accepted and then falls through to
`default: "Usage API not implemented"`.
That seam has produced the same bug three times -- #9603 (bailian, whose
own comment reads "fetcher existed, list entry missing"), #11722, and
#12256 (openrouter credits, which #13080 then asked for again six days
after the fix landed because the card had never appeared).
usage-families-split.test.ts pins the dispatcher against fetcherProviders,
so the open-sse side cannot drift; this pins the other edge.
Divergence stays allowed but has to be declared with a reason:
opencode, opencode-zen, xai have a fetcher, not offered to the dashboard
xiaomi-mimo-token-plan offered, no fetcher -- but inert, because it
authenticates by API key and is absent from
PROVIDER_LIMITS_APIKEY_PROVIDERS, so
isSupportedUsageConnection refuses it before
the dispatcher is reached
I could not establish intent for the first three from the tree, so they are
pinned rather than "corrected" -- `xai-oauth`/`xao` are offered while the
API-key `xai` is not, which reads like it may be deliberate. A third test
fails if a declared divergence stops diverging, so the allowlists cannot go
stale and quietly excuse a future recurrence of the same id.
Mutations, each killed by the right test:
new fetcher, no dashboard entry -> the forward guard + the stale check
dashboard entry, no fetcher -> the reverse guard + the stale check
a declared divergence gets fixed -> the stale check alone
duplicate id in either list -> the duplicate test alone
105 related tests pass (this, usage-families-split, provider-plugin-manifest,
provider-limits*), eslint clean. Test-only; no production file touched.
* fix(tests): retire claude-3-5-sonnet-20241022 from the combo integration suites
Sibling of #12670. Eight integration suites still targeted the retired claude-3-5-sonnet-20241022, which the vendor lifecycle registry rejects with HTTP 410, so every combo listing it lost that target: 23 cases failed on the release tip for one cause. Replace it with claude-sonnet-4-6, the successor the lifecycle record names and the id chat-pipeline.test.ts already uses. Fixture model id only; no assertion changed, no production code touched.
* docs(changelog): fragment for the retired-fixture cleanup (#13056)
* fix(oauth): read pollToken body once on non-JSON upstream responses
The device-flow pollToken handlers for kimi-coding and github tried
response.json() first and fell back to response.text() in the catch.
Once .json() rejects on a non-JSON body the stream is already consumed,
so the .text() fallback always throws TypeError (Body is unusable) and
pollToken rejects, surfacing as a generic 500 on /api/oauth/<provider>/poll
instead of the intended graceful { error: "invalid_response" } payload.
Non-JSON responses are realistic when the OAuth upstream sits behind a
CDN/anti-bot HTML error page or a proxy interstitial (auth.kimi.com in
particular).
Read the body once as text, then JSON.parse it, preserving the original
invalid_response fallback. Adds a regression test that drives both
providers with a stubbed fetch returning an HTML error page and a JSON
error body. Prunes the two now-unused no-unused-vars suppressions for the
removed catch bindings.
* docs(changelog): fragment for #13046
* fix(claude): forward client-negotiated thinking-binding-controls and thinking-display-updates betas
Gateways drops anthropic-beta tokens not on FORWARDABLE_CLIENT_BETAS, so
@ai-sdk/anthropic Fable 5.1 requests carrying thinking.block_binding were
rejected upstream with thinking.adaptive.block_binding: Extra inputs are
not permitted even when the client negotiated
thinking-binding-controls-2026-08-01 correctly. Same class for
thinking.display updates (thinking-display-updates-2026-08-18).
Regression guard: tests/unit/thinking-binding-controls-beta-forward.test.ts
* chore(changelog): fragment for #12989
* chore: trim comments
handleSonioxTranscription took no formData, built the job body from a fixed
three-key object, and reduced the transcript to { text }. Every client-supplied
parameter was therefore dropped in silence: the request returned 200, the flag
had no effect, and from the caller's side an unsupported parameter and a dropped
one looked identical. Diarization and Soniox's `context` were both unreachable,
and the per-token `speaker` attribution Soniox returns was discarded.
The handler now receives the form data (as the Deepgram one already did) and
maps what the caller asked for onto the job: diarization under the three
spellings callers reach for, `context` verbatim, and `language` as a Soniox
language hint. Keys are added only when requested, so a request carrying no
options produces byte-identical job bodies and the existing
audio-soniox-provider deep-equality assertions still hold.
Response shape stays `{ text }` by default. When diarization or
response_format=verbose_json is requested, the token stream is collapsed into
contiguous single-speaker runs and returned as OpenAI-style `segments` carrying
`speaker`, with `words` when word granularity is asked for.
Verified against a live Soniox account on a real two-party Persian phone call:
default response unchanged, 13 segments over 2 distinct speakers with turn
boundaries matching the dialogue, and `context` correcting a proper noun the
model otherwise gets wrong.
Closes#12947
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Modal is bring-your-own-deploy, so every connection needs its own app URL, and
the server-side validator already required providerSpecificData.baseUrl. The
add/edit connection form never rendered the field, so a Modal connection could
not be validated or saved at all.
Adding the id to CONFIGURABLE_BASE_URL_PROVIDERS reuses the same always-on Base
URL field as the kimi/moonshot case (#7447). The placeholder switch is folded
into a record lookup in the same commit so the function stays under the
complexity cap as ids are added; the record was checked against the switch for
every pre-existing id and only "modal" changes behaviour.
Rebased onto the current release tip, which now carries #13120's own entry in
the same set.
Co-authored-by: Goni Sulaiman <gonisulaimann@users.noreply.github.com>
* fix(cli): find npm-global Claude .cmd shims under Program Files\nodejs (#12563)
Stock Node MSI installs drop claude.cmd there, but detection never listed that directory and Electron's PATH often omits it, so the dashboard reported settings_found_binary_unresolved while a normal shell could run the CLI.
* fix(cli): soft-fail npm prefix cache and enrich Windows lookup PATH (#12563)
Stop permanently caching a failed npm config get prefix as empty, and prepend npm-prefix / APPDATA\npm / nvm / Program Files dirs on Windows lookup PATH so custom installs survive Electron PATH gaps.
Chat admission sampled host-wide /proc/pressure/memory, so a swapping
Docker host 503'd idle containers with resource_pressure. Prefer this
unit's cgroup memory.pressure and keep the host file as fallback.
* fix(command-code): floor tiny muse-spark output budgets so hidden reasoning cannot consume the whole budget
muse-spark models routed through command-code burn the entire output budget on
hidden server-side reasoning before emitting visible content. A small caller-set
max_tokens (e.g. 64) comes back as HTTP 200 with null content (out=64, reasoning=61).
Reuse the prefix-aware MUSE_SPARK_PATTERN to detect prefixed ids (meta/muse-spark-1.2-contributor,
cmd/meta/muse-...) and floor tiny budgets to 512 in both the /provider/v1 path and
the /alpha/generate fallback. No budget is synthesized when absent; large budgets untouched.
* docs(changelog): add changelog fragment for the command-code muse-spark budget floor (#12497)
* fix(combo): scope Claude model failures to the model, not the account
A priority combo whose steps are five models on one Claude OAuth connection
stops at step 1. hasPerModelQuota() returns false for the claude provider, so
markAccountUnavailable() records a model-specific 404 or 5xx against the
connection row, and getPersistedConnectionCooldownSkipReason() then skips every
sibling step before dispatch. Verified with a combo whose first step names a
model that cannot exist: the 404 lands and step 2 is never tried, while the
same combo works as soon as step 2 points at a different account.
A Claude OAuth connection multiplexes Fable 5, Opus 5/4.8/4.7/4.6, Sonnet and
Haiku behind one credential, which is the multiplexing hasPerModelQuota already
describes. Its quota is a separate question: a 429 on a Max subscription is
account-wide, and shouldMarkAccountExhaustedFrom429 pins that. So this adds
hasPerModelFailureScope() for the non-quota statuses and leaves 429 alone.
Combo exhaustion gets the same treatment for 404, which names one model the
account cannot serve rather than a bad connection. The empty-content 502 was
already exempt through isEmptyContentFailure.
Closes#12334
* fix(combo): extract Claude per-model failure scope to keep file-size caps
Move hasPerModelFailureScope into a leaf so frozen accountFallback.ts and
auth.ts stay at their file-size caps after #12334. Register
combo-claude-per-model-scope.test.ts in Stryker tap.testFiles so the
mutation-test-coverage gate sees the covering unit test.
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
---------
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
Rebase the focused image-quota visibility fix onto the current release/v3.8.51 tip while preserving the newer shared Antigravity catalog and AGY live-discovery changes.
* fix(sse): classify "N API calls / month" 429 text as quota_exhausted
QUOTA_PATTERNS recognized "monthly ... limit" and "per month ... limit",
but not the reversed order providers actually use in trial-key messages —
Cohere's is "You are using a Trial key, which is limited to 1000 API calls
/ month". That 429 fell through to the generic short-backoff rate_limit
path, so a monthly allowance that will not reset for the rest of the
billing cycle kept being retried every few seconds.
Broaden the pattern set to catch both phrase orders and the "N calls /
month" and "N requests/month" spellings.
Observed in production against Cohere trial keys: 481 of 752 429s in 24h
carried this text and were all treated as short transient rate limits.
* docs(changelog): add fragment for #12252
---------
Co-authored-by: brick30llc-ctrl <admin@brick30.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
The release tip went red on check:file-size after #14065 (fix(codex): whitelist
reasoning object keys before the wire, #13643) merged with +1 line in
open-sse/executors/codex.ts and no baseline entry — the PR->release fast-gates
do not run check:file-size. Every merge-train boarding after it inherits the
red, so the drift is absorbed once at the tip (owner-approved train-rebaseline
policy, 2026-09-18). Measured clean: check:file-size passes on the tip with
this entry.
Adds a shadow release-acceptance report alongside release-green: an inventory/reduce/oracle pipeline under `scripts/quality/release-acceptance/` with a JSON schema, fixtures and a workflow that uploads the report as an artifact.
Contained by design, which is why it merges as-is: it runs only on push to `release/v*` and on manual dispatch (never on pull requests), the step is `continue-on-error`, `permissions: contents: read`, `persist-credentials: false`, and it consumes no secrets. Nothing in the product changes; the report is advisory until we decide to promote it.
Validated as a combined board first (this PR merged with the 11 siblings of the same batch on the release tip): eslint on every changed file with the suppressions file, typecheck:core, check:open-sse-typecheck, complexity, cognitive-complexity, changelog-integrity, i18n new-key coverage, docs-sync, migration-numbering, provider-consistency and a duplicate-identifier audit all green, plus 275 passing / 0 failing focused node:test cases across the 28 test files the batch touches. Then re-validated alone on the fresh tip before this merge: conflicts re-resolved, file sizes rebaselined for this PR's own growth, eslint and this PR's focused tests re-run.
Thanks @HouMinXi!
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
The Codex executor now whitelists the wire `reasoning` object to `effort`/`summary` before dispatch instead of spreading whatever the client sent, and maps `reasoning.enabled === false` to `effort: "none"` when no more specific effort was requested. OpenRouter-style keys (`enabled`, `max_tokens`, `exclude`) were reaching the Responses API and 400-ing the whole combo target with `Unknown parameter: 'reasoning.<key>'`.
The precedence chain keeps an explicit per-request effort ahead of `enabled: false`, and the strip matches the siblings already removed in the same function (`truncation`, `user`, `prompt_cache_retention`).
Validated as a combined board first (this PR merged with the 11 siblings of the same batch on the release tip): eslint on every changed file with the suppressions file, typecheck:core, check:open-sse-typecheck, complexity, cognitive-complexity, changelog-integrity, i18n new-key coverage, docs-sync, migration-numbering, provider-consistency and a duplicate-identifier audit all green, plus 275 passing / 0 failing focused node:test cases across the 28 test files the batch touches. Then re-validated alone on the fresh tip before this merge: conflicts re-resolved, file sizes rebaselined for this PR's own growth, eslint and this PR's focused tests re-run.
Thanks @HouMinXi!
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Closes a real process-killer: the direct-response start timeout could fire after the fetch promise had already settled, and aborting at that point delivered the abort reason to a promise nobody was awaiting — Node promotes that to an `unhandledRejection` → `uncaughtException` and the process dies (#12861). The timer is now a no-op once the attempt has settled, and the same guard is extended to combo hedge cancels and upstream fetch failures.
Validated as a combined board first (this PR merged with the 11 siblings of the same batch on the release tip): eslint on every changed file with the suppressions file, typecheck:core, check:open-sse-typecheck, complexity, cognitive-complexity, changelog-integrity, i18n new-key coverage, docs-sync, migration-numbering, provider-consistency and a duplicate-identifier audit all green, plus 275 passing / 0 failing focused node:test cases across the 28 test files the batch touches. Then re-validated alone on the fresh tip before this merge: conflicts re-resolved, file sizes rebaselined for this PR's own growth, eslint and this PR's focused tests re-run.
Thanks @HouMinXi!
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Declares the accepted thinking-effort tiers per Agnes chat model (2.0/2.5: none/low/medium/high/max; 3.0 adds minimal/xhigh), so the generic declared-tier clamp maps `xhigh`/`off` onto values the upstream accepts instead of forwarding them verbatim and collecting a 400.
Validated as a combined board first (this PR merged with the 11 siblings of the same batch on the release tip): eslint on every changed file with the suppressions file, typecheck:core, check:open-sse-typecheck, complexity, cognitive-complexity, changelog-integrity, i18n new-key coverage, docs-sync, migration-numbering, provider-consistency and a duplicate-identifier audit all green, plus 275 passing / 0 failing focused node:test cases across the 28 test files the batch touches. Then re-validated alone on the fresh tip before this merge: conflicts re-resolved, file sizes rebaselined for this PR's own growth, eslint and this PR's focused tests re-run.
Thanks @HouMinXi!
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
* fix(db): never TRUNCATE-checkpoint a live WAL
A live TRUNCATE checkpoint rewrites the shared wal-index while other
processes hold it mapped; dereferencing the stale mapping SIGBUSes the
process. Two production crashes six hours apart, coredump stack in
better-sqlite3 native memcpy (issue #13973).
Remove the periodic TRUNCATE scheduler. Runtime checkpoints are
PASSIVE-only, which move pages without changing the wal-index geometry,
while TRUNCATE stays on the shutdown path where reclaiming the file is
safe. The 256MB size guard now warns instead of escalating to a live
TRUNCATE, busy PASSIVE ticks feed the persisted busy telemetry that the
TRUNCATE tick used to carry, and a positive
OMNIROUTE_WAL_TRUNCATE_INTERVAL_MS logs a one-time deprecation warning.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* fix(db): RESTART the WAL when it exceeds the size guard
The 256MB size guard only warned, so a live WAL could keep growing until
the next restart. wal_checkpoint(RESTART) starts a new WAL file without
rewriting the mapped wal-index, which is what SIGBUS'd the process when
we used TRUNCATE under traffic.
Related to #13973.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* docs: drop a fake TRUNCATE env name from the WAL guard row
Backticks around TRUNCATE made the env/docs checker treat it as a
variable. The VACUUM rows next to it were never part of this change
and are not in the base docs.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
---------
Signed-off-by: Minxi Hou <houminxi@gmail.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Every PR against release/v3.8.51 is born red on all four Unit Tests fast-path
shards. Reproduced on the pure tip (1603c86e): ~35 tests. This commit repairs
the two large clusters plus the stale assertions sharing their root cause
(17 tests); the rest is tracked separately.
RTK (12 tests, real regression): #13521 gated dedup on
skipFilters || isDocumentLikeRead
but isDocumentLikeRead is true for ANY text whose type detection is unknown —
not only non-shell tool results — so plain repeated tool output (the classic
RTK case) stopped being deduplicated, processRtkText returned no stats, and
rtkEngine.apply().stats.engine came back undefined. The intent of #13388 was
the non-shell-tool skip, which resolveToolMeta already expresses as
skipFilters; dedup now honours only that. The #13521 regression guard
(rtk-file-content-preservation, tool named 'read' → skipFilters) still passes
4/4; rtk-engine is back to 9/9.
Golden + stale assertions (5 tests, product changes never propagated):
- tests/snapshots/provider/translate-path.json: xKiro (#12648) was added to the
registry without regenerating the snapshot — purely additive entry.
- providers-constants-split: APIKEY_PROVIDER_COUNT 241 → 242 (xKiro).
- tests/snapshots/g13/combo-chatcore-public-seams.json and the three
Content-Type assertions in chatcore-translation-paths / chat-route-coverage:
#13419 deliberately made streaming responses declare
'text/event-stream; charset=utf-8' (Arabic/Persian mojibake) and updated the
integration test but not these unit assertions.
Before/after on the 26 base-red files: 266 tests, 23 → 18 failing here
(the RTK suites were counted per-file in CI; per-test this is 17 fixed). The
file-size ✗ on chatcore-translation-paths.test.ts is the pre-existing drift
#14016 rebaselines — this commit keeps that file's line count unchanged.
The gate fails on the pure release/v3.8.51 tip (3 files above the frozen
baseline), so every PR against the release is born red on it. None of the
three is a PR defect — they are drift from merged work:
- src/lib/usage/glmResetCards.ts: entered the gate's scope when #12754 added
the route that imports it. runWithProxyContext is an untyped async helper
(Promise<any>), so runWithConnectionFetch<T> could not return T. Every call
site passes an async callback and awaits it — declare that contract:
fn: () => Promise<T> → Promise<T>.
- src/sse/handlers/chat.ts: handleSingleModelChat had no return annotation, so
runWithTransientBackendRetry<T extends ResponseLike> fell back to the
constraint and the value could no longer feed withSessionHeader(Response).
Annotated Promise<Response> (every return path builds a Response).
- src/app/api/internal/codex-responses-ws/route.ts: the bridge helpers return
either { error: Response } or a payload, but as unannotated object-literal
unions TypeScript synthesised error?: undefined on the success member, and
every "error" in x guard stopped narrowing (TS2339 x5 on the destructure).
Explicit return types keep the discriminant real; the ApiKeyMetadata alias now
points at the policy shape (the wider one both sources are assignable to),
which clears the TS2740 self-mismatch; logger.warn → log.warn (the module
logger factory has no .warn).
check-api-typecheck.mjs: OK — 283 errors, baseline ratcheted DOWN from 294
(codex-responses-ws 7→4 TS2339, TS2740 1→0; combos/test and keys/[id] 1→0).
typecheck:core clean; 43/43 unit tests in the touched areas green.
tests/unit/chatcore-translation-paths.test.ts 3447 -> 3449, from #13173 (Fable
mid-conversation cache prefixes — the new assertions for that case).
This is the only one left. The other two this PR originally carried
(chatHelpers.ts and chatCore.ts) were absorbed by the rebaselines the merging
PRs brought with them, so the branch was rebuilt on the current tip rather than
shipping stale numbers. Measured clean: check:file-size and test-file-size both
pass with no violations.
* fix(ci): document OMNIROUTE_STRIP_SYSTEM_PREAMBLE (env/docs contract base-red)
* fix(ci): allowlist COMBO_LOOP_SAFETY_TIMEOUT_MS as a doc-only source constant
The env/docs contract gate had a SECOND violation on the release tip, added after
this branch was cut: #13857's comboTimeoutMs narrative in ENVIRONMENT.md cites
COMBO_LOOP_SAFETY_TIMEOUT_MS, which is a source constant
(open-sse/services/combo/comboPredicates.ts:35 — `10 * 60 * 1000`), not an
operator-facing env var. The doc regex captured the SHOUTY_NAME and reported it
as documented-but-missing-from-.env.example.
DOC_ONLY_ALLOWLIST already exists for exactly this class (see CLI_COMPAT_OMITTED_PROVIDER_IDS,
LOCAL_ONLY_API_PREFIXES, VACUUM). Gate now reports all three directions in sync.
* fix(i18n): review-locale reviews every leaf of a catalog that did not exist at --since
* fix(i18n): review the 64 non-pt-BR dashboard catalogs for translation quality
Runs scripts/i18n/review-locale.mjs over every locale except pt-BR (done in
#13885): 75,263 corrections applied against the English source, 1,677 of
them reverted because the "correction" replaced a real translation with the
plain English term (the real-translation ratio gate counts those as
untranslated). zh-CN/zh-TW provider term normalised after the run.
review-locale.mjs hardening found by the run: per-batch retries with backoff
(a skipped batch is listed, not fatal), catalog checkpoint every 25 batches,
and setDeep resolving leaf keys that contain a dot.
* test: expect the jina alias prefix in the custom-model catalog case
The custom-model assertions expected ids prefixed `jina-ai/`, but the catalog
prefixes model ids with the provider alias, which is `jina`. The synced-model
test directly above asserts `jina/` and passes, so the two cases contradicted
each other within the same file.
The expectation predates the alias: the test was written in v3.7.9 (2026-05-04)
and `alias: "jina"` was added in v3.8.36 (2026-06-25).
Aligns the two assertions with the sibling test and with the product. The file
now passes 44/44 (was 43 with 1 failure).
Confirmed the assertions still bite: renaming the alias to `jina-XX` fails
exactly these two cases.
* test: pin the pt-BR pack in the two language-pack fixtures
Both tests assert the Portuguese output-style string but configured
languageConfig with enabled:false and defaultLanguage:"en".
resolveOutputStyleLanguage returns "en" on its first line when enabled is not
true, so the English pack was injected and the assertion could never hold.
autoDetect:true would not have helped either: the user turns in these fixtures
are English, so the detector resolves back to "en". The pack under test has to
be pinned, hence autoDetect:false with an explicit defaultLanguage.
This restores coverage rather than just turning the suite green. Mutating the
pt-BR pack string in outputMode.ts now fails exactly these two tests; with the
old fixture the file reported 9 pass / 2 fail whether the pack was intact or
mutated, so it detected nothing. File is 11/11 (was 9 + 2 failures).
The third languageConfig fixture in this file belongs to an rtk test that makes
no language assertion and is left untouched.
* test: keep the canonical jina-ai prefix in the catalog case
Reverts 8d371d4. The catalog file holds two Jina cases that are not the
same scenario: the custom-model/alias case legitimately expects the
`jina/` alias prefix, while the specialty-model case expects the
canonical provider id `jina-ai/`. Aligning the second to the first reads
like a fix but changes a passing assertion into a failing one.
Verified against the current release tip by mutation, both directions:
the specialty case passes as `jina-ai/...` and fails as `jina/...`, with
the runner reporting `actual: 'jina-ai/jina-embeddings-v5-text-small'`.
The canonical ids are what the source declares — `embeddingRegistry.ts`
and `rerankRegistry.ts` both key the provider as `jina-ai`, as does
EMBEDDING_RERANK_PROVIDER_IDS in src/shared/constants/providers.ts.
The pt-BR language-pack commit on this branch is untouched: that one is a
real fix and repairs two genuinely failing assertions.
---------
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* feat(api): add per-key allowAutoCombos to gate the built-in auto/* combos
`auto/*` combos currently bypass per-key authorization entirely. They are
virtual — synthesised in the catalog, never stored as combo rows — so
`resolveRequestedComboName()` returns null for them and
`isComboAllowedForKey()` fails open:
const comboName = await resolveRequestedComboName(modelStr);
if (!comboName) return { allowed: true, comboName: null };
`validateModelAccess()` then sets `requestedComboName = modelStr` for any
`auto/` id and returns before `isModelAllowedForKey()` runs, so
`allowedModels` and `blockedModels` are skipped for those ids too.
The effect is that `allowedCombos` does not constrain `auto/*`: a key
scoped to a single cheap lane can still send `auto/best-coding` and reach
every model on the gateway. `blockedModels: ["auto/*"]` only unadvertises
the ids — it cannot deny them.
Add an explicit per-key flag instead of tightening the fail-open, which
would silently revoke `auto/*` from every key whose `allowedCombos` lacks
an entry for it. `allow_auto_combos` is NOT NULL DEFAULT 1 and the row
parser treats anything but an explicit falsy value as allowed, so every
existing key keeps working and opting out is deliberate.
When set to false:
- `validateModelAccess()` rejects `auto/*` for that key;
- the catalog skips the `auto/*` synthesis loop for it, reusing the
existing `hideAuto` break so the key is not offered ids it cannot use.
Settable via PATCH /api/keys/[id]. The create path and the dashboard
toggle are deliberately left for a follow-up: the API Manager control
needs UI strings across all message catalogs, which does not belong in
the same change as the policy fix.
* feat(dashboard): add the Auto Combos toggle to API key permissions
Exposes the `allowAutoCombos` flag in the API Manager permissions modal so
the per-key gate can be managed from the dashboard rather than only over
the API.
The control mirrors the prompt-compression toggle: a small dedicated
component, a `role="switch"` button, and labels from the `settings`
message namespace.
Defaults to ON. State reads `apiKey?.allowAutoCombos !== false` — using
`!== false` rather than `=== true` so a key that predates the column, or
one that has never been configured, renders as enabled and matches the
`NOT NULL DEFAULT 1` column.
The field is threaded through all three positional lists (the save
handler signature, the modal prop type and the onSave call) plus the
PATCH payload, so no later argument shifts position.
UI strings are added to en.json and to vi.json. Vietnamese is translated
rather than left as a sync placeholder because
tests/unit/i18n-vi-completeness.test.ts asserts key parity with English
and bans `__MISSING__` markers in that locale. The remaining locales fall
back to English at runtime; `i18n:check-ui-coverage` still passes well
clear of its threshold. They are deliberately not mass-synced here: a
full `i18n:sync-ui` run also replicates ~844 unrelated pre-existing gaps
across all 50 catalogs, which does not belong in this change.
* feat(api): advertise the combo description in /v1/models
A combo's description is stored on its record and returned by
GET /api/combos, but the catalog row never carried it, so no client could
show it.
Claude Code's gateway model discovery reads exactly `id`, `display_name`
and `description` from each entry in the /v1/models `data` array and
renders the description in the /model picker — an entry without one reads
"From gateway" instead. Other OpenAI-compatible clients surface it too.
Emit it only when the combo actually has one, so rows for combos without
a description are byte-identical to before. The value is typeof-narrowed
and trimmed because ComboRecord is Record<string, unknown>, and
`comboMetadata` still spreads last so context and capability metadata
keep precedence.
`display_name` is deliberately not sent: a combo's id is already its
human-chosen name, and the field is only consulted when it differs from
the id.
Ref: https://code.claude.com/docs/en/llm-gateway-protocol.md#model-discovery
* fix(api): list a key's allowed combos in /v1/models
`allowedCombos` gates combos; `modelAccessMode`, `allowedModels` and
`blockedModels` gate provider models. The catalog consulted only the
latter, so a key with `modelAccessMode: "restricted"` and an empty
`allowedModels` received an empty catalog — zero rows — while every combo
in its `allowedCombos` dispatched normally. The catalog contradicted the
key.
Observed on a live gateway: a key with 24 entries in `allowedCombos` and
`restricted` + `allowedModels: []` returned {"object":"list","data":[]},
yet `claude-orchestrate` answered 200 on that same key.
Gate combo rows on `allowedCombos` instead of hiding them. Listing a
combo the key can already dispatch grants no new access, so this is a
consistency fix rather than a relaxation, and it needs no opt-in: the
rule is simply that a key's catalog shows what that key can use.
auto/* rows are exempt. They fail open at dispatch — they resolve to no
stored combo — and their synthesis is already gated by allowAutoCombos,
so gating them here would make the catalog stricter than dispatch.
The decision lives in a new exported helper, isComboNameAllowedForKey(),
which wraps the existing matchesComboAccessRule. An absent list means no
combo restriction, matching validateComboAccess, which skips the check
when allowedCombos is not an array; an empty list allows nothing.
Also advertise `display_name` on combo rows from an operator-set
`displayName` field. Claude Code uses it as the picker entry's name when
it differs from the id, which lets a combo carry a discovery-compatible
id and still read cleanly. It is never derived from the combo name — an
unset field advertises nothing.
* fix(api): accept displayName on the combo schemas
The previous commit advertises `display_name` in /v1/models from a
combo's `displayName`, but neither createComboSchema nor
updateComboSchema declared the field, so Zod stripped it from every
request body and the value could never be set. The endpoint would have
answered 200 and written nothing — the feature was unreachable.
This is the same silent no-op that made `blockedModels` unsettable on
API keys: a field plumbed through the route and the store, missing only
its schema declaration.
Declare it on both schemas and count it in updateComboSchema's "no valid
fields" guard, so a body carrying only `displayName` is a valid update
rather than being rejected as empty. Nullable on update so a label can be
cleared.
* feat(api): add per-key catalogScope to scope what /v1/models advertises
A key had no way to say which kinds of thing its catalog should list. It
always advertised whatever the key's model and combo policies permitted,
mixed together. A client that builds its model picker from /v1/models —
Claude Code's gateway discovery, for one — then sees provider models
alongside the curated combos it was meant to offer.
Add a three-way per-key setting: "all" (default), "combos", "models".
This is a listing preference, not an access control: narrowing it never
changes what the key may dispatch, which the model policy and
allowedCombos continue to decide. That is why it is an explicit setting
rather than implied behaviour — unlike gating combo rows on
allowedCombos, which was a correctness fix and needed no opt-in.
Defaults to "all" everywhere: the column, the parser, the metadata and
the UI state, so every existing key is unchanged. The parser widens to
"all" on an unrecognised value rather than narrowing, so a bad value can
never silently hide rows an operator expects to see.
The dashboard control is a segmented radio group beside the Auto Combos
toggle. UI strings are added to en.json and vi.json; the remaining
locales fall back to English, and vi is translated rather than left as a
sync placeholder because tests/unit/i18n-vi-completeness.test.ts asserts
key parity and bans markers there.
* fix(api): invalidate the model catalog on key visibility changes
updateApiKeyPermissions already advances the unified /v1/models catalog
generation for the fields that change what a key may dispatch, but the two
fields this branch introduces -- allowAutoCombos and catalogScope -- were
missing from that predicate. Both change what the catalog advertises, so a
PATCH toggling either one left the request-shaped catalog cache serving the
previous listing until its TTL expired, and the dashboard's API-key screen
could show a catalog that disagreed with the key it had just written.
Add the two fields to the existing predicate -- no new cache machinery. The
call still runs only after a successful write, so a no-op or failed update
does not invalidate, and unrelated metadata edits (isActive, rate limits)
still leave the catalog cached.
Observed on a live deployment before the fix: PATCH catalogScope="combos"
returned 200 and the column read back "combos", yet GET /v1/models kept
returning the previous mixed rows until a process restart, after which the
same key correctly returned combo-only rows.
* docs(changelog): add fragment for per-key allowAutoCombos and catalogScope
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* chore(quality): rebaseline the two ceilings this PR's own growth moved
src/app/api/v1/models/catalog.ts 2075 -> 2117 and src/lib/db/apiKeys.ts
1625 -> 1659. Measured on the clean tip first: catalog.ts sits at 2074 (under
its 2075 ceiling) and apiKeys.ts at 1620 (under 1625), so none of this is
inherited — it is the feature itself. Gating the built-in auto/* combos per key
means the permission field has to be read, validated and carried all the way to
the catalog filter, and each of those is an explicit call site rather than
something extractable without hiding the gate.
Covered by the PR's 25 tests. The other violations in this tree (chatHelpers.ts,
chatCore.ts, chatcore-translation-paths.test.ts) are inherited base-reds and were
left untouched.
---------
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* chat/suffix-effort: keep reasoning intent tied to each model attempt
Carry resolved suffix effort through dispatch without treating a derived
value as explicit client input. Prepare reasoning defaults and dependent
parameter constraints for each handler attempt so a replacement model
does not inherit the original model's suffix.
Keep explicit reasoning choices in context-aware request hashes to avoid
sharing concurrent responses across different effort settings. Preserve
the legacy hash interface and tenant namespace.
Exercise retries, credential refresh, tool follow-ups, replacement models
and overlapping requests with local HTTP and targeted regression tests.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* chat/upstream-body: separate normalization from async payload preparation
Keep synchronous per-attempt normalization together so payload preparation
stays within the function size and complexity limits without changing its
ordering or explicit reasoning semantics. Condense redundant provider
selection comments to retain the formatted file within its size ceiling.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* changelog: record the suffix-effort propagation fix
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* fix(quality): rebaseline file-size cap for chatHelpers.ts growth
The release tip independently grew src/sse/handlers/chatHelpers.ts from
1164 to 1213 lines while the frozen cap sat at 1214; this PR's own +3
lines (threading resolvedThinkingEffort through resolveModelOrError and
executeChatWithBreaker) push the merged result to 1217, past the cap.
Owner-approved exception for this file only, with the measured growth
breakdown recorded in the baseline entry.
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
---------
Signed-off-by: Minxi Hou <houminxi@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(db): skip integrity scans during health polling
* test(db): update health error fixture for scan-free polling
* docs(changelog): add fragment for health poll integrity skip
* fix(db): keep the #13149 dashboard skip inside the #13717 managed health check
Merge fallout only: runManagedDbHealthCheck moved behind the health
coordinator on the release tip, so the per-call skipIntegrityCheck now
travels through it. A waived integrity scan is part of the job identity,
so it is never replayed from the 60s diagnosis cache to a caller that
asked for the full scan.
Co-authored-by: cryptiklemur <cryptiklemur@users.noreply.github.com>
---------
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: cryptiklemur <cryptiklemur@users.noreply.github.com>
* mcp/audit: fall back when better-sqlite3 export is not callable
Dashboard MCP status polls reopen a failed native sqlite load every 30s
because a minified TypeError ("a is not a function") was not treated as
a native load failure and a failed open was not cached. Classify that
shape, fall back to node:sqlite, cache the miss, and refuse to ship a
Docker image without better_sqlite3.node.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* mcp/audit: force native better-sqlite3 compile in Docker
better-sqlite3 13 ships a linux prebuild. Bare `node-gyp rebuild`
then only TOUCHes stamp files and never writes
build/Release/better_sqlite3.node, so the new test -f gate fails the
image build. Pass --force_build=1, matching the package's own
build-release script.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* db/core: keep native-load classification under the file-size cap
The audit fallback added two TypeError fingerprints in core.ts and
crossed the frozen 1788-line cap. Move the classifier into
sqliteLoadError.ts and re-export it so existing importers stay stable.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* build/bootstrap: keep the encrypted-credentials probe narrow
The native-load classifier was copied into scripts/build/bootstrap-env.mjs
alongside the runtime one, but the two files consume its verdict in opposite
directions. In src/lib/db/sqliteLoadError.ts a true verdict means "the driver
is unusable, cascade to node:sqlite", so treating a non-callable export as a
load failure is what we want. In the bootstrap the verdict feeds
hasEncryptedCredentials, where true means "no encrypted credentials found" and
clears the way to generate a fresh STORAGE_ENCRYPTION_KEY.
With the TypeError patterns in the bootstrap copy, a binding that loads but
exports something non-callable over a database full of enc:v1: rows reads as an
empty database, and the operator silently loses access to every stored
credential. Drop those two patterns from the bootstrap copy only, and note in
both files why the pair is deliberately not identical.
A corrupt binding still fails loudly there, now with the database path, the
underlying message, and a rebuild hint, so the narrower classifier does not
cost any diagnosability.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* fix(mcp): keep audit logging recoverable when the database is created later
getDb() cached a null for the "storage.sqlite does not exist yet" branch, and
closeAuditDb() returns before clearing a falsy cache — so an MCP server started
before the app created the database stayed without audit logging for the whole
process lifetime. Only a genuine driver-load failure is cached now; the
not-found branch retries, which is how it recovers when the file appears.
Covered by a new test that fails without the change.
Also replace the fabricated minified TypeError text ("a is not a function")
thrown by the loader with "better-sqlite3 export is not a function": the
operator sees a diagnosable message and isNativeSqliteLoadError() still
classifies it (it matches on "is not a function").
---------
Signed-off-by: Minxi Hou <houminxi@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* feat(dashboard): expose comboTimeoutMs next to Target timeout
The runtime already applied config.comboTimeoutMs as the whole-combo
wall-clock budget (0 = 10-minute hang-stop). Schema treated it as an
unknown passthrough key and the dashboard only painted Target timeout,
so operators could not raise the 15-step failover ceiling from the UI.
Declare comboTimeoutMs on comboRuntimeConfigSchema, mount both knobs in
the combo editor Advanced panel and Combo defaults, and keep
comboTimeoutMs longer than targetTimeoutMs so failover still has time.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* docs(changelog): attach #13857 to comboTimeoutMs fragment
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* test(dashboard): name comboTimeoutMs store as milliseconds
The input is seconds; the stored config field is milliseconds. The old
title said "in seconds" while asserting 1_200_000.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* chore(i18n,changelog): translate #13857 keys into all locales and drop the CHANGELOG hunk
---------
Signed-off-by: Minxi Hou <houminxi@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* feat(compression): make Lite tool-result truncation length configurable
Lite truncated tool results at a hardcoded 2000 characters. Coding-agent
payloads (file reads, crash dumps) lost the middle of the content with no
supported way to raise the cap.
Honor lite.maxToolLength from settings, then OMNIROUTE_LITE_MAX_TOOL_LENGTH,
then 2000. Existing installs keep the old length.
Related to #13178.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
#13178 stays open.
* compression/lite: keep a stored cap when a step or toggle write is incomplete
An out-of-range step maxToolLength was still a number, so it hid a valid
global cap and fell through to env. A toggle-only settings PUT replaced
the whole lite row and dropped the stored cap. Save treated an out-of-range
number like a cleared field. Reject the bad Save, merge omitted caps, and
use null to clear.
Related to #13178.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* compression/lite: stop dashboard copy from hard-coding a 2000-char cap
The page overlays schema descriptions from i18n. Updating only
LITE_SCHEMA left operators seeing "over 2,000 characters" after the
cap became configurable. Also assert the Save error string, not the
Save button.
Related to #13178.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
* chore(changelog): move #13915 entry to a changelog.d fragment
---------
Signed-off-by: Minxi Hou <houminxi@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(db): reclaim freed pages incrementally instead of a blocking VACUUM in the cleanup scheduler (#12821)
startCleanupScheduler() ran a synchronous whole-database VACUUM on the event
loop whenever a cleanup pass deleted at least one row - 30 s after every
start and every 6 h. With node:sqlite that blocks every route (/healthz
included) for the duration: 7 min 55 s on a 540 MB storage.sqlite to reclaim
six rows. It also bypassed vacuumScheduler, the app-level owner of full
VACUUMs and the operator's scheduledVacuum / vacuumHour settings.
cleanup.ts no longer issues a full VACUUM. After each pass reclaimFreedPages()
branches on PRAGMA auto_vacuum:
- INCREMENTAL: drain the freelist with PRAGMA incremental_vacuum(N) in ~1 MiB
batches (N from page_size), pausing between batches for as long as the last
one took (<=250 ms), PASSIVE checkpoint every 64 batches and a TRUNCATE
checkpoint at the end so the main file shrinks in WAL mode; hard caps of
2048 batches / 30 s per pass, the remainder waits for the next pass.
- FULL: nothing to do, SQLite reclaims on commit.
- NONE: incremental_vacuum is a no-op, so record a request via the new
vacuumScheduler.requestFullVacuum(); the rebuild runs in the configured
window (or via the Storage page button). scheduledVacuum=never is honored.
vacuumScheduler persists fullVacuumRequestedAt / fullVacuumRequestReason,
clears them on the next successful runNow(), and hydrates from key_value
before an early request so it cannot clobber a persisted lastRunAt.
Loop robustness: db.exec() rather than pragma() (bun:sqlite's all() steps a
zero-column pragma once), SQLITE_BUSY/LOCKED and a handle closed under the
pass stop it quietly, other errors stop it with partial progress logged.
Also drops the duplicate cleanupProxyLogs() call in the scheduled pass -
runAutoCleanup() already covers proxy_logs.
Tests: new tests/unit/db/cleanup-reclaim-freed-pages.test.ts (INCREMENTAL
drain/pause/checkpoint, page_size-derived batch, caps, FULL no-op, NONE
defers and leaves page_count untouched, runScheduledCleanupPass() path);
vacuum-scheduler.test.ts covers requestFullVacuum persistence, restart
survival and clearing; cleanup-column-fix.test.mjs now asserts
incremental_vacuum and the absence of a full VACUUM statement.
* chore(changelog): name the #12821 fragment after its PR (#12830)
* fix(db): extract reclaimFreedPages into its own module and fix full-suite regressions
Split the #12821 incremental-vacuum reclamation logic out of cleanup.ts
into src/lib/db/reclaimFreedPages.ts (re-exported for callers/tests) so
cleanup.ts stays under the file-size cap after the #13011 reconciliation
merge grew it past the 1200-line threshold.
Also fixes two full-suite failures surfaced by running the
cleanup/vacuumScheduler/db-health suite post-merge (not just this PR's
own 3 test files, per the plan-file's mandatory item):
- tests/unit/cleanup-column-fix.test.mjs scanned cleanup.ts's raw source
for the PRAGMA incremental_vacuum invariant, which now lives in the
extracted module — updated to scan both files.
- tests/unit/db/cleanup-reclaim-freed-pages.test.ts asserted the freelist
count is byte-for-byte unchanged when auto_vacuum=NONE. The tip's
runAutoCleanup() now also runs cleanupCompressionRunTelemetry(), which
lazily creates its table on first use (ensureCompressionRunTelemetryTable)
— a legitimate one-time page cost from a freshly migrated DB, unrelated
to reclaimFreedPages()'s own behavior. Loosened the assertion to a small
tolerance while keeping the page_count assertion that actually guards
against a full rebuild.
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* chore(db): drop the reclaimable-bytes VACUUM gate test superseded by incremental reclaim
tests/unit/vacuum-reclaimable-threshold.test.ts pinned cleanup.ts's
vacuumAfterCleanup()/getReclaimableBytes()/getVacuumMinReclaimableBytes()
(#13079). This branch removes the inline post-cleanup full VACUUM entirely in
favour of reclaimFreedPages() (#12821), which reads the same freelist_count /
page_size signal and defers a full VACUUM to the vacuum scheduler when
auto_vacuum=NONE. With those three exports gone the file cannot compile, and
the behaviour it guarded no longer exists.
---------
Co-authored-by: insoln <is@careerum.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* feat(usage): redeem GLM Coding Plan Reset Cards from Provider Limits
z.ai sells Reset Cards that clear an exhausted GLM coding-plan window (5-hour or
weekly) ahead of its natural rollover, but OmniRoute only ever read the passive
nextResetTime, so redeeming one meant leaving the dashboard.
Add the wire layer for z.ai's two reset endpoints
(/api/biz/customer-package-reset/list and /use), which authenticate with the same
Bearer API key as /api/monitor/usage/quota/limit and report failures inside an
HTTP-200 envelope, so callers must inspect success/code rather than the status line.
The banked count rides along with the quota poll - only for keys that actually
report a resettable window, and strictly best-effort so a card-less account or a
transient failure still renders its quotas. The existing reset-credit card, picker
and confirmation flow, until now gated to Codex, now also drive glm/glm-cn/glmt/zai
through the new /api/usage/glm-reset-card route, reusing z.ai's requestId as the
idempotency key so a retry cannot burn two cards.
* test(usage): cover GLM reset-card edge cases
* test(dashboard): require GLM reset-card copy
* fix(usage): harden GLM reset-card redemption
* fix(usage): treat missing GLM key as empty
* fix(usage): fence GLM reset-card operations and coalesce lease-window duplicates
- Acquire a synthetic 60s exclusive-connection lease around each list/use
wire operation; release in finally so a competing lease can acquire
immediately after success or failure.
- Coalesce same-key duplicates that arrive after lease acquisition by
checking the in-flight attempt before loading the connection.
- Run the post-commit quota refresh outside the lease (redemption is
already committed; the refresh is auxiliary and failure-tolerant).
- Do not discard a retained ambiguous attempt on a lease-conflict 409.
- Harden transport error mapping: static messages for proxy transport
failures, keep explicit direct routing for unproxied connections
through list, use, and refresh.
* fix(i18n): sync GLM reset-card keys to pt-BR and vi locales
---------
Co-authored-by: insoln <is@careerum.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(codex): fail the stream when the websocket closes before a terminal event
* docs(changelog): add fragment for Codex websocket premature-close fix
* chore(quality): rebaseline file-size baselines for #12737 test and executor growth
* fix(codex): log websocket failures and harden premature-close tests
Review follow-up: failController now logs the failure (code + message)
via nextInput.log, and onclose surfaces the WS close code/reason in the
log line (the public payload stays sanitized through the allowlist).
Adds regression tests for the onerror-before-onclose sequence and a
close with zero prior events.
* chore(quality): re-measure the #12737 codex.ts file-size rebaseline after the release merge
The PR's own annotation was written against base 1505 and the frozen cap was
already at 1528 on release/v3.8.51 (which grew the file independently). With
this PR's +13 lines the merged file measures 1530, so the frozen entry moves
1528->1530 (+2 of genuine PR growth; the remaining 11 lines fit the headroom
the tip already had). No other frozen entry touched.
---------
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(providers): read the vLLM context window from max_model_len
normalizeDiscoveredModels resolved the window from inputTokenLimit,
context_length, contextLength and top_provider.context_length. vLLM
reports it as max_model_len and nothing else, so a synced vLLM model
carried no inputTokenLimit and the resolver fell back to the 128K
default - half the window on a 250K deployment.
The native vllm provider and the OpenAI/Anthropic-compatible custom
providers all pass raw records through this function, so one chain entry
covers the three connection shapes.
Closes#12858
* docs(changelog): fragment for #12897
---------
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>