474 Commits

Author SHA1 Message Date
sususu98
d11ff49978 Merge pull request #7457 from sususu98/fix/bio-policy-request-fault
fix(clienterror,openai): classify bio_policy and safety policy blocks as 400 request faults
2026-11-16 18:00:21 +08:00
Luis Pater
0bfb3d01cb fix(auth): treat Claude expired refresh token response as terminal
- Match Anthropic's "refresh token expired" grant description in isTerminalRefreshGrantMessage and normalize it to refresh_token_expired in terminalRefreshErrorCode so expired Claude refresh tokens mark RequiresSignIn and stop scheduling refresh retries.
- Add regression tests verifying terminal sign-in handling for Claude expired refresh tokens while preserving exponential backoff retries for generic Claude invalid_grant errors.

Closes: #7596
2026-11-16 17:23:38 +08:00
sususu98
1f76e479c4 fix(clienterror,openai): classify bio_policy and safety policy blocks as 400 request faults
- Add bio_policy, cyber_policy_violation, misalignment_policy_violation, content_policy_violation, and image_content_policy_violation to request-fault codes so policy rejections stop failover without cooling down credentials.
- Unify trusted error JSON extraction across auth, model-not-found, credit-balance, and request-fault checks while restricting wrapper unwrapping and policy-text matching to prevent prompt-echo false positives.
- Map typeless policy error codes and body.error layouts consistently across Codex SSE/WebSocket, Responses, xAI, and Claude stream translation paths, filling blank messages with official fallback copy.
2026-11-16 12:28:56 +08:00
Luis Pater
508f8708d0 chore: replace standard JSON package with moego JSON throughout the project 2026-11-16 09:58:12 +08:00
Luis Pater
b4fdfdece3 chore: replace standard regexp with moego regexp throughout the project 2026-11-16 03:02:43 +08:00
Luis Pater
a8c9c8a4a4 fix(openai): fail over pre-commit responses websocket create errors
- Unpin and exclude the failed credential when a full response.create on a persistent Responses WebSocket fails with a pre-commit quota or auth error.
- Propagate excluded auth IDs through handler metadata into mixed and Home stream selection while blocking replay once any downstream frame is committed.
- Add regression tests for pre-commit 429 failover, post-commit non-replay, and Home repeated excluded-auth rejection.

Closes: #7585
2026-11-16 01:59:04 +08:00
Luis Pater
05a353cf12 feat(sdk): wrap built-in executors via builder hook on every registration path
- Add Builder.WithExecutorWrapper applied in the centralized registerExecutor gate so embedder wrappers survive startup sync, auth, and model refresh paths that bypass OnConfigApplied.
- Track the service-owned underlying executor per provider with manager revisions to preserve Claude WithConfig reuse and Codex/XAI session sharing across wrapping without double-wrapping.
- Harden replacement lifecycle for wrapped executors, including shared-session preservation, stale-ownership invalidation, and safe traversal of opaque or cyclic wrappers.

Closes: #7568
2026-11-15 17:57:09 +08:00
Luis Pater
22d40703f2 feat(scheduler): support ExcludeCandidates in plugin scheduler fallback and delegation
- Add ExcludeCandidates with PascalCase and snake_case ojson decoding to pluginapi.SchedulerPickResponse and preserve normalized exclusions in pluginhost when unhandled or delegated.
- Filter excluded auth IDs per selection pass in Manager before priority tiering and built-in selector evaluation so healthy lower-priority credentials can promote without mutating caller tried state.
- Add unit tests covering JSON/RPC compatibility, host normalization, priority promotion, session affinity, and cooldown/empty-pool errors.

