Commit Graph

1347 Commits

Author SHA1 Message Date
Luis Pater
a96e640d88 fix(auth): keep sign-in-required Codex credentials quarantined across manual refresh
- Fail forced refreshes when rejected refresh tokens remain unchanged without disk rotation and preserve rejected access token markers across no-op refreshes.
- Require a valid active access token when sign-in is required before restoring active routing status during refresh and lifecycle updates.
- Return the redacted credential entry view from the v8 management credential refresh endpoint.

Closes: #7135
2026-11-01 14:27:47 +08:00
Luis Pater
ecbaa6c710 fix(devin): route compound fast thinking levels to upstream fast variants
- Resolve strict "<level>-fast" requests (parenthesis suffix or body thinking_level) to "<base>-<clamped-level>-fast" in ResolveDevinChatModelUID instead of silently falling back to the default effort.
- Treat a bare "fast" request as the default-effort fast variant so "(fast)" no longer resolves to the plain default UID; private aliases, special families, and the lightning tier keep their existing handling.
- Add regression coverage for the fast suffix and body-level forms plus pinning cases for private aliases and lightning models.

Closes: #7144
2026-11-01 14:27:46 +08:00
HunterSThompson
bb6e1aa8c0 fix(meta): include Muse namespace in tool-bearing requests 2026-11-01 14:27:45 +08:00
HunterSThompson
5d8fddd338 chore(meta): match Muse Code 1.4.14 client headers
Subscription keys return HTTP 403 client_attestation_denied when the
request still looks like muse-build/1.3.0. Stamp the headers captured
from Muse Code 1.4.14-R7309.1: muse-build/1.4.14, X-Client-Id tbh:exec,
and a fresh session id set.
2026-11-01 14:27:43 +08:00
sususu
fd02b720e6 fix(proxy): stamp keepalive on uTLS dialers, rebind stale compat executors, and close retired pools outside fence lock 2026-11-01 14:20:38 +08:00
sususu
893958e401 fix(proxy): decline pooling when http.DefaultTransport is not *http.Transport 2026-11-01 14:14:16 +08:00
sususu
6c231c2332 fix(proxy): lazily allocate uTLS pools and close fenced transports 2026-11-01 14:14:16 +08:00
sususu
638f5f55e0 fix(proxy): honour per-key pool opt-in and isolate pools per runtime
- Keep an empty connection-pool block as an opt-in. Synthesising it to nil
  silently disabled pooling for `connection-pool: {}` and for keys inheriting
  an empty group block.
- Fold the transport kind into the pool key and pool the Claude Code uTLS
  transport per credential. Anthropic upstreams previously shared one
  transport across keys and ignored the key's pool settings.
- Fence generations per publisher instead of process-wide. Building or
  reloading one service no longer retires the pools another service is
  still serving, which degraded it to one transport per request.
2026-11-01 14:14:16 +08:00
sususu
34a01b7602 feat(proxy): pool upstream transports per api key
Give the generic proxy-aware clients a reusable transport per api-key
credential, driven by the `connection-pool` block added in the previous commit.

- Pools are keyed by credential scope (auth ID, then path/source, then a digest
  of refresh/access/API-key material, then anonymous), normalized proxy target
  (authenticated proxies fold a SHA-256 digest of user:pass into the key so each
  proxy identity or sticky-session username keeps its own pool without storing
  plaintext secrets in the cache key or logs), and the resolved settings. Two
  keys therefore never share a TCP/TLS connection regardless of whether the
  proxy is unauthenticated, authenticated, direct, or inherited.
- Capacity is a 512-entry LRU: one key keeps a warm pool, 100 keys keep one each,
  and 100000 keys fall back to the historical one-transport-per-request behavior
  when the cache is full. Each transport is bounded to MaxIdleConnsPerHost
  instead of the cloned default of 100 idle sockets, so idle sockets stay at
  capacity*max no matter how many keys exist.
