Commit Graph

723 Commits

Author SHA1 Message Date
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
Luis Pater
19fb0f0774 Merge pull request #4251 from huahai0202/fix/xai-namespace-tool-routing 2026-07-13 14:48:55 +08:00
huahai0202
4123e27583 fix(xai): handle additional namespace tools 2026-07-13 10:39:39 +08:00
sususu
18d239d567 fix(xai): clear replay after compaction 2026-07-12 23:59:39 +08:00
huahai0202
eb6d169407 fix(xai): qualify namespaced tool choices 2026-07-12 23:58:16 +08:00
sususu
487f8afc98 fix(xai): disable unisolated replay without caller auth 2026-07-12 23:38:11 +08:00
huahai0202
c4eda81b93 fix(xai): address namespace routing review feedback
Use exact namespace separator matching, normalize replay-inserted calls, preserve payloads on JSON update failures, and remove redundant completed-response restoration.
2026-07-12 23:33:53 +08:00
sususu
f1e9347f51 fix(xai): preserve tool-call-only replay batches 2026-07-12 23:19:36 +08:00
huahai0202
0e3a3e6199 fix(xai): preserve namespace tool routing
xAI Responses does not accept namespace tool containers, so the executor flattens nested tools before forwarding them upstream. The original namespace support in 8b3670b8 moved children to the top level but discarded their namespace identity; ca67caf later retained namespace context only for targeted schema simplification.

Qualify flattened names to avoid collisions, normalize namespaced function-call history, and restore name plus namespace on HTTP and WebSocket responses. This keeps Codex MCP routing intact without changing the existing xAI tool_search filtering policy.
2026-07-12 23:16:57 +08:00
sususu
3f875ecd2d fix(xai): avoid ambiguous reasoning replay injection 2026-07-12 23:07:04 +08:00
sususu
dc551b7de5 refactor(xai): remove unused assistant content equal helpers
Drop xaiAssistantMessageContentEqual and xaiAssistantMessagePartValue,
which were left unused after the last-assistant skip path landed.
2026-07-12 22:31:19 +08:00
sususu
041816c2fd feat(xai): encrypted reasoning replay for Responses/Claude with hardened cache
Preserve include=reasoning.encrypted_content, cache reasoning+assistant message
for store:false multi-turn, and accept Grok thinking signatures on Claude→Codex
for grok targets.

Harden replay cache: blob-level reasoning filter, never double-inject assistant
when history has a last message, isolate session keys by downstream API key,
clear cache on non-replayable completed turns, and normalize refusal parts.
2026-07-12 22:31:19 +08:00
Luis Pater
0ba5fab529 Merge pull request #4240 from BG-QWQ/fix/xai-cli-user-agent-4233
fix(executor): identify Grok CLI OAuth requests
2026-07-12 20:27:51 +08:00
Luis Pater
6c70996e43 feat(executor): add logging for resolved xAI base URL and enhance test coverage
- Introduced `logXAIResolvedBaseURL` for consistent logging of resolved upstream base URLs.
- Added helper `xaiBaseURLSource` to classify base URL origins (default, CLI chat proxy, custom).
- Enhanced test suite with `TestXAIBaseURLSource` to cover base URL source classification logic.
2026-07-12 17:23:56 +08:00
1502538344
1a0bbe09c6 fix(executor): identify Grok CLI OAuth requests 2026-07-12 16:40:08 +08:00