Closes: #7535
2026-11-14 19:12:07 +08:00
Luis Pater
5a351d9570 feat(antigravity): deactivate credentials on TOS_VIOLATION and add optional pool-wide protective pause
- Detect the 403 PERMISSION_DENIED ErrorInfo reason=TOS_VIOLATION signature and mark the credential StatusDisabled + Disabled so it is excluded from rotation and persisted across restarts, while OAuth refresh stays intact; carry appeal_url/appeal_url_link_text through Error.Metadata to auth.Metadata and the management API.
- Add an optional pool-wide protective pause (antigravity.tos-pause-window, default 6h) armed only by TOS results, never by transient 429s, covering all Antigravity request paths including SSE mid-stream error frames and CountTokens.
- Distinguish terminal TOS results from stale/superseded results using a new Result.RefreshToken account hint so a same-account OAuth refresh applies the suspension while a genuine credential replacement discards it safely.

Closes: #7515
2026-11-14 04:49:56 +08:00
Luis Pater
4da9f68527 fix(auth): carry the pool cooldown reset on the terminal 429
- Wrap the final 429 in a poolCooldownTerminalError at the Execute/ExecuteCount/ExecuteStream boundaries when every candidate credential for the model is blocked and at least one is in a timed cooldown, preserving the upstream error body and status while marking IsModelCooldown so the Claude handler appends the reset time.
- Compute the Retry-After from the earliest auto-recovery across all blocked candidates (including non-cooldown timed blocks) so the client sees the pool's real recovery instead of the last attempt's hint.
- Add regression coverage for both cooldown variants across the three execution paths, the available-candidate guard, mixed-block earliest deadlines, the sub-floor hint clamp, and the Claude handler end-to-end.

Closes: #7521
2026-11-14 03:53:47 +08:00
Luis Pater
cf07c78abd fix(gemini/antigravity): fail zero-output abnormal terminations before HTTP 200 commit
- Detect MALFORMED_FUNCTION_CALL, UNEXPECTED_TOOL_CALL, and MALFORMED_RESPONSE with zero visible output before bootstrap commit, reasoning replay caching, or usage finalization across Antigravity, Gemini, Vertex, and AI Studio executors.
- Withhold only contentless leading shell frames while keeping thought chunks unbuffered for TTFT, and align Claude response error handling and stream completion flags while preserving valid partial outputs.
- Add unit, executor, bootstrap failover, and cross-module HTTP regression tests covering credential rotation and HTTP 502 exhaustion.

Closes: #7513
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-14 00:50:21 +08:00
Luis Pater
7fd90c7aa1 feat(meta): relay Muse Code client endpoints under /muse-code
- Implement core Muse Code relay handler, origin resolution, header/query sanitization, credential selection/preparation, 401 refresh, and bounded failover in internal/client/musecode.
- Register thin /muse-code routes, safe-mode proxy guarding, and request-ID logging prefixes in internal/api and internal/logging.
- Isolate model-less credential-scoped cooldowns, preserve execution sequence ordering, and honor request-scoped error rules across sdk/cliproxy/auth.

Closes: #7508
2026-11-13 22:30:37 +08:00
Luis Pater
b285660f84 feat(api): expose standalone in-flight request count on management API
- Add a lightweight per-request in-flight tracker on the auth manager that covers selection, upstream calls, retry waits, and the full stream lifetime; it stays disabled in Home mode where the execution registry is authoritative.
- Register GET /v8/management/observability/requests/in-flight returning counts only (in_flight, oldest_started_at, by_provider) with no request bodies or credential identifiers.

Closes: #7476
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-13 03:06:02 +08:00
Luis Pater
e63179492e fix(auth): back off rejected refresh recovery jobs
- Preserve a positive refresh delay for expired credentials with an unknown refresh outcome to prevent immediate redispatch.
- Cover task completion, disabled credentials, diagnostic errors, and replacement-grant rescheduling with regression tests.

Closes: #7491
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-12 23:57:10 +08:00
Luis Pater
02ec93d004 fix(claude): preserve beta profiles across thread turns
- Reuse successful wire beta snapshots across thread turns and executor reloads.
- Keep continuations on their original credential and honor explicit payload/header policies.
- Recover snapshots through KV and publish state before streaming completion, with regression coverage.