- Dead peers are detected without request timeouts: 30s TCP keepalive on every
  dialed connection (including SOCKS5, which used proxy.Direct before) plus the
  idle timeout, 300s by default. Measured against ollama.com, an idle pooled
  connection was still reusable after 600s; the 90s that used to bound this path
  was net/http's own IdleConnTimeout, not an upstream limit.
- Explicit 0 or negative values disable keep-alives (including when proxy-url is
  empty), invalid durations are parsed once per pool instead of warning per
  request, and pooling works with or without an explicit proxy-url while keeping
  priority for context-injected RoundTrippers when proxy-url is empty.
- Config snapshots carry a generation so a request holding an obsolete snapshot
  cannot repopulate the cache after a reload. Generation 0 means the config never
  passed the fence and stays poolable, so callers that build their own config are
  not silently downgraded.
2026-11-01 14:14:16 +08:00
Luis Pater
b63322b9c3 fix(registry): preserve explicit thinkingLevel on Antigravity Claude 5.5 models
- Add supported thinking levels (`low`, `medium`, `high`) to the Antigravity `claude-opus-5-5-high` and `claude-sonnet-5-5-high` model definitions so hybrid capability validation preserves explicit `thinkingLevel` settings instead of converting them to `thinkingBudget`.
- Add regression tests covering `ApplyRequestThinking` and streaming/non-streaming Antigravity executor requests for both Claude 5.5 models.

Closes: #7133
2026-11-01 13:45:03 +08:00
Luis Pater
cc4b9949e7 feat(claude): add opt-in visible Codex commentary with preserved replay
- Add `client.claude.show-codex-commentary` config and propagate the request-scoped display policy through HTTP and WebSocket Codex executors.
- Mirror public Codex `commentary` messages into visible Claude text blocks alongside the `cpa:commentary:v1` thinking marker in streaming and non-streaming responses without altering genuine reasoning or token accounting.
- Deduplicate only the exact adjacent mirrored commentary text block during Claude-to-Codex request replay when enabled.

Closes: #7129
2026-10-31 10:04:12 +08:00
Luis Pater
dbb706215a fix(codex): expand recognized CPA compaction capsules before forwarding to OpenAI
- Expand recognized CPA compaction capsules into developer context messages across Codex HTTP, compact, WebSocket, duplex steering, and token-counting paths while preserving native OpenAI compaction items.
- Reject corrupted CPA compaction capsules with HTTP 400 instead of forwarding unverifiable ciphertext to upstream.

Closes: #7118
2026-10-30 22:33:02 +08:00
Luis Pater
514d09f746 feat(codex): guide recovery when automatic credential renewal becomes impossible
- Classify terminal Codex refresh grant failures (`refresh_token_reused`, `refresh_token_expired`, `refresh_token_invalidated`, `token_revoked`, `invalid_client`, `invalid_grant`, and HTTP 401) as non-retryable, track rejected outer and SIWC refresh tokens independently, and defer retry checks until `access_token` expiry while keeping valid access tokens available for inference.
- Expose structured renewal states, recovery stages, sanitized refresh diagnostics, targeted account-matching OAuth re-authentication (`POST /v8/management/oauth/auth-url`), and pinned inference verification (`POST /v8/management/credentials/verify`) across Management API v8 and the TUI.
- Add unit and workflow regression tests covering terminal vs. transient refresh handling, per-partition SIWC/outer isolation, incomplete stream rejection, quota cooldown preservation, and secret redaction.

Closes: #5783
2026-10-30 07:06:33 +08:00
Luis Pater
f013eb662a fix(openai): keep incomplete streams without [DONE] out of credential cooldown
- Mark locally synthesized missing-[DONE] stream errors as stream-truncated in OpenAICompatExecutor so auth cooldown and cross-credential replay are skipped while preserving the 502 error.
- Add regression tests verifying that incomplete HTTP 200 OpenAI-compatible streams do not cool down credentials or exhaust the pool into auth_unavailable.

