- auto/best-vision and auto/pro-vision now resolve to the vision CATEGORY
(candidate filter by capability) instead of the flat smart variant, so the
vision-bridge describe/reroute target can actually see images
(resolveBuiltinAutoSpec in builtinCatalog).
- vision candidate pool excludes registry entries whose catalog OVERSTATES
vision support (opencode-go/opencode-zen/tokenrouter are forced through the
vision bridge by isVisionBridgeForcedModel) in both the auto-combo candidate
filter (suffixComposition) and the vision router (visionBridgeRouter).
- reroute guard: an auto/* target is a virtual combo; a missing 'auto' provider
row (hasUsableCredentials=false) must never block the reroute.
- claude-wire backends (minimax, zai, ...) reject remote image URLs (MiniMax
403 2013): ensureBase64ImagesForClaudeWire resolves URLs to base64 before
rerouting, and the describe self-loop normalizes to base64 for those targets
(isClaudeWireFormatModel).
- self-loop describe uses a real DB-backed key (resolveSelfLoopApiKey) instead
of the sk_omniroute sentinel rejected by REQUIRE_API_KEY instances, and
bypasses the runtime's hooked global fetch via undici (ProxyFetch with a dead
local proxy would otherwise break every describe); compression is disabled
on the self-loop sub-request so image payloads are never mangled.
Tests: vision-bridge-auto-reroute (2), vision-bridge-selfloop-key (4),
vision-bridge-claude-wire (6), builtin-vision-spec (4),
vision-filter-excludes-forced (4).
Co-authored-by: herjarsa <herjarsa@users.noreply.github.com>
* fix: add per-connection virtual admission lanes (#9654)
Worst-day-ever analysis to harden AdaptiveAdmissionController:
- Guard expireEntry() against null entry (CRITICAL null deref)
- Add deleteLane() to drain+reject on LRU eviction (HIGH orphaned promises)
- Fix Map mutation during evictIdleLanes iteration (MEDIUM safety)
- Add ADMISSION_LANE_EVICTED reject code (MEDIUM clarity)
- Pass sessionId to admitChatRequest in route.ts
- virtualLanes defaults to false in validateConfig
- 7 new controller tests + 14 new byte-level admission tests
- Assertions tightened from >= to === (Matt Pocock methodology)
Debunked 2 false positives: concurrency race (single-threaded JS)
and memory amplification (FairCostQueue bounds per-lane).
Fixes#9654
* fix(admission): restore bounded queue-wait on per-connection lanes (#9654)
The per-connection lane refactor dropped the bounded queue-wait
(acquireHeavyWithin / #waiters / queueMs). #9654's acceptance criteria and
#9608 section C prefer server-side wait/pacing up to defaultMaxWaitMs over
an instant retryable 503.
- ChatAdmissionController: re-add #waiters FIFO + acquireHeavyWithin(timeoutMs);
queueMs: 0 preserves the instant-503 path
- admitChatStructure and admitChatRequest.reserve are async again and take queueMs
- route: pass CHAT_ADMISSION_QUEUE_MAX_MS and await the admission calls
- per-connection lane tests await the async admitChatStructure
Admission suite: 114/114 pass (bun test, 7 files).
* chore: re-trigger CI after dast-smoke infra cancellation (#9654)
* feat(admission): cancel queue-wait on client abort (#9654)
U2 from KC plan 2026-08-09-001. Thread the request AbortSignal through
acquireHeavyWithin so a disconnected client stops parking in the FIFO
for the full queueMs.
- acquireHeavyWithin(timeoutMs, signal?): on abort the waiter is removed
from the FIFO immediately and the promise resolves null early;
pre-aborted signals never park; the deadline timer is cleared when
abort/release wins the race
- admitChatRequest reserve() passes request.signal; admitChatStructure
gains options.signal; the route threads request.signal
- 5 exact-assertion tests (settle-early, pre-aborted, byte-heavy,
structural, FIFO-preservation): 119/119 across the 7-file suite
* fix(admission): bound queued bytes for the queue-wait heap valve (#9654)
U3 from KC plan 2026-08-09-001. The restored queue-wait parks fully-buffered
bodies; without a cap, several large coding-agent bodies (~750 KB) waiting at
once recreates the #4380 heap amplification this module was built to stop.
- acquireHeavyWithin(timeoutMs, signal?, queuedBytes): each parked waiter is
charged its buffered size against CHAT_ADMISSION_MAX_QUEUED_BYTES (default
4 MB); over-budget waits reject immediately with a retryable 503 and never
park. The charge is released on wake, abort, or timeout.
- Real sizes threaded from admitChatRequest (declared length / sniffed bytes);
structural waits charge the conservative 256 KB weight.
- Lower default OMNIROUTE_CHAT_ADMISSION_QUEUE_MS to 2000ms (was 5000ms).
- Env vars documented in .env.example; 6 exact-assertion tests: 125/125 across
the 7-file admission suite (was 119).
* docs: map the two admission-lane systems for operators (#9654)
U5 from KC plan 2026-08-09-001. Verifies lane metrics are exposed by the health
payload (GET /api/monitoring/health -> adaptiveAdmission -> lane* fields) and
records which lane system reports where: byte-level per-connection lanes (always
on, memory scope) vs adaptive virtual lanes (opt-in via OMNIROUTE_CHAT_VIRTUAL_LANES,
dispatch scope) plus the explicit opt-in ops note.
* docs: add required frontmatter to admission-lanes doc (dast-smoke build fix)
* docs: sync env vars with .env.example and ENVIRONMENT.md (docs gate fix)
* fix(admission): complete REJECT_MAP, literal lane env read, split oversized test file
Three CI-gate fixes surfaced by the post-merge check run (head 3de77166e):
1. open-sse-typecheck (TS2741): REJECT_MAP was missing the ADMISSION_LANE_EVICTED
entry that controller.ts:662 emits on lane eviction. Add the 503 mapping so the
Record<AdmissionRejectCode, RejectHttpMapping> is total.
2. Docs Gates fabricated-claim: OMNIROUTE_CHAT_VIRTUAL_LANES was read dynamically
via ENV_KEYS.virtualLanes (env[key]), invisible to the literal env.X scanner.
Read it literally — behavior-identical, doc claim now verifiable.
3. check:file-size: chat-body-admission.test.ts (1307 lines) exceeded the 1000-line
new-file cap. Split the queue-wait/abort/heap-valve section into
chat-body-admission-queue.test.ts (818 + 513 lines, both under cap).
Suite: 125/125 across 8 files. All three checkers pass locally.
* refactor(admission): drop dead ENV_KEYS.virtualLanes entry + lock lane-evicted mapping test
Code-review follow-up on 50c93d266:
1. ENV_KEYS.virtualLanes is now unreferenced since the literal env read landed;
remove it so the config map only lists keys actually read through the map.
2. Add an exact-assertion runtime test for the ADMISSION_LANE_EVICTED mapping:
a queued lane waiter evicted by the 60s idle TTL rejects with 503 /
admission_lane_evicted / Retry-After 1 / sanitized body (no raw tenant key).
Proves the REJECT_MAP entry end-to-end through buildAdmissionRejectResponse.
Suite: 126/126 (17 in runtime file, 125 in the 8-file admission suite).
---------
Co-authored-by: Brandon Bennett <brandonbennett@macbookair.myfiosgateway.com>
Wire Bearer /alpha billing credits and 5h/weekly windows into Provider
Limits and genericQuotaFetcher so dashboard and preflight see live CC quotas.
Co-authored-by: Cursor <cursoragent@cursor.com>
opencode.ai/zen/v1 rejects non-browser clients (urllib) with 403
error_code 1010 while curl on the same key succeeds. The 403 was
treated as an auth-level failure and two of them crystallized a
misleading ALL_ACCOUNTS_INACTIVE on the free pool.
- errorClassifier: new FINGERPRINT_REJECTION type; a 403 carrying
error_code 1010 / browser_signature_banned is the CDN refusing the
client TLS/UA signature, not the account credentials.
- combo/targetExhaustion: fingerprint rejections skip auth-level
exhaustion so remaining targets stay eligible.
- auth: resolveTerminalConnectionStatus no longer treats the
fingerprint rejection as a terminal banned account state.
UA passthrough is deliberately untouched: #5997/#5720 make the
forward-only behavior load-bearing.
Signed-off-by: Minxi Hou <houminxi@gmail.com>
process.uptime() returns a number, but the handler ran it through a
string-only toString() helper that fell back to "unknown" for anything
that wasn't already a string -- so every real uptime value was
discarded, 100% reproducibly.
Also stop masking upstream fetch failures as fake healthy defaults:
when /api/monitoring/health, /api/resilience, or /api/rate-limits
can't be reached, the tool now reports which source failed (via a new
optional `degraded` field) instead of returning zeros/empty arrays
indistinguishable from genuine "no data".
Regression coverage dispatches through the real MCP handler (client.callTool)
rather than asserting on the mock directly, since the prior mock-only
tests could never have caught either bug.
Restore the shared media detector and the hard-reason set lost by the maintainer cherry-pick. Re-document the two live low-memory controls and cover nested case-insensitive image indicators.
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(quality): clears two release/v3.8.50 base-red gates
Unblocks Merge integrity and Docs Gates for every PR against
release/v3.8.50, not just this branch:
- changelog.d/features/9415-newapi-sub2api-aggregator-balance.md had a
non-standard YAML frontmatter header that no other fragment in the
tree uses. check-changelog-integrity.mjs reads a fragment's first
non-blank line to validate it starts with a markdown bullet; the
frontmatter's leading `---` made that check fail regardless of the
actual bullet content further down. Removed the frontmatter and
reformatted the body to match the documented changelog.d/README.md
bullet convention.
- docs/ops/VM_DEPLOYMENT_GUIDE.md documented OMNIROUTE_MAX_POOL_SIZE
and OMNIROUTE_DB_POOL_SIZE as tunable env vars, but neither is read
anywhere in the codebase (confirmed via full-repo grep) — this repo
uses SQLite, which has no connection-pool concept these vars could
plausibly control. check:fabricated-docs --strict correctly flags
fabricated env-var claims; removed the bullet rather than
implementing a feature to match invented documentation.
* fix(i18n): completes Vietnamese parity, fixes empty migration query
Two more release/v3.8.50 base-red items, both surfaced while chasing
CI failures on unrelated PRs:
- vi.json was missing 8 keys that #9539 (NewAPI/Sub2API aggregator
balance) added to en.json without a matching i18n:sync-ui run —
pt-BR.json already had all 8, only Vietnamese drifted. Added
translations for the 6 provider-settings strings, the feature-flag
description, and the quota tooltip; verified against
tests/unit/i18n-vi-completeness.test.ts (parity, placeholder
preservation, ICU parse — all 5 assertions pass).
- src/lib/db/migrations/120_interception_rules.sql was pure comments
documenting a no-schema-change key_value namespace, with no
executable SQL statement — the migration runner logged
"FAILED: 120_interception_rules — Query contained no valid SQL
statement" on every fresh DB init. 118_provider_param_filters.sql
(same pattern, two migrations earlier) already ends with a bare
`SELECT 1;` no-op for exactly this reason; 120 was just missing it.
Verified directly against better-sqlite3 that the file now executes
without error.
* fix(types): clears 6 pre-existing release/v3.8.50 typecheck errors
typecheck:core is its own blocking CI job (quality.yml), separate from
Docs Gates/Merge integrity. Confirmed pre-existing and unrelated to
any current work by branching this worktree directly from
upstream/release/v3.8.50 with no other merges applied.
- accountSemaphore.ts: isBypassed() already excludes null/<=0
maxConcurrency before ensureGate() is called, but a boolean-
returning helper isn't a type predicate TS can narrow through.
Added a targeted `as number` at the one call site, with a comment
explaining why it's safe.
- combo/comboStructure.ts: two module-scope `const HARD_COMPAT_REASONS`
declarations with different values — a genuine "can't redeclare"
compile error, not a narrowing gap. The first (4-item set including
"output_tokens") had zero usages between its own declaration and the
second; the second (3-item set, matching the CompatFilterOptions doc
comment exactly) is what hasHardCapabilityFailure/
describeCapabilityFilterExhaustion/the third call site all actually
use. Removed the dead first declaration.
- combo/comboStructure.ts + combo/fusionPanel.ts: both accessed
`.prompt`/`.model` on a `ComboModelStep | ComboProviderWildcardStep`
union after only excluding `combo-ref`, but `ComboProviderWildcardStep`
has neither field — a real latent bug (fusionPanel would have pushed
`undefined` into a fusion panel for a wildcard step). Narrowed to
`step.kind === "model"` in comboStructure, and switched to the
already-existing `getComboModelString()` helper in fusionPanel (which
correctly resolves to null for unsupported step kinds, mirroring how
combo-ref is already skipped there). Verified directly via a
standalone script exercising both branches (wildcard vs. model step).
- combo/quotaStrategies.ts: imported `preferAntigravityConnectionsWithStoredProject`
from a module that never existed (`../antigravityProjectPersistence.ts`,
distinct from the real `antigravityProjectPersist.ts`) — the function
itself was referenced nowhere else in the codebase. Wrote the missing
implementation: prefers Antigravity connections with a discovered
`projectId` for reset-aware routing, failing open to the full list
when none have one yet (per the file's own "Exclude... from reset-aware
pool" changelog note, softened to a preference — strict exclusion
would empty the pool entirely for a fleet of freshly-added accounts).
Verified directly via a standalone script.
- compression/engines/ccr/index.ts: `enforceGlobalBudget(owner, bytes)`
was called with only `bytes` at one of its two call sites, missing the
`owner` argument the other call site (and the function's own doc
comment on preferring the calling principal's LRU eviction) already
uses correctly. Added the missing `entry.principalId` argument.
- firecrawlQuotaFetcher.ts: `fetchFirecrawlQuota` was annotated to
return `Promise<QuotaInfo | null>` but every return path constructs a
`FirecrawlQuota` (QuotaInfo extended with remainingCredits/planCredits/
extraCreditsInferred/overPlan) — the type the file already defines and
the type `parseFirecrawlCreditUsage` already correctly returns.
Widened the annotation to match; `FirecrawlQuota extends QuotaInfo` so
this stays compatible with the `QuotaFetcher` contract.
npm run typecheck:core and npm run check:dashboard-typecheck both pass
cleanly. A subset of DB-backed tests in this area also fail, but 100%
attributably to an already-tracked, unrelated migration version
collision (134 -> [ccr_blocks, proxy_logs_egress_ip], see
_tasks/features-v3.8.4/9route/POST-MERGE-AUDIT.md) — confirmed by every
failure's stack trace bottoming out at that exact error, not at
anything touched here.
* fix(sse): update stale ALL_ACCOUNTS_INACTIVE test assertions to ALL_TARGETS_SKIPPED
Two combo-routing-engine.test.ts cases assert the pre-dispatch-skip scenario (isModelAvailable always false, zero dispatch attempts) returns ALL_ACCOUNTS_INACTIVE. Production code already distinguishes this case via the recordedAttempts === 0 branch and returns the more precise ALL_TARGETS_SKIPPED -- the tests were never updated when that branch shipped upstream, so they fail on a clean release/v3.8.50 checkout independent of this PR's changes.
* fix(sse): update second stale ALL_ACCOUNTS_INACTIVE assertion (T24)
Same pre-existing upstream test-drift as 038035f93: t23-t24-fallback-resilience.test.ts's T24 case asserts the pre-dispatch-skip scenario returns ALL_ACCOUNTS_INACTIVE, but production code returns the more precise ALL_TARGETS_SKIPPED when recordedAttempts === 0. Caught by this PR's own fresh CI run after the dirty-mergeable-state fix.
* fix(quality): rebaseline combo-routing-engine.test.ts own-comment growth
The ALL_ACCOUNTS_INACTIVE->ALL_TARGETS_SKIPPED fix (58ab721fe) added explanatory comments (+7 lines), pushing the file past its frozen 3457 cap. CI's PR-mode check:file-size caught it; local check-file-size.mjs was not re-run after that specific commit.
* chore(tests): drop explanatory comments on ALL_TARGETS_SKIPPED assertions
Kept the assertion value fix (ALL_ACCOUNTS_INACTIVE -> ALL_TARGETS_SKIPPED); the comments were unnecessary. Reverts the file-size baseline bump these comments caused (combo-routing-engine.test.ts back to its original 3457).
---------
Co-authored-by: Will Gordon <wgordon@redhat.com>
* fix(sse): grace period before finalizing a client disconnect as 499 (#9653)
A client that closes its connection right after reading a fully-completed
SSE stream can race OmniRoute's own completion bookkeeping: the bytes
already reached the client, but the transform stream's own completion
callback (onStreamComplete, which flips streamCompletionRecorded) hasn't
finished bubbling up when the disconnect handler fires, so the request gets
persisted as a false 499 with zero token usage even though it delivered its
full response.
Confirmed live on real traffic before this fix: a request whose server log
showed "disconnect: request_signal_aborted" at 18236ms was persisted with
status 200 and full token usage (82814/1292) once the grace period let the
real completion win the race, matching what the client actually received.
createClientDisconnectGraceHandler (new leaf in
streamFailureFinalization.ts) polls isStreamCompletionRecorded() for up to
STREAM_DISCONNECT_GRACE_PERIOD_MS (default 10s, env-configurable, 0
disables) before finalizing as a failure. If a real completion lands within
the window, handleStreamFailure's own guard is a no-op and the genuine 200
stands.
Covered by tests/unit/stream-disconnect-grace-period-9653.test.ts (fake-timer
driven: already-recorded completion short-circuits, disabled-grace-period
finalizes immediately, a completion landing mid-window skips finalize
entirely, and no completion ever landing finalizes once the deadline
passes).
(cherry picked from commit 5d0fe28c42)
* chore(quality): rebaseline chatCore.ts for the disconnect grace-period fix
Own growth from the disconnect grace-period fix: 5030->5039 (+9, the
createClientDisconnectGraceHandler wiring at the existing
onClientDisconnectFinalize call site).
---------
Co-authored-by: Markus Hartung <mail@hartmark.se>
* fix(sse): persist per-tool-call JSON escape state across SSE delta chunks
escapeJsonStringValues() reset its inString/pendingEscape state on every
call instead of carrying it forward per tool-call index, so a raw newline
byte (or an already-escaped \n) split across two delta chunks got corrupted
in transit — the model's own output was correctly escaped, OmniRoute broke
it. Root-caused via a dispatched investigation into real OpenClaw traffic
that looked like model-generation quality but wasn't.
Fix: escapeJsonStringValues now takes and mutates a persistent per-call
state object (JsonStringEscapeState), keyed per tool-call index in the
translator's init state and cleared when a tool call is superseded.
* chore(quality): rebaseline openai-responses.ts for the escape-state fix
Own growth from the extracted per-tool-call JSON escape-state fix
(previous commit): open-sse/translator/response/openai-responses.ts
1204->1249 (+45).
---------
Co-authored-by: Markus Hartung <mail@hartmark.se>
* fix(compression): add Lite tool truncation toggle
* fix(antigravity): add missing antigravityProjectPersistence.ts module
The quota-strategy engine (quotaStrategies.ts) imports from
antigravityProjectPersistence.ts, but only antigravityProjectPersist.ts
existed in the tree. Add the missing module with the expected
preferAntigravityConnectionsWithStoredProject() helper and re-export
the existing persistDiscoveredAntigravityProjectId().
Co-authored-by: diegosouzapw <diegosouza.pw@outlook.com>
* fix(file-size): rebaseline strategySelector.ts for Lite truncation toggle
The PR adds one line to threading options?.config?.lite into
applyLiteCompression. Update the frozen size from 1060 to 1061.
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Refs #9629
---------
Co-authored-by: Xiangzhe <xiangzhedev@gmail.com>
Co-authored-by: xz-dev <xz-dev@users.noreply.github.com>
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
* fix(adobe-firefly): open browser sign-in and resolve provider slug in /login
POST /api/providers/[id]/login passed the connection DB id to
inAppLoginService.startLogin, but that service looks up the provider by
slug in TOKEN_EXTRACTION_CONFIGS. The lookup always missed and returned
"No extraction config" without launching a browser — so the VibeProxy
"Sign in" button for Adobe Firefly (and every other web-cookie provider)
never opened a browser.
Adobe Firefly additionally had no extraction config because its IMS JWT
is never in cookies/localStorage — it only rides on the Authorization:
Bearer header of firefly-3p.ff.adobe.io XHRs.
- Resolve the provider slug from the connection row and pass the slug
(not the DB id) to inAppLoginService.startLogin.
- Add open-sse/services/adobeFireflyBrowserLogin.ts: a Playwright
service that launches a visible browser at firefly.adobe.com and
intercepts firefly-3p requests to capture the IMS JWT + sherlockToken
cookie. Wire it into the /login route for the adobe-firefly slug.
- Fix latent bug: updateProviderConnection reads camelCase keys
(apiKey, providerSpecificData), so the previous snake_case call never
persisted extracted credentials.
* fix(adobe-firefly): open browser sign-in and resolve provider slug in /login
POST /api/providers/[id]/login passed the connection DB id to
inAppLoginService.startLogin, but TOKEN_EXTRACTION_CONFIGS is keyed by
provider slug — so browser login never launched for web-cookie providers.
Adobe Firefly also cannot use cookie extraction: the IMS JWT only appears
on Authorization headers to firefly-3p.ff.adobe.io. Add a dedicated
Playwright interceptor and persist credentials with camelCase keys that
updateProviderConnection actually reads.
* fix(adobe-firefly): use system Chrome/Edge CDP for browser sign-in
Playwright is not available inside the pkg-packaged VibeProxyServices.exe,
so import('playwright') always failed with 'Playwright not installed' and
never opened a window. Launch Chrome/Edge with --remote-debugging-port and
capture the firefly-3p Authorization Bearer via pure CDP WebSocket instead.
* fix(adobe-firefly): live x-arp-session-id / Arkose wire (stop 408 under load)
Browser generate-async requires x-arp-session-id as base64({sid,ark,ftr}) with a
real Arkose blob (sherlockToken). JWT alone frequently returns colligo HTTP 408
system under load while credits still work.
- Match live ftr magic __UDF43-m4_31ck + Arkose pk in synthetic ARP fallback
- Ranked extract of sherlockToken / x-arp from Cookie, HAR, fetch() paste, and
space-joined JWT+ARP (PasswordBox newline collapse)
- Reuse one ARP for storage upload + generate-async
- Clearer 408 errors when browser ARP is missing vs stale
- Unit suite 42/42
* fix(adobe-firefly): durable session ARP rebuild and aux_sid false-positive
Rebuild x-arp-session-id from forterToken/arkose/ff_session_guid instead of
ranking long Cookie pairs (e.g. aux_sid=…) as opaque ARP, which caused colligo
HTTP 408. Cache IMS JWT + cookie sessions, rotate ARP on 408 retries, and keep
Playwright warm-up opt-in only (headless Forter is rejected).
Also expand synthetic ARP shape with bfp/fpjs to match live successful captures.
* fix(adobe-firefly): durable session, off-screen Chrome recovery, browser sign-in
Rebuild x-arp-session-id from Cookie pieces (sid/ark/forter) so aux_sid is never
sent as ARP. Sticky ARP + submit spacing reduce mid-batch colligo 408 thrash.
Add optional managed Chrome warm (off-screen headed by default; Forter rejects
headless) and POST /api/providers/{id}/login browser sign-in that returns JWT+Cookie
after a fresh SSO. Visible sign-in resets off-screen window placement and clears
prior Adobe session when adding another account.
* fix(adobe-firefly): renew sessions through durable CDP
* fix(adobe-firefly): isolate browser sessions per account
* fix(adobe-firefly): make account login fresh and deterministic
* chore(adobe-firefly): remove obsolete browser fallback
* docs(adobe-firefly): document renewal controls
* fix(adobe-firefly): harden CDP warm, risk session, and browser sign-in
Stop colligo 408 thrash from stale Forter and frozen Google login during
Sign in with browser:
- CDP warm: clear Firefly origin storage + risk cookies (keep SSO); require
forter age under 10 minutes on loop and timeout paths; dual CDP queues;
await Runtime.runIfWaitingForDebugger; profile-lock launch retries
- Session: connectionId fingerprint; write-back JWT+Cookie; warm-fail
cooldown; fail closed risk_session_stale when forter is known-stale
- Client: submit gate around generate-async; max 2 attempts when forter
known-stale; poll 401 one refresh; pass sessionBrowserKey through handlers
- Login route: pure system Chrome/Edge CDP only; camelCase credential persist
- Unit: browser-login + firefly suites green (60)
---------
Co-authored-by: artickc <artur1992123@mail.ru>
* fix(combo): restore routing module load
* fix(db): resolve ccr migration version collision
Renumber the CCR block-store migration from 134 to 139, reconcile databases that already applied the legacy slot, and add regression coverage for both upgrade paths.
Co-Authored-By: GPT-5 <noreply@openai.com>
* fix(changelog): format the aggregator balance fragment as a bullet
The fragment landed with YAML frontmatter rather than the bullet the
aggregator reads, so check:changelog-integrity exits 1 on every branch and
takes the merge-integrity job down with it regardless of what the branch
changed.
Only the format changes. The entry text is the author's, unedited, and now
carries the link to the pull request that shipped it.
* fix(test): update expected auth/vision/provider schema for base-drifted expectations
* fix(test): narrow this branch to the drifted test expectations
Three other PRs already cover what this one was carrying. #9618 renumbers the
colliding ccr_blocks migration, #9632 repairs the malformed aggregator changelog
fragment, and #9676 restores the combo module load by implementing the selection
helper the import was reaching for, rather than deleting the caller the way this
branch did. Keeping any of it here would put two files back on the same migration
slot and overwrite a better fix with a worse one.
What survives is the part none of them touch. Once the combo barrel loads again,
three assertions in the context-window filter suite start failing: they demand
that catalog-too-small targets be dropped, while the file's own header and its
four neighbouring tests say those targets stay available as runtime fallback.
The unresolved import was masking them. A new case pins the output-token limit
as a genuine hard requirement so the relaxation cannot drift further.
The provider count assertion kept one literal at the old value after the rest of
the file moved to 198, so the partition check failed on a sum that was correct.
* chore(quality): re-time migrationRunner for the 139 guard on the new tip
---------
Co-authored-by: alexey.nazarov@softmg.ru <alexey.nazarov@softmg.ru>
Co-authored-by: GPT-5 <noreply@openai.com>
Co-authored-by: Minxi Hou <houminxi@gmail.com>
* fix(web-tools): anchor tool contract at prompt tail + user-turn reminder
The <tool> contract from prepareToolMessages was prepended as the first
system message. Web executors fold all system messages into one block, so
with agentic clients whose system prompts exceed ~28K chars the contract
sat at the head of a huge block and web models ignored it, refusing tool
calls with "tool X is not in my tool set" (chatgpt-web, 0/3 at 30K chars).
Two changes, both required in testing:
- Dual placement: the full contract now rides as a trailing system
message (folds to the tail of the system block) and a one-line
reminder naming the tools is appended to the latest user message.
- Rewording: the contract now frames injected tools as client tools
invoked via a plain-text protocol, distinct from the model's native
tool registry (web.run, python.exec, ...), and instructs the model to
never claim they are unavailable. Without this the model resolved
tool names against its native registry and refused even when it had
seen the contract.
Measured on cgpt-web gpt-5.5-thinking/gpt-5.6-thinking/o3: prepend 0/3
tool calls at 30K chars; dual placement 16/17 across 30K-250K system
prompts, 30-tool sets, multi-turn tool history, streaming, and 3-way
concurrency, with no spurious calls on no-tool prompts. Known limit:
~40K-char single user messages still flake (2/3) due to the upstream
model's own injection heuristics.
All prepareToolMessages consumers parse system messages
position-independently and select the current user turn by role scan,
so the trailing system message is shape-safe for every web executor.
* test(web-tools): cover contract placement edge cases
---------
Co-authored-by: Ryan Brosas <ryanjoserbrosas@gmail.com>
Wire Openference as a first-party OAuth gateway (PKCE, rotating refresh)
and an API-key catalog entry on api.openference.com, with live model
discovery, connection testing, free-tier badges, and regression tests.
Co-authored-by: Anh Tran <anhlead@outlook.com>
Every duckduckgo-web chat request failed with HTTP 418 ERR_CHALLENGE while
duck.ai worked normally in a browser from the same IP. Ground truth was
established by driving a real headful Chromium at duck.ai from that IP (it
returned 200), so the environment was never the problem — the anti-abuse
challenge solver was. Six independent defects were found; the first alone
disabled the solver completely.
1. Module syntax inside the vm sandbox source.
CHALLENGE_STUBS is executed with vm.runInContext, which compiles in SCRIPT
mode. A refactor mass-added `export` to the five `function` declarations
inside that template literal (they read as ordinary top-level TS functions),
so every solve threw SyntaxError. The executor swallows solve failures and
posts the raw unsolved challenge, which upstream answers with 418.
2. Double-escaped regex in a String.raw template.
`\\s` in __parseCssDisplay reached the sandbox as a literal backslash, so the
display regex never matched and a getComputedStyle probe silently read empty.
3. buildHtmlLookup undercounted descendants by one.
`count` backs el.querySelectorAll('*').length; that returns DESCENDANTS and
countHtmlElements already skips the #document-fragment root, so the `- 1` was
wrong. Chromium reports 3 for '<li><div></li><li></div'; we reported 2, and a
variant multiplies innerHTML.length by that count.
4. Browser-fidelity probes.
Newer challenge variants assert JS/DOM invariants a flat stub cannot satisfy:
real prototype chains (HTMLDivElement -> HTMLElement -> Element), NodeList
identity, a live body.children HTMLCollection, native-code toString, and
sloppy-mode `this === window`. Nine of thirteen failed. Notably Math must NOT
be sealed — Chromium reports Object.isSealed(Math) === false, and sealing it
made our vector differ by one.
5. The solved payload dropped meta.origin / meta.stack / meta.duration.
The duck.ai bundle always sends all three; captured browser requests confirm
it. Without them upstream returns 418 even when every client_hash is correct.
6. reasoningEffort is now mandatory on duckchat/v1/chat.
An otherwise byte-identical payload returns 200 with the field and 400
ERR_BAD_REQUEST without it (A/B verified live, repeated).
Also removes the throwaway "seed" chat POST that ran before every real request.
It existed to coax a usable challenge out of the upstream while the solver was
broken; it only doubled chat calls against an IP-rate-limited endpoint, showing
up as spurious 429 ERR_RATE_LIMIT.
Verification: the solver now reproduces real Chromium's probe vectors exactly
for all 8 captured challenge variants, and the executor returns 200 end-to-end
live (non-streaming, streaming, claude-haiku-4-5, and a math prompt returning
"42").
Tests: tests/unit/duckduckgo-challenge-solver-regression.test.ts (32 tests) and
tests/unit/duckduckgo-reasoning-effort-required.test.ts (5 tests), backed by
tests/fixtures/duckduckgo/challenge-variants.json — real captured challenge
programs plus the probe vectors a real browser produced for them, so the suite
asserts against recorded browser behaviour rather than our own output. Each fix
was confirmed to fail its test when individually reverted.
Co-authored-by: Mynacol <git@mynacol.xyz>
requestLogger.ts's cloneBoundedForLog had its own hardcoded depth cap of 6,
independent of the existing configurable getChatLogMaxDepth(). A typical
Chat Completions response body's responseBody.choices[0].message.tool_calls[0].function
sits at exactly depth 6, so every logged tool call's function field
(name+arguments) was silently replaced with the literal string "[MaxDepth]"
before ever being stored — corrupting the data, not just how it renders.
Bumped the shared default 6->20 and switched requestLogger.ts to read it
instead of using its own literal.
(cherry picked from commit a2df6cf289)
Co-authored-by: Markus Hartung <mail@hartmark.se>
* feat(logging): make the chat-log truncation limit configurable, bumped default 128x
The 8KB cap on logged request/response bodies
(open-sse/handlers/chatCore/logTruncation.ts::truncateForLog()) was
hardcoded — trivially exceeded by any real multi-turn agentic
conversation, meaning the dashboard's "Full Conversation" panel could
only ever show a placeholder instead of the actual messages for nearly
every logged row of any conversation with real substance.
- Added CHAT_LOG_MAX_BODY_KB env var (src/lib/logEnv.ts::
getChatLogMaxBodyBytes()), default 1024 KB (1MB) — a 128x bump from
the old hardcoded 8KB — following the same configurable-limit pattern
as the sibling CHAT_LOG_TEXT_LIMIT/CHAT_LOG_ARRAY_TAIL_ITEMS/etc. vars.
- Documented in .env.example and docs/reference/ENVIRONMENT.md.
estimateSizeFast() (open-sse/utils/estimateSize.ts) has been
substantially rewritten upstream since this bug was first found (now an
iterative Frame-based walker with a separate node-visit budget, not the
simple stack loop originally patched) — re-implemented the fix against
the current algorithm rather than porting the old diff: the byte
early-exit was unconditionally the module-level ESTIMATE_SIZE_BYTE_LIMIT
(256 KiB) with no way for a caller to raise it, so any caller comparing
against a bigger configured threshold could never see a size above
~256 KiB — every payload between 256 KiB and the caller's real limit
looked "under threshold" and truncation never fired, the opposite of
intended. Added an optional byteLimit parameter (default unchanged at
ESTIMATE_SIZE_BYTE_LIMIT, so isSmallEnoughForSemanticCache's existing
behavior is untouched) threaded through both the byte-check early-exit
and the node-budget-exhaustion fail-closed fallback, with
truncateForLog() now passing its own configured getChatLogMaxBodyBytes()
value through.
* feat(dashboard): show conversation session tag in request detail metadata
Adds a "Conversation" field to the request detail panel's metadata
grid (after "Combo"), showing the request's conversation id
(sessionTag) for quick reference/copy.
---------
Co-authored-by: Markus Hartung <mail@hartmark.se>
* fix(responses-api): sync reasoning-cache write index with the fixed read side
The turn-index-hardcoding fix updated the reasoning-cache read side
(translator/index.ts's main replay loop) to key lookups by the assistant
message's real position in the messages array, but two other spots still
used the old hardcoded convention:
- chatCore.ts's write side (both the streaming and non-streaming
completion paths) still cached every response under a hardcoded
messageIndex: 0.
- translator/index.ts's own plain-turn (non-tool-call) cache-key lookup
ALSO still hardcoded messageIndex 0 at its call site — a second,
previously undiscovered instance of the same class of bug, found while
re-verifying this fix against the current upstream tip (the original
fix only addressed the write side).
Past the first assistant turn these conventions no longer matched, so
DeepSeek/Xiaomi-mimo plain-turn reasoning replay silently missed the
cache and fell back to the placeholder (or, once #9573 removed the
placeholder fallback, to an absent field) in ordinary multi-turn
conversations.
Compute the write-side index from the incoming request's message count
instead, and use the real loop-provided messageIndex on the read-side
lookup, both matching the position the response occupies once the
client appends it to history for the next turn.
Note: this was originally part of a larger squashed fix (output_index
collision prevention across reasoning/message/tool_call items,
reasoning-content-alias generalization) that has since been superseded
by upstream's own independent fix — translator/response/openai-responses.ts
now has its own dense-output-index-sort + getReadableReasoningValue
implementation (own comment: "mirrors upstream PR #721"). Only this
narrower, still-genuinely-broken write/read index sync survives as a
distinct bug.
Test plan:
- TDD: tests/unit/reasoning-cache.test.ts's new end-to-end
"write side (chatCore's messageIndex) and read side (translateRequest)
agree on the same key end-to-end" test, plus the pre-existing
"should inject placeholder for a plain (non-tool-call) DeepSeek turn"
and "should replay cached reasoning for a plain (non-tool-call)
DeepSeek turn when available" tests — confirmed failing against the
pre-fix code on a clean release/v3.8.50 checkout (both the
hardcoded-0 write side AND the hardcoded-0 read-side lookup
independently reproduce the mismatch), passing after both fixes
- npm run typecheck:core — clean
- npm run lint — clean
- npm run check:file-size — clean (chatCore.ts rebaselined 5034->5042
for the messageIndex computation at both call sites;
reasoning-cache.test.ts frozen at 1035, matching the original fix's
own rebaseline)
- 2 pre-existing, unrelated test failures in the same file
("should replace empty-string reasoning_content with
NON_ANTHROPIC_THINKING_PLACEHOLDER on cache miss",
"should inject placeholder for a plain (non-tool-call) DeepSeek turn
missing reasoning_content") confirmed present on a completely clean,
untouched release/v3.8.50 checkout — these test obsolete
placeholder-injection behavior the code deliberately removed per
#9573 (see the code's own comment); not touched by this PR
* fix(chat): reduce file size
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(chat): reconcile file-size baseline
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
---------
Co-authored-by: Markus Hartung <mail@hartmark.se>
* fix(deps): bump transitive deps for 6 Dependabot + remaining audit vulns on main
Same overrides as #9464 (ip-address, hono, fast-uri, socket.io-parser, undici)
applied directly to main. Also covers brace-expansion (scoped), js-yaml v4 copies,
and mermaid.
npm audit: 6→0 vulnerabilities.
Closes Dependabot #161-#166.
* fix(deps): bump nanoid, dompurify for 2 new Dependabot alerts (#189, #190)
Bumps: nanoid ^3.3.17 (was transitive, now overridden), dompurify ^3.4.13
(with monaco-editor scoped override). Closes Dependabot #189, #190.
Remaining #182-#188 (js-yaml + mermaid) already closed by #9651 merge —
awaiting Dependabot re-scan.
npm audit → 0 vulnerabilities.
* fix(repo): harden .gitignore to also ignore a _tasks symlink (/_tasks)
_tasks is a SEPARATE nested git repo (gitignored). The pattern _tasks/ (trailing
slash) ignores only a directory, not a SYMLINK named _tasks. A self-referential
_tasks symlink can slip in via git add -A and, once pulled, checkout materializes
it over the real _tasks repo (destroying plans/specs/hands-off). Anchored /_tasks
ignores the symlink too, preventing re-capture.
* fix(translator): keep Responses namespace identity across the hub-and-spoke pivot
Step 1 of the pivot (openai-responses -> openai) flattens namespace sub-tools
to a qualified wire name (#8295) and records the `{namespace, name}` pair on a
non-enumerable `_toolNameMap`. Step 2 (openai -> target) returns a brand-new
object, so the property was dropped for every non-OpenAI target. chatCore then
handed `null` to the #7936 response seam and namespace sub-tool calls reached
the client under their flattened name, which Codex rejects with
`unsupported call: <name>` — the symptom #7936 was opened to fix.
Copying `_toolNameMap` through is not viable: openai-to-claude and
openai-to-gemini publish their own `Map<string, string>` alias map on that same
property during step 2, so it carries two incompatible types. This adds a
dedicated `_namespaceToolIdentityMap`, propagated by translateRequest across
the pivot; chatCore prefers it and falls back to `_toolNameMap` for the
non-pivot producers. Both keys are stripped from the cliproxyapi wire body.
Fixes#9780
* fix(chat): reduce file size
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(chat): reduce combined file size
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
* fix(chat): reduce combined file size
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
---------
Co-authored-by: diegosouzapw <diegosouzapw@users.noreply.github.com>
Co-authored-by: VXNCXNX <vincent@preuve.ai>
* fix(sse): apply Azure request-param rules on the azure-ai wire path
Azure rejects several stock Chat Completions params on its newer deployments
and returns HTTP 400 rather than ignoring them:
max_tokens -> 'max_tokens' is not supported with this model.
Use 'max_completion_tokens' instead.
reasoning_effort -> Function tools with reasoning_effort are not supported.
Those rules lived inline in AzureOpenAIExecutor, so they only covered the
azure-openai provider. azure-ai (Azure AI Foundry) had no executor entry and
fell through to the bare DefaultExecutor, so the SAME Azure deployment
succeeded on one connection and 400'd on the other. Every agentic client sends
tools on every turn, so azure-ai failed on the first request.
Extract the rules to open-sse/executors/azureParamRules.ts, add an
AzureAiExecutor that inherits DefaultExecutor's azure-ai URL/header/apiType
handling unchanged and applies the shared rules, and register it for azure-ai.
Also widen the deployment pattern to cover gpt-chat-latest: it is a moving
alias that resolves to a GPT-5-era model and rejects max_tokens, but carries no
version number for the token-boundary pattern to key on. Verified against the
base regex - gpt-chat-latest did not match, which is exactly the observed 400.
Regression guard: tests/unit/azure-param-rules.test.ts, including an assertion
that getExecutor("azure-ai") no longer resolves to a bare DefaultExecutor.
* fix(sse): clamp Azure gpt-4o-mini completion tokens to its 16384 ceiling
Azure gpt-4o-mini deployments accept at most 16384 completion tokens and 400 on
anything larger:
max_tokens is too large: 32000. This model supports at most 16384 completion
tokens, whereas you provided 32000.
The 32000 is OmniRoute's own doing: adjustMaxTokens raises any smaller
max_tokens to DEFAULT_MIN_TOKENS (32000) whenever tools are present, to avoid
truncated tool arguments. That floor has no upper bound, so an agentic client
asking for far less still trips the model ceiling on its first turn.
Add scoped maxOutputCap rules in paramSupport.ts for both Azure wire paths.
PROVIDER_MAX_TOKENS is the wrong lever here - it is provider-wide, and the same
Azure resource also serves GPT-5 deployments with a much higher ceiling.
Regression guard: tests/unit/azure-max-output-clamp.test.ts, which also pins
that the clamp does not leak to gpt-5.1 or to gpt-4o-mini on other providers.
---------
Co-authored-by: Mihaly Bodo <michael@proton-quantum.com>