Closes: #7470
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-12 21:07:10 +08:00
Luis Pater
1f5bf2a569 fix(codex): release refresh claims on pre-send errors and defer macOS wakes
- Classify request creation and pre-handoff connection failures separately from ambiguous post-connection errors so unsubmitted refresh grants release their journal claim and remain retryable.
- Implement owner-bound, single-attempt claim release across memory, file, PostgreSQL, Git, and S3 refresh journals while preserving replay protection for completed or uncertain exchanges.
- Apply macOS power-state readiness deferral to ordinary Codex refreshes and preserve a positive reschedule backoff in the auto-refresh manager.

Closes: #7450
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-11 17:49:05 +08:00
Luis Pater
9d7d012b35 fix(auth): preserve large weighted pool fairness and force cooldowns
- Share smooth-weighted credits across dynamic large-pool subsets while isolating removed or re-registered credentials and bounding retained state.
- Preserve scheduler shard cursors and underlying weighted selectors across unrelated config and session-affinity reloads.
- Track and persist explicit ErrorCodeForceCooldown deadlines across disable-cooling reloads, interleaved errors, and cooldown state restores.

Closes: #7431
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-11 14:48:15 +08:00
Luis Pater
ecebc71345 fix(auth): keep request retry rounds after scheduler plugin reject
- Separate plugin scheduler rejections from request-stop rules via dedicated boundary markers so a rejection after an intra-round attempt failure preserves the attempt error and allows outer request-retry rounds to proceed.
- Stop immediately on zero-attempt rejections and track terminal scheduler-rejected rounds so Antigravity credits fallback cannot bypass plugin rejection policies.
- Add regression tests covering Execute, ExecuteCount, ExecuteStream, sticky retry-round rejections, boundary error unwrapping, and Antigravity credits fallback suppression.

Closes: #7434
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-11 11:09:04 +08:00
Luis Pater
69ed202a1a fix(registry): restore model listings once bounded cooldown deadlines expire
- Align client model projections with selector availabilityBlock semantics and carry bounded suspension deadlines while keeping disabled and terminal unauthorized gates open-ended.
- Track per-client suspension deadlines in ModelRegistry and fold live deadlines into availability cache expiration so /v1/models relists models automatically once cooldowns end.
- Add deterministic regression tests covering transient 408 cooldown expiry, forked aliases, open-ended gates, manual overrides, and bounded quota recovery.

Closes: #7421
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-11 07:41:33 +08:00
Luis Pater
cb70eacfa5 fix(claude): emit anthropic-ratelimit-unified headers on local cooldown 429s
- Retain and persist rejected Claude unified quota signals alongside active cooldown deadlines so out-of-order completions, restarts, and dual-layer quota wraps keep accurate window metadata.
- Populate anthropic-ratelimit-unified-* headers on Claude quota modelCooldownError responses aligned with Retry-After while keeping SafeResponseHeaders restricted to trusted retry headers.
- Exclude non-Claude, Cloudflare challenge, and ordinary per-minute rate-limit cooldowns from unified subscription quota header synthesis across selector and scheduler paths.

Closes: #7417
Co-authored-by: Dylan <1990016@gmail.com>
Co-authored-by: lzt404 <2596933790@qq.com>
2026-11-11 01:20:48 +08:00
sususu98
18883a57b4 fix(usage,auth): propagate request-scoped error rule classification to usage fail.code 2026-11-10 14:17:12 +08:00
hkfires
216f2947fc feat(home): report reused dispatch turns in usage
Add attempt-scoped HomeSelection metadata carrying the reused and
additional flags, scheduling route model, and credential policy
through usage records to the Redis queue. Mark retained executions
and Codex duplex successors as reused so Home can compensate later
turns after completion without redispatching or reacquiring a
concurrency slot.