Closes: #5283
2026-10-30 02:29:35 +08:00
Dylan
4cb98e3ccd fix(logging): prevent deferred request retention on Responses WebSockets
Keep the error-only upstream request capture policy on the connection
context, before model routing and upstream execution begin. Check it before
accessing pooled Gin state so delayed plugin callbacks retain the policy
even after cancellation or Gin context reuse.

Preserve ordinary HTTP error capture, failed upgrade handling, and full
request logging. Cover large repeated requests, late callbacks, real
WebSocket logging, and Codex duplex routing with regression tests.

Related: #6960
2026-10-29 23:25:54 +08:00
hkfires
265ca17983 Merge pull request #7095: reassemble AI Studio SSE frames 2026-10-29 19:29:28 +08:00
sususu
82deffb9ca fix(usage): preserve output_item.done tool counts and multiline SSE usage 2026-10-29 15:57:38 +08:00
sususu
97dd3a4a2f fix(usage): preserve stream failure usage, multipart image params, and provisional zero search counters 2026-10-29 15:16:53 +08:00
sususu
d5eb4ca1d5 perf(usage): optimize stream usage observation and large payload parsing 2026-10-29 14:44:33 +08:00
sususu
bd5ec5310a feat(usage): capture structured Gemini, Vertex, AI Studio, and Antigravity usage 2026-10-29 14:44:33 +08:00
sususu
01551f5f6b feat(usage): capture structured OpenAI and Codex usage across responses, chat, and images 2026-10-29 14:42:21 +08:00
sususu
24840fddf8 feat(usage): capture structured xAI usage across chat, responses, and media 2026-10-29 14:40:08 +08:00
sususu
89e472f325 feat(usage): capture structured Anthropic Messages upstream usage details 2026-10-29 14:39:43 +08:00
Kayokoi
498170a49c fix(aistudio): add relay SSE frame reassembly helper 2026-10-29 12:34:51 +08:00
Kayokoi
7df437c822 fix(aistudio): buffer fragmented relay SSE frames 2026-10-29 12:32:47 +08:00
sususu98
56efc81fa5 Merge pull request #7092 from sususu98/fix/slow-test-disconnect
Fix WebSocket disconnect test and Devin diagnostics
2026-10-29 09:58:15 +08:00
sususu
02ee313962 fix(devin): classify JSON control character errors 2026-10-29 09:46:47 +08:00
Luis Pater
90c447d3a8 fix(responses): use tsc_ item id prefix for Gemini tool search calls
- Update the Gemini OpenAI Responses tool search call item ID prefix from ts_ to tsc_ so replayed search items pass Codex upstream validation after switching models.
- Normalize legacy ts_ and unprefixed tool_search_call item IDs in SanitizeCodexInputItemIDs on outbound Codex requests while preserving call_id and avoiding ID collisions.

Closes: #7084
2026-10-29 07:03:21 +08:00
Luis Pater
0fe38224e5 feat(pluginhost): support raw request body byte-range patching
Existing request interceptors wrap the full request body in a JSON RPC envelope with Base64 encoding and skip subsequent duplex WebSocket business frames, causing ~3.33x memory and CPU amplification when rewriting small fields such as Codex `<timezone>` and `<current_date>` in large contexts.

- Add schema v8 raw request body patch methods (`request.patch_body_before` and `request.patch_body_after`) and capabilities (`request_interceptor_patch_body_before/after`, `request_body_patcher_before/after`) that pass raw `Body []byte` directly across the C ABI without JSON/Base64 request wrapping
- Add `RequestBodyEdit`, `RequestBodyPatchResponse`, and `RequestBodyPatcher` in `sdk/pluginapi` with single-pass host splicing, bounds/overlap validation, `json.Valid` verification, no-op original body reuse, and sequential multi-plugin chaining
- Eliminate redundant full-body slice clones in handler/conductor request interceptor application paths
- Run before-auth and after-auth request interceptors on subsequent duplex WebSocket `response.create`, `response.append`, and `response.steer` messages

