Commit Graph

737 Commits

Author SHA1 Message Date
sususu98
72886356dd fix(antigravity): preserve complete reasoning replay (#4525) 2026-07-25 14:07:31 +08:00
Luis Pater
84bf9376e5 feat(executor): replace sdktranslator.TranslateRequest with helps.TranslateRequestWithCodexMultiAgentV2
- Updated Kimi and Gemini executors to use `TranslateRequestWithCodexMultiAgentV2` for improved multi-agent v2 optimization.
- Enhanced configuration and API server to support `CodexOptimizeMultiAgentV2`.
- Added codex multi-agent V2 optimizations in `config`, `executor`, and `watcher` modules.
2026-07-25 00:32:37 +08:00
Luis Pater
42f36b94e0 fix(usage): harden canonical token normalization 2026-07-24 01:18:18 +08:00
Dylan
fe8a616aa3 fix(usage): classify partial token accounting correctly 2026-07-24 00:31:32 +08:00
Dylan
416a080174 fix(usage): add normalized token accounting v2 2026-07-23 21:27:03 +08:00
Luis Pater
e5729872fa Merge pull request #4522 from sususu98/fix/responses-ws-continuity 2026-07-23 14:31:41 +08:00
Luis Pater
b30e7d992a Merge branch 'credential-concurrency' into dev
# Conflicts:
#	internal/api/server.go
2026-07-23 13:53:11 +08:00
Luis Pater
3ecd4afe80 feat: add Home credential concurrency support 2026-07-23 13:42:08 +08:00
sususu
840ba5dcc1 fix(xai): preserve compacted websocket transcript state 2026-07-23 13:07:37 +08:00
sususu
e05ae09425 fix(responses): preserve context across websocket transport changes 2026-07-23 13:07:23 +08:00
Luis Pater
f3e36f19c0 feat(executor): add Claude input token state handling and token estimation logic
- Introduced `ClaudeInputTokenState` to track and estimate input token usage for Claude message_start events.
- Added `TranslateStreamWithClaudeInputTokens` for token-aware stream translation.
- Updated executors (XAI, Kimi, Gemini) to leverage the new logic.
- Included robust test cases for token counting, JSON validation, and concurrent tokenization scenarios.
2026-07-22 05:21:14 +08:00
Luis Pater
cb110ad4fa perf(executor): improve token counting by introducing countXAIInputTokens
- Refactored token counting logic into a reusable `countXAIInputTokens` function for better readability and maintainability.
- Replaced direct encoder usage with structured input handling, including JSON parsing and segment collection.
- Switched tokenizer from `Cl100kBase` to `O200kBase` to support larger contexts.

Closes: #4492
2026-07-22 04:00:51 +08:00
sususu98
7329437297 fix(websocket): propagate upstream 1009 without credential fallback (#4444)
Preserve Codex and XAI upstream message-too-big closes across the Responses WebSocket boundary while treating them as request-scoped errors. Prevent CPA reconnect and credential cooldown/fallback, scope close state to the active connection, retain terminal errors under backpressure, and ensure downstream disconnect cleanup cannot wait behind a blocked writer.
2026-07-20 16:18:13 +08:00
Luis Pater
53c1e7e2dd perf(util): introduce GetGJSONBytesNoCopy for efficient JSON parsing without data duplication
- Added `GetGJSONBytesNoCopy` in `internal/util` for safe, no-copy JSON parse operations leveraging `unsafe`.
- Replaced `gjson.GetBytes` with the new helper in key payload processing paths (`kimi_executor`, `vertex_payload_helpers`, etc.) to improve performance.
- Added unit tests for behavior validation, including edge cases with empty input.
2026-07-20 15:37:55 +08:00
Luis Pater
8b4fd28c95 perf(executor): replace sjson.SetBytes with optimized helpers for conditional payload updates
- Introduced `SetStringIfDifferent`, `SetBoolIfDifferent`, and similar helpers in `payload_helpers` to avoid unnecessary writes during JSON modifications.
- Simplified message patching in `kimi_executor` for reasoning and tool call adjustments.
- Updated all executors (Gemini, Codex, XAI, Antigravity, etc.) to use the new helpers, enhancing readability and potentially reducing overhead.
- Removed obsolete `filterKimiEmptyAssistantMessages` function in `kimi_executor`.
2026-07-20 13:57:14 +08:00
Luis Pater
fde40c5a0a feat(executor): sanitize and drop overlong encrypted reasoning IDs in Codex input processing
- Updated `SanitizeCodexInputItemIDs` to remove encrypted reasoning items with IDs exceeding the Codex length limit.
- Refactored logic to deterministically shorten other overlong input item IDs, ensuring compliance with the Codex format.
- Added new tests to verify dropping behavior for encrypted reasoning and shortening of lengthy IDs without encrypted content.
2026-07-20 02:02:17 +08:00
Luis Pater
f175c084d3 feat(executor): promote additional_tools to top-level tools in XAI requests
- Added `promoteXAIAdditionalTools` to normalize and migrate `additional_tools` to the top-level `tools` array in XAI request bodies.
- Updated test cases to validate the promotion logic and ensure unsupported `additional_tools` items are excluded from input payloads.

Closes: #4434
2026-07-19 16:32:47 +08:00
Luis Pater
93d74a890a Merge pull request #4419 from mikewong23571/fix/kimi-upstream-model-normalization 2026-07-18 23:29:16 +08:00
Luis Pater
70c4bd78b2 feat(kimi): route Claude requests through Claude executor in Kimi
- Updated Kimi executor to delegate non-streaming and streaming Claude requests to the Claude executor when `SourceFormat` is `claude`.
- Injected `base_url` for Claude API compatibility during delegation.
2026-07-18 23:15:57 +08:00
Luis Pater
117654317a feat(kimi): migrate Kimi executor to use chat completions path and remove deprecated code
- Updated Kimi executor to route all Claude requests through the OpenAI-compatible chat completions API.
- Removed legacy delegation to Claude executor for non-streaming and streaming execution.
- Enhanced translator integration for request normalization and Kimi model stripping.
- Updated tests to validate chat completions behavior, including upstream request logging, payload transformation, and response handling.
- Deleted Kimi K3[1M] variant and associated metadata.
2026-07-18 22:55:26 +08:00
mikewong23571
8bafd85433 fix(executor): normalize Kimi upstream model ID to canonical k3
Claude Code sends the configured model name (e.g. kimi-k3[1m]) to
CLIProxyAPI. The Kimi executor forwarded this internal ID to Kimi's
https://api.kimi.com/coding endpoint. Kimi treats kimi-k3 and
kimi-k3[1m] as 256K-context models, while only bare k3 supports the
full 1M context window.

Normalize the upstream model by stripping the CLIProxyAPI kimi- prefix
and any Claude Code [1m] suffix while preserving a trailing thinking
suffix (e.g. (1024)), so that requests for kimi-k3, kimi-k3[1m],
kimi-k3(1024), and kimi-k3[1m](1024) are all sent to Kimi as k3 or
k3(1024). This applies to:

- Execute (Claude and OpenAI branches)
- ExecuteStream (Claude and OpenAI branches)
- CountTokens

Validation (using the stored Kimi token):
- GET /v1/models shows k3 with context_length 1048576.
- Direct /v1/messages calls with ~270k input tokens:
  - model=k3 succeeds.
  - model=k3[1m], kimi-k3, kimi-k3[1m] fail with:
    'Your request exceeded model token limit: 262144 (requested: 270014)'.

Add unit tests for normalizeKimiUpstreamModel.

Closes #4418

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-18 05:33:12 -07:00
Luis Pater
76dc0fdc54 feat(executor): extend applyClaudeHeaders and Kimi executor with additional header support
- Added an `incomingHeaders` argument to `applyClaudeHeaders` to enable external header injection for flexibility.
- Updated Kimi executor to delegate header support to Claude executor, facilitating upstream request logging and beta header forwarding.
- Introduced tests for delegated configuration, header handling, and upstream request/response logging to improve coverage.
2026-07-18 19:36:09 +08:00
Luis Pater
81d70f5d9f feat(executor): add normalization for parallel tool calls in Codex executors
- Introduced `normalizeCodexWebsocketParallelToolCalls` and `normalizeCodexParallelToolCalls` to enforce consistent `parallel_tool_calls` handling.
- Updated WebSocket and HTTP executor logic to support headers during parallel tool normalization.
- Refactored redundant logic by consolidating normalization routines for improved clarity and maintainability.
2026-07-18 03:58:03 +08:00
Luis Pater
2f80cb9ae8 feat(executor): add root union type normalization and extended tests
- Introduced `normalizeXAIObjectRootUnionBranchTypes` for ensuring object-only branches in root-level unions.
- Updated XAI executor logic to handle additional schema adjustments, ensuring compatibility with stricter validations.
- Extended test coverage to validate schema normalization, including both functional and custom tool scenarios.

Closes: #4397
2026-07-18 03:34:30 +08:00
Luis Pater
baffbe2cc7 feat(executor): implement agent-scoped cache key isolation and enhance replay handling
- Introduced agent-specific cache key isolation to ensure distinct prompt caching across agents.
- Improved reasoning replay handling for Claude models, including cumulative tool turn restoration and validation.
- Enhanced HTTP and WebSocket session consistency during execution scope and cache replay synchronization.
- Added new unit tests and extended coverage for prompt caching, agent isolation, and replay cache functionality.

Closes: #4352
2026-07-18 02:18:09 +08:00
Luis Pater
fbe116071a feat(websockets): implement active connection tracking for websocket sessions
- Introduced per-connection active channel management for Codex and XAI websocket sessions.
- Enhanced session behavior to support clearing and reassigning active channels tied to specific connections.
- Added support for detecting and detaching stale connections upon session target changes.
- Refactored websocket message handling logic to ensure connection-specific channel consistency.
- Extended test coverage for websocket session behaviors, including reconnections, target switching, and pinned auth transitions.
2026-07-18 00:40:56 +08:00
Luis Pater
1cfe529f32 feat(executor): add ID shortening for overlong Codex input items
- Implemented deterministic shortening of overlong Codex input item IDs to meet 64-character limit.
- Added `SanitizeCodexInputItemIDs` helper for efficient ID shortening in request bodies.
- Updated Codex executor and websocket implementations to utilize the new helper.
- Introduced unit tests to validate ID length restrictions, avoidance of collisions, and deterministic behavior.

Closes: #4401
2026-07-17 23:52:58 +08:00
Luis Pater
9f4f53ca5a fix(xai): update compact request handling to use dedicated base URL
- Switched from `xaiChatBaseURL` to `xaiCompactBaseURL` for compact requests to avoid 404 errors from CLI chat-proxy.
- Updated headers to use standard API headers for compact endpoints.
- Added `xaiCompactBaseURL` helper function for dedicated compact request base URL resolution.
- Adjusted comments to clarify handling of compact and websocket transports.

Closes: #4376
2026-07-17 17:52:53 +08:00
Luis Pater
4231ad6e2a fix(executor): ensure top_p is removed in normalizeClaudeSamplingForUpstream
- Updated `normalizeClaudeSamplingForUpstream` to delete `top_p` from payloads.
- Adjusted test to validate the removal of both `temperature` and `top_p`.

Closes: #4383
2026-07-17 16:43:26 +08:00
Luis Pater
f583414fd9 fix(xai): normalize image refs with special JSON keys 2026-07-17 16:13:54 +08:00
jellyfish-p
f82123a3ef fix(xai): rewrite image.image_url to image.url before upstream send
Normalize OpenAI-style image refs across images, videos, and Responses so Grok receives {image:{url:...}} instead of image_url.
2026-07-17 14:42:12 +08:00
Luis Pater
106270bea6 feat(kimi): use dynamic version from buildinfo for API headers
- Updated `X-Msh-Version` and `User-Agent` headers in both `kimi.go` and `kimi_executor.go` to dynamically include the current version from `buildinfo`.
- Replaced hardcoded values with `buildinfo.Version` to ensure consistency with the build version.
2026-07-16 22:32:35 +08:00
Luis Pater
09da52ad50 feat(translator): improve error handling and response conversion for incomplete statuses
- Enhanced response handling to support `response.incomplete` events across translator components and executors.
- Refactored `resultErrorFromError` to centralize error conversion and consolidate repeated logic for constructing custom errors.
- Updated handling of `max_output_tokens` and similar terminal reasons in OpenAI and Gemini translator workflows.
- Introduced `IsRequestScoped` and `IsRequestScopedError` to differentiate between request-scoped and non-request-scoped errors.
- Added comprehensive test cases for incomplete responses, terminal failures, and error propagation in both streaming and non-streaming conditions.

Closes: #3055
2026-07-16 04:38:19 +08:00
Luis Pater
466cee6e16 fix: complete xAI image usage reporting 2026-07-16 02:32:56 +08:00
Luis Pater
3cb2d27d98 Merge remote-tracking branch 'origin/pr-4344' into dev 2026-07-16 02:29:45 +08:00
Luis Pater
b6ce0beecd feat(executor): simplify xAI function schema handling and rejection logic
- Refactored `xaiFunctionParametersNeedSimplification` to identify schemas xAI cannot process, including those with non-object types in unions.
- Limited parameter simplifications to problematic schemas instead of specific tools or namespaces.
- Clarified and updated debug messages to reflect schema rejection and hang prevention.

Closes: #4343
2026-07-16 02:05:50 +08:00
Matt Van Horn
9f500aef7a fix: publish usage event for xAI images/generations path 2026-07-15 08:45:44 -07:00
Luis Pater
768b4c49fd feat(usage): track generate flag with backward-compatible defaults
Propagate client generate metadata through usage records while keeping
legacy callers that omit the field enabled by default. Preserve an
existing context generate=false when metadata does not set the value,
and normalize omission to true only at publishing boundaries.
2026-07-15 21:30:09 +08:00
Luis Pater
e57416731a feat(logging): add deferred request body capture for error handling
- Introduced `deferredRequestBodyCapture` for spooling and retaining large error-only request bodies for improved logging.
- Enhanced `RequestLoggingMiddleware` to capture request body based on size and error criteria.
- Implemented decompression and truncation for large request bodies with Zstd encoding.
- Added support for deferred API request logging and context tracking.
- Included extensive test coverage for error-specific body capture and serialization behavior.
2026-07-14 23:35:29 +08:00
sususu98
03d58c4402 fix(usage): collapse OpenAI service tier metadata (#4275)
* fix(usage): preserve request service tier metadata

* fix(usage): collapse request tier metadata

* fix(usage): emit only service_tier and response_service_tier

Collapse request tier to service_tier for usage records and queue payloads. Keep RequestServiceTier as a deprecated input-only alias for older plugin callers.
2026-07-14 14:19:13 +08:00
Luis Pater
a9831c841a fix(xai): sync allowed_tools and prune orphaned choices for x_search inject
Normalize and drop tool_choice entries that reference tools removed by
normalizeXAITools before injecting native x_search, then allow x_search in
allowed_tools without duplicates so Grok can select the injected tool.
2026-07-14 05:03:19 +08:00
Luis Pater
423f3d5ff7 feat(xai): add xAI API key support with comprehensive handling and tests
- Introduced `xai-api-key` to configuration for supporting xAI provider integration.
- Added API key operations: creation, updates, deletion, and sanitization.
- Implemented backend enhancements for credential-specific routing, response filtering with model aliasing, and WebSocket handling for xAI services.
- Included extensive test coverage to validate configuration parsing, CRUD operations, and the new functionalities.
- Updated related modules to handle `xai-api-key`, including the watcher, management handlers, and configuration sanitizers.
2026-07-14 04:40:12 +08:00
Luis Pater
a5577cc67d feat(xai): enhance response filtering with client-declared tool support to distinguish internal X Search traces
- Added `clientDeclaredTools` to `xaiInternalXSearchResponseFilter` for improved filtering precision.
- Implemented `collectXAIClientDeclaredToolKeys` to register client-declared tools with effective normalization to function calls.
- Prevented leakage of internal traces (e.g., `xs_call-*`) while preserving client-declared tools with overlapping names.
- Introduced multiple test cases to ensure filter correctness and preserve expected WebSocket response outputs.
- Enhanced completed output handling in response filtering.

Closes: #4282 / PR #4284.
2026-07-14 03:38:29 +08:00
Luis Pater
4fd81f904b Merge pull request #4284 from vvanglro/codex/fix-xai-x-search-history-4282 2026-07-14 01:30:40 +08:00
vvanglro
4651c3705d perf(xai): reuse parsed input array 2026-07-14 00:44:14 +08:00
sususu98
194fbce4b4 fix(executor): strip orphan reasoning ids when store is disabled (#4285)
* fix(executor): strip orphan reasoning ids when store is disabled

Codex backend requires store=false and treats reasoning items with an
id but no usable encrypted_content as store lookups, which 404 with
"Item with id not found". Drop those orphan ids after removing invalid
encrypted_content (and when encrypted_content is already missing),
while preserving ids when store=true.

* fix(executor): skip id delete when reasoning item has no id

Avoid sjson.Delete on encrypted_content drops that never carried an id,
matching the orphan-id path's Exists() guard.
2026-07-14 00:35:48 +08:00
vvanglro
caa93a7fc6 fix(xai): filter internal X search calls 2026-07-14 00:19:49 +08:00
Dmitry R.
7f6d491e70 perf(executor): avoid O(n^2) rebuilds when sanitizing reasoning encrypted_content (#4281)
Previously each dropped encrypted_content re-ran sjson.DeleteBytes on
the whole body/array per item, causing O(n^2) work on inputs with many
reasoning items.

Now the array is walked once, editing only offending items in place
and lazily building a replacement "input" array via strings.Builder.
The builder stays nil (no allocation) when nothing needs sanitizing,
and the array is spliced back with a single SetRawBytes call.
2026-07-14 00:16:05 +08:00
vvanglro
7bb8132817 fix(xai): normalize custom tool call history 2026-07-13 23:45:44 +08:00
Luis Pater
e674f19129 Fix xAI allowed tool namespace choices 2026-07-13 14:58:03 +08:00