Mark split additional-model records as additional so they never add
scheduling charges, while preserving independent per-response
execution IDs for deduplication. Document the deferred accounting
and add coverage across conductor, duplex, reporter, and queue.
2026-11-09 22:31:47 +08:00
hkfires
e84d4836b7 fix(auth): account pinned traffic in bare weighted routing
Extend weighted pinned accounting beyond session affinity so pinned
and ordinary requests share the same credits even when affinity is
disabled. Route scheduler, legacy, mixed, and bare selector picks
through the shared weighted pool, exclude zero-weight credentials
before priority selection, and preserve single-provider transport
preference for mixed requests.
2026-11-09 18:41:34 +08:00
hkfires
e479ab1253 perf(auth): compact weighted round-robin pools
Replace string pool keys and map-based credit state with SHA-256
digest keys and sorted slice members holding weight, current, and
pending credits in a single allocation. Reservations now retain
only the member index instead of a weights map and auth ID.

Verify full pool identity on digest hits and chain collisions so
unrelated candidate pools never share credits or weights. Update
tests to access pool credits through test helpers.
2026-11-09 14:23:17 +08:00
hkfires
d20451504f feat(auth): compensate weighted routing for sticky sessions
Charge session-affinity hits, parent inheritance, LCP matches,
and pinned requests against the eligible weighted pool without
moving existing bindings, so new sessions favor under-served
credentials and request ratios stay approximately weighted.

Scope settled credits per eligible credential set, capped at
+/-32 pool rounds, with in-flight reservations that commit on
local selection success and release on failure.
2026-11-09 14:23:16 +08:00
hkfires
0561334f06 fix(home): preserve fork kind in home dispatch
Map IsFork metadata to X-Node-Kind: fork when dispatching to
Home so forked sessions keep their lineage kind alongside
explicit kinds such as compaction. Clone dispatch headers
before adding the Home-only header to avoid mutating caller
headers, and cover fork, compaction, and ordinary children
with session hierarchy tests.
2026-11-09 14:18:50 +08:00
Luis Pater
098af7d543 fix(auth): share and migrate model cooldowns across equivalent model spellings
- Normalize model state, scheduler shard, and cooldown lookups case-insensitively while preserving stored model key casing.
- Atomically migrate route-alias cooldowns to the resolved upstream model key when OAuth model aliases or credentials are updated.
- Add regression tests covering mixed-case alias targets, pre-existing alias cooldown migration, and concurrent persistence windows.

Closes: #7360
2026-11-09 09:35:10 +08:00
Luis Pater
14e577174a fix(pluginhost): support credential-scoped rate limit errors from plugin executors
- Add optional credential_scoped metadata and documented routing/cooldown error code constants to pluginabi.Error so plugin executors can report account-wide 429 limits.
- Preserve credential-scoped classification on rpcError across synchronous RPC envelopes and streaming error callbacks while prioritizing credential quota scope over model-only or cooldown-skipping error codes.
- Recognize credential_quota error codes in core auth cooldown classification and cover whole-credential cooldown propagation and error events with regression tests.

Closes: #7359
2026-11-09 03:19:45 +08:00
Luis Pater
40c16182b8 feat(auth): support session-affinity-rebind-on never mode
- Add the "never" option for routing.session-affinity-rebind-on to preserve established session bindings across all credential failures and refuse cross-credential failover across primary, fallback-key, and Merkle LCP paths.
- Scope retry rounds and Antigravity credits fallback to the bound credential under "never" mode, returning 503 session_auth_retry on transient unavailability and 429 or upstream errors on quota/auth blocks.
- Add unit and end-to-end regression tests covering selector refusal, retry rounds, empty candidate sets, Antigravity credits fallback, and runtime config reload.

Closes: #7348
2026-11-08 15:38:30 +08:00
Luis Pater
09b3a57981 fix(codex): harden SIWC refresh deferral and expires_in parsing
- Parse expires_in with finite/range checks to prevent duration overflow.
- Introduce ErrSIWCRefreshDeferred sentinel and add macOS pmset deferral diagnostics.
- Expand regression tests and reduce SIWC renewal completion log noise.
2026-11-08 05:06:59 +08:00
Luis Pater
466b28dabc Merge branch 'codex/pr-7311' into dev 2026-11-08 04:48:23 +08:00
Dylan
5f38d5572c fix(auth): keep native Codex available during SIWC recovery
Preserve unknown refresh recovery state without inventing an access-token rejection. Evaluate availability for the requested partition and block missing tokens before model-level selection in both auth guards.