Closes: #7072
2026-10-28 21:38:42 +08:00
Luis Pater
9717e325ba fix(responses): reject late websocket interrupts after terminal events
- Track the running response identity in the Codex websocket session and reject interrupts that do not target it, so an interrupt after response.completed is never forwarded upstream while turn teardown is pending.
- Gate the handler's local interrupt path by explicit turn ownership and close it before terminal payloads are written downstream, preventing fabricated response.incomplete events and silently dropped claimed frames.
- Add deterministic regression tests covering late and unknown interrupts across completion, failure, queued rejection, upstream loss, and HTTP fallback turns.

Closes: #7065
2026-10-28 18:33:51 +08:00
Luis Pater
ba26dea03f Merge pull request #7023 from JohnsonRan/patch/response-decode-sync-zstd
perf(executor): decode upstream zstd synchronously and sniff unlabeled bodies lazily
2026-10-28 02:26:07 +08:00
Luis Pater
b74422180e fix(auth,usage): snapshot request state to avoid reading reused gin.Context (#7056) 2026-10-27 21:22:46 +08:00
Luis Pater
86a1aabf01 fix(codex): retry another credential on early websocket 429 without closing downstream
When an upstream Codex WebSocket returns an early 429 usage_limit_reached (via an error or response.failed frame) before any downstream payload chunk is emitted, notifying UpstreamDisconnectChan caused the Responses WebSocket handler to close the client connection and cancel the request context before the conductor could fail over to another eligible credential.

Suppress downstream disconnect notification on pre-output upstream WebSocket errors and treat bootstrap usage-limit terminal failures as failover-eligible while bootstrap buffering is active, allowing the conductor to retry another credential on the same downstream WebSocket connection.

Fixes #7051
2026-10-27 18:35:03 +08:00
Luis Pater
826bb16780 fix(images): apply payload default rules to xAI image endpoints
- Build un-defaulted original request payloads for xAI image generation and edit handlers and propagate them via execution context so payload default rules can distinguish omitted client fields from built-in defaults.
- Pass normalized original requests into the xAI image executor payload finalizer and report finalized response_format values back to handlers via metadata callbacks across streaming and non-streaming responses.
- Add unit and handler regression tests covering payload default, default-raw, and override rules for xAI image endpoints.

Closes: #7048
2026-10-27 17:27:20 +08:00
Luis Pater
b4f59d7035 fix(devin): log apply_patch rejection diagnostics and recover complete bare patches
- Attach content-free log diagnostics to Devin apply_patch 502 rejections with fixed reason categories, argument byte counts, prefix shapes, and parse error classes.
- Buffer and recover complete, well-framed bare Codex patches from Devin invalid_json_str arguments via applypatch.WrapInput after a clean EOS trailer in streaming and non-streaming execution.
- Keep truncated streams, trailer errors, mixed argument sources, and malformed patches fail-closed without exposing patch content.

Closes: #7046
2026-10-27 16:19:45 +08:00
Luis Pater
f73e66ac2a fix(responses-ws): keep downstream websocket open on upstream Codex disconnect
Keep the client's /v1/responses websocket open when an upstream Codex websocket drops during or between turns, report correlated non-closing error frames without replaying in-flight turns, fence pre-loss queued input across handler and executor boundaries, and preserve pinned credential affinity across Home turn releases.

Closes: #7028
2026-10-27 15:32:41 +08:00
sususu
7517549a64 fix(signature): do not reject Antigravity CAQS signatures by channel ID 2026-10-27 10:24:02 +08:00
Luis Pater
be929f07fa fix(interactions): normalize gemini stream sse lines
- Strip SSE data prefixes and ignore control lines before initializing stream state.
- Cover translated content, usage, and completion across vertex authentication paths.

Closes: #7025
2026-10-27 09:49:17 +08:00
sususu98
023dd2adca Merge pull request #7016 from sususu98/fix/vertex-gemini-thought-signature-7007
fix(signature): recognize and scope Vertex bare-Tink Gemini thought signatures
2026-10-27 09:47:48 +08:00
sususu
a8582fbaca fix(signature): pin Vertex bare-Tink recognition to observed key ids
Without a protobuf wrapper, the ciphertext after the Tink prefix byte is
indistinguishable from uniform random bytes. Matching only the 0x01
prefix byte claimed about 1/256 of unenveloped payloads as Gemini: xAI
encrypted_content starting with 0x01 was then rejected by the Grok
validator and dropped from replay, and Kimi signatures were misclassified.

- require the observed Vertex key id (8f3d6b5f) in addition to the
  prefix byte; a rotated key falls back to the bypass sentinel, which is
  the behavior before bare-Tink recognition
- expose IsGeminiVertexBareTinkSignature and scope the Gemini
  Interactions sanitizer: the public endpoint drops bare-Tink thought
  steps, the Vertex Interactions endpoint keeps them
- restore the xAI seed and Kimi ordering tests that had been adjusted
  around the false positive, and add regressions for a 0x01-leading Grok
  payload and an unknown key id
2026-10-27 09:39:35 +08:00
Luis Pater
9a35fa12b2 fix(codex): treat turn_rate_limit_exceeded as transient capacity with retry hint
- Classify Codex turn-rate and model-capacity 429s as transient per-model rate limits via a new executor contract, honour upstream Retry-After headers behind quota resets, and cool only the reporting model without quota labelling or exponential backoff.
- Carry the trusted retry deadline to terminal clients and retry scheduling across direct, streaming, bootstrap, and Home paths, keeping Home aggregated deadlines authoritative over per-attempt hints.

Closes: #7017
2026-10-27 04:29:38 +08:00
JohnsonRan
3c948a5808 perf(executor): decode upstream zstd synchronously and sniff unlabeled bodies lazily
DecodeResponseBody used zstd.NewReader with its default options, which
hands blocks to up to four asynchronous decoders: allocations and handoff
latency on every streamed response for no gain on bodies read as they
arrive. Decode with WithDecoderConcurrency(1) instead.

A response without Content-Encoding was sniffed for gzip/zstd magic with
Peek(4) before DecodeResponseBody returned, blocking the caller until the
upstream sent its first bytes. Detect on the first Read instead, waiting
for more than one byte only when the first byte can start a gzip or zstd
frame.
2026-10-27 04:18:42 +09:00
sususu
1398f27390 fix(signature): scope Vertex bare-Tink replay to Vertex targets
Live replay showed Antigravity (cloudcode-pa) and AI Studio
(generativelanguage) reject Vertex bare-Tink thought signatures with
400 "Corrupted thought signature", while Vertex accepts them natively.
After recognizing bare-Tink as a Gemini envelope, history issued by
Vertex and routed to those endpoints was replayed verbatim and failed.

- add SanitizeNonVertexGeminiRequestThoughtSignatures, which treats
  bare-Tink as incompatible: the first functionCall in a group gets the
  bypass sentinel and other parts drop the signature
- use it in the Antigravity, Gemini API and AI Studio executors; the
  Vertex executor keeps the preserving sanitizer
- cover the endpoint split in the signature package and with mocked
  upstream bodies for the Gemini API and Antigravity executors
2026-10-26 23:33:12 +08:00
sususu
58a4d04f32 fix(signature): recognize Vertex bare-Tink Gemini thought signatures
Vertex serve paths emit the Tink primitive output directly as the whole
thoughtSignature (0x01 prefix + 4-byte key id + ciphertext) instead of the
protobuf field-2 wrapper used by AI Studio and Antigravity, so every Vertex
Gemini signature was misclassified and rewritten to
skip_thought_signature_validator (#7007).

- add GeminiThoughtSignatureEnvelopeBareTink with a bounded structural check
  (prefix byte + key id + 16-byte auth-tag floor)
- register the 0x01-derived 'A' first char in the self-describing prefilter
- cover detection, replay preservation, floor rejection and cross-family
  non-claims with synthetic fixtures
- document envelope precedence in the Kimi ordering test; move the xAI cache
  seed off the 0x01-colliding seed 14
2026-10-26 23:33:12 +08:00
Luis Pater
aa4130e64c fix(gemini): keep truncated HTTP 200 streams out of credential cooldown and failover
- Tag locally synthesized missing-finishReason failures as stream-truncated in the Gemini and Vertex executors, and carry that classification through the auth manager so it skips credential cooldown and stops cross-credential replay while the public 502 and partial usage are preserved.
- Carry the truncation classification through usage reporting and the Home queue payload so Home-side schedulers also skip the spurious cooldown, and add regression coverage for both the manager and usage paths.

Closes: #7005
2026-10-26 21:07:08 +08:00
Luis Pater
1d45a5f332 fix(claude): handle forced tool restrictions in claude 5.5
- Fall back to schema prompts for Antigravity Claude 5.5 while preserving unrelated request settings.
- Normalize unsupported forced tool choices before thinking preparation in direct Claude execution and token-count paths.
- Add regression coverage for schema integrity, model boundaries, retries, and final payload rule precedence.

Closes: #7000
2026-10-26 20:36:51 +08:00
Luis Pater
ede07cafa6 fix(interactions): emit [DONE] sentinel after terminal usage frame in Antigravity and Gemini streams
- Cache the latest valid usage frame in both Interactions translators and emit interaction.completed with the done sentinel once usage at or after the finish frame arrives, keeping earlier cached usage only as the explicit-[DONE] fallback so split finish/usage frames keep the final token counts.
- Recognize a bare [DONE] payload in the Antigravity stream parser (previously misparsed as a JSON array) and restore filter-renamed cpaUsageMetadata in the Gemini translator so executor-filtered frames still complete the stream.
- Document that a clean Antigravity EOF terminates Interactions streams even without finishReason, matching real tool-call streams, while read errors still surface without a synthetic completion.

Closes: #7003
2026-10-26 18:40:53 +08:00
Luis Pater
531721bfce fix(codex): restore Codex commentary history via internal thinking signature marker
- Stamp Codex commentary thinking blocks with the CLIProxyAPI-internal marker `cpa:commentary:v1` in streaming and non-streaming Claude responses, keeping real reasoning signatures isolated.
- Restore marked blocks on replay before any provider signature handling: as an assistant `phase: "commentary"` message for Codex targets and as plain assistant text for Claude-compatible, OpenAI, Gemini, Interactions, and Antigravity targets, so the marker never reaches an upstream.
- Add the unconditional marker restore at the Claude upstream sanitize entry so non-Claude model names cannot bypass it, with round-trip and cross-format regression tests.

Closes: #6994
2026-10-26 15:58:41 +08:00
Luis Pater
064e008b07 feat(codex): add full-chain compression for Codex upstream and downstream traffic
- Compress finalized Codex OAuth request bodies with zstd on the verified ChatGPT backend path, with size/benefit gating, header-body alignment, and one uncompressed retry on 400/415 rejection.
- Negotiate downstream HTTP response compression under server.response-compression (zstd/gzip with q-values, SSE-safe flushing, commit-time Vary merging) and enable negotiated permessage-deflate on Codex and downstream WebSockets.
- Advertise Accept-Encoding to Codex upstreams and decode gzip/deflate/br/zstd upstream responses through a shared decoder before parsing or relaying.

Closes: #6905
2026-10-26 10:09:56 +08:00
Luis Pater
e5321f535c fix(auth,pluginapi,usage): share per-selection ID between Scheduler.Pick and UsageRecord
- generate a unique selection_id for each handled Scheduler.Pick decision and freeze it into the execution context and UsageReporter
- propagate SelectionID through core usage records and pluginapi.UsageRecord while clearing stale IDs on unhandled, rejected, Home, and credits fallback paths

Closes: #6988
2026-10-26 03:25:42 +08:00