Commit Graph

44 Commits

Author SHA1 Message Date
sususu
f3e836ce6c refactor(claude): deduplicate CLI identity application and tidy helpers
- Extract the credential-identity block shared by the streaming and
  non-streaming Claude paths into applyClaudeCLIIdentity, so the identity
  seed choice (API key versus stable Kimi auth identity) cannot drift
  between the two paths
- Move stripDefaultKimiClaudeCodeAttribution next to the other attribution
  and CCH helpers in claude_signing.go; it is only called from the Claude
  executor paths and never from the Kimi executor itself
- Reattach the addConfigHeadersToAttrs doc comment to its function in the
  watcher synthesizer helpers
2026-08-18 18:21:33 +08:00
sususu98
f1b0431c77 feat(claude): add fingerprint-profile=claude-code-cli for API keys and delegated providers (#5047)
* feat(config): add fingerprint-profile to Claude keys and auth JSON

- Add FingerprintProfile to ClaudeKey configuration struct and normalizer
- Track fingerprint-profile in config diff
- Map fingerprint-profile / fingerprint_profile to auth attributes in file and config synthesizers
- Support fingerprint-profile in Management API PatchClaudeKey and normalization
- Add Claude billing attribution string manipulation utilities in internal/util
- Document fingerprint-profile options in config.example.yaml

* feat(claude): add fingerprint policy and request-local CLI identity

- Centralize Claude fingerprint policy resolution in claude_fingerprint_policy.go
- Support stable Claude CLI identity synthesis (UUIDv5 account_uuid and SHA-256 device_id)
  seeded from API keys or stable OAuth IDs, keeping access tokens isolated
- Warn on unrecognized fingerprint-profile values

* feat(claude): apply CLI fingerprint to Messages and keep API keys caller-owned

- Wire centralized fingerprint policy into Claude and Kimi executors
- Keep first-party Anthropic API keys and delegated providers caller-owned by default
- Apply Claude Code CLI wire profile (betas, metadata, diagnostics, MCP aliases)
  when fingerprint-profile=claude-code-cli is configured
- Strictly align CCH signing with native Claude Code 2.1.220: only first-party
  api.anthropic.com and Vertex sign dynamic CCH; third-party gateways and Kimi
  receive billing header without cch= to avoid prompt cache busting
- Respect caller-owned count_tokens bodies by default while aligning CLI shape on opt-in
- Fall back to CLIProxyAPI/<version> User-Agent when caller sends no UA in caller-owned mode
- Scope custom operator header overrides accurately in caller-owned mode
- Add comprehensive test coverage for policy resolution, gateway opt-in, Kimi, and token counting
2026-08-18 17:29:26 +08:00
Luis Pater
e0b4956242 fix(openai): ensure Responses usage includes token detail fields
- add shared `EnsureResponsesUsageDetails` helper to patch `usage` objects with:
  - `output_tokens_details.reasoning_tokens = 0`
  - `input_tokens_details.cached_tokens = 0`
  - for both plain JSON and SSE `data:` frames, including multi-line frames
- apply the helper to OpenAI Response format outputs in non-stream and stream paths across executors/plugins so translated payloads consistently include required usage details
- update websocket/completion payload builders to emit default `usage` detail fields for prewarm/finish responses

Closes: #4985
2026-08-15 15:00:19 +08:00
Luis Pater
a2337beb24 fix(kimi): select upstream request format from source format (Claude/OpenAI)
Closes: #4910
2026-08-12 15:43:19 +08:00
Luis Pater
a59caebc68 fix(kimi): treat [reasoning unavailable] as unusable reasoning in message normalization
- Introduce a shared `isUsableKimiReasoning` helper and constant for the placeholder string.
- Prevent tool-call normalization from propagating or reusing placeholder/empty reasoning content.
- Preserve and reuse the latest valid assistant reasoning when normalizing `reasoning_content` for tool messages.

Closes: #4899
2026-08-12 01:30:18 +08:00
Luis Pater
36936340a3 fix(kimi): canonicalize K2.7 Code model aliases to official Kimi-For-Coding IDs
Closes: #4605
2026-08-08 05:08:42 +08:00
Luis Pater
8c37dd9862 feat(executor): introduce Kimi Thinking Replay cache and continuity mechanisms
- Added logic for caching and restoring Kimi "Thinking Replay" states to improve continuity across requests.
- Implemented `kimiThinkingReplayScope`, content replay preparation, and conditional cache storage based on replay validity.
- Introduced helper methods for replay content restoration, caching, and cleanup on errors.
- Enhanced executor workflows to utilize the "Thinking Replay" cache for both immediate and streaming response handling.
- Integrated periodic cleanup of expired and oversized replay cache entries.

Closes: #4695
2026-07-31 22:59:13 +08:00
sususu
0c2ec7da23 fix(thinking): honor normalized summary payloads 2026-07-31 12:45:13 +08:00
sususu
b3046d29b9 feat(thinking): preserve cross-protocol summary visibility 2026-07-30 21:53:30 +08:00
Luis Pater
57ef784224 feat(executor): implement local token counting for Claude requests
- Added `CountClaudeInputTokens` for estimating token usage with O200kBase tokenizer.
- Enhanced `ClaudeExecutor` to handle token counting locally, reducing dependency on upstream services.
- Introduced validation for token count requests for improved error handling.
- Updated tests to cover local token counting behavior and invalid request handling.

Closes: #4103
2026-07-27 00:50:11 +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
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
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
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
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
Supra4E8C
bc812e5f74 perf(usage): avoid parsing irrelevant stream chunks 2026-07-11 02:42:42 +08:00
Luis Pater
dea4787970 refactor(executor): centralize OpenAI stream usage handling with StreamUsageBuffer
- Introduced `StreamUsageBuffer` to encapsulate stream usage observation and publishing logic.
- Updated OpenAI-compatible executors and helpers to use `StreamUsageBuffer` for consistent stream usage tracking.
- Added unit tests to validate `StreamUsageBuffer` behavior, ensuring proper handling of usage details.

Closes: #4053
2026-07-08 04:01:22 +08:00
Luis Pater
8e39db2ec7 feat(plugin, api): introduce host model callback support with Go example and API handlers
- Added an example plugin `host-model-callback` in Go to summarize host model callbacks.
- Implemented `cliproxy_plugin_init`, `cliproxyPluginCall`, and other plugin functions for callback handling.
- Introduced API handlers for `ModelExecution` and `ModelExecutionStream` with support for both streaming and non-streaming requests.
- Included unit tests (`model_execution_test.go`) to validate execution logic and streaming responses.
2026-06-12 02:22:23 +08:00
Luis Pater
959067edfb feat(usage): introduce executor type tracking in usage reporting
- Replaced `NewUsageReporter` with `NewExecutorUsageReporter` to include executor type in usage records.
- Updated all executors to use the new reporter implementation.
- Extended `UsageReporter` to track and publish executor type.
- Added tests to validate proper executor type recording and handling.
- Enhanced RedisQueue plugin and payload schema with executor type support.
2026-06-02 00:43:16 +08:00
Luis Pater
94c1b25146 feat(executor): add TTFT tracking and reporting for enhanced performance metrics
- Introduced Time-To-First-Token (TTFT) measurement and reporting across major executors.
- Added TTFT calculation to `UsageReporter`, including support for HTTP clients and WebSocket communication.
- Updated tests to validate TTFT tracking in streamed and non-streamed scenarios.
- Ensured integration with `usage` plugin and augmented usage records with TTFT data.
2026-05-28 02:59:24 +08:00
Luis Pater
11f0f906bd feat(logging): add SetTranslatedReasoningEffort to track reasoning levels in usage reporting
- Introduced `SetTranslatedReasoningEffort` method in `UsageReporter` to capture and log reasoning efforts from translated payloads.
- Updated executors to incorporate the new reporting functionality for handling reasoning efforts across various providers.
- Enhanced logging for thinking level extraction with new helper function `ExtractTranslatedReasoningEffort`.
2026-05-28 02:19:45 +08:00
Luis Pater
2007a89594 feat(runtime): enhance payload rule resolution with dynamic path support
- Introduced `resolvePayloadRulePaths` function to dynamically resolve rule paths supporting array queries and complex logic.
- Updated payload processing logic (`apply defaults`, `overrides`, `filters`) to handle resolved paths for better flexibility.
- Added helper functions for path parsing, query matching, and logical resolution to improve modularity and reusability.
- Introduced payload condition match logic, including `match`, `not-match`, `exist`, and `not-exist` rules in `PayloadConfig`.
- Enhanced `payloadModelRulesMatch` function to support conditional checks at various levels.
- Added helper methods for evaluating JSON path conditions and values.
- Updated tests to validate new conditional rules against different payload scenarios.
2026-05-17 23:06:43 +08:00
Luis Pater
66c3dae06b feat(home): implement count for home auth dispatch requests and enable usage statistics
- Added `count` attribute to `homeAuthCount` requests to improve home message batching.
- Enabled usage statistics for home mode by default and added config-level enforcement.
- Adjusted failure logging to include detailed metadata in `UsageReporter`.
- Updated multiple executors to pass error details to `PublishFailure` for better debugging.
- Enhanced unit tests to validate `count` behavior and usage statistics enforcement across components.
2026-05-10 01:30:43 +08:00
Luis Pater
e50cabac4b chore: upgrade CLIProxyAPI dependency to v7 across the project
- Updated all references from v6 to v7 for `github.com/router-for-me/CLIProxyAPI`.
- Ensured consistency in imports within core libraries, tests, and integration tests.
- Added missing tests for new features in Redis Protocol integration.
2026-05-08 11:46:46 +08:00
Luis Pater
162897e02a Merge remote-tracking branch 'origin/pr/3205' into dev 2026-05-04 21:17:01 +08:00
1137043480
bf0e5c23f7 fix: prevent goroutine leaks in streaming executors via context-aware channel sends
All streaming executors use bare channel sends (out <- chunk) inside goroutines
that process upstream SSE responses. When the downstream consumer disconnects
(client timeout, network drop, etc.), these sends block indefinitely, causing
the goroutine and all associated resources (HTTP response body, scanner buffers,
translation state) to leak permanently.

Over time, leaked goroutines accumulate monotonically, leading to RSS growth
from ~30MB to 3.7GB+ and eventual OOM kills on resource-constrained VPS hosts.

Fix: Replace all bare 'out <- ...' sends with:
  select {
  case out <- ...:
  case <-ctx.Done():
    return
  }

This ensures goroutines terminate promptly when the request context is canceled,
allowing GC to reclaim all associated resources.

Affected executors (9 files, 36+ send sites):
- antigravity_executor.go (5 sites)
- gemini_cli_executor.go (6 sites)
- gemini_vertex_executor.go (6 sites)
- aistudio_executor.go (4 sites)
- gemini_executor.go (3 sites)
- openai_compat_executor.go (3 sites)
- claude_executor.go (4 sites)
- codex_executor.go (2 sites)
- kimi_executor.go (3 sites)
2026-05-03 11:25:04 -04:00
Luis Pater
672fdd14ed feat: filter and drop empty assistant messages in Kimi executor
- Added `filterKimiEmptyAssistantMessages` to identify and remove empty assistant messages with no content, tool links, or reasoning.
- Integrated logging to track the number of dropped messages.
- Updated tests to validate the filtering logic for both empty and valid assistant messages.

Fixed: #1730
2026-05-03 22:40:42 +08:00
Luis Pater
f56a19e5b8 feat: add tri-state support for disable-image-generation configuration
- Introduced `DisableImageGenerationMode` with support for `false`, `true`, and `chat` values.
- Updated payload handling to preserve `image_generation` on images endpoints when `chat` mode is enabled.
- Modified OpenAI image handlers (`ImagesGenerations`, `ImagesEdits`) to respect tri-state logic.
- Added unit tests for `DisableImageGenerationMode` behavior and endpoint-specific handling.
- Enhanced configuration diff logging to support `DisableImageGenerationMode`.
2026-04-30 12:10:27 +08:00
Luis Pater
d949921143 feat(auth): add proxy URL override support to auth constructors and executors
- Introduced `WithProxyURL` variants for `CodexAuth`, `ClaudeAuth`, `IFlowAuth`, and `DeviceFlowClient`.
- Updated executors to use proxy-aware constructors for improved configurability.
- Added unit tests to validate proxy override precedence and functionality.

Closes: #2823
2026-04-16 22:11:39 +08:00
Luis Pater
09e480036a feat(auth): add support for managing custom headers in auth files
Closes #2457
2026-04-02 19:11:09 +08:00
Luis Pater
d2c7e4e96a refactor(runtime): move executor utilities to helps package and update references 2026-04-01 03:08:20 +08:00
Luis Pater
2bd646ad70 refactor: replace sjson.Set usage with sjson.SetBytes to optimize mutable JSON transformations 2026-03-19 17:58:54 +08:00
Kirill Turanskiy
1f8f198c45 feat: passthrough upstream response headers to clients
CPA previously stripped ALL response headers from upstream AI provider
APIs, preventing clients from seeing rate-limit info, request IDs,
server-timing and other useful headers.

Changes:
- Add Headers field to Response and StreamResult structs
- Add FilterUpstreamHeaders helper (hop-by-hop + security denylist)
- Add WriteUpstreamHeaders helper (respects CPA-set headers)
- ExecuteWithAuthManager/ExecuteCountWithAuthManager now return headers
- ExecuteStreamWithAuthManager returns headers from initial connection
- All 11 provider executors populate Response.Headers
- All handler call sites write filtered upstream headers before response

Filtered headers (not forwarded):
- RFC 7230 hop-by-hop: Connection, Transfer-Encoding, Keep-Alive, etc.
- Security: Set-Cookie
- CPA-managed: Content-Length, Content-Encoding
2026-02-18 00:16:22 +03:00
Luis Pater
7e9d0db6aa Merge pull request #1467 from dusty-du/fix/kimi-toolcall-reasoning-content
Fix Kimi tool-call payload normalization for reasoning_content
2026-02-07 09:35:04 +08:00
Luis Pater
78ef04fcf1 fix(kimi): reduce redundant payload cloning and simplify translation calls 2026-02-07 08:51:48 +08:00
Luis Pater
f7d0019df7 fix(kimi): update base URL and integrate ClaudeExecutor fallback
- Updated `KimiAPIBaseURL` to remove versioning from the root path.
- Integrated `ClaudeExecutor` fallback in `KimiExecutor` methods for compatibility with Claude requests.
- Simplified token counting by delegating to `ClaudeExecutor`.
2026-02-07 06:42:08 +08:00
test
52364af5bf Fix Kimi tool-call reasoning_content normalization 2026-02-06 14:46:16 -05:00
Luis Pater
68cb81a258 feat: add Kimi authentication support and streamline device ID handling
- Introduced `RequestKimiToken` API for Kimi authentication flow.
- Integrated device ID management throughout Kimi-related components.
- Enhanced header management for Kimi API requests with device ID context.
2026-02-06 20:43:30 +08:00
test
f5f26f0cbe Add Kimi (Moonshot AI) provider support
- OAuth2 device authorization grant flow (RFC 8628) for authentication
- Streaming and non-streaming chat completions via OpenAI-compatible API
- Models: kimi-k2, kimi-k2-thinking, kimi-k2.5
- CLI `--kimi-login` command for device flow auth
- Token management with automatic refresh
- Thinking/reasoning effort support for thinking-enabled models

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-05 19:24:46 -05:00