Cover partial refresh and later inference through real OAuth HTTP responses, CodexExecutor, and Manager execution. Auth, executor, integration, race, and build checks pass. The full suite encounters an existing WebSocket temporary-log cleanup race, reproduced on clean dev.
2026-11-07 12:50:35 +08:00
Jehuda Rajasa
baec297fec fix(auth): retain partition failures alongside SIWC wake cancellation 2026-11-07 01:23:36 +07:00
Jehuda Rajasa
80ee739f33 fix(codex): preserve SIWC rotations and honor renewal windows 2026-11-07 01:23:01 +07:00
Luis Pater
bfac85864c fix(codex): normalize small output budgets for all source formats
- Raise positive integer max_output_tokens below 16 to the Codex minimum on the translated payload across HTTP and WebSocket paths, before user payload rules.
- Send inference verification with a 16-token budget so healthy Codex OAuth credentials are no longer rejected by the upstream minimum.
- Add regression coverage for VerifyInference and small budgets from every Codex source format.

Closes: #7304
2026-11-07 01:57:53 +08:00
Luis Pater
68cd75724e fix(codex): prevent replay after uncertain refresh outcomes
- Preserve refresh failure stages and prevent immediate or later grant replay.
- Coordinate durable claims and recovery receipts across file, PostgreSQL, Git, and S3 stores.
- Add regression coverage for retries, concurrency, persistence, and recovery.

Closes: #7289
2026-11-07 01:44:42 +08:00
Dylan
1d4e054978 fix(auth): preserve terminal responses across execution paths
Treat preserved terminal responses as request-scoped unless the executor
marks a credential-specific rejection. Reuse the existing request error
policy to stop credential retries, unauthorized refresh, and cooldown
without changing explicit continue rules or ordinary failover.

End stopped Home stream selections without waiting for a redispatch
release acknowledgement that could replace the original response.

Cover local and Home execute, count, stream and bootstrap paths, exact
response preservation, missing release acknowledgements, and terminal
401 refresh suppression.

Refs: router-for-me/CLIProxyAPIHome#178
2026-11-06 16:27:43 +08:00
Luis Pater
1c53721167 fix(auth): keep count_tokens 501 and unsupported capability responses availability-neutral
- Classify HTTP 501 and typed unsupported count_tokens errors as availability-neutral in isCountTokensEndpointNotFoundError while preserving explicit model-not-found, auth, and quota cooldowns.
- Expose ErrorCode() on plugin RPC and auth error types so resultErrorFromError retains structured plugin error codes during count_tokens execution.
- Add regression tests verifying that repeated count_tokens 501 responses neither suspend inference availability nor extend active model cooldowns.

Closes: #7271
2026-11-05 19:25:12 +08:00
sususu98
585f97deac fix(auth): pass context and headers to availableAuthsForSelector in HasAlternativeTargetForModel 2026-11-05 11:51:57 +08:00
sususu98
62c58a7480 Merge pull request #7265 from sususu98/fix/codex-openai-image-bypass-siwc
fix(codex,auth): bypass SIWC for OpenAI image requests and route directly to Codex images endpoint
2026-11-05 10:40:21 +08:00
Luis Pater
b5e6027ce4 fix(openai): expose terminal 429 error frames on responses websocket
- Forward terminal 429 quota and model-cooldown errors with trusted Retry-After headers when websocket credential failover is exhausted.
- Suppress 1012 HTTP replay on pinned continuation 429 failures when no alternative local or Home credential is eligible.
- Add regression tests covering multi-credential rotation, single-credential exhaustion, expired alternatives, and Home failover.

