Commit Graph

713 Commits

Author SHA1 Message Date
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
Luis Pater
2075f77c8e feat(executor): enhance cache_tokens handling and extend parsing logic with alias normalization
- Added support for `cache_read_tokens` and `cache_creation_tokens` aliases across `prompt_tokens_details`, `input_tokens_details`, and other usage details.
- Updated token parsing logic to handle multiple aliases and improve fallback scenarios.
- Extended test coverage for alias normalization, including `cache_write_tokens`, `cacheCreationTokens`, and `cachedContentTokenCount`.
- Improved total token calculation by incorporating conditional read token addition logic.
2026-07-12 03:22:41 +08:00
Luis Pater
e99a2056ba feat(executor): add using_api attribute support for API path toggle and enhance test coverage
- Introduced `using_api` attribute in xAI auth for toggling between official API and CLI chat-proxy paths.
- Updated `xaiChatBaseURL` and `applyXAIChatHeaders` to conditionally apply the appropriate logic based on the `using_api` value.
- Added robust handling of attribute and metadata parsing for `using_api`.
- Extended test suite to cover `using_api` scenarios, including defaults, overrides, and header behaviors.
2026-07-11 12:15:55 +08:00
Luis Pater
aa05fb27f3 feat(executor, handlers): enhance websocket output restoration and compact compaction logic
- Refactored websocket output collection to restore completed events using fallback items and indexed payloads.
- Updated `CodexExecutorCompact` tests to ensure no injection of `image_generation` tools and maintain compact input order.
- Added new tests to validate sustained reasoning, proper output restoration, and compaction replay behavior.
- Improved logic to handle incremental response appends and preserved reasoning continuations.
- Enhanced test coverage for normalization, tool calls, and downstream payload restoration scenarios.

Closes: #4176
2026-07-11 11:42:51 +08:00
Supra4E8C
8c2bf2c24b Merge pull request #4202 from router-for-me/codex/issue-33-service-tier-reporting
feat(usage): report request and response service tiers
2026-07-11 03:12:02 +08:00
Supra4E8C
bc812e5f74 perf(usage): avoid parsing irrelevant stream chunks 2026-07-11 02:42:42 +08:00
Luis Pater
dc162b938e feat(executor): refactor XAI header application logic and extend test coverage
- Extracted `applyXAIDefaultHeaders` and `applyXAICustomHeaders` for cleaner separation of concerns in API header application.
- Updated `applyXAIChatHeaders` to ensure proper header overrides for CLI chat-proxy-specific configurations.
- Added test case to validate custom headers' ability to override CLI chat-proxy defaults.
2026-07-11 02:12:57 +08:00
Luis Pater
3533484a1f feat(executor): add chat-proxy-specific headers and improve base URL handling
- Introduced `xaiChatBaseURL` helper to normalize base URLs for non-media chat requests.
- Added `applyXAIChatHeaders` to handle CLI chat-proxy-specific headers.
- Updated logic to differentiate between default, chat-proxy, and custom gateway base URLs.
- Extended test coverage to validate behavior of headers and base URL handling across scenarios.

Closes: #4182
2026-07-11 02:07:01 +08:00
Supra4E8C
ea20742e77 fix(usage): retain response tier without usage 2026-07-11 01:37:39 +08:00
Supra4E8C
dc4be1674a feat(usage): report request and response service tiers 2026-07-11 00:49:30 +08:00
Supra4E8C
631f7a652c fix(executor): enhance image generation tool handling for responses-lite requests 2026-07-10 18:54:31 +08:00