Closes: #7256
2026-11-05 10:38:56 +08:00
sususu98
dfe8b182c5 fix(codex,auth): bypass SIWC for OpenAI image requests and route directly to Codex images endpoint 2026-11-05 10:27:44 +08:00
Luis Pater
d38997717d fix(management): honor targeted OAuth re-login across all built-in providers
- Bind oauthRecoveryTarget, return target_auth_id, validate account/organization/domain identity, update the target credential in place, and report post-login verification outcomes across Antigravity, Kimi, Kimi-AI, Claude, xAI, Meta, and Devin OAuth sessions.
- Support auth_index-only target lookup, preserve target filenames during targeted saves without triggering legacy filename migration, and extend AuthGrantFingerprint with api_key and session_token fallbacks.
- Add regression tests covering targeted re-login, identity/organization/domain mismatch rejection, xAI partial identity preservation, and post-login inference verification across built-in providers.

Closes: #7204
2026-11-03 10:15:13 +08:00
Luis Pater
e25b7dafa0 fix(devin): sanitize embedded exec tool phrases and stop retrying request-caused 403 errors
- Rewrite embedded exec_command and write_stdin phrases across all Devin tool descriptions regardless of tool name or mixed occurrences so Codex code-mode exec tools are not rejected.
- Classify Devin MCP configuration and content-policy 403 permission_denied errors as request faults in clienterror.IsRequestFault so the conductor neither retries nor cools down credentials.

Closes: #7198
2026-11-03 08:40:02 +08:00
Luis Pater
e582706557 fix(auth): prevent auto-refresh spin for disabled credentials with rejected refresh tokens
- Defer refresh scheduling to access token expiry or unschedule when a disabled credential encounters a terminal refresh error or holds an unchanged rejected refresh token.
- Preserve access token expiry scheduling on early return in refreshAuthForRequestAtEpoch and retain StatusDisabled when expired disabled credentials are unscheduled.
- Add regression coverage verifying disabled Codex credentials with rejected refresh tokens and unexpired access tokens do not spin the auto-refresh loop.

Closes: #7183
2026-11-03 03:47:11 +08:00
Luis Pater
6e6afab99a refactor: migrate gjson, sjson, and base64 to MoeForge/moego
- Replace tidwall/gjson and tidwall/sjson with github.com/MoeForge/moego/ojson
  and encoding/base64 with github.com/MoeForge/moego/base64 across the main
  module and examples
- Introduce cross-method *ojson.Doc request rewriting pipelines across
  thinking, signature, client/codex, runtime/executor/helps, pluginhost, and
  all provider executors with FinalizePayloadDoc as the final semantic barrier
- Convert all consecutive JSON mutations (>= 2 Set/SetRaw/Delete operations)
  to batch edits on ojson.Doc
- Upgrade read-only byte paths to ojson.GetBytesNoCopy,
  ojson.GetManyBytesNoCopy, and util.ParseGJSONBytesNoCopy with explicit
  strings.Clone ownership protection across streaming and persistent state
- Use base64.StdEncoding.ValidateString for zero-allocation signature checks
  and base64.EncodeDataURL for single-allocation data URL construction
2026-11-03 03:05:04 +08:00
sususu98
ef04e83ae9 Merge pull request #7165 from sususu98/fix/credential-dedup-connection-pool-7163
fix(config): include connection-pool settings in credential deduplication keys
2026-11-02 17:53:01 +08:00
Luis Pater
24f9744013 Merge pull request #7143 from router-for-me/fix/codex-no-refresh-token-spin
fix(auth): prevent Codex refresh spin without refresh tokens
2026-11-01 22:29:52 +08:00
sususu
8643ea56d5 fix(config): include connection-pool settings in credential deduplication keys
Include normalized per-credential connection-pool settings in Gemini/Interactions
and Vertex-compatible API key deduplication keys so entries that differ only in
connection-pool configuration are not silently dropped during sanitization.

Fixes #7163
2026-11-01 22:04:06 +08:00
Supra4E8C
9513c2d5dc docs(auth): explain Codex refresh token key requirement 2026-11-01 18:07:44